OSDN Git Service

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