cache.c 44.3 KB
Newer Older
L
Linus Torvalds 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*
 * net/sunrpc/cache.c
 *
 * Generic code for various authentication-related caches
 * used by sunrpc clients and servers.
 *
 * Copyright (C) 2002 Neil Brown <neilb@cse.unsw.edu.au>
 *
 * Released under terms in GPL version 2.  See COPYING.
 *
 */

#include <linux/types.h>
#include <linux/fs.h>
#include <linux/file.h>
#include <linux/slab.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/kmod.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/ctype.h>
23
#include <linux/string_helpers.h>
L
Linus Torvalds 已提交
24 25 26 27 28 29
#include <asm/uaccess.h>
#include <linux/poll.h>
#include <linux/seq_file.h>
#include <linux/proc_fs.h>
#include <linux/net.h>
#include <linux/workqueue.h>
A
Arjan van de Ven 已提交
30
#include <linux/mutex.h>
31
#include <linux/pagemap.h>
L
Linus Torvalds 已提交
32 33 34 35
#include <asm/ioctls.h>
#include <linux/sunrpc/types.h>
#include <linux/sunrpc/cache.h>
#include <linux/sunrpc/stats.h>
36
#include <linux/sunrpc/rpc_pipe_fs.h>
37
#include "netns.h"
L
Linus Torvalds 已提交
38 39 40

#define	 RPCDBG_FACILITY RPCDBG_CACHE

41
static bool cache_defer_req(struct cache_req *req, struct cache_head *item);
L
Linus Torvalds 已提交
42 43
static void cache_revisit_request(struct cache_head *item);

44
static void cache_init(struct cache_head *h, struct cache_detail *detail)
L
Linus Torvalds 已提交
45
{
46
	time_t now = seconds_since_boot();
47
	INIT_HLIST_NODE(&h->cache_list);
L
Linus Torvalds 已提交
48
	h->flags = 0;
49
	kref_init(&h->ref);
L
Linus Torvalds 已提交
50
	h->expiry_time = now + CACHE_NEW_EXPIRY;
51 52 53
	if (now <= detail->flush_time)
		/* ensure it isn't already expired */
		now = detail->flush_time + 1;
L
Linus Torvalds 已提交
54 55 56
	h->last_refresh = now;
}

57 58 59
struct cache_head *sunrpc_cache_lookup(struct cache_detail *detail,
				       struct cache_head *key, int hash)
{
60 61
	struct cache_head *new = NULL, *freeme = NULL, *tmp = NULL;
	struct hlist_head *head;
62 63 64 65 66

	head = &detail->hash_table[hash];

	read_lock(&detail->hash_lock);

67
	hlist_for_each_entry(tmp, head, cache_list) {
68
		if (detail->match(tmp, key)) {
69 70 71
			if (cache_is_expired(detail, tmp))
				/* This entry is expired, we will discard it. */
				break;
72 73 74 75 76 77 78 79 80 81 82
			cache_get(tmp);
			read_unlock(&detail->hash_lock);
			return tmp;
		}
	}
	read_unlock(&detail->hash_lock);
	/* Didn't find anything, insert an empty entry */

	new = detail->alloc();
	if (!new)
		return NULL;
83 84 85 86
	/* must fully initialise 'new', else
	 * we might get lose if we need to
	 * cache_put it soon.
	 */
87
	cache_init(new, detail);
88
	detail->init(new, key);
89 90 91 92

	write_lock(&detail->hash_lock);

	/* check if entry appeared while we slept */
93
	hlist_for_each_entry(tmp, head, cache_list) {
94
		if (detail->match(tmp, key)) {
95
			if (cache_is_expired(detail, tmp)) {
96
				hlist_del_init(&tmp->cache_list);
97 98 99 100
				detail->entries --;
				freeme = tmp;
				break;
			}
101 102
			cache_get(tmp);
			write_unlock(&detail->hash_lock);
103
			cache_put(new, detail);
104 105 106
			return tmp;
		}
	}
107 108

	hlist_add_head(&new->cache_list, head);
109 110 111 112
	detail->entries++;
	cache_get(new);
	write_unlock(&detail->hash_lock);

113 114
	if (freeme)
		cache_put(freeme, detail);
115 116
	return new;
}
117
EXPORT_SYMBOL_GPL(sunrpc_cache_lookup);
118

119

120
static void cache_dequeue(struct cache_detail *detail, struct cache_head *ch);
121

122 123
static void cache_fresh_locked(struct cache_head *head, time_t expiry,
			       struct cache_detail *detail)
124
{
125 126 127 128
	time_t now = seconds_since_boot();
	if (now <= detail->flush_time)
		/* ensure it isn't immediately treated as expired */
		now = detail->flush_time + 1;
129
	head->expiry_time = expiry;
130
	head->last_refresh = now;
131
	smp_wmb(); /* paired with smp_rmb() in cache_is_valid() */
132
	set_bit(CACHE_VALID, &head->flags);
133 134 135
}

static void cache_fresh_unlocked(struct cache_head *head,
136
				 struct cache_detail *detail)
137 138 139
{
	if (test_and_clear_bit(CACHE_PENDING, &head->flags)) {
		cache_revisit_request(head);
140
		cache_dequeue(detail, head);
141 142 143
	}
}

144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
struct cache_head *sunrpc_cache_update(struct cache_detail *detail,
				       struct cache_head *new, struct cache_head *old, int hash)
{
	/* The 'old' entry is to be replaced by 'new'.
	 * If 'old' is not VALID, we update it directly,
	 * otherwise we need to replace it
	 */
	struct cache_head *tmp;

	if (!test_bit(CACHE_VALID, &old->flags)) {
		write_lock(&detail->hash_lock);
		if (!test_bit(CACHE_VALID, &old->flags)) {
			if (test_bit(CACHE_NEGATIVE, &new->flags))
				set_bit(CACHE_NEGATIVE, &old->flags);
			else
				detail->update(old, new);
160
			cache_fresh_locked(old, new->expiry_time, detail);
161
			write_unlock(&detail->hash_lock);
162
			cache_fresh_unlocked(old, detail);
163 164 165 166 167 168 169
			return old;
		}
		write_unlock(&detail->hash_lock);
	}
	/* We need to insert a new entry */
	tmp = detail->alloc();
	if (!tmp) {
170
		cache_put(old, detail);
171 172
		return NULL;
	}
173
	cache_init(tmp, detail);
174 175 176 177 178 179 180
	detail->init(tmp, old);

	write_lock(&detail->hash_lock);
	if (test_bit(CACHE_NEGATIVE, &new->flags))
		set_bit(CACHE_NEGATIVE, &tmp->flags);
	else
		detail->update(tmp, new);
181
	hlist_add_head(&tmp->cache_list, &detail->hash_table[hash]);
182
	detail->entries++;
183
	cache_get(tmp);
184 185
	cache_fresh_locked(tmp, new->expiry_time, detail);
	cache_fresh_locked(old, 0, detail);
186
	write_unlock(&detail->hash_lock);
187 188
	cache_fresh_unlocked(tmp, detail);
	cache_fresh_unlocked(old, detail);
189
	cache_put(old, detail);
190 191
	return tmp;
}
192
EXPORT_SYMBOL_GPL(sunrpc_cache_update);
L
Linus Torvalds 已提交
193

194 195
static int cache_make_upcall(struct cache_detail *cd, struct cache_head *h)
{
196 197
	if (cd->cache_upcall)
		return cd->cache_upcall(cd, h);
198
	return sunrpc_cache_pipe_upcall(cd, h);
199
}
200

201
static inline int cache_is_valid(struct cache_head *h)
202
{
203
	if (!test_bit(CACHE_VALID, &h->flags))
204 205 206 207 208
		return -EAGAIN;
	else {
		/* entry is valid */
		if (test_bit(CACHE_NEGATIVE, &h->flags))
			return -ENOENT;
209 210 211 212 213 214 215 216
		else {
			/*
			 * In combination with write barrier in
			 * sunrpc_cache_update, ensures that anyone
			 * using the cache entry after this sees the
			 * updated contents:
			 */
			smp_rmb();
217
			return 0;
218
		}
219 220
	}
}
221

222 223 224 225 226
static int try_to_negate_entry(struct cache_detail *detail, struct cache_head *h)
{
	int rv;

	write_lock(&detail->hash_lock);
227
	rv = cache_is_valid(h);
228 229
	if (rv == -EAGAIN) {
		set_bit(CACHE_NEGATIVE, &h->flags);
230 231
		cache_fresh_locked(h, seconds_since_boot()+CACHE_NEW_EXPIRY,
				   detail);
232
		rv = -ENOENT;
233 234 235
	}
	write_unlock(&detail->hash_lock);
	cache_fresh_unlocked(h, detail);
236
	return rv;
237 238
}

