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