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