L
Linus Torvalds 已提交
239 240 241 242 243 244 245 246
/*
 * This is the generic cache management routine for all
 * the authentication caches.
 * It checks the currency of a cache item and will (later)
 * initiate an upcall to fill it if needed.
 *
 *
 * Returns 0 if the cache_head can be used, or cache_puts it and returns
247 248 249 250
 * -EAGAIN if upcall is pending and request has been queued
 * -ETIMEDOUT if upcall failed or request could not be queue or
 *           upcall completed but item is still invalid (implying that
 *           the cache item has been replaced with a newer one).
L
Linus Torvalds 已提交
251 252 253 254 255 256 257 258 259
 * -ENOENT if cache entry was negative
 */
int cache_check(struct cache_detail *detail,
		    struct cache_head *h, struct cache_req *rqstp)
{
	int rv;
	long refresh_age, age;

	/* First decide return status as best we can */
260
	rv = cache_is_valid(h);
L
Linus Torvalds 已提交
261 262 263

	/* now see if we want to start an upcall */
	refresh_age = (h->expiry_time - h->last_refresh);
264
	age = seconds_since_boot() - h->last_refresh;
L
Linus Torvalds 已提交
265 266 267 268

	if (rqstp == NULL) {
		if (rv == -EAGAIN)
			rv = -ENOENT;
269 270
	} else if (rv == -EAGAIN ||
		   (h->expiry_time != 0 && age > refresh_age/2)) {
271 272
		dprintk("RPC:       Want update, refage=%ld, age=%ld\n",
				refresh_age, age);
L
Linus Torvalds 已提交
273 274 275
		if (!test_and_set_bit(CACHE_PENDING, &h->flags)) {
			switch (cache_make_upcall(detail, h)) {
			case -EINVAL:
276
				rv = try_to_negate_entry(detail, h);
L
Linus Torvalds 已提交
277 278
				break;
			case -EAGAIN:
279
				cache_fresh_unlocked(h, detail);
L
Linus Torvalds 已提交
280 281 282 283 284
				break;
			}
		}
	}

285
	if (rv == -EAGAIN) {
286 287 288 289 290
		if (!cache_defer_req(rqstp, h)) {
			/*
			 * Request was not deferred; handle it as best
			 * we can ourselves:
			 */
291
			rv = cache_is_valid(h);
292 293 294 295
			if (rv == -EAGAIN)
				rv = -ETIMEDOUT;
		}
	}
296
	if (rv)
297
		cache_put(h, detail);
L
Linus Torvalds 已提交
298 299
	return rv;
}
300
EXPORT_SYMBOL_GPL(cache_check);
L
Linus Torvalds 已提交
301 302 303 304 305 306 307

/*
 * caches need to be periodically cleaned.
 * For this we maintain a list of cache_detail and
 * a current pointer into that list and into the table
 * for that entry.
 *
308
 * Each time cache_clean is called it finds the next non-empty entry
L
Linus Torvalds 已提交
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
 * in the current table and walks the list in that entry
 * looking for entries that can be removed.
 *
 * An entry gets removed if:
 * - The expiry is before current time
 * - The last_refresh time is before the flush_time for that cache
 *
 * later we might drop old entries with non-NEVER expiry if that table
 * is getting 'full' for some definition of 'full'
 *
 * The question of "how often to scan a table" is an interesting one
 * and is answered in part by the use of the "nextcheck" field in the
 * cache_detail.
 * When a scan of a table begins, the nextcheck field is set to a time
 * that is well into the future.
 * While scanning, if an expiry time is found that is earlier than the
 * current nextcheck time, nextcheck is set to that expiry time.
 * If the flush_time is ever set to a time earlier than the nextcheck
 * time, the nextcheck time is then set to that flush_time.
 *
 * A table is then only scanned if the current time is at least
 * the nextcheck time.
331
 *
L
Linus Torvalds 已提交
332 333 334 335 336 337 338
 */

static LIST_HEAD(cache_list);
static DEFINE_SPINLOCK(cache_list_lock);
static struct cache_detail *current_detail;
static int current_index;

339
static void do_cache_clean(struct work_struct *work);
340
static struct delayed_work cache_cleaner;
L
Linus Torvalds 已提交
341

342
void sunrpc_init_cache_detail(struct cache_detail *cd)
343
{
L
Linus Torvalds 已提交
344 345 346 347 348 349 350 351 352 353 354 355
	rwlock_init(&cd->hash_lock);
	INIT_LIST_HEAD(&cd->queue);
	spin_lock(&cache_list_lock);
	cd->nextcheck = 0;
	cd->entries = 0;
	atomic_set(&cd->readers, 0);
	cd->last_close = 0;
	cd->last_warn = -1;
	list_add(&cd->others, &cache_list);
	spin_unlock(&cache_list_lock);

	/* start the cleaning process */
356
	schedule_delayed_work(&cache_cleaner, 0);
L
Linus Torvalds 已提交
357
}
358
EXPORT_SYMBOL_GPL(sunrpc_init_cache_detail);
L
Linus Torvalds 已提交
359

360
void sunrpc_destroy_cache_detail(struct cache_detail *cd)
L
Linus Torvalds 已提交
361 362 363 364 365 366 367
{
	cache_purge(cd);
	spin_lock(&cache_list_lock);
	write_lock(&cd->hash_lock);
	if (cd->entries || atomic_read(&cd->inuse)) {
		write_unlock(&cd->hash_lock);
		spin_unlock(&cache_list_lock);
368
		goto out;
L
Linus Torvalds 已提交
369 370 371 372 373 374 375 376
	}
	if (current_detail == cd)
		current_detail = NULL;
	list_del_init(&cd->others);
	write_unlock(&cd->hash_lock);
	spin_unlock(&cache_list_lock);
	if (list_empty(&cache_list)) {
		/* module must be being unloaded so its safe to kill the worker */
377
		cancel_delayed_work_sync(&cache_cleaner);
L
Linus Torvalds 已提交
378
	}
379 380
	return;
out:
381
	printk(KERN_ERR "RPC: failed to unregister %s cache\n", cd->name);
L
Linus Torvalds 已提交
382
}
383
EXPORT_SYMBOL_GPL(sunrpc_destroy_cache_detail);
L
Linus Torvalds 已提交
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410

/* clean cache tries to find something to clean
 * and cleans it.
 * It returns 1 if it cleaned something,
 *            0 if it didn't find anything this time
 *           -1 if it fell off the end of the list.
 */
static int cache_clean(void)
{
	int rv = 0;
	struct list_head *next;

	spin_lock(&cache_list_lock);

	/* find a suitable table if we don't already have one */
	while (current_detail == NULL ||
	    current_index >= current_detail->hash_size) {
		if (current_detail)
			next = current_detail->others.next;
		else
			next = cache_list.next;
		if (next == &cache_list) {
			current_detail = NULL;
			spin_unlock(&cache_list_lock);
			return -1;
		}
		current_detail = list_entry(next, struct cache_detail, others);
411
		if (current_detail->nextcheck > seconds_since_boot())
L
Linus Torvalds 已提交
412 413 414
			current_index = current_detail->hash_size;
		else {
			current_index = 0;
415
			current_detail->nextcheck = seconds_since_boot()+30*60;
L
Linus Torvalds 已提交
416 417 418 419 420 421
		}
	}

	/* find a non-empty bucket in the table */
	while (current_detail &&
	       current_index < current_detail->hash_size &&
422
	       hlist_empty(&current_detail->hash_table[current_index]))
L
Linus Torvalds 已提交
423 424 425
		current_index++;

	/* find a cleanable entry in the bucket and clean it, or set to next bucket */
426

L
Linus Torvalds 已提交
427
	if (current_detail && current_index < current_detail->hash_size) {
428
		struct cache_head *ch = NULL;
L
Linus Torvalds 已提交
429
		struct cache_detail *d;
430 431
		struct hlist_head *head;
		struct hlist_node *tmp;
432

L
Linus Torvalds 已提交
433 434 435
		write_lock(&current_detail->hash_lock);

		/* Ok, now to clean this strand */
436

437 438
		head = &current_detail->hash_table[current_index];
		hlist_for_each_entry_safe(ch, tmp, head, cache_list) {
L
Linus Torvalds 已提交
439 440
			if (current_detail->nextcheck > ch->expiry_time)
				current_detail->nextcheck = ch->expiry_time+1;
441
			if (!cache_is_expired(current_detail, ch))
L
Linus Torvalds 已提交
442 443
				continue;

444
			hlist_del_init(&ch->cache_list);
L
Linus Torvalds 已提交
445 446
			current_detail->entries--;
			rv = 1;
447
			break;
L
Linus Torvalds 已提交
448
		}
449

L
Linus Torvalds 已提交
450 451 452 453 454
		write_unlock(&current_detail->hash_lock);
		d = current_detail;
		if (!ch)
			current_index ++;
		spin_unlock(&cache_list_lock);
455
		if (ch) {
456
			set_bit(CACHE_CLEANED, &ch->flags);
457
			cache_fresh_unlocked(ch, d);
458
			cache_put(ch, d);
459
		}
L
Linus Torvalds 已提交
460 461 462 463 464 465 466 467 468
	} else
		spin_unlock(&cache_list_lock);

	return rv;
}

