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