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