/*
 * We want to regularly clean the cache, so we need to schedule some work ...
 */
469
static void do_cache_clean(struct work_struct *work)
L
Linus Torvalds 已提交
470 471 472
{
	int delay = 5;
	if (cache_clean() == -1)
473
		delay = round_jiffies_relative(30*HZ);
L
Linus Torvalds 已提交
474 475 476 477 478 479 480 481 482

	if (list_empty(&cache_list))
		delay = 0;

	if (delay)
		schedule_delayed_work(&cache_cleaner, delay);
}


483
/*
L
Linus Torvalds 已提交
484
 * Clean all caches promptly.  This just calls cache_clean
485
 * repeatedly until we are sure that every cache has had a chance to
L
Linus Torvalds 已提交
486 487 488 489 490 491 492 493 494
 * be fully cleaned
 */
void cache_flush(void)
{
	while (cache_clean() != -1)
		cond_resched();
	while (cache_clean() != -1)
		cond_resched();
}
495
EXPORT_SYMBOL_GPL(cache_flush);
L
Linus Torvalds 已提交
496 497 498

void cache_purge(struct cache_detail *detail)
{
499 500 501 502 503
	time_t now = seconds_since_boot();
	if (detail->flush_time >= now)
		now = detail->flush_time + 1;
	/* 'now' is the maximum value any 'last_refresh' can have */
	detail->flush_time = now;
504
	detail->nextcheck = seconds_since_boot();
L
Linus Torvalds 已提交
505 506
	cache_flush();
}
507
EXPORT_SYMBOL_GPL(cache_purge);
L
Linus Torvalds 已提交
508 509 510 511 512 513 514 515 516 517


/*
 * Deferral and Revisiting of Requests.
 *
 * If a cache lookup finds a pending entry, we
 * need to defer the request and revisit it later.
 * All deferred requests are stored in a hash table,
 * indexed by "struct cache_head *".
 * As it may be wasteful to store a whole request
518
 * structure, we allow the request to provide a
L
Linus Torvalds 已提交
519 520 521 522 523 524 525 526 527 528 529 530 531
 * deferred form, which must contain a
 * 'struct cache_deferred_req'
 * This cache_deferred_req contains a method to allow
 * it to be revisited when cache info is available
 */

#define	DFR_HASHSIZE	(PAGE_SIZE/sizeof(struct list_head))
#define	DFR_HASH(item)	((((long)item)>>4 ^ (((long)item)>>13)) % DFR_HASHSIZE)

#define	DFR_MAX	300	/* ??? */

static DEFINE_SPINLOCK(cache_defer_lock);
static LIST_HEAD(cache_defer_list);
532
static struct hlist_head cache_defer_hash[DFR_HASHSIZE];
L
Linus Torvalds 已提交
533 534
static int cache_defer_cnt;

J
J. Bruce Fields 已提交
535 536
static void __unhash_deferred_req(struct cache_deferred_req *dreq)
{
537
	hlist_del_init(&dreq->hash);
538 539 540 541
	if (!list_empty(&dreq->recent)) {
		list_del_init(&dreq->recent);
		cache_defer_cnt--;
	}
J
J. Bruce Fields 已提交
542 543 544
}

static void __hash_deferred_req(struct cache_deferred_req *dreq, struct cache_head *item)
L
Linus Torvalds 已提交
545 546 547
{
	int hash = DFR_HASH(item);

548
	INIT_LIST_HEAD(&dreq->recent);
549
	hlist_add_head(&dreq->hash, &cache_defer_hash[hash]);
J
J. Bruce Fields 已提交
550 551
}

552 553 554
static void setup_deferral(struct cache_deferred_req *dreq,
			   struct cache_head *item,
			   int count_me)
L
Linus Torvalds 已提交
555 556 557 558 559 560
{

	dreq->item = item;

	spin_lock(&cache_defer_lock);

J
J. Bruce Fields 已提交
561
	__hash_deferred_req(dreq, item);
L
Linus Torvalds 已提交
562

563 564 565
	if (count_me) {
		cache_defer_cnt++;
		list_add(&dreq->recent, &cache_defer_list);
L
Linus Torvalds 已提交
566
	}
567

L
Linus Torvalds 已提交
568 569
	spin_unlock(&cache_defer_lock);

J
J. Bruce Fields 已提交
570
}
571

J
J. Bruce Fields 已提交
572 573 574 575 576 577 578 579 580 581 582 583
struct thread_deferred_req {
	struct cache_deferred_req handle;
	struct completion completion;
};

static void cache_restart_thread(struct cache_deferred_req *dreq, int too_many)
{
	struct thread_deferred_req *dr =
		container_of(dreq, struct thread_deferred_req, handle);
	complete(&dr->completion);
}

584
static void cache_wait_req(struct cache_req *req, struct cache_head *item)
J
J. Bruce Fields 已提交
585 586 587 588 589 590 591
{
	struct thread_deferred_req sleeper;
	struct cache_deferred_req *dreq = &sleeper.handle;

	sleeper.completion = COMPLETION_INITIALIZER_ONSTACK(sleeper.completion);
	dreq->revisit = cache_restart_thread;

592
	setup_deferral(dreq, item, 0);
J
J. Bruce Fields 已提交
593

594
	if (!test_bit(CACHE_PENDING, &item->flags) ||
595
	    wait_for_completion_interruptible_timeout(
J
J. Bruce Fields 已提交
596 597 598 599 600
		    &sleeper.completion, req->thread_wait) <= 0) {
		/* The completion wasn't completed, so we need
		 * to clean up
		 */
		spin_lock(&cache_defer_lock);
601
		if (!hlist_unhashed(&sleeper.handle.hash)) {
J
J. Bruce Fields 已提交
602 603 604 605 606 607 608
			__unhash_deferred_req(&sleeper.handle);
			spin_unlock(&cache_defer_lock);
		} else {
			/* cache_revisit_request already removed
			 * this from the hash table, but hasn't
			 * called ->revisit yet.  It will very soon
			 * and we need to wait for it.
609
			 */
J
J. Bruce Fields 已提交
610 611
			spin_unlock(&cache_defer_lock);
			wait_for_completion(&sleeper.completion);
612
		}
J
J. Bruce Fields 已提交
613 614 615
	}
}

616
static void cache_limit_defers(void)
J
J. Bruce Fields 已提交
617
{
618 619 620 621
	/* Make sure we haven't exceed the limit of allowed deferred
	 * requests.
	 */
	struct cache_deferred_req *discard = NULL;
J
J. Bruce Fields 已提交
622

623 624
	if (cache_defer_cnt <= DFR_MAX)
		return;
625

626 627 628 629
	spin_lock(&cache_defer_lock);

	/* Consider removing either the first or the last */
	if (cache_defer_cnt > DFR_MAX) {
630
		if (prandom_u32() & 1)
631 632 633 634 635 636 637 638
			discard = list_entry(cache_defer_list.next,
					     struct cache_deferred_req, recent);
		else
			discard = list_entry(cache_defer_list.prev,
					     struct cache_deferred_req, recent);
		__unhash_deferred_req(discard);
	}
	spin_unlock(&cache_defer_lock);
639 640
	if (discard)
		discard->revisit(discard, 1);
641
}
642

643 644
/* Return true if and only if a deferred request is queued. */
static bool cache_defer_req(struct cache_req *req, struct cache_head *item)
645 646
{
	struct cache_deferred_req *dreq;
647

J
J. Bruce Fields 已提交
648
	if (req->thread_wait) {
649 650
		cache_wait_req(req, item);
		if (!test_bit(CACHE_PENDING, &item->flags))
651
			return false;
L
Linus Torvalds 已提交
652
	}
J
J. Bruce Fields 已提交
653 654
	dreq = req->defer(req);
	if (dreq == NULL)
655
		return false;
656
	setup_deferral(dreq, item, 1);
657 658 659 660 661
	if (!test_bit(CACHE_PENDING, &item->flags))
		/* Bit could have been cleared before we managed to
		 * set up the deferral, so need to revisit just in case
		 */
		cache_revisit_request(item);
662 663

	cache_limit_defers();
664
	return true;
L
Linus Torvalds 已提交
665 666 667 668 669 670
}

static void cache_revisit_request(struct cache_head *item)
{
	struct cache_deferred_req *dreq;
	struct list_head pending;
671
	struct hlist_node *tmp;
L
Linus Torvalds 已提交
672 673 674 675
	int hash = DFR_HASH(item);

	INIT_LIST_HEAD(&pending);
	spin_lock(&cache_defer_lock);
676

677
	hlist_for_each_entry_safe(dreq, tmp, &cache_defer_hash[hash], hash)
678 679 680
		if (dreq->item == item) {
			__unhash_deferred_req(dreq);
			list_add(&dreq->recent, &pending);
L
Linus Torvalds 已提交
681
		}
682

L
Linus Torvalds 已提交
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
	spin_unlock(&cache_defer_lock);

	while (!list_empty(&pending)) {
		dreq = list_entry(pending.next, struct cache_deferred_req, recent);
		list_del_init(&dreq->recent);
		dreq->revisit(dreq, 0);
	}
}

