xref: /openbmc/linux/net/sunrpc/cache.c (revision 9f7d35d9)
1 /*
2  * net/sunrpc/cache.c
3  *
4  * Generic code for various authentication-related caches
5  * used by sunrpc clients and servers.
6  *
7  * Copyright (C) 2002 Neil Brown <neilb@cse.unsw.edu.au>
8  *
9  * Released under terms in GPL version 2.  See COPYING.
10  *
11  */
12 
13 #include <linux/types.h>
14 #include <linux/fs.h>
15 #include <linux/file.h>
16 #include <linux/slab.h>
17 #include <linux/signal.h>
18 #include <linux/sched.h>
19 #include <linux/kmod.h>
20 #include <linux/list.h>
21 #include <linux/module.h>
22 #include <linux/ctype.h>
23 #include <linux/string_helpers.h>
24 #include <linux/uaccess.h>
25 #include <linux/poll.h>
26 #include <linux/seq_file.h>
27 #include <linux/proc_fs.h>
28 #include <linux/net.h>
29 #include <linux/workqueue.h>
30 #include <linux/mutex.h>
31 #include <linux/pagemap.h>
32 #include <asm/ioctls.h>
33 #include <linux/sunrpc/types.h>
34 #include <linux/sunrpc/cache.h>
35 #include <linux/sunrpc/stats.h>
36 #include <linux/sunrpc/rpc_pipe_fs.h>
37 #include "netns.h"
38 
39 #define	 RPCDBG_FACILITY RPCDBG_CACHE
40 
41 static bool cache_defer_req(struct cache_req *req, struct cache_head *item);
42 static void cache_revisit_request(struct cache_head *item);
43 
44 static void cache_init(struct cache_head *h, struct cache_detail *detail)
45 {
46 	time_t now = seconds_since_boot();
47 	INIT_HLIST_NODE(&h->cache_list);
48 	h->flags = 0;
49 	kref_init(&h->ref);
50 	h->expiry_time = now + CACHE_NEW_EXPIRY;
51 	if (now <= detail->flush_time)
52 		/* ensure it isn't already expired */
53 		now = detail->flush_time + 1;
54 	h->last_refresh = now;
55 }
56 
57 static void cache_fresh_locked(struct cache_head *head, time_t expiry,
58 				struct cache_detail *detail);
59 static void cache_fresh_unlocked(struct cache_head *head,
60 				struct cache_detail *detail);
61 
62 static struct cache_head *sunrpc_cache_find_rcu(struct cache_detail *detail,
63 						struct cache_head *key,
64 						int hash)
65 {
66 	struct hlist_head *head = &detail->hash_table[hash];
67 	struct cache_head *tmp;
68 
69 	rcu_read_lock();
70 	hlist_for_each_entry_rcu(tmp, head, cache_list) {
71 		if (detail->match(tmp, key)) {
72 			if (cache_is_expired(detail, tmp))
73 				continue;
74 			tmp = cache_get_rcu(tmp);
75 			rcu_read_unlock();
76 			return tmp;
77 		}
78 	}
79 	rcu_read_unlock();
80 	return NULL;
81 }
82 
83 static struct cache_head *sunrpc_cache_add_entry(struct cache_detail *detail,
84 						 struct cache_head *key,
85 						 int hash)
86 {
87 	struct cache_head *new, *tmp, *freeme = NULL;
88 	struct hlist_head *head = &detail->hash_table[hash];
89 
90 	new = detail->alloc();
91 	if (!new)
92 		return NULL;
93 	/* must fully initialise 'new', else
94 	 * we might get lose if we need to
95 	 * cache_put it soon.
96 	 */
97 	cache_init(new, detail);
98 	detail->init(new, key);
99 
100 	spin_lock(&detail->hash_lock);
101 
102 	/* check if entry appeared while we slept */
103 	hlist_for_each_entry_rcu(tmp, head, cache_list) {
104 		if (detail->match(tmp, key)) {
105 			if (cache_is_expired(detail, tmp)) {
106 				hlist_del_init_rcu(&tmp->cache_list);
107 				detail->entries --;
108 				cache_fresh_locked(tmp, 0, detail);
109 				freeme = tmp;
110 				break;
111 			}
112 			cache_get(tmp);
113 			spin_unlock(&detail->hash_lock);
114 			cache_put(new, detail);
115 			return tmp;
116 		}
117 	}
118 
119 	hlist_add_head_rcu(&new->cache_list, head);
120 	detail->entries++;
121 	cache_get(new);
122 	spin_unlock(&detail->hash_lock);
123 
124 	if (freeme) {
125 		cache_fresh_unlocked(freeme, detail);
126 		cache_put(freeme, detail);
127 	}
128 	return new;
129 }
130 
131 struct cache_head *sunrpc_cache_lookup_rcu(struct cache_detail *detail,
132 					   struct cache_head *key, int hash)
133 {
134 	struct cache_head *ret;
135 
136 	ret = sunrpc_cache_find_rcu(detail, key, hash);
137 	if (ret)
138 		return ret;
139 	/* Didn't find anything, insert an empty entry */
140 	return sunrpc_cache_add_entry(detail, key, hash);
141 }
142 EXPORT_SYMBOL_GPL(sunrpc_cache_lookup_rcu);
143 
144 static void cache_dequeue(struct cache_detail *detail, struct cache_head *ch);
145 
146 static void cache_fresh_locked(struct cache_head *head, time_t expiry,
147 			       struct cache_detail *detail)
148 {
149 	time_t now = seconds_since_boot();
150 	if (now <= detail->flush_time)
151 		/* ensure it isn't immediately treated as expired */
152 		now = detail->flush_time + 1;
153 	head->expiry_time = expiry;
154 	head->last_refresh = now;
155 	smp_wmb(); /* paired with smp_rmb() in cache_is_valid() */
156 	set_bit(CACHE_VALID, &head->flags);
157 }
158 
159 static void cache_fresh_unlocked(struct cache_head *head,
160 				 struct cache_detail *detail)
161 {
162 	if (test_and_clear_bit(CACHE_PENDING, &head->flags)) {
163 		cache_revisit_request(head);
164 		cache_dequeue(detail, head);
165 	}
166 }
167 
168 struct cache_head *sunrpc_cache_update(struct cache_detail *detail,
169 				       struct cache_head *new, struct cache_head *old, int hash)
170 {
171 	/* The 'old' entry is to be replaced by 'new'.
172 	 * If 'old' is not VALID, we update it directly,
173 	 * otherwise we need to replace it
174 	 */
175 	struct cache_head *tmp;
176 
177 	if (!test_bit(CACHE_VALID, &old->flags)) {
178 		spin_lock(&detail->hash_lock);
179 		if (!test_bit(CACHE_VALID, &old->flags)) {
180 			if (test_bit(CACHE_NEGATIVE, &new->flags))
181 				set_bit(CACHE_NEGATIVE, &old->flags);
182 			else
183 				detail->update(old, new);
184 			cache_fresh_locked(old, new->expiry_time, detail);
185 			spin_unlock(&detail->hash_lock);
186 			cache_fresh_unlocked(old, detail);
187 			return old;
188 		}
189 		spin_unlock(&detail->hash_lock);
190 	}
191 	/* We need to insert a new entry */
192 	tmp = detail->alloc();
193 	if (!tmp) {
194 		cache_put(old, detail);
195 		return NULL;
196 	}
197 	cache_init(tmp, detail);
198 	detail->init(tmp, old);
199 
200 	spin_lock(&detail->hash_lock);
201 	if (test_bit(CACHE_NEGATIVE, &new->flags))
202 		set_bit(CACHE_NEGATIVE, &tmp->flags);
203 	else
204 		detail->update(tmp, new);
205 	hlist_add_head(&tmp->cache_list, &detail->hash_table[hash]);
206 	detail->entries++;
207 	cache_get(tmp);
208 	cache_fresh_locked(tmp, new->expiry_time, detail);
209 	cache_fresh_locked(old, 0, detail);
210 	spin_unlock(&detail->hash_lock);
211 	cache_fresh_unlocked(tmp, detail);
212 	cache_fresh_unlocked(old, detail);
213 	cache_put(old, detail);
214 	return tmp;
215 }
216 EXPORT_SYMBOL_GPL(sunrpc_cache_update);
217 
218 static int cache_make_upcall(struct cache_detail *cd, struct cache_head *h)
219 {
220 	if (cd->cache_upcall)
221 		return cd->cache_upcall(cd, h);
222 	return sunrpc_cache_pipe_upcall(cd, h);
223 }
224 
225 static inline int cache_is_valid(struct cache_head *h)
226 {
227 	if (!test_bit(CACHE_VALID, &h->flags))
228 		return -EAGAIN;
229 	else {
230 		/* entry is valid */
231 		if (test_bit(CACHE_NEGATIVE, &h->flags))
232 			return -ENOENT;
233 		else {
234 			/*
235 			 * In combination with write barrier in
236 			 * sunrpc_cache_update, ensures that anyone
237 			 * using the cache entry after this sees the
238 			 * updated contents:
239 			 */
240 			smp_rmb();
241 			return 0;
242 		}
243 	}
244 }
245 
246 static int try_to_negate_entry(struct cache_detail *detail, struct cache_head *h)
247 {
248 	int rv;
249 
250 	spin_lock(&detail->hash_lock);
251 	rv = cache_is_valid(h);
252 	if (rv == -EAGAIN) {
253 		set_bit(CACHE_NEGATIVE, &h->flags);
254 		cache_fresh_locked(h, seconds_since_boot()+CACHE_NEW_EXPIRY,
255 				   detail);
256 		rv = -ENOENT;
257 	}
258 	spin_unlock(&detail->hash_lock);
259 	cache_fresh_unlocked(h, detail);
260 	return rv;
261 }
262 
263 /*
264  * This is the generic cache management routine for all
265  * the authentication caches.
266  * It checks the currency of a cache item and will (later)
267  * initiate an upcall to fill it if needed.
268  *
269  *
270  * Returns 0 if the cache_head can be used, or cache_puts it and returns
271  * -EAGAIN if upcall is pending and request has been queued
272  * -ETIMEDOUT if upcall failed or request could not be queue or
273  *           upcall completed but item is still invalid (implying that
274  *           the cache item has been replaced with a newer one).
275  * -ENOENT if cache entry was negative
276  */
277 int cache_check(struct cache_detail *detail,
278 		    struct cache_head *h, struct cache_req *rqstp)
279 {
280 	int rv;
281 	long refresh_age, age;
282 
283 	/* First decide return status as best we can */
284 	rv = cache_is_valid(h);
285 
286 	/* now see if we want to start an upcall */
287 	refresh_age = (h->expiry_time - h->last_refresh);
288 	age = seconds_since_boot() - h->last_refresh;
289 
290 	if (rqstp == NULL) {
291 		if (rv == -EAGAIN)
292 			rv = -ENOENT;
293 	} else if (rv == -EAGAIN ||
294 		   (h->expiry_time != 0 && age > refresh_age/2)) {
295 		dprintk("RPC:       Want update, refage=%ld, age=%ld\n",
296 				refresh_age, age);
297 		if (!test_and_set_bit(CACHE_PENDING, &h->flags)) {
298 			switch (cache_make_upcall(detail, h)) {
299 			case -EINVAL:
300 				rv = try_to_negate_entry(detail, h);
301 				break;
302 			case -EAGAIN:
303 				cache_fresh_unlocked(h, detail);
304 				break;
305 			}
306 		}
307 	}
308 
309 	if (rv == -EAGAIN) {
310 		if (!cache_defer_req(rqstp, h)) {
311 			/*
312 			 * Request was not deferred; handle it as best
313 			 * we can ourselves:
314 			 */
315 			rv = cache_is_valid(h);
316 			if (rv == -EAGAIN)
317 				rv = -ETIMEDOUT;
318 		}
319 	}
320 	if (rv)
321 		cache_put(h, detail);
322 	return rv;
323 }
324 EXPORT_SYMBOL_GPL(cache_check);
325 
326 /*
327  * caches need to be periodically cleaned.
328  * For this we maintain a list of cache_detail and
329  * a current pointer into that list and into the table
330  * for that entry.
331  *
332  * Each time cache_clean is called it finds the next non-empty entry
333  * in the current table and walks the list in that entry
334  * looking for entries that can be removed.
335  *
336  * An entry gets removed if:
337  * - The expiry is before current time
338  * - The last_refresh time is before the flush_time for that cache
339  *
340  * later we might drop old entries with non-NEVER expiry if that table
341  * is getting 'full' for some definition of 'full'
342  *
343  * The question of "how often to scan a table" is an interesting one
344  * and is answered in part by the use of the "nextcheck" field in the
345  * cache_detail.
346  * When a scan of a table begins, the nextcheck field is set to a time
347  * that is well into the future.
348  * While scanning, if an expiry time is found that is earlier than the
349  * current nextcheck time, nextcheck is set to that expiry time.
350  * If the flush_time is ever set to a time earlier than the nextcheck
351  * time, the nextcheck time is then set to that flush_time.
352  *
353  * A table is then only scanned if the current time is at least
354  * the nextcheck time.
355  *
356  */
357 
358 static LIST_HEAD(cache_list);
359 static DEFINE_SPINLOCK(cache_list_lock);
360 static struct cache_detail *current_detail;
361 static int current_index;
362 
363 static void do_cache_clean(struct work_struct *work);
364 static struct delayed_work cache_cleaner;
365 
366 void sunrpc_init_cache_detail(struct cache_detail *cd)
367 {
368 	spin_lock_init(&cd->hash_lock);
369 	INIT_LIST_HEAD(&cd->queue);
370 	spin_lock(&cache_list_lock);
371 	cd->nextcheck = 0;
372 	cd->entries = 0;
373 	atomic_set(&cd->readers, 0);
374 	cd->last_close = 0;
375 	cd->last_warn = -1;
376 	list_add(&cd->others, &cache_list);
377 	spin_unlock(&cache_list_lock);
378 
379 	/* start the cleaning process */
380 	queue_delayed_work(system_power_efficient_wq, &cache_cleaner, 0);
381 }
382 EXPORT_SYMBOL_GPL(sunrpc_init_cache_detail);
383 
384 void sunrpc_destroy_cache_detail(struct cache_detail *cd)
385 {
386 	cache_purge(cd);
387 	spin_lock(&cache_list_lock);
388 	spin_lock(&cd->hash_lock);
389 	if (current_detail == cd)
390 		current_detail = NULL;
391 	list_del_init(&cd->others);
392 	spin_unlock(&cd->hash_lock);
393 	spin_unlock(&cache_list_lock);
394 	if (list_empty(&cache_list)) {
395 		/* module must be being unloaded so its safe to kill the worker */
396 		cancel_delayed_work_sync(&cache_cleaner);
397 	}
398 }
399 EXPORT_SYMBOL_GPL(sunrpc_destroy_cache_detail);
400 
401 /* clean cache tries to find something to clean
402  * and cleans it.
403  * It returns 1 if it cleaned something,
404  *            0 if it didn't find anything this time
405  *           -1 if it fell off the end of the list.
406  */
407 static int cache_clean(void)
408 {
409 	int rv = 0;
410 	struct list_head *next;
411 
412 	spin_lock(&cache_list_lock);
413 
414 	/* find a suitable table if we don't already have one */
415 	while (current_detail == NULL ||
416 	    current_index >= current_detail->hash_size) {
417 		if (current_detail)
418 			next = current_detail->others.next;
419 		else
420 			next = cache_list.next;
421 		if (next == &cache_list) {
422 			current_detail = NULL;
423 			spin_unlock(&cache_list_lock);
424 			return -1;
425 		}
426 		current_detail = list_entry(next, struct cache_detail, others);
427 		if (current_detail->nextcheck > seconds_since_boot())
428 			current_index = current_detail->hash_size;
429 		else {
430 			current_index = 0;
431 			current_detail->nextcheck = seconds_since_boot()+30*60;
432 		}
433 	}
434 
435 	/* find a non-empty bucket in the table */
436 	while (current_detail &&
437 	       current_index < current_detail->hash_size &&
438 	       hlist_empty(&current_detail->hash_table[current_index]))
439 		current_index++;
440 
441 	/* find a cleanable entry in the bucket and clean it, or set to next bucket */
442 
443 	if (current_detail && current_index < current_detail->hash_size) {
444 		struct cache_head *ch = NULL;
445 		struct cache_detail *d;
446 		struct hlist_head *head;
447 		struct hlist_node *tmp;
448 
449 		spin_lock(&current_detail->hash_lock);
450 
451 		/* Ok, now to clean this strand */
452 
453 		head = &current_detail->hash_table[current_index];
454 		hlist_for_each_entry_safe(ch, tmp, head, cache_list) {
455 			if (current_detail->nextcheck > ch->expiry_time)
456 				current_detail->nextcheck = ch->expiry_time+1;
457 			if (!cache_is_expired(current_detail, ch))
458 				continue;
459 
460 			hlist_del_init_rcu(&ch->cache_list);
461 			current_detail->entries--;
462 			rv = 1;
463 			break;
464 		}
465 
466 		spin_unlock(&current_detail->hash_lock);
467 		d = current_detail;
468 		if (!ch)
469 			current_index ++;
470 		spin_unlock(&cache_list_lock);
471 		if (ch) {
472 			set_bit(CACHE_CLEANED, &ch->flags);
473 			cache_fresh_unlocked(ch, d);
474 			cache_put(ch, d);
475 		}
476 	} else
477 		spin_unlock(&cache_list_lock);
478 
479 	return rv;
480 }
481 
482 /*
483  * We want to regularly clean the cache, so we need to schedule some work ...
484  */
485 static void do_cache_clean(struct work_struct *work)
486 {
487 	int delay = 5;
488 	if (cache_clean() == -1)
489 		delay = round_jiffies_relative(30*HZ);
490 
491 	if (list_empty(&cache_list))
492 		delay = 0;
493 
494 	if (delay)
495 		queue_delayed_work(system_power_efficient_wq,
496 				   &cache_cleaner, delay);
497 }
498 
499 
500 /*
501  * Clean all caches promptly.  This just calls cache_clean
502  * repeatedly until we are sure that every cache has had a chance to
503  * be fully cleaned
504  */
505 void cache_flush(void)
506 {
507 	while (cache_clean() != -1)
508 		cond_resched();
509 	while (cache_clean() != -1)
510 		cond_resched();
511 }
512 EXPORT_SYMBOL_GPL(cache_flush);
513 
514 void cache_purge(struct cache_detail *detail)
515 {
516 	struct cache_head *ch = NULL;
517 	struct hlist_head *head = NULL;
518 	struct hlist_node *tmp = NULL;
519 	int i = 0;
520 
521 	spin_lock(&detail->hash_lock);
522 	if (!detail->entries) {
523 		spin_unlock(&detail->hash_lock);
524 		return;
525 	}
526 
527 	dprintk("RPC: %d entries in %s cache\n", detail->entries, detail->name);
528 	for (i = 0; i < detail->hash_size; i++) {
529 		head = &detail->hash_table[i];
530 		hlist_for_each_entry_safe(ch, tmp, head, cache_list) {
531 			hlist_del_init_rcu(&ch->cache_list);
532 			detail->entries--;
533 
534 			set_bit(CACHE_CLEANED, &ch->flags);
535 			spin_unlock(&detail->hash_lock);
536 			cache_fresh_unlocked(ch, detail);
537 			cache_put(ch, detail);
538 			spin_lock(&detail->hash_lock);
539 		}
540 	}
541 	spin_unlock(&detail->hash_lock);
542 }
543 EXPORT_SYMBOL_GPL(cache_purge);
544 
545 
546 /*
547  * Deferral and Revisiting of Requests.
548  *
549  * If a cache lookup finds a pending entry, we
550  * need to defer the request and revisit it later.
551  * All deferred requests are stored in a hash table,
552  * indexed by "struct cache_head *".
553  * As it may be wasteful to store a whole request
554  * structure, we allow the request to provide a
555  * deferred form, which must contain a
556  * 'struct cache_deferred_req'
557  * This cache_deferred_req contains a method to allow
558  * it to be revisited when cache info is available
559  */
560 
561 #define	DFR_HASHSIZE	(PAGE_SIZE/sizeof(struct list_head))
562 #define	DFR_HASH(item)	((((long)item)>>4 ^ (((long)item)>>13)) % DFR_HASHSIZE)
563 
564 #define	DFR_MAX	300	/* ??? */
565 
566 static DEFINE_SPINLOCK(cache_defer_lock);
567 static LIST_HEAD(cache_defer_list);
568 static struct hlist_head cache_defer_hash[DFR_HASHSIZE];
569 static int cache_defer_cnt;
570 
571 static void __unhash_deferred_req(struct cache_deferred_req *dreq)
572 {
573 	hlist_del_init(&dreq->hash);
574 	if (!list_empty(&dreq->recent)) {
575 		list_del_init(&dreq->recent);
576 		cache_defer_cnt--;
577 	}
578 }
579 
580 static void __hash_deferred_req(struct cache_deferred_req *dreq, struct cache_head *item)
581 {
582 	int hash = DFR_HASH(item);
583 
584 	INIT_LIST_HEAD(&dreq->recent);
585 	hlist_add_head(&dreq->hash, &cache_defer_hash[hash]);
586 }
587 
588 static void setup_deferral(struct cache_deferred_req *dreq,
589 			   struct cache_head *item,
590 			   int count_me)
591 {
592 
593 	dreq->item = item;
594 
595 	spin_lock(&cache_defer_lock);
596 
597 	__hash_deferred_req(dreq, item);
598 
599 	if (count_me) {
600 		cache_defer_cnt++;
601 		list_add(&dreq->recent, &cache_defer_list);
602 	}
603 
604 	spin_unlock(&cache_defer_lock);
605 
606 }
607 
608 struct thread_deferred_req {
609 	struct cache_deferred_req handle;
610 	struct completion completion;
611 };
612 
613 static void cache_restart_thread(struct cache_deferred_req *dreq, int too_many)
614 {
615 	struct thread_deferred_req *dr =
616 		container_of(dreq, struct thread_deferred_req, handle);
617 	complete(&dr->completion);
618 }
619 
620 static void cache_wait_req(struct cache_req *req, struct cache_head *item)
621 {
622 	struct thread_deferred_req sleeper;
623 	struct cache_deferred_req *dreq = &sleeper.handle;
624 
625 	sleeper.completion = COMPLETION_INITIALIZER_ONSTACK(sleeper.completion);
626 	dreq->revisit = cache_restart_thread;
627 
628 	setup_deferral(dreq, item, 0);
629 
630 	if (!test_bit(CACHE_PENDING, &item->flags) ||
631 	    wait_for_completion_interruptible_timeout(
632 		    &sleeper.completion, req->thread_wait) <= 0) {
633 		/* The completion wasn't completed, so we need
634 		 * to clean up
635 		 */
636 		spin_lock(&cache_defer_lock);
637 		if (!hlist_unhashed(&sleeper.handle.hash)) {
638 			__unhash_deferred_req(&sleeper.handle);
639 			spin_unlock(&cache_defer_lock);
640 		} else {
641 			/* cache_revisit_request already removed
642 			 * this from the hash table, but hasn't
643 			 * called ->revisit yet.  It will very soon
644 			 * and we need to wait for it.
645 			 */
646 			spin_unlock(&cache_defer_lock);
647 			wait_for_completion(&sleeper.completion);
648 		}
649 	}
650 }
651 
652 static void cache_limit_defers(void)
653 {
654 	/* Make sure we haven't exceed the limit of allowed deferred
655 	 * requests.
656 	 */
657 	struct cache_deferred_req *discard = NULL;
658 
659 	if (cache_defer_cnt <= DFR_MAX)
660 		return;
661 
662 	spin_lock(&cache_defer_lock);
663 
664 	/* Consider removing either the first or the last */
665 	if (cache_defer_cnt > DFR_MAX) {
666 		if (prandom_u32() & 1)
667 			discard = list_entry(cache_defer_list.next,
668 					     struct cache_deferred_req, recent);
669 		else
670 			discard = list_entry(cache_defer_list.prev,
671 					     struct cache_deferred_req, recent);
672 		__unhash_deferred_req(discard);
673 	}
674 	spin_unlock(&cache_defer_lock);
675 	if (discard)
676 		discard->revisit(discard, 1);
677 }
678 
679 /* Return true if and only if a deferred request is queued. */
680 static bool cache_defer_req(struct cache_req *req, struct cache_head *item)
681 {
682 	struct cache_deferred_req *dreq;
683 
684 	if (req->thread_wait) {
685 		cache_wait_req(req, item);
686 		if (!test_bit(CACHE_PENDING, &item->flags))
687 			return false;
688 	}
689 	dreq = req->defer(req);
690 	if (dreq == NULL)
691 		return false;
692 	setup_deferral(dreq, item, 1);
693 	if (!test_bit(CACHE_PENDING, &item->flags))
694 		/* Bit could have been cleared before we managed to
695 		 * set up the deferral, so need to revisit just in case
696 		 */
697 		cache_revisit_request(item);
698 
699 	cache_limit_defers();
700 	return true;
701 }
702 
703 static void cache_revisit_request(struct cache_head *item)
704 {
705 	struct cache_deferred_req *dreq;
706 	struct list_head pending;
707 	struct hlist_node *tmp;
708 	int hash = DFR_HASH(item);
709 
710 	INIT_LIST_HEAD(&pending);
711 	spin_lock(&cache_defer_lock);
712 
713 	hlist_for_each_entry_safe(dreq, tmp, &cache_defer_hash[hash], hash)
714 		if (dreq->item == item) {
715 			__unhash_deferred_req(dreq);
716 			list_add(&dreq->recent, &pending);
717 		}
718 
719 	spin_unlock(&cache_defer_lock);
720 
721 	while (!list_empty(&pending)) {
722 		dreq = list_entry(pending.next, struct cache_deferred_req, recent);
723 		list_del_init(&dreq->recent);
724 		dreq->revisit(dreq, 0);
725 	}
726 }
727 
728 void cache_clean_deferred(void *owner)
729 {
730 	struct cache_deferred_req *dreq, *tmp;
731 	struct list_head pending;
732 
733 
734 	INIT_LIST_HEAD(&pending);
735 	spin_lock(&cache_defer_lock);
736 
737 	list_for_each_entry_safe(dreq, tmp, &cache_defer_list, recent) {
738 		if (dreq->owner == owner) {
739 			__unhash_deferred_req(dreq);
740 			list_add(&dreq->recent, &pending);
741 		}
742 	}
743 	spin_unlock(&cache_defer_lock);
744 
745 	while (!list_empty(&pending)) {
746 		dreq = list_entry(pending.next, struct cache_deferred_req, recent);
747 		list_del_init(&dreq->recent);
748 		dreq->revisit(dreq, 1);
749 	}
750 }
751 
752 /*
753  * communicate with user-space
754  *
755  * We have a magic /proc file - /proc/net/rpc/<cachename>/channel.
756  * On read, you get a full request, or block.
757  * On write, an update request is processed.
758  * Poll works if anything to read, and always allows write.
759  *
760  * Implemented by linked list of requests.  Each open file has
761  * a ->private that also exists in this list.  New requests are added
762  * to the end and may wakeup and preceding readers.
763  * New readers are added to the head.  If, on read, an item is found with
764  * CACHE_UPCALLING clear, we free it from the list.
765  *
766  */
767 
768 static DEFINE_SPINLOCK(queue_lock);
769 static DEFINE_MUTEX(queue_io_mutex);
770 
771 struct cache_queue {
772 	struct list_head	list;
773 	int			reader;	/* if 0, then request */
774 };
775 struct cache_request {
776 	struct cache_queue	q;
777 	struct cache_head	*item;
778 	char			* buf;
779 	int			len;
780 	int			readers;
781 };
782 struct cache_reader {
783 	struct cache_queue	q;
784 	int			offset;	/* if non-0, we have a refcnt on next request */
785 };
786 
787 static int cache_request(struct cache_detail *detail,
788 			       struct cache_request *crq)
789 {
790 	char *bp = crq->buf;
791 	int len = PAGE_SIZE;
792 
793 	detail->cache_request(detail, crq->item, &bp, &len);
794 	if (len < 0)
795 		return -EAGAIN;
796 	return PAGE_SIZE - len;
797 }
798 
799 static ssize_t cache_read(struct file *filp, char __user *buf, size_t count,
800 			  loff_t *ppos, struct cache_detail *cd)
801 {
802 	struct cache_reader *rp = filp->private_data;
803 	struct cache_request *rq;
804 	struct inode *inode = file_inode(filp);
805 	int err;
806 
807 	if (count == 0)
808 		return 0;
809 
810 	inode_lock(inode); /* protect against multiple concurrent
811 			      * readers on this file */
812  again:
813 	spin_lock(&queue_lock);
814 	/* need to find next request */
815 	while (rp->q.list.next != &cd->queue &&
816 	       list_entry(rp->q.list.next, struct cache_queue, list)
817 	       ->reader) {
818 		struct list_head *next = rp->q.list.next;
819 		list_move(&rp->q.list, next);
820 	}
821 	if (rp->q.list.next == &cd->queue) {
822 		spin_unlock(&queue_lock);
823 		inode_unlock(inode);
824 		WARN_ON_ONCE(rp->offset);
825 		return 0;
826 	}
827 	rq = container_of(rp->q.list.next, struct cache_request, q.list);
828 	WARN_ON_ONCE(rq->q.reader);
829 	if (rp->offset == 0)
830 		rq->readers++;
831 	spin_unlock(&queue_lock);
832 
833 	if (rq->len == 0) {
834 		err = cache_request(cd, rq);
835 		if (err < 0)
836 			goto out;
837 		rq->len = err;
838 	}
839 
840 	if (rp->offset == 0 && !test_bit(CACHE_PENDING, &rq->item->flags)) {
841 		err = -EAGAIN;
842 		spin_lock(&queue_lock);
843 		list_move(&rp->q.list, &rq->q.list);
844 		spin_unlock(&queue_lock);
845 	} else {
846 		if (rp->offset + count > rq->len)
847 			count = rq->len - rp->offset;
848 		err = -EFAULT;
849 		if (copy_to_user(buf, rq->buf + rp->offset, count))
850 			goto out;
851 		rp->offset += count;
852 		if (rp->offset >= rq->len) {
853 			rp->offset = 0;
854 			spin_lock(&queue_lock);
855 			list_move(&rp->q.list, &rq->q.list);
856 			spin_unlock(&queue_lock);
857 		}
858 		err = 0;
859 	}
860  out:
861 	if (rp->offset == 0) {
862 		/* need to release rq */
863 		spin_lock(&queue_lock);
864 		rq->readers--;
865 		if (rq->readers == 0 &&
866 		    !test_bit(CACHE_PENDING, &rq->item->flags)) {
867 			list_del(&rq->q.list);
868 			spin_unlock(&queue_lock);
869 			cache_put(rq->item, cd);
870 			kfree(rq->buf);
871 			kfree(rq);
872 		} else
873 			spin_unlock(&queue_lock);
874 	}
875 	if (err == -EAGAIN)
876 		goto again;
877 	inode_unlock(inode);
878 	return err ? err :  count;
879 }
880 
881 static ssize_t cache_do_downcall(char *kaddr, const char __user *buf,
882 				 size_t count, struct cache_detail *cd)
883 {
884 	ssize_t ret;
885 
886 	if (count == 0)
887 		return -EINVAL;
888 	if (copy_from_user(kaddr, buf, count))
889 		return -EFAULT;
890 	kaddr[count] = '\0';
891 	ret = cd->cache_parse(cd, kaddr, count);
892 	if (!ret)
893 		ret = count;
894 	return ret;
895 }
896 
897 static ssize_t cache_slow_downcall(const char __user *buf,
898 				   size_t count, struct cache_detail *cd)
899 {
900 	static char write_buf[8192]; /* protected by queue_io_mutex */
901 	ssize_t ret = -EINVAL;
902 
903 	if (count >= sizeof(write_buf))
904 		goto out;
905 	mutex_lock(&queue_io_mutex);
906 	ret = cache_do_downcall(write_buf, buf, count, cd);
907 	mutex_unlock(&queue_io_mutex);
908 out:
909 	return ret;
910 }
911 
912 static ssize_t cache_downcall(struct address_space *mapping,
913 			      const char __user *buf,
914 			      size_t count, struct cache_detail *cd)
915 {
916 	struct page *page;
917 	char *kaddr;
918 	ssize_t ret = -ENOMEM;
919 
920 	if (count >= PAGE_SIZE)
921 		goto out_slow;
922 
923 	page = find_or_create_page(mapping, 0, GFP_KERNEL);
924 	if (!page)
925 		goto out_slow;
926 
927 	kaddr = kmap(page);
928 	ret = cache_do_downcall(kaddr, buf, count, cd);
929 	kunmap(page);
930 	unlock_page(page);
931 	put_page(page);
932 	return ret;
933 out_slow:
934 	return cache_slow_downcall(buf, count, cd);
935 }
936 
937 static ssize_t cache_write(struct file *filp, const char __user *buf,
938 			   size_t count, loff_t *ppos,
939 			   struct cache_detail *cd)
940 {
941 	struct address_space *mapping = filp->f_mapping;
942 	struct inode *inode = file_inode(filp);
943 	ssize_t ret = -EINVAL;
944 
945 	if (!cd->cache_parse)
946 		goto out;
947 
948 	inode_lock(inode);
949 	ret = cache_downcall(mapping, buf, count, cd);
950 	inode_unlock(inode);
951 out:
952 	return ret;
953 }
954 
955 static DECLARE_WAIT_QUEUE_HEAD(queue_wait);
956 
957 static __poll_t cache_poll(struct file *filp, poll_table *wait,
958 			       struct cache_detail *cd)
959 {
960 	__poll_t mask;
961 	struct cache_reader *rp = filp->private_data;
962 	struct cache_queue *cq;
963 
964 	poll_wait(filp, &queue_wait, wait);
965 
966 	/* alway allow write */
967 	mask = EPOLLOUT | EPOLLWRNORM;
968 
969 	if (!rp)
970 		return mask;
971 
972 	spin_lock(&queue_lock);
973 
974 	for (cq= &rp->q; &cq->list != &cd->queue;
975 	     cq = list_entry(cq->list.next, struct cache_queue, list))
976 		if (!cq->reader) {
977 			mask |= EPOLLIN | EPOLLRDNORM;
978 			break;
979 		}
980 	spin_unlock(&queue_lock);
981 	return mask;
982 }
983 
984 static int cache_ioctl(struct inode *ino, struct file *filp,
985 		       unsigned int cmd, unsigned long arg,
986 		       struct cache_detail *cd)
987 {
988 	int len = 0;
989 	struct cache_reader *rp = filp->private_data;
990 	struct cache_queue *cq;
991 
992 	if (cmd != FIONREAD || !rp)
993 		return -EINVAL;
994 
995 	spin_lock(&queue_lock);
996 
997 	/* only find the length remaining in current request,
998 	 * or the length of the next request
999 	 */
1000 	for (cq= &rp->q; &cq->list != &cd->queue;
1001 	     cq = list_entry(cq->list.next, struct cache_queue, list))
1002 		if (!cq->reader) {
1003 			struct cache_request *cr =
1004 				container_of(cq, struct cache_request, q);
1005 			len = cr->len - rp->offset;
1006 			break;
1007 		}
1008 	spin_unlock(&queue_lock);
1009 
1010 	return put_user(len, (int __user *)arg);
1011 }
1012 
1013 static int cache_open(struct inode *inode, struct file *filp,
1014 		      struct cache_detail *cd)
1015 {
1016 	struct cache_reader *rp = NULL;
1017 
1018 	if (!cd || !try_module_get(cd->owner))
1019 		return -EACCES;
1020 	nonseekable_open(inode, filp);
1021 	if (filp->f_mode & FMODE_READ) {
1022 		rp = kmalloc(sizeof(*rp), GFP_KERNEL);
1023 		if (!rp) {
1024 			module_put(cd->owner);
1025 			return -ENOMEM;
1026 		}
1027 		rp->offset = 0;
1028 		rp->q.reader = 1;
1029 		atomic_inc(&cd->readers);
1030 		spin_lock(&queue_lock);
1031 		list_add(&rp->q.list, &cd->queue);
1032 		spin_unlock(&queue_lock);
1033 	}
1034 	filp->private_data = rp;
1035 	return 0;
1036 }
1037 
1038 static int cache_release(struct inode *inode, struct file *filp,
1039 			 struct cache_detail *cd)
1040 {
1041 	struct cache_reader *rp = filp->private_data;
1042 
1043 	if (rp) {
1044 		spin_lock(&queue_lock);
1045 		if (rp->offset) {
1046 			struct cache_queue *cq;
1047 			for (cq= &rp->q; &cq->list != &cd->queue;
1048 			     cq = list_entry(cq->list.next, struct cache_queue, list))
1049 				if (!cq->reader) {
1050 					container_of(cq, struct cache_request, q)
1051 						->readers--;
1052 					break;
1053 				}
1054 			rp->offset = 0;
1055 		}
1056 		list_del(&rp->q.list);
1057 		spin_unlock(&queue_lock);
1058 
1059 		filp->private_data = NULL;
1060 		kfree(rp);
1061 
1062 		cd->last_close = seconds_since_boot();
1063 		atomic_dec(&cd->readers);
1064 	}
1065 	module_put(cd->owner);
1066 	return 0;
1067 }
1068 
1069 
1070 
1071 static void cache_dequeue(struct cache_detail *detail, struct cache_head *ch)
1072 {
1073 	struct cache_queue *cq, *tmp;
1074 	struct cache_request *cr;
1075 	struct list_head dequeued;
1076 
1077 	INIT_LIST_HEAD(&dequeued);
1078 	spin_lock(&queue_lock);
1079 	list_for_each_entry_safe(cq, tmp, &detail->queue, list)
1080 		if (!cq->reader) {
1081 			cr = container_of(cq, struct cache_request, q);
1082 			if (cr->item != ch)
1083 				continue;
1084 			if (test_bit(CACHE_PENDING, &ch->flags))
1085 				/* Lost a race and it is pending again */
1086 				break;
1087 			if (cr->readers != 0)
1088 				continue;
1089 			list_move(&cr->q.list, &dequeued);
1090 		}
1091 	spin_unlock(&queue_lock);
1092 	while (!list_empty(&dequeued)) {
1093 		cr = list_entry(dequeued.next, struct cache_request, q.list);
1094 		list_del(&cr->q.list);
1095 		cache_put(cr->item, detail);
1096 		kfree(cr->buf);
1097 		kfree(cr);
1098 	}
1099 }
1100 
1101 /*
1102  * Support routines for text-based upcalls.
1103  * Fields are separated by spaces.
1104  * Fields are either mangled to quote space tab newline slosh with slosh
1105  * or a hexified with a leading \x
1106  * Record is terminated with newline.
1107  *
1108  */
1109 
1110 void qword_add(char **bpp, int *lp, char *str)
1111 {
1112 	char *bp = *bpp;
1113 	int len = *lp;
1114 	int ret;
1115 
1116 	if (len < 0) return;
1117 
1118 	ret = string_escape_str(str, bp, len, ESCAPE_OCTAL, "\\ \n\t");
1119 	if (ret >= len) {
1120 		bp += len;
1121 		len = -1;
1122 	} else {
1123 		bp += ret;
1124 		len -= ret;
1125 		*bp++ = ' ';
1126 		len--;
1127 	}
1128 	*bpp = bp;
1129 	*lp = len;
1130 }
1131 EXPORT_SYMBOL_GPL(qword_add);
1132 
1133 void qword_addhex(char **bpp, int *lp, char *buf, int blen)
1134 {
1135 	char *bp = *bpp;
1136 	int len = *lp;
1137 
1138 	if (len < 0) return;
1139 
1140 	if (len > 2) {
1141 		*bp++ = '\\';
1142 		*bp++ = 'x';
1143 		len -= 2;
1144 		while (blen && len >= 2) {
1145 			bp = hex_byte_pack(bp, *buf++);
1146 			len -= 2;
1147 			blen--;
1148 		}
1149 	}
1150 	if (blen || len<1) len = -1;
1151 	else {
1152 		*bp++ = ' ';
1153 		len--;
1154 	}
1155 	*bpp = bp;
1156 	*lp = len;
1157 }
1158 EXPORT_SYMBOL_GPL(qword_addhex);
1159 
1160 static void warn_no_listener(struct cache_detail *detail)
1161 {
1162 	if (detail->last_warn != detail->last_close) {
1163 		detail->last_warn = detail->last_close;
1164 		if (detail->warn_no_listener)
1165 			detail->warn_no_listener(detail, detail->last_close != 0);
1166 	}
1167 }
1168 
1169 static bool cache_listeners_exist(struct cache_detail *detail)
1170 {
1171 	if (atomic_read(&detail->readers))
1172 		return true;
1173 	if (detail->last_close == 0)
1174 		/* This cache was never opened */
1175 		return false;
1176 	if (detail->last_close < seconds_since_boot() - 30)
1177 		/*
1178 		 * We allow for the possibility that someone might
1179 		 * restart a userspace daemon without restarting the
1180 		 * server; but after 30 seconds, we give up.
1181 		 */
1182 		 return false;
1183 	return true;
1184 }
1185 
1186 /*
1187  * register an upcall request to user-space and queue it up for read() by the
1188  * upcall daemon.
1189  *
1190  * Each request is at most one page long.
1191  */
1192 int sunrpc_cache_pipe_upcall(struct cache_detail *detail, struct cache_head *h)
1193 {
1194 
1195 	char *buf;
1196 	struct cache_request *crq;
1197 	int ret = 0;
1198 
1199 	if (!detail->cache_request)
1200 		return -EINVAL;
1201 
1202 	if (!cache_listeners_exist(detail)) {
1203 		warn_no_listener(detail);
1204 		return -EINVAL;
1205 	}
1206 	if (test_bit(CACHE_CLEANED, &h->flags))
1207 		/* Too late to make an upcall */
1208 		return -EAGAIN;
1209 
1210 	buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
1211 	if (!buf)
1212 		return -EAGAIN;
1213 
1214 	crq = kmalloc(sizeof (*crq), GFP_KERNEL);
1215 	if (!crq) {
1216 		kfree(buf);
1217 		return -EAGAIN;
1218 	}
1219 
1220 	crq->q.reader = 0;
1221 	crq->buf = buf;
1222 	crq->len = 0;
1223 	crq->readers = 0;
1224 	spin_lock(&queue_lock);
1225 	if (test_bit(CACHE_PENDING, &h->flags)) {
1226 		crq->item = cache_get(h);
1227 		list_add_tail(&crq->q.list, &detail->queue);
1228 	} else
1229 		/* Lost a race, no longer PENDING, so don't enqueue */
1230 		ret = -EAGAIN;
1231 	spin_unlock(&queue_lock);
1232 	wake_up(&queue_wait);
1233 	if (ret == -EAGAIN) {
1234 		kfree(buf);
1235 		kfree(crq);
1236 	}
1237 	return ret;
1238 }
1239 EXPORT_SYMBOL_GPL(sunrpc_cache_pipe_upcall);
1240 
1241 /*
1242  * parse a message from user-space and pass it
1243  * to an appropriate cache
1244  * Messages are, like requests, separated into fields by
1245  * spaces and dequotes as \xHEXSTRING or embedded \nnn octal
1246  *
1247  * Message is
1248  *   reply cachename expiry key ... content....
1249  *
1250  * key and content are both parsed by cache
1251  */
1252 
1253 int qword_get(char **bpp, char *dest, int bufsize)
1254 {
1255 	/* return bytes copied, or -1 on error */
1256 	char *bp = *bpp;
1257 	int len = 0;
1258 
1259 	while (*bp == ' ') bp++;
1260 
1261 	if (bp[0] == '\\' && bp[1] == 'x') {
1262 		/* HEX STRING */
1263 		bp += 2;
1264 		while (len < bufsize - 1) {
1265 			int h, l;
1266 
1267 			h = hex_to_bin(bp[0]);
1268 			if (h < 0)
1269 				break;
1270 
1271 			l = hex_to_bin(bp[1]);
1272 			if (l < 0)
1273 				break;
1274 
1275 			*dest++ = (h << 4) | l;
1276 			bp += 2;
1277 			len++;
1278 		}
1279 	} else {
1280 		/* text with \nnn octal quoting */
1281 		while (*bp != ' ' && *bp != '\n' && *bp && len < bufsize-1) {
1282 			if (*bp == '\\' &&
1283 			    isodigit(bp[1]) && (bp[1] <= '3') &&
1284 			    isodigit(bp[2]) &&
1285 			    isodigit(bp[3])) {
1286 				int byte = (*++bp -'0');
1287 				bp++;
1288 				byte = (byte << 3) | (*bp++ - '0');
1289 				byte = (byte << 3) | (*bp++ - '0');
1290 				*dest++ = byte;
1291 				len++;
1292 			} else {
1293 				*dest++ = *bp++;
1294 				len++;
1295 			}
1296 		}
1297 	}
1298 
1299 	if (*bp != ' ' && *bp != '\n' && *bp != '\0')
1300 		return -1;
1301 	while (*bp == ' ') bp++;
1302 	*bpp = bp;
1303 	*dest = '\0';
1304 	return len;
1305 }
1306 EXPORT_SYMBOL_GPL(qword_get);
1307 
1308 
1309 /*
1310  * support /proc/net/rpc/$CACHENAME/content
1311  * as a seqfile.
1312  * We call ->cache_show passing NULL for the item to
1313  * get a header, then pass each real item in the cache
1314  */
1315 
1316 static void *__cache_seq_start(struct seq_file *m, loff_t *pos)
1317 {
1318 	loff_t n = *pos;
1319 	unsigned int hash, entry;
1320 	struct cache_head *ch;
1321 	struct cache_detail *cd = m->private;
1322 
1323 	if (!n--)
1324 		return SEQ_START_TOKEN;
1325 	hash = n >> 32;
1326 	entry = n & ((1LL<<32) - 1);
1327 
1328 	hlist_for_each_entry_rcu(ch, &cd->hash_table[hash], cache_list)
1329 		if (!entry--)
1330 			return ch;
1331 	n &= ~((1LL<<32) - 1);
1332 	do {
1333 		hash++;
1334 		n += 1LL<<32;
1335 	} while(hash < cd->hash_size &&
1336 		hlist_empty(&cd->hash_table[hash]));
1337 	if (hash >= cd->hash_size)
1338 		return NULL;
1339 	*pos = n+1;
1340 	return hlist_entry_safe(rcu_dereference_raw(
1341 				hlist_first_rcu(&cd->hash_table[hash])),
1342 				struct cache_head, cache_list);
1343 }
1344 
1345 static void *cache_seq_next(struct seq_file *m, void *p, loff_t *pos)
1346 {
1347 	struct cache_head *ch = p;
1348 	int hash = (*pos >> 32);
1349 	struct cache_detail *cd = m->private;
1350 
1351 	if (p == SEQ_START_TOKEN)
1352 		hash = 0;
1353 	else if (ch->cache_list.next == NULL) {
1354 		hash++;
1355 		*pos += 1LL<<32;
1356 	} else {
1357 		++*pos;
1358 		return hlist_entry_safe(rcu_dereference_raw(
1359 					hlist_next_rcu(&ch->cache_list)),
1360 					struct cache_head, cache_list);
1361 	}
1362 	*pos &= ~((1LL<<32) - 1);
1363 	while (hash < cd->hash_size &&
1364 	       hlist_empty(&cd->hash_table[hash])) {
1365 		hash++;
1366 		*pos += 1LL<<32;
1367 	}
1368 	if (hash >= cd->hash_size)
1369 		return NULL;
1370 	++*pos;
1371 	return hlist_entry_safe(rcu_dereference_raw(
1372 				hlist_first_rcu(&cd->hash_table[hash])),
1373 				struct cache_head, cache_list);
1374 }
1375 EXPORT_SYMBOL_GPL(cache_seq_next);
1376 
1377 void *cache_seq_start_rcu(struct seq_file *m, loff_t *pos)
1378 	__acquires(RCU)
1379 {
1380 	rcu_read_lock();
1381 	return __cache_seq_start(m, pos);
1382 }
1383 EXPORT_SYMBOL_GPL(cache_seq_start_rcu);
1384 
1385 void *cache_seq_next_rcu(struct seq_file *file, void *p, loff_t *pos)
1386 {
1387 	return cache_seq_next(file, p, pos);
1388 }
1389 EXPORT_SYMBOL_GPL(cache_seq_next_rcu);
1390 
1391 void cache_seq_stop_rcu(struct seq_file *m, void *p)
1392 	__releases(RCU)
1393 {
1394 	rcu_read_unlock();
1395 }
1396 EXPORT_SYMBOL_GPL(cache_seq_stop_rcu);
1397 
1398 static int c_show(struct seq_file *m, void *p)
1399 {
1400 	struct cache_head *cp = p;
1401 	struct cache_detail *cd = m->private;
1402 
1403 	if (p == SEQ_START_TOKEN)
1404 		return cd->cache_show(m, cd, NULL);
1405 
1406 	ifdebug(CACHE)
1407 		seq_printf(m, "# expiry=%ld refcnt=%d flags=%lx\n",
1408 			   convert_to_wallclock(cp->expiry_time),
1409 			   kref_read(&cp->ref), cp->flags);
1410 	cache_get(cp);
1411 	if (cache_check(cd, cp, NULL))
1412 		/* cache_check does a cache_put on failure */
1413 		seq_printf(m, "# ");
1414 	else {
1415 		if (cache_is_expired(cd, cp))
1416 			seq_printf(m, "# ");
1417 		cache_put(cp, cd);
1418 	}
1419 
1420 	return cd->cache_show(m, cd, cp);
1421 }
1422 
1423 static const struct seq_operations cache_content_op = {
1424 	.start	= cache_seq_start_rcu,
1425 	.next	= cache_seq_next_rcu,
1426 	.stop	= cache_seq_stop_rcu,
1427 	.show	= c_show,
1428 };
1429 
1430 static int content_open(struct inode *inode, struct file *file,
1431 			struct cache_detail *cd)
1432 {
1433 	struct seq_file *seq;
1434 	int err;
1435 
1436 	if (!cd || !try_module_get(cd->owner))
1437 		return -EACCES;
1438 
1439 	err = seq_open(file, &cache_content_op);
1440 	if (err) {
1441 		module_put(cd->owner);
1442 		return err;
1443 	}
1444 
1445 	seq = file->private_data;
1446 	seq->private = cd;
1447 	return 0;
1448 }
1449 
1450 static int content_release(struct inode *inode, struct file *file,
1451 		struct cache_detail *cd)
1452 {
1453 	int ret = seq_release(inode, file);
1454 	module_put(cd->owner);
1455 	return ret;
1456 }
1457 
1458 static int open_flush(struct inode *inode, struct file *file,
1459 			struct cache_detail *cd)
1460 {
1461 	if (!cd || !try_module_get(cd->owner))
1462 		return -EACCES;
1463 	return nonseekable_open(inode, file);
1464 }
1465 
1466 static int release_flush(struct inode *inode, struct file *file,
1467 			struct cache_detail *cd)
1468 {
1469 	module_put(cd->owner);
1470 	return 0;
1471 }
1472 
1473 static ssize_t read_flush(struct file *file, char __user *buf,
1474 			  size_t count, loff_t *ppos,
1475 			  struct cache_detail *cd)
1476 {
1477 	char tbuf[22];
1478 	size_t len;
1479 
1480 	len = snprintf(tbuf, sizeof(tbuf), "%lu\n",
1481 			convert_to_wallclock(cd->flush_time));
1482 	return simple_read_from_buffer(buf, count, ppos, tbuf, len);
1483 }
1484 
1485 static ssize_t write_flush(struct file *file, const char __user *buf,
1486 			   size_t count, loff_t *ppos,
1487 			   struct cache_detail *cd)
1488 {
1489 	char tbuf[20];
1490 	char *ep;
1491 	time_t now;
1492 
1493 	if (*ppos || count > sizeof(tbuf)-1)
1494 		return -EINVAL;
1495 	if (copy_from_user(tbuf, buf, count))
1496 		return -EFAULT;
1497 	tbuf[count] = 0;
1498 	simple_strtoul(tbuf, &ep, 0);
1499 	if (*ep && *ep != '\n')
1500 		return -EINVAL;
1501 	/* Note that while we check that 'buf' holds a valid number,
1502 	 * we always ignore the value and just flush everything.
1503 	 * Making use of the number leads to races.
1504 	 */
1505 
1506 	now = seconds_since_boot();
1507 	/* Always flush everything, so behave like cache_purge()
1508 	 * Do this by advancing flush_time to the current time,
1509 	 * or by one second if it has already reached the current time.
1510 	 * Newly added cache entries will always have ->last_refresh greater
1511 	 * that ->flush_time, so they don't get flushed prematurely.
1512 	 */
1513 
1514 	if (cd->flush_time >= now)
1515 		now = cd->flush_time + 1;
1516 
1517 	cd->flush_time = now;
1518 	cd->nextcheck = now;
1519 	cache_flush();
1520 
1521 	*ppos += count;
1522 	return count;
1523 }
1524 
1525 static ssize_t cache_read_procfs(struct file *filp, char __user *buf,
1526 				 size_t count, loff_t *ppos)
1527 {
1528 	struct cache_detail *cd = PDE_DATA(file_inode(filp));
1529 
1530 	return cache_read(filp, buf, count, ppos, cd);
1531 }
1532 
1533 static ssize_t cache_write_procfs(struct file *filp, const char __user *buf,
1534 				  size_t count, loff_t *ppos)
1535 {
1536 	struct cache_detail *cd = PDE_DATA(file_inode(filp));
1537 
1538 	return cache_write(filp, buf, count, ppos, cd);
1539 }
1540 
1541 static __poll_t cache_poll_procfs(struct file *filp, poll_table *wait)
1542 {
1543 	struct cache_detail *cd = PDE_DATA(file_inode(filp));
1544 
1545 	return cache_poll(filp, wait, cd);
1546 }
1547 
1548 static long cache_ioctl_procfs(struct file *filp,
1549 			       unsigned int cmd, unsigned long arg)
1550 {
1551 	struct inode *inode = file_inode(filp);
1552 	struct cache_detail *cd = PDE_DATA(inode);
1553 
1554 	return cache_ioctl(inode, filp, cmd, arg, cd);
1555 }
1556 
1557 static int cache_open_procfs(struct inode *inode, struct file *filp)
1558 {
1559 	struct cache_detail *cd = PDE_DATA(inode);
1560 
1561 	return cache_open(inode, filp, cd);
1562 }
1563 
1564 static int cache_release_procfs(struct inode *inode, struct file *filp)
1565 {
1566 	struct cache_detail *cd = PDE_DATA(inode);
1567 
1568 	return cache_release(inode, filp, cd);
1569 }
1570 
1571 static const struct file_operations cache_file_operations_procfs = {
1572 	.owner		= THIS_MODULE,
1573 	.llseek		= no_llseek,
1574 	.read		= cache_read_procfs,
1575 	.write		= cache_write_procfs,
1576 	.poll		= cache_poll_procfs,
1577 	.unlocked_ioctl	= cache_ioctl_procfs, /* for FIONREAD */
1578 	.open		= cache_open_procfs,
1579 	.release	= cache_release_procfs,
1580 };
1581 
1582 static int content_open_procfs(struct inode *inode, struct file *filp)
1583 {
1584 	struct cache_detail *cd = PDE_DATA(inode);
1585 
1586 	return content_open(inode, filp, cd);
1587 }
1588 
1589 static int content_release_procfs(struct inode *inode, struct file *filp)
1590 {
1591 	struct cache_detail *cd = PDE_DATA(inode);
1592 
1593 	return content_release(inode, filp, cd);
1594 }
1595 
1596 static const struct file_operations content_file_operations_procfs = {
1597 	.open		= content_open_procfs,
1598 	.read		= seq_read,
1599 	.llseek		= seq_lseek,
1600 	.release	= content_release_procfs,
1601 };
1602 
1603 static int open_flush_procfs(struct inode *inode, struct file *filp)
1604 {
1605 	struct cache_detail *cd = PDE_DATA(inode);
1606 
1607 	return open_flush(inode, filp, cd);
1608 }
1609 
1610 static int release_flush_procfs(struct inode *inode, struct file *filp)
1611 {
1612 	struct cache_detail *cd = PDE_DATA(inode);
1613 
1614 	return release_flush(inode, filp, cd);
1615 }
1616 
1617 static ssize_t read_flush_procfs(struct file *filp, char __user *buf,
1618 			    size_t count, loff_t *ppos)
1619 {
1620 	struct cache_detail *cd = PDE_DATA(file_inode(filp));
1621 
1622 	return read_flush(filp, buf, count, ppos, cd);
1623 }
1624 
1625 static ssize_t write_flush_procfs(struct file *filp,
1626 				  const char __user *buf,
1627 				  size_t count, loff_t *ppos)
1628 {
1629 	struct cache_detail *cd = PDE_DATA(file_inode(filp));
1630 
1631 	return write_flush(filp, buf, count, ppos, cd);
1632 }
1633 
1634 static const struct file_operations cache_flush_operations_procfs = {
1635 	.open		= open_flush_procfs,
1636 	.read		= read_flush_procfs,
1637 	.write		= write_flush_procfs,
1638 	.release	= release_flush_procfs,
1639 	.llseek		= no_llseek,
1640 };
1641 
1642 static void remove_cache_proc_entries(struct cache_detail *cd)
1643 {
1644 	if (cd->procfs) {
1645 		proc_remove(cd->procfs);
1646 		cd->procfs = NULL;
1647 	}
1648 }
1649 
1650 #ifdef CONFIG_PROC_FS
1651 static int create_cache_proc_entries(struct cache_detail *cd, struct net *net)
1652 {
1653 	struct proc_dir_entry *p;
1654 	struct sunrpc_net *sn;
1655 
1656 	sn = net_generic(net, sunrpc_net_id);
1657 	cd->procfs = proc_mkdir(cd->name, sn->proc_net_rpc);
1658 	if (cd->procfs == NULL)
1659 		goto out_nomem;
1660 
1661 	p = proc_create_data("flush", S_IFREG | 0600,
1662 			     cd->procfs, &cache_flush_operations_procfs, cd);
1663 	if (p == NULL)
1664 		goto out_nomem;
1665 
1666 	if (cd->cache_request || cd->cache_parse) {
1667 		p = proc_create_data("channel", S_IFREG | 0600, cd->procfs,
1668 				     &cache_file_operations_procfs, cd);
1669 		if (p == NULL)
1670 			goto out_nomem;
1671 	}
1672 	if (cd->cache_show) {
1673 		p = proc_create_data("content", S_IFREG | 0400, cd->procfs,
1674 				     &content_file_operations_procfs, cd);
1675 		if (p == NULL)
1676 			goto out_nomem;
1677 	}
1678 	return 0;
1679 out_nomem:
1680 	remove_cache_proc_entries(cd);
1681 	return -ENOMEM;
1682 }
1683 #else /* CONFIG_PROC_FS */
1684 static int create_cache_proc_entries(struct cache_detail *cd, struct net *net)
1685 {
1686 	return 0;
1687 }
1688 #endif
1689 
1690 void __init cache_initialize(void)
1691 {
1692 	INIT_DEFERRABLE_WORK(&cache_cleaner, do_cache_clean);
1693 }
1694 
1695 int cache_register_net(struct cache_detail *cd, struct net *net)
1696 {
1697 	int ret;
1698 
1699 	sunrpc_init_cache_detail(cd);
1700 	ret = create_cache_proc_entries(cd, net);
1701 	if (ret)
1702 		sunrpc_destroy_cache_detail(cd);
1703 	return ret;
1704 }
1705 EXPORT_SYMBOL_GPL(cache_register_net);
1706 
1707 void cache_unregister_net(struct cache_detail *cd, struct net *net)
1708 {
1709 	remove_cache_proc_entries(cd);
1710 	sunrpc_destroy_cache_detail(cd);
1711 }
1712 EXPORT_SYMBOL_GPL(cache_unregister_net);
1713 
1714 struct cache_detail *cache_create_net(const struct cache_detail *tmpl, struct net *net)
1715 {
1716 	struct cache_detail *cd;
1717 	int i;
1718 
1719 	cd = kmemdup(tmpl, sizeof(struct cache_detail), GFP_KERNEL);
1720 	if (cd == NULL)
1721 		return ERR_PTR(-ENOMEM);
1722 
1723 	cd->hash_table = kcalloc(cd->hash_size, sizeof(struct hlist_head),
1724 				 GFP_KERNEL);
1725 	if (cd->hash_table == NULL) {
1726 		kfree(cd);
1727 		return ERR_PTR(-ENOMEM);
1728 	}
1729 
1730 	for (i = 0; i < cd->hash_size; i++)
1731 		INIT_HLIST_HEAD(&cd->hash_table[i]);
1732 	cd->net = net;
1733 	return cd;
1734 }
1735 EXPORT_SYMBOL_GPL(cache_create_net);
1736 
1737 void cache_destroy_net(struct cache_detail *cd, struct net *net)
1738 {
1739 	kfree(cd->hash_table);
1740 	kfree(cd);
1741 }
1742 EXPORT_SYMBOL_GPL(cache_destroy_net);
1743 
1744 static ssize_t cache_read_pipefs(struct file *filp, char __user *buf,
1745 				 size_t count, loff_t *ppos)
1746 {
1747 	struct cache_detail *cd = RPC_I(file_inode(filp))->private;
1748 
1749 	return cache_read(filp, buf, count, ppos, cd);
1750 }
1751 
1752 static ssize_t cache_write_pipefs(struct file *filp, const char __user *buf,
1753 				  size_t count, loff_t *ppos)
1754 {
1755 	struct cache_detail *cd = RPC_I(file_inode(filp))->private;
1756 
1757 	return cache_write(filp, buf, count, ppos, cd);
1758 }
1759 
1760 static __poll_t cache_poll_pipefs(struct file *filp, poll_table *wait)
1761 {
1762 	struct cache_detail *cd = RPC_I(file_inode(filp))->private;
1763 
1764 	return cache_poll(filp, wait, cd);
1765 }
1766 
1767 static long cache_ioctl_pipefs(struct file *filp,
1768 			      unsigned int cmd, unsigned long arg)
1769 {
1770 	struct inode *inode = file_inode(filp);
1771 	struct cache_detail *cd = RPC_I(inode)->private;
1772 
1773 	return cache_ioctl(inode, filp, cmd, arg, cd);
1774 }
1775 
1776 static int cache_open_pipefs(struct inode *inode, struct file *filp)
1777 {
1778 	struct cache_detail *cd = RPC_I(inode)->private;
1779 
1780 	return cache_open(inode, filp, cd);
1781 }
1782 
1783 static int cache_release_pipefs(struct inode *inode, struct file *filp)
1784 {
1785 	struct cache_detail *cd = RPC_I(inode)->private;
1786 
1787 	return cache_release(inode, filp, cd);
1788 }
1789 
1790 const struct file_operations cache_file_operations_pipefs = {
1791 	.owner		= THIS_MODULE,
1792 	.llseek		= no_llseek,
1793 	.read		= cache_read_pipefs,
1794 	.write		= cache_write_pipefs,
1795 	.poll		= cache_poll_pipefs,
1796 	.unlocked_ioctl	= cache_ioctl_pipefs, /* for FIONREAD */
1797 	.open		= cache_open_pipefs,
1798 	.release	= cache_release_pipefs,
1799 };
1800 
1801 static int content_open_pipefs(struct inode *inode, struct file *filp)
1802 {
1803 	struct cache_detail *cd = RPC_I(inode)->private;
1804 
1805 	return content_open(inode, filp, cd);
1806 }
1807 
1808 static int content_release_pipefs(struct inode *inode, struct file *filp)
1809 {
1810 	struct cache_detail *cd = RPC_I(inode)->private;
1811 
1812 	return content_release(inode, filp, cd);
1813 }
1814 
1815 const struct file_operations content_file_operations_pipefs = {
1816 	.open		= content_open_pipefs,
1817 	.read		= seq_read,
1818 	.llseek		= seq_lseek,
1819 	.release	= content_release_pipefs,
1820 };
1821 
1822 static int open_flush_pipefs(struct inode *inode, struct file *filp)
1823 {
1824 	struct cache_detail *cd = RPC_I(inode)->private;
1825 
1826 	return open_flush(inode, filp, cd);
1827 }
1828 
1829 static int release_flush_pipefs(struct inode *inode, struct file *filp)
1830 {
1831 	struct cache_detail *cd = RPC_I(inode)->private;
1832 
1833 	return release_flush(inode, filp, cd);
1834 }
1835 
1836 static ssize_t read_flush_pipefs(struct file *filp, char __user *buf,
1837 			    size_t count, loff_t *ppos)
1838 {
1839 	struct cache_detail *cd = RPC_I(file_inode(filp))->private;
1840 
1841 	return read_flush(filp, buf, count, ppos, cd);
1842 }
1843 
1844 static ssize_t write_flush_pipefs(struct file *filp,
1845 				  const char __user *buf,
1846 				  size_t count, loff_t *ppos)
1847 {
1848 	struct cache_detail *cd = RPC_I(file_inode(filp))->private;
1849 
1850 	return write_flush(filp, buf, count, ppos, cd);
1851 }
1852 
1853 const struct file_operations cache_flush_operations_pipefs = {
1854 	.open		= open_flush_pipefs,
1855 	.read		= read_flush_pipefs,
1856 	.write		= write_flush_pipefs,
1857 	.release	= release_flush_pipefs,
1858 	.llseek		= no_llseek,
1859 };
1860 
1861 int sunrpc_cache_register_pipefs(struct dentry *parent,
1862 				 const char *name, umode_t umode,
1863 				 struct cache_detail *cd)
1864 {
1865 	struct dentry *dir = rpc_create_cache_dir(parent, name, umode, cd);
1866 	if (IS_ERR(dir))
1867 		return PTR_ERR(dir);
1868 	cd->pipefs = dir;
1869 	return 0;
1870 }
1871 EXPORT_SYMBOL_GPL(sunrpc_cache_register_pipefs);
1872 
1873 void sunrpc_cache_unregister_pipefs(struct cache_detail *cd)
1874 {
1875 	if (cd->pipefs) {
1876 		rpc_remove_cache_dir(cd->pipefs);
1877 		cd->pipefs = NULL;
1878 	}
1879 }
1880 EXPORT_SYMBOL_GPL(sunrpc_cache_unregister_pipefs);
1881 
1882 void sunrpc_cache_unhash(struct cache_detail *cd, struct cache_head *h)
1883 {
1884 	spin_lock(&cd->hash_lock);
1885 	if (!hlist_unhashed(&h->cache_list)){
1886 		hlist_del_init_rcu(&h->cache_list);
1887 		cd->entries--;
1888 		spin_unlock(&cd->hash_lock);
1889 		cache_put(h, cd);
1890 	} else
1891 		spin_unlock(&cd->hash_lock);
1892 }
1893 EXPORT_SYMBOL_GPL(sunrpc_cache_unhash);
1894