nfsd: fix the check for confirmed openowner in nfs4_preprocess_stateid_op
[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 = fl->fl_file;
2829         get_file(fp->fi_deleg_file);
2830         atomic_set(&fp->fi_delegees, 1);
2831         spin_lock(&recall_lock);
2832         hash_delegation_locked(dp, fp);
2833         spin_unlock(&recall_lock);
2834         return 0;
2835 }
2836
2837 static int nfs4_set_delegation(struct nfs4_delegation *dp, int flag)
2838 {
2839         struct nfs4_file *fp = dp->dl_file;
2840
2841         if (!fp->fi_lease)
2842                 return nfs4_setlease(dp, flag);
2843         spin_lock(&recall_lock);
2844         if (fp->fi_had_conflict) {
2845                 spin_unlock(&recall_lock);
2846                 return -EAGAIN;
2847         }
2848         atomic_inc(&fp->fi_delegees);
2849         hash_delegation_locked(dp, fp);
2850         spin_unlock(&recall_lock);
2851         return 0;
2852 }
2853
2854 /*
2855  * Attempt to hand out a delegation.
2856  */
2857 static void
2858 nfs4_open_delegation(struct svc_fh *fh, struct nfsd4_open *open, struct nfs4_ol_stateid *stp)
2859 {
2860         struct nfs4_delegation *dp;
2861         struct nfs4_openowner *oo = container_of(stp->st_stateowner, struct nfs4_openowner, oo_owner);
2862         int cb_up;
2863         int status, flag = 0;
2864
2865         cb_up = nfsd4_cb_channel_good(oo->oo_owner.so_client);
2866         flag = NFS4_OPEN_DELEGATE_NONE;
2867         open->op_recall = 0;
2868         switch (open->op_claim_type) {
2869                 case NFS4_OPEN_CLAIM_PREVIOUS:
2870                         if (!cb_up)
2871                                 open->op_recall = 1;
2872                         flag = open->op_delegate_type;
2873                         if (flag == NFS4_OPEN_DELEGATE_NONE)
2874                                 goto out;
2875                         break;
2876                 case NFS4_OPEN_CLAIM_NULL:
2877                         /* Let's not give out any delegations till everyone's
2878                          * had the chance to reclaim theirs.... */
2879                         if (locks_in_grace())
2880                                 goto out;
2881                         if (!cb_up || !(oo->oo_flags & NFS4_OO_CONFIRMED))
2882                                 goto out;
2883                         if (open->op_share_access & NFS4_SHARE_ACCESS_WRITE)
2884                                 flag = NFS4_OPEN_DELEGATE_WRITE;
2885                         else
2886                                 flag = NFS4_OPEN_DELEGATE_READ;
2887                         break;
2888                 default:
2889                         goto out;
2890         }
2891
2892         dp = alloc_init_deleg(oo->oo_owner.so_client, stp, fh, flag);
2893         if (dp == NULL)
2894                 goto out_no_deleg;
2895         status = nfs4_set_delegation(dp, flag);
2896         if (status)
2897                 goto out_free;
2898
2899         memcpy(&open->op_delegate_stateid, &dp->dl_stid.sc_stateid, sizeof(dp->dl_stid.sc_stateid));
2900
2901         dprintk("NFSD: delegation stateid=" STATEID_FMT "\n",
2902                 STATEID_VAL(&dp->dl_stid.sc_stateid));
2903 out:
2904         if (open->op_claim_type == NFS4_OPEN_CLAIM_PREVIOUS
2905                         && flag == NFS4_OPEN_DELEGATE_NONE
2906                         && open->op_delegate_type != NFS4_OPEN_DELEGATE_NONE)
2907                 dprintk("NFSD: WARNING: refusing delegation reclaim\n");
2908         open->op_delegate_type = flag;
2909         return;
2910 out_free:
2911         nfs4_put_delegation(dp);
2912 out_no_deleg:
2913         flag = NFS4_OPEN_DELEGATE_NONE;
2914         goto out;
2915 }
2916
2917 /*
2918  * called with nfs4_lock_state() held.
2919  */
2920 __be32
2921 nfsd4_process_open2(struct svc_rqst *rqstp, struct svc_fh *current_fh, struct nfsd4_open *open)
2922 {
2923         struct nfsd4_compoundres *resp = rqstp->rq_resp;
2924         struct nfs4_client *cl = open->op_openowner->oo_owner.so_client;
2925         struct nfs4_file *fp = NULL;
2926         struct inode *ino = current_fh->fh_dentry->d_inode;
2927         struct nfs4_ol_stateid *stp = NULL;
2928         struct nfs4_delegation *dp = NULL;
2929         __be32 status;
2930
2931         /*
2932          * Lookup file; if found, lookup stateid and check open request,
2933          * and check for delegations in the process of being recalled.
2934          * If not found, create the nfs4_file struct
2935          */
2936         fp = find_file(ino);
2937         if (fp) {
2938                 if ((status = nfs4_check_open(fp, open, &stp)))
2939                         goto out;
2940                 status = nfs4_check_deleg(cl, fp, open, &dp);
2941                 if (status)
2942                         goto out;
2943         } else {
2944                 status = nfserr_bad_stateid;
2945                 if (nfsd4_is_deleg_cur(open))
2946                         goto out;
2947                 status = nfserr_jukebox;
2948                 fp = open->op_file;
2949                 open->op_file = NULL;
2950                 nfsd4_init_file(fp, ino);
2951         }
2952
2953         /*
2954          * OPEN the file, or upgrade an existing OPEN.
2955          * If truncate fails, the OPEN fails.
2956          */
2957         if (stp) {
2958                 /* Stateid was found, this is an OPEN upgrade */
2959                 status = nfs4_upgrade_open(rqstp, fp, current_fh, stp, open);
2960                 if (status)
2961                         goto out;
2962         } else {
2963                 status = nfs4_get_vfs_file(rqstp, fp, current_fh, open);
2964                 if (status)
2965                         goto out;
2966                 stp = open->op_stp;
2967                 open->op_stp = NULL;
2968                 init_open_stateid(stp, fp, open);
2969                 status = nfsd4_truncate(rqstp, current_fh, open);
2970                 if (status) {
2971                         release_open_stateid(stp);
2972                         goto out;
2973                 }
2974         }
2975         update_stateid(&stp->st_stid.sc_stateid);
2976         memcpy(&open->op_stateid, &stp->st_stid.sc_stateid, sizeof(stateid_t));
2977
2978         if (nfsd4_has_session(&resp->cstate))
2979                 open->op_openowner->oo_flags |= NFS4_OO_CONFIRMED;
2980
2981         /*
2982         * Attempt to hand out a delegation. No error return, because the
2983         * OPEN succeeds even if we fail.
2984         */
2985         nfs4_open_delegation(current_fh, open, stp);
2986
2987         status = nfs_ok;
2988
2989         dprintk("%s: stateid=" STATEID_FMT "\n", __func__,
2990                 STATEID_VAL(&stp->st_stid.sc_stateid));
2991 out:
2992         if (fp)
2993                 put_nfs4_file(fp);
2994         if (status == 0 && open->op_claim_type == NFS4_OPEN_CLAIM_PREVIOUS)
2995                 nfs4_set_claim_prev(open);
2996         /*
2997         * To finish the open response, we just need to set the rflags.
2998         */
2999         open->op_rflags = NFS4_OPEN_RESULT_LOCKTYPE_POSIX;
3000         if (!(open->op_openowner->oo_flags & NFS4_OO_CONFIRMED) &&
3001             !nfsd4_has_session(&resp->cstate))
3002                 open->op_rflags |= NFS4_OPEN_RESULT_CONFIRM;
3003
3004         return status;
3005 }
3006
3007 void nfsd4_cleanup_open_state(struct nfsd4_open *open, __be32 status)
3008 {
3009         if (open->op_openowner) {
3010                 struct nfs4_openowner *oo = open->op_openowner;
3011
3012                 if (!list_empty(&oo->oo_owner.so_stateids))
3013                         list_del_init(&oo->oo_close_lru);
3014                 if (oo->oo_flags & NFS4_OO_NEW) {
3015                         if (status) {
3016                                 release_openowner(oo);
3017                                 open->op_openowner = NULL;
3018                         } else
3019                                 oo->oo_flags &= ~NFS4_OO_NEW;
3020                 }
3021         }
3022         if (open->op_file)
3023                 nfsd4_free_file(open->op_file);
3024         if (open->op_stp)
3025                 nfs4_free_stateid(open->op_stp);
3026 }
3027
3028 __be32
3029 nfsd4_renew(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3030             clientid_t *clid)
3031 {
3032         struct nfs4_client *clp;
3033         __be32 status;
3034
3035         nfs4_lock_state();
3036         dprintk("process_renew(%08x/%08x): starting\n", 
3037                         clid->cl_boot, clid->cl_id);
3038         status = nfserr_stale_clientid;
3039         if (STALE_CLIENTID(clid))
3040                 goto out;
3041         clp = find_confirmed_client(clid);
3042         status = nfserr_expired;
3043         if (clp == NULL) {
3044                 /* We assume the client took too long to RENEW. */
3045                 dprintk("nfsd4_renew: clientid not found!\n");
3046                 goto out;
3047         }
3048         status = nfserr_cb_path_down;
3049         if (!list_empty(&clp->cl_delegations)
3050                         && clp->cl_cb_state != NFSD4_CB_UP)
3051                 goto out;
3052         status = nfs_ok;
3053 out:
3054         nfs4_unlock_state();
3055         return status;
3056 }
3057
3058 static struct lock_manager nfsd4_manager = {
3059 };
3060
3061 static void
3062 nfsd4_end_grace(void)
3063 {
3064         dprintk("NFSD: end of grace period\n");
3065         nfsd4_recdir_purge_old();
3066         locks_end_grace(&nfsd4_manager);
3067         /*
3068          * Now that every NFSv4 client has had the chance to recover and
3069          * to see the (possibly new, possibly shorter) lease time, we
3070          * can safely set the next grace time to the current lease time:
3071          */
3072         nfsd4_grace = nfsd4_lease;
3073 }
3074
3075 static time_t
3076 nfs4_laundromat(void)
3077 {
3078         struct nfs4_client *clp;
3079         struct nfs4_openowner *oo;
3080         struct nfs4_delegation *dp;
3081         struct list_head *pos, *next, reaplist;
3082         time_t cutoff = get_seconds() - nfsd4_lease;
3083         time_t t, clientid_val = nfsd4_lease;
3084         time_t u, test_val = nfsd4_lease;
3085
3086         nfs4_lock_state();
3087
3088         dprintk("NFSD: laundromat service - starting\n");
3089         if (locks_in_grace())
3090                 nfsd4_end_grace();
3091         INIT_LIST_HEAD(&reaplist);
3092         spin_lock(&client_lock);
3093         list_for_each_safe(pos, next, &client_lru) {
3094                 clp = list_entry(pos, struct nfs4_client, cl_lru);
3095                 if (time_after((unsigned long)clp->cl_time, (unsigned long)cutoff)) {
3096                         t = clp->cl_time - cutoff;
3097                         if (clientid_val > t)
3098                                 clientid_val = t;
3099                         break;
3100                 }
3101                 if (atomic_read(&clp->cl_refcount)) {
3102                         dprintk("NFSD: client in use (clientid %08x)\n",
3103                                 clp->cl_clientid.cl_id);
3104                         continue;
3105                 }
3106                 unhash_client_locked(clp);
3107                 list_add(&clp->cl_lru, &reaplist);
3108         }
3109         spin_unlock(&client_lock);
3110         list_for_each_safe(pos, next, &reaplist) {
3111                 clp = list_entry(pos, struct nfs4_client, cl_lru);
3112                 dprintk("NFSD: purging unused client (clientid %08x)\n",
3113                         clp->cl_clientid.cl_id);
3114                 nfsd4_remove_clid_dir(clp);
3115                 expire_client(clp);
3116         }
3117         spin_lock(&recall_lock);
3118         list_for_each_safe(pos, next, &del_recall_lru) {
3119                 dp = list_entry (pos, struct nfs4_delegation, dl_recall_lru);
3120                 if (time_after((unsigned long)dp->dl_time, (unsigned long)cutoff)) {
3121                         u = dp->dl_time - cutoff;
3122                         if (test_val > u)
3123                                 test_val = u;
3124                         break;
3125                 }
3126                 list_move(&dp->dl_recall_lru, &reaplist);
3127         }
3128         spin_unlock(&recall_lock);
3129         list_for_each_safe(pos, next, &reaplist) {
3130                 dp = list_entry (pos, struct nfs4_delegation, dl_recall_lru);
3131                 list_del_init(&dp->dl_recall_lru);
3132                 unhash_delegation(dp);
3133         }
3134         test_val = nfsd4_lease;
3135         list_for_each_safe(pos, next, &close_lru) {
3136                 oo = container_of(pos, struct nfs4_openowner, oo_close_lru);
3137                 if (time_after((unsigned long)oo->oo_time, (unsigned long)cutoff)) {
3138                         u = oo->oo_time - cutoff;
3139                         if (test_val > u)
3140                                 test_val = u;
3141                         break;
3142                 }
3143                 release_openowner(oo);
3144         }
3145         if (clientid_val < NFSD_LAUNDROMAT_MINTIMEOUT)
3146                 clientid_val = NFSD_LAUNDROMAT_MINTIMEOUT;
3147         nfs4_unlock_state();
3148         return clientid_val;
3149 }
3150
3151 static struct workqueue_struct *laundry_wq;
3152 static void laundromat_main(struct work_struct *);
3153 static DECLARE_DELAYED_WORK(laundromat_work, laundromat_main);
3154
3155 static void
3156 laundromat_main(struct work_struct *not_used)
3157 {
3158         time_t t;
3159
3160         t = nfs4_laundromat();
3161         dprintk("NFSD: laundromat_main - sleeping for %ld seconds\n", t);
3162         queue_delayed_work(laundry_wq, &laundromat_work, t*HZ);
3163 }
3164
3165 static inline __be32 nfs4_check_fh(struct svc_fh *fhp, struct nfs4_ol_stateid *stp)
3166 {
3167         if (fhp->fh_dentry->d_inode != stp->st_file->fi_inode)
3168                 return nfserr_bad_stateid;
3169         return nfs_ok;
3170 }
3171
3172 static int
3173 STALE_STATEID(stateid_t *stateid)
3174 {
3175         if (stateid->si_opaque.so_clid.cl_boot == boot_time)
3176                 return 0;
3177         dprintk("NFSD: stale stateid " STATEID_FMT "!\n",
3178                 STATEID_VAL(stateid));
3179         return 1;
3180 }
3181
3182 static inline int
3183 access_permit_read(unsigned long access_bmap)
3184 {
3185         return test_bit(NFS4_SHARE_ACCESS_READ, &access_bmap) ||
3186                 test_bit(NFS4_SHARE_ACCESS_BOTH, &access_bmap) ||
3187                 test_bit(NFS4_SHARE_ACCESS_WRITE, &access_bmap);
3188 }
3189
3190 static inline int
3191 access_permit_write(unsigned long access_bmap)
3192 {
3193         return test_bit(NFS4_SHARE_ACCESS_WRITE, &access_bmap) ||
3194                 test_bit(NFS4_SHARE_ACCESS_BOTH, &access_bmap);
3195 }
3196
3197 static
3198 __be32 nfs4_check_openmode(struct nfs4_ol_stateid *stp, int flags)
3199 {
3200         __be32 status = nfserr_openmode;
3201
3202         /* For lock stateid's, we test the parent open, not the lock: */
3203         if (stp->st_openstp)
3204                 stp = stp->st_openstp;
3205         if ((flags & WR_STATE) && (!access_permit_write(stp->st_access_bmap)))
3206                 goto out;
3207         if ((flags & RD_STATE) && (!access_permit_read(stp->st_access_bmap)))
3208                 goto out;
3209         status = nfs_ok;
3210 out:
3211         return status;
3212 }
3213
3214 static inline __be32
3215 check_special_stateids(svc_fh *current_fh, stateid_t *stateid, int flags)
3216 {
3217         if (ONE_STATEID(stateid) && (flags & RD_STATE))
3218                 return nfs_ok;
3219         else if (locks_in_grace()) {
3220                 /* Answer in remaining cases depends on existence of
3221                  * conflicting state; so we must wait out the grace period. */
3222                 return nfserr_grace;
3223         } else if (flags & WR_STATE)
3224                 return nfs4_share_conflict(current_fh,
3225                                 NFS4_SHARE_DENY_WRITE);
3226         else /* (flags & RD_STATE) && ZERO_STATEID(stateid) */
3227                 return nfs4_share_conflict(current_fh,
3228                                 NFS4_SHARE_DENY_READ);
3229 }
3230
3231 /*
3232  * Allow READ/WRITE during grace period on recovered state only for files
3233  * that are not able to provide mandatory locking.
3234  */
3235 static inline int
3236 grace_disallows_io(struct inode *inode)
3237 {
3238         return locks_in_grace() && mandatory_lock(inode);
3239 }
3240
3241 /* Returns true iff a is later than b: */
3242 static bool stateid_generation_after(stateid_t *a, stateid_t *b)
3243 {
3244         return (s32)a->si_generation - (s32)b->si_generation > 0;
3245 }
3246
3247 static int check_stateid_generation(stateid_t *in, stateid_t *ref, bool has_session)
3248 {
3249         /*
3250          * When sessions are used the stateid generation number is ignored
3251          * when it is zero.
3252          */
3253         if (has_session && in->si_generation == 0)
3254                 return nfs_ok;
3255
3256         if (in->si_generation == ref->si_generation)
3257                 return nfs_ok;
3258
3259         /* If the client sends us a stateid from the future, it's buggy: */
3260         if (stateid_generation_after(in, ref))
3261                 return nfserr_bad_stateid;
3262         /*
3263          * However, we could see a stateid from the past, even from a
3264          * non-buggy client.  For example, if the client sends a lock
3265          * while some IO is outstanding, the lock may bump si_generation
3266          * while the IO is still in flight.  The client could avoid that
3267          * situation by waiting for responses on all the IO requests,
3268          * but better performance may result in retrying IO that
3269          * receives an old_stateid error if requests are rarely
3270          * reordered in flight:
3271          */
3272         return nfserr_old_stateid;
3273 }
3274
3275 static __be32 nfsd4_check_openowner_confirmed(struct nfs4_ol_stateid *ols)
3276 {
3277         if (ols->st_stateowner->so_is_open_owner &&
3278             !(openowner(ols->st_stateowner)->oo_flags & NFS4_OO_CONFIRMED))
3279                 return nfserr_bad_stateid;
3280         return nfs_ok;
3281 }
3282
3283 __be32 nfs4_validate_stateid(struct nfs4_client *cl, stateid_t *stateid)
3284 {
3285         struct nfs4_stid *s;
3286         __be32 status;
3287
3288         if (STALE_STATEID(stateid))
3289                 return nfserr_stale_stateid;
3290
3291         s = find_stateid(cl, stateid);
3292         if (!s)
3293                  return nfserr_stale_stateid;
3294         status = check_stateid_generation(stateid, &s->sc_stateid, 1);
3295         if (status)
3296                 return status;
3297         if (!(s->sc_type & (NFS4_OPEN_STID | NFS4_LOCK_STID)))
3298                 return nfs_ok;
3299         return nfsd4_check_openowner_confirmed(openlockstateid(s));
3300 }
3301
3302 static __be32 nfsd4_lookup_stateid(stateid_t *stateid, unsigned char typemask, struct nfs4_stid **s)
3303 {
3304         struct nfs4_client *cl;
3305
3306         if (ZERO_STATEID(stateid) || ONE_STATEID(stateid))
3307                 return nfserr_bad_stateid;
3308         if (STALE_STATEID(stateid))
3309                 return nfserr_stale_stateid;
3310         cl = find_confirmed_client(&stateid->si_opaque.so_clid);
3311         if (!cl)
3312                 return nfserr_expired;
3313         *s = find_stateid_by_type(cl, stateid, typemask);
3314         if (!*s)
3315                 return nfserr_bad_stateid;
3316         return nfs_ok;
3317
3318 }
3319
3320 /*
3321 * Checks for stateid operations
3322 */
3323 __be32
3324 nfs4_preprocess_stateid_op(struct nfsd4_compound_state *cstate,
3325                            stateid_t *stateid, int flags, struct file **filpp)
3326 {
3327         struct nfs4_stid *s;
3328         struct nfs4_ol_stateid *stp = NULL;
3329         struct nfs4_delegation *dp = NULL;
3330         struct svc_fh *current_fh = &cstate->current_fh;
3331         struct inode *ino = current_fh->fh_dentry->d_inode;
3332         __be32 status;
3333
3334         if (filpp)
3335                 *filpp = NULL;
3336
3337         if (grace_disallows_io(ino))
3338                 return nfserr_grace;
3339
3340         if (ZERO_STATEID(stateid) || ONE_STATEID(stateid))
3341                 return check_special_stateids(current_fh, stateid, flags);
3342
3343         status = nfsd4_lookup_stateid(stateid, NFS4_DELEG_STID|NFS4_OPEN_STID|NFS4_LOCK_STID, &s);
3344         if (status)
3345                 return status;
3346         status = check_stateid_generation(stateid, &s->sc_stateid, nfsd4_has_session(cstate));
3347         if (status)
3348                 goto out;
3349         switch (s->sc_type) {
3350         case NFS4_DELEG_STID:
3351                 dp = delegstateid(s);
3352                 status = nfs4_check_delegmode(dp, flags);
3353                 if (status)
3354                         goto out;
3355                 if (filpp) {
3356                         *filpp = dp->dl_file->fi_deleg_file;
3357                         BUG_ON(!*filpp);
3358                 }
3359                 break;
3360         case NFS4_OPEN_STID:
3361         case NFS4_LOCK_STID:
3362                 stp = openlockstateid(s);
3363                 status = nfs4_check_fh(current_fh, stp);
3364                 if (status)
3365                         goto out;
3366                 status = nfsd4_check_openowner_confirmed(stp);
3367                 if (status)
3368                         goto out;
3369                 status = nfs4_check_openmode(stp, flags);
3370                 if (status)
3371                         goto out;
3372                 if (filpp) {
3373                         if (flags & RD_STATE)
3374                                 *filpp = find_readable_file(stp->st_file);
3375                         else
3376                                 *filpp = find_writeable_file(stp->st_file);
3377                 }
3378                 break;
3379         default:
3380                 return nfserr_bad_stateid;
3381         }
3382         status = nfs_ok;
3383 out:
3384         return status;
3385 }
3386
3387 static __be32
3388 nfsd4_free_lock_stateid(struct nfs4_ol_stateid *stp)
3389 {
3390         struct nfs4_lockowner *lo = lockowner(stp->st_stateowner);
3391
3392         if (check_for_locks(stp->st_file, lo))
3393                 return nfserr_locks_held;
3394         /*
3395          * Currently there's a 1-1 lock stateid<->lockowner
3396          * correspondance, and we have to delete the lockowner when we
3397          * delete the lock stateid:
3398          */
3399         release_lockowner(lo);
3400         return nfs_ok;
3401 }
3402
3403 /*
3404  * Test if the stateid is valid
3405  */
3406 __be32
3407 nfsd4_test_stateid(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3408                    struct nfsd4_test_stateid *test_stateid)
3409 {
3410         /* real work is done during encoding */
3411         return nfs_ok;
3412 }
3413
3414 __be32
3415 nfsd4_free_stateid(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3416                    struct nfsd4_free_stateid *free_stateid)
3417 {
3418         stateid_t *stateid = &free_stateid->fr_stateid;
3419         struct nfs4_stid *s;
3420         struct nfs4_client *cl = cstate->session->se_client;
3421         __be32 ret = nfserr_bad_stateid;
3422
3423         nfs4_lock_state();
3424         s = find_stateid(cl, stateid);
3425         if (!s)
3426                 goto out;
3427         switch (s->sc_type) {
3428         case NFS4_DELEG_STID:
3429                 ret = nfserr_locks_held;
3430                 goto out;
3431         case NFS4_OPEN_STID:
3432         case NFS4_LOCK_STID:
3433                 ret = check_stateid_generation(stateid, &s->sc_stateid, 1);
3434                 if (ret)
3435                         goto out;
3436                 if (s->sc_type == NFS4_LOCK_STID)
3437                         ret = nfsd4_free_lock_stateid(openlockstateid(s));
3438                 else
3439                         ret = nfserr_locks_held;
3440                 break;
3441         default:
3442                 ret = nfserr_bad_stateid;
3443         }
3444 out:
3445         nfs4_unlock_state();
3446         return ret;
3447 }
3448
3449 static inline int
3450 setlkflg (int type)
3451 {
3452         return (type == NFS4_READW_LT || type == NFS4_READ_LT) ?
3453                 RD_STATE : WR_STATE;
3454 }
3455
3456 static __be32 nfs4_seqid_op_checks(struct nfsd4_compound_state *cstate, stateid_t *stateid, u32 seqid, struct nfs4_ol_stateid *stp)
3457 {
3458         struct svc_fh *current_fh = &cstate->current_fh;
3459         struct nfs4_stateowner *sop = stp->st_stateowner;
3460         __be32 status;
3461
3462         status = nfsd4_check_seqid(cstate, sop, seqid);
3463         if (status)
3464                 return status;
3465         if (stp->st_stid.sc_type == NFS4_CLOSED_STID)
3466                 /*
3467                  * "Closed" stateid's exist *only* to return
3468                  * nfserr_replay_me from the previous step.
3469                  */
3470                 return nfserr_bad_stateid;
3471         status = check_stateid_generation(stateid, &stp->st_stid.sc_stateid, nfsd4_has_session(cstate));
3472         if (status)
3473                 return status;
3474         return nfs4_check_fh(current_fh, stp);
3475 }
3476
3477 /* 
3478  * Checks for sequence id mutating operations. 
3479  */
3480 static __be32
3481 nfs4_preprocess_seqid_op(struct nfsd4_compound_state *cstate, u32 seqid,
3482                          stateid_t *stateid, char typemask,
3483                          struct nfs4_ol_stateid **stpp)
3484 {
3485         __be32 status;
3486         struct nfs4_stid *s;
3487
3488         dprintk("NFSD: %s: seqid=%d stateid = " STATEID_FMT "\n", __func__,
3489                 seqid, STATEID_VAL(stateid));
3490
3491         *stpp = NULL;
3492         status = nfsd4_lookup_stateid(stateid, typemask, &s);
3493         if (status)
3494                 return status;
3495         *stpp = openlockstateid(s);
3496         cstate->replay_owner = (*stpp)->st_stateowner;
3497
3498         return nfs4_seqid_op_checks(cstate, stateid, seqid, *stpp);
3499 }
3500
3501 static __be32 nfs4_preprocess_confirmed_seqid_op(struct nfsd4_compound_state *cstate, u32 seqid, stateid_t *stateid, struct nfs4_ol_stateid **stpp)
3502 {
3503         __be32 status;
3504         struct nfs4_openowner *oo;
3505
3506         status = nfs4_preprocess_seqid_op(cstate, seqid, stateid,
3507                                                 NFS4_OPEN_STID, stpp);
3508         if (status)
3509                 return status;
3510         oo = openowner((*stpp)->st_stateowner);
3511         if (!(oo->oo_flags & NFS4_OO_CONFIRMED))
3512                 return nfserr_bad_stateid;
3513         return nfs_ok;
3514 }
3515
3516 __be32
3517 nfsd4_open_confirm(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3518                    struct nfsd4_open_confirm *oc)
3519 {
3520         __be32 status;
3521         struct nfs4_openowner *oo;
3522         struct nfs4_ol_stateid *stp;
3523
3524         dprintk("NFSD: nfsd4_open_confirm on file %.*s\n",
3525                         (int)cstate->current_fh.fh_dentry->d_name.len,
3526                         cstate->current_fh.fh_dentry->d_name.name);
3527
3528         status = fh_verify(rqstp, &cstate->current_fh, S_IFREG, 0);
3529         if (status)
3530                 return status;
3531
3532         nfs4_lock_state();
3533
3534         status = nfs4_preprocess_seqid_op(cstate,
3535                                         oc->oc_seqid, &oc->oc_req_stateid,
3536                                         NFS4_OPEN_STID, &stp);
3537         if (status)
3538                 goto out;
3539         oo = openowner(stp->st_stateowner);
3540         status = nfserr_bad_stateid;
3541         if (oo->oo_flags & NFS4_OO_CONFIRMED)
3542                 goto out;
3543         oo->oo_flags |= NFS4_OO_CONFIRMED;
3544         update_stateid(&stp->st_stid.sc_stateid);
3545         memcpy(&oc->oc_resp_stateid, &stp->st_stid.sc_stateid, sizeof(stateid_t));
3546         dprintk("NFSD: %s: success, seqid=%d stateid=" STATEID_FMT "\n",
3547                 __func__, oc->oc_seqid, STATEID_VAL(&stp->st_stid.sc_stateid));
3548
3549         nfsd4_create_clid_dir(oo->oo_owner.so_client);
3550         status = nfs_ok;
3551 out:
3552         if (!cstate->replay_owner)
3553                 nfs4_unlock_state();
3554         return status;
3555 }
3556
3557 static inline void nfs4_stateid_downgrade_bit(struct nfs4_ol_stateid *stp, u32 access)
3558 {
3559         if (!test_bit(access, &stp->st_access_bmap))
3560                 return;
3561         nfs4_file_put_access(stp->st_file, nfs4_access_to_omode(access));
3562         __clear_bit(access, &stp->st_access_bmap);
3563 }
3564
3565 static inline void nfs4_stateid_downgrade(struct nfs4_ol_stateid *stp, u32 to_access)
3566 {
3567         switch (to_access) {
3568         case NFS4_SHARE_ACCESS_READ:
3569                 nfs4_stateid_downgrade_bit(stp, NFS4_SHARE_ACCESS_WRITE);
3570                 nfs4_stateid_downgrade_bit(stp, NFS4_SHARE_ACCESS_BOTH);
3571                 break;
3572         case NFS4_SHARE_ACCESS_WRITE:
3573                 nfs4_stateid_downgrade_bit(stp, NFS4_SHARE_ACCESS_READ);
3574                 nfs4_stateid_downgrade_bit(stp, NFS4_SHARE_ACCESS_BOTH);
3575                 break;
3576         case NFS4_SHARE_ACCESS_BOTH:
3577                 break;
3578         default:
3579                 BUG();
3580         }
3581 }
3582
3583 static void
3584 reset_union_bmap_deny(unsigned long deny, unsigned long *bmap)
3585 {
3586         int i;
3587         for (i = 0; i < 4; i++) {
3588                 if ((i & deny) != i)
3589                         __clear_bit(i, bmap);
3590         }
3591 }
3592
3593 __be32
3594 nfsd4_open_downgrade(struct svc_rqst *rqstp,
3595                      struct nfsd4_compound_state *cstate,
3596                      struct nfsd4_open_downgrade *od)
3597 {
3598         __be32 status;
3599         struct nfs4_ol_stateid *stp;
3600
3601         dprintk("NFSD: nfsd4_open_downgrade on file %.*s\n", 
3602                         (int)cstate->current_fh.fh_dentry->d_name.len,
3603                         cstate->current_fh.fh_dentry->d_name.name);
3604
3605         /* We don't yet support WANT bits: */
3606         od->od_share_access &= NFS4_SHARE_ACCESS_MASK;
3607
3608         nfs4_lock_state();
3609         status = nfs4_preprocess_confirmed_seqid_op(cstate, od->od_seqid,
3610                                         &od->od_stateid, &stp);
3611         if (status)
3612                 goto out; 
3613         status = nfserr_inval;
3614         if (!test_bit(od->od_share_access, &stp->st_access_bmap)) {
3615                 dprintk("NFSD:access not a subset current bitmap: 0x%lx, input access=%08x\n",
3616                         stp->st_access_bmap, od->od_share_access);
3617                 goto out;
3618         }
3619         if (!test_bit(od->od_share_deny, &stp->st_deny_bmap)) {
3620                 dprintk("NFSD:deny not a subset current bitmap: 0x%lx, input deny=%08x\n",
3621                         stp->st_deny_bmap, od->od_share_deny);
3622                 goto out;
3623         }
3624         nfs4_stateid_downgrade(stp, od->od_share_access);
3625
3626         reset_union_bmap_deny(od->od_share_deny, &stp->st_deny_bmap);
3627
3628         update_stateid(&stp->st_stid.sc_stateid);
3629         memcpy(&od->od_stateid, &stp->st_stid.sc_stateid, sizeof(stateid_t));
3630         status = nfs_ok;
3631 out:
3632         if (!cstate->replay_owner)
3633                 nfs4_unlock_state();
3634         return status;
3635 }
3636
3637 void nfsd4_purge_closed_stateid(struct nfs4_stateowner *so)
3638 {
3639         struct nfs4_openowner *oo;
3640         struct nfs4_ol_stateid *s;
3641
3642         if (!so->so_is_open_owner)
3643                 return;
3644         oo = openowner(so);
3645         s = oo->oo_last_closed_stid;
3646         if (!s)
3647                 return;
3648         if (!(oo->oo_flags & NFS4_OO_PURGE_CLOSE)) {
3649                 /* Release the last_closed_stid on the next seqid bump: */
3650                 oo->oo_flags |= NFS4_OO_PURGE_CLOSE;
3651                 return;
3652         }
3653         oo->oo_flags &= ~NFS4_OO_PURGE_CLOSE;
3654         release_last_closed_stateid(oo);
3655 }
3656
3657 static void nfsd4_close_open_stateid(struct nfs4_ol_stateid *s)
3658 {
3659         unhash_open_stateid(s);
3660         s->st_stid.sc_type = NFS4_CLOSED_STID;
3661 }
3662
3663 /*
3664  * nfs4_unlock_state() called after encode
3665  */
3666 __be32
3667 nfsd4_close(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3668             struct nfsd4_close *close)
3669 {
3670         __be32 status;
3671         struct nfs4_openowner *oo;
3672         struct nfs4_ol_stateid *stp;
3673
3674         dprintk("NFSD: nfsd4_close on file %.*s\n", 
3675                         (int)cstate->current_fh.fh_dentry->d_name.len,
3676                         cstate->current_fh.fh_dentry->d_name.name);
3677
3678         nfs4_lock_state();
3679         status = nfs4_preprocess_seqid_op(cstate, close->cl_seqid,
3680                                         &close->cl_stateid,
3681                                         NFS4_OPEN_STID|NFS4_CLOSED_STID,
3682                                         &stp);
3683         if (status)
3684                 goto out; 
3685         oo = openowner(stp->st_stateowner);
3686         status = nfs_ok;
3687         update_stateid(&stp->st_stid.sc_stateid);
3688         memcpy(&close->cl_stateid, &stp->st_stid.sc_stateid, sizeof(stateid_t));
3689
3690         nfsd4_close_open_stateid(stp);
3691         release_last_closed_stateid(oo);
3692         oo->oo_last_closed_stid = stp;
3693
3694         /* place unused nfs4_stateowners on so_close_lru list to be
3695          * released by the laundromat service after the lease period
3696          * to enable us to handle CLOSE replay
3697          */
3698         if (list_empty(&oo->oo_owner.so_stateids))
3699                 move_to_close_lru(oo);
3700 out:
3701         if (!cstate->replay_owner)
3702                 nfs4_unlock_state();
3703         return status;
3704 }
3705
3706 __be32
3707 nfsd4_delegreturn(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3708                   struct nfsd4_delegreturn *dr)
3709 {
3710         struct nfs4_delegation *dp;
3711         stateid_t *stateid = &dr->dr_stateid;
3712         struct nfs4_stid *s;
3713         struct inode *inode;
3714         __be32 status;
3715
3716         if ((status = fh_verify(rqstp, &cstate->current_fh, S_IFREG, 0)))
3717                 return status;
3718         inode = cstate->current_fh.fh_dentry->d_inode;
3719
3720         nfs4_lock_state();
3721         status = nfsd4_lookup_stateid(stateid, NFS4_DELEG_STID, &s);
3722         if (status)
3723                 goto out;
3724         dp = delegstateid(s);
3725         status = check_stateid_generation(stateid, &dp->dl_stid.sc_stateid, nfsd4_has_session(cstate));
3726         if (status)
3727                 goto out;
3728
3729         unhash_delegation(dp);
3730 out:
3731         nfs4_unlock_state();
3732
3733         return status;
3734 }
3735
3736
3737 /* 
3738  * Lock owner state (byte-range locks)
3739  */
3740 #define LOFF_OVERFLOW(start, len)      ((u64)(len) > ~(u64)(start))
3741 #define LOCK_HASH_BITS              8
3742 #define LOCK_HASH_SIZE             (1 << LOCK_HASH_BITS)
3743 #define LOCK_HASH_MASK             (LOCK_HASH_SIZE - 1)
3744
3745 static inline u64
3746 end_offset(u64 start, u64 len)
3747 {
3748         u64 end;
3749
3750         end = start + len;
3751         return end >= start ? end: NFS4_MAX_UINT64;
3752 }
3753
3754 /* last octet in a range */
3755 static inline u64
3756 last_byte_offset(u64 start, u64 len)
3757 {
3758         u64 end;
3759
3760         BUG_ON(!len);
3761         end = start + len;
3762         return end > start ? end - 1: NFS4_MAX_UINT64;
3763 }
3764
3765 static inline unsigned int
3766 lock_ownerstr_hashval(struct inode *inode, u32 cl_id,
3767                 struct xdr_netobj *ownername)
3768 {
3769         return (file_hashval(inode) + cl_id
3770                         + opaque_hashval(ownername->data, ownername->len))
3771                 & LOCK_HASH_MASK;
3772 }
3773
3774 static struct list_head lock_ownerstr_hashtbl[LOCK_HASH_SIZE];
3775
3776 /*
3777  * TODO: Linux file offsets are _signed_ 64-bit quantities, which means that
3778  * we can't properly handle lock requests that go beyond the (2^63 - 1)-th
3779  * byte, because of sign extension problems.  Since NFSv4 calls for 64-bit
3780  * locking, this prevents us from being completely protocol-compliant.  The
3781  * real solution to this problem is to start using unsigned file offsets in
3782  * the VFS, but this is a very deep change!
3783  */
3784 static inline void
3785 nfs4_transform_lock_offset(struct file_lock *lock)
3786 {
3787         if (lock->fl_start < 0)
3788                 lock->fl_start = OFFSET_MAX;
3789         if (lock->fl_end < 0)
3790                 lock->fl_end = OFFSET_MAX;
3791 }
3792
3793 /* Hack!: For now, we're defining this just so we can use a pointer to it
3794  * as a unique cookie to identify our (NFSv4's) posix locks. */
3795 static const struct lock_manager_operations nfsd_posix_mng_ops  = {
3796 };
3797
3798 static inline void
3799 nfs4_set_lock_denied(struct file_lock *fl, struct nfsd4_lock_denied *deny)
3800 {
3801         struct nfs4_lockowner *lo;
3802
3803         if (fl->fl_lmops == &nfsd_posix_mng_ops) {
3804                 lo = (struct nfs4_lockowner *) fl->fl_owner;
3805                 deny->ld_owner.data = kmemdup(lo->lo_owner.so_owner.data,
3806                                         lo->lo_owner.so_owner.len, GFP_KERNEL);
3807                 if (!deny->ld_owner.data)
3808                         /* We just don't care that much */
3809                         goto nevermind;
3810                 deny->ld_owner.len = lo->lo_owner.so_owner.len;
3811                 deny->ld_clientid = lo->lo_owner.so_client->cl_clientid;
3812         } else {
3813 nevermind:
3814                 deny->ld_owner.len = 0;
3815                 deny->ld_owner.data = NULL;
3816                 deny->ld_clientid.cl_boot = 0;
3817                 deny->ld_clientid.cl_id = 0;
3818         }
3819         deny->ld_start = fl->fl_start;
3820         deny->ld_length = NFS4_MAX_UINT64;
3821         if (fl->fl_end != NFS4_MAX_UINT64)
3822                 deny->ld_length = fl->fl_end - fl->fl_start + 1;        
3823         deny->ld_type = NFS4_READ_LT;
3824         if (fl->fl_type != F_RDLCK)
3825                 deny->ld_type = NFS4_WRITE_LT;
3826 }
3827
3828 static bool same_lockowner_ino(struct nfs4_lockowner *lo, struct inode *inode, clientid_t *clid, struct xdr_netobj *owner)
3829 {
3830         struct nfs4_ol_stateid *lst;
3831
3832         if (!same_owner_str(&lo->lo_owner, owner, clid))
3833                 return false;
3834         if (list_empty(&lo->lo_owner.so_stateids)) {
3835                 WARN_ON_ONCE(1);
3836                 return false;
3837         }
3838         lst = list_first_entry(&lo->lo_owner.so_stateids,
3839                                struct nfs4_ol_stateid, st_perstateowner);
3840         return lst->st_file->fi_inode == inode;
3841 }
3842
3843 static struct nfs4_lockowner *
3844 find_lockowner_str(struct inode *inode, clientid_t *clid,
3845                 struct xdr_netobj *owner)
3846 {
3847         unsigned int hashval = lock_ownerstr_hashval(inode, clid->cl_id, owner);
3848         struct nfs4_lockowner *lo;
3849         struct nfs4_stateowner *op;
3850
3851         list_for_each_entry(op, &lock_ownerstr_hashtbl[hashval], so_strhash) {
3852                 lo = lockowner(op);
3853                 if (same_lockowner_ino(lo, inode, clid, owner))
3854                         return lo;
3855         }
3856         return NULL;
3857 }
3858
3859 static void hash_lockowner(struct nfs4_lockowner *lo, unsigned int strhashval, struct nfs4_client *clp, struct nfs4_ol_stateid *open_stp)
3860 {
3861         list_add(&lo->lo_owner.so_strhash, &lock_ownerstr_hashtbl[strhashval]);
3862         list_add(&lo->lo_perstateid, &open_stp->st_lockowners);
3863 }
3864
3865 /*
3866  * Alloc a lock owner structure.
3867  * Called in nfsd4_lock - therefore, OPEN and OPEN_CONFIRM (if needed) has 
3868  * occurred. 
3869  *
3870  * strhashval = lock_ownerstr_hashval 
3871  */
3872
3873 static struct nfs4_lockowner *
3874 alloc_init_lock_stateowner(unsigned int strhashval, struct nfs4_client *clp, struct nfs4_ol_stateid *open_stp, struct nfsd4_lock *lock) {
3875         struct nfs4_lockowner *lo;
3876
3877         lo = alloc_stateowner(lockowner_slab, &lock->lk_new_owner, clp);
3878         if (!lo)
3879                 return NULL;
3880         INIT_LIST_HEAD(&lo->lo_owner.so_stateids);
3881         lo->lo_owner.so_is_open_owner = 0;
3882         /* It is the openowner seqid that will be incremented in encode in the
3883          * case of new lockowners; so increment the lock seqid manually: */
3884         lo->lo_owner.so_seqid = lock->lk_new_lock_seqid + 1;
3885         hash_lockowner(lo, strhashval, clp, open_stp);
3886         return lo;
3887 }
3888
3889 static struct nfs4_ol_stateid *
3890 alloc_init_lock_stateid(struct nfs4_lockowner *lo, struct nfs4_file *fp, struct nfs4_ol_stateid *open_stp)
3891 {
3892         struct nfs4_ol_stateid *stp;
3893         struct nfs4_client *clp = lo->lo_owner.so_client;
3894
3895         stp = nfs4_alloc_stateid(clp);
3896         if (stp == NULL)
3897                 return NULL;
3898         init_stid(&stp->st_stid, clp, NFS4_LOCK_STID);
3899         list_add(&stp->st_perfile, &fp->fi_stateids);
3900         list_add(&stp->st_perstateowner, &lo->lo_owner.so_stateids);
3901         stp->st_stateowner = &lo->lo_owner;
3902         get_nfs4_file(fp);
3903         stp->st_file = fp;
3904         stp->st_access_bmap = 0;
3905         stp->st_deny_bmap = open_stp->st_deny_bmap;
3906         stp->st_openstp = open_stp;
3907         return stp;
3908 }
3909
3910 static int
3911 check_lock_length(u64 offset, u64 length)
3912 {
3913         return ((length == 0)  || ((length != NFS4_MAX_UINT64) &&
3914              LOFF_OVERFLOW(offset, length)));
3915 }
3916
3917 static void get_lock_access(struct nfs4_ol_stateid *lock_stp, u32 access)
3918 {
3919         struct nfs4_file *fp = lock_stp->st_file;
3920         int oflag = nfs4_access_to_omode(access);
3921
3922         if (test_bit(access, &lock_stp->st_access_bmap))
3923                 return;
3924         nfs4_file_get_access(fp, oflag);
3925         __set_bit(access, &lock_stp->st_access_bmap);
3926 }
3927
3928 /*
3929  *  LOCK operation 
3930  */
3931 __be32
3932 nfsd4_lock(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3933            struct nfsd4_lock *lock)
3934 {
3935         struct nfs4_openowner *open_sop = NULL;
3936         struct nfs4_lockowner *lock_sop = NULL;
3937         struct nfs4_ol_stateid *lock_stp;
3938         struct nfs4_file *fp;
3939         struct file *filp = NULL;
3940         struct file_lock file_lock;
3941         struct file_lock conflock;
3942         __be32 status = 0;
3943         unsigned int strhashval;
3944         int lkflg;
3945         int err;
3946
3947         dprintk("NFSD: nfsd4_lock: start=%Ld length=%Ld\n",
3948                 (long long) lock->lk_offset,
3949                 (long long) lock->lk_length);
3950
3951         if (check_lock_length(lock->lk_offset, lock->lk_length))
3952                  return nfserr_inval;
3953
3954         if ((status = fh_verify(rqstp, &cstate->current_fh,
3955                                 S_IFREG, NFSD_MAY_LOCK))) {
3956                 dprintk("NFSD: nfsd4_lock: permission denied!\n");
3957                 return status;
3958         }
3959
3960         nfs4_lock_state();
3961
3962         if (lock->lk_is_new) {
3963                 /*
3964                  * Client indicates that this is a new lockowner.
3965                  * Use open owner and open stateid to create lock owner and
3966                  * lock stateid.
3967                  */
3968                 struct nfs4_ol_stateid *open_stp = NULL;
3969                 
3970                 status = nfserr_stale_clientid;
3971                 if (!nfsd4_has_session(cstate) &&
3972                     STALE_CLIENTID(&lock->lk_new_clientid))
3973                         goto out;
3974
3975                 /* validate and update open stateid and open seqid */
3976                 status = nfs4_preprocess_confirmed_seqid_op(cstate,
3977                                         lock->lk_new_open_seqid,
3978                                         &lock->lk_new_open_stateid,
3979                                         &open_stp);
3980                 if (status)
3981                         goto out;
3982                 open_sop = openowner(open_stp->st_stateowner);
3983                 status = nfserr_bad_stateid;
3984                 if (!nfsd4_has_session(cstate) &&
3985                         !same_clid(&open_sop->oo_owner.so_client->cl_clientid,
3986                                                 &lock->v.new.clientid))
3987                         goto out;
3988                 /* create lockowner and lock stateid */
3989                 fp = open_stp->st_file;
3990                 strhashval = lock_ownerstr_hashval(fp->fi_inode,
3991                                 open_sop->oo_owner.so_client->cl_clientid.cl_id,
3992                                 &lock->v.new.owner);
3993                 /* XXX: Do we need to check for duplicate stateowners on
3994                  * the same file, or should they just be allowed (and
3995                  * create new stateids)? */
3996                 status = nfserr_jukebox;
3997                 lock_sop = alloc_init_lock_stateowner(strhashval,
3998                                 open_sop->oo_owner.so_client, open_stp, lock);
3999                 if (lock_sop == NULL)
4000                         goto out;
4001                 lock_stp = alloc_init_lock_stateid(lock_sop, fp, open_stp);
4002                 if (lock_stp == NULL)
4003                         goto out;
4004         } else {
4005                 /* lock (lock owner + lock stateid) already exists */
4006                 status = nfs4_preprocess_seqid_op(cstate,
4007                                        lock->lk_old_lock_seqid,
4008                                        &lock->lk_old_lock_stateid,
4009                                        NFS4_LOCK_STID, &lock_stp);
4010                 if (status)
4011                         goto out;
4012                 lock_sop = lockowner(lock_stp->st_stateowner);
4013                 fp = lock_stp->st_file;
4014         }
4015         /* lock_sop and lock_stp have been created or found */
4016
4017         lkflg = setlkflg(lock->lk_type);
4018         status = nfs4_check_openmode(lock_stp, lkflg);
4019         if (status)
4020                 goto out;
4021
4022         status = nfserr_grace;
4023         if (locks_in_grace() && !lock->lk_reclaim)
4024                 goto out;
4025         status = nfserr_no_grace;
4026         if (!locks_in_grace() && lock->lk_reclaim)
4027                 goto out;
4028
4029         locks_init_lock(&file_lock);
4030         switch (lock->lk_type) {
4031                 case NFS4_READ_LT:
4032                 case NFS4_READW_LT:
4033                         filp = find_readable_file(lock_stp->st_file);
4034                         if (filp)
4035                                 get_lock_access(lock_stp, NFS4_SHARE_ACCESS_READ);
4036                         file_lock.fl_type = F_RDLCK;
4037                         break;
4038                 case NFS4_WRITE_LT:
4039                 case NFS4_WRITEW_LT:
4040                         filp = find_writeable_file(lock_stp->st_file);
4041                         if (filp)
4042                                 get_lock_access(lock_stp, NFS4_SHARE_ACCESS_WRITE);
4043                         file_lock.fl_type = F_WRLCK;
4044                         break;
4045                 default:
4046                         status = nfserr_inval;
4047                 goto out;
4048         }
4049         if (!filp) {
4050                 status = nfserr_openmode;
4051                 goto out;
4052         }
4053         file_lock.fl_owner = (fl_owner_t)lock_sop;
4054         file_lock.fl_pid = current->tgid;
4055         file_lock.fl_file = filp;
4056         file_lock.fl_flags = FL_POSIX;
4057         file_lock.fl_lmops = &nfsd_posix_mng_ops;
4058
4059         file_lock.fl_start = lock->lk_offset;
4060         file_lock.fl_end = last_byte_offset(lock->lk_offset, lock->lk_length);
4061         nfs4_transform_lock_offset(&file_lock);
4062
4063         /*
4064         * Try to lock the file in the VFS.
4065         * Note: locks.c uses the BKL to protect the inode's lock list.
4066         */
4067
4068         err = vfs_lock_file(filp, F_SETLK, &file_lock, &conflock);
4069         switch (-err) {
4070         case 0: /* success! */
4071                 update_stateid(&lock_stp->st_stid.sc_stateid);
4072                 memcpy(&lock->lk_resp_stateid, &lock_stp->st_stid.sc_stateid, 
4073                                 sizeof(stateid_t));
4074                 status = 0;
4075                 break;
4076         case (EAGAIN):          /* conflock holds conflicting lock */
4077                 status = nfserr_denied;
4078                 dprintk("NFSD: nfsd4_lock: conflicting lock found!\n");
4079                 nfs4_set_lock_denied(&conflock, &lock->lk_denied);
4080                 break;
4081         case (EDEADLK):
4082                 status = nfserr_deadlock;
4083                 break;
4084         default:
4085                 dprintk("NFSD: nfsd4_lock: vfs_lock_file() failed! status %d\n",err);
4086                 status = nfserrno(err);
4087                 break;
4088         }
4089 out:
4090         if (status && lock->lk_is_new && lock_sop)
4091                 release_lockowner(lock_sop);
4092         if (!cstate->replay_owner)
4093                 nfs4_unlock_state();
4094         return status;
4095 }
4096
4097 /*
4098  * The NFSv4 spec allows a client to do a LOCKT without holding an OPEN,
4099  * so we do a temporary open here just to get an open file to pass to
4100  * vfs_test_lock.  (Arguably perhaps test_lock should be done with an
4101  * inode operation.)
4102  */
4103 static __be32 nfsd_test_lock(struct svc_rqst *rqstp, struct svc_fh *fhp, struct file_lock *lock)
4104 {
4105         struct file *file;
4106         __be32 err = nfsd_open(rqstp, fhp, S_IFREG, NFSD_MAY_READ, &file);
4107         if (!err) {
4108                 err = nfserrno(vfs_test_lock(file, lock));
4109                 nfsd_close(file);
4110         }
4111         return err;
4112 }
4113
4114 /*
4115  * LOCKT operation
4116  */
4117 __be32
4118 nfsd4_lockt(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
4119             struct nfsd4_lockt *lockt)
4120 {
4121         struct inode *inode;
4122         struct file_lock file_lock;
4123         struct nfs4_lockowner *lo;
4124         __be32 status;
4125
4126         if (locks_in_grace())
4127                 return nfserr_grace;
4128
4129         if (check_lock_length(lockt->lt_offset, lockt->lt_length))
4130                  return nfserr_inval;
4131
4132         nfs4_lock_state();
4133
4134         status = nfserr_stale_clientid;
4135         if (!nfsd4_has_session(cstate) && STALE_CLIENTID(&lockt->lt_clientid))
4136                 goto out;
4137
4138         if ((status = fh_verify(rqstp, &cstate->current_fh, S_IFREG, 0)))
4139                 goto out;
4140
4141         inode = cstate->current_fh.fh_dentry->d_inode;
4142         locks_init_lock(&file_lock);
4143         switch (lockt->lt_type) {
4144                 case NFS4_READ_LT:
4145                 case NFS4_READW_LT:
4146                         file_lock.fl_type = F_RDLCK;
4147                 break;
4148                 case NFS4_WRITE_LT:
4149                 case NFS4_WRITEW_LT:
4150                         file_lock.fl_type = F_WRLCK;
4151                 break;
4152                 default:
4153                         dprintk("NFSD: nfs4_lockt: bad lock type!\n");
4154                         status = nfserr_inval;
4155                 goto out;
4156         }
4157
4158         lo = find_lockowner_str(inode, &lockt->lt_clientid, &lockt->lt_owner);
4159         if (lo)
4160                 file_lock.fl_owner = (fl_owner_t)lo;
4161         file_lock.fl_pid = current->tgid;
4162         file_lock.fl_flags = FL_POSIX;
4163
4164         file_lock.fl_start = lockt->lt_offset;
4165         file_lock.fl_end = last_byte_offset(lockt->lt_offset, lockt->lt_length);
4166
4167         nfs4_transform_lock_offset(&file_lock);
4168
4169         status = nfsd_test_lock(rqstp, &cstate->current_fh, &file_lock);
4170         if (status)
4171                 goto out;
4172
4173         if (file_lock.fl_type != F_UNLCK) {
4174                 status = nfserr_denied;
4175                 nfs4_set_lock_denied(&file_lock, &lockt->lt_denied);
4176         }
4177 out:
4178         nfs4_unlock_state();
4179         return status;
4180 }
4181
4182 __be32
4183 nfsd4_locku(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
4184             struct nfsd4_locku *locku)
4185 {
4186         struct nfs4_ol_stateid *stp;
4187         struct file *filp = NULL;
4188         struct file_lock file_lock;
4189         __be32 status;
4190         int err;
4191                                                         
4192         dprintk("NFSD: nfsd4_locku: start=%Ld length=%Ld\n",
4193                 (long long) locku->lu_offset,
4194                 (long long) locku->lu_length);
4195
4196         if (check_lock_length(locku->lu_offset, locku->lu_length))
4197                  return nfserr_inval;
4198
4199         nfs4_lock_state();
4200                                                                                 
4201         status = nfs4_preprocess_seqid_op(cstate, locku->lu_seqid,
4202                                         &locku->lu_stateid, NFS4_LOCK_STID, &stp);
4203         if (status)
4204                 goto out;
4205         filp = find_any_file(stp->st_file);
4206         if (!filp) {
4207                 status = nfserr_lock_range;
4208                 goto out;
4209         }
4210         BUG_ON(!filp);
4211         locks_init_lock(&file_lock);
4212         file_lock.fl_type = F_UNLCK;
4213         file_lock.fl_owner = (fl_owner_t)lockowner(stp->st_stateowner);
4214         file_lock.fl_pid = current->tgid;
4215         file_lock.fl_file = filp;
4216         file_lock.fl_flags = FL_POSIX; 
4217         file_lock.fl_lmops = &nfsd_posix_mng_ops;
4218         file_lock.fl_start = locku->lu_offset;
4219
4220         file_lock.fl_end = last_byte_offset(locku->lu_offset, locku->lu_length);
4221         nfs4_transform_lock_offset(&file_lock);
4222
4223         /*
4224         *  Try to unlock the file in the VFS.
4225         */
4226         err = vfs_lock_file(filp, F_SETLK, &file_lock, NULL);
4227         if (err) {
4228                 dprintk("NFSD: nfs4_locku: vfs_lock_file failed!\n");
4229                 goto out_nfserr;
4230         }
4231         /*
4232         * OK, unlock succeeded; the only thing left to do is update the stateid.
4233         */
4234         update_stateid(&stp->st_stid.sc_stateid);
4235         memcpy(&locku->lu_stateid, &stp->st_stid.sc_stateid, sizeof(stateid_t));
4236
4237 out:
4238         if (!cstate->replay_owner)
4239                 nfs4_unlock_state();
4240         return status;
4241
4242 out_nfserr:
4243         status = nfserrno(err);
4244         goto out;
4245 }
4246
4247 /*
4248  * returns
4249  *      1: locks held by lockowner
4250  *      0: no locks held by lockowner
4251  */
4252 static int
4253 check_for_locks(struct nfs4_file *filp, struct nfs4_lockowner *lowner)
4254 {
4255         struct file_lock **flpp;
4256         struct inode *inode = filp->fi_inode;
4257         int status = 0;
4258
4259         lock_flocks();
4260         for (flpp = &inode->i_flock; *flpp != NULL; flpp = &(*flpp)->fl_next) {
4261                 if ((*flpp)->fl_owner == (fl_owner_t)lowner) {
4262                         status = 1;
4263                         goto out;
4264                 }
4265         }
4266 out:
4267         unlock_flocks();
4268         return status;
4269 }
4270
4271 __be32
4272 nfsd4_release_lockowner(struct svc_rqst *rqstp,
4273                         struct nfsd4_compound_state *cstate,
4274                         struct nfsd4_release_lockowner *rlockowner)
4275 {
4276         clientid_t *clid = &rlockowner->rl_clientid;
4277         struct nfs4_stateowner *sop;
4278         struct nfs4_lockowner *lo;
4279         struct nfs4_ol_stateid *stp;
4280         struct xdr_netobj *owner = &rlockowner->rl_owner;
4281         struct list_head matches;
4282         int i;
4283         __be32 status;
4284
4285         dprintk("nfsd4_release_lockowner clientid: (%08x/%08x):\n",
4286                 clid->cl_boot, clid->cl_id);
4287
4288         /* XXX check for lease expiration */
4289
4290         status = nfserr_stale_clientid;
4291         if (STALE_CLIENTID(clid))
4292                 return status;
4293
4294         nfs4_lock_state();
4295
4296         status = nfserr_locks_held;
4297         /* XXX: we're doing a linear search through all the lockowners.
4298          * Yipes!  For now we'll just hope clients aren't really using
4299          * release_lockowner much, but eventually we have to fix these
4300          * data structures. */
4301         INIT_LIST_HEAD(&matches);
4302         for (i = 0; i < LOCK_HASH_SIZE; i++) {
4303                 list_for_each_entry(sop, &lock_ownerstr_hashtbl[i], so_strhash) {
4304                         if (!same_owner_str(sop, owner, clid))
4305                                 continue;
4306                         list_for_each_entry(stp, &sop->so_stateids,
4307                                         st_perstateowner) {
4308                                 lo = lockowner(sop);
4309                                 if (check_for_locks(stp->st_file, lo))
4310                                         goto out;
4311                                 list_add(&lo->lo_list, &matches);
4312                         }
4313                 }
4314         }
4315         /* Clients probably won't expect us to return with some (but not all)
4316          * of the lockowner state released; so don't release any until all
4317          * have been checked. */
4318         status = nfs_ok;
4319         while (!list_empty(&matches)) {
4320                 lo = list_entry(matches.next, struct nfs4_lockowner,
4321                                                                 lo_list);
4322                 /* unhash_stateowner deletes so_perclient only
4323                  * for openowners. */
4324                 list_del(&lo->lo_list);
4325                 release_lockowner(lo);
4326         }
4327 out:
4328         nfs4_unlock_state();
4329         return status;
4330 }
4331
4332 static inline struct nfs4_client_reclaim *
4333 alloc_reclaim(void)
4334 {
4335         return kmalloc(sizeof(struct nfs4_client_reclaim), GFP_KERNEL);
4336 }
4337
4338 int
4339 nfs4_has_reclaimed_state(const char *name, bool use_exchange_id)
4340 {
4341         unsigned int strhashval = clientstr_hashval(name);
4342         struct nfs4_client *clp;
4343
4344         clp = find_confirmed_client_by_str(name, strhashval);
4345         return clp ? 1 : 0;
4346 }
4347
4348 /*
4349  * failure => all reset bets are off, nfserr_no_grace...
4350  */
4351 int
4352 nfs4_client_to_reclaim(const char *name)
4353 {
4354         unsigned int strhashval;
4355         struct nfs4_client_reclaim *crp = NULL;
4356
4357         dprintk("NFSD nfs4_client_to_reclaim NAME: %.*s\n", HEXDIR_LEN, name);
4358         crp = alloc_reclaim();
4359         if (!crp)
4360                 return 0;
4361         strhashval = clientstr_hashval(name);
4362         INIT_LIST_HEAD(&crp->cr_strhash);
4363         list_add(&crp->cr_strhash, &reclaim_str_hashtbl[strhashval]);
4364         memcpy(crp->cr_recdir, name, HEXDIR_LEN);
4365         reclaim_str_hashtbl_size++;
4366         return 1;
4367 }
4368
4369 static void
4370 nfs4_release_reclaim(void)
4371 {
4372         struct nfs4_client_reclaim *crp = NULL;
4373         int i;
4374
4375         for (i = 0; i < CLIENT_HASH_SIZE; i++) {
4376                 while (!list_empty(&reclaim_str_hashtbl[i])) {
4377                         crp = list_entry(reclaim_str_hashtbl[i].next,
4378                                         struct nfs4_client_reclaim, cr_strhash);
4379                         list_del(&crp->cr_strhash);
4380                         kfree(crp);
4381                         reclaim_str_hashtbl_size--;
4382                 }
4383         }
4384         BUG_ON(reclaim_str_hashtbl_size);
4385 }
4386
4387 /*
4388  * called from OPEN, CLAIM_PREVIOUS with a new clientid. */
4389 static struct nfs4_client_reclaim *
4390 nfs4_find_reclaim_client(clientid_t *clid)
4391 {
4392         unsigned int strhashval;
4393         struct nfs4_client *clp;
4394         struct nfs4_client_reclaim *crp = NULL;
4395
4396
4397         /* find clientid in conf_id_hashtbl */
4398         clp = find_confirmed_client(clid);
4399         if (clp == NULL)
4400                 return NULL;
4401
4402         dprintk("NFSD: nfs4_find_reclaim_client for %.*s with recdir %s\n",
4403                             clp->cl_name.len, clp->cl_name.data,
4404                             clp->cl_recdir);
4405
4406         /* find clp->cl_name in reclaim_str_hashtbl */
4407         strhashval = clientstr_hashval(clp->cl_recdir);
4408         list_for_each_entry(crp, &reclaim_str_hashtbl[strhashval], cr_strhash) {
4409                 if (same_name(crp->cr_recdir, clp->cl_recdir)) {
4410                         return crp;
4411                 }
4412         }
4413         return NULL;
4414 }
4415
4416 /*
4417 * Called from OPEN. Look for clientid in reclaim list.
4418 */
4419 __be32
4420 nfs4_check_open_reclaim(clientid_t *clid)
4421 {
4422         return nfs4_find_reclaim_client(clid) ? nfs_ok : nfserr_reclaim_bad;
4423 }
4424
4425 /* initialization to perform at module load time: */
4426
4427 int
4428 nfs4_state_init(void)
4429 {
4430         int i, status;
4431
4432         status = nfsd4_init_slabs();
4433         if (status)
4434                 return status;
4435         for (i = 0; i < CLIENT_HASH_SIZE; i++) {
4436                 INIT_LIST_HEAD(&conf_id_hashtbl[i]);
4437                 INIT_LIST_HEAD(&conf_str_hashtbl[i]);
4438                 INIT_LIST_HEAD(&unconf_str_hashtbl[i]);
4439                 INIT_LIST_HEAD(&unconf_id_hashtbl[i]);
4440                 INIT_LIST_HEAD(&reclaim_str_hashtbl[i]);
4441         }
4442         for (i = 0; i < SESSION_HASH_SIZE; i++)
4443                 INIT_LIST_HEAD(&sessionid_hashtbl[i]);
4444         for (i = 0; i < FILE_HASH_SIZE; i++) {
4445                 INIT_LIST_HEAD(&file_hashtbl[i]);
4446         }
4447         for (i = 0; i < OPEN_OWNER_HASH_SIZE; i++) {
4448                 INIT_LIST_HEAD(&open_ownerstr_hashtbl[i]);
4449         }
4450         for (i = 0; i < LOCK_HASH_SIZE; i++) {
4451                 INIT_LIST_HEAD(&lock_ownerstr_hashtbl[i]);
4452         }
4453         memset(&onestateid, ~0, sizeof(stateid_t));
4454         INIT_LIST_HEAD(&close_lru);
4455         INIT_LIST_HEAD(&client_lru);
4456         INIT_LIST_HEAD(&del_recall_lru);
4457         reclaim_str_hashtbl_size = 0;
4458         return 0;
4459 }
4460
4461 static void
4462 nfsd4_load_reboot_recovery_data(void)
4463 {
4464         int status;
4465
4466         nfs4_lock_state();
4467         nfsd4_init_recdir();
4468         status = nfsd4_recdir_load();
4469         nfs4_unlock_state();
4470         if (status)
4471                 printk("NFSD: Failure reading reboot recovery data\n");
4472 }
4473
4474 /*
4475  * Since the lifetime of a delegation isn't limited to that of an open, a
4476  * client may quite reasonably hang on to a delegation as long as it has
4477  * the inode cached.  This becomes an obvious problem the first time a
4478  * client's inode cache approaches the size of the server's total memory.
4479  *
4480  * For now we avoid this problem by imposing a hard limit on the number
4481  * of delegations, which varies according to the server's memory size.
4482  */
4483 static void
4484 set_max_delegations(void)
4485 {
4486         /*
4487          * Allow at most 4 delegations per megabyte of RAM.  Quick
4488          * estimates suggest that in the worst case (where every delegation
4489          * is for a different inode), a delegation could take about 1.5K,
4490          * giving a worst case usage of about 6% of memory.
4491          */
4492         max_delegations = nr_free_buffer_pages() >> (20 - 2 - PAGE_SHIFT);
4493 }
4494
4495 /* initialization to perform when the nfsd service is started: */
4496
4497 static int
4498 __nfs4_state_start(void)
4499 {
4500         int ret;
4501
4502         boot_time = get_seconds();
4503         locks_start_grace(&nfsd4_manager);
4504         printk(KERN_INFO "NFSD: starting %ld-second grace period\n",
4505                nfsd4_grace);
4506         ret = set_callback_cred();
4507         if (ret)
4508                 return -ENOMEM;
4509         laundry_wq = create_singlethread_workqueue("nfsd4");
4510         if (laundry_wq == NULL)
4511                 return -ENOMEM;
4512         ret = nfsd4_create_callback_queue();
4513         if (ret)
4514                 goto out_free_laundry;
4515         queue_delayed_work(laundry_wq, &laundromat_work, nfsd4_grace * HZ);
4516         set_max_delegations();
4517         return 0;
4518 out_free_laundry:
4519         destroy_workqueue(laundry_wq);
4520         return ret;
4521 }
4522
4523 int
4524 nfs4_state_start(void)
4525 {
4526         nfsd4_load_reboot_recovery_data();
4527         return __nfs4_state_start();
4528 }
4529
4530 static void
4531 __nfs4_state_shutdown(void)
4532 {
4533         int i;
4534         struct nfs4_client *clp = NULL;
4535         struct nfs4_delegation *dp = NULL;
4536         struct list_head *pos, *next, reaplist;
4537
4538         for (i = 0; i < CLIENT_HASH_SIZE; i++) {
4539                 while (!list_empty(&conf_id_hashtbl[i])) {
4540                         clp = list_entry(conf_id_hashtbl[i].next, struct nfs4_client, cl_idhash);
4541                         expire_client(clp);
4542                 }
4543                 while (!list_empty(&unconf_str_hashtbl[i])) {
4544                         clp = list_entry(unconf_str_hashtbl[i].next, struct nfs4_client, cl_strhash);
4545                         expire_client(clp);
4546                 }
4547         }
4548         INIT_LIST_HEAD(&reaplist);
4549         spin_lock(&recall_lock);
4550         list_for_each_safe(pos, next, &del_recall_lru) {
4551                 dp = list_entry (pos, struct nfs4_delegation, dl_recall_lru);
4552                 list_move(&dp->dl_recall_lru, &reaplist);
4553         }
4554         spin_unlock(&recall_lock);
4555         list_for_each_safe(pos, next, &reaplist) {
4556                 dp = list_entry (pos, struct nfs4_delegation, dl_recall_lru);
4557                 list_del_init(&dp->dl_recall_lru);
4558                 unhash_delegation(dp);
4559         }
4560
4561         nfsd4_shutdown_recdir();
4562 }
4563
4564 void
4565 nfs4_state_shutdown(void)
4566 {
4567         cancel_delayed_work_sync(&laundromat_work);
4568         destroy_workqueue(laundry_wq);
4569         locks_end_grace(&nfsd4_manager);
4570         nfs4_lock_state();
4571         nfs4_release_reclaim();
4572         __nfs4_state_shutdown();
4573         nfs4_unlock_state();
4574         nfsd4_destroy_callback_queue();
4575 }