void cache_clean_deferred(void *owner)
{
	struct cache_deferred_req *dreq, *tmp;
	struct list_head pending;


	INIT_LIST_HEAD(&pending);
	spin_lock(&cache_defer_lock);
700

L
Linus Torvalds 已提交
701 702
	list_for_each_entry_safe(dreq, tmp, &cache_defer_list, recent) {
		if (dreq->owner == owner) {
J
J. Bruce Fields 已提交
703
			__unhash_deferred_req(dreq);
704
			list_add(&dreq->recent, &pending);
L
Linus Torvalds 已提交
705 706 707 708 709 710 711 712 713 714 715 716 717 718
		}
	}
	spin_unlock(&cache_defer_lock);

	while (!list_empty(&pending)) {
		dreq = list_entry(pending.next, struct cache_deferred_req, recent);
		list_del_init(&dreq->recent);
		dreq->revisit(dreq, 1);
	}
}

/*
 * communicate with user-space
 *
J
J. Bruce Fields 已提交
719 720 721 722
 * We have a magic /proc file - /proc/sunrpc/<cachename>/channel.
 * On read, you get a full request, or block.
 * On write, an update request is processed.
 * Poll works if anything to read, and always allows write.
L
Linus Torvalds 已提交
723
 *
724
 * Implemented by linked list of requests.  Each open file has
J
J. Bruce Fields 已提交
725
 * a ->private that also exists in this list.  New requests are added
L
Linus Torvalds 已提交
726 727 728 729 730 731 732
 * to the end and may wakeup and preceding readers.
 * New readers are added to the head.  If, on read, an item is found with
 * CACHE_UPCALLING clear, we free it from the list.
 *
 */

static DEFINE_SPINLOCK(queue_lock);
A
Arjan van de Ven 已提交
733
static DEFINE_MUTEX(queue_io_mutex);
L
Linus Torvalds 已提交
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750

struct cache_queue {
	struct list_head	list;
	int			reader;	/* if 0, then request */
};
struct cache_request {
	struct cache_queue	q;
	struct cache_head	*item;
	char			* buf;
	int			len;
	int			readers;
};
struct cache_reader {
	struct cache_queue	q;
	int			offset;	/* if non-0, we have a refcnt on next request */
};

751 752 753 754 755 756 757 758 759 760 761 762
static int cache_request(struct cache_detail *detail,
			       struct cache_request *crq)
{
	char *bp = crq->buf;
	int len = PAGE_SIZE;

	detail->cache_request(detail, crq->item, &bp, &len);
	if (len < 0)
		return -EAGAIN;
	return PAGE_SIZE - len;
}

763 764
static ssize_t cache_read(struct file *filp, char __user *buf, size_t count,
			  loff_t *ppos, struct cache_detail *cd)
L
Linus Torvalds 已提交
765 766 767
{
	struct cache_reader *rp = filp->private_data;
	struct cache_request *rq;
A
Al Viro 已提交
768
	struct inode *inode = file_inode(filp);
L
Linus Torvalds 已提交
769 770 771 772 773
	int err;

	if (count == 0)
		return 0;

A
Al Viro 已提交
774
	inode_lock(inode); /* protect against multiple concurrent
L
Linus Torvalds 已提交
775 776 777 778 779 780 781 782 783 784 785 786
			      * readers on this file */
 again:
	spin_lock(&queue_lock);
	/* need to find next request */
	while (rp->q.list.next != &cd->queue &&
	       list_entry(rp->q.list.next, struct cache_queue, list)
	       ->reader) {
		struct list_head *next = rp->q.list.next;
		list_move(&rp->q.list, next);
	}
	if (rp->q.list.next == &cd->queue) {
		spin_unlock(&queue_lock);
A
Al Viro 已提交
787
		inode_unlock(inode);
788
		WARN_ON_ONCE(rp->offset);
L
Linus Torvalds 已提交
789 790 791
		return 0;
	}
	rq = container_of(rp->q.list.next, struct cache_request, q.list);
792
	WARN_ON_ONCE(rq->q.reader);
L
Linus Torvalds 已提交
793 794 795 796
	if (rp->offset == 0)
		rq->readers++;
	spin_unlock(&queue_lock);

797 798 799 800 801 802 803
	if (rq->len == 0) {
		err = cache_request(cd, rq);
		if (err < 0)
			goto out;
		rq->len = err;
	}

L
Linus Torvalds 已提交
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
	if (rp->offset == 0 && !test_bit(CACHE_PENDING, &rq->item->flags)) {
		err = -EAGAIN;
		spin_lock(&queue_lock);
		list_move(&rp->q.list, &rq->q.list);
		spin_unlock(&queue_lock);
	} else {
		if (rp->offset + count > rq->len)
			count = rq->len - rp->offset;
		err = -EFAULT;
		if (copy_to_user(buf, rq->buf + rp->offset, count))
			goto out;
		rp->offset += count;
		if (rp->offset >= rq->len) {
			rp->offset = 0;
			spin_lock(&queue_lock);
			list_move(&rp->q.list, &rq->q.list);
			spin_unlock(&queue_lock);
		}
		err = 0;
	}
 out:
	if (rp->offset == 0) {
		/* need to release rq */
		spin_lock(&queue_lock);
		rq->readers--;
		if (rq->readers == 0 &&
		    !test_bit(CACHE_PENDING, &rq->item->flags)) {
			list_del(&rq->q.list);
			spin_unlock(&queue_lock);
833
			cache_put(rq->item, cd);
L
Linus Torvalds 已提交
834 835 836 837 838 839 840
			kfree(rq->buf);
			kfree(rq);
		} else
			spin_unlock(&queue_lock);
	}
	if (err == -EAGAIN)
		goto again;
A
Al Viro 已提交
841
	inode_unlock(inode);
L
Linus Torvalds 已提交
842 843 844
	return err ? err :  count;
}

845 846 847 848
static ssize_t cache_do_downcall(char *kaddr, const char __user *buf,
				 size_t count, struct cache_detail *cd)
{
	ssize_t ret;
L
Linus Torvalds 已提交
849

850 851
	if (count == 0)
		return -EINVAL;
852 853 854 855 856 857 858 859 860 861 862
	if (copy_from_user(kaddr, buf, count))
		return -EFAULT;
	kaddr[count] = '\0';
	ret = cd->cache_parse(cd, kaddr, count);
	if (!ret)
		ret = count;
	return ret;
}

static ssize_t cache_slow_downcall(const char __user *buf,
				   size_t count, struct cache_detail *cd)
L
Linus Torvalds 已提交
863
{
864 865
	static char write_buf[8192]; /* protected by queue_io_mutex */
	ssize_t ret = -EINVAL;
L
Linus Torvalds 已提交
866 867

	if (count >= sizeof(write_buf))
868
		goto out;
A
Arjan van de Ven 已提交
869
	mutex_lock(&queue_io_mutex);
870 871 872 873 874
	ret = cache_do_downcall(write_buf, buf, count, cd);
	mutex_unlock(&queue_io_mutex);
out:
	return ret;
}
L
Linus Torvalds 已提交
875

876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
static ssize_t cache_downcall(struct address_space *mapping,
			      const char __user *buf,
			      size_t count, struct cache_detail *cd)
{
	struct page *page;
	char *kaddr;
	ssize_t ret = -ENOMEM;

	if (count >= PAGE_CACHE_SIZE)
		goto out_slow;

	page = find_or_create_page(mapping, 0, GFP_KERNEL);
	if (!page)
		goto out_slow;

	kaddr = kmap(page);
	ret = cache_do_downcall(kaddr, buf, count, cd);
	kunmap(page);
	unlock_page(page);
	page_cache_release(page);
	return ret;
out_slow:
	return cache_slow_downcall(buf, count, cd);
}
L
Linus Torvalds 已提交
900

901 902 903
static ssize_t cache_write(struct file *filp, const char __user *buf,
			   size_t count, loff_t *ppos,
			   struct cache_detail *cd)
904 905
{
	struct address_space *mapping = filp->f_mapping;
A
Al Viro 已提交
906
	struct inode *inode = file_inode(filp);
907 908 909 910 911
	ssize_t ret = -EINVAL;

	if (!cd->cache_parse)
		goto out;

A
Al Viro 已提交
912
	inode_lock(inode);
913
	ret = cache_downcall(mapping, buf, count, cd);
A
Al Viro 已提交
914
	inode_unlock(inode);
915 916
out:
	return ret;
L
Linus Torvalds 已提交
917 918 919 920
}

static DECLARE_WAIT_QUEUE_HEAD(queue_wait);

