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