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