921 922
static unsigned int cache_poll(struct file *filp, poll_table *wait,
			       struct cache_detail *cd)
L
Linus Torvalds 已提交
923 924 925 926 927 928 929 930
{
	unsigned int mask;
	struct cache_reader *rp = filp->private_data;
	struct cache_queue *cq;

	poll_wait(filp, &queue_wait, wait);

	/* alway allow write */
A
Al Viro 已提交
931
	mask = POLLOUT | POLLWRNORM;
L
Linus Torvalds 已提交
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947

	if (!rp)
		return mask;

	spin_lock(&queue_lock);

	for (cq= &rp->q; &cq->list != &cd->queue;
	     cq = list_entry(cq->list.next, struct cache_queue, list))
		if (!cq->reader) {
			mask |= POLLIN | POLLRDNORM;
			break;
		}
	spin_unlock(&queue_lock);
	return mask;
}

948 949 950
static int cache_ioctl(struct inode *ino, struct file *filp,
		       unsigned int cmd, unsigned long arg,
		       struct cache_detail *cd)
L
Linus Torvalds 已提交
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
{
	int len = 0;
	struct cache_reader *rp = filp->private_data;
	struct cache_queue *cq;

	if (cmd != FIONREAD || !rp)
		return -EINVAL;

	spin_lock(&queue_lock);

	/* only find the length remaining in current request,
	 * or the length of the next request
	 */
	for (cq= &rp->q; &cq->list != &cd->queue;
	     cq = list_entry(cq->list.next, struct cache_queue, list))
		if (!cq->reader) {
			struct cache_request *cr =
				container_of(cq, struct cache_request, q);
			len = cr->len - rp->offset;
			break;
		}
	spin_unlock(&queue_lock);

	return put_user(len, (int __user *)arg);
}

977 978
static int cache_open(struct inode *inode, struct file *filp,
		      struct cache_detail *cd)
L
Linus Torvalds 已提交
979 980 981
{
	struct cache_reader *rp = NULL;

982 983
	if (!cd || !try_module_get(cd->owner))
		return -EACCES;
L
Linus Torvalds 已提交
984 985 986
	nonseekable_open(inode, filp);
	if (filp->f_mode & FMODE_READ) {
		rp = kmalloc(sizeof(*rp), GFP_KERNEL);
987 988
		if (!rp) {
			module_put(cd->owner);
L
Linus Torvalds 已提交
989
			return -ENOMEM;
990
		}
L
Linus Torvalds 已提交
991 992 993 994 995 996 997 998 999 1000 1001
		rp->offset = 0;
		rp->q.reader = 1;
		atomic_inc(&cd->readers);
		spin_lock(&queue_lock);
		list_add(&rp->q.list, &cd->queue);
		spin_unlock(&queue_lock);
	}
	filp->private_data = rp;
	return 0;
}

1002 1003
static int cache_release(struct inode *inode, struct file *filp,
			 struct cache_detail *cd)
L
Linus Torvalds 已提交
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
{
	struct cache_reader *rp = filp->private_data;

	if (rp) {
		spin_lock(&queue_lock);
		if (rp->offset) {
			struct cache_queue *cq;
			for (cq= &rp->q; &cq->list != &cd->queue;
			     cq = list_entry(cq->list.next, struct cache_queue, list))
				if (!cq->reader) {
					container_of(cq, struct cache_request, q)
						->readers--;
					break;
				}
			rp->offset = 0;
		}
		list_del(&rp->q.list);
		spin_unlock(&queue_lock);

		filp->private_data = NULL;
		kfree(rp);

1026
		cd->last_close = seconds_since_boot();
L
Linus Torvalds 已提交
1027 1028
		atomic_dec(&cd->readers);
	}
1029
	module_put(cd->owner);
L
Linus Torvalds 已提交
1030 1031 1032 1033 1034
	return 0;
}



1035
static void cache_dequeue(struct cache_detail *detail, struct cache_head *ch)
L
Linus Torvalds 已提交
1036
{
1037 1038 1039 1040 1041
	struct cache_queue *cq, *tmp;
	struct cache_request *cr;
	struct list_head dequeued;

	INIT_LIST_HEAD(&dequeued);
L
Linus Torvalds 已提交
1042
	spin_lock(&queue_lock);
1043
	list_for_each_entry_safe(cq, tmp, &detail->queue, list)
L
Linus Torvalds 已提交
1044
		if (!cq->reader) {
1045
			cr = container_of(cq, struct cache_request, q);
L
Linus Torvalds 已提交
1046 1047
			if (cr->item != ch)
				continue;
1048 1049 1050
			if (test_bit(CACHE_PENDING, &ch->flags))
				/* Lost a race and it is pending again */
				break;
L
Linus Torvalds 已提交
1051
			if (cr->readers != 0)
1052
				continue;
1053
			list_move(&cr->q.list, &dequeued);
L
Linus Torvalds 已提交
1054 1055
		}
	spin_unlock(&queue_lock);
1056 1057 1058 1059 1060 1061 1062
	while (!list_empty(&dequeued)) {
		cr = list_entry(dequeued.next, struct cache_request, q.list);
		list_del(&cr->q.list);
		cache_put(cr->item, detail);
		kfree(cr->buf);
		kfree(cr);
	}
L
Linus Torvalds 已提交
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
}

/*
 * Support routines for text-based upcalls.
 * Fields are separated by spaces.
 * Fields are either mangled to quote space tab newline slosh with slosh
 * or a hexified with a leading \x
 * Record is terminated with newline.
 *
 */

void qword_add(char **bpp, int *lp, char *str)
{
	char *bp = *bpp;
	int len = *lp;
1078
	int ret;
L
Linus Torvalds 已提交
1079 1080 1081

	if (len < 0) return;

1082 1083 1084
	ret = string_escape_str(str, bp, len, ESCAPE_OCTAL, "\\ \n\t");
	if (ret >= len) {
		bp += len;
1085
		len = -1;
1086 1087
	} else {
		bp += ret;
1088
		len -= ret;
L
Linus Torvalds 已提交
1089 1090 1091 1092 1093 1094
		*bp++ = ' ';
		len--;
	}
	*bpp = bp;
	*lp = len;
}
1095
EXPORT_SYMBOL_GPL(qword_add);
L
Linus Torvalds 已提交
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108

void qword_addhex(char **bpp, int *lp, char *buf, int blen)
{
	char *bp = *bpp;
	int len = *lp;

	if (len < 0) return;

	if (len > 2) {
		*bp++ = '\\';
		*bp++ = 'x';
		len -= 2;
		while (blen && len >= 2) {
1109
			bp = hex_byte_pack(bp, *buf++);
L
Linus Torvalds 已提交
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
			len -= 2;
			blen--;
		}
	}
	if (blen || len<1) len = -1;
	else {
		*bp++ = ' ';
		len--;
	}
	*bpp = bp;
	*lp = len;
}
1122
EXPORT_SYMBOL_GPL(qword_addhex);
L
Linus Torvalds 已提交
1123 1124 1125 1126 1127 1128

static void warn_no_listener(struct cache_detail *detail)
{
	if (detail->last_warn != detail->last_close) {
		detail->last_warn = detail->last_close;
		if (detail->warn_no_listener)
1129
			detail->warn_no_listener(detail, detail->last_close != 0);
L
Linus Torvalds 已提交
1130 1131 1132
	}
}

1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
static bool cache_listeners_exist(struct cache_detail *detail)
{
	if (atomic_read(&detail->readers))
		return true;
	if (detail->last_close == 0)
		/* This cache was never opened */
		return false;
	if (detail->last_close < seconds_since_boot() - 30)
		/*
		 * We allow for the possibility that someone might
		 * restart a userspace daemon without restarting the
		 * server; but after 30 seconds, we give up.
		 */
		 return false;
	return true;
}

L
Linus Torvalds 已提交
1150
/*
1151 1152 1153
 * register an upcall request to user-space and queue it up for read() by the
 * upcall daemon.
 *
L
Linus Torvalds 已提交
1154 1155
 * Each request is at most one page long.
 */
