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