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