1156
int sunrpc_cache_pipe_upcall(struct cache_detail *detail, struct cache_head *h)
L
Linus Torvalds 已提交
1157 1158 1159 1160
{

	char *buf;
	struct cache_request *crq;
1161
	int ret = 0;
L
Linus Torvalds 已提交
1162

1163 1164
	if (!detail->cache_request)
		return -EINVAL;
L
Linus Torvalds 已提交
1165

1166 1167 1168
	if (!cache_listeners_exist(detail)) {
		warn_no_listener(detail);
		return -EINVAL;
L
Linus Torvalds 已提交
1169
	}
1170 1171 1172
	if (test_bit(CACHE_CLEANED, &h->flags))
		/* Too late to make an upcall */
		return -EAGAIN;
L
Linus Torvalds 已提交
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185

	buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
	if (!buf)
		return -EAGAIN;

	crq = kmalloc(sizeof (*crq), GFP_KERNEL);
	if (!crq) {
		kfree(buf);
		return -EAGAIN;
	}

	crq->q.reader = 0;
	crq->buf = buf;
1186
	crq->len = 0;
L
Linus Torvalds 已提交
1187 1188
	crq->readers = 0;
	spin_lock(&queue_lock);
1189 1190
	if (test_bit(CACHE_PENDING, &h->flags)) {
		crq->item = cache_get(h);
1191
		list_add_tail(&crq->q.list, &detail->queue);
1192
	} else
1193 1194
		/* Lost a race, no longer PENDING, so don't enqueue */
		ret = -EAGAIN;
L
Linus Torvalds 已提交
1195 1196
	spin_unlock(&queue_lock);
	wake_up(&queue_wait);
1197 1198 1199 1200 1201
	if (ret == -EAGAIN) {
		kfree(buf);
		kfree(crq);
	}
	return ret;
L
Linus Torvalds 已提交
1202
}
1203
EXPORT_SYMBOL_GPL(sunrpc_cache_pipe_upcall);
L
Linus Torvalds 已提交
1204 1205 1206 1207 1208 1209 1210

/*
 * parse a message from user-space and pass it
 * to an appropriate cache
 * Messages are, like requests, separated into fields by
 * spaces and dequotes as \xHEXSTRING or embedded \nnn octal
 *
1211
 * Message is
L
Linus Torvalds 已提交
1212 1213
 *   reply cachename expiry key ... content....
 *
1214
 * key and content are both parsed by cache
L
Linus Torvalds 已提交
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
 */

int qword_get(char **bpp, char *dest, int bufsize)
{
	/* return bytes copied, or -1 on error */
	char *bp = *bpp;
	int len = 0;

	while (*bp == ' ') bp++;

	if (bp[0] == '\\' && bp[1] == 'x') {
		/* HEX STRING */
		bp += 2;
1228
		while (len < bufsize - 1) {
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
			int h, l;

			h = hex_to_bin(bp[0]);
			if (h < 0)
				break;

			l = hex_to_bin(bp[1]);
			if (l < 0)
				break;

			*dest++ = (h << 4) | l;
			bp += 2;
L
Linus Torvalds 已提交
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
			len++;
		}
	} else {
		/* text with \nnn octal quoting */
		while (*bp != ' ' && *bp != '\n' && *bp && len < bufsize-1) {
			if (*bp == '\\' &&
			    isodigit(bp[1]) && (bp[1] <= '3') &&
			    isodigit(bp[2]) &&
			    isodigit(bp[3])) {
				int byte = (*++bp -'0');
				bp++;
				byte = (byte << 3) | (*bp++ - '0');
				byte = (byte << 3) | (*bp++ - '0');
				*dest++ = byte;
				len++;
			} else {
				*dest++ = *bp++;
				len++;
			}
		}
	}

	if (*bp != ' ' && *bp != '\n' && *bp != '\0')
		return -1;
	while (*bp == ' ') bp++;
	*bpp = bp;
	*dest = '\0';
	return len;
}
1270
EXPORT_SYMBOL_GPL(qword_get);
L
Linus Torvalds 已提交
1271 1272 1273 1274 1275 1276 1277 1278 1279


/*
 * support /proc/sunrpc/cache/$CACHENAME/content
 * as a seqfile.
 * We call ->cache_show passing NULL for the item to
 * get a header, then pass each real item in the cache
 */

1280
void *cache_seq_start(struct seq_file *m, loff_t *pos)
1281
	__acquires(cd->hash_lock)
L
Linus Torvalds 已提交
1282 1283
{
	loff_t n = *pos;
1284
	unsigned int hash, entry;
L
Linus Torvalds 已提交
1285
	struct cache_head *ch;
1286
	struct cache_detail *cd = m->private;
L
Linus Torvalds 已提交
1287 1288 1289 1290 1291 1292 1293

	read_lock(&cd->hash_lock);
	if (!n--)
		return SEQ_START_TOKEN;
	hash = n >> 32;
	entry = n & ((1LL<<32) - 1);

1294
	hlist_for_each_entry(ch, &cd->hash_table[hash], cache_list)
L
Linus Torvalds 已提交
1295 1296 1297 1298 1299 1300
		if (!entry--)
			return ch;
	n &= ~((1LL<<32) - 1);
	do {
		hash++;
		n += 1LL<<32;
1301
	} while(hash < cd->hash_size &&
1302
		hlist_empty(&cd->hash_table[hash]));
L
Linus Torvalds 已提交
1303 1304 1305
	if (hash >= cd->hash_size)
		return NULL;
	*pos = n+1;
1306 1307
	return hlist_entry_safe(cd->hash_table[hash].first,
				struct cache_head, cache_list);
L
Linus Torvalds 已提交
1308
}
1309
EXPORT_SYMBOL_GPL(cache_seq_start);
L
Linus Torvalds 已提交
1310

1311
void *cache_seq_next(struct seq_file *m, void *p, loff_t *pos)
L
Linus Torvalds 已提交
1312 1313 1314
{
	struct cache_head *ch = p;
	int hash = (*pos >> 32);
1315
	struct cache_detail *cd = m->private;
L
Linus Torvalds 已提交
1316 1317 1318

	if (p == SEQ_START_TOKEN)
		hash = 0;
1319
	else if (ch->cache_list.next == NULL) {
L
Linus Torvalds 已提交
1320 1321 1322 1323
		hash++;
		*pos += 1LL<<32;
	} else {
		++*pos;
1324 1325
		return hlist_entry_safe(ch->cache_list.next,
					struct cache_head, cache_list);
L
Linus Torvalds 已提交
1326 1327 1328
	}
	*pos &= ~((1LL<<32) - 1);
	while (hash < cd->hash_size &&
1329
	       hlist_empty(&cd->hash_table[hash])) {
L
Linus Torvalds 已提交
1330 1331 1332 1333 1334 1335
		hash++;
		*pos += 1LL<<32;
	}
	if (hash >= cd->hash_size)
		return NULL;
	++*pos;
1336 1337
	return hlist_entry_safe(cd->hash_table[hash].first,
				struct cache_head, cache_list);
L
Linus Torvalds 已提交
1338
}
1339
EXPORT_SYMBOL_GPL(cache_seq_next);
L
Linus Torvalds 已提交
1340

1341
void cache_seq_stop(struct seq_file *m, void *p)
1342
	__releases(cd->hash_lock)
L
Linus Torvalds 已提交
1343
{
1344
	struct cache_detail *cd = m->private;
L
Linus Torvalds 已提交
1345 1346
	read_unlock(&cd->hash_lock);
}
1347
EXPORT_SYMBOL_GPL(cache_seq_stop);
L
Linus Torvalds 已提交
1348 1349 1350 1351

static int c_show(struct seq_file *m, void *p)
{
	struct cache_head *cp = p;
1352
	struct cache_detail *cd = m->private;
L
Linus Torvalds 已提交
1353 1354 1355 1356 1357

	if (p == SEQ_START_TOKEN)
		return cd->cache_show(m, cd, NULL);

	ifdebug(CACHE)
1358
		seq_printf(m, "# expiry=%ld refcnt=%d flags=%lx\n",
1359 1360
			   convert_to_wallclock(cp->expiry_time),
			   atomic_read(&cp->ref.refcount), cp->flags);
L
Linus Torvalds 已提交
1361 1362 1363 1364
	cache_get(cp);
	if (cache_check(cd, cp, NULL))
		/* cache_check does a cache_put on failure */
		seq_printf(m, "# ");
1365 1366 1367
	else {
		if (cache_is_expired(cd, cp))
			seq_printf(m, "# ");
L
Linus Torvalds 已提交
1368
		cache_put(cp, cd);
1369
	}
L
Linus Torvalds 已提交
1370 1371 1372 1373

	return cd->cache_show(m, cd, cp);
}

1374
static const struct seq_operations cache_content_op = {
1375 1376 1377
	.start	= cache_seq_start,
	.next	= cache_seq_next,
	.stop	= cache_seq_stop,
L
Linus Torvalds 已提交
1378 1379 1380
	.show	= c_show,
};

1381 1382
static int content_open(struct inode *inode, struct file *file,
			struct cache_detail *cd)
L
Linus Torvalds 已提交
1383
{
1384 1385
	struct seq_file *seq;
	int err;
L
Linus Torvalds 已提交
1386

1387 1388
	if (!cd || !try_module_get(cd->owner))
		return -EACCES;
1389 1390 1391

	err = seq_open(file, &cache_content_op);
	if (err) {
1392
		module_put(cd->owner);
1393
		return err;
1394
	}
L
Linus Torvalds 已提交
1395

1396 1397
	seq = file->private_data;
	seq->private = cd;
1398
	return 0;
L
Linus Torvalds 已提交
1399 1400
}

