Merge branch 'stable-3.2' into pandora-3.2
[pandora-kernel.git] / fs / nfsd / nfs4state.c
1 /*
2 *  Copyright (c) 2001 The Regents of the University of Michigan.
3 *  All rights reserved.
4 *
5 *  Kendrick Smith <kmsmith@umich.edu>
6 *  Andy Adamson <kandros@umich.edu>
7 *
8 *  Redistribution and use in source and binary forms, with or without
9 *  modification, are permitted provided that the following conditions
10 *  are met:
11 *
12 *  1. Redistributions of source code must retain the above copyright
13 *     notice, this list of conditions and the following disclaimer.
14 *  2. Redistributions in binary form must reproduce the above copyright
15 *     notice, this list of conditions and the following disclaimer in the
16 *     documentation and/or other materials provided with the distribution.
17 *  3. Neither the name of the University nor the names of its
18 *     contributors may be used to endorse or promote products derived
19 *     from this software without specific prior written permission.
20 *
21 *  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
22 *  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
23 *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
24 *  DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 *  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
28 *  BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 *  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 *  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 *
33 */
34
35 #include <linux/file.h>
36 #include <linux/fs.h>
37 #include <linux/slab.h>
38 #include <linux/namei.h>
39 #include <linux/swap.h>
40 #include <linux/pagemap.h>
41 #include <linux/sunrpc/svcauth_gss.h>
42 #include <linux/sunrpc/clnt.h>
43 #include "xdr4.h"
44 #include "vfs.h"
45
46 #define NFSDDBG_FACILITY                NFSDDBG_PROC
47
48 /* Globals */
49 time_t nfsd4_lease = 90;     /* default lease time */
50 time_t nfsd4_grace = 90;
51 static time_t boot_time;
52 static stateid_t zerostateid;             /* bits all 0 */
53 static stateid_t onestateid;              /* bits all 1 */
54 static u64 current_sessionid = 1;
55
56 #define ZERO_STATEID(stateid) (!memcmp((stateid), &zerostateid, sizeof(stateid_t)))
57 #define ONE_STATEID(stateid)  (!memcmp((stateid), &onestateid, sizeof(stateid_t)))
58
59 /* forward declarations */
60 static int check_for_locks(struct nfs4_file *filp, struct nfs4_lockowner *lowner);
61
62 /* Locking: */
63
64 /* Currently used for almost all code touching nfsv4 state: */
65 static DEFINE_MUTEX(client_mutex);
66
67 /*
68  * Currently used for the del_recall_lru and file hash table.  In an
69  * effort to decrease the scope of the client_mutex, this spinlock may
70  * eventually cover more:
71  */
72 static DEFINE_SPINLOCK(recall_lock);
73
74 static struct kmem_cache *openowner_slab = NULL;
75 static struct kmem_cache *lockowner_slab = NULL;
76 static struct kmem_cache *file_slab = NULL;
77 static struct kmem_cache *stateid_slab = NULL;
78 static struct kmem_cache *deleg_slab = NULL;
79
80 void
81 nfs4_lock_state(void)
82 {
83         mutex_lock(&client_mutex);
84 }
85
86 void
87 nfs4_unlock_state(void)
88 {
89         mutex_unlock(&client_mutex);
90 }
91
92 static inline u32
93 opaque_hashval(const void *ptr, int nbytes)
94 {
95         unsigned char *cptr = (unsigned char *) ptr;
96
97         u32 x = 0;
98         while (nbytes--) {
99                 x *= 37;
100                 x += *cptr++;
101         }
102         return x;
103 }
104
105 static struct list_head del_recall_lru;
106
107 static void nfsd4_free_file(struct nfs4_file *f)
108 {
109         kmem_cache_free(file_slab, f);
110 }
111
112 static inline void
113 put_nfs4_file(struct nfs4_file *fi)
114 {
115         if (atomic_dec_and_lock(&fi->fi_ref, &recall_lock)) {
116                 list_del(&fi->fi_hash);
117                 spin_unlock(&recall_lock);
118                 iput(fi->fi_inode);
119                 nfsd4_free_file(fi);
120         }
121 }
122
123 static inline void
124 get_nfs4_file(struct nfs4_file *fi)
125 {
126         atomic_inc(&fi->fi_ref);
127 }
128
129 static int num_delegations;
130 unsigned int max_delegations;
131
132 /*
133  * Open owner state (share locks)
134  */
135
136 /* hash tables for open owners */
137 #define OPEN_OWNER_HASH_BITS              8
138 #define OPEN_OWNER_HASH_SIZE             (1 << OPEN_OWNER_HASH_BITS)
139 #define OPEN_OWNER_HASH_MASK             (OPEN_OWNER_HASH_SIZE - 1)
140
141 static unsigned int open_ownerstr_hashval(u32 clientid, struct xdr_netobj *ownername)
142 {
143         unsigned int ret;
144
145         ret = opaque_hashval(ownername->data, ownername->len);
146         ret += clientid;
147         return ret & OPEN_OWNER_HASH_MASK;
148 }
149
150 static struct list_head open_ownerstr_hashtbl[OPEN_OWNER_HASH_SIZE];
151
152 /* hash table for nfs4_file */
153 #define FILE_HASH_BITS                   8
154 #define FILE_HASH_SIZE                  (1 << FILE_HASH_BITS)
155
156 static unsigned int file_hashval(struct inode *ino)
157 {
158         /* XXX: why are we hashing on inode pointer, anyway? */
159         return hash_ptr(ino, FILE_HASH_BITS);
160 }
161
162 static struct list_head file_hashtbl[FILE_HASH_SIZE];
163
164 static void __nfs4_file_get_access(struct nfs4_file *fp, int oflag)
165 {
166         BUG_ON(!(fp->fi_fds[oflag] || fp->fi_fds[O_RDWR]));
167         atomic_inc(&fp->fi_access[oflag]);
168 }
169
170 static void nfs4_file_get_access(struct nfs4_file *fp, int oflag)
171 {
172         if (oflag == O_RDWR) {
173                 __nfs4_file_get_access(fp, O_RDONLY);
174                 __nfs4_file_get_access(fp, O_WRONLY);
175         } else
176                 __nfs4_file_get_access(fp, oflag);
177 }
178
179 static void nfs4_file_put_fd(struct nfs4_file *fp, int oflag)
180 {
181         if (fp->fi_fds[oflag]) {
182                 fput(fp->fi_fds[oflag]);
183                 fp->fi_fds[oflag] = NULL;
184         }
185 }
186
187 static void __nfs4_file_put_access(struct nfs4_file *fp, int oflag)
188 {
189         if (atomic_dec_and_test(&fp->fi_access[oflag])) {
190                 nfs4_file_put_fd(fp, oflag);
191                 if (atomic_read(&fp->fi_access[1 - oflag]) == 0)
192                         nfs4_file_put_fd(fp, O_RDWR);
193         }
194 }
195
196 static void nfs4_file_put_access(struct nfs4_file *fp, int oflag)
197 {
198         if (oflag == O_RDWR) {
199                 __nfs4_file_put_access(fp, O_RDONLY);
200                 __nfs4_file_put_access(fp, O_WRONLY);
201         } else
202                 __nfs4_file_put_access(fp, oflag);
203 }
204
205 static inline int get_new_stid(struct nfs4_stid *stid)
206 {
207         static int min_stateid = 0;
208         struct idr *stateids = &stid->sc_client->cl_stateids;
209         int new_stid;
210         int error;
211
212         error = idr_get_new_above(stateids, stid, min_stateid, &new_stid);
213         /*
214          * Note: the necessary preallocation was done in
215          * nfs4_alloc_stateid().  The idr code caps the number of
216          * preallocations that can exist at a time, but the state lock
217          * prevents anyone from using ours before we get here:
218          */
219         BUG_ON(error);
220         /*
221          * It shouldn't be a problem to reuse an opaque stateid value.
222          * I don't think it is for 4.1.  But with 4.0 I worry that, for
223          * example, a stray write retransmission could be accepted by
224          * the server when it should have been rejected.  Therefore,
225          * adopt a trick from the sctp code to attempt to maximize the
226          * amount of time until an id is reused, by ensuring they always
227          * "increase" (mod INT_MAX):
228          */
229
230         min_stateid = new_stid+1;
231         if (min_stateid == INT_MAX)
232                 min_stateid = 0;
233         return new_stid;
234 }
235
236 static void init_stid(struct nfs4_stid *stid, struct nfs4_client *cl, unsigned char type)
237 {
238         stateid_t *s = &stid->sc_stateid;
239         int new_id;
240
241         stid->sc_type = type;
242         stid->sc_client = cl;
243         s->si_opaque.so_clid = cl->cl_clientid;
244         new_id = get_new_stid(stid);
245         s->si_opaque.so_id = (u32)new_id;
246         /* Will be incremented before return to client: */
247         s->si_generation = 0;
248 }
249
250 static struct nfs4_stid *nfs4_alloc_stid(struct nfs4_client *cl, struct kmem_cache *slab)
251 {
252         struct idr *stateids = &cl->cl_stateids;
253
254         if (!idr_pre_get(stateids, GFP_KERNEL))
255                 return NULL;
256         /*
257          * Note: if we fail here (or any time between now and the time
258          * we actually get the new idr), we won't need to undo the idr
259          * preallocation, since the idr code caps the number of
260          * preallocated entries.
261          */
262         return kmem_cache_alloc(slab, GFP_KERNEL);
263 }
264
265 static struct nfs4_ol_stateid * nfs4_alloc_stateid(struct nfs4_client *clp)
266 {
267         return openlockstateid(nfs4_alloc_stid(clp, stateid_slab));
268 }
269
270 static struct nfs4_delegation *
271 alloc_init_deleg(struct nfs4_client *clp, struct nfs4_ol_stateid *stp, struct svc_fh *current_fh, u32 type)
272 {
273         struct nfs4_delegation *dp;
274         struct nfs4_file *fp = stp->st_file;
275
276         dprintk("NFSD alloc_init_deleg\n");
277         /*
278          * Major work on the lease subsystem (for example, to support
279          * calbacks on stat) will be required before we can support
280          * write delegations properly.
281          */
282         if (type != NFS4_OPEN_DELEGATE_READ)
283                 return NULL;
284         if (fp->fi_had_conflict)
285                 return NULL;
286         if (num_delegations > max_delegations)
287                 return NULL;
288         dp = delegstateid(nfs4_alloc_stid(clp, deleg_slab));
289         if (dp == NULL)
290                 return dp;
291         init_stid(&dp->dl_stid, clp, NFS4_DELEG_STID);
292         /*
293          * delegation seqid's are never incremented.  The 4.1 special
294          * meaning of seqid 0 isn't meaningful, really, but let's avoid
295          * 0 anyway just for consistency and use 1:
296          */
297         dp->dl_stid.sc_stateid.si_generation = 1;
298         num_delegations++;
299         INIT_LIST_HEAD(&dp->dl_perfile);
300         INIT_LIST_HEAD(&dp->dl_perclnt);
301         INIT_LIST_HEAD(&dp->dl_recall_lru);
302         get_nfs4_file(fp);
303         dp->dl_file = fp;
304         dp->dl_type = type;
305         fh_copy_shallow(&dp->dl_fh, &current_fh->fh_handle);
306         dp->dl_time = 0;
307         atomic_set(&dp->dl_count, 1);
308         INIT_WORK(&dp->dl_recall.cb_work, nfsd4_do_callback_rpc);
309         return dp;
310 }
311
312 void
313 nfs4_put_delegation(struct nfs4_delegation *dp)
314 {
315         if (atomic_dec_and_test(&dp->dl_count)) {
316                 dprintk("NFSD: freeing dp %p\n",dp);
317                 put_nfs4_file(dp->dl_file);
318                 kmem_cache_free(deleg_slab, dp);
319                 num_delegations--;
320         }
321 }
322
323 static void nfs4_put_deleg_lease(struct nfs4_file *fp)
324 {
325         if (atomic_dec_and_test(&fp->fi_delegees)) {
326                 vfs_setlease(fp->fi_deleg_file, F_UNLCK, &fp->fi_lease);
327                 fp->fi_lease = NULL;
328                 fput(fp->fi_deleg_file);
329                 fp->fi_deleg_file = NULL;
330         }
331 }
332
333 static void unhash_stid(struct nfs4_stid *s)
334 {
335         struct idr *stateids = &s->sc_client->cl_stateids;
336
337         idr_remove(stateids, s->sc_stateid.si_opaque.so_id);
338 }
339
340 static void
341 hash_delegation_locked(struct nfs4_delegation *dp, struct nfs4_file *fp)
342 {
343         lockdep_assert_held(&recall_lock);
344
345         list_add(&dp->dl_perfile, &fp->fi_delegations);
346         list_add(&dp->dl_perclnt, &dp->dl_stid.sc_client->cl_delegations);
347 }
348
349 /* Called under the state lock. */
350 static void
351 unhash_delegation(struct nfs4_delegation *dp)
352 {
353         unhash_stid(&dp->dl_stid);
354         spin_lock(&recall_lock);
355         list_del_init(&dp->dl_perclnt);
356         list_del_init(&dp->dl_perfile);
357         list_del_init(&dp->dl_recall_lru);
358         spin_unlock(&recall_lock);
359         nfs4_put_deleg_lease(dp->dl_file);
360         nfs4_put_delegation(dp);
361 }
362
363 /* 
364  * SETCLIENTID state 
365  */
366
367 /* client_lock protects the client lru list and session hash table */
368 static DEFINE_SPINLOCK(client_lock);
369
370 /* Hash tables for nfs4_clientid state */
371 #define CLIENT_HASH_BITS                 4
372 #define CLIENT_HASH_SIZE                (1 << CLIENT_HASH_BITS)
373 #define CLIENT_HASH_MASK                (CLIENT_HASH_SIZE - 1)
374
375 static unsigned int clientid_hashval(u32 id)
376 {
377         return id & CLIENT_HASH_MASK;
378 }
379
380 static unsigned int clientstr_hashval(const char *name)
381 {
382         return opaque_hashval(name, 8) & CLIENT_HASH_MASK;
383 }
384
385 /*
386  * reclaim_str_hashtbl[] holds known client info from previous reset/reboot
387  * used in reboot/reset lease grace period processing
388  *
389  * conf_id_hashtbl[], and conf_str_hashtbl[] hold confirmed
390  * setclientid_confirmed info. 
391  *
392  * unconf_str_hastbl[] and unconf_id_hashtbl[] hold unconfirmed 
393  * setclientid info.
394  *
395  * client_lru holds client queue ordered by nfs4_client.cl_time
396  * for lease renewal.
397  *
398  * close_lru holds (open) stateowner queue ordered by nfs4_stateowner.so_time
399  * for last close replay.
400  */
401 static struct list_head reclaim_str_hashtbl[CLIENT_HASH_SIZE];
402 static int reclaim_str_hashtbl_size = 0;
403 static struct list_head conf_id_hashtbl[CLIENT_HASH_SIZE];
404 static struct list_head conf_str_hashtbl[CLIENT_HASH_SIZE];
405 static struct list_head unconf_str_hashtbl[CLIENT_HASH_SIZE];
406 static struct list_head unconf_id_hashtbl[CLIENT_HASH_SIZE];
407 static struct list_head client_lru;
408 static struct list_head close_lru;
409
410 /*
411  * We store the NONE, READ, WRITE, and BOTH bits separately in the
412  * st_{access,deny}_bmap field of the stateid, in order to track not
413  * only what share bits are currently in force, but also what
414  * combinations of share bits previous opens have used.  This allows us
415  * to enforce the recommendation of rfc 3530 14.2.19 that the server
416  * return an error if the client attempt to downgrade to a combination
417  * of share bits not explicable by closing some of its previous opens.
418  *
419  * XXX: This enforcement is actually incomplete, since we don't keep
420  * track of access/deny bit combinations; so, e.g., we allow:
421  *
422  *      OPEN allow read, deny write
423  *      OPEN allow both, deny none
424  *      DOWNGRADE allow read, deny none
425  *
426  * which we should reject.
427  */
428 static void
429 set_access(unsigned int *access, unsigned long bmap) {
430         int i;
431
432         *access = 0;
433         for (i = 1; i < 4; i++) {
434                 if (test_bit(i, &bmap))
435                         *access |= i;
436         }
437 }
438
439 static void
440 set_deny(unsigned int *deny, unsigned long bmap) {
441         int i;
442
443         *deny = 0;
444         for (i = 0; i < 4; i++) {
445                 if (test_bit(i, &bmap))
446                         *deny |= i ;
447         }
448 }
449
450 static int
451 test_share(struct nfs4_ol_stateid *stp, struct nfsd4_open *open) {
452         unsigned int access, deny;
453
454         set_access(&access, stp->st_access_bmap);
455         set_deny(&deny, stp->st_deny_bmap);
456         if ((access & open->op_share_deny) || (deny & open->op_share_access))
457                 return 0;
458         return 1;
459 }
460
461 static int nfs4_access_to_omode(u32 access)
462 {
463         switch (access & NFS4_SHARE_ACCESS_BOTH) {
464         case NFS4_SHARE_ACCESS_READ:
465                 return O_RDONLY;
466         case NFS4_SHARE_ACCESS_WRITE:
467                 return O_WRONLY;
468         case NFS4_SHARE_ACCESS_BOTH:
469                 return O_RDWR;
470         }
471         BUG();
472 }
473
474 static void unhash_generic_stateid(struct nfs4_ol_stateid *stp)
475 {
476         list_del(&stp->st_perfile);
477         list_del(&stp->st_perstateowner);
478 }
479
480 static void close_generic_stateid(struct nfs4_ol_stateid *stp)
481 {
482         int i;
483
484         if (stp->st_access_bmap) {
485                 for (i = 1; i < 4; i++) {
486                         if (test_bit(i, &stp->st_access_bmap))
487                                 nfs4_file_put_access(stp->st_file,
488                                                 nfs4_access_to_omode(i));
489                         __clear_bit(i, &stp->st_access_bmap);
490                 }
491         }
492         put_nfs4_file(stp->st_file);
493         stp->st_file = NULL;
494 }
495
496 static void free_generic_stateid(struct nfs4_ol_stateid *stp)
497 {
498         kmem_cache_free(stateid_slab, stp);
499 }
500
501 static void release_lock_stateid(struct nfs4_ol_stateid *stp)
502 {
503         struct file *file;
504
505         unhash_generic_stateid(stp);
506         unhash_stid(&stp->st_stid);
507         file = find_any_file(stp->st_file);
508         if (file)
509                 locks_remove_posix(file, (fl_owner_t)lockowner(stp->st_stateowner));
510         close_generic_stateid(stp);
511         free_generic_stateid(stp);
512 }
513
514 static void unhash_lockowner(struct nfs4_lockowner *lo)
515 {
516         struct nfs4_ol_stateid *stp;
517
518         list_del(&lo->lo_owner.so_strhash);
519         list_del(&lo->lo_perstateid);
520         while (!list_empty(&lo->lo_owner.so_stateids)) {
521                 stp = list_first_entry(&lo->lo_owner.so_stateids,
522                                 struct nfs4_ol_stateid, st_perstateowner);
523                 release_lock_stateid(stp);
524         }
525 }
526
527 static void release_lockowner(struct nfs4_lockowner *lo)
528 {
529         unhash_lockowner(lo);
530         nfs4_free_lockowner(lo);
531 }
532
533 static void
534 release_stateid_lockowners(struct nfs4_ol_stateid *open_stp)
535 {
536         struct nfs4_lockowner *lo;
537
538         while (!list_empty(&open_stp->st_lockowners)) {
539                 lo = list_entry(open_stp->st_lockowners.next,
540                                 struct nfs4_lockowner, lo_perstateid);
541                 release_lockowner(lo);
542         }
543 }
544
545 static void unhash_open_stateid(struct nfs4_ol_stateid *stp)
546 {
547         unhash_generic_stateid(stp);
548         release_stateid_lockowners(stp);
549         close_generic_stateid(stp);
550 }
551
552 static void release_open_stateid(struct nfs4_ol_stateid *stp)
553 {
554         unhash_open_stateid(stp);
555         unhash_stid(&stp->st_stid);
556         free_generic_stateid(stp);
557 }
558
559 static void unhash_openowner(struct nfs4_openowner *oo)
560 {
561         struct nfs4_ol_stateid *stp;
562
563         list_del(&oo->oo_owner.so_strhash);
564         list_del(&oo->oo_perclient);
565         while (!list_empty(&oo->oo_owner.so_stateids)) {
566                 stp = list_first_entry(&oo->oo_owner.so_stateids,
567                                 struct nfs4_ol_stateid, st_perstateowner);
568                 release_open_stateid(stp);
569         }
570 }
571
572 static void release_last_closed_stateid(struct nfs4_openowner *oo)
573 {
574         struct nfs4_ol_stateid *s = oo->oo_last_closed_stid;
575
576         if (s) {
577                 unhash_stid(&s->st_stid);
578                 free_generic_stateid(s);
579                 oo->oo_last_closed_stid = NULL;
580         }
581 }
582
583 static void release_openowner(struct nfs4_openowner *oo)
584 {
585         unhash_openowner(oo);
586         list_del(&oo->oo_close_lru);
587         release_last_closed_stateid(oo);
588         nfs4_free_openowner(oo);
589 }
590
591 #define SESSION_HASH_SIZE       512
592 static struct list_head sessionid_hashtbl[SESSION_HASH_SIZE];
593
594 static inline int
595 hash_sessionid(struct nfs4_sessionid *sessionid)
596 {
597         struct nfsd4_sessionid *sid = (struct nfsd4_sessionid *)sessionid;
598
599         return sid->sequence % SESSION_HASH_SIZE;
600 }
601
602 static inline void
603 dump_sessionid(const char *fn, struct nfs4_sessionid *sessionid)
604 {
605         u32 *ptr = (u32 *)(&sessionid->data[0]);
606         dprintk("%s: %u:%u:%u:%u\n", fn, ptr[0], ptr[1], ptr[2], ptr[3]);
607 }
608
609 static void
610 gen_sessionid(struct nfsd4_session *ses)
611 {
612         struct nfs4_client *clp = ses->se_client;
613         struct nfsd4_sessionid *sid;
614
615         sid = (struct nfsd4_sessionid *)ses->se_sessionid.data;
616         sid->clientid = clp->cl_clientid;
617         sid->sequence = current_sessionid++;
618         sid->reserved = 0;
619 }
620
621 /*
622  * The protocol defines ca_maxresponssize_cached to include the size of
623  * the rpc header, but all we need to cache is the data starting after
624  * the end of the initial SEQUENCE operation--the rest we regenerate
625  * each time.  Therefore we can advertise a ca_maxresponssize_cached
626  * value that is the number of bytes in our cache plus a few additional
627  * bytes.  In order to stay on the safe side, and not promise more than
628  * we can cache, those additional bytes must be the minimum possible: 24
629  * bytes of rpc header (xid through accept state, with AUTH_NULL
630  * verifier), 12 for the compound header (with zero-length tag), and 44
631  * for the SEQUENCE op response:
632  */
633 #define NFSD_MIN_HDR_SEQ_SZ  (24 + 12 + 44)
634
635 static void
636 free_session_slots(struct nfsd4_session *ses)
637 {
638         int i;
639
640         for (i = 0; i < ses->se_fchannel.maxreqs; i++)
641                 kfree(ses->se_slots[i]);
642 }
643
644 /*
645  * We don't actually need to cache the rpc and session headers, so we
646  * can allocate a little less for each slot:
647  */
648 static inline int slot_bytes(struct nfsd4_channel_attrs *ca)
649 {
650         return ca->maxresp_cached - NFSD_MIN_HDR_SEQ_SZ;
651 }
652
653 static int nfsd4_sanitize_slot_size(u32 size)
654 {
655         size -= NFSD_MIN_HDR_SEQ_SZ; /* We don't cache the rpc header */
656         size = min_t(u32, size, NFSD_SLOT_CACHE_SIZE);
657
658         return size;
659 }
660
661 /*
662  * XXX: If we run out of reserved DRC memory we could (up to a point)
663  * re-negotiate active sessions and reduce their slot usage to make
664  * rooom for new connections. For now we just fail the create session.
665  */
666 static int nfsd4_get_drc_mem(int slotsize, u32 num)
667 {
668         int avail;
669
670         num = min_t(u32, num, NFSD_MAX_SLOTS_PER_SESSION);
671
672         spin_lock(&nfsd_drc_lock);
673         avail = min_t(int, NFSD_MAX_MEM_PER_SESSION,
674                         nfsd_drc_max_mem - nfsd_drc_mem_used);
675         num = min_t(int, num, avail / slotsize);
676         nfsd_drc_mem_used += num * slotsize;
677         spin_unlock(&nfsd_drc_lock);
678
679         return num;
680 }
681
682 static void nfsd4_put_drc_mem(int slotsize, int num)
683 {
684         spin_lock(&nfsd_drc_lock);
685         nfsd_drc_mem_used -= slotsize * num;
686         spin_unlock(&nfsd_drc_lock);
687 }
688
689 static struct nfsd4_session *alloc_session(int slotsize, int numslots)
690 {
691         struct nfsd4_session *new;
692         int mem, i;
693
694         BUILD_BUG_ON(NFSD_MAX_SLOTS_PER_SESSION * sizeof(struct nfsd4_slot *)
695                         + sizeof(struct nfsd4_session) > PAGE_SIZE);
696         mem = numslots * sizeof(struct nfsd4_slot *);
697
698         new = kzalloc(sizeof(*new) + mem, GFP_KERNEL);
699         if (!new)
700                 return NULL;
701         /* allocate each struct nfsd4_slot and data cache in one piece */
702         for (i = 0; i < numslots; i++) {
703                 mem = sizeof(struct nfsd4_slot) + slotsize;
704                 new->se_slots[i] = kzalloc(mem, GFP_KERNEL);
705                 if (!new->se_slots[i])
706                         goto out_free;
707         }
708         return new;
709 out_free:
710         while (i--)
711                 kfree(new->se_slots[i]);
712         kfree(new);
713         return NULL;
714 }
715
716 static void init_forechannel_attrs(struct nfsd4_channel_attrs *new, struct nfsd4_channel_attrs *req, int numslots, int slotsize)
717 {
718         u32 maxrpc = nfsd_serv->sv_max_mesg;
719
720         new->maxreqs = numslots;
721         new->maxresp_cached = min_t(u32, req->maxresp_cached,
722                                         slotsize + NFSD_MIN_HDR_SEQ_SZ);
723         new->maxreq_sz = min_t(u32, req->maxreq_sz, maxrpc);
724         new->maxresp_sz = min_t(u32, req->maxresp_sz, maxrpc);
725         new->maxops = min_t(u32, req->maxops, NFSD_MAX_OPS_PER_COMPOUND);
726 }
727
728 static void free_conn(struct nfsd4_conn *c)
729 {
730         svc_xprt_put(c->cn_xprt);
731         kfree(c);
732 }
733
734 static void nfsd4_conn_lost(struct svc_xpt_user *u)
735 {
736         struct nfsd4_conn *c = container_of(u, struct nfsd4_conn, cn_xpt_user);
737         struct nfs4_client *clp = c->cn_session->se_client;
738
739         spin_lock(&clp->cl_lock);
740         if (!list_empty(&c->cn_persession)) {
741                 list_del(&c->cn_persession);
742                 free_conn(c);
743         }
744         spin_unlock(&clp->cl_lock);
745         nfsd4_probe_callback(clp);
746 }
747
748 static struct nfsd4_conn *alloc_conn(struct svc_rqst *rqstp, u32 flags)
749 {
750         struct nfsd4_conn *conn;
751
752         conn = kmalloc(sizeof(struct nfsd4_conn), GFP_KERNEL);
753         if (!conn)
754                 return NULL;
755         svc_xprt_get(rqstp->rq_xprt);
756         conn->cn_xprt = rqstp->rq_xprt;
757         conn->cn_flags = flags;
758         INIT_LIST_HEAD(&conn->cn_xpt_user.list);
759         return conn;
760 }
761
762 static void __nfsd4_hash_conn(struct nfsd4_conn *conn, struct nfsd4_session *ses)
763 {
764         conn->cn_session = ses;
765         list_add(&conn->cn_persession, &ses->se_conns);
766 }
767
768 static void nfsd4_hash_conn(struct nfsd4_conn *conn, struct nfsd4_session *ses)
769 {
770         struct nfs4_client *clp = ses->se_client;
771
772         spin_lock(&clp->cl_lock);
773         __nfsd4_hash_conn(conn, ses);
774         spin_unlock(&clp->cl_lock);
775 }
776
777 static int nfsd4_register_conn(struct nfsd4_conn *conn)
778 {
779         conn->cn_xpt_user.callback = nfsd4_conn_lost;
780         return register_xpt_user(conn->cn_xprt, &conn->cn_xpt_user);
781 }
782
783 static __be32 nfsd4_new_conn(struct svc_rqst *rqstp, struct nfsd4_session *ses, u32 dir)
784 {
785         struct nfsd4_conn *conn;
786         int ret;
787
788         conn = alloc_conn(rqstp, dir);
789         if (!conn)
790                 return nfserr_jukebox;
791         nfsd4_hash_conn(conn, ses);
792         ret = nfsd4_register_conn(conn);
793         if (ret)
794                 /* oops; xprt is already down: */
795                 nfsd4_conn_lost(&conn->cn_xpt_user);
796         return nfs_ok;
797 }
798
799 static __be32 nfsd4_new_conn_from_crses(struct svc_rqst *rqstp, struct nfsd4_session *ses)
800 {
801         u32 dir = NFS4_CDFC4_FORE;
802
803         if (ses->se_flags & SESSION4_BACK_CHAN)
804                 dir |= NFS4_CDFC4_BACK;
805
806         return nfsd4_new_conn(rqstp, ses, dir);
807 }
808
809 /* must be called under client_lock */
810 static void nfsd4_del_conns(struct nfsd4_session *s)
811 {
812         struct nfs4_client *clp = s->se_client;
813         struct nfsd4_conn *c;
814
815         spin_lock(&clp->cl_lock);
816         while (!list_empty(&s->se_conns)) {
817                 c = list_first_entry(&s->se_conns, struct nfsd4_conn, cn_persession);
818                 list_del_init(&c->cn_persession);
819                 spin_unlock(&clp->cl_lock);
820
821                 unregister_xpt_user(c->cn_xprt, &c->cn_xpt_user);
822                 free_conn(c);
823
824                 spin_lock(&clp->cl_lock);
825         }
826         spin_unlock(&clp->cl_lock);
827 }
828
829 void free_session(struct kref *kref)
830 {
831         struct nfsd4_session *ses;
832         int mem;
833
834         ses = container_of(kref, struct nfsd4_session, se_ref);
835         nfsd4_del_conns(ses);
836         spin_lock(&nfsd_drc_lock);
837         mem = ses->se_fchannel.maxreqs * slot_bytes(&ses->se_fchannel);
838         nfsd_drc_mem_used -= mem;
839         spin_unlock(&nfsd_drc_lock);
840         free_session_slots(ses);
841         kfree(ses);
842 }
843
844 static struct nfsd4_session *alloc_init_session(struct svc_rqst *rqstp, struct nfs4_client *clp, struct nfsd4_create_session *cses)
845 {
846         struct nfsd4_session *new;
847         struct nfsd4_channel_attrs *fchan = &cses->fore_channel;
848         int numslots, slotsize;
849         int status;
850         int idx;
851
852         /*
853          * Note decreasing slot size below client's request may
854          * make it difficult for client to function correctly, whereas
855          * decreasing the number of slots will (just?) affect
856          * performance.  When short on memory we therefore prefer to
857          * decrease number of slots instead of their size.
858          */
859         slotsize = nfsd4_sanitize_slot_size(fchan->maxresp_cached);
860         numslots = nfsd4_get_drc_mem(slotsize, fchan->maxreqs);
861         if (numslots < 1)
862                 return NULL;
863
864         new = alloc_session(slotsize, numslots);
865         if (!new) {
866                 nfsd4_put_drc_mem(slotsize, fchan->maxreqs);
867                 return NULL;
868         }
869         init_forechannel_attrs(&new->se_fchannel, fchan, numslots, slotsize);
870
871         new->se_client = clp;
872         gen_sessionid(new);
873
874         INIT_LIST_HEAD(&new->se_conns);
875
876         new->se_cb_seq_nr = 1;
877         new->se_flags = cses->flags;
878         new->se_cb_prog = cses->callback_prog;
879         kref_init(&new->se_ref);
880         idx = hash_sessionid(&new->se_sessionid);
881         spin_lock(&client_lock);
882         list_add(&new->se_hash, &sessionid_hashtbl[idx]);
883         spin_lock(&clp->cl_lock);
884         list_add(&new->se_perclnt, &clp->cl_sessions);
885         spin_unlock(&clp->cl_lock);
886         spin_unlock(&client_lock);
887
888         status = nfsd4_new_conn_from_crses(rqstp, new);
889         /* whoops: benny points out, status is ignored! (err, or bogus) */
890         if (status) {
891                 free_session(&new->se_ref);
892                 return NULL;
893         }
894         if (cses->flags & SESSION4_BACK_CHAN) {
895                 struct sockaddr *sa = svc_addr(rqstp);
896                 /*
897                  * This is a little silly; with sessions there's no real
898                  * use for the callback address.  Use the peer address
899                  * as a reasonable default for now, but consider fixing
900                  * the rpc client not to require an address in the
901                  * future:
902                  */
903                 rpc_copy_addr((struct sockaddr *)&clp->cl_cb_conn.cb_addr, sa);
904                 clp->cl_cb_conn.cb_addrlen = svc_addr_len(sa);
905         }
906         nfsd4_probe_callback(clp);
907         return new;
908 }
909
910 /* caller must hold client_lock */
911 static struct nfsd4_session *
912 find_in_sessionid_hashtbl(struct nfs4_sessionid *sessionid)
913 {
914         struct nfsd4_session *elem;
915         int idx;
916
917         dump_sessionid(__func__, sessionid);
918         idx = hash_sessionid(sessionid);
919         /* Search in the appropriate list */
920         list_for_each_entry(elem, &sessionid_hashtbl[idx], se_hash) {
921                 if (!memcmp(elem->se_sessionid.data, sessionid->data,
922                             NFS4_MAX_SESSIONID_LEN)) {
923                         return elem;
924                 }
925         }
926
927         dprintk("%s: session not found\n", __func__);
928         return NULL;
929 }
930
931 /* caller must hold client_lock */
932 static void
933 unhash_session(struct nfsd4_session *ses)
934 {
935         list_del(&ses->se_hash);
936         spin_lock(&ses->se_client->cl_lock);
937         list_del(&ses->se_perclnt);
938         spin_unlock(&ses->se_client->cl_lock);
939 }
940
941 /* must be called under the client_lock */
942 static inline void
943 renew_client_locked(struct nfs4_client *clp)
944 {
945         if (is_client_expired(clp)) {
946                 dprintk("%s: client (clientid %08x/%08x) already expired\n",
947                         __func__,
948                         clp->cl_clientid.cl_boot,
949                         clp->cl_clientid.cl_id);
950                 return;
951         }
952
953         dprintk("renewing client (clientid %08x/%08x)\n", 
954                         clp->cl_clientid.cl_boot, 
955                         clp->cl_clientid.cl_id);
956         list_move_tail(&clp->cl_lru, &client_lru);
957         clp->cl_time = get_seconds();
958 }
959
960 static inline void
961 renew_client(struct nfs4_client *clp)
962 {
963         spin_lock(&client_lock);
964         renew_client_locked(clp);
965         spin_unlock(&client_lock);
966 }
967
968 /* SETCLIENTID and SETCLIENTID_CONFIRM Helper functions */
969 static int
970 STALE_CLIENTID(clientid_t *clid)
971 {
972         if (clid->cl_boot == boot_time)
973                 return 0;
974         dprintk("NFSD stale clientid (%08x/%08x) boot_time %08lx\n",
975                 clid->cl_boot, clid->cl_id, boot_time);
976         return 1;
977 }
978
979 /* 
980  * XXX Should we use a slab cache ?
981  * This type of memory management is somewhat inefficient, but we use it
982  * anyway since SETCLIENTID is not a common operation.
983  */
984 static struct nfs4_client *alloc_client(struct xdr_netobj name)
985 {
986         struct nfs4_client *clp;
987
988         clp = kzalloc(sizeof(struct nfs4_client), GFP_KERNEL);
989         if (clp == NULL)
990                 return NULL;
991         clp->cl_name.data = kmalloc(name.len, GFP_KERNEL);
992         if (clp->cl_name.data == NULL) {
993                 kfree(clp);
994                 return NULL;
995         }
996         memcpy(clp->cl_name.data, name.data, name.len);
997         clp->cl_name.len = name.len;
998         INIT_LIST_HEAD(&clp->cl_sessions);
999         idr_init(&clp->cl_stateids);
1000         atomic_set(&clp->cl_refcount, 0);
1001         clp->cl_cb_state = NFSD4_CB_UNKNOWN;
1002         INIT_LIST_HEAD(&clp->cl_idhash);
1003         INIT_LIST_HEAD(&clp->cl_strhash);
1004         INIT_LIST_HEAD(&clp->cl_openowners);
1005         INIT_LIST_HEAD(&clp->cl_delegations);
1006         INIT_LIST_HEAD(&clp->cl_lru);
1007         INIT_LIST_HEAD(&clp->cl_callbacks);
1008         spin_lock_init(&clp->cl_lock);
1009         rpc_init_wait_queue(&clp->cl_cb_waitq, "Backchannel slot table");
1010         return clp;
1011 }
1012
1013 static inline void
1014 free_client(struct nfs4_client *clp)
1015 {
1016         while (!list_empty(&clp->cl_sessions)) {
1017                 struct nfsd4_session *ses;
1018                 ses = list_entry(clp->cl_sessions.next, struct nfsd4_session,
1019                                 se_perclnt);
1020                 list_del(&ses->se_perclnt);
1021                 nfsd4_put_session(ses);
1022         }
1023         rpc_destroy_wait_queue(&clp->cl_cb_waitq);
1024         if (clp->cl_cred.cr_group_info)
1025                 put_group_info(clp->cl_cred.cr_group_info);
1026         kfree(clp->cl_principal);
1027         kfree(clp->cl_name.data);
1028         idr_remove_all(&clp->cl_stateids);
1029         idr_destroy(&clp->cl_stateids);
1030         kfree(clp);
1031 }
1032
1033 void
1034 release_session_client(struct nfsd4_session *session)
1035 {
1036         struct nfs4_client *clp = session->se_client;
1037
1038         if (!atomic_dec_and_lock(&clp->cl_refcount, &client_lock))
1039                 return;
1040         if (is_client_expired(clp)) {
1041                 free_client(clp);
1042                 session->se_client = NULL;
1043         } else
1044                 renew_client_locked(clp);
1045         spin_unlock(&client_lock);
1046 }
1047
1048 /* must be called under the client_lock */
1049 static inline void
1050 unhash_client_locked(struct nfs4_client *clp)
1051 {
1052         struct nfsd4_session *ses;
1053
1054         mark_client_expired(clp);
1055         list_del(&clp->cl_lru);
1056         spin_lock(&clp->cl_lock);
1057         list_for_each_entry(ses, &clp->cl_sessions, se_perclnt)
1058                 list_del_init(&ses->se_hash);
1059         spin_unlock(&clp->cl_lock);
1060 }
1061
1062 static void
1063 expire_client(struct nfs4_client *clp)
1064 {
1065         struct nfs4_openowner *oo;
1066         struct nfs4_delegation *dp;
1067         struct list_head reaplist;
1068
1069         INIT_LIST_HEAD(&reaplist);
1070         spin_lock(&recall_lock);
1071         while (!list_empty(&clp->cl_delegations)) {
1072                 dp = list_entry(clp->cl_delegations.next, struct nfs4_delegation, dl_perclnt);
1073                 list_del_init(&dp->dl_perclnt);
1074                 list_move(&dp->dl_recall_lru, &reaplist);
1075         }
1076         spin_unlock(&recall_lock);
1077         while (!list_empty(&reaplist)) {
1078                 dp = list_entry(reaplist.next, struct nfs4_delegation, dl_recall_lru);
1079                 list_del_init(&dp->dl_recall_lru);
1080                 unhash_delegation(dp);
1081         }
1082         while (!list_empty(&clp->cl_openowners)) {
1083                 oo = list_entry(clp->cl_openowners.next, struct nfs4_openowner, oo_perclient);
1084                 release_openowner(oo);
1085         }
1086         nfsd4_shutdown_callback(clp);
1087         if (clp->cl_cb_conn.cb_xprt)
1088                 svc_xprt_put(clp->cl_cb_conn.cb_xprt);
1089         list_del(&clp->cl_idhash);
1090         list_del(&clp->cl_strhash);
1091         spin_lock(&client_lock);
1092         unhash_client_locked(clp);
1093         if (atomic_read(&clp->cl_refcount) == 0)
1094                 free_client(clp);
1095         spin_unlock(&client_lock);
1096 }
1097
1098 static void copy_verf(struct nfs4_client *target, nfs4_verifier *source)
1099 {
1100         memcpy(target->cl_verifier.data, source->data,
1101                         sizeof(target->cl_verifier.data));
1102 }
1103
1104 static void copy_clid(struct nfs4_client *target, struct nfs4_client *source)
1105 {
1106         target->cl_clientid.cl_boot = source->cl_clientid.cl_boot; 
1107         target->cl_clientid.cl_id = source->cl_clientid.cl_id; 
1108 }
1109
1110 static void copy_cred(struct svc_cred *target, struct svc_cred *source)
1111 {
1112         target->cr_uid = source->cr_uid;
1113         target->cr_gid = source->cr_gid;
1114         target->cr_group_info = source->cr_group_info;
1115         get_group_info(target->cr_group_info);
1116 }
1117
1118 static int same_name(const char *n1, const char *n2)
1119 {
1120         return 0 == memcmp(n1, n2, HEXDIR_LEN);
1121 }
1122
1123 static int
1124 same_verf(nfs4_verifier *v1, nfs4_verifier *v2)
1125 {
1126         return 0 == memcmp(v1->data, v2->data, sizeof(v1->data));
1127 }
1128
1129 static int
1130 same_clid(clientid_t *cl1, clientid_t *cl2)
1131 {
1132         return (cl1->cl_boot == cl2->cl_boot) && (cl1->cl_id == cl2->cl_id);
1133 }
1134
1135 /* XXX what about NGROUP */
1136 static int
1137 same_creds(struct svc_cred *cr1, struct svc_cred *cr2)
1138 {
1139         return cr1->cr_uid == cr2->cr_uid;
1140 }
1141
1142 static void gen_clid(struct nfs4_client *clp)
1143 {
1144         static u32 current_clientid = 1;
1145
1146         clp->cl_clientid.cl_boot = boot_time;
1147         clp->cl_clientid.cl_id = current_clientid++; 
1148 }
1149
1150 static void gen_confirm(struct nfs4_client *clp)
1151 {
1152         static u32 i;
1153         u32 *p;
1154
1155         p = (u32 *)clp->cl_confirm.data;
1156         *p++ = get_seconds();
1157         *p++ = i++;
1158 }
1159
1160 static struct nfs4_stid *find_stateid(struct nfs4_client *cl, stateid_t *t)
1161 {
1162         return idr_find(&cl->cl_stateids, t->si_opaque.so_id);
1163 }
1164
1165 static struct nfs4_stid *find_stateid_by_type(struct nfs4_client *cl, stateid_t *t, char typemask)
1166 {
1167         struct nfs4_stid *s;
1168
1169         s = find_stateid(cl, t);
1170         if (!s)
1171                 return NULL;
1172         if (typemask & s->sc_type)
1173                 return s;
1174         return NULL;
1175 }
1176
1177 static struct nfs4_client *create_client(struct xdr_netobj name, char *recdir,
1178                 struct svc_rqst *rqstp, nfs4_verifier *verf)
1179 {
1180         struct nfs4_client *clp;
1181         struct sockaddr *sa = svc_addr(rqstp);
1182         char *princ;
1183
1184         clp = alloc_client(name);
1185         if (clp == NULL)
1186                 return NULL;
1187
1188
1189         princ = svc_gss_principal(rqstp);
1190         if (princ) {
1191                 clp->cl_principal = kstrdup(princ, GFP_KERNEL);
1192                 if (clp->cl_principal == NULL) {
1193                         free_client(clp);
1194                         return NULL;
1195                 }
1196         }
1197
1198         memcpy(clp->cl_recdir, recdir, HEXDIR_LEN);
1199         INIT_WORK(&clp->cl_cb_null.cb_work, nfsd4_do_callback_rpc);
1200         clp->cl_time = get_seconds();
1201         clear_bit(0, &clp->cl_cb_slot_busy);
1202         copy_verf(clp, verf);
1203         rpc_copy_addr((struct sockaddr *) &clp->cl_addr, sa);
1204         clp->cl_flavor = rqstp->rq_flavor;
1205         copy_cred(&clp->cl_cred, &rqstp->rq_cred);
1206         gen_confirm(clp);
1207         clp->cl_cb_session = NULL;
1208         return clp;
1209 }
1210
1211 static void
1212 add_to_unconfirmed(struct nfs4_client *clp, unsigned int strhashval)
1213 {
1214         unsigned int idhashval;
1215
1216         list_add(&clp->cl_strhash, &unconf_str_hashtbl[strhashval]);
1217         idhashval = clientid_hashval(clp->cl_clientid.cl_id);
1218         list_add(&clp->cl_idhash, &unconf_id_hashtbl[idhashval]);
1219         renew_client(clp);
1220 }
1221
1222 static void
1223 move_to_confirmed(struct nfs4_client *clp)
1224 {
1225         unsigned int idhashval = clientid_hashval(clp->cl_clientid.cl_id);
1226         unsigned int strhashval;
1227
1228         dprintk("NFSD: move_to_confirm nfs4_client %p\n", clp);
1229         list_move(&clp->cl_idhash, &conf_id_hashtbl[idhashval]);
1230         strhashval = clientstr_hashval(clp->cl_recdir);
1231         list_move(&clp->cl_strhash, &conf_str_hashtbl[strhashval]);
1232         renew_client(clp);
1233 }
1234
1235 static struct nfs4_client *
1236 find_confirmed_client(clientid_t *clid)
1237 {
1238         struct nfs4_client *clp;
1239         unsigned int idhashval = clientid_hashval(clid->cl_id);
1240
1241         list_for_each_entry(clp, &conf_id_hashtbl[idhashval], cl_idhash) {
1242                 if (same_clid(&clp->cl_clientid, clid)) {
1243                         renew_client(clp);
1244                         return clp;
1245                 }
1246         }
1247         return NULL;
1248 }
1249
1250 static struct nfs4_client *
1251 find_unconfirmed_client(clientid_t *clid)
1252 {
1253         struct nfs4_client *clp;
1254         unsigned int idhashval = clientid_hashval(clid->cl_id);
1255
1256         list_for_each_entry(clp, &unconf_id_hashtbl[idhashval], cl_idhash) {
1257                 if (same_clid(&clp->cl_clientid, clid))
1258                         return clp;
1259         }
1260         return NULL;
1261 }
1262
1263 static bool clp_used_exchangeid(struct nfs4_client *clp)
1264 {
1265         return clp->cl_exchange_flags != 0;
1266
1267
1268 static struct nfs4_client *
1269 find_confirmed_client_by_str(const char *dname, unsigned int hashval)
1270 {
1271         struct nfs4_client *clp;
1272
1273         list_for_each_entry(clp, &conf_str_hashtbl[hashval], cl_strhash) {
1274                 if (same_name(clp->cl_recdir, dname))
1275                         return clp;
1276         }
1277         return NULL;
1278 }
1279
1280 static struct nfs4_client *
1281 find_unconfirmed_client_by_str(const char *dname, unsigned int hashval)
1282 {
1283         struct nfs4_client *clp;
1284
1285         list_for_each_entry(clp, &unconf_str_hashtbl[hashval], cl_strhash) {
1286                 if (same_name(clp->cl_recdir, dname))
1287                         return clp;
1288         }
1289         return NULL;
1290 }
1291
1292 static void
1293 gen_callback(struct nfs4_client *clp, struct nfsd4_setclientid *se, struct svc_rqst *rqstp)
1294 {
1295         struct nfs4_cb_conn *conn = &clp->cl_cb_conn;
1296         struct sockaddr *sa = svc_addr(rqstp);
1297         u32 scopeid = rpc_get_scope_id(sa);
1298         unsigned short expected_family;
1299
1300         /* Currently, we only support tcp and tcp6 for the callback channel */
1301         if (se->se_callback_netid_len == 3 &&
1302             !memcmp(se->se_callback_netid_val, "tcp", 3))
1303                 expected_family = AF_INET;
1304         else if (se->se_callback_netid_len == 4 &&
1305                  !memcmp(se->se_callback_netid_val, "tcp6", 4))
1306                 expected_family = AF_INET6;
1307         else
1308                 goto out_err;
1309
1310         conn->cb_addrlen = rpc_uaddr2sockaddr(se->se_callback_addr_val,
1311                                             se->se_callback_addr_len,
1312                                             (struct sockaddr *)&conn->cb_addr,
1313                                             sizeof(conn->cb_addr));
1314
1315         if (!conn->cb_addrlen || conn->cb_addr.ss_family != expected_family)
1316                 goto out_err;
1317
1318         if (conn->cb_addr.ss_family == AF_INET6)
1319                 ((struct sockaddr_in6 *)&conn->cb_addr)->sin6_scope_id = scopeid;
1320
1321         conn->cb_prog = se->se_callback_prog;
1322         conn->cb_ident = se->se_callback_ident;
1323         memcpy(&conn->cb_saddr, &rqstp->rq_daddr, rqstp->rq_daddrlen);
1324         return;
1325 out_err:
1326         conn->cb_addr.ss_family = AF_UNSPEC;
1327         conn->cb_addrlen = 0;
1328         dprintk(KERN_INFO "NFSD: this client (clientid %08x/%08x) "
1329                 "will not receive delegations\n",
1330                 clp->cl_clientid.cl_boot, clp->cl_clientid.cl_id);
1331
1332         return;
1333 }
1334
1335 /*
1336  * Cache a reply. nfsd4_check_drc_limit() has bounded the cache size.
1337  */
1338 void
1339 nfsd4_store_cache_entry(struct nfsd4_compoundres *resp)
1340 {
1341         struct nfsd4_slot *slot = resp->cstate.slot;
1342         unsigned int base;
1343
1344         dprintk("--> %s slot %p\n", __func__, slot);
1345
1346         slot->sl_opcnt = resp->opcnt;
1347         slot->sl_status = resp->cstate.status;
1348
1349         if (nfsd4_not_cached(resp)) {
1350                 slot->sl_datalen = 0;
1351                 return;
1352         }
1353         slot->sl_datalen = (char *)resp->p - (char *)resp->cstate.datap;
1354         base = (char *)resp->cstate.datap -
1355                                         (char *)resp->xbuf->head[0].iov_base;
1356         if (read_bytes_from_xdr_buf(resp->xbuf, base, slot->sl_data,
1357                                     slot->sl_datalen))
1358                 WARN("%s: sessions DRC could not cache compound\n", __func__);
1359         return;
1360 }
1361
1362 /*
1363  * Encode the replay sequence operation from the slot values.
1364  * If cachethis is FALSE encode the uncached rep error on the next
1365  * operation which sets resp->p and increments resp->opcnt for
1366  * nfs4svc_encode_compoundres.
1367  *
1368  */
1369 static __be32
1370 nfsd4_enc_sequence_replay(struct nfsd4_compoundargs *args,
1371                           struct nfsd4_compoundres *resp)
1372 {
1373         struct nfsd4_op *op;
1374         struct nfsd4_slot *slot = resp->cstate.slot;
1375
1376         dprintk("--> %s resp->opcnt %d cachethis %u \n", __func__,
1377                 resp->opcnt, resp->cstate.slot->sl_cachethis);
1378
1379         /* Encode the replayed sequence operation */
1380         op = &args->ops[resp->opcnt - 1];
1381         nfsd4_encode_operation(resp, op);
1382
1383         /* Return nfserr_retry_uncached_rep in next operation. */
1384         if (args->opcnt > 1 && slot->sl_cachethis == 0) {
1385                 op = &args->ops[resp->opcnt++];
1386                 op->status = nfserr_retry_uncached_rep;
1387                 nfsd4_encode_operation(resp, op);
1388         }
1389         return op->status;
1390 }
1391
1392 /*
1393  * The sequence operation is not cached because we can use the slot and
1394  * session values.
1395  */
1396 __be32
1397 nfsd4_replay_cache_entry(struct nfsd4_compoundres *resp,
1398                          struct nfsd4_sequence *seq)
1399 {
1400         struct nfsd4_slot *slot = resp->cstate.slot;
1401         __be32 status;
1402
1403         dprintk("--> %s slot %p\n", __func__, slot);
1404
1405         /* Either returns 0 or nfserr_retry_uncached */
1406         status = nfsd4_enc_sequence_replay(resp->rqstp->rq_argp, resp);
1407         if (status == nfserr_retry_uncached_rep)
1408                 return status;
1409
1410         /* The sequence operation has been encoded, cstate->datap set. */
1411         memcpy(resp->cstate.datap, slot->sl_data, slot->sl_datalen);
1412
1413         resp->opcnt = slot->sl_opcnt;
1414         resp->p = resp->cstate.datap + XDR_QUADLEN(slot->sl_datalen);
1415         status = slot->sl_status;
1416
1417         return status;
1418 }
1419
1420 /*
1421  * Set the exchange_id flags returned by the server.
1422  */
1423 static void
1424 nfsd4_set_ex_flags(struct nfs4_client *new, struct nfsd4_exchange_id *clid)
1425 {
1426         /* pNFS is not supported */
1427         new->cl_exchange_flags |= EXCHGID4_FLAG_USE_NON_PNFS;
1428
1429         /* Referrals are supported, Migration is not. */
1430         new->cl_exchange_flags |= EXCHGID4_FLAG_SUPP_MOVED_REFER;
1431
1432         /* set the wire flags to return to client. */
1433         clid->flags = new->cl_exchange_flags;
1434 }
1435
1436 __be32
1437 nfsd4_exchange_id(struct svc_rqst *rqstp,
1438                   struct nfsd4_compound_state *cstate,
1439                   struct nfsd4_exchange_id *exid)
1440 {
1441         struct nfs4_client *unconf, *conf, *new;
1442         int status;
1443         unsigned int            strhashval;
1444         char                    dname[HEXDIR_LEN];
1445         char                    addr_str[INET6_ADDRSTRLEN];
1446         nfs4_verifier           verf = exid->verifier;
1447         struct sockaddr         *sa = svc_addr(rqstp);
1448
1449         rpc_ntop(sa, addr_str, sizeof(addr_str));
1450         dprintk("%s rqstp=%p exid=%p clname.len=%u clname.data=%p "
1451                 "ip_addr=%s flags %x, spa_how %d\n",
1452                 __func__, rqstp, exid, exid->clname.len, exid->clname.data,
1453                 addr_str, exid->flags, exid->spa_how);
1454
1455         if (exid->flags & ~EXCHGID4_FLAG_MASK_A)
1456                 return nfserr_inval;
1457
1458         /* Currently only support SP4_NONE */
1459         switch (exid->spa_how) {
1460         case SP4_NONE:
1461                 break;
1462         case SP4_SSV:
1463                 return nfserr_serverfault;
1464         default:
1465                 BUG();                          /* checked by xdr code */
1466         case SP4_MACH_CRED:
1467                 return nfserr_serverfault;      /* no excuse :-/ */
1468         }
1469
1470         status = nfs4_make_rec_clidname(dname, &exid->clname);
1471
1472         if (status)
1473                 goto error;
1474
1475         strhashval = clientstr_hashval(dname);
1476
1477         nfs4_lock_state();
1478         status = nfs_ok;
1479
1480         conf = find_confirmed_client_by_str(dname, strhashval);
1481         if (conf) {
1482                 if (!clp_used_exchangeid(conf)) {
1483                         status = nfserr_clid_inuse; /* XXX: ? */
1484                         goto out;
1485                 }
1486                 if (!same_verf(&verf, &conf->cl_verifier)) {
1487                         /* 18.35.4 case 8 */
1488                         if (exid->flags & EXCHGID4_FLAG_UPD_CONFIRMED_REC_A) {
1489                                 status = nfserr_not_same;
1490                                 goto out;
1491                         }
1492                         /* Client reboot: destroy old state */
1493                         expire_client(conf);
1494                         goto out_new;
1495                 }
1496                 if (!same_creds(&conf->cl_cred, &rqstp->rq_cred)) {
1497                         /* 18.35.4 case 9 */
1498                         if (exid->flags & EXCHGID4_FLAG_UPD_CONFIRMED_REC_A) {
1499                                 status = nfserr_perm;
1500                                 goto out;
1501                         }
1502                         expire_client(conf);
1503                         goto out_new;
1504                 }
1505                 /*
1506                  * Set bit when the owner id and verifier map to an already
1507                  * confirmed client id (18.35.3).
1508                  */
1509                 exid->flags |= EXCHGID4_FLAG_CONFIRMED_R;
1510
1511                 /*
1512                  * Falling into 18.35.4 case 2, possible router replay.
1513                  * Leave confirmed record intact and return same result.
1514                  */
1515                 copy_verf(conf, &verf);
1516                 new = conf;
1517                 goto out_copy;
1518         }
1519
1520         /* 18.35.4 case 7 */
1521         if (exid->flags & EXCHGID4_FLAG_UPD_CONFIRMED_REC_A) {
1522                 status = nfserr_noent;
1523                 goto out;
1524         }
1525
1526         unconf  = find_unconfirmed_client_by_str(dname, strhashval);
1527         if (unconf) {
1528                 /*
1529                  * Possible retry or client restart.  Per 18.35.4 case 4,
1530                  * a new unconfirmed record should be generated regardless
1531                  * of whether any properties have changed.
1532                  */
1533                 expire_client(unconf);
1534         }
1535
1536 out_new:
1537         /* Normal case */
1538         new = create_client(exid->clname, dname, rqstp, &verf);
1539         if (new == NULL) {
1540                 status = nfserr_jukebox;
1541                 goto out;
1542         }
1543
1544         gen_clid(new);
1545         add_to_unconfirmed(new, strhashval);
1546 out_copy:
1547         exid->clientid.cl_boot = new->cl_clientid.cl_boot;
1548         exid->clientid.cl_id = new->cl_clientid.cl_id;
1549
1550         exid->seqid = 1;
1551         nfsd4_set_ex_flags(new, exid);
1552
1553         dprintk("nfsd4_exchange_id seqid %d flags %x\n",
1554                 new->cl_cs_slot.sl_seqid, new->cl_exchange_flags);
1555         status = nfs_ok;
1556
1557 out:
1558         nfs4_unlock_state();
1559 error:
1560         dprintk("nfsd4_exchange_id returns %d\n", ntohl(status));
1561         return status;
1562 }
1563
1564 static int
1565 check_slot_seqid(u32 seqid, u32 slot_seqid, int slot_inuse)
1566 {
1567         dprintk("%s enter. seqid %d slot_seqid %d\n", __func__, seqid,
1568                 slot_seqid);
1569
1570         /* The slot is in use, and no response has been sent. */
1571         if (slot_inuse) {
1572                 if (seqid == slot_seqid)
1573                         return nfserr_jukebox;
1574                 else
1575                         return nfserr_seq_misordered;
1576         }
1577         /* Normal */
1578         if (likely(seqid == slot_seqid + 1))
1579                 return nfs_ok;
1580         /* Replay */
1581         if (seqid == slot_seqid)
1582                 return nfserr_replay_cache;
1583         /* Wraparound */
1584         if (seqid == 1 && (slot_seqid + 1) == 0)
1585                 return nfs_ok;
1586         /* Misordered replay or misordered new request */
1587         return nfserr_seq_misordered;
1588 }
1589
1590 /*
1591  * Cache the create session result into the create session single DRC
1592  * slot cache by saving the xdr structure. sl_seqid has been set.
1593  * Do this for solo or embedded create session operations.
1594  */
1595 static void
1596 nfsd4_cache_create_session(struct nfsd4_create_session *cr_ses,
1597                            struct nfsd4_clid_slot *slot, int nfserr)
1598 {
1599         slot->sl_status = nfserr;
1600         memcpy(&slot->sl_cr_ses, cr_ses, sizeof(*cr_ses));
1601 }
1602
1603 static __be32
1604 nfsd4_replay_create_session(struct nfsd4_create_session *cr_ses,
1605                             struct nfsd4_clid_slot *slot)
1606 {
1607         memcpy(cr_ses, &slot->sl_cr_ses, sizeof(*cr_ses));
1608         return slot->sl_status;
1609 }
1610
1611 #define NFSD_MIN_REQ_HDR_SEQ_SZ ((\
1612                         2 * 2 + /* credential,verifier: AUTH_NULL, length 0 */ \
1613                         1 +     /* MIN tag is length with zero, only length */ \
1614                         3 +     /* version, opcount, opcode */ \
1615                         XDR_QUADLEN(NFS4_MAX_SESSIONID_LEN) + \
1616                                 /* seqid, slotID, slotID, cache */ \
1617                         4 ) * sizeof(__be32))
1618
1619 #define NFSD_MIN_RESP_HDR_SEQ_SZ ((\
1620                         2 +     /* verifier: AUTH_NULL, length 0 */\
1621                         1 +     /* status */ \
1622                         1 +     /* MIN tag is length with zero, only length */ \
1623                         3 +     /* opcount, opcode, opstatus*/ \
1624                         XDR_QUADLEN(NFS4_MAX_SESSIONID_LEN) + \
1625                                 /* seqid, slotID, slotID, slotID, status */ \
1626                         5 ) * sizeof(__be32))
1627
1628 static __be32 check_forechannel_attrs(struct nfsd4_channel_attrs fchannel)
1629 {
1630         return fchannel.maxreq_sz < NFSD_MIN_REQ_HDR_SEQ_SZ
1631                 || fchannel.maxresp_sz < NFSD_MIN_RESP_HDR_SEQ_SZ;
1632 }
1633
1634 __be32
1635 nfsd4_create_session(struct svc_rqst *rqstp,
1636                      struct nfsd4_compound_state *cstate,
1637                      struct nfsd4_create_session *cr_ses)
1638 {
1639         struct sockaddr *sa = svc_addr(rqstp);
1640         struct nfs4_client *conf, *unconf;
1641         struct nfsd4_session *new;
1642         struct nfsd4_clid_slot *cs_slot = NULL;
1643         bool confirm_me = false;
1644         int status = 0;
1645
1646         if (cr_ses->flags & ~SESSION4_FLAG_MASK_A)
1647                 return nfserr_inval;
1648
1649         nfs4_lock_state();
1650         unconf = find_unconfirmed_client(&cr_ses->clientid);
1651         conf = find_confirmed_client(&cr_ses->clientid);
1652
1653         if (conf) {
1654                 cs_slot = &conf->cl_cs_slot;
1655                 status = check_slot_seqid(cr_ses->seqid, cs_slot->sl_seqid, 0);
1656                 if (status == nfserr_replay_cache) {
1657                         dprintk("Got a create_session replay! seqid= %d\n",
1658                                 cs_slot->sl_seqid);
1659                         /* Return the cached reply status */
1660                         status = nfsd4_replay_create_session(cr_ses, cs_slot);
1661                         goto out;
1662                 } else if (cr_ses->seqid != cs_slot->sl_seqid + 1) {
1663                         status = nfserr_seq_misordered;
1664                         dprintk("Sequence misordered!\n");
1665                         dprintk("Expected seqid= %d but got seqid= %d\n",
1666                                 cs_slot->sl_seqid, cr_ses->seqid);
1667                         goto out;
1668                 }
1669         } else if (unconf) {
1670                 if (!same_creds(&unconf->cl_cred, &rqstp->rq_cred) ||
1671                     !rpc_cmp_addr(sa, (struct sockaddr *) &unconf->cl_addr)) {
1672                         status = nfserr_clid_inuse;
1673                         goto out;
1674                 }
1675
1676                 cs_slot = &unconf->cl_cs_slot;
1677                 status = check_slot_seqid(cr_ses->seqid, cs_slot->sl_seqid, 0);
1678                 if (status) {
1679                         /* an unconfirmed replay returns misordered */
1680                         status = nfserr_seq_misordered;
1681                         goto out;
1682                 }
1683
1684                 confirm_me = true;
1685                 conf = unconf;
1686         } else {
1687                 status = nfserr_stale_clientid;
1688                 goto out;
1689         }
1690
1691         /*
1692          * XXX: we should probably set this at creation time, and check
1693          * for consistent minorversion use throughout:
1694          */
1695         conf->cl_minorversion = 1;
1696         /*
1697          * We do not support RDMA or persistent sessions
1698          */
1699         cr_ses->flags &= ~SESSION4_PERSIST;
1700         cr_ses->flags &= ~SESSION4_RDMA;
1701
1702         status = nfserr_toosmall;
1703         if (check_forechannel_attrs(cr_ses->fore_channel))
1704                 goto out;
1705
1706         status = nfserr_jukebox;
1707         new = alloc_init_session(rqstp, conf, cr_ses);
1708         if (!new)
1709                 goto out;
1710         status = nfs_ok;
1711         memcpy(cr_ses->sessionid.data, new->se_sessionid.data,
1712                NFS4_MAX_SESSIONID_LEN);
1713         memcpy(&cr_ses->fore_channel, &new->se_fchannel,
1714                 sizeof(struct nfsd4_channel_attrs));
1715         cs_slot->sl_seqid++;
1716         cr_ses->seqid = cs_slot->sl_seqid;
1717
1718         /* cache solo and embedded create sessions under the state lock */
1719         nfsd4_cache_create_session(cr_ses, cs_slot, status);
1720         if (confirm_me)
1721                 move_to_confirmed(conf);
1722 out:
1723         nfs4_unlock_state();
1724         dprintk("%s returns %d\n", __func__, ntohl(status));
1725         return status;
1726 }
1727
1728 static bool nfsd4_last_compound_op(struct svc_rqst *rqstp)
1729 {
1730         struct nfsd4_compoundres *resp = rqstp->rq_resp;
1731         struct nfsd4_compoundargs *argp = rqstp->rq_argp;
1732
1733         return argp->opcnt == resp->opcnt;
1734 }
1735
1736 static __be32 nfsd4_map_bcts_dir(u32 *dir)
1737 {
1738         switch (*dir) {
1739         case NFS4_CDFC4_FORE:
1740         case NFS4_CDFC4_BACK:
1741                 return nfs_ok;
1742         case NFS4_CDFC4_FORE_OR_BOTH:
1743         case NFS4_CDFC4_BACK_OR_BOTH:
1744                 *dir = NFS4_CDFC4_BOTH;
1745                 return nfs_ok;
1746         };
1747         return nfserr_inval;
1748 }
1749
1750 __be32 nfsd4_bind_conn_to_session(struct svc_rqst *rqstp,
1751                      struct nfsd4_compound_state *cstate,
1752                      struct nfsd4_bind_conn_to_session *bcts)
1753 {
1754         __be32 status;
1755
1756         if (!nfsd4_last_compound_op(rqstp))
1757                 return nfserr_not_only_op;
1758         spin_lock(&client_lock);
1759         cstate->session = find_in_sessionid_hashtbl(&bcts->sessionid);
1760         /* Sorta weird: we only need the refcnt'ing because new_conn acquires
1761          * client_lock iself: */
1762         if (cstate->session) {
1763                 nfsd4_get_session(cstate->session);
1764                 atomic_inc(&cstate->session->se_client->cl_refcount);
1765         }
1766         spin_unlock(&client_lock);
1767         if (!cstate->session)
1768                 return nfserr_badsession;
1769
1770         status = nfsd4_map_bcts_dir(&bcts->dir);
1771         if (!status)
1772                 nfsd4_new_conn(rqstp, cstate->session, bcts->dir);
1773         return status;
1774 }
1775
1776 static bool nfsd4_compound_in_session(struct nfsd4_session *session, struct nfs4_sessionid *sid)
1777 {
1778         if (!session)
1779                 return 0;
1780         return !memcmp(sid, &session->se_sessionid, sizeof(*sid));
1781 }
1782
1783 __be32
1784 nfsd4_destroy_session(struct svc_rqst *r,
1785                       struct nfsd4_compound_state *cstate,
1786                       struct nfsd4_destroy_session *sessionid)
1787 {
1788         struct nfsd4_session *ses;
1789         u32 status = nfserr_badsession;
1790
1791         /* Notes:
1792          * - The confirmed nfs4_client->cl_sessionid holds destroyed sessinid
1793          * - Should we return nfserr_back_chan_busy if waiting for
1794          *   callbacks on to-be-destroyed session?
1795          * - Do we need to clear any callback info from previous session?
1796          */
1797
1798         if (nfsd4_compound_in_session(cstate->session, &sessionid->sessionid)) {
1799                 if (!nfsd4_last_compound_op(r))
1800                         return nfserr_not_only_op;
1801         }
1802         dump_sessionid(__func__, &sessionid->sessionid);
1803         spin_lock(&client_lock);
1804         ses = find_in_sessionid_hashtbl(&sessionid->sessionid);
1805         if (!ses) {
1806                 spin_unlock(&client_lock);
1807                 goto out;
1808         }
1809
1810         unhash_session(ses);
1811         spin_unlock(&client_lock);
1812
1813         nfs4_lock_state();
1814         nfsd4_probe_callback_sync(ses->se_client);
1815         nfs4_unlock_state();
1816
1817         nfsd4_del_conns(ses);
1818
1819         nfsd4_put_session(ses);
1820         status = nfs_ok;
1821 out:
1822         dprintk("%s returns %d\n", __func__, ntohl(status));
1823         return status;
1824 }
1825
1826 static struct nfsd4_conn *__nfsd4_find_conn(struct svc_xprt *xpt, struct nfsd4_session *s)
1827 {
1828         struct nfsd4_conn *c;
1829
1830         list_for_each_entry(c, &s->se_conns, cn_persession) {
1831                 if (c->cn_xprt == xpt) {
1832                         return c;
1833                 }
1834         }
1835         return NULL;
1836 }
1837
1838 static void nfsd4_sequence_check_conn(struct nfsd4_conn *new, struct nfsd4_session *ses)
1839 {
1840         struct nfs4_client *clp = ses->se_client;
1841         struct nfsd4_conn *c;
1842         int ret;
1843
1844         spin_lock(&clp->cl_lock);
1845         c = __nfsd4_find_conn(new->cn_xprt, ses);
1846         if (c) {
1847                 spin_unlock(&clp->cl_lock);
1848                 free_conn(new);
1849                 return;
1850         }
1851         __nfsd4_hash_conn(new, ses);
1852         spin_unlock(&clp->cl_lock);
1853         ret = nfsd4_register_conn(new);
1854         if (ret)
1855                 /* oops; xprt is already down: */
1856                 nfsd4_conn_lost(&new->cn_xpt_user);
1857         return;
1858 }
1859
1860 static bool nfsd4_session_too_many_ops(struct svc_rqst *rqstp, struct nfsd4_session *session)
1861 {
1862         struct nfsd4_compoundargs *args = rqstp->rq_argp;
1863
1864         return args->opcnt > session->se_fchannel.maxops;
1865 }
1866
1867 static bool nfsd4_request_too_big(struct svc_rqst *rqstp,
1868                                   struct nfsd4_session *session)
1869 {
1870         struct xdr_buf *xb = &rqstp->rq_arg;
1871
1872         return xb->len > session->se_fchannel.maxreq_sz;
1873 }
1874
1875 __be32
1876 nfsd4_sequence(struct svc_rqst *rqstp,
1877                struct nfsd4_compound_state *cstate,
1878                struct nfsd4_sequence *seq)
1879 {
1880         struct nfsd4_compoundres *resp = rqstp->rq_resp;
1881         struct nfsd4_session *session;
1882         struct nfsd4_slot *slot;
1883         struct nfsd4_conn *conn;
1884         int status;
1885
1886         if (resp->opcnt != 1)
1887                 return nfserr_sequence_pos;
1888
1889         /*
1890          * Will be either used or freed by nfsd4_sequence_check_conn
1891          * below.
1892          */
1893         conn = alloc_conn(rqstp, NFS4_CDFC4_FORE);
1894         if (!conn)
1895                 return nfserr_jukebox;
1896
1897         spin_lock(&client_lock);
1898         status = nfserr_badsession;
1899         session = find_in_sessionid_hashtbl(&seq->sessionid);
1900         if (!session)
1901                 goto out;
1902
1903         status = nfserr_too_many_ops;
1904         if (nfsd4_session_too_many_ops(rqstp, session))
1905                 goto out;
1906
1907         status = nfserr_req_too_big;
1908         if (nfsd4_request_too_big(rqstp, session))
1909                 goto out;
1910
1911         status = nfserr_badslot;
1912         if (seq->slotid >= session->se_fchannel.maxreqs)
1913                 goto out;
1914
1915         slot = session->se_slots[seq->slotid];
1916         dprintk("%s: slotid %d\n", __func__, seq->slotid);
1917
1918         /* We do not negotiate the number of slots yet, so set the
1919          * maxslots to the session maxreqs which is used to encode
1920          * sr_highest_slotid and the sr_target_slot id to maxslots */
1921         seq->maxslots = session->se_fchannel.maxreqs;
1922
1923         status = check_slot_seqid(seq->seqid, slot->sl_seqid, slot->sl_inuse);
1924         if (status == nfserr_replay_cache) {
1925                 cstate->slot = slot;
1926                 cstate->session = session;
1927                 /* Return the cached reply status and set cstate->status
1928                  * for nfsd4_proc_compound processing */
1929                 status = nfsd4_replay_cache_entry(resp, seq);
1930                 cstate->status = nfserr_replay_cache;
1931                 goto out;
1932         }
1933         if (status)
1934                 goto out;
1935
1936         nfsd4_sequence_check_conn(conn, session);
1937         conn = NULL;
1938
1939         /* Success! bump slot seqid */
1940         slot->sl_inuse = true;
1941         slot->sl_seqid = seq->seqid;
1942         slot->sl_cachethis = seq->cachethis;
1943
1944         cstate->slot = slot;
1945         cstate->session = session;
1946
1947 out:
1948         /* Hold a session reference until done processing the compound. */
1949         if (cstate->session) {
1950                 struct nfs4_client *clp = session->se_client;
1951
1952                 nfsd4_get_session(cstate->session);
1953                 atomic_inc(&clp->cl_refcount);
1954                 switch (clp->cl_cb_state) {
1955                 case NFSD4_CB_DOWN:
1956                         seq->status_flags = SEQ4_STATUS_CB_PATH_DOWN;
1957                         break;
1958                 case NFSD4_CB_FAULT:
1959                         seq->status_flags = SEQ4_STATUS_BACKCHANNEL_FAULT;
1960                         break;
1961                 default:
1962                         seq->status_flags = 0;
1963                 }
1964         }
1965         kfree(conn);
1966         spin_unlock(&client_lock);
1967         dprintk("%s: return %d\n", __func__, ntohl(status));
1968         return status;
1969 }
1970
1971 static inline bool has_resources(struct nfs4_client *clp)
1972 {
1973         return !list_empty(&clp->cl_openowners)
1974                 || !list_empty(&clp->cl_delegations)
1975                 || !list_empty(&clp->cl_sessions);
1976 }
1977
1978 __be32
1979 nfsd4_destroy_clientid(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_destroy_clientid *dc)
1980 {
1981         struct nfs4_client *conf, *unconf, *clp;
1982         int status = 0;
1983
1984         nfs4_lock_state();
1985         unconf = find_unconfirmed_client(&dc->clientid);
1986         conf = find_confirmed_client(&dc->clientid);
1987
1988         if (conf) {
1989                 clp = conf;
1990
1991                 if (!is_client_expired(conf) && has_resources(conf)) {
1992                         status = nfserr_clientid_busy;
1993                         goto out;
1994                 }
1995
1996                 /* rfc5661 18.50.3 */
1997                 if (cstate->session && conf == cstate->session->se_client) {
1998                         status = nfserr_clientid_busy;
1999                         goto out;
2000                 }
2001         } else if (unconf)
2002                 clp = unconf;
2003         else {
2004                 status = nfserr_stale_clientid;
2005                 goto out;
2006         }
2007
2008         expire_client(clp);
2009 out:
2010         nfs4_unlock_state();
2011         dprintk("%s return %d\n", __func__, ntohl(status));
2012         return status;
2013 }
2014
2015 __be32
2016 nfsd4_reclaim_complete(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_reclaim_complete *rc)
2017 {
2018         int status = 0;
2019
2020         if (rc->rca_one_fs) {
2021                 if (!cstate->current_fh.fh_dentry)
2022                         return nfserr_nofilehandle;
2023                 /*
2024                  * We don't take advantage of the rca_one_fs case.
2025                  * That's OK, it's optional, we can safely ignore it.
2026                  */
2027                  return nfs_ok;
2028         }
2029
2030         nfs4_lock_state();
2031         status = nfserr_complete_already;
2032         if (cstate->session->se_client->cl_firststate)
2033                 goto out;
2034
2035         status = nfserr_stale_clientid;
2036         if (is_client_expired(cstate->session->se_client))
2037                 /*
2038                  * The following error isn't really legal.
2039                  * But we only get here if the client just explicitly
2040                  * destroyed the client.  Surely it no longer cares what
2041                  * error it gets back on an operation for the dead
2042                  * client.
2043                  */
2044                 goto out;
2045
2046         status = nfs_ok;
2047         nfsd4_create_clid_dir(cstate->session->se_client);
2048 out:
2049         nfs4_unlock_state();
2050         return status;
2051 }
2052
2053 __be32
2054 nfsd4_setclientid(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
2055                   struct nfsd4_setclientid *setclid)
2056 {
2057         struct xdr_netobj       clname = setclid->se_name;
2058         nfs4_verifier           clverifier = setclid->se_verf;
2059         unsigned int            strhashval;
2060         struct nfs4_client      *conf, *unconf, *new;
2061         __be32                  status;
2062         char                    dname[HEXDIR_LEN];
2063         
2064         status = nfs4_make_rec_clidname(dname, &clname);
2065         if (status)
2066                 return status;
2067
2068         /* 
2069          * XXX The Duplicate Request Cache (DRC) has been checked (??)
2070          * We get here on a DRC miss.
2071          */
2072
2073         strhashval = clientstr_hashval(dname);
2074
2075         nfs4_lock_state();
2076         conf = find_confirmed_client_by_str(dname, strhashval);
2077         if (conf) {
2078                 /* RFC 3530 14.2.33 CASE 0: */
2079                 status = nfserr_clid_inuse;
2080                 if (clp_used_exchangeid(conf))
2081                         goto out;
2082                 if (!same_creds(&conf->cl_cred, &rqstp->rq_cred)) {
2083                         char addr_str[INET6_ADDRSTRLEN];
2084                         rpc_ntop((struct sockaddr *) &conf->cl_addr, addr_str,
2085                                  sizeof(addr_str));
2086                         dprintk("NFSD: setclientid: string in use by client "
2087                                 "at %s\n", addr_str);
2088                         goto out;
2089                 }
2090         }
2091         /*
2092          * section 14.2.33 of RFC 3530 (under the heading "IMPLEMENTATION")
2093          * has a description of SETCLIENTID request processing consisting
2094          * of 5 bullet points, labeled as CASE0 - CASE4 below.
2095          */
2096         unconf = find_unconfirmed_client_by_str(dname, strhashval);
2097         status = nfserr_jukebox;
2098         if (!conf) {
2099                 /*
2100                  * RFC 3530 14.2.33 CASE 4:
2101                  * placed first, because it is the normal case
2102                  */
2103                 if (unconf)
2104                         expire_client(unconf);
2105                 new = create_client(clname, dname, rqstp, &clverifier);
2106                 if (new == NULL)
2107                         goto out;
2108                 gen_clid(new);
2109         } else if (same_verf(&conf->cl_verifier, &clverifier)) {
2110                 /*
2111                  * RFC 3530 14.2.33 CASE 1:
2112                  * probable callback update
2113                  */
2114                 if (unconf) {
2115                         /* Note this is removing unconfirmed {*x***},
2116                          * which is stronger than RFC recommended {vxc**}.
2117                          * This has the advantage that there is at most
2118                          * one {*x***} in either list at any time.
2119                          */
2120                         expire_client(unconf);
2121                 }
2122                 new = create_client(clname, dname, rqstp, &clverifier);
2123                 if (new == NULL)
2124                         goto out;
2125                 copy_clid(new, conf);
2126         } else if (!unconf) {
2127                 /*
2128                  * RFC 3530 14.2.33 CASE 2:
2129                  * probable client reboot; state will be removed if
2130                  * confirmed.
2131                  */
2132                 new = create_client(clname, dname, rqstp, &clverifier);
2133                 if (new == NULL)
2134                         goto out;
2135                 gen_clid(new);
2136         } else {
2137                 /*
2138                  * RFC 3530 14.2.33 CASE 3:
2139                  * probable client reboot; state will be removed if
2140                  * confirmed.
2141                  */
2142                 expire_client(unconf);
2143                 new = create_client(clname, dname, rqstp, &clverifier);
2144                 if (new == NULL)
2145                         goto out;
2146                 gen_clid(new);
2147         }
2148         /*
2149          * XXX: we should probably set this at creation time, and check
2150          * for consistent minorversion use throughout:
2151          */
2152         new->cl_minorversion = 0;
2153         gen_callback(new, setclid, rqstp);
2154         add_to_unconfirmed(new, strhashval);
2155         setclid->se_clientid.cl_boot = new->cl_clientid.cl_boot;
2156         setclid->se_clientid.cl_id = new->cl_clientid.cl_id;
2157         memcpy(setclid->se_confirm.data, new->cl_confirm.data, sizeof(setclid->se_confirm.data));
2158         status = nfs_ok;
2159 out:
2160         nfs4_unlock_state();
2161         return status;
2162 }
2163
2164
2165 /*
2166  * Section 14.2.34 of RFC 3530 (under the heading "IMPLEMENTATION") has
2167  * a description of SETCLIENTID_CONFIRM request processing consisting of 4
2168  * bullets, labeled as CASE1 - CASE4 below.
2169  */
2170 __be32
2171 nfsd4_setclientid_confirm(struct svc_rqst *rqstp,
2172                          struct nfsd4_compound_state *cstate,
2173                          struct nfsd4_setclientid_confirm *setclientid_confirm)
2174 {
2175         struct sockaddr *sa = svc_addr(rqstp);
2176         struct nfs4_client *conf, *unconf;
2177         nfs4_verifier confirm = setclientid_confirm->sc_confirm; 
2178         clientid_t * clid = &setclientid_confirm->sc_clientid;
2179         __be32 status;
2180
2181         if (STALE_CLIENTID(clid))
2182                 return nfserr_stale_clientid;
2183         /* 
2184          * XXX The Duplicate Request Cache (DRC) has been checked (??)
2185          * We get here on a DRC miss.
2186          */
2187
2188         nfs4_lock_state();
2189
2190         conf = find_confirmed_client(clid);
2191         unconf = find_unconfirmed_client(clid);
2192
2193         status = nfserr_clid_inuse;
2194         if (conf && !rpc_cmp_addr((struct sockaddr *) &conf->cl_addr, sa))
2195                 goto out;
2196         if (unconf && !rpc_cmp_addr((struct sockaddr *) &unconf->cl_addr, sa))
2197                 goto out;
2198
2199         /*
2200          * section 14.2.34 of RFC 3530 has a description of
2201          * SETCLIENTID_CONFIRM request processing consisting
2202          * of 4 bullet points, labeled as CASE1 - CASE4 below.
2203          */
2204         if (conf && unconf && same_verf(&confirm, &unconf->cl_confirm)) {
2205                 /*
2206                  * RFC 3530 14.2.34 CASE 1:
2207                  * callback update
2208                  */
2209                 if (!same_creds(&conf->cl_cred, &unconf->cl_cred))
2210                         status = nfserr_clid_inuse;
2211                 else {
2212                         nfsd4_change_callback(conf, &unconf->cl_cb_conn);
2213                         nfsd4_probe_callback(conf);
2214                         expire_client(unconf);
2215                         status = nfs_ok;
2216
2217                 }
2218         } else if (conf && !unconf) {
2219                 /*
2220                  * RFC 3530 14.2.34 CASE 2:
2221                  * probable retransmitted request; play it safe and
2222                  * do nothing.
2223                  */
2224                 if (!same_creds(&conf->cl_cred, &rqstp->rq_cred))
2225                         status = nfserr_clid_inuse;
2226                 else
2227                         status = nfs_ok;
2228         } else if (!conf && unconf
2229                         && same_verf(&unconf->cl_confirm, &confirm)) {
2230                 /*
2231                  * RFC 3530 14.2.34 CASE 3:
2232                  * Normal case; new or rebooted client:
2233                  */
2234                 if (!same_creds(&unconf->cl_cred, &rqstp->rq_cred)) {
2235                         status = nfserr_clid_inuse;
2236                 } else {
2237                         unsigned int hash =
2238                                 clientstr_hashval(unconf->cl_recdir);
2239                         conf = find_confirmed_client_by_str(unconf->cl_recdir,
2240                                                             hash);
2241                         if (conf) {
2242                                 nfsd4_remove_clid_dir(conf);
2243                                 expire_client(conf);
2244                         }
2245                         move_to_confirmed(unconf);
2246                         conf = unconf;
2247                         nfsd4_probe_callback(conf);
2248                         status = nfs_ok;
2249                 }
2250         } else if ((!conf || (conf && !same_verf(&conf->cl_confirm, &confirm)))
2251             && (!unconf || (unconf && !same_verf(&unconf->cl_confirm,
2252                                                                 &confirm)))) {
2253                 /*
2254                  * RFC 3530 14.2.34 CASE 4:
2255                  * Client probably hasn't noticed that we rebooted yet.
2256                  */
2257                 status = nfserr_stale_clientid;
2258         } else {
2259                 /* check that we have hit one of the cases...*/
2260                 status = nfserr_clid_inuse;
2261         }
2262 out:
2263         nfs4_unlock_state();
2264         return status;
2265 }
2266
2267 static struct nfs4_file *nfsd4_alloc_file(void)
2268 {
2269         return kmem_cache_alloc(file_slab, GFP_KERNEL);
2270 }
2271
2272 /* OPEN Share state helper functions */
2273 static void nfsd4_init_file(struct nfs4_file *fp, struct inode *ino)
2274 {
2275         unsigned int hashval = file_hashval(ino);
2276
2277         atomic_set(&fp->fi_ref, 1);
2278         INIT_LIST_HEAD(&fp->fi_hash);
2279         INIT_LIST_HEAD(&fp->fi_stateids);
2280         INIT_LIST_HEAD(&fp->fi_delegations);
2281         fp->fi_inode = igrab(ino);
2282         fp->fi_had_conflict = false;
2283         fp->fi_lease = NULL;
2284         memset(fp->fi_fds, 0, sizeof(fp->fi_fds));
2285         memset(fp->fi_access, 0, sizeof(fp->fi_access));
2286         spin_lock(&recall_lock);
2287         list_add(&fp->fi_hash, &file_hashtbl[hashval]);
2288         spin_unlock(&recall_lock);
2289 }
2290
2291 static void
2292 nfsd4_free_slab(struct kmem_cache **slab)
2293 {
2294         if (*slab == NULL)
2295                 return;
2296         kmem_cache_destroy(*slab);
2297         *slab = NULL;
2298 }
2299
2300 void
2301 nfsd4_free_slabs(void)
2302 {
2303         nfsd4_free_slab(&openowner_slab);
2304         nfsd4_free_slab(&lockowner_slab);
2305         nfsd4_free_slab(&file_slab);
2306         nfsd4_free_slab(&stateid_slab);
2307         nfsd4_free_slab(&deleg_slab);
2308 }
2309
2310 static int
2311 nfsd4_init_slabs(void)
2312 {
2313         openowner_slab = kmem_cache_create("nfsd4_openowners",
2314                         sizeof(struct nfs4_openowner), 0, 0, NULL);
2315         if (openowner_slab == NULL)
2316                 goto out_nomem;
2317         lockowner_slab = kmem_cache_create("nfsd4_lockowners",
2318                         sizeof(struct nfs4_lockowner), 0, 0, NULL);
2319         if (lockowner_slab == NULL)
2320                 goto out_nomem;
2321         file_slab = kmem_cache_create("nfsd4_files",
2322                         sizeof(struct nfs4_file), 0, 0, NULL);
2323         if (file_slab == NULL)
2324                 goto out_nomem;
2325         stateid_slab = kmem_cache_create("nfsd4_stateids",
2326                         sizeof(struct nfs4_ol_stateid), 0, 0, NULL);
2327         if (stateid_slab == NULL)
2328                 goto out_nomem;
2329         deleg_slab = kmem_cache_create("nfsd4_delegations",
2330                         sizeof(struct nfs4_delegation), 0, 0, NULL);
2331         if (deleg_slab == NULL)
2332                 goto out_nomem;
2333         return 0;
2334 out_nomem:
2335         nfsd4_free_slabs();
2336         dprintk("nfsd4: out of memory while initializing nfsv4\n");
2337         return -ENOMEM;
2338 }
2339
2340 void nfs4_free_openowner(struct nfs4_openowner *oo)
2341 {
2342         kfree(oo->oo_owner.so_owner.data);
2343         kmem_cache_free(openowner_slab, oo);
2344 }
2345
2346 void nfs4_free_lockowner(struct nfs4_lockowner *lo)
2347 {
2348         kfree(lo->lo_owner.so_owner.data);
2349         kmem_cache_free(lockowner_slab, lo);
2350 }
2351
2352 static void init_nfs4_replay(struct nfs4_replay *rp)
2353 {
2354         rp->rp_status = nfserr_serverfault;
2355         rp->rp_buflen = 0;
2356         rp->rp_buf = rp->rp_ibuf;
2357 }
2358
2359 static inline void *alloc_stateowner(struct kmem_cache *slab, struct xdr_netobj *owner, struct nfs4_client *clp)
2360 {
2361         struct nfs4_stateowner *sop;
2362
2363         sop = kmem_cache_alloc(slab, GFP_KERNEL);
2364         if (!sop)
2365                 return NULL;
2366
2367         sop->so_owner.data = kmemdup(owner->data, owner->len, GFP_KERNEL);
2368         if (!sop->so_owner.data) {
2369                 kmem_cache_free(slab, sop);
2370                 return NULL;
2371         }
2372         sop->so_owner.len = owner->len;
2373
2374         INIT_LIST_HEAD(&sop->so_stateids);
2375         sop->so_client = clp;
2376         init_nfs4_replay(&sop->so_replay);
2377         return sop;
2378 }
2379
2380 static void hash_openowner(struct nfs4_openowner *oo, struct nfs4_client *clp, unsigned int strhashval)
2381 {
2382         list_add(&oo->oo_owner.so_strhash, &open_ownerstr_hashtbl[strhashval]);
2383         list_add(&oo->oo_perclient, &clp->cl_openowners);
2384 }
2385
2386 static struct nfs4_openowner *
2387 alloc_init_open_stateowner(unsigned int strhashval, struct nfs4_client *clp, struct nfsd4_open *open) {
2388         struct nfs4_openowner *oo;
2389
2390         oo = alloc_stateowner(openowner_slab, &open->op_owner, clp);
2391         if (!oo)
2392                 return NULL;
2393         oo->oo_owner.so_is_open_owner = 1;
2394         oo->oo_owner.so_seqid = open->op_seqid;
2395         oo->oo_flags = NFS4_OO_NEW;
2396         oo->oo_time = 0;
2397         oo->oo_last_closed_stid = NULL;
2398         INIT_LIST_HEAD(&oo->oo_close_lru);
2399         hash_openowner(oo, clp, strhashval);
2400         return oo;
2401 }
2402
2403 static void init_open_stateid(struct nfs4_ol_stateid *stp, struct nfs4_file *fp, struct nfsd4_open *open) {
2404         struct nfs4_openowner *oo = open->op_openowner;
2405         struct nfs4_client *clp = oo->oo_owner.so_client;
2406
2407         init_stid(&stp->st_stid, clp, NFS4_OPEN_STID);
2408         INIT_LIST_HEAD(&stp->st_lockowners);
2409         list_add(&stp->st_perstateowner, &oo->oo_owner.so_stateids);
2410         list_add(&stp->st_perfile, &fp->fi_stateids);
2411         stp->st_stateowner = &oo->oo_owner;
2412         get_nfs4_file(fp);
2413         stp->st_file = fp;
2414         stp->st_access_bmap = 0;
2415         stp->st_deny_bmap = 0;
2416         __set_bit(open->op_share_access, &stp->st_access_bmap);
2417         __set_bit(open->op_share_deny, &stp->st_deny_bmap);
2418         stp->st_openstp = NULL;
2419 }
2420
2421 static void
2422 move_to_close_lru(struct nfs4_openowner *oo)
2423 {
2424         dprintk("NFSD: move_to_close_lru nfs4_openowner %p\n", oo);
2425
2426         list_move_tail(&oo->oo_close_lru, &close_lru);
2427         oo->oo_time = get_seconds();
2428 }
2429
2430 static int
2431 same_owner_str(struct nfs4_stateowner *sop, struct xdr_netobj *owner,
2432                                                         clientid_t *clid)
2433 {
2434         return (sop->so_owner.len == owner->len) &&
2435                 0 == memcmp(sop->so_owner.data, owner->data, owner->len) &&
2436                 (sop->so_client->cl_clientid.cl_id == clid->cl_id);
2437 }
2438
2439 static struct nfs4_openowner *
2440 find_openstateowner_str(unsigned int hashval, struct nfsd4_open *open)
2441 {
2442         struct nfs4_stateowner *so;
2443         struct nfs4_openowner *oo;
2444
2445         list_for_each_entry(so, &open_ownerstr_hashtbl[hashval], so_strhash) {
2446                 if (same_owner_str(so, &open->op_owner, &open->op_clientid)) {
2447                         oo = openowner(so);
2448                         renew_client(oo->oo_owner.so_client);
2449                         return oo;
2450                 }
2451         }
2452         return NULL;
2453 }
2454
2455 /* search file_hashtbl[] for file */
2456 static struct nfs4_file *
2457 find_file(struct inode *ino)
2458 {
2459         unsigned int hashval = file_hashval(ino);
2460         struct nfs4_file *fp;
2461
2462         spin_lock(&recall_lock);
2463         list_for_each_entry(fp, &file_hashtbl[hashval], fi_hash) {
2464                 if (fp->fi_inode == ino) {
2465                         get_nfs4_file(fp);
2466                         spin_unlock(&recall_lock);
2467                         return fp;
2468                 }
2469         }
2470         spin_unlock(&recall_lock);
2471         return NULL;
2472 }
2473
2474 /*
2475  * Called to check deny when READ with all zero stateid or
2476  * WRITE with all zero or all one stateid
2477  */
2478 static __be32
2479 nfs4_share_conflict(struct svc_fh *current_fh, unsigned int deny_type)
2480 {
2481         struct inode *ino = current_fh->fh_dentry->d_inode;
2482         struct nfs4_file *fp;
2483         struct nfs4_ol_stateid *stp;
2484         __be32 ret;
2485
2486         dprintk("NFSD: nfs4_share_conflict\n");
2487
2488         fp = find_file(ino);
2489         if (!fp)
2490                 return nfs_ok;
2491         ret = nfserr_locked;
2492         /* Search for conflicting share reservations */
2493         list_for_each_entry(stp, &fp->fi_stateids, st_perfile) {
2494                 if (test_bit(deny_type, &stp->st_deny_bmap) ||
2495                     test_bit(NFS4_SHARE_DENY_BOTH, &stp->st_deny_bmap))
2496                         goto out;
2497         }
2498         ret = nfs_ok;
2499 out:
2500         put_nfs4_file(fp);
2501         return ret;
2502 }
2503
2504 static void nfsd_break_one_deleg(struct nfs4_delegation *dp)
2505 {
2506         /* We're assuming the state code never drops its reference
2507          * without first removing the lease.  Since we're in this lease
2508          * callback (and since the lease code is serialized by the kernel
2509          * lock) we know the server hasn't removed the lease yet, we know
2510          * it's safe to take a reference: */
2511         atomic_inc(&dp->dl_count);
2512
2513         list_add_tail(&dp->dl_recall_lru, &del_recall_lru);
2514
2515         /* only place dl_time is set. protected by lock_flocks*/
2516         dp->dl_time = get_seconds();
2517
2518         nfsd4_cb_recall(dp);
2519 }
2520
2521 /* Called from break_lease() with lock_flocks() held. */
2522 static void nfsd_break_deleg_cb(struct file_lock *fl)
2523 {
2524         struct nfs4_file *fp = (struct nfs4_file *)fl->fl_owner;
2525         struct nfs4_delegation *dp;
2526
2527         BUG_ON(!fp);
2528         /* We assume break_lease is only called once per lease: */
2529         BUG_ON(fp->fi_had_conflict);
2530         /*
2531          * We don't want the locks code to timeout the lease for us;
2532          * we'll remove it ourself if a delegation isn't returned
2533          * in time:
2534          */
2535         fl->fl_break_time = 0;
2536
2537         spin_lock(&recall_lock);
2538         fp->fi_had_conflict = true;
2539         list_for_each_entry(dp, &fp->fi_delegations, dl_perfile)
2540                 nfsd_break_one_deleg(dp);
2541         spin_unlock(&recall_lock);
2542 }
2543
2544 static
2545 int nfsd_change_deleg_cb(struct file_lock **onlist, int arg)
2546 {
2547         if (arg & F_UNLCK)
2548                 return lease_modify(onlist, arg);
2549         else
2550                 return -EAGAIN;
2551 }
2552
2553 static const struct lock_manager_operations nfsd_lease_mng_ops = {
2554         .lm_break = nfsd_break_deleg_cb,
2555         .lm_change = nfsd_change_deleg_cb,
2556 };
2557
2558 static __be32 nfsd4_check_seqid(struct nfsd4_compound_state *cstate, struct nfs4_stateowner *so, u32 seqid)
2559 {
2560         if (nfsd4_has_session(cstate))
2561                 return nfs_ok;
2562         if (seqid == so->so_seqid - 1)
2563                 return nfserr_replay_me;
2564         if (seqid == so->so_seqid)
2565                 return nfs_ok;
2566         return nfserr_bad_seqid;
2567 }
2568
2569 __be32
2570 nfsd4_process_open1(struct nfsd4_compound_state *cstate,
2571                     struct nfsd4_open *open)
2572 {
2573         clientid_t *clientid = &open->op_clientid;
2574         struct nfs4_client *clp = NULL;
2575         unsigned int strhashval;
2576         struct nfs4_openowner *oo = NULL;
2577         __be32 status;
2578
2579         if (STALE_CLIENTID(&open->op_clientid))
2580                 return nfserr_stale_clientid;
2581         /*
2582          * In case we need it later, after we've already created the
2583          * file and don't want to risk a further failure:
2584          */
2585         open->op_file = nfsd4_alloc_file();
2586         if (open->op_file == NULL)
2587                 return nfserr_jukebox;
2588
2589         strhashval = open_ownerstr_hashval(clientid->cl_id, &open->op_owner);
2590         oo = find_openstateowner_str(strhashval, open);
2591         open->op_openowner = oo;
2592         if (!oo) {
2593                 clp = find_confirmed_client(clientid);
2594                 if (clp == NULL)
2595                         return nfserr_expired;
2596                 goto new_owner;
2597         }
2598         if (!(oo->oo_flags & NFS4_OO_CONFIRMED)) {
2599                 /* Replace unconfirmed owners without checking for replay. */
2600                 clp = oo->oo_owner.so_client;
2601                 release_openowner(oo);
2602                 open->op_openowner = NULL;
2603                 goto new_owner;
2604         }
2605         status = nfsd4_check_seqid(cstate, &oo->oo_owner, open->op_seqid);
2606         if (status)
2607                 return status;
2608         clp = oo->oo_owner.so_client;
2609         goto alloc_stateid;
2610 new_owner:
2611         oo = alloc_init_open_stateowner(strhashval, clp, open);
2612         if (oo == NULL)
2613                 return nfserr_jukebox;
2614         open->op_openowner = oo;
2615 alloc_stateid:
2616         open->op_stp = nfs4_alloc_stateid(clp);
2617         if (!open->op_stp)
2618                 return nfserr_jukebox;
2619         return nfs_ok;
2620 }
2621
2622 static inline __be32
2623 nfs4_check_delegmode(struct nfs4_delegation *dp, int flags)
2624 {
2625         if ((flags & WR_STATE) && (dp->dl_type == NFS4_OPEN_DELEGATE_READ))
2626                 return nfserr_openmode;
2627         else
2628                 return nfs_ok;
2629 }
2630
2631 static int share_access_to_flags(u32 share_access)
2632 {
2633         share_access &= ~NFS4_SHARE_WANT_MASK;
2634
2635         return share_access == NFS4_SHARE_ACCESS_READ ? RD_STATE : WR_STATE;
2636 }
2637
2638 static struct nfs4_delegation *find_deleg_stateid(struct nfs4_client *cl, stateid_t *s)
2639 {
2640         struct nfs4_stid *ret;
2641
2642         ret = find_stateid_by_type(cl, s, NFS4_DELEG_STID);
2643         if (!ret)
2644                 return NULL;
2645         return delegstateid(ret);
2646 }
2647
2648 static bool nfsd4_is_deleg_cur(struct nfsd4_open *open)
2649 {
2650         return open->op_claim_type == NFS4_OPEN_CLAIM_DELEGATE_CUR ||
2651                open->op_claim_type == NFS4_OPEN_CLAIM_DELEG_CUR_FH;
2652 }
2653
2654 static __be32
2655 nfs4_check_deleg(struct nfs4_client *cl, struct nfs4_file *fp, struct nfsd4_open *open,
2656                 struct nfs4_delegation **dp)
2657 {
2658         int flags;
2659         __be32 status = nfserr_bad_stateid;
2660
2661         *dp = find_deleg_stateid(cl, &open->op_delegate_stateid);
2662         if (*dp == NULL)
2663                 goto out;
2664         flags = share_access_to_flags(open->op_share_access);
2665         status = nfs4_check_delegmode(*dp, flags);
2666         if (status)
2667                 *dp = NULL;
2668 out:
2669         if (!nfsd4_is_deleg_cur(open))
2670                 return nfs_ok;
2671         if (status)
2672                 return status;
2673         open->op_openowner->oo_flags |= NFS4_OO_CONFIRMED;
2674         return nfs_ok;
2675 }
2676
2677 static __be32
2678 nfs4_check_open(struct nfs4_file *fp, struct nfsd4_open *open, struct nfs4_ol_stateid **stpp)
2679 {
2680         struct nfs4_ol_stateid *local;
2681         struct nfs4_openowner *oo = open->op_openowner;
2682
2683         list_for_each_entry(local, &fp->fi_stateids, st_perfile) {
2684                 /* ignore lock owners */
2685                 if (local->st_stateowner->so_is_open_owner == 0)
2686                         continue;
2687                 /* remember if we have seen this open owner */
2688                 if (local->st_stateowner == &oo->oo_owner)
2689                         *stpp = local;
2690                 /* check for conflicting share reservations */
2691                 if (!test_share(local, open))
2692                         return nfserr_share_denied;
2693         }
2694         return nfs_ok;
2695 }
2696
2697 static void nfs4_free_stateid(struct nfs4_ol_stateid *s)
2698 {
2699         kmem_cache_free(stateid_slab, s);
2700 }
2701
2702 static inline int nfs4_access_to_access(u32 nfs4_access)
2703 {
2704         int flags = 0;
2705
2706         if (nfs4_access & NFS4_SHARE_ACCESS_READ)
2707                 flags |= NFSD_MAY_READ;
2708         if (nfs4_access & NFS4_SHARE_ACCESS_WRITE)
2709                 flags |= NFSD_MAY_WRITE;
2710         return flags;
2711 }
2712
2713 static __be32 nfs4_get_vfs_file(struct svc_rqst *rqstp, struct nfs4_file *fp,
2714                 struct svc_fh *cur_fh, struct nfsd4_open *open)
2715 {
2716         __be32 status;
2717         int oflag = nfs4_access_to_omode(open->op_share_access);
2718         int access = nfs4_access_to_access(open->op_share_access);
2719
2720         if (!fp->fi_fds[oflag]) {
2721                 status = nfsd_open(rqstp, cur_fh, S_IFREG, access,
2722                         &fp->fi_fds[oflag]);
2723                 if (status)
2724                         return status;
2725         }
2726         nfs4_file_get_access(fp, oflag);
2727
2728         return nfs_ok;
2729 }
2730
2731 static inline __be32
2732 nfsd4_truncate(struct svc_rqst *rqstp, struct svc_fh *fh,
2733                 struct nfsd4_open *open)
2734 {
2735         struct iattr iattr = {
2736                 .ia_valid = ATTR_SIZE,
2737                 .ia_size = 0,
2738         };
2739         if (!open->op_truncate)
2740                 return 0;
2741         if (!(open->op_share_access & NFS4_SHARE_ACCESS_WRITE))
2742                 return nfserr_inval;
2743         return nfsd_setattr(rqstp, fh, &iattr, 0, (time_t)0);
2744 }
2745
2746 static __be32
2747 nfs4_upgrade_open(struct svc_rqst *rqstp, struct nfs4_file *fp, struct svc_fh *cur_fh, struct nfs4_ol_stateid *stp, struct nfsd4_open *open)
2748 {
2749         u32 op_share_access = open->op_share_access;
2750         bool new_access;
2751         __be32 status;
2752
2753         new_access = !test_bit(op_share_access, &stp->st_access_bmap);
2754         if (new_access) {
2755                 status = nfs4_get_vfs_file(rqstp, fp, cur_fh, open);
2756                 if (status)
2757                         return status;
2758         }
2759         status = nfsd4_truncate(rqstp, cur_fh, open);
2760         if (status) {
2761                 if (new_access) {
2762                         int oflag = nfs4_access_to_omode(op_share_access);
2763                         nfs4_file_put_access(fp, oflag);
2764                 }
2765                 return status;
2766         }
2767         /* remember the open */
2768         __set_bit(op_share_access, &stp->st_access_bmap);
2769         __set_bit(open->op_share_deny, &stp->st_deny_bmap);
2770
2771         return nfs_ok;
2772 }
2773
2774
2775 static void
2776 nfs4_set_claim_prev(struct nfsd4_open *open)
2777 {
2778         open->op_openowner->oo_flags |= NFS4_OO_CONFIRMED;
2779         open->op_openowner->oo_owner.so_client->cl_firststate = 1;
2780 }
2781
2782 /* Should we give out recallable state?: */
2783 static bool nfsd4_cb_channel_good(struct nfs4_client *clp)
2784 {
2785         if (clp->cl_cb_state == NFSD4_CB_UP)
2786                 return true;
2787         /*
2788          * In the sessions case, since we don't have to establish a
2789          * separate connection for callbacks, we assume it's OK
2790          * until we hear otherwise:
2791          */
2792         return clp->cl_minorversion && clp->cl_cb_state == NFSD4_CB_UNKNOWN;
2793 }
2794
2795 static struct file_lock *nfs4_alloc_init_lease(struct nfs4_delegation *dp, int flag)
2796 {
2797         struct file_lock *fl;
2798
2799         fl = locks_alloc_lock();
2800         if (!fl)
2801                 return NULL;
2802         locks_init_lock(fl);
2803         fl->fl_lmops = &nfsd_lease_mng_ops;
2804         fl->fl_flags = FL_LEASE;
2805         fl->fl_type = flag == NFS4_OPEN_DELEGATE_READ? F_RDLCK: F_WRLCK;
2806         fl->fl_end = OFFSET_MAX;
2807         fl->fl_owner = (fl_owner_t)(dp->dl_file);
2808         fl->fl_pid = current->tgid;
2809         return fl;
2810 }
2811
2812 static int nfs4_setlease(struct nfs4_delegation *dp, int flag)
2813 {
2814         struct nfs4_file *fp = dp->dl_file;
2815         struct file_lock *fl;
2816         int status;
2817
2818         fl = nfs4_alloc_init_lease(dp, flag);
2819         if (!fl)
2820                 return -ENOMEM;
2821         fl->fl_file = find_readable_file(fp);
2822         status = vfs_setlease(fl->fl_file, fl->fl_type, &fl);
2823         if (status) {
2824                 locks_free_lock(fl);
2825                 return -ENOMEM;
2826         }
2827         fp->fi_lease = fl;
2828         fp->fi_deleg_file = get_file(fl->fl_file);
2829         atomic_set(&fp->fi_delegees, 1);
2830         spin_lock(&recall_lock);
2831         hash_delegation_locked(dp, fp);
2832         spin_unlock(&recall_lock);
2833         return 0;
2834 }
2835
2836 static int nfs4_set_delegation(struct nfs4_delegation *dp, int flag)
2837 {
2838         struct nfs4_file *fp = dp->dl_file;
2839
2840         if (!fp->fi_lease)
2841                 return nfs4_setlease(dp, flag);
2842         spin_lock(&recall_lock);
2843         if (fp->fi_had_conflict) {
2844                 spin_unlock(&recall_lock);
2845                 return -EAGAIN;
2846         }
2847         atomic_inc(&fp->fi_delegees);
2848         hash_delegation_locked(dp, fp);
2849         spin_unlock(&recall_lock);
2850         return 0;
2851 }
2852
2853 /*
2854  * Attempt to hand out a delegation.
2855  */
2856 static void
2857 nfs4_open_delegation(struct svc_fh *fh, struct nfsd4_open *open, struct nfs4_ol_stateid *stp)
2858 {
2859         struct nfs4_delegation *dp;
2860         struct nfs4_openowner *oo = container_of(stp->st_stateowner, struct nfs4_openowner, oo_owner);
2861         int cb_up;
2862         int status, flag = 0;
2863
2864         cb_up = nfsd4_cb_channel_good(oo->oo_owner.so_client);
2865         flag = NFS4_OPEN_DELEGATE_NONE;
2866         open->op_recall = 0;
2867         switch (open->op_claim_type) {
2868                 case NFS4_OPEN_CLAIM_PREVIOUS:
2869                         if (!cb_up)
2870                                 open->op_recall = 1;
2871                         flag = open->op_delegate_type;
2872                         if (flag == NFS4_OPEN_DELEGATE_NONE)
2873                                 goto out;
2874                         break;
2875                 case NFS4_OPEN_CLAIM_NULL:
2876                         /* Let's not give out any delegations till everyone's
2877                          * had the chance to reclaim theirs.... */
2878                         if (locks_in_grace())
2879                                 goto out;
2880                         if (!cb_up || !(oo->oo_flags & NFS4_OO_CONFIRMED))
2881                                 goto out;
2882                         if (open->op_share_access & NFS4_SHARE_ACCESS_WRITE)
2883                                 flag = NFS4_OPEN_DELEGATE_WRITE;
2884                         else
2885                                 flag = NFS4_OPEN_DELEGATE_READ;
2886                         break;
2887                 default:
2888                         goto out;
2889         }
2890
2891         dp = alloc_init_deleg(oo->oo_owner.so_client, stp, fh, flag);
2892         if (dp == NULL)
2893                 goto out_no_deleg;
2894         status = nfs4_set_delegation(dp, flag);
2895         if (status)
2896                 goto out_free;
2897
2898         memcpy(&open->op_delegate_stateid, &dp->dl_stid.sc_stateid, sizeof(dp->dl_stid.sc_stateid));
2899
2900         dprintk("NFSD: delegation stateid=" STATEID_FMT "\n",
2901                 STATEID_VAL(&dp->dl_stid.sc_stateid));
2902 out:
2903         if (open->op_claim_type == NFS4_OPEN_CLAIM_PREVIOUS
2904                         && flag == NFS4_OPEN_DELEGATE_NONE
2905                         && open->op_delegate_type != NFS4_OPEN_DELEGATE_NONE)
2906                 dprintk("NFSD: WARNING: refusing delegation reclaim\n");
2907         open->op_delegate_type = flag;
2908         return;
2909 out_free:
2910         nfs4_put_delegation(dp);
2911 out_no_deleg:
2912         flag = NFS4_OPEN_DELEGATE_NONE;
2913         goto out;
2914 }
2915
2916 /*
2917  * called with nfs4_lock_state() held.
2918  */
2919 __be32
2920 nfsd4_process_open2(struct svc_rqst *rqstp, struct svc_fh *current_fh, struct nfsd4_open *open)
2921 {
2922         struct nfsd4_compoundres *resp = rqstp->rq_resp;
2923         struct nfs4_client *cl = open->op_openowner->oo_owner.so_client;
2924         struct nfs4_file *fp = NULL;
2925         struct inode *ino = current_fh->fh_dentry->d_inode;
2926         struct nfs4_ol_stateid *stp = NULL;
2927         struct nfs4_delegation *dp = NULL;
2928         __be32 status;
2929
2930         /*
2931          * Lookup file; if found, lookup stateid and check open request,
2932          * and check for delegations in the process of being recalled.
2933          * If not found, create the nfs4_file struct
2934          */
2935         fp = find_file(ino);
2936         if (fp) {
2937                 if ((status = nfs4_check_open(fp, open, &stp)))
2938                         goto out;
2939                 status = nfs4_check_deleg(cl, fp, open, &dp);
2940                 if (status)
2941                         goto out;
2942         } else {
2943                 status = nfserr_bad_stateid;
2944                 if (nfsd4_is_deleg_cur(open))
2945                         goto out;
2946                 status = nfserr_jukebox;
2947                 fp = open->op_file;
2948                 open->op_file = NULL;
2949                 nfsd4_init_file(fp, ino);
2950         }
2951
2952         /*
2953          * OPEN the file, or upgrade an existing OPEN.
2954          * If truncate fails, the OPEN fails.
2955          */
2956         if (stp) {
2957                 /* Stateid was found, this is an OPEN upgrade */
2958                 status = nfs4_upgrade_open(rqstp, fp, current_fh, stp, open);
2959                 if (status)
2960                         goto out;
2961         } else {
2962                 status = nfs4_get_vfs_file(rqstp, fp, current_fh, open);
2963                 if (status)
2964                         goto out;
2965                 stp = open->op_stp;
2966                 open->op_stp = NULL;
2967                 init_open_stateid(stp, fp, open);
2968                 status = nfsd4_truncate(rqstp, current_fh, open);
2969                 if (status) {
2970                         release_open_stateid(stp);
2971                         goto out;
2972                 }
2973         }
2974         update_stateid(&stp->st_stid.sc_stateid);
2975         memcpy(&open->op_stateid, &stp->st_stid.sc_stateid, sizeof(stateid_t));
2976
2977         if (nfsd4_has_session(&resp->cstate))
2978                 open->op_openowner->oo_flags |= NFS4_OO_CONFIRMED;
2979
2980         /*
2981         * Attempt to hand out a delegation. No error return, because the
2982         * OPEN succeeds even if we fail.
2983         */
2984         nfs4_open_delegation(current_fh, open, stp);
2985
2986         status = nfs_ok;
2987
2988         dprintk("%s: stateid=" STATEID_FMT "\n", __func__,
2989                 STATEID_VAL(&stp->st_stid.sc_stateid));
2990 out:
2991         if (fp)
2992                 put_nfs4_file(fp);
2993         if (status == 0 && open->op_claim_type == NFS4_OPEN_CLAIM_PREVIOUS)
2994                 nfs4_set_claim_prev(open);
2995         /*
2996         * To finish the open response, we just need to set the rflags.
2997         */
2998         open->op_rflags = NFS4_OPEN_RESULT_LOCKTYPE_POSIX;
2999         if (!(open->op_openowner->oo_flags & NFS4_OO_CONFIRMED) &&
3000             !nfsd4_has_session(&resp->cstate))
3001                 open->op_rflags |= NFS4_OPEN_RESULT_CONFIRM;
3002
3003         return status;
3004 }
3005
3006 void nfsd4_cleanup_open_state(struct nfsd4_open *open, __be32 status)
3007 {
3008         if (open->op_openowner) {
3009                 struct nfs4_openowner *oo = open->op_openowner;
3010
3011                 if (!list_empty(&oo->oo_owner.so_stateids))
3012                         list_del_init(&oo->oo_close_lru);
3013                 if (oo->oo_flags & NFS4_OO_NEW) {
3014                         if (status) {
3015                                 release_openowner(oo);
3016                                 open->op_openowner = NULL;
3017                         } else
3018                                 oo->oo_flags &= ~NFS4_OO_NEW;
3019                 }
3020         }
3021         if (open->op_file)
3022                 nfsd4_free_file(open->op_file);
3023         if (open->op_stp)
3024                 nfs4_free_stateid(open->op_stp);
3025 }
3026
3027 __be32
3028 nfsd4_renew(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3029             clientid_t *clid)
3030 {
3031         struct nfs4_client *clp;
3032         __be32 status;
3033
3034         nfs4_lock_state();
3035         dprintk("process_renew(%08x/%08x): starting\n", 
3036                         clid->cl_boot, clid->cl_id);
3037         status = nfserr_stale_clientid;
3038         if (STALE_CLIENTID(clid))
3039                 goto out;
3040         clp = find_confirmed_client(clid);
3041         status = nfserr_expired;
3042         if (clp == NULL) {
3043                 /* We assume the client took too long to RENEW. */
3044                 dprintk("nfsd4_renew: clientid not found!\n");
3045                 goto out;
3046         }
3047         status = nfserr_cb_path_down;
3048         if (!list_empty(&clp->cl_delegations)
3049                         && clp->cl_cb_state != NFSD4_CB_UP)
3050                 goto out;
3051         status = nfs_ok;
3052 out:
3053         nfs4_unlock_state();
3054         return status;
3055 }
3056
3057 static struct lock_manager nfsd4_manager = {
3058 };
3059
3060 static void
3061 nfsd4_end_grace(void)
3062 {
3063         dprintk("NFSD: end of grace period\n");
3064         nfsd4_recdir_purge_old();
3065         locks_end_grace(&nfsd4_manager);
3066         /*
3067          * Now that every NFSv4 client has had the chance to recover and
3068          * to see the (possibly new, possibly shorter) lease time, we
3069          * can safely set the next grace time to the current lease time:
3070          */
3071         nfsd4_grace = nfsd4_lease;
3072 }
3073
3074 static time_t
3075 nfs4_laundromat(void)
3076 {
3077         struct nfs4_client *clp;
3078         struct nfs4_openowner *oo;
3079         struct nfs4_delegation *dp;
3080         struct list_head *pos, *next, reaplist;
3081         time_t cutoff = get_seconds() - nfsd4_lease;
3082         time_t t, clientid_val = nfsd4_lease;
3083         time_t u, test_val = nfsd4_lease;
3084
3085         nfs4_lock_state();
3086
3087         dprintk("NFSD: laundromat service - starting\n");
3088         if (locks_in_grace())
3089                 nfsd4_end_grace();
3090         INIT_LIST_HEAD(&reaplist);
3091         spin_lock(&client_lock);
3092         list_for_each_safe(pos, next, &client_lru) {
3093                 clp = list_entry(pos, struct nfs4_client, cl_lru);
3094                 if (time_after((unsigned long)clp->cl_time, (unsigned long)cutoff)) {
3095                         t = clp->cl_time - cutoff;
3096                         if (clientid_val > t)
3097                                 clientid_val = t;
3098                         break;
3099                 }
3100                 if (atomic_read(&clp->cl_refcount)) {
3101                         dprintk("NFSD: client in use (clientid %08x)\n",
3102                                 clp->cl_clientid.cl_id);
3103                         continue;
3104                 }
3105                 unhash_client_locked(clp);
3106                 list_add(&clp->cl_lru, &reaplist);
3107         }
3108         spin_unlock(&client_lock);
3109         list_for_each_safe(pos, next, &reaplist) {
3110                 clp = list_entry(pos, struct nfs4_client, cl_lru);
3111                 dprintk("NFSD: purging unused client (clientid %08x)\n",
3112                         clp->cl_clientid.cl_id);
3113                 nfsd4_remove_clid_dir(clp);
3114                 expire_client(clp);
3115         }
3116         spin_lock(&recall_lock);
3117         list_for_each_safe(pos, next, &del_recall_lru) {
3118                 dp = list_entry (pos, struct nfs4_delegation, dl_recall_lru);
3119                 if (time_after((unsigned long)dp->dl_time, (unsigned long)cutoff)) {
3120                         u = dp->dl_time - cutoff;
3121                         if (test_val > u)
3122                                 test_val = u;
3123                         break;
3124                 }
3125                 list_move(&dp->dl_recall_lru, &reaplist);
3126         }
3127         spin_unlock(&recall_lock);
3128         list_for_each_safe(pos, next, &reaplist) {
3129                 dp = list_entry (pos, struct nfs4_delegation, dl_recall_lru);
3130                 list_del_init(&dp->dl_recall_lru);
3131                 unhash_delegation(dp);
3132         }
3133         test_val = nfsd4_lease;
3134         list_for_each_safe(pos, next, &close_lru) {
3135                 oo = container_of(pos, struct nfs4_openowner, oo_close_lru);
3136                 if (time_after((unsigned long)oo->oo_time, (unsigned long)cutoff)) {
3137                         u = oo->oo_time - cutoff;
3138                         if (test_val > u)
3139                                 test_val = u;
3140                         break;
3141                 }
3142                 release_openowner(oo);
3143         }
3144         if (clientid_val < NFSD_LAUNDROMAT_MINTIMEOUT)
3145                 clientid_val = NFSD_LAUNDROMAT_MINTIMEOUT;
3146         nfs4_unlock_state();
3147         return clientid_val;
3148 }
3149
3150 static struct workqueue_struct *laundry_wq;
3151 static void laundromat_main(struct work_struct *);
3152 static DECLARE_DELAYED_WORK(laundromat_work, laundromat_main);
3153
3154 static void
3155 laundromat_main(struct work_struct *not_used)
3156 {
3157         time_t t;
3158
3159         t = nfs4_laundromat();
3160         dprintk("NFSD: laundromat_main - sleeping for %ld seconds\n", t);
3161         queue_delayed_work(laundry_wq, &laundromat_work, t*HZ);
3162 }
3163
3164 static inline __be32 nfs4_check_fh(struct svc_fh *fhp, struct nfs4_ol_stateid *stp)
3165 {
3166         if (fhp->fh_dentry->d_inode != stp->st_file->fi_inode)
3167                 return nfserr_bad_stateid;
3168         return nfs_ok;
3169 }
3170
3171 static int
3172 STALE_STATEID(stateid_t *stateid)
3173 {
3174         if (stateid->si_opaque.so_clid.cl_boot == boot_time)
3175                 return 0;
3176         dprintk("NFSD: stale stateid " STATEID_FMT "!\n",
3177                 STATEID_VAL(stateid));
3178         return 1;
3179 }
3180
3181 static inline int
3182 access_permit_read(unsigned long access_bmap)
3183 {
3184         return test_bit(NFS4_SHARE_ACCESS_READ, &access_bmap) ||
3185                 test_bit(NFS4_SHARE_ACCESS_BOTH, &access_bmap) ||
3186                 test_bit(NFS4_SHARE_ACCESS_WRITE, &access_bmap);
3187 }
3188
3189 static inline int
3190 access_permit_write(unsigned long access_bmap)
3191 {
3192         return test_bit(NFS4_SHARE_ACCESS_WRITE, &access_bmap) ||
3193                 test_bit(NFS4_SHARE_ACCESS_BOTH, &access_bmap);
3194 }
3195
3196 static
3197 __be32 nfs4_check_openmode(struct nfs4_ol_stateid *stp, int flags)
3198 {
3199         __be32 status = nfserr_openmode;
3200
3201         /* For lock stateid's, we test the parent open, not the lock: */
3202         if (stp->st_openstp)
3203                 stp = stp->st_openstp;
3204         if ((flags & WR_STATE) && (!access_permit_write(stp->st_access_bmap)))
3205                 goto out;
3206         if ((flags & RD_STATE) && (!access_permit_read(stp->st_access_bmap)))
3207                 goto out;
3208         status = nfs_ok;
3209 out:
3210         return status;
3211 }
3212
3213 static inline __be32
3214 check_special_stateids(svc_fh *current_fh, stateid_t *stateid, int flags)
3215 {
3216         if (ONE_STATEID(stateid) && (flags & RD_STATE))
3217                 return nfs_ok;
3218         else if (locks_in_grace()) {
3219                 /* Answer in remaining cases depends on existence of
3220                  * conflicting state; so we must wait out the grace period. */
3221                 return nfserr_grace;
3222         } else if (flags & WR_STATE)
3223                 return nfs4_share_conflict(current_fh,
3224                                 NFS4_SHARE_DENY_WRITE);
3225         else /* (flags & RD_STATE) && ZERO_STATEID(stateid) */
3226                 return nfs4_share_conflict(current_fh,
3227                                 NFS4_SHARE_DENY_READ);
3228 }
3229
3230 /*
3231  * Allow READ/WRITE during grace period on recovered state only for files
3232  * that are not able to provide mandatory locking.
3233  */
3234 static inline int
3235 grace_disallows_io(struct inode *inode)
3236 {
3237         return locks_in_grace() && mandatory_lock(inode);
3238 }
3239
3240 /* Returns true iff a is later than b: */
3241 static bool stateid_generation_after(stateid_t *a, stateid_t *b)
3242 {
3243         return (s32)a->si_generation - (s32)b->si_generation > 0;
3244 }
3245
3246 static int check_stateid_generation(stateid_t *in, stateid_t *ref, bool has_session)
3247 {
3248         /*
3249          * When sessions are used the stateid generation number is ignored
3250          * when it is zero.
3251          */
3252         if (has_session && in->si_generation == 0)
3253                 return nfs_ok;
3254
3255         if (in->si_generation == ref->si_generation)
3256                 return nfs_ok;
3257
3258         /* If the client sends us a stateid from the future, it's buggy: */
3259         if (stateid_generation_after(in, ref))
3260                 return nfserr_bad_stateid;
3261         /*
3262          * However, we could see a stateid from the past, even from a
3263          * non-buggy client.  For example, if the client sends a lock
3264          * while some IO is outstanding, the lock may bump si_generation
3265          * while the IO is still in flight.  The client could avoid that
3266          * situation by waiting for responses on all the IO requests,
3267          * but better performance may result in retrying IO that
3268          * receives an old_stateid error if requests are rarely
3269          * reordered in flight:
3270          */
3271         return nfserr_old_stateid;
3272 }
3273
3274 static __be32 nfsd4_check_openowner_confirmed(struct nfs4_ol_stateid *ols)
3275 {
3276         if (ols->st_stateowner->so_is_open_owner &&
3277             !(openowner(ols->st_stateowner)->oo_flags & NFS4_OO_CONFIRMED))
3278                 return nfserr_bad_stateid;
3279         return nfs_ok;
3280 }
3281
3282 __be32 nfs4_validate_stateid(struct nfs4_client *cl, stateid_t *stateid)
3283 {
3284         struct nfs4_stid *s;
3285         __be32 status;
3286
3287         if (STALE_STATEID(stateid))
3288                 return nfserr_stale_stateid;
3289
3290         s = find_stateid(cl, stateid);
3291         if (!s)
3292                  return nfserr_stale_stateid;
3293         status = check_stateid_generation(stateid, &s->sc_stateid, 1);
3294         if (status)
3295                 return status;
3296         if (!(s->sc_type & (NFS4_OPEN_STID | NFS4_LOCK_STID)))
3297                 return nfs_ok;
3298         return nfsd4_check_openowner_confirmed(openlockstateid(s));
3299 }
3300
3301 static __be32 nfsd4_lookup_stateid(stateid_t *stateid, unsigned char typemask, struct nfs4_stid **s)
3302 {
3303         struct nfs4_client *cl;
3304
3305         if (ZERO_STATEID(stateid) || ONE_STATEID(stateid))
3306                 return nfserr_bad_stateid;
3307         if (STALE_STATEID(stateid))
3308                 return nfserr_stale_stateid;
3309         cl = find_confirmed_client(&stateid->si_opaque.so_clid);
3310         if (!cl)
3311                 return nfserr_expired;
3312         *s = find_stateid_by_type(cl, stateid, typemask);
3313         if (!*s)
3314                 return nfserr_bad_stateid;
3315         return nfs_ok;
3316
3317 }
3318
3319 /*
3320 * Checks for stateid operations
3321 */
3322 __be32
3323 nfs4_preprocess_stateid_op(struct nfsd4_compound_state *cstate,
3324                            stateid_t *stateid, int flags, struct file **filpp)
3325 {
3326         struct nfs4_stid *s;
3327         struct nfs4_ol_stateid *stp = NULL;
3328         struct nfs4_delegation *dp = NULL;
3329         struct svc_fh *current_fh = &cstate->current_fh;
3330         struct inode *ino = current_fh->fh_dentry->d_inode;
3331         __be32 status;
3332
3333         if (filpp)
3334                 *filpp = NULL;
3335
3336         if (grace_disallows_io(ino))
3337                 return nfserr_grace;
3338
3339         if (ZERO_STATEID(stateid) || ONE_STATEID(stateid))
3340                 return check_special_stateids(current_fh, stateid, flags);
3341
3342         status = nfsd4_lookup_stateid(stateid, NFS4_DELEG_STID|NFS4_OPEN_STID|NFS4_LOCK_STID, &s);
3343         if (status)
3344                 return status;
3345         status = check_stateid_generation(stateid, &s->sc_stateid, nfsd4_has_session(cstate));
3346         if (status)
3347                 goto out;
3348         switch (s->sc_type) {
3349         case NFS4_DELEG_STID:
3350                 dp = delegstateid(s);
3351                 status = nfs4_check_delegmode(dp, flags);
3352                 if (status)
3353                         goto out;
3354                 if (filpp) {
3355                         *filpp = dp->dl_file->fi_deleg_file;
3356                         BUG_ON(!*filpp);
3357                 }
3358                 break;
3359         case NFS4_OPEN_STID:
3360         case NFS4_LOCK_STID:
3361                 stp = openlockstateid(s);
3362                 status = nfs4_check_fh(current_fh, stp);
3363                 if (status)
3364                         goto out;
3365                 status = nfsd4_check_openowner_confirmed(stp);
3366                 if (status)
3367                         goto out;
3368                 status = nfs4_check_openmode(stp, flags);
3369                 if (status)
3370                         goto out;
3371                 if (filpp) {
3372                         if (flags & RD_STATE)
3373                                 *filpp = find_readable_file(stp->st_file);
3374                         else
3375                                 *filpp = find_writeable_file(stp->st_file);
3376                 }
3377                 break;
3378         default:
3379                 return nfserr_bad_stateid;
3380         }
3381         status = nfs_ok;
3382 out:
3383         return status;
3384 }
3385
3386 static __be32
3387 nfsd4_free_lock_stateid(struct nfs4_ol_stateid *stp)
3388 {
3389         struct nfs4_lockowner *lo = lockowner(stp->st_stateowner);
3390
3391         if (check_for_locks(stp->st_file, lo))
3392                 return nfserr_locks_held;
3393         /*
3394          * Currently there's a 1-1 lock stateid<->lockowner
3395          * correspondance, and we have to delete the lockowner when we
3396          * delete the lock stateid:
3397          */
3398         release_lockowner(lo);
3399         return nfs_ok;
3400 }
3401
3402 /*
3403  * Test if the stateid is valid
3404  */
3405 __be32
3406 nfsd4_test_stateid(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3407                    struct nfsd4_test_stateid *test_stateid)
3408 {
3409         /* real work is done during encoding */
3410         return nfs_ok;
3411 }
3412
3413 __be32
3414 nfsd4_free_stateid(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3415                    struct nfsd4_free_stateid *free_stateid)
3416 {
3417         stateid_t *stateid = &free_stateid->fr_stateid;
3418         struct nfs4_stid *s;
3419         struct nfs4_client *cl = cstate->session->se_client;
3420         __be32 ret = nfserr_bad_stateid;
3421
3422         nfs4_lock_state();
3423         s = find_stateid(cl, stateid);
3424         if (!s)
3425                 goto out;
3426         switch (s->sc_type) {
3427         case NFS4_DELEG_STID:
3428                 ret = nfserr_locks_held;
3429                 goto out;
3430         case NFS4_OPEN_STID:
3431         case NFS4_LOCK_STID:
3432                 ret = check_stateid_generation(stateid, &s->sc_stateid, 1);
3433                 if (ret)
3434                         goto out;
3435                 if (s->sc_type == NFS4_LOCK_STID)
3436                         ret = nfsd4_free_lock_stateid(openlockstateid(s));
3437                 else
3438                         ret = nfserr_locks_held;
3439                 break;
3440         default:
3441                 ret = nfserr_bad_stateid;
3442         }
3443 out:
3444         nfs4_unlock_state();
3445         return ret;
3446 }
3447
3448 static inline int
3449 setlkflg (int type)
3450 {
3451         return (type == NFS4_READW_LT || type == NFS4_READ_LT) ?
3452                 RD_STATE : WR_STATE;
3453 }
3454
3455 static __be32 nfs4_seqid_op_checks(struct nfsd4_compound_state *cstate, stateid_t *stateid, u32 seqid, struct nfs4_ol_stateid *stp)
3456 {
3457         struct svc_fh *current_fh = &cstate->current_fh;
3458         struct nfs4_stateowner *sop = stp->st_stateowner;
3459         __be32 status;
3460
3461         status = nfsd4_check_seqid(cstate, sop, seqid);
3462         if (status)
3463                 return status;
3464         if (stp->st_stid.sc_type == NFS4_CLOSED_STID)
3465                 /*
3466                  * "Closed" stateid's exist *only* to return
3467                  * nfserr_replay_me from the previous step.
3468                  */
3469                 return nfserr_bad_stateid;
3470         status = check_stateid_generation(stateid, &stp->st_stid.sc_stateid, nfsd4_has_session(cstate));
3471         if (status)
3472                 return status;
3473         return nfs4_check_fh(current_fh, stp);
3474 }
3475
3476 /* 
3477  * Checks for sequence id mutating operations. 
3478  */
3479 static __be32
3480 nfs4_preprocess_seqid_op(struct nfsd4_compound_state *cstate, u32 seqid,
3481                          stateid_t *stateid, char typemask,
3482                          struct nfs4_ol_stateid **stpp)
3483 {
3484         __be32 status;
3485         struct nfs4_stid *s;
3486
3487         dprintk("NFSD: %s: seqid=%d stateid = " STATEID_FMT "\n", __func__,
3488                 seqid, STATEID_VAL(stateid));
3489
3490         *stpp = NULL;
3491         status = nfsd4_lookup_stateid(stateid, typemask, &s);
3492         if (status)
3493                 return status;
3494         *stpp = openlockstateid(s);
3495         cstate->replay_owner = (*stpp)->st_stateowner;
3496
3497         return nfs4_seqid_op_checks(cstate, stateid, seqid, *stpp);
3498 }
3499
3500 static __be32 nfs4_preprocess_confirmed_seqid_op(struct nfsd4_compound_state *cstate, u32 seqid, stateid_t *stateid, struct nfs4_ol_stateid **stpp)
3501 {
3502         __be32 status;
3503         struct nfs4_openowner *oo;
3504
3505         status = nfs4_preprocess_seqid_op(cstate, seqid, stateid,
3506                                                 NFS4_OPEN_STID, stpp);
3507         if (status)
3508                 return status;
3509         oo = openowner((*stpp)->st_stateowner);
3510         if (!(oo->oo_flags & NFS4_OO_CONFIRMED))
3511                 return nfserr_bad_stateid;
3512         return nfs_ok;
3513 }
3514
3515 __be32
3516 nfsd4_open_confirm(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3517                    struct nfsd4_open_confirm *oc)
3518 {
3519         __be32 status;
3520         struct nfs4_openowner *oo;
3521         struct nfs4_ol_stateid *stp;
3522
3523         dprintk("NFSD: nfsd4_open_confirm on file %.*s\n",
3524                         (int)cstate->current_fh.fh_dentry->d_name.len,
3525                         cstate->current_fh.fh_dentry->d_name.name);
3526
3527         status = fh_verify(rqstp, &cstate->current_fh, S_IFREG, 0);
3528         if (status)
3529                 return status;
3530
3531         nfs4_lock_state();
3532
3533         status = nfs4_preprocess_seqid_op(cstate,
3534                                         oc->oc_seqid, &oc->oc_req_stateid,
3535                                         NFS4_OPEN_STID, &stp);
3536         if (status)
3537                 goto out;
3538         oo = openowner(stp->st_stateowner);
3539         status = nfserr_bad_stateid;
3540         if (oo->oo_flags & NFS4_OO_CONFIRMED)
3541                 goto out;
3542         oo->oo_flags |= NFS4_OO_CONFIRMED;
3543         update_stateid(&stp->st_stid.sc_stateid);
3544         memcpy(&oc->oc_resp_stateid, &stp->st_stid.sc_stateid, sizeof(stateid_t));
3545         dprintk("NFSD: %s: success, seqid=%d stateid=" STATEID_FMT "\n",
3546                 __func__, oc->oc_seqid, STATEID_VAL(&stp->st_stid.sc_stateid));
3547
3548         nfsd4_create_clid_dir(oo->oo_owner.so_client);
3549         status = nfs_ok;
3550 out:
3551         if (!cstate->replay_owner)
3552                 nfs4_unlock_state();
3553         return status;
3554 }
3555
3556 static inline void nfs4_stateid_downgrade_bit(struct nfs4_ol_stateid *stp, u32 access)
3557 {
3558         if (!test_bit(access, &stp->st_access_bmap))
3559                 return;
3560         nfs4_file_put_access(stp->st_file, nfs4_access_to_omode(access));
3561         __clear_bit(access, &stp->st_access_bmap);
3562 }
3563
3564 static inline void nfs4_stateid_downgrade(struct nfs4_ol_stateid *stp, u32 to_access)
3565 {
3566         switch (to_access) {
3567         case NFS4_SHARE_ACCESS_READ:
3568                 nfs4_stateid_downgrade_bit(stp, NFS4_SHARE_ACCESS_WRITE);
3569                 nfs4_stateid_downgrade_bit(stp, NFS4_SHARE_ACCESS_BOTH);
3570                 break;
3571         case NFS4_SHARE_ACCESS_WRITE:
3572                 nfs4_stateid_downgrade_bit(stp, NFS4_SHARE_ACCESS_READ);
3573                 nfs4_stateid_downgrade_bit(stp, NFS4_SHARE_ACCESS_BOTH);
3574                 break;
3575         case NFS4_SHARE_ACCESS_BOTH:
3576                 break;
3577         default:
3578                 BUG();
3579         }
3580 }
3581
3582 static void
3583 reset_union_bmap_deny(unsigned long deny, unsigned long *bmap)
3584 {
3585         int i;
3586         for (i = 0; i < 4; i++) {
3587                 if ((i & deny) != i)
3588                         __clear_bit(i, bmap);
3589         }
3590 }
3591
3592 __be32
3593 nfsd4_open_downgrade(struct svc_rqst *rqstp,
3594                      struct nfsd4_compound_state *cstate,
3595                      struct nfsd4_open_downgrade *od)
3596 {
3597         __be32 status;
3598         struct nfs4_ol_stateid *stp;
3599
3600         dprintk("NFSD: nfsd4_open_downgrade on file %.*s\n", 
3601                         (int)cstate->current_fh.fh_dentry->d_name.len,
3602                         cstate->current_fh.fh_dentry->d_name.name);
3603
3604         /* We don't yet support WANT bits: */
3605         od->od_share_access &= NFS4_SHARE_ACCESS_MASK;
3606
3607         nfs4_lock_state();
3608         status = nfs4_preprocess_confirmed_seqid_op(cstate, od->od_seqid,
3609                                         &od->od_stateid, &stp);
3610         if (status)
3611                 goto out; 
3612         status = nfserr_inval;
3613         if (!test_bit(od->od_share_access, &stp->st_access_bmap)) {
3614                 dprintk("NFSD:access not a subset current bitmap: 0x%lx, input access=%08x\n",
3615                         stp->st_access_bmap, od->od_share_access);
3616                 goto out;
3617         }
3618         if (!test_bit(od->od_share_deny, &stp->st_deny_bmap)) {
3619                 dprintk("NFSD:deny not a subset current bitmap: 0x%lx, input deny=%08x\n",
3620                         stp->st_deny_bmap, od->od_share_deny);
3621                 goto out;
3622         }
3623         nfs4_stateid_downgrade(stp, od->od_share_access);
3624
3625         reset_union_bmap_deny(od->od_share_deny, &stp->st_deny_bmap);
3626
3627         update_stateid(&stp->st_stid.sc_stateid);
3628         memcpy(&od->od_stateid, &stp->st_stid.sc_stateid, sizeof(stateid_t));
3629         status = nfs_ok;
3630 out:
3631         if (!cstate->replay_owner)
3632                 nfs4_unlock_state();
3633         return status;
3634 }
3635
3636 void nfsd4_purge_closed_stateid(struct nfs4_stateowner *so)
3637 {
3638         struct nfs4_openowner *oo;
3639         struct nfs4_ol_stateid *s;
3640
3641         if (!so->so_is_open_owner)
3642                 return;
3643         oo = openowner(so);
3644         s = oo->oo_last_closed_stid;
3645         if (!s)
3646                 return;
3647         if (!(oo->oo_flags & NFS4_OO_PURGE_CLOSE)) {
3648                 /* Release the last_closed_stid on the next seqid bump: */
3649                 oo->oo_flags |= NFS4_OO_PURGE_CLOSE;
3650                 return;
3651         }
3652         oo->oo_flags &= ~NFS4_OO_PURGE_CLOSE;
3653         release_last_closed_stateid(oo);
3654 }
3655
3656 static void nfsd4_close_open_stateid(struct nfs4_ol_stateid *s)
3657 {
3658         unhash_open_stateid(s);
3659         s->st_stid.sc_type = NFS4_CLOSED_STID;
3660 }
3661
3662 /*
3663  * nfs4_unlock_state() called after encode
3664  */
3665 __be32
3666 nfsd4_close(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3667             struct nfsd4_close *close)
3668 {
3669         __be32 status;
3670         struct nfs4_openowner *oo;
3671         struct nfs4_ol_stateid *stp;
3672
3673         dprintk("NFSD: nfsd4_close on file %.*s\n", 
3674                         (int)cstate->current_fh.fh_dentry->d_name.len,
3675                         cstate->current_fh.fh_dentry->d_name.name);
3676
3677         nfs4_lock_state();
3678         status = nfs4_preprocess_seqid_op(cstate, close->cl_seqid,
3679                                         &close->cl_stateid,
3680                                         NFS4_OPEN_STID|NFS4_CLOSED_STID,
3681                                         &stp);
3682         if (status)
3683                 goto out; 
3684         oo = openowner(stp->st_stateowner);
3685         status = nfs_ok;
3686         update_stateid(&stp->st_stid.sc_stateid);
3687         memcpy(&close->cl_stateid, &stp->st_stid.sc_stateid, sizeof(stateid_t));
3688
3689         nfsd4_close_open_stateid(stp);
3690         release_last_closed_stateid(oo);
3691         oo->oo_last_closed_stid = stp;
3692
3693         /* place unused nfs4_stateowners on so_close_lru list to be
3694          * released by the laundromat service after the lease period
3695          * to enable us to handle CLOSE replay
3696          */
3697         if (list_empty(&oo->oo_owner.so_stateids))
3698                 move_to_close_lru(oo);
3699 out:
3700         if (!cstate->replay_owner)
3701                 nfs4_unlock_state();
3702         return status;
3703 }
3704
3705 __be32
3706 nfsd4_delegreturn(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3707                   struct nfsd4_delegreturn *dr)
3708 {
3709         struct nfs4_delegation *dp;
3710         stateid_t *stateid = &dr->dr_stateid;
3711         struct nfs4_stid *s;
3712         struct inode *inode;
3713         __be32 status;
3714
3715         if ((status = fh_verify(rqstp, &cstate->current_fh, S_IFREG, 0)))
3716                 return status;
3717         inode = cstate->current_fh.fh_dentry->d_inode;
3718
3719         nfs4_lock_state();
3720         status = nfsd4_lookup_stateid(stateid, NFS4_DELEG_STID, &s);
3721         if (status)
3722                 goto out;
3723         dp = delegstateid(s);
3724         status = check_stateid_generation(stateid, &dp->dl_stid.sc_stateid, nfsd4_has_session(cstate));
3725         if (status)
3726                 goto out;
3727
3728         unhash_delegation(dp);
3729 out:
3730         nfs4_unlock_state();
3731
3732         return status;
3733 }
3734
3735
3736 /* 
3737  * Lock owner state (byte-range locks)
3738  */
3739 #define LOFF_OVERFLOW(start, len)      ((u64)(len) > ~(u64)(start))
3740 #define LOCK_HASH_BITS              8
3741 #define LOCK_HASH_SIZE             (1 << LOCK_HASH_BITS)
3742 #define LOCK_HASH_MASK             (LOCK_HASH_SIZE - 1)
3743
3744 static inline u64
3745 end_offset(u64 start, u64 len)
3746 {
3747         u64 end;
3748
3749         end = start + len;
3750         return end >= start ? end: NFS4_MAX_UINT64;
3751 }
3752
3753 /* last octet in a range */
3754 static inline u64
3755 last_byte_offset(u64 start, u64 len)
3756 {
3757         u64 end;
3758
3759         BUG_ON(!len);
3760         end = start + len;
3761         return end > start ? end - 1: NFS4_MAX_UINT64;
3762 }
3763
3764 static inline unsigned int
3765 lock_ownerstr_hashval(struct inode *inode, u32 cl_id,
3766                 struct xdr_netobj *ownername)
3767 {
3768         return (file_hashval(inode) + cl_id
3769                         + opaque_hashval(ownername->data, ownername->len))
3770                 & LOCK_HASH_MASK;
3771 }
3772
3773 static struct list_head lock_ownerstr_hashtbl[LOCK_HASH_SIZE];
3774
3775 /*
3776  * TODO: Linux file offsets are _signed_ 64-bit quantities, which means that
3777  * we can't properly handle lock requests that go beyond the (2^63 - 1)-th
3778  * byte, because of sign extension problems.  Since NFSv4 calls for 64-bit
3779  * locking, this prevents us from being completely protocol-compliant.  The
3780  * real solution to this problem is to start using unsigned file offsets in
3781  * the VFS, but this is a very deep change!
3782  */
3783 static inline void
3784 nfs4_transform_lock_offset(struct file_lock *lock)
3785 {
3786         if (lock->fl_start < 0)
3787                 lock->fl_start = OFFSET_MAX;
3788         if (lock->fl_end < 0)
3789                 lock->fl_end = OFFSET_MAX;
3790 }
3791
3792 /* Hack!: For now, we're defining this just so we can use a pointer to it
3793  * as a unique cookie to identify our (NFSv4's) posix locks. */
3794 static const struct lock_manager_operations nfsd_posix_mng_ops  = {
3795 };
3796
3797 static inline void
3798 nfs4_set_lock_denied(struct file_lock *fl, struct nfsd4_lock_denied *deny)
3799 {
3800         struct nfs4_lockowner *lo;
3801
3802         if (fl->fl_lmops == &nfsd_posix_mng_ops) {
3803                 lo = (struct nfs4_lockowner *) fl->fl_owner;
3804                 deny->ld_owner.data = kmemdup(lo->lo_owner.so_owner.data,
3805                                         lo->lo_owner.so_owner.len, GFP_KERNEL);
3806                 if (!deny->ld_owner.data)
3807                         /* We just don't care that much */
3808                         goto nevermind;
3809                 deny->ld_owner.len = lo->lo_owner.so_owner.len;
3810                 deny->ld_clientid = lo->lo_owner.so_client->cl_clientid;
3811         } else {
3812 nevermind:
3813                 deny->ld_owner.len = 0;
3814                 deny->ld_owner.data = NULL;
3815                 deny->ld_clientid.cl_boot = 0;
3816                 deny->ld_clientid.cl_id = 0;
3817         }
3818         deny->ld_start = fl->fl_start;
3819         deny->ld_length = NFS4_MAX_UINT64;
3820         if (fl->fl_end != NFS4_MAX_UINT64)
3821                 deny->ld_length = fl->fl_end - fl->fl_start + 1;        
3822         deny->ld_type = NFS4_READ_LT;
3823         if (fl->fl_type != F_RDLCK)
3824                 deny->ld_type = NFS4_WRITE_LT;
3825 }
3826
3827 static bool same_lockowner_ino(struct nfs4_lockowner *lo, struct inode *inode, clientid_t *clid, struct xdr_netobj *owner)
3828 {
3829         struct nfs4_ol_stateid *lst;
3830
3831         if (!same_owner_str(&lo->lo_owner, owner, clid))
3832                 return false;
3833         if (list_empty(&lo->lo_owner.so_stateids)) {
3834                 WARN_ON_ONCE(1);
3835                 return false;
3836         }
3837         lst = list_first_entry(&lo->lo_owner.so_stateids,
3838                                struct nfs4_ol_stateid, st_perstateowner);
3839         return lst->st_file->fi_inode == inode;
3840 }
3841
3842 static struct nfs4_lockowner *
3843 find_lockowner_str(struct inode *inode, clientid_t *clid,
3844                 struct xdr_netobj *owner)
3845 {
3846         unsigned int hashval = lock_ownerstr_hashval(inode, clid->cl_id, owner);
3847         struct nfs4_lockowner *lo;
3848         struct nfs4_stateowner *op;
3849
3850         list_for_each_entry(op, &lock_ownerstr_hashtbl[hashval], so_strhash) {
3851                 lo = lockowner(op);
3852                 if (same_lockowner_ino(lo, inode, clid, owner))
3853                         return lo;
3854         }
3855         return NULL;
3856 }
3857
3858 static void hash_lockowner(struct nfs4_lockowner *lo, unsigned int strhashval, struct nfs4_client *clp, struct nfs4_ol_stateid *open_stp)
3859 {
3860         list_add(&lo->lo_owner.so_strhash, &lock_ownerstr_hashtbl[strhashval]);
3861         list_add(&lo->lo_perstateid, &open_stp->st_lockowners);
3862 }
3863
3864 /*
3865  * Alloc a lock owner structure.
3866  * Called in nfsd4_lock - therefore, OPEN and OPEN_CONFIRM (if needed) has 
3867  * occurred. 
3868  *
3869  * strhashval = lock_ownerstr_hashval 
3870  */
3871
3872 static struct nfs4_lockowner *
3873 alloc_init_lock_stateowner(unsigned int strhashval, struct nfs4_client *clp, struct nfs4_ol_stateid *open_stp, struct nfsd4_lock *lock) {
3874         struct nfs4_lockowner *lo;
3875
3876         lo = alloc_stateowner(lockowner_slab, &lock->lk_new_owner, clp);
3877         if (!lo)
3878                 return NULL;
3879         INIT_LIST_HEAD(&lo->lo_owner.so_stateids);
3880         lo->lo_owner.so_is_open_owner = 0;
3881         /* It is the openowner seqid that will be incremented in encode in the
3882          * case of new lockowners; so increment the lock seqid manually: */
3883         lo->lo_owner.so_seqid = lock->lk_new_lock_seqid + 1;
3884         hash_lockowner(lo, strhashval, clp, open_stp);
3885         return lo;
3886 }
3887
3888 static struct nfs4_ol_stateid *
3889 alloc_init_lock_stateid(struct nfs4_lockowner *lo, struct nfs4_file *fp, struct nfs4_ol_stateid *open_stp)
3890 {
3891         struct nfs4_ol_stateid *stp;
3892         struct nfs4_client *clp = lo->lo_owner.so_client;
3893
3894         stp = nfs4_alloc_stateid(clp);
3895         if (stp == NULL)
3896                 return NULL;
3897         init_stid(&stp->st_stid, clp, NFS4_LOCK_STID);
3898         list_add(&stp->st_perfile, &fp->fi_stateids);
3899         list_add(&stp->st_perstateowner, &lo->lo_owner.so_stateids);
3900         stp->st_stateowner = &lo->lo_owner;
3901         get_nfs4_file(fp);
3902         stp->st_file = fp;
3903         stp->st_access_bmap = 0;
3904         stp->st_deny_bmap = open_stp->st_deny_bmap;
3905         stp->st_openstp = open_stp;
3906         return stp;
3907 }
3908
3909 static int
3910 check_lock_length(u64 offset, u64 length)
3911 {
3912         return ((length == 0)  || ((length != NFS4_MAX_UINT64) &&
3913              LOFF_OVERFLOW(offset, length)));
3914 }
3915
3916 static void get_lock_access(struct nfs4_ol_stateid *lock_stp, u32 access)
3917 {
3918         struct nfs4_file *fp = lock_stp->st_file;
3919         int oflag = nfs4_access_to_omode(access);
3920
3921         if (test_bit(access, &lock_stp->st_access_bmap))
3922                 return;
3923         nfs4_file_get_access(fp, oflag);
3924         __set_bit(access, &lock_stp->st_access_bmap);
3925 }
3926
3927 /*
3928  *  LOCK operation 
3929  */
3930 __be32
3931 nfsd4_lock(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3932            struct nfsd4_lock *lock)
3933 {
3934         struct nfs4_openowner *open_sop = NULL;
3935         struct nfs4_lockowner *lock_sop = NULL;
3936         struct nfs4_ol_stateid *lock_stp;
3937         struct nfs4_file *fp;
3938         struct file *filp = NULL;
3939         struct file_lock file_lock;
3940         struct file_lock conflock;
3941         __be32 status = 0;
3942         unsigned int strhashval;
3943         int lkflg;
3944         int err;
3945
3946         dprintk("NFSD: nfsd4_lock: start=%Ld length=%Ld\n",
3947                 (long long) lock->lk_offset,
3948                 (long long) lock->lk_length);
3949
3950         if (check_lock_length(lock->lk_offset, lock->lk_length))
3951                  return nfserr_inval;
3952
3953         if ((status = fh_verify(rqstp, &cstate->current_fh,
3954                                 S_IFREG, NFSD_MAY_LOCK))) {
3955                 dprintk("NFSD: nfsd4_lock: permission denied!\n");
3956                 return status;
3957         }
3958
3959         nfs4_lock_state();
3960
3961         if (lock->lk_is_new) {
3962                 /*
3963                  * Client indicates that this is a new lockowner.
3964                  * Use open owner and open stateid to create lock owner and
3965                  * lock stateid.
3966                  */
3967                 struct nfs4_ol_stateid *open_stp = NULL;
3968                 
3969                 status = nfserr_stale_clientid;
3970                 if (!nfsd4_has_session(cstate) &&
3971                     STALE_CLIENTID(&lock->lk_new_clientid))
3972                         goto out;
3973
3974                 /* validate and update open stateid and open seqid */
3975                 status = nfs4_preprocess_confirmed_seqid_op(cstate,
3976                                         lock->lk_new_open_seqid,
3977                                         &lock->lk_new_open_stateid,
3978                                         &open_stp);
3979                 if (status)
3980                         goto out;
3981                 open_sop = openowner(open_stp->st_stateowner);
3982                 status = nfserr_bad_stateid;
3983                 if (!nfsd4_has_session(cstate) &&
3984                         !same_clid(&open_sop->oo_owner.so_client->cl_clientid,
3985                                                 &lock->v.new.clientid))
3986                         goto out;
3987                 /* create lockowner and lock stateid */
3988                 fp = open_stp->st_file;
3989                 strhashval = lock_ownerstr_hashval(fp->fi_inode,
3990                                 open_sop->oo_owner.so_client->cl_clientid.cl_id,
3991                                 &lock->v.new.owner);
3992                 /* XXX: Do we need to check for duplicate stateowners on
3993                  * the same file, or should they just be allowed (and
3994                  * create new stateids)? */
3995                 status = nfserr_jukebox;
3996                 lock_sop = alloc_init_lock_stateowner(strhashval,
3997                                 open_sop->oo_owner.so_client, open_stp, lock);
3998                 if (lock_sop == NULL)
3999                         goto out;
4000                 lock_stp = alloc_init_lock_stateid(lock_sop, fp, open_stp);
4001                 if (lock_stp == NULL)
4002                         goto out;
4003         } else {
4004                 /* lock (lock owner + lock stateid) already exists */
4005                 status = nfs4_preprocess_seqid_op(cstate,
4006                                        lock->lk_old_lock_seqid,
4007                                        &lock->lk_old_lock_stateid,
4008                                        NFS4_LOCK_STID, &lock_stp);
4009                 if (status)
4010                         goto out;
4011                 lock_sop = lockowner(lock_stp->st_stateowner);
4012                 fp = lock_stp->st_file;
4013         }
4014         /* lock_sop and lock_stp have been created or found */
4015
4016         lkflg = setlkflg(lock->lk_type);
4017         status = nfs4_check_openmode(lock_stp, lkflg);
4018         if (status)
4019                 goto out;
4020
4021         status = nfserr_grace;
4022         if (locks_in_grace() && !lock->lk_reclaim)
4023                 goto out;
4024         status = nfserr_no_grace;
4025         if (!locks_in_grace() && lock->lk_reclaim)
4026                 goto out;
4027
4028         locks_init_lock(&file_lock);
4029         switch (lock->lk_type) {
4030                 case NFS4_READ_LT:
4031                 case NFS4_READW_LT:
4032                         filp = find_readable_file(lock_stp->st_file);
4033                         if (filp)
4034                                 get_lock_access(lock_stp, NFS4_SHARE_ACCESS_READ);
4035                         file_lock.fl_type = F_RDLCK;
4036                         break;
4037                 case NFS4_WRITE_LT:
4038                 case NFS4_WRITEW_LT:
4039                         filp = find_writeable_file(lock_stp->st_file);
4040                         if (filp)
4041                                 get_lock_access(lock_stp, NFS4_SHARE_ACCESS_WRITE);
4042                         file_lock.fl_type = F_WRLCK;
4043                         break;
4044                 default:
4045                         status = nfserr_inval;
4046                 goto out;
4047         }
4048         if (!filp) {
4049                 status = nfserr_openmode;
4050                 goto out;
4051         }
4052         file_lock.fl_owner = (fl_owner_t)lock_sop;
4053         file_lock.fl_pid = current->tgid;
4054         file_lock.fl_file = filp;
4055         file_lock.fl_flags = FL_POSIX;
4056         file_lock.fl_lmops = &nfsd_posix_mng_ops;
4057
4058         file_lock.fl_start = lock->lk_offset;
4059         file_lock.fl_end = last_byte_offset(lock->lk_offset, lock->lk_length);
4060         nfs4_transform_lock_offset(&file_lock);
4061
4062         /*
4063         * Try to lock the file in the VFS.
4064         * Note: locks.c uses the BKL to protect the inode's lock list.
4065         */
4066
4067         err = vfs_lock_file(filp, F_SETLK, &file_lock, &conflock);
4068         switch (-err) {
4069         case 0: /* success! */
4070                 update_stateid(&lock_stp->st_stid.sc_stateid);
4071                 memcpy(&lock->lk_resp_stateid, &lock_stp->st_stid.sc_stateid, 
4072                                 sizeof(stateid_t));
4073                 status = 0;
4074                 break;
4075         case (EAGAIN):          /* conflock holds conflicting lock */
4076                 status = nfserr_denied;
4077                 dprintk("NFSD: nfsd4_lock: conflicting lock found!\n");
4078                 nfs4_set_lock_denied(&conflock, &lock->lk_denied);
4079                 break;
4080         case (EDEADLK):
4081                 status = nfserr_deadlock;
4082                 break;
4083         default:
4084                 dprintk("NFSD: nfsd4_lock: vfs_lock_file() failed! status %d\n",err);
4085                 status = nfserrno(err);
4086                 break;
4087         }
4088 out:
4089         if (status && lock->lk_is_new && lock_sop)
4090                 release_lockowner(lock_sop);
4091         if (!cstate->replay_owner)
4092                 nfs4_unlock_state();
4093         return status;
4094 }
4095
4096 /*
4097  * The NFSv4 spec allows a client to do a LOCKT without holding an OPEN,
4098  * so we do a temporary open here just to get an open file to pass to
4099  * vfs_test_lock.  (Arguably perhaps test_lock should be done with an
4100  * inode operation.)
4101  */
4102 static __be32 nfsd_test_lock(struct svc_rqst *rqstp, struct svc_fh *fhp, struct file_lock *lock)
4103 {
4104         struct file *file;
4105         __be32 err = nfsd_open(rqstp, fhp, S_IFREG, NFSD_MAY_READ, &file);
4106         if (!err) {
4107                 err = nfserrno(vfs_test_lock(file, lock));
4108                 nfsd_close(file);
4109         }
4110         return err;
4111 }
4112
4113 /*
4114  * LOCKT operation
4115  */
4116 __be32
4117 nfsd4_lockt(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
4118             struct nfsd4_lockt *lockt)
4119 {
4120         struct inode *inode;
4121         struct file_lock file_lock;
4122         struct nfs4_lockowner *lo;
4123         __be32 status;
4124
4125         if (locks_in_grace())
4126                 return nfserr_grace;
4127
4128         if (check_lock_length(lockt->lt_offset, lockt->lt_length))
4129                  return nfserr_inval;
4130
4131         nfs4_lock_state();
4132
4133         status = nfserr_stale_clientid;
4134         if (!nfsd4_has_session(cstate) && STALE_CLIENTID(&lockt->lt_clientid))
4135                 goto out;
4136
4137         if ((status = fh_verify(rqstp, &cstate->current_fh, S_IFREG, 0)))
4138                 goto out;
4139
4140         inode = cstate->current_fh.fh_dentry->d_inode;
4141         locks_init_lock(&file_lock);
4142         switch (lockt->lt_type) {
4143                 case NFS4_READ_LT:
4144                 case NFS4_READW_LT:
4145                         file_lock.fl_type = F_RDLCK;
4146                 break;
4147                 case NFS4_WRITE_LT:
4148                 case NFS4_WRITEW_LT:
4149                         file_lock.fl_type = F_WRLCK;
4150                 break;
4151                 default:
4152                         dprintk("NFSD: nfs4_lockt: bad lock type!\n");
4153                         status = nfserr_inval;
4154                 goto out;
4155         }
4156
4157         lo = find_lockowner_str(inode, &lockt->lt_clientid, &lockt->lt_owner);
4158         if (lo)
4159                 file_lock.fl_owner = (fl_owner_t)lo;
4160         file_lock.fl_pid = current->tgid;
4161         file_lock.fl_flags = FL_POSIX;
4162
4163         file_lock.fl_start = lockt->lt_offset;
4164         file_lock.fl_end = last_byte_offset(lockt->lt_offset, lockt->lt_length);
4165
4166         nfs4_transform_lock_offset(&file_lock);
4167
4168         status = nfsd_test_lock(rqstp, &cstate->current_fh, &file_lock);
4169         if (status)
4170                 goto out;
4171
4172         if (file_lock.fl_type != F_UNLCK) {
4173                 status = nfserr_denied;
4174                 nfs4_set_lock_denied(&file_lock, &lockt->lt_denied);
4175         }
4176 out:
4177         nfs4_unlock_state();
4178         return status;
4179 }
4180
4181 __be32
4182 nfsd4_locku(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
4183             struct nfsd4_locku *locku)
4184 {
4185         struct nfs4_ol_stateid *stp;
4186         struct file *filp = NULL;
4187         struct file_lock file_lock;
4188         __be32 status;
4189         int err;
4190                                                         
4191         dprintk("NFSD: nfsd4_locku: start=%Ld length=%Ld\n",
4192                 (long long) locku->lu_offset,
4193                 (long long) locku->lu_length);
4194
4195         if (check_lock_length(locku->lu_offset, locku->lu_length))
4196                  return nfserr_inval;
4197
4198         nfs4_lock_state();
4199                                                                                 
4200         status = nfs4_preprocess_seqid_op(cstate, locku->lu_seqid,
4201                                         &locku->lu_stateid, NFS4_LOCK_STID, &stp);
4202         if (status)
4203                 goto out;
4204         filp = find_any_file(stp->st_file);
4205         if (!filp) {
4206                 status = nfserr_lock_range;
4207                 goto out;
4208         }
4209         BUG_ON(!filp);
4210         locks_init_lock(&file_lock);
4211         file_lock.fl_type = F_UNLCK;
4212         file_lock.fl_owner = (fl_owner_t)lockowner(stp->st_stateowner);
4213         file_lock.fl_pid = current->tgid;
4214         file_lock.fl_file = filp;
4215         file_lock.fl_flags = FL_POSIX; 
4216         file_lock.fl_lmops = &nfsd_posix_mng_ops;
4217         file_lock.fl_start = locku->lu_offset;
4218
4219         file_lock.fl_end = last_byte_offset(locku->lu_offset, locku->lu_length);
4220         nfs4_transform_lock_offset(&file_lock);
4221
4222         /*
4223         *  Try to unlock the file in the VFS.
4224         */
4225         err = vfs_lock_file(filp, F_SETLK, &file_lock, NULL);
4226         if (err) {
4227                 dprintk("NFSD: nfs4_locku: vfs_lock_file failed!\n");
4228                 goto out_nfserr;
4229         }
4230         /*
4231         * OK, unlock succeeded; the only thing left to do is update the stateid.
4232         */
4233         update_stateid(&stp->st_stid.sc_stateid);
4234         memcpy(&locku->lu_stateid, &stp->st_stid.sc_stateid, sizeof(stateid_t));
4235
4236 out:
4237         if (!cstate->replay_owner)
4238                 nfs4_unlock_state();
4239         return status;
4240
4241 out_nfserr:
4242         status = nfserrno(err);
4243         goto out;
4244 }
4245
4246 /*
4247  * returns
4248  *      1: locks held by lockowner
4249  *      0: no locks held by lockowner
4250  */
4251 static int
4252 check_for_locks(struct nfs4_file *filp, struct nfs4_lockowner *lowner)
4253 {
4254         struct file_lock **flpp;
4255         struct inode *inode = filp->fi_inode;
4256         int status = 0;
4257
4258         lock_flocks();
4259         for (flpp = &inode->i_flock; *flpp != NULL; flpp = &(*flpp)->fl_next) {
4260                 if ((*flpp)->fl_owner == (fl_owner_t)lowner) {
4261                         status = 1;
4262                         goto out;
4263                 }
4264         }
4265 out:
4266         unlock_flocks();
4267         return status;
4268 }
4269
4270 __be32
4271 nfsd4_release_lockowner(struct svc_rqst *rqstp,
4272                         struct nfsd4_compound_state *cstate,
4273                         struct nfsd4_release_lockowner *rlockowner)
4274 {
4275         clientid_t *clid = &rlockowner->rl_clientid;
4276         struct nfs4_stateowner *sop;
4277         struct nfs4_lockowner *lo;
4278         struct nfs4_ol_stateid *stp;
4279         struct xdr_netobj *owner = &rlockowner->rl_owner;
4280         struct list_head matches;
4281         int i;
4282         __be32 status;
4283
4284         dprintk("nfsd4_release_lockowner clientid: (%08x/%08x):\n",
4285                 clid->cl_boot, clid->cl_id);
4286
4287         /* XXX check for lease expiration */
4288
4289         status = nfserr_stale_clientid;
4290         if (STALE_CLIENTID(clid))
4291                 return status;
4292
4293         nfs4_lock_state();
4294
4295         status = nfserr_locks_held;
4296         /* XXX: we're doing a linear search through all the lockowners.
4297          * Yipes!  For now we'll just hope clients aren't really using
4298          * release_lockowner much, but eventually we have to fix these
4299          * data structures. */
4300         INIT_LIST_HEAD(&matches);
4301         for (i = 0; i < LOCK_HASH_SIZE; i++) {
4302                 list_for_each_entry(sop, &lock_ownerstr_hashtbl[i], so_strhash) {
4303                         if (!same_owner_str(sop, owner, clid))
4304                                 continue;
4305                         list_for_each_entry(stp, &sop->so_stateids,
4306                                         st_perstateowner) {
4307                                 lo = lockowner(sop);
4308                                 if (check_for_locks(stp->st_file, lo))
4309                                         goto out;
4310                                 list_add(&lo->lo_list, &matches);
4311                         }
4312                 }
4313         }
4314         /* Clients probably won't expect us to return with some (but not all)
4315          * of the lockowner state released; so don't release any until all
4316          * have been checked. */
4317         status = nfs_ok;
4318         while (!list_empty(&matches)) {
4319                 lo = list_entry(matches.next, struct nfs4_lockowner,
4320                                                                 lo_list);
4321                 /* unhash_stateowner deletes so_perclient only
4322                  * for openowners. */
4323                 list_del(&lo->lo_list);
4324                 release_lockowner(lo);
4325         }
4326 out:
4327         nfs4_unlock_state();
4328         return status;
4329 }
4330
4331 static inline struct nfs4_client_reclaim *
4332 alloc_reclaim(void)
4333 {
4334         return kmalloc(sizeof(struct nfs4_client_reclaim), GFP_KERNEL);
4335 }
4336
4337 int
4338 nfs4_has_reclaimed_state(const char *name, bool use_exchange_id)
4339 {
4340         unsigned int strhashval = clientstr_hashval(name);
4341         struct nfs4_client *clp;
4342
4343         clp = find_confirmed_client_by_str(name, strhashval);
4344         return clp ? 1 : 0;
4345 }
4346
4347 /*
4348  * failure => all reset bets are off, nfserr_no_grace...
4349  */
4350 int
4351 nfs4_client_to_reclaim(const char *name)
4352 {
4353         unsigned int strhashval;
4354         struct nfs4_client_reclaim *crp = NULL;
4355
4356         dprintk("NFSD nfs4_client_to_reclaim NAME: %.*s\n", HEXDIR_LEN, name);
4357         crp = alloc_reclaim();
4358         if (!crp)
4359                 return 0;
4360         strhashval = clientstr_hashval(name);
4361         INIT_LIST_HEAD(&crp->cr_strhash);
4362         list_add(&crp->cr_strhash, &reclaim_str_hashtbl[strhashval]);
4363         memcpy(crp->cr_recdir, name, HEXDIR_LEN);
4364         reclaim_str_hashtbl_size++;
4365         return 1;
4366 }
4367
4368 static void
4369 nfs4_release_reclaim(void)
4370 {
4371         struct nfs4_client_reclaim *crp = NULL;
4372         int i;
4373
4374         for (i = 0; i < CLIENT_HASH_SIZE; i++) {
4375                 while (!list_empty(&reclaim_str_hashtbl[i])) {
4376                         crp = list_entry(reclaim_str_hashtbl[i].next,
4377                                         struct nfs4_client_reclaim, cr_strhash);
4378                         list_del(&crp->cr_strhash);
4379                         kfree(crp);
4380                         reclaim_str_hashtbl_size--;
4381                 }
4382         }
4383         BUG_ON(reclaim_str_hashtbl_size);
4384 }
4385
4386 /*
4387  * called from OPEN, CLAIM_PREVIOUS with a new clientid. */
4388 static struct nfs4_client_reclaim *
4389 nfs4_find_reclaim_client(clientid_t *clid)
4390 {
4391         unsigned int strhashval;
4392         struct nfs4_client *clp;
4393         struct nfs4_client_reclaim *crp = NULL;
4394
4395
4396         /* find clientid in conf_id_hashtbl */
4397         clp = find_confirmed_client(clid);
4398         if (clp == NULL)
4399                 return NULL;
4400
4401         dprintk("NFSD: nfs4_find_reclaim_client for %.*s with recdir %s\n",
4402                             clp->cl_name.len, clp->cl_name.data,
4403                             clp->cl_recdir);
4404
4405         /* find clp->cl_name in reclaim_str_hashtbl */
4406         strhashval = clientstr_hashval(clp->cl_recdir);
4407         list_for_each_entry(crp, &reclaim_str_hashtbl[strhashval], cr_strhash) {
4408                 if (same_name(crp->cr_recdir, clp->cl_recdir)) {
4409                         return crp;
4410                 }
4411         }
4412         return NULL;
4413 }
4414
4415 /*
4416 * Called from OPEN. Look for clientid in reclaim list.
4417 */
4418 __be32
4419 nfs4_check_open_reclaim(clientid_t *clid)
4420 {
4421         return nfs4_find_reclaim_client(clid) ? nfs_ok : nfserr_reclaim_bad;
4422 }
4423
4424 /* initialization to perform at module load time: */
4425
4426 int
4427 nfs4_state_init(void)
4428 {
4429         int i, status;
4430
4431         status = nfsd4_init_slabs();
4432         if (status)
4433                 return status;
4434         for (i = 0; i < CLIENT_HASH_SIZE; i++) {
4435                 INIT_LIST_HEAD(&conf_id_hashtbl[i]);
4436                 INIT_LIST_HEAD(&conf_str_hashtbl[i]);
4437                 INIT_LIST_HEAD(&unconf_str_hashtbl[i]);
4438                 INIT_LIST_HEAD(&unconf_id_hashtbl[i]);
4439                 INIT_LIST_HEAD(&reclaim_str_hashtbl[i]);
4440         }
4441         for (i = 0; i < SESSION_HASH_SIZE; i++)
4442                 INIT_LIST_HEAD(&sessionid_hashtbl[i]);
4443         for (i = 0; i < FILE_HASH_SIZE; i++) {
4444                 INIT_LIST_HEAD(&file_hashtbl[i]);
4445         }
4446         for (i = 0; i < OPEN_OWNER_HASH_SIZE; i++) {
4447                 INIT_LIST_HEAD(&open_ownerstr_hashtbl[i]);
4448         }
4449         for (i = 0; i < LOCK_HASH_SIZE; i++) {
4450                 INIT_LIST_HEAD(&lock_ownerstr_hashtbl[i]);
4451         }
4452         memset(&onestateid, ~0, sizeof(stateid_t));
4453         INIT_LIST_HEAD(&close_lru);
4454         INIT_LIST_HEAD(&client_lru);
4455         INIT_LIST_HEAD(&del_recall_lru);
4456         reclaim_str_hashtbl_size = 0;
4457         return 0;
4458 }
4459
4460 static void
4461 nfsd4_load_reboot_recovery_data(void)
4462 {
4463         int status;
4464
4465         nfs4_lock_state();
4466         nfsd4_init_recdir();
4467         status = nfsd4_recdir_load();
4468         nfs4_unlock_state();
4469         if (status)
4470                 printk("NFSD: Failure reading reboot recovery data\n");
4471 }
4472
4473 /*
4474  * Since the lifetime of a delegation isn't limited to that of an open, a
4475  * client may quite reasonably hang on to a delegation as long as it has
4476  * the inode cached.  This becomes an obvious problem the first time a
4477  * client's inode cache approaches the size of the server's total memory.
4478  *
4479  * For now we avoid this problem by imposing a hard limit on the number
4480  * of delegations, which varies according to the server's memory size.
4481  */
4482 static void
4483 set_max_delegations(void)
4484 {
4485         /*
4486          * Allow at most 4 delegations per megabyte of RAM.  Quick
4487          * estimates suggest that in the worst case (where every delegation
4488          * is for a different inode), a delegation could take about 1.5K,
4489          * giving a worst case usage of about 6% of memory.
4490          */
4491         max_delegations = nr_free_buffer_pages() >> (20 - 2 - PAGE_SHIFT);
4492 }
4493
4494 /* initialization to perform when the nfsd service is started: */
4495
4496 static int
4497 __nfs4_state_start(void)
4498 {
4499         int ret;
4500
4501         boot_time = get_seconds();
4502         locks_start_grace(&nfsd4_manager);
4503         printk(KERN_INFO "NFSD: starting %ld-second grace period\n",
4504                nfsd4_grace);
4505         ret = set_callback_cred();
4506         if (ret)
4507                 return -ENOMEM;
4508         laundry_wq = create_singlethread_workqueue("nfsd4");
4509         if (laundry_wq == NULL)
4510                 return -ENOMEM;
4511         ret = nfsd4_create_callback_queue();
4512         if (ret)
4513                 goto out_free_laundry;
4514         queue_delayed_work(laundry_wq, &laundromat_work, nfsd4_grace * HZ);
4515         set_max_delegations();
4516         return 0;
4517 out_free_laundry:
4518         destroy_workqueue(laundry_wq);
4519         return ret;
4520 }
4521
4522 int
4523 nfs4_state_start(void)
4524 {
4525         nfsd4_load_reboot_recovery_data();
4526         return __nfs4_state_start();
4527 }
4528
4529 static void
4530 __nfs4_state_shutdown(void)
4531 {
4532         int i;
4533         struct nfs4_client *clp = NULL;
4534         struct nfs4_delegation *dp = NULL;
4535         struct list_head *pos, *next, reaplist;
4536
4537         for (i = 0; i < CLIENT_HASH_SIZE; i++) {
4538                 while (!list_empty(&conf_id_hashtbl[i])) {
4539                         clp = list_entry(conf_id_hashtbl[i].next, struct nfs4_client, cl_idhash);
4540                         expire_client(clp);
4541                 }
4542                 while (!list_empty(&unconf_str_hashtbl[i])) {
4543                         clp = list_entry(unconf_str_hashtbl[i].next, struct nfs4_client, cl_strhash);
4544                         expire_client(clp);
4545                 }
4546         }
4547         INIT_LIST_HEAD(&reaplist);
4548         spin_lock(&recall_lock);
4549         list_for_each_safe(pos, next, &del_recall_lru) {
4550                 dp = list_entry (pos, struct nfs4_delegation, dl_recall_lru);
4551                 list_move(&dp->dl_recall_lru, &reaplist);
4552         }
4553         spin_unlock(&recall_lock);
4554         list_for_each_safe(pos, next, &reaplist) {
4555                 dp = list_entry (pos, struct nfs4_delegation, dl_recall_lru);
4556                 list_del_init(&dp->dl_recall_lru);
4557                 unhash_delegation(dp);
4558         }
4559
4560         nfsd4_shutdown_recdir();
4561 }
4562
4563 void
4564 nfs4_state_shutdown(void)
4565 {
4566         cancel_delayed_work_sync(&laundromat_work);
4567         destroy_workqueue(laundry_wq);
4568         locks_end_grace(&nfsd4_manager);
4569         nfs4_lock_state();
4570         nfs4_release_reclaim();
4571         __nfs4_state_shutdown();
4572         nfs4_unlock_state();
4573         nfsd4_destroy_callback_queue();
4574 }