]> err.no Git - linux-2.6/blob - net/sunrpc/cache.c
mac80211: pass dtim_period to low level driver
[linux-2.6] / 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 <asm/uaccess.h>
24 #include <linux/poll.h>
25 #include <linux/seq_file.h>
26 #include <linux/proc_fs.h>
27 #include <linux/net.h>
28 #include <linux/workqueue.h>
29 #include <linux/mutex.h>
30 #include <asm/ioctls.h>
31 #include <linux/sunrpc/types.h>
32 #include <linux/sunrpc/cache.h>
33 #include <linux/sunrpc/stats.h>
34
35 #define  RPCDBG_FACILITY RPCDBG_CACHE
36
37 static int cache_defer_req(struct cache_req *req, struct cache_head *item);
38 static void cache_revisit_request(struct cache_head *item);
39
40 static void cache_init(struct cache_head *h)
41 {
42         time_t now = get_seconds();
43         h->next = NULL;
44         h->flags = 0;
45         kref_init(&h->ref);
46         h->expiry_time = now + CACHE_NEW_EXPIRY;
47         h->last_refresh = now;
48 }
49
50 struct cache_head *sunrpc_cache_lookup(struct cache_detail *detail,
51                                        struct cache_head *key, int hash)
52 {
53         struct cache_head **head,  **hp;
54         struct cache_head *new = NULL;
55
56         head = &detail->hash_table[hash];
57
58         read_lock(&detail->hash_lock);
59
60         for (hp=head; *hp != NULL ; hp = &(*hp)->next) {
61                 struct cache_head *tmp = *hp;
62                 if (detail->match(tmp, key)) {
63                         cache_get(tmp);
64                         read_unlock(&detail->hash_lock);
65                         return tmp;
66                 }
67         }
68         read_unlock(&detail->hash_lock);
69         /* Didn't find anything, insert an empty entry */
70
71         new = detail->alloc();
72         if (!new)
73                 return NULL;
74         /* must fully initialise 'new', else
75          * we might get lose if we need to
76          * cache_put it soon.
77          */
78         cache_init(new);
79         detail->init(new, key);
80
81         write_lock(&detail->hash_lock);
82
83         /* check if entry appeared while we slept */
84         for (hp=head; *hp != NULL ; hp = &(*hp)->next) {
85                 struct cache_head *tmp = *hp;
86                 if (detail->match(tmp, key)) {
87                         cache_get(tmp);
88                         write_unlock(&detail->hash_lock);
89                         cache_put(new, detail);
90                         return tmp;
91                 }
92         }
93         new->next = *head;
94         *head = new;
95         detail->entries++;
96         cache_get(new);
97         write_unlock(&detail->hash_lock);
98
99         return new;
100 }
101 EXPORT_SYMBOL(sunrpc_cache_lookup);
102
103
104 static void queue_loose(struct cache_detail *detail, struct cache_head *ch);
105
106 static int cache_fresh_locked(struct cache_head *head, time_t expiry)
107 {
108         head->expiry_time = expiry;
109         head->last_refresh = get_seconds();
110         return !test_and_set_bit(CACHE_VALID, &head->flags);
111 }
112
113 static void cache_fresh_unlocked(struct cache_head *head,
114                         struct cache_detail *detail, int new)
115 {
116         if (new)
117                 cache_revisit_request(head);
118         if (test_and_clear_bit(CACHE_PENDING, &head->flags)) {
119                 cache_revisit_request(head);
120                 queue_loose(detail, head);
121         }
122 }
123
124 struct cache_head *sunrpc_cache_update(struct cache_detail *detail,
125                                        struct cache_head *new, struct cache_head *old, int hash)
126 {
127         /* The 'old' entry is to be replaced by 'new'.
128          * If 'old' is not VALID, we update it directly,
129          * otherwise we need to replace it
130          */
131         struct cache_head **head;
132         struct cache_head *tmp;
133         int is_new;
134
135         if (!test_bit(CACHE_VALID, &old->flags)) {
136                 write_lock(&detail->hash_lock);
137                 if (!test_bit(CACHE_VALID, &old->flags)) {
138                         if (test_bit(CACHE_NEGATIVE, &new->flags))
139                                 set_bit(CACHE_NEGATIVE, &old->flags);
140                         else
141                                 detail->update(old, new);
142                         is_new = cache_fresh_locked(old, new->expiry_time);
143                         write_unlock(&detail->hash_lock);
144                         cache_fresh_unlocked(old, detail, is_new);
145                         return old;
146                 }
147                 write_unlock(&detail->hash_lock);
148         }
149         /* We need to insert a new entry */
150         tmp = detail->alloc();
151         if (!tmp) {
152                 cache_put(old, detail);
153                 return NULL;
154         }
155         cache_init(tmp);
156         detail->init(tmp, old);
157         head = &detail->hash_table[hash];
158
159         write_lock(&detail->hash_lock);
160         if (test_bit(CACHE_NEGATIVE, &new->flags))
161                 set_bit(CACHE_NEGATIVE, &tmp->flags);
162         else
163                 detail->update(tmp, new);
164         tmp->next = *head;
165         *head = tmp;
166         detail->entries++;
167         cache_get(tmp);
168         is_new = cache_fresh_locked(tmp, new->expiry_time);
169         cache_fresh_locked(old, 0);
170         write_unlock(&detail->hash_lock);
171         cache_fresh_unlocked(tmp, detail, is_new);
172         cache_fresh_unlocked(old, detail, 0);
173         cache_put(old, detail);
174         return tmp;
175 }
176 EXPORT_SYMBOL(sunrpc_cache_update);
177
178 static int cache_make_upcall(struct cache_detail *detail, struct cache_head *h);
179 /*
180  * This is the generic cache management routine for all
181  * the authentication caches.
182  * It checks the currency of a cache item and will (later)
183  * initiate an upcall to fill it if needed.
184  *
185  *
186  * Returns 0 if the cache_head can be used, or cache_puts it and returns
187  * -EAGAIN if upcall is pending,
188  * -ETIMEDOUT if upcall failed and should be retried,
189  * -ENOENT if cache entry was negative
190  */
191 int cache_check(struct cache_detail *detail,
192                     struct cache_head *h, struct cache_req *rqstp)
193 {
194         int rv;
195         long refresh_age, age;
196
197         /* First decide return status as best we can */
198         if (!test_bit(CACHE_VALID, &h->flags) ||
199             h->expiry_time < get_seconds())
200                 rv = -EAGAIN;
201         else if (detail->flush_time > h->last_refresh)
202                 rv = -EAGAIN;
203         else {
204                 /* entry is valid */
205                 if (test_bit(CACHE_NEGATIVE, &h->flags))
206                         rv = -ENOENT;
207                 else rv = 0;
208         }
209
210         /* now see if we want to start an upcall */
211         refresh_age = (h->expiry_time - h->last_refresh);
212         age = get_seconds() - h->last_refresh;
213
214         if (rqstp == NULL) {
215                 if (rv == -EAGAIN)
216                         rv = -ENOENT;
217         } else if (rv == -EAGAIN || age > refresh_age/2) {
218                 dprintk("RPC:       Want update, refage=%ld, age=%ld\n",
219                                 refresh_age, age);
220                 if (!test_and_set_bit(CACHE_PENDING, &h->flags)) {
221                         switch (cache_make_upcall(detail, h)) {
222                         case -EINVAL:
223                                 clear_bit(CACHE_PENDING, &h->flags);
224                                 if (rv == -EAGAIN) {
225                                         set_bit(CACHE_NEGATIVE, &h->flags);
226                                         cache_fresh_unlocked(h, detail,
227                                              cache_fresh_locked(h, get_seconds()+CACHE_NEW_EXPIRY));
228                                         rv = -ENOENT;
229                                 }
230                                 break;
231
232                         case -EAGAIN:
233                                 clear_bit(CACHE_PENDING, &h->flags);
234                                 cache_revisit_request(h);
235                                 break;
236                         }
237                 }
238         }
239
240         if (rv == -EAGAIN)
241                 if (cache_defer_req(rqstp, h) != 0)
242                         rv = -ETIMEDOUT;
243
244         if (rv)
245                 cache_put(h, detail);
246         return rv;
247 }
248 EXPORT_SYMBOL(cache_check);
249
250 /*
251  * caches need to be periodically cleaned.
252  * For this we maintain a list of cache_detail and
253  * a current pointer into that list and into the table
254  * for that entry.
255  *
256  * Each time clean_cache is called it finds the next non-empty entry
257  * in the current table and walks the list in that entry
258  * looking for entries that can be removed.
259  *
260  * An entry gets removed if:
261  * - The expiry is before current time
262  * - The last_refresh time is before the flush_time for that cache
263  *
264  * later we might drop old entries with non-NEVER expiry if that table
265  * is getting 'full' for some definition of 'full'
266  *
267  * The question of "how often to scan a table" is an interesting one
268  * and is answered in part by the use of the "nextcheck" field in the
269  * cache_detail.
270  * When a scan of a table begins, the nextcheck field is set to a time
271  * that is well into the future.
272  * While scanning, if an expiry time is found that is earlier than the
273  * current nextcheck time, nextcheck is set to that expiry time.
274  * If the flush_time is ever set to a time earlier than the nextcheck
275  * time, the nextcheck time is then set to that flush_time.
276  *
277  * A table is then only scanned if the current time is at least
278  * the nextcheck time.
279  *
280  */
281
282 static LIST_HEAD(cache_list);
283 static DEFINE_SPINLOCK(cache_list_lock);
284 static struct cache_detail *current_detail;
285 static int current_index;
286
287 static const struct file_operations cache_file_operations;
288 static const struct file_operations content_file_operations;
289 static const struct file_operations cache_flush_operations;
290
291 static void do_cache_clean(struct work_struct *work);
292 static DECLARE_DELAYED_WORK(cache_cleaner, do_cache_clean);
293
294 static void remove_cache_proc_entries(struct cache_detail *cd)
295 {
296         if (cd->proc_ent == NULL)
297                 return;
298         if (cd->flush_ent)
299                 remove_proc_entry("flush", cd->proc_ent);
300         if (cd->channel_ent)
301                 remove_proc_entry("channel", cd->proc_ent);
302         if (cd->content_ent)
303                 remove_proc_entry("content", cd->proc_ent);
304         cd->proc_ent = NULL;
305         remove_proc_entry(cd->name, proc_net_rpc);
306 }
307
308 #ifdef CONFIG_PROC_FS
309 static int create_cache_proc_entries(struct cache_detail *cd)
310 {
311         struct proc_dir_entry *p;
312
313         cd->proc_ent = proc_mkdir(cd->name, proc_net_rpc);
314         if (cd->proc_ent == NULL)
315                 goto out_nomem;
316         cd->proc_ent->owner = cd->owner;
317         cd->channel_ent = cd->content_ent = NULL;
318
319         p = proc_create_data("flush", S_IFREG|S_IRUSR|S_IWUSR,
320                              cd->proc_ent, &cache_flush_operations, cd);
321         cd->flush_ent = p;
322         if (p == NULL)
323                 goto out_nomem;
324         p->owner = cd->owner;
325
326         if (cd->cache_request || cd->cache_parse) {
327                 p = proc_create_data("channel", S_IFREG|S_IRUSR|S_IWUSR,
328                                      cd->proc_ent, &cache_file_operations, cd);
329                 cd->channel_ent = p;
330                 if (p == NULL)
331                         goto out_nomem;
332                 p->owner = cd->owner;
333         }
334         if (cd->cache_show) {
335                 p = proc_create_data("content", S_IFREG|S_IRUSR|S_IWUSR,
336                                 cd->proc_ent, &content_file_operations, cd);
337                 cd->content_ent = p;
338                 if (p == NULL)
339                         goto out_nomem;
340                 p->owner = cd->owner;
341         }
342         return 0;
343 out_nomem:
344         remove_cache_proc_entries(cd);
345         return -ENOMEM;
346 }
347 #else /* CONFIG_PROC_FS */
348 static int create_cache_proc_entries(struct cache_detail *cd)
349 {
350         return 0;
351 }
352 #endif
353
354 int cache_register(struct cache_detail *cd)
355 {
356         int ret;
357
358         ret = create_cache_proc_entries(cd);
359         if (ret)
360                 return ret;
361         rwlock_init(&cd->hash_lock);
362         INIT_LIST_HEAD(&cd->queue);
363         spin_lock(&cache_list_lock);
364         cd->nextcheck = 0;
365         cd->entries = 0;
366         atomic_set(&cd->readers, 0);
367         cd->last_close = 0;
368         cd->last_warn = -1;
369         list_add(&cd->others, &cache_list);
370         spin_unlock(&cache_list_lock);
371
372         /* start the cleaning process */
373         schedule_delayed_work(&cache_cleaner, 0);
374         return 0;
375 }
376 EXPORT_SYMBOL(cache_register);
377
378 void cache_unregister(struct cache_detail *cd)
379 {
380         cache_purge(cd);
381         spin_lock(&cache_list_lock);
382         write_lock(&cd->hash_lock);
383         if (cd->entries || atomic_read(&cd->inuse)) {
384                 write_unlock(&cd->hash_lock);
385                 spin_unlock(&cache_list_lock);
386                 goto out;
387         }
388         if (current_detail == cd)
389                 current_detail = NULL;
390         list_del_init(&cd->others);
391         write_unlock(&cd->hash_lock);
392         spin_unlock(&cache_list_lock);
393         remove_cache_proc_entries(cd);
394         if (list_empty(&cache_list)) {
395                 /* module must be being unloaded so its safe to kill the worker */
396                 cancel_delayed_work_sync(&cache_cleaner);
397         }
398         return;
399 out:
400         printk(KERN_ERR "nfsd: failed to unregister %s cache\n", cd->name);
401 }
402 EXPORT_SYMBOL(cache_unregister);
403
404 /* clean cache tries to find something to clean
405  * and cleans it.
406  * It returns 1 if it cleaned something,
407  *            0 if it didn't find anything this time
408  *           -1 if it fell off the end of the list.
409  */
410 static int cache_clean(void)
411 {
412         int rv = 0;
413         struct list_head *next;
414
415         spin_lock(&cache_list_lock);
416
417         /* find a suitable table if we don't already have one */
418         while (current_detail == NULL ||
419             current_index >= current_detail->hash_size) {
420                 if (current_detail)
421                         next = current_detail->others.next;
422                 else
423                         next = cache_list.next;
424                 if (next == &cache_list) {
425                         current_detail = NULL;
426                         spin_unlock(&cache_list_lock);
427                         return -1;
428                 }
429                 current_detail = list_entry(next, struct cache_detail, others);
430                 if (current_detail->nextcheck > get_seconds())
431                         current_index = current_detail->hash_size;
432                 else {
433                         current_index = 0;
434                         current_detail->nextcheck = get_seconds()+30*60;
435                 }
436         }
437
438         /* find a non-empty bucket in the table */
439         while (current_detail &&
440                current_index < current_detail->hash_size &&
441                current_detail->hash_table[current_index] == NULL)
442                 current_index++;
443
444         /* find a cleanable entry in the bucket and clean it, or set to next bucket */
445
446         if (current_detail && current_index < current_detail->hash_size) {
447                 struct cache_head *ch, **cp;
448                 struct cache_detail *d;
449
450                 write_lock(&current_detail->hash_lock);
451
452                 /* Ok, now to clean this strand */
453
454                 cp = & current_detail->hash_table[current_index];
455                 ch = *cp;
456                 for (; ch; cp= & ch->next, ch= *cp) {
457                         if (current_detail->nextcheck > ch->expiry_time)
458                                 current_detail->nextcheck = ch->expiry_time+1;
459                         if (ch->expiry_time >= get_seconds()
460                             && ch->last_refresh >= current_detail->flush_time
461                                 )
462                                 continue;
463                         if (test_and_clear_bit(CACHE_PENDING, &ch->flags))
464                                 queue_loose(current_detail, ch);
465
466                         if (atomic_read(&ch->ref.refcount) == 1)
467                                 break;
468                 }
469                 if (ch) {
470                         *cp = ch->next;
471                         ch->next = NULL;
472                         current_detail->entries--;
473                         rv = 1;
474                 }
475                 write_unlock(&current_detail->hash_lock);
476                 d = current_detail;
477                 if (!ch)
478                         current_index ++;
479                 spin_unlock(&cache_list_lock);
480                 if (ch)
481                         cache_put(ch, d);
482         } else
483                 spin_unlock(&cache_list_lock);
484
485         return rv;
486 }
487
488 /*
489  * We want to regularly clean the cache, so we need to schedule some work ...
490  */
491 static void do_cache_clean(struct work_struct *work)
492 {
493         int delay = 5;
494         if (cache_clean() == -1)
495                 delay = 30*HZ;
496
497         if (list_empty(&cache_list))
498                 delay = 0;
499
500         if (delay)
501                 schedule_delayed_work(&cache_cleaner, delay);
502 }
503
504
505 /*
506  * Clean all caches promptly.  This just calls cache_clean
507  * repeatedly until we are sure that every cache has had a chance to
508  * be fully cleaned
509  */
510 void cache_flush(void)
511 {
512         while (cache_clean() != -1)
513                 cond_resched();
514         while (cache_clean() != -1)
515                 cond_resched();
516 }
517 EXPORT_SYMBOL(cache_flush);
518
519 void cache_purge(struct cache_detail *detail)
520 {
521         detail->flush_time = LONG_MAX;
522         detail->nextcheck = get_seconds();
523         cache_flush();
524         detail->flush_time = 1;
525 }
526 EXPORT_SYMBOL(cache_purge);
527
528
529 /*
530  * Deferral and Revisiting of Requests.
531  *
532  * If a cache lookup finds a pending entry, we
533  * need to defer the request and revisit it later.
534  * All deferred requests are stored in a hash table,
535  * indexed by "struct cache_head *".
536  * As it may be wasteful to store a whole request
537  * structure, we allow the request to provide a
538  * deferred form, which must contain a
539  * 'struct cache_deferred_req'
540  * This cache_deferred_req contains a method to allow
541  * it to be revisited when cache info is available
542  */
543
544 #define DFR_HASHSIZE    (PAGE_SIZE/sizeof(struct list_head))
545 #define DFR_HASH(item)  ((((long)item)>>4 ^ (((long)item)>>13)) % DFR_HASHSIZE)
546
547 #define DFR_MAX 300     /* ??? */
548
549 static DEFINE_SPINLOCK(cache_defer_lock);
550 static LIST_HEAD(cache_defer_list);
551 static struct list_head cache_defer_hash[DFR_HASHSIZE];
552 static int cache_defer_cnt;
553
554 static int cache_defer_req(struct cache_req *req, struct cache_head *item)
555 {
556         struct cache_deferred_req *dreq;
557         int hash = DFR_HASH(item);
558
559         if (cache_defer_cnt >= DFR_MAX) {
560                 /* too much in the cache, randomly drop this one,
561                  * or continue and drop the oldest below
562                  */
563                 if (net_random()&1)
564                         return -ETIMEDOUT;
565         }
566         dreq = req->defer(req);
567         if (dreq == NULL)
568                 return -ETIMEDOUT;
569
570         dreq->item = item;
571
572         spin_lock(&cache_defer_lock);
573
574         list_add(&dreq->recent, &cache_defer_list);
575
576         if (cache_defer_hash[hash].next == NULL)
577                 INIT_LIST_HEAD(&cache_defer_hash[hash]);
578         list_add(&dreq->hash, &cache_defer_hash[hash]);
579
580         /* it is in, now maybe clean up */
581         dreq = NULL;
582         if (++cache_defer_cnt > DFR_MAX) {
583                 dreq = list_entry(cache_defer_list.prev,
584                                   struct cache_deferred_req, recent);
585                 list_del(&dreq->recent);
586                 list_del(&dreq->hash);
587                 cache_defer_cnt--;
588         }
589         spin_unlock(&cache_defer_lock);
590
591         if (dreq) {
592                 /* there was one too many */
593                 dreq->revisit(dreq, 1);
594         }
595         if (!test_bit(CACHE_PENDING, &item->flags)) {
596                 /* must have just been validated... */
597                 cache_revisit_request(item);
598         }
599         return 0;
600 }
601
602 static void cache_revisit_request(struct cache_head *item)
603 {
604         struct cache_deferred_req *dreq;
605         struct list_head pending;
606
607         struct list_head *lp;
608         int hash = DFR_HASH(item);
609
610         INIT_LIST_HEAD(&pending);
611         spin_lock(&cache_defer_lock);
612
613         lp = cache_defer_hash[hash].next;
614         if (lp) {
615                 while (lp != &cache_defer_hash[hash]) {
616                         dreq = list_entry(lp, struct cache_deferred_req, hash);
617                         lp = lp->next;
618                         if (dreq->item == item) {
619                                 list_del(&dreq->hash);
620                                 list_move(&dreq->recent, &pending);
621                                 cache_defer_cnt--;
622                         }
623                 }
624         }
625         spin_unlock(&cache_defer_lock);
626
627         while (!list_empty(&pending)) {
628                 dreq = list_entry(pending.next, struct cache_deferred_req, recent);
629                 list_del_init(&dreq->recent);
630                 dreq->revisit(dreq, 0);
631         }
632 }
633
634 void cache_clean_deferred(void *owner)
635 {
636         struct cache_deferred_req *dreq, *tmp;
637         struct list_head pending;
638
639
640         INIT_LIST_HEAD(&pending);
641         spin_lock(&cache_defer_lock);
642
643         list_for_each_entry_safe(dreq, tmp, &cache_defer_list, recent) {
644                 if (dreq->owner == owner) {
645                         list_del(&dreq->hash);
646                         list_move(&dreq->recent, &pending);
647                         cache_defer_cnt--;
648                 }
649         }
650         spin_unlock(&cache_defer_lock);
651
652         while (!list_empty(&pending)) {
653                 dreq = list_entry(pending.next, struct cache_deferred_req, recent);
654                 list_del_init(&dreq->recent);
655                 dreq->revisit(dreq, 1);
656         }
657 }
658
659 /*
660  * communicate with user-space
661  *
662  * We have a magic /proc file - /proc/sunrpc/<cachename>/channel.
663  * On read, you get a full request, or block.
664  * On write, an update request is processed.
665  * Poll works if anything to read, and always allows write.
666  *
667  * Implemented by linked list of requests.  Each open file has
668  * a ->private that also exists in this list.  New requests are added
669  * to the end and may wakeup and preceding readers.
670  * New readers are added to the head.  If, on read, an item is found with
671  * CACHE_UPCALLING clear, we free it from the list.
672  *
673  */
674
675 static DEFINE_SPINLOCK(queue_lock);
676 static DEFINE_MUTEX(queue_io_mutex);
677
678 struct cache_queue {
679         struct list_head        list;
680         int                     reader; /* if 0, then request */
681 };
682 struct cache_request {
683         struct cache_queue      q;
684         struct cache_head       *item;
685         char                    * buf;
686         int                     len;
687         int                     readers;
688 };
689 struct cache_reader {
690         struct cache_queue      q;
691         int                     offset; /* if non-0, we have a refcnt on next request */
692 };
693
694 static ssize_t
695 cache_read(struct file *filp, char __user *buf, size_t count, loff_t *ppos)
696 {
697         struct cache_reader *rp = filp->private_data;
698         struct cache_request *rq;
699         struct cache_detail *cd = PDE(filp->f_path.dentry->d_inode)->data;
700         int err;
701
702         if (count == 0)
703                 return 0;
704
705         mutex_lock(&queue_io_mutex); /* protect against multiple concurrent
706                               * readers on this file */
707  again:
708         spin_lock(&queue_lock);
709         /* need to find next request */
710         while (rp->q.list.next != &cd->queue &&
711                list_entry(rp->q.list.next, struct cache_queue, list)
712                ->reader) {
713                 struct list_head *next = rp->q.list.next;
714                 list_move(&rp->q.list, next);
715         }
716         if (rp->q.list.next == &cd->queue) {
717                 spin_unlock(&queue_lock);
718                 mutex_unlock(&queue_io_mutex);
719                 BUG_ON(rp->offset);
720                 return 0;
721         }
722         rq = container_of(rp->q.list.next, struct cache_request, q.list);
723         BUG_ON(rq->q.reader);
724         if (rp->offset == 0)
725                 rq->readers++;
726         spin_unlock(&queue_lock);
727
728         if (rp->offset == 0 && !test_bit(CACHE_PENDING, &rq->item->flags)) {
729                 err = -EAGAIN;
730                 spin_lock(&queue_lock);
731                 list_move(&rp->q.list, &rq->q.list);
732                 spin_unlock(&queue_lock);
733         } else {
734                 if (rp->offset + count > rq->len)
735                         count = rq->len - rp->offset;
736                 err = -EFAULT;
737                 if (copy_to_user(buf, rq->buf + rp->offset, count))
738                         goto out;
739                 rp->offset += count;
740                 if (rp->offset >= rq->len) {
741                         rp->offset = 0;
742                         spin_lock(&queue_lock);
743                         list_move(&rp->q.list, &rq->q.list);
744                         spin_unlock(&queue_lock);
745                 }
746                 err = 0;
747         }
748  out:
749         if (rp->offset == 0) {
750                 /* need to release rq */
751                 spin_lock(&queue_lock);
752                 rq->readers--;
753                 if (rq->readers == 0 &&
754                     !test_bit(CACHE_PENDING, &rq->item->flags)) {
755                         list_del(&rq->q.list);
756                         spin_unlock(&queue_lock);
757                         cache_put(rq->item, cd);
758                         kfree(rq->buf);
759                         kfree(rq);
760                 } else
761                         spin_unlock(&queue_lock);
762         }
763         if (err == -EAGAIN)
764                 goto again;
765         mutex_unlock(&queue_io_mutex);
766         return err ? err :  count;
767 }
768
769 static char write_buf[8192]; /* protected by queue_io_mutex */
770
771 static ssize_t
772 cache_write(struct file *filp, const char __user *buf, size_t count,
773             loff_t *ppos)
774 {
775         int err;
776         struct cache_detail *cd = PDE(filp->f_path.dentry->d_inode)->data;
777
778         if (count == 0)
779                 return 0;
780         if (count >= sizeof(write_buf))
781                 return -EINVAL;
782
783         mutex_lock(&queue_io_mutex);
784
785         if (copy_from_user(write_buf, buf, count)) {
786                 mutex_unlock(&queue_io_mutex);
787                 return -EFAULT;
788         }
789         write_buf[count] = '\0';
790         if (cd->cache_parse)
791                 err = cd->cache_parse(cd, write_buf, count);
792         else
793                 err = -EINVAL;
794
795         mutex_unlock(&queue_io_mutex);
796         return err ? err : count;
797 }
798
799 static DECLARE_WAIT_QUEUE_HEAD(queue_wait);
800
801 static unsigned int
802 cache_poll(struct file *filp, poll_table *wait)
803 {
804         unsigned int mask;
805         struct cache_reader *rp = filp->private_data;
806         struct cache_queue *cq;
807         struct cache_detail *cd = PDE(filp->f_path.dentry->d_inode)->data;
808
809         poll_wait(filp, &queue_wait, wait);
810
811         /* alway allow write */
812         mask = POLL_OUT | POLLWRNORM;
813
814         if (!rp)
815                 return mask;
816
817         spin_lock(&queue_lock);
818
819         for (cq= &rp->q; &cq->list != &cd->queue;
820              cq = list_entry(cq->list.next, struct cache_queue, list))
821                 if (!cq->reader) {
822                         mask |= POLLIN | POLLRDNORM;
823                         break;
824                 }
825         spin_unlock(&queue_lock);
826         return mask;
827 }
828
829 static int
830 cache_ioctl(struct inode *ino, struct file *filp,
831             unsigned int cmd, unsigned long arg)
832 {
833         int len = 0;
834         struct cache_reader *rp = filp->private_data;
835         struct cache_queue *cq;
836         struct cache_detail *cd = PDE(ino)->data;
837
838         if (cmd != FIONREAD || !rp)
839                 return -EINVAL;
840
841         spin_lock(&queue_lock);
842
843         /* only find the length remaining in current request,
844          * or the length of the next request
845          */
846         for (cq= &rp->q; &cq->list != &cd->queue;
847              cq = list_entry(cq->list.next, struct cache_queue, list))
848                 if (!cq->reader) {
849                         struct cache_request *cr =
850                                 container_of(cq, struct cache_request, q);
851                         len = cr->len - rp->offset;
852                         break;
853                 }
854         spin_unlock(&queue_lock);
855
856         return put_user(len, (int __user *)arg);
857 }
858
859 static int
860 cache_open(struct inode *inode, struct file *filp)
861 {
862         struct cache_reader *rp = NULL;
863
864         nonseekable_open(inode, filp);
865         if (filp->f_mode & FMODE_READ) {
866                 struct cache_detail *cd = PDE(inode)->data;
867
868                 rp = kmalloc(sizeof(*rp), GFP_KERNEL);
869                 if (!rp)
870                         return -ENOMEM;
871                 rp->offset = 0;
872                 rp->q.reader = 1;
873                 atomic_inc(&cd->readers);
874                 spin_lock(&queue_lock);
875                 list_add(&rp->q.list, &cd->queue);
876                 spin_unlock(&queue_lock);
877         }
878         filp->private_data = rp;
879         return 0;
880 }
881
882 static int
883 cache_release(struct inode *inode, struct file *filp)
884 {
885         struct cache_reader *rp = filp->private_data;
886         struct cache_detail *cd = PDE(inode)->data;
887
888         if (rp) {
889                 spin_lock(&queue_lock);
890                 if (rp->offset) {
891                         struct cache_queue *cq;
892                         for (cq= &rp->q; &cq->list != &cd->queue;
893                              cq = list_entry(cq->list.next, struct cache_queue, list))
894                                 if (!cq->reader) {
895                                         container_of(cq, struct cache_request, q)
896                                                 ->readers--;
897                                         break;
898                                 }
899                         rp->offset = 0;
900                 }
901                 list_del(&rp->q.list);
902                 spin_unlock(&queue_lock);
903
904                 filp->private_data = NULL;
905                 kfree(rp);
906
907                 cd->last_close = get_seconds();
908                 atomic_dec(&cd->readers);
909         }
910         return 0;
911 }
912
913
914
915 static const struct file_operations cache_file_operations = {
916         .owner          = THIS_MODULE,
917         .llseek         = no_llseek,
918         .read           = cache_read,
919         .write          = cache_write,
920         .poll           = cache_poll,
921         .ioctl          = cache_ioctl, /* for FIONREAD */
922         .open           = cache_open,
923         .release        = cache_release,
924 };
925
926
927 static void queue_loose(struct cache_detail *detail, struct cache_head *ch)
928 {
929         struct cache_queue *cq;
930         spin_lock(&queue_lock);
931         list_for_each_entry(cq, &detail->queue, list)
932                 if (!cq->reader) {
933                         struct cache_request *cr = container_of(cq, struct cache_request, q);
934                         if (cr->item != ch)
935                                 continue;
936                         if (cr->readers != 0)
937                                 continue;
938                         list_del(&cr->q.list);
939                         spin_unlock(&queue_lock);
940                         cache_put(cr->item, detail);
941                         kfree(cr->buf);
942                         kfree(cr);
943                         return;
944                 }
945         spin_unlock(&queue_lock);
946 }
947
948 /*
949  * Support routines for text-based upcalls.
950  * Fields are separated by spaces.
951  * Fields are either mangled to quote space tab newline slosh with slosh
952  * or a hexified with a leading \x
953  * Record is terminated with newline.
954  *
955  */
956
957 void qword_add(char **bpp, int *lp, char *str)
958 {
959         char *bp = *bpp;
960         int len = *lp;
961         char c;
962
963         if (len < 0) return;
964
965         while ((c=*str++) && len)
966                 switch(c) {
967                 case ' ':
968                 case '\t':
969                 case '\n':
970                 case '\\':
971                         if (len >= 4) {
972                                 *bp++ = '\\';
973                                 *bp++ = '0' + ((c & 0300)>>6);
974                                 *bp++ = '0' + ((c & 0070)>>3);
975                                 *bp++ = '0' + ((c & 0007)>>0);
976                         }
977                         len -= 4;
978                         break;
979                 default:
980                         *bp++ = c;
981                         len--;
982                 }
983         if (c || len <1) len = -1;
984         else {
985                 *bp++ = ' ';
986                 len--;
987         }
988         *bpp = bp;
989         *lp = len;
990 }
991 EXPORT_SYMBOL(qword_add);
992
993 void qword_addhex(char **bpp, int *lp, char *buf, int blen)
994 {
995         char *bp = *bpp;
996         int len = *lp;
997
998         if (len < 0) return;
999
1000         if (len > 2) {
1001                 *bp++ = '\\';
1002                 *bp++ = 'x';
1003                 len -= 2;
1004                 while (blen && len >= 2) {
1005                         unsigned char c = *buf++;
1006                         *bp++ = '0' + ((c&0xf0)>>4) + (c>=0xa0)*('a'-'9'-1);
1007                         *bp++ = '0' + (c&0x0f) + ((c&0x0f)>=0x0a)*('a'-'9'-1);
1008                         len -= 2;
1009                         blen--;
1010                 }
1011         }
1012         if (blen || len<1) len = -1;
1013         else {
1014                 *bp++ = ' ';
1015                 len--;
1016         }
1017         *bpp = bp;
1018         *lp = len;
1019 }
1020 EXPORT_SYMBOL(qword_addhex);
1021
1022 static void warn_no_listener(struct cache_detail *detail)
1023 {
1024         if (detail->last_warn != detail->last_close) {
1025                 detail->last_warn = detail->last_close;
1026                 if (detail->warn_no_listener)
1027                         detail->warn_no_listener(detail);
1028         }
1029 }
1030
1031 /*
1032  * register an upcall request to user-space.
1033  * Each request is at most one page long.
1034  */
1035 static int cache_make_upcall(struct cache_detail *detail, struct cache_head *h)
1036 {
1037
1038         char *buf;
1039         struct cache_request *crq;
1040         char *bp;
1041         int len;
1042
1043         if (detail->cache_request == NULL)
1044                 return -EINVAL;
1045
1046         if (atomic_read(&detail->readers) == 0 &&
1047             detail->last_close < get_seconds() - 30) {
1048                         warn_no_listener(detail);
1049                         return -EINVAL;
1050         }
1051
1052         buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
1053         if (!buf)
1054                 return -EAGAIN;
1055
1056         crq = kmalloc(sizeof (*crq), GFP_KERNEL);
1057         if (!crq) {
1058                 kfree(buf);
1059                 return -EAGAIN;
1060         }
1061
1062         bp = buf; len = PAGE_SIZE;
1063
1064         detail->cache_request(detail, h, &bp, &len);
1065
1066         if (len < 0) {
1067                 kfree(buf);
1068                 kfree(crq);
1069                 return -EAGAIN;
1070         }
1071         crq->q.reader = 0;
1072         crq->item = cache_get(h);
1073         crq->buf = buf;
1074         crq->len = PAGE_SIZE - len;
1075         crq->readers = 0;
1076         spin_lock(&queue_lock);
1077         list_add_tail(&crq->q.list, &detail->queue);
1078         spin_unlock(&queue_lock);
1079         wake_up(&queue_wait);
1080         return 0;
1081 }
1082
1083 /*
1084  * parse a message from user-space and pass it
1085  * to an appropriate cache
1086  * Messages are, like requests, separated into fields by
1087  * spaces and dequotes as \xHEXSTRING or embedded \nnn octal
1088  *
1089  * Message is
1090  *   reply cachename expiry key ... content....
1091  *
1092  * key and content are both parsed by cache
1093  */
1094
1095 #define isodigit(c) (isdigit(c) && c <= '7')
1096 int qword_get(char **bpp, char *dest, int bufsize)
1097 {
1098         /* return bytes copied, or -1 on error */
1099         char *bp = *bpp;
1100         int len = 0;
1101
1102         while (*bp == ' ') bp++;
1103
1104         if (bp[0] == '\\' && bp[1] == 'x') {
1105                 /* HEX STRING */
1106                 bp += 2;
1107                 while (isxdigit(bp[0]) && isxdigit(bp[1]) && len < bufsize) {
1108                         int byte = isdigit(*bp) ? *bp-'0' : toupper(*bp)-'A'+10;
1109                         bp++;
1110                         byte <<= 4;
1111                         byte |= isdigit(*bp) ? *bp-'0' : toupper(*bp)-'A'+10;
1112                         *dest++ = byte;
1113                         bp++;
1114                         len++;
1115                 }
1116         } else {
1117                 /* text with \nnn octal quoting */
1118                 while (*bp != ' ' && *bp != '\n' && *bp && len < bufsize-1) {
1119                         if (*bp == '\\' &&
1120                             isodigit(bp[1]) && (bp[1] <= '3') &&
1121                             isodigit(bp[2]) &&
1122                             isodigit(bp[3])) {
1123                                 int byte = (*++bp -'0');
1124                                 bp++;
1125                                 byte = (byte << 3) | (*bp++ - '0');
1126                                 byte = (byte << 3) | (*bp++ - '0');
1127                                 *dest++ = byte;
1128                                 len++;
1129                         } else {
1130                                 *dest++ = *bp++;
1131                                 len++;
1132                         }
1133                 }
1134         }
1135
1136         if (*bp != ' ' && *bp != '\n' && *bp != '\0')
1137                 return -1;
1138         while (*bp == ' ') bp++;
1139         *bpp = bp;
1140         *dest = '\0';
1141         return len;
1142 }
1143 EXPORT_SYMBOL(qword_get);
1144
1145
1146 /*
1147  * support /proc/sunrpc/cache/$CACHENAME/content
1148  * as a seqfile.
1149  * We call ->cache_show passing NULL for the item to
1150  * get a header, then pass each real item in the cache
1151  */
1152
1153 struct handle {
1154         struct cache_detail *cd;
1155 };
1156
1157 static void *c_start(struct seq_file *m, loff_t *pos)
1158         __acquires(cd->hash_lock)
1159 {
1160         loff_t n = *pos;
1161         unsigned hash, entry;
1162         struct cache_head *ch;
1163         struct cache_detail *cd = ((struct handle*)m->private)->cd;
1164
1165
1166         read_lock(&cd->hash_lock);
1167         if (!n--)
1168                 return SEQ_START_TOKEN;
1169         hash = n >> 32;
1170         entry = n & ((1LL<<32) - 1);
1171
1172         for (ch=cd->hash_table[hash]; ch; ch=ch->next)
1173                 if (!entry--)
1174                         return ch;
1175         n &= ~((1LL<<32) - 1);
1176         do {
1177                 hash++;
1178                 n += 1LL<<32;
1179         } while(hash < cd->hash_size &&
1180                 cd->hash_table[hash]==NULL);
1181         if (hash >= cd->hash_size)
1182                 return NULL;
1183         *pos = n+1;
1184         return cd->hash_table[hash];
1185 }
1186
1187 static void *c_next(struct seq_file *m, void *p, loff_t *pos)
1188 {
1189         struct cache_head *ch = p;
1190         int hash = (*pos >> 32);
1191         struct cache_detail *cd = ((struct handle*)m->private)->cd;
1192
1193         if (p == SEQ_START_TOKEN)
1194                 hash = 0;
1195         else if (ch->next == NULL) {
1196                 hash++;
1197                 *pos += 1LL<<32;
1198         } else {
1199                 ++*pos;
1200                 return ch->next;
1201         }
1202         *pos &= ~((1LL<<32) - 1);
1203         while (hash < cd->hash_size &&
1204                cd->hash_table[hash] == NULL) {
1205                 hash++;
1206                 *pos += 1LL<<32;
1207         }
1208         if (hash >= cd->hash_size)
1209                 return NULL;
1210         ++*pos;
1211         return cd->hash_table[hash];
1212 }
1213
1214 static void c_stop(struct seq_file *m, void *p)
1215         __releases(cd->hash_lock)
1216 {
1217         struct cache_detail *cd = ((struct handle*)m->private)->cd;
1218         read_unlock(&cd->hash_lock);
1219 }
1220
1221 static int c_show(struct seq_file *m, void *p)
1222 {
1223         struct cache_head *cp = p;
1224         struct cache_detail *cd = ((struct handle*)m->private)->cd;
1225
1226         if (p == SEQ_START_TOKEN)
1227                 return cd->cache_show(m, cd, NULL);
1228
1229         ifdebug(CACHE)
1230                 seq_printf(m, "# expiry=%ld refcnt=%d flags=%lx\n",
1231                            cp->expiry_time, atomic_read(&cp->ref.refcount), cp->flags);
1232         cache_get(cp);
1233         if (cache_check(cd, cp, NULL))
1234                 /* cache_check does a cache_put on failure */
1235                 seq_printf(m, "# ");
1236         else
1237                 cache_put(cp, cd);
1238
1239         return cd->cache_show(m, cd, cp);
1240 }
1241
1242 static const struct seq_operations cache_content_op = {
1243         .start  = c_start,
1244         .next   = c_next,
1245         .stop   = c_stop,
1246         .show   = c_show,
1247 };
1248
1249 static int content_open(struct inode *inode, struct file *file)
1250 {
1251         struct handle *han;
1252         struct cache_detail *cd = PDE(inode)->data;
1253
1254         han = __seq_open_private(file, &cache_content_op, sizeof(*han));
1255         if (han == NULL)
1256                 return -ENOMEM;
1257
1258         han->cd = cd;
1259         return 0;
1260 }
1261
1262 static const struct file_operations content_file_operations = {
1263         .open           = content_open,
1264         .read           = seq_read,
1265         .llseek         = seq_lseek,
1266         .release        = seq_release_private,
1267 };
1268
1269 static ssize_t read_flush(struct file *file, char __user *buf,
1270                             size_t count, loff_t *ppos)
1271 {
1272         struct cache_detail *cd = PDE(file->f_path.dentry->d_inode)->data;
1273         char tbuf[20];
1274         unsigned long p = *ppos;
1275         size_t len;
1276
1277         sprintf(tbuf, "%lu\n", cd->flush_time);
1278         len = strlen(tbuf);
1279         if (p >= len)
1280                 return 0;
1281         len -= p;
1282         if (len > count)
1283                 len = count;
1284         if (copy_to_user(buf, (void*)(tbuf+p), len))
1285                 return -EFAULT;
1286         *ppos += len;
1287         return len;
1288 }
1289
1290 static ssize_t write_flush(struct file * file, const char __user * buf,
1291                              size_t count, loff_t *ppos)
1292 {
1293         struct cache_detail *cd = PDE(file->f_path.dentry->d_inode)->data;
1294         char tbuf[20];
1295         char *ep;
1296         long flushtime;
1297         if (*ppos || count > sizeof(tbuf)-1)
1298                 return -EINVAL;
1299         if (copy_from_user(tbuf, buf, count))
1300                 return -EFAULT;
1301         tbuf[count] = 0;
1302         flushtime = simple_strtoul(tbuf, &ep, 0);
1303         if (*ep && *ep != '\n')
1304                 return -EINVAL;
1305
1306         cd->flush_time = flushtime;
1307         cd->nextcheck = get_seconds();
1308         cache_flush();
1309
1310         *ppos += count;
1311         return count;
1312 }
1313
1314 static const struct file_operations cache_flush_operations = {
1315         .open           = nonseekable_open,
1316         .read           = read_flush,
1317         .write          = write_flush,
1318 };