1401 1402 1403
static int content_release(struct inode *inode, struct file *file,
		struct cache_detail *cd)
{
1404
	int ret = seq_release(inode, file);
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
	module_put(cd->owner);
	return ret;
}

static int open_flush(struct inode *inode, struct file *file,
			struct cache_detail *cd)
{
	if (!cd || !try_module_get(cd->owner))
		return -EACCES;
	return nonseekable_open(inode, file);
}

static int release_flush(struct inode *inode, struct file *file,
			struct cache_detail *cd)
{
	module_put(cd->owner);
	return 0;
}
L
Linus Torvalds 已提交
1423 1424

static ssize_t read_flush(struct file *file, char __user *buf,
1425 1426
			  size_t count, loff_t *ppos,
			  struct cache_detail *cd)
L
Linus Torvalds 已提交
1427
{
1428
	char tbuf[22];
L
Linus Torvalds 已提交
1429
	unsigned long p = *ppos;
1430
	size_t len;
L
Linus Torvalds 已提交
1431

1432
	snprintf(tbuf, sizeof(tbuf), "%lu\n", convert_to_wallclock(cd->flush_time));
L
Linus Torvalds 已提交
1433 1434 1435 1436
	len = strlen(tbuf);
	if (p >= len)
		return 0;
	len -= p;
1437 1438
	if (len > count)
		len = count;
L
Linus Torvalds 已提交
1439
	if (copy_to_user(buf, (void*)(tbuf+p), len))
1440 1441
		return -EFAULT;
	*ppos += len;
L
Linus Torvalds 已提交
1442 1443 1444
	return len;
}

1445 1446 1447
static ssize_t write_flush(struct file *file, const char __user *buf,
			   size_t count, loff_t *ppos,
			   struct cache_detail *cd)
L
Linus Torvalds 已提交
1448 1449
{
	char tbuf[20];
1450
	char *bp, *ep;
1451
	time_t then, now;
1452

L
Linus Torvalds 已提交
1453 1454 1455 1456 1457
	if (*ppos || count > sizeof(tbuf)-1)
		return -EINVAL;
	if (copy_from_user(tbuf, buf, count))
		return -EFAULT;
	tbuf[count] = 0;
1458
	simple_strtoul(tbuf, &ep, 0);
L
Linus Torvalds 已提交
1459 1460 1461
	if (*ep && *ep != '\n')
		return -EINVAL;

1462
	bp = tbuf;
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
	then = get_expiry(&bp);
	now = seconds_since_boot();
	cd->nextcheck = now;
	/* Can only set flush_time to 1 second beyond "now", or
	 * possibly 1 second beyond flushtime.  This is because
	 * flush_time never goes backwards so it mustn't get too far
	 * ahead of time.
	 */
	if (then >= now) {
		/* Want to flush everything, so behave like cache_purge() */
		if (cd->flush_time >= now)
			now = cd->flush_time + 1;
		then = now;
	}

	cd->flush_time = then;
L
Linus Torvalds 已提交
1479 1480 1481 1482 1483 1484
	cache_flush();

	*ppos += count;
	return count;
}

1485 1486 1487
static ssize_t cache_read_procfs(struct file *filp, char __user *buf,
				 size_t count, loff_t *ppos)
{
A
Al Viro 已提交
1488
	struct cache_detail *cd = PDE_DATA(file_inode(filp));
1489 1490 1491 1492 1493 1494 1495

	return cache_read(filp, buf, count, ppos, cd);
}

static ssize_t cache_write_procfs(struct file *filp, const char __user *buf,
				  size_t count, loff_t *ppos)
{
A
Al Viro 已提交
1496
	struct cache_detail *cd = PDE_DATA(file_inode(filp));
1497 1498 1499 1500 1501 1502

	return cache_write(filp, buf, count, ppos, cd);
}

static unsigned int cache_poll_procfs(struct file *filp, poll_table *wait)
{
A
Al Viro 已提交
1503
	struct cache_detail *cd = PDE_DATA(file_inode(filp));
1504 1505 1506 1507

	return cache_poll(filp, wait, cd);
}

1508 1509
static long cache_ioctl_procfs(struct file *filp,
			       unsigned int cmd, unsigned long arg)
1510
{
A
Al Viro 已提交
1511
	struct inode *inode = file_inode(filp);
A
Al Viro 已提交
1512
	struct cache_detail *cd = PDE_DATA(inode);
1513

A
Arnd Bergmann 已提交
1514
	return cache_ioctl(inode, filp, cmd, arg, cd);
1515 1516 1517 1518
}

static int cache_open_procfs(struct inode *inode, struct file *filp)
{
A
Al Viro 已提交
1519
	struct cache_detail *cd = PDE_DATA(inode);
1520 1521 1522 1523 1524 1525

	return cache_open(inode, filp, cd);
}

static int cache_release_procfs(struct inode *inode, struct file *filp)
{
A
Al Viro 已提交
1526
	struct cache_detail *cd = PDE_DATA(inode);
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536

	return cache_release(inode, filp, cd);
}

static const struct file_operations cache_file_operations_procfs = {
	.owner		= THIS_MODULE,
	.llseek		= no_llseek,
	.read		= cache_read_procfs,
	.write		= cache_write_procfs,
	.poll		= cache_poll_procfs,
1537
	.unlocked_ioctl	= cache_ioctl_procfs, /* for FIONREAD */
1538 1539
	.open		= cache_open_procfs,
	.release	= cache_release_procfs,
L
Linus Torvalds 已提交
1540
};
1541 1542 1543

static int content_open_procfs(struct inode *inode, struct file *filp)
{
A
Al Viro 已提交
1544
	struct cache_detail *cd = PDE_DATA(inode);
1545 1546 1547 1548

	return content_open(inode, filp, cd);
}

1549 1550
static int content_release_procfs(struct inode *inode, struct file *filp)
{
A
Al Viro 已提交
1551
	struct cache_detail *cd = PDE_DATA(inode);
1552 1553 1554 1555

	return content_release(inode, filp, cd);
}

1556 1557 1558 1559
static const struct file_operations content_file_operations_procfs = {
	.open		= content_open_procfs,
	.read		= seq_read,
	.llseek		= seq_lseek,
1560
	.release	= content_release_procfs,
1561 1562
};

1563 1564
static int open_flush_procfs(struct inode *inode, struct file *filp)
{
A
Al Viro 已提交
1565
	struct cache_detail *cd = PDE_DATA(inode);
1566 1567 1568 1569 1570 1571

	return open_flush(inode, filp, cd);
}

static int release_flush_procfs(struct inode *inode, struct file *filp)
{
A
Al Viro 已提交
1572
	struct cache_detail *cd = PDE_DATA(inode);
1573 1574 1575 1576

	return release_flush(inode, filp, cd);
}

1577 1578 1579
static ssize_t read_flush_procfs(struct file *filp, char __user *buf,
			    size_t count, loff_t *ppos)
{
A
Al Viro 已提交
1580
	struct cache_detail *cd = PDE_DATA(file_inode(filp));
1581 1582 1583 1584 1585 1586 1587 1588

	return read_flush(filp, buf, count, ppos, cd);
}

static ssize_t write_flush_procfs(struct file *filp,
				  const char __user *buf,
				  size_t count, loff_t *ppos)
{
A
Al Viro 已提交
1589
	struct cache_detail *cd = PDE_DATA(file_inode(filp));
1590 1591 1592 1593 1594

	return write_flush(filp, buf, count, ppos, cd);
}

static const struct file_operations cache_flush_operations_procfs = {
1595
	.open		= open_flush_procfs,
1596 1597
	.read		= read_flush_procfs,
	.write		= write_flush_procfs,
1598
	.release	= release_flush_procfs,
1599
	.llseek		= no_llseek,
L
Linus Torvalds 已提交
1600
};
1601

1602
static void remove_cache_proc_entries(struct cache_detail *cd, struct net *net)
1603
{
1604 1605
	struct sunrpc_net *sn;

1606 1607 1608 1609 1610 1611 1612 1613 1614
	if (cd->u.procfs.proc_ent == NULL)
		return;
	if (cd->u.procfs.flush_ent)
		remove_proc_entry("flush", cd->u.procfs.proc_ent);
	if (cd->u.procfs.channel_ent)
		remove_proc_entry("channel", cd->u.procfs.proc_ent);
	if (cd->u.procfs.content_ent)
		remove_proc_entry("content", cd->u.procfs.proc_ent);
	cd->u.procfs.proc_ent = NULL;
1615 1616
	sn = net_generic(net, sunrpc_net_id);
	remove_proc_entry(cd->name, sn->proc_net_rpc);
1617 1618 1619
}

