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