#ifdef CONFIG_PROC_FS
1620
static int create_cache_proc_entries(struct cache_detail *cd, struct net *net)
1621 1622
{
	struct proc_dir_entry *p;
1623
	struct sunrpc_net *sn;
1624

1625 1626
	sn = net_generic(net, sunrpc_net_id);
	cd->u.procfs.proc_ent = proc_mkdir(cd->name, sn->proc_net_rpc);
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
	if (cd->u.procfs.proc_ent == NULL)
		goto out_nomem;
	cd->u.procfs.channel_ent = NULL;
	cd->u.procfs.content_ent = NULL;

	p = proc_create_data("flush", S_IFREG|S_IRUSR|S_IWUSR,
			     cd->u.procfs.proc_ent,
			     &cache_flush_operations_procfs, cd);
	cd->u.procfs.flush_ent = p;
	if (p == NULL)
		goto out_nomem;

1639
	if (cd->cache_request || cd->cache_parse) {
1640 1641 1642 1643 1644 1645 1646 1647
		p = proc_create_data("channel", S_IFREG|S_IRUSR|S_IWUSR,
				     cd->u.procfs.proc_ent,
				     &cache_file_operations_procfs, cd);
		cd->u.procfs.channel_ent = p;
		if (p == NULL)
			goto out_nomem;
	}
	if (cd->cache_show) {
1648
		p = proc_create_data("content", S_IFREG|S_IRUSR,
1649 1650 1651 1652 1653 1654 1655 1656
				cd->u.procfs.proc_ent,
				&content_file_operations_procfs, cd);
		cd->u.procfs.content_ent = p;
		if (p == NULL)
			goto out_nomem;
	}
	return 0;
out_nomem:
1657
	remove_cache_proc_entries(cd, net);
1658 1659 1660
	return -ENOMEM;
}
#else /* CONFIG_PROC_FS */
1661
static int create_cache_proc_entries(struct cache_detail *cd, struct net *net)
1662 1663 1664 1665 1666
{
	return 0;
}
#endif

1667 1668
void __init cache_initialize(void)
{
1669
	INIT_DEFERRABLE_WORK(&cache_cleaner, do_cache_clean);
1670 1671
}

1672
int cache_register_net(struct cache_detail *cd, struct net *net)
1673 1674 1675 1676
{
	int ret;

	sunrpc_init_cache_detail(cd);
1677
	ret = create_cache_proc_entries(cd, net);
1678 1679 1680 1681
	if (ret)
		sunrpc_destroy_cache_detail(cd);
	return ret;
}
1682
EXPORT_SYMBOL_GPL(cache_register_net);
1683 1684

void cache_unregister_net(struct cache_detail *cd, struct net *net)
1685
{
1686
	remove_cache_proc_entries(cd, net);
1687 1688
	sunrpc_destroy_cache_detail(cd);
}
1689
EXPORT_SYMBOL_GPL(cache_unregister_net);
1690

1691 1692 1693
struct cache_detail *cache_create_net(struct cache_detail *tmpl, struct net *net)
{
	struct cache_detail *cd;
1694
	int i;
1695 1696 1697 1698 1699

	cd = kmemdup(tmpl, sizeof(struct cache_detail), GFP_KERNEL);
	if (cd == NULL)
		return ERR_PTR(-ENOMEM);

1700
	cd->hash_table = kzalloc(cd->hash_size * sizeof(struct hlist_head),
1701 1702 1703 1704 1705
				 GFP_KERNEL);
	if (cd->hash_table == NULL) {
		kfree(cd);
		return ERR_PTR(-ENOMEM);
	}
1706 1707 1708

	for (i = 0; i < cd->hash_size; i++)
		INIT_HLIST_HEAD(&cd->hash_table[i]);
1709 1710 1711 1712 1713 1714
	cd->net = net;
	return cd;
}
EXPORT_SYMBOL_GPL(cache_create_net);

void cache_destroy_net(struct cache_detail *cd, struct net *net)
1715
{
1716 1717
	kfree(cd->hash_table);
	kfree(cd);
1718
}
1719
EXPORT_SYMBOL_GPL(cache_destroy_net);
1720 1721 1722 1723

static ssize_t cache_read_pipefs(struct file *filp, char __user *buf,
				 size_t count, loff_t *ppos)
{
A
Al Viro 已提交
1724
	struct cache_detail *cd = RPC_I(file_inode(filp))->private;
1725 1726 1727 1728 1729 1730 1731

	return cache_read(filp, buf, count, ppos, cd);
}

static ssize_t cache_write_pipefs(struct file *filp, const char __user *buf,
				  size_t count, loff_t *ppos)
{
A
Al Viro 已提交
1732
	struct cache_detail *cd = RPC_I(file_inode(filp))->private;
1733 1734 1735 1736 1737 1738

	return cache_write(filp, buf, count, ppos, cd);
}

static unsigned int cache_poll_pipefs(struct file *filp, poll_table *wait)
{
A
Al Viro 已提交
1739
	struct cache_detail *cd = RPC_I(file_inode(filp))->private;
1740 1741 1742 1743

	return cache_poll(filp, wait, cd);
}

1744
static long cache_ioctl_pipefs(struct file *filp,
1745 1746
			      unsigned int cmd, unsigned long arg)
{
A
Al Viro 已提交
1747
	struct inode *inode = file_inode(filp);
1748 1749
	struct cache_detail *cd = RPC_I(inode)->private;

A
Arnd Bergmann 已提交
1750
	return cache_ioctl(inode, filp, cmd, arg, cd);
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772
}

static int cache_open_pipefs(struct inode *inode, struct file *filp)
{
	struct cache_detail *cd = RPC_I(inode)->private;

	return cache_open(inode, filp, cd);
}

static int cache_release_pipefs(struct inode *inode, struct file *filp)
{
	struct cache_detail *cd = RPC_I(inode)->private;

	return cache_release(inode, filp, cd);
}

const struct file_operations cache_file_operations_pipefs = {
	.owner		= THIS_MODULE,
	.llseek		= no_llseek,
	.read		= cache_read_pipefs,
	.write		= cache_write_pipefs,
	.poll		= cache_poll_pipefs,
1773
	.unlocked_ioctl	= cache_ioctl_pipefs, /* for FIONREAD */
1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784
	.open		= cache_open_pipefs,
	.release	= cache_release_pipefs,
};

static int content_open_pipefs(struct inode *inode, struct file *filp)
{
	struct cache_detail *cd = RPC_I(inode)->private;

	return content_open(inode, filp, cd);
}

1785 1786 1787 1788 1789 1790 1791
static int content_release_pipefs(struct inode *inode, struct file *filp)
{
	struct cache_detail *cd = RPC_I(inode)->private;

	return content_release(inode, filp, cd);
}

1792 1793 1794 1795
const struct file_operations content_file_operations_pipefs = {
	.open		= content_open_pipefs,
	.read		= seq_read,
	.llseek		= seq_lseek,
1796
	.release	= content_release_pipefs,
1797 1798
};

1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812
static int open_flush_pipefs(struct inode *inode, struct file *filp)
{
	struct cache_detail *cd = RPC_I(inode)->private;

	return open_flush(inode, filp, cd);
}

static int release_flush_pipefs(struct inode *inode, struct file *filp)
{
	struct cache_detail *cd = RPC_I(inode)->private;

	return release_flush(inode, filp, cd);
}

1813 1814 1815
static ssize_t read_flush_pipefs(struct file *filp, char __user *buf,
			    size_t count, loff_t *ppos)
{
A
Al Viro 已提交
1816
	struct cache_detail *cd = RPC_I(file_inode(filp))->private;
1817 1818 1819 1820 1821 1822 1823 1824

	return read_flush(filp, buf, count, ppos, cd);
}

static ssize_t write_flush_pipefs(struct file *filp,
				  const char __user *buf,
				  size_t count, loff_t *ppos)
{
A
Al Viro 已提交
1825
	struct cache_detail *cd = RPC_I(file_inode(filp))->private;
1826 1827 1828 1829 1830

	return write_flush(filp, buf, count, ppos, cd);
}

const struct file_operations cache_flush_operations_pipefs = {
1831
	.open		= open_flush_pipefs,
1832 1833
	.read		= read_flush_pipefs,
	.write		= write_flush_pipefs,
1834
	.release	= release_flush_pipefs,
1835
	.llseek		= no_llseek,
1836 1837 1838
};

int sunrpc_cache_register_pipefs(struct dentry *parent,
A
Al Viro 已提交
1839
				 const char *name, umode_t umode,
1840 1841
				 struct cache_detail *cd)
{
1842 1843 1844 1845 1846
	struct dentry *dir = rpc_create_cache_dir(parent, name, umode, cd);
	if (IS_ERR(dir))
		return PTR_ERR(dir);
	cd->u.pipefs.dir = dir;
	return 0;
1847 1848 1849 1850 1851 1852 1853 1854 1855 1856
}
EXPORT_SYMBOL_GPL(sunrpc_cache_register_pipefs);

void sunrpc_cache_unregister_pipefs(struct cache_detail *cd)
{
	rpc_remove_cache_dir(cd->u.pipefs.dir);
	cd->u.pipefs.dir = NULL;
}
EXPORT_SYMBOL_GPL(sunrpc_cache_unregister_pipefs);