GNU Linux-libre 5.13.14-gnu1
[releases.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 <linux/jhash.h>
45 #include <linux/string_helpers.h>
46 #include <linux/fsnotify.h>
47 #include "xdr4.h"
48 #include "xdr4cb.h"
49 #include "vfs.h"
50 #include "current_stateid.h"
51
52 #include "netns.h"
53 #include "pnfs.h"
54 #include "filecache.h"
55 #include "trace.h"
56
57 #define NFSDDBG_FACILITY                NFSDDBG_PROC
58
59 #define all_ones {{~0,~0},~0}
60 static const stateid_t one_stateid = {
61         .si_generation = ~0,
62         .si_opaque = all_ones,
63 };
64 static const stateid_t zero_stateid = {
65         /* all fields zero */
66 };
67 static const stateid_t currentstateid = {
68         .si_generation = 1,
69 };
70 static const stateid_t close_stateid = {
71         .si_generation = 0xffffffffU,
72 };
73
74 static u64 current_sessionid = 1;
75
76 #define ZERO_STATEID(stateid) (!memcmp((stateid), &zero_stateid, sizeof(stateid_t)))
77 #define ONE_STATEID(stateid)  (!memcmp((stateid), &one_stateid, sizeof(stateid_t)))
78 #define CURRENT_STATEID(stateid) (!memcmp((stateid), &currentstateid, sizeof(stateid_t)))
79 #define CLOSE_STATEID(stateid)  (!memcmp((stateid), &close_stateid, sizeof(stateid_t)))
80
81 /* forward declarations */
82 static bool check_for_locks(struct nfs4_file *fp, struct nfs4_lockowner *lowner);
83 static void nfs4_free_ol_stateid(struct nfs4_stid *stid);
84 void nfsd4_end_grace(struct nfsd_net *nn);
85 static void _free_cpntf_state_locked(struct nfsd_net *nn, struct nfs4_cpntf_state *cps);
86
87 /* Locking: */
88
89 /*
90  * Currently used for the del_recall_lru and file hash table.  In an
91  * effort to decrease the scope of the client_mutex, this spinlock may
92  * eventually cover more:
93  */
94 static DEFINE_SPINLOCK(state_lock);
95
96 enum nfsd4_st_mutex_lock_subclass {
97         OPEN_STATEID_MUTEX = 0,
98         LOCK_STATEID_MUTEX = 1,
99 };
100
101 /*
102  * A waitqueue for all in-progress 4.0 CLOSE operations that are waiting for
103  * the refcount on the open stateid to drop.
104  */
105 static DECLARE_WAIT_QUEUE_HEAD(close_wq);
106
107 /*
108  * A waitqueue where a writer to clients/#/ctl destroying a client can
109  * wait for cl_rpc_users to drop to 0 and then for the client to be
110  * unhashed.
111  */
112 static DECLARE_WAIT_QUEUE_HEAD(expiry_wq);
113
114 static struct kmem_cache *client_slab;
115 static struct kmem_cache *openowner_slab;
116 static struct kmem_cache *lockowner_slab;
117 static struct kmem_cache *file_slab;
118 static struct kmem_cache *stateid_slab;
119 static struct kmem_cache *deleg_slab;
120 static struct kmem_cache *odstate_slab;
121
122 static void free_session(struct nfsd4_session *);
123
124 static const struct nfsd4_callback_ops nfsd4_cb_recall_ops;
125 static const struct nfsd4_callback_ops nfsd4_cb_notify_lock_ops;
126
127 static bool is_session_dead(struct nfsd4_session *ses)
128 {
129         return ses->se_flags & NFS4_SESSION_DEAD;
130 }
131
132 static __be32 mark_session_dead_locked(struct nfsd4_session *ses, int ref_held_by_me)
133 {
134         if (atomic_read(&ses->se_ref) > ref_held_by_me)
135                 return nfserr_jukebox;
136         ses->se_flags |= NFS4_SESSION_DEAD;
137         return nfs_ok;
138 }
139
140 static bool is_client_expired(struct nfs4_client *clp)
141 {
142         return clp->cl_time == 0;
143 }
144
145 static __be32 get_client_locked(struct nfs4_client *clp)
146 {
147         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
148
149         lockdep_assert_held(&nn->client_lock);
150
151         if (is_client_expired(clp))
152                 return nfserr_expired;
153         atomic_inc(&clp->cl_rpc_users);
154         return nfs_ok;
155 }
156
157 /* must be called under the client_lock */
158 static inline void
159 renew_client_locked(struct nfs4_client *clp)
160 {
161         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
162
163         if (is_client_expired(clp)) {
164                 WARN_ON(1);
165                 printk("%s: client (clientid %08x/%08x) already expired\n",
166                         __func__,
167                         clp->cl_clientid.cl_boot,
168                         clp->cl_clientid.cl_id);
169                 return;
170         }
171
172         list_move_tail(&clp->cl_lru, &nn->client_lru);
173         clp->cl_time = ktime_get_boottime_seconds();
174 }
175
176 static void put_client_renew_locked(struct nfs4_client *clp)
177 {
178         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
179
180         lockdep_assert_held(&nn->client_lock);
181
182         if (!atomic_dec_and_test(&clp->cl_rpc_users))
183                 return;
184         if (!is_client_expired(clp))
185                 renew_client_locked(clp);
186         else
187                 wake_up_all(&expiry_wq);
188 }
189
190 static void put_client_renew(struct nfs4_client *clp)
191 {
192         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
193
194         if (!atomic_dec_and_lock(&clp->cl_rpc_users, &nn->client_lock))
195                 return;
196         if (!is_client_expired(clp))
197                 renew_client_locked(clp);
198         else
199                 wake_up_all(&expiry_wq);
200         spin_unlock(&nn->client_lock);
201 }
202
203 static __be32 nfsd4_get_session_locked(struct nfsd4_session *ses)
204 {
205         __be32 status;
206
207         if (is_session_dead(ses))
208                 return nfserr_badsession;
209         status = get_client_locked(ses->se_client);
210         if (status)
211                 return status;
212         atomic_inc(&ses->se_ref);
213         return nfs_ok;
214 }
215
216 static void nfsd4_put_session_locked(struct nfsd4_session *ses)
217 {
218         struct nfs4_client *clp = ses->se_client;
219         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
220
221         lockdep_assert_held(&nn->client_lock);
222
223         if (atomic_dec_and_test(&ses->se_ref) && is_session_dead(ses))
224                 free_session(ses);
225         put_client_renew_locked(clp);
226 }
227
228 static void nfsd4_put_session(struct nfsd4_session *ses)
229 {
230         struct nfs4_client *clp = ses->se_client;
231         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
232
233         spin_lock(&nn->client_lock);
234         nfsd4_put_session_locked(ses);
235         spin_unlock(&nn->client_lock);
236 }
237
238 static struct nfsd4_blocked_lock *
239 find_blocked_lock(struct nfs4_lockowner *lo, struct knfsd_fh *fh,
240                         struct nfsd_net *nn)
241 {
242         struct nfsd4_blocked_lock *cur, *found = NULL;
243
244         spin_lock(&nn->blocked_locks_lock);
245         list_for_each_entry(cur, &lo->lo_blocked, nbl_list) {
246                 if (fh_match(fh, &cur->nbl_fh)) {
247                         list_del_init(&cur->nbl_list);
248                         list_del_init(&cur->nbl_lru);
249                         found = cur;
250                         break;
251                 }
252         }
253         spin_unlock(&nn->blocked_locks_lock);
254         if (found)
255                 locks_delete_block(&found->nbl_lock);
256         return found;
257 }
258
259 static struct nfsd4_blocked_lock *
260 find_or_allocate_block(struct nfs4_lockowner *lo, struct knfsd_fh *fh,
261                         struct nfsd_net *nn)
262 {
263         struct nfsd4_blocked_lock *nbl;
264
265         nbl = find_blocked_lock(lo, fh, nn);
266         if (!nbl) {
267                 nbl= kmalloc(sizeof(*nbl), GFP_KERNEL);
268                 if (nbl) {
269                         INIT_LIST_HEAD(&nbl->nbl_list);
270                         INIT_LIST_HEAD(&nbl->nbl_lru);
271                         fh_copy_shallow(&nbl->nbl_fh, fh);
272                         locks_init_lock(&nbl->nbl_lock);
273                         nfsd4_init_cb(&nbl->nbl_cb, lo->lo_owner.so_client,
274                                         &nfsd4_cb_notify_lock_ops,
275                                         NFSPROC4_CLNT_CB_NOTIFY_LOCK);
276                 }
277         }
278         return nbl;
279 }
280
281 static void
282 free_blocked_lock(struct nfsd4_blocked_lock *nbl)
283 {
284         locks_delete_block(&nbl->nbl_lock);
285         locks_release_private(&nbl->nbl_lock);
286         kfree(nbl);
287 }
288
289 static void
290 remove_blocked_locks(struct nfs4_lockowner *lo)
291 {
292         struct nfs4_client *clp = lo->lo_owner.so_client;
293         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
294         struct nfsd4_blocked_lock *nbl;
295         LIST_HEAD(reaplist);
296
297         /* Dequeue all blocked locks */
298         spin_lock(&nn->blocked_locks_lock);
299         while (!list_empty(&lo->lo_blocked)) {
300                 nbl = list_first_entry(&lo->lo_blocked,
301                                         struct nfsd4_blocked_lock,
302                                         nbl_list);
303                 list_del_init(&nbl->nbl_list);
304                 list_move(&nbl->nbl_lru, &reaplist);
305         }
306         spin_unlock(&nn->blocked_locks_lock);
307
308         /* Now free them */
309         while (!list_empty(&reaplist)) {
310                 nbl = list_first_entry(&reaplist, struct nfsd4_blocked_lock,
311                                         nbl_lru);
312                 list_del_init(&nbl->nbl_lru);
313                 free_blocked_lock(nbl);
314         }
315 }
316
317 static void
318 nfsd4_cb_notify_lock_prepare(struct nfsd4_callback *cb)
319 {
320         struct nfsd4_blocked_lock       *nbl = container_of(cb,
321                                                 struct nfsd4_blocked_lock, nbl_cb);
322         locks_delete_block(&nbl->nbl_lock);
323 }
324
325 static int
326 nfsd4_cb_notify_lock_done(struct nfsd4_callback *cb, struct rpc_task *task)
327 {
328         /*
329          * Since this is just an optimization, we don't try very hard if it
330          * turns out not to succeed. We'll requeue it on NFS4ERR_DELAY, and
331          * just quit trying on anything else.
332          */
333         switch (task->tk_status) {
334         case -NFS4ERR_DELAY:
335                 rpc_delay(task, 1 * HZ);
336                 return 0;
337         default:
338                 return 1;
339         }
340 }
341
342 static void
343 nfsd4_cb_notify_lock_release(struct nfsd4_callback *cb)
344 {
345         struct nfsd4_blocked_lock       *nbl = container_of(cb,
346                                                 struct nfsd4_blocked_lock, nbl_cb);
347
348         free_blocked_lock(nbl);
349 }
350
351 static const struct nfsd4_callback_ops nfsd4_cb_notify_lock_ops = {
352         .prepare        = nfsd4_cb_notify_lock_prepare,
353         .done           = nfsd4_cb_notify_lock_done,
354         .release        = nfsd4_cb_notify_lock_release,
355 };
356
357 /*
358  * We store the NONE, READ, WRITE, and BOTH bits separately in the
359  * st_{access,deny}_bmap field of the stateid, in order to track not
360  * only what share bits are currently in force, but also what
361  * combinations of share bits previous opens have used.  This allows us
362  * to enforce the recommendation of rfc 3530 14.2.19 that the server
363  * return an error if the client attempt to downgrade to a combination
364  * of share bits not explicable by closing some of its previous opens.
365  *
366  * XXX: This enforcement is actually incomplete, since we don't keep
367  * track of access/deny bit combinations; so, e.g., we allow:
368  *
369  *      OPEN allow read, deny write
370  *      OPEN allow both, deny none
371  *      DOWNGRADE allow read, deny none
372  *
373  * which we should reject.
374  */
375 static unsigned int
376 bmap_to_share_mode(unsigned long bmap)
377 {
378         int i;
379         unsigned int access = 0;
380
381         for (i = 1; i < 4; i++) {
382                 if (test_bit(i, &bmap))
383                         access |= i;
384         }
385         return access;
386 }
387
388 /* set share access for a given stateid */
389 static inline void
390 set_access(u32 access, struct nfs4_ol_stateid *stp)
391 {
392         unsigned char mask = 1 << access;
393
394         WARN_ON_ONCE(access > NFS4_SHARE_ACCESS_BOTH);
395         stp->st_access_bmap |= mask;
396 }
397
398 /* clear share access for a given stateid */
399 static inline void
400 clear_access(u32 access, struct nfs4_ol_stateid *stp)
401 {
402         unsigned char mask = 1 << access;
403
404         WARN_ON_ONCE(access > NFS4_SHARE_ACCESS_BOTH);
405         stp->st_access_bmap &= ~mask;
406 }
407
408 /* test whether a given stateid has access */
409 static inline bool
410 test_access(u32 access, struct nfs4_ol_stateid *stp)
411 {
412         unsigned char mask = 1 << access;
413
414         return (bool)(stp->st_access_bmap & mask);
415 }
416
417 /* set share deny for a given stateid */
418 static inline void
419 set_deny(u32 deny, struct nfs4_ol_stateid *stp)
420 {
421         unsigned char mask = 1 << deny;
422
423         WARN_ON_ONCE(deny > NFS4_SHARE_DENY_BOTH);
424         stp->st_deny_bmap |= mask;
425 }
426
427 /* clear share deny for a given stateid */
428 static inline void
429 clear_deny(u32 deny, struct nfs4_ol_stateid *stp)
430 {
431         unsigned char mask = 1 << deny;
432
433         WARN_ON_ONCE(deny > NFS4_SHARE_DENY_BOTH);
434         stp->st_deny_bmap &= ~mask;
435 }
436
437 /* test whether a given stateid is denying specific access */
438 static inline bool
439 test_deny(u32 deny, struct nfs4_ol_stateid *stp)
440 {
441         unsigned char mask = 1 << deny;
442
443         return (bool)(stp->st_deny_bmap & mask);
444 }
445
446 static int nfs4_access_to_omode(u32 access)
447 {
448         switch (access & NFS4_SHARE_ACCESS_BOTH) {
449         case NFS4_SHARE_ACCESS_READ:
450                 return O_RDONLY;
451         case NFS4_SHARE_ACCESS_WRITE:
452                 return O_WRONLY;
453         case NFS4_SHARE_ACCESS_BOTH:
454                 return O_RDWR;
455         }
456         WARN_ON_ONCE(1);
457         return O_RDONLY;
458 }
459
460 static inline int
461 access_permit_read(struct nfs4_ol_stateid *stp)
462 {
463         return test_access(NFS4_SHARE_ACCESS_READ, stp) ||
464                 test_access(NFS4_SHARE_ACCESS_BOTH, stp) ||
465                 test_access(NFS4_SHARE_ACCESS_WRITE, stp);
466 }
467
468 static inline int
469 access_permit_write(struct nfs4_ol_stateid *stp)
470 {
471         return test_access(NFS4_SHARE_ACCESS_WRITE, stp) ||
472                 test_access(NFS4_SHARE_ACCESS_BOTH, stp);
473 }
474
475 static inline struct nfs4_stateowner *
476 nfs4_get_stateowner(struct nfs4_stateowner *sop)
477 {
478         atomic_inc(&sop->so_count);
479         return sop;
480 }
481
482 static int
483 same_owner_str(struct nfs4_stateowner *sop, struct xdr_netobj *owner)
484 {
485         return (sop->so_owner.len == owner->len) &&
486                 0 == memcmp(sop->so_owner.data, owner->data, owner->len);
487 }
488
489 static struct nfs4_openowner *
490 find_openstateowner_str_locked(unsigned int hashval, struct nfsd4_open *open,
491                         struct nfs4_client *clp)
492 {
493         struct nfs4_stateowner *so;
494
495         lockdep_assert_held(&clp->cl_lock);
496
497         list_for_each_entry(so, &clp->cl_ownerstr_hashtbl[hashval],
498                             so_strhash) {
499                 if (!so->so_is_open_owner)
500                         continue;
501                 if (same_owner_str(so, &open->op_owner))
502                         return openowner(nfs4_get_stateowner(so));
503         }
504         return NULL;
505 }
506
507 static struct nfs4_openowner *
508 find_openstateowner_str(unsigned int hashval, struct nfsd4_open *open,
509                         struct nfs4_client *clp)
510 {
511         struct nfs4_openowner *oo;
512
513         spin_lock(&clp->cl_lock);
514         oo = find_openstateowner_str_locked(hashval, open, clp);
515         spin_unlock(&clp->cl_lock);
516         return oo;
517 }
518
519 static inline u32
520 opaque_hashval(const void *ptr, int nbytes)
521 {
522         unsigned char *cptr = (unsigned char *) ptr;
523
524         u32 x = 0;
525         while (nbytes--) {
526                 x *= 37;
527                 x += *cptr++;
528         }
529         return x;
530 }
531
532 static void nfsd4_free_file_rcu(struct rcu_head *rcu)
533 {
534         struct nfs4_file *fp = container_of(rcu, struct nfs4_file, fi_rcu);
535
536         kmem_cache_free(file_slab, fp);
537 }
538
539 void
540 put_nfs4_file(struct nfs4_file *fi)
541 {
542         might_lock(&state_lock);
543
544         if (refcount_dec_and_lock(&fi->fi_ref, &state_lock)) {
545                 hlist_del_rcu(&fi->fi_hash);
546                 spin_unlock(&state_lock);
547                 WARN_ON_ONCE(!list_empty(&fi->fi_clnt_odstate));
548                 WARN_ON_ONCE(!list_empty(&fi->fi_delegations));
549                 call_rcu(&fi->fi_rcu, nfsd4_free_file_rcu);
550         }
551 }
552
553 static struct nfsd_file *
554 __nfs4_get_fd(struct nfs4_file *f, int oflag)
555 {
556         if (f->fi_fds[oflag])
557                 return nfsd_file_get(f->fi_fds[oflag]);
558         return NULL;
559 }
560
561 static struct nfsd_file *
562 find_writeable_file_locked(struct nfs4_file *f)
563 {
564         struct nfsd_file *ret;
565
566         lockdep_assert_held(&f->fi_lock);
567
568         ret = __nfs4_get_fd(f, O_WRONLY);
569         if (!ret)
570                 ret = __nfs4_get_fd(f, O_RDWR);
571         return ret;
572 }
573
574 static struct nfsd_file *
575 find_writeable_file(struct nfs4_file *f)
576 {
577         struct nfsd_file *ret;
578
579         spin_lock(&f->fi_lock);
580         ret = find_writeable_file_locked(f);
581         spin_unlock(&f->fi_lock);
582
583         return ret;
584 }
585
586 static struct nfsd_file *
587 find_readable_file_locked(struct nfs4_file *f)
588 {
589         struct nfsd_file *ret;
590
591         lockdep_assert_held(&f->fi_lock);
592
593         ret = __nfs4_get_fd(f, O_RDONLY);
594         if (!ret)
595                 ret = __nfs4_get_fd(f, O_RDWR);
596         return ret;
597 }
598
599 static struct nfsd_file *
600 find_readable_file(struct nfs4_file *f)
601 {
602         struct nfsd_file *ret;
603
604         spin_lock(&f->fi_lock);
605         ret = find_readable_file_locked(f);
606         spin_unlock(&f->fi_lock);
607
608         return ret;
609 }
610
611 struct nfsd_file *
612 find_any_file(struct nfs4_file *f)
613 {
614         struct nfsd_file *ret;
615
616         if (!f)
617                 return NULL;
618         spin_lock(&f->fi_lock);
619         ret = __nfs4_get_fd(f, O_RDWR);
620         if (!ret) {
621                 ret = __nfs4_get_fd(f, O_WRONLY);
622                 if (!ret)
623                         ret = __nfs4_get_fd(f, O_RDONLY);
624         }
625         spin_unlock(&f->fi_lock);
626         return ret;
627 }
628
629 static struct nfsd_file *find_deleg_file(struct nfs4_file *f)
630 {
631         struct nfsd_file *ret = NULL;
632
633         spin_lock(&f->fi_lock);
634         if (f->fi_deleg_file)
635                 ret = nfsd_file_get(f->fi_deleg_file);
636         spin_unlock(&f->fi_lock);
637         return ret;
638 }
639
640 static atomic_long_t num_delegations;
641 unsigned long max_delegations;
642
643 /*
644  * Open owner state (share locks)
645  */
646
647 /* hash tables for lock and open owners */
648 #define OWNER_HASH_BITS              8
649 #define OWNER_HASH_SIZE             (1 << OWNER_HASH_BITS)
650 #define OWNER_HASH_MASK             (OWNER_HASH_SIZE - 1)
651
652 static unsigned int ownerstr_hashval(struct xdr_netobj *ownername)
653 {
654         unsigned int ret;
655
656         ret = opaque_hashval(ownername->data, ownername->len);
657         return ret & OWNER_HASH_MASK;
658 }
659
660 /* hash table for nfs4_file */
661 #define FILE_HASH_BITS                   8
662 #define FILE_HASH_SIZE                  (1 << FILE_HASH_BITS)
663
664 static unsigned int file_hashval(struct svc_fh *fh)
665 {
666         struct inode *inode = d_inode(fh->fh_dentry);
667
668         /* XXX: why not (here & in file cache) use inode? */
669         return (unsigned int)hash_long(inode->i_ino, FILE_HASH_BITS);
670 }
671
672 static struct hlist_head file_hashtbl[FILE_HASH_SIZE];
673
674 static void
675 __nfs4_file_get_access(struct nfs4_file *fp, u32 access)
676 {
677         lockdep_assert_held(&fp->fi_lock);
678
679         if (access & NFS4_SHARE_ACCESS_WRITE)
680                 atomic_inc(&fp->fi_access[O_WRONLY]);
681         if (access & NFS4_SHARE_ACCESS_READ)
682                 atomic_inc(&fp->fi_access[O_RDONLY]);
683 }
684
685 static __be32
686 nfs4_file_get_access(struct nfs4_file *fp, u32 access)
687 {
688         lockdep_assert_held(&fp->fi_lock);
689
690         /* Does this access mode make sense? */
691         if (access & ~NFS4_SHARE_ACCESS_BOTH)
692                 return nfserr_inval;
693
694         /* Does it conflict with a deny mode already set? */
695         if ((access & fp->fi_share_deny) != 0)
696                 return nfserr_share_denied;
697
698         __nfs4_file_get_access(fp, access);
699         return nfs_ok;
700 }
701
702 static __be32 nfs4_file_check_deny(struct nfs4_file *fp, u32 deny)
703 {
704         /* Common case is that there is no deny mode. */
705         if (deny) {
706                 /* Does this deny mode make sense? */
707                 if (deny & ~NFS4_SHARE_DENY_BOTH)
708                         return nfserr_inval;
709
710                 if ((deny & NFS4_SHARE_DENY_READ) &&
711                     atomic_read(&fp->fi_access[O_RDONLY]))
712                         return nfserr_share_denied;
713
714                 if ((deny & NFS4_SHARE_DENY_WRITE) &&
715                     atomic_read(&fp->fi_access[O_WRONLY]))
716                         return nfserr_share_denied;
717         }
718         return nfs_ok;
719 }
720
721 static void __nfs4_file_put_access(struct nfs4_file *fp, int oflag)
722 {
723         might_lock(&fp->fi_lock);
724
725         if (atomic_dec_and_lock(&fp->fi_access[oflag], &fp->fi_lock)) {
726                 struct nfsd_file *f1 = NULL;
727                 struct nfsd_file *f2 = NULL;
728
729                 swap(f1, fp->fi_fds[oflag]);
730                 if (atomic_read(&fp->fi_access[1 - oflag]) == 0)
731                         swap(f2, fp->fi_fds[O_RDWR]);
732                 spin_unlock(&fp->fi_lock);
733                 if (f1)
734                         nfsd_file_put(f1);
735                 if (f2)
736                         nfsd_file_put(f2);
737         }
738 }
739
740 static void nfs4_file_put_access(struct nfs4_file *fp, u32 access)
741 {
742         WARN_ON_ONCE(access & ~NFS4_SHARE_ACCESS_BOTH);
743
744         if (access & NFS4_SHARE_ACCESS_WRITE)
745                 __nfs4_file_put_access(fp, O_WRONLY);
746         if (access & NFS4_SHARE_ACCESS_READ)
747                 __nfs4_file_put_access(fp, O_RDONLY);
748 }
749
750 /*
751  * Allocate a new open/delegation state counter. This is needed for
752  * pNFS for proper return on close semantics.
753  *
754  * Note that we only allocate it for pNFS-enabled exports, otherwise
755  * all pointers to struct nfs4_clnt_odstate are always NULL.
756  */
757 static struct nfs4_clnt_odstate *
758 alloc_clnt_odstate(struct nfs4_client *clp)
759 {
760         struct nfs4_clnt_odstate *co;
761
762         co = kmem_cache_zalloc(odstate_slab, GFP_KERNEL);
763         if (co) {
764                 co->co_client = clp;
765                 refcount_set(&co->co_odcount, 1);
766         }
767         return co;
768 }
769
770 static void
771 hash_clnt_odstate_locked(struct nfs4_clnt_odstate *co)
772 {
773         struct nfs4_file *fp = co->co_file;
774
775         lockdep_assert_held(&fp->fi_lock);
776         list_add(&co->co_perfile, &fp->fi_clnt_odstate);
777 }
778
779 static inline void
780 get_clnt_odstate(struct nfs4_clnt_odstate *co)
781 {
782         if (co)
783                 refcount_inc(&co->co_odcount);
784 }
785
786 static void
787 put_clnt_odstate(struct nfs4_clnt_odstate *co)
788 {
789         struct nfs4_file *fp;
790
791         if (!co)
792                 return;
793
794         fp = co->co_file;
795         if (refcount_dec_and_lock(&co->co_odcount, &fp->fi_lock)) {
796                 list_del(&co->co_perfile);
797                 spin_unlock(&fp->fi_lock);
798
799                 nfsd4_return_all_file_layouts(co->co_client, fp);
800                 kmem_cache_free(odstate_slab, co);
801         }
802 }
803
804 static struct nfs4_clnt_odstate *
805 find_or_hash_clnt_odstate(struct nfs4_file *fp, struct nfs4_clnt_odstate *new)
806 {
807         struct nfs4_clnt_odstate *co;
808         struct nfs4_client *cl;
809
810         if (!new)
811                 return NULL;
812
813         cl = new->co_client;
814
815         spin_lock(&fp->fi_lock);
816         list_for_each_entry(co, &fp->fi_clnt_odstate, co_perfile) {
817                 if (co->co_client == cl) {
818                         get_clnt_odstate(co);
819                         goto out;
820                 }
821         }
822         co = new;
823         co->co_file = fp;
824         hash_clnt_odstate_locked(new);
825 out:
826         spin_unlock(&fp->fi_lock);
827         return co;
828 }
829
830 struct nfs4_stid *nfs4_alloc_stid(struct nfs4_client *cl, struct kmem_cache *slab,
831                                   void (*sc_free)(struct nfs4_stid *))
832 {
833         struct nfs4_stid *stid;
834         int new_id;
835
836         stid = kmem_cache_zalloc(slab, GFP_KERNEL);
837         if (!stid)
838                 return NULL;
839
840         idr_preload(GFP_KERNEL);
841         spin_lock(&cl->cl_lock);
842         /* Reserving 0 for start of file in nfsdfs "states" file: */
843         new_id = idr_alloc_cyclic(&cl->cl_stateids, stid, 1, 0, GFP_NOWAIT);
844         spin_unlock(&cl->cl_lock);
845         idr_preload_end();
846         if (new_id < 0)
847                 goto out_free;
848
849         stid->sc_free = sc_free;
850         stid->sc_client = cl;
851         stid->sc_stateid.si_opaque.so_id = new_id;
852         stid->sc_stateid.si_opaque.so_clid = cl->cl_clientid;
853         /* Will be incremented before return to client: */
854         refcount_set(&stid->sc_count, 1);
855         spin_lock_init(&stid->sc_lock);
856         INIT_LIST_HEAD(&stid->sc_cp_list);
857
858         /*
859          * It shouldn't be a problem to reuse an opaque stateid value.
860          * I don't think it is for 4.1.  But with 4.0 I worry that, for
861          * example, a stray write retransmission could be accepted by
862          * the server when it should have been rejected.  Therefore,
863          * adopt a trick from the sctp code to attempt to maximize the
864          * amount of time until an id is reused, by ensuring they always
865          * "increase" (mod INT_MAX):
866          */
867         return stid;
868 out_free:
869         kmem_cache_free(slab, stid);
870         return NULL;
871 }
872
873 /*
874  * Create a unique stateid_t to represent each COPY.
875  */
876 static int nfs4_init_cp_state(struct nfsd_net *nn, copy_stateid_t *stid,
877                               unsigned char sc_type)
878 {
879         int new_id;
880
881         stid->stid.si_opaque.so_clid.cl_boot = (u32)nn->boot_time;
882         stid->stid.si_opaque.so_clid.cl_id = nn->s2s_cp_cl_id;
883         stid->sc_type = sc_type;
884
885         idr_preload(GFP_KERNEL);
886         spin_lock(&nn->s2s_cp_lock);
887         new_id = idr_alloc_cyclic(&nn->s2s_cp_stateids, stid, 0, 0, GFP_NOWAIT);
888         stid->stid.si_opaque.so_id = new_id;
889         stid->stid.si_generation = 1;
890         spin_unlock(&nn->s2s_cp_lock);
891         idr_preload_end();
892         if (new_id < 0)
893                 return 0;
894         return 1;
895 }
896
897 int nfs4_init_copy_state(struct nfsd_net *nn, struct nfsd4_copy *copy)
898 {
899         return nfs4_init_cp_state(nn, &copy->cp_stateid, NFS4_COPY_STID);
900 }
901
902 struct nfs4_cpntf_state *nfs4_alloc_init_cpntf_state(struct nfsd_net *nn,
903                                                      struct nfs4_stid *p_stid)
904 {
905         struct nfs4_cpntf_state *cps;
906
907         cps = kzalloc(sizeof(struct nfs4_cpntf_state), GFP_KERNEL);
908         if (!cps)
909                 return NULL;
910         cps->cpntf_time = ktime_get_boottime_seconds();
911         refcount_set(&cps->cp_stateid.sc_count, 1);
912         if (!nfs4_init_cp_state(nn, &cps->cp_stateid, NFS4_COPYNOTIFY_STID))
913                 goto out_free;
914         spin_lock(&nn->s2s_cp_lock);
915         list_add(&cps->cp_list, &p_stid->sc_cp_list);
916         spin_unlock(&nn->s2s_cp_lock);
917         return cps;
918 out_free:
919         kfree(cps);
920         return NULL;
921 }
922
923 void nfs4_free_copy_state(struct nfsd4_copy *copy)
924 {
925         struct nfsd_net *nn;
926
927         WARN_ON_ONCE(copy->cp_stateid.sc_type != NFS4_COPY_STID);
928         nn = net_generic(copy->cp_clp->net, nfsd_net_id);
929         spin_lock(&nn->s2s_cp_lock);
930         idr_remove(&nn->s2s_cp_stateids,
931                    copy->cp_stateid.stid.si_opaque.so_id);
932         spin_unlock(&nn->s2s_cp_lock);
933 }
934
935 static void nfs4_free_cpntf_statelist(struct net *net, struct nfs4_stid *stid)
936 {
937         struct nfs4_cpntf_state *cps;
938         struct nfsd_net *nn;
939
940         nn = net_generic(net, nfsd_net_id);
941         spin_lock(&nn->s2s_cp_lock);
942         while (!list_empty(&stid->sc_cp_list)) {
943                 cps = list_first_entry(&stid->sc_cp_list,
944                                        struct nfs4_cpntf_state, cp_list);
945                 _free_cpntf_state_locked(nn, cps);
946         }
947         spin_unlock(&nn->s2s_cp_lock);
948 }
949
950 static struct nfs4_ol_stateid * nfs4_alloc_open_stateid(struct nfs4_client *clp)
951 {
952         struct nfs4_stid *stid;
953
954         stid = nfs4_alloc_stid(clp, stateid_slab, nfs4_free_ol_stateid);
955         if (!stid)
956                 return NULL;
957
958         return openlockstateid(stid);
959 }
960
961 static void nfs4_free_deleg(struct nfs4_stid *stid)
962 {
963         kmem_cache_free(deleg_slab, stid);
964         atomic_long_dec(&num_delegations);
965 }
966
967 /*
968  * When we recall a delegation, we should be careful not to hand it
969  * out again straight away.
970  * To ensure this we keep a pair of bloom filters ('new' and 'old')
971  * in which the filehandles of recalled delegations are "stored".
972  * If a filehandle appear in either filter, a delegation is blocked.
973  * When a delegation is recalled, the filehandle is stored in the "new"
974  * filter.
975  * Every 30 seconds we swap the filters and clear the "new" one,
976  * unless both are empty of course.
977  *
978  * Each filter is 256 bits.  We hash the filehandle to 32bit and use the
979  * low 3 bytes as hash-table indices.
980  *
981  * 'blocked_delegations_lock', which is always taken in block_delegations(),
982  * is used to manage concurrent access.  Testing does not need the lock
983  * except when swapping the two filters.
984  */
985 static DEFINE_SPINLOCK(blocked_delegations_lock);
986 static struct bloom_pair {
987         int     entries, old_entries;
988         time64_t swap_time;
989         int     new; /* index into 'set' */
990         DECLARE_BITMAP(set[2], 256);
991 } blocked_delegations;
992
993 static int delegation_blocked(struct knfsd_fh *fh)
994 {
995         u32 hash;
996         struct bloom_pair *bd = &blocked_delegations;
997
998         if (bd->entries == 0)
999                 return 0;
1000         if (ktime_get_seconds() - bd->swap_time > 30) {
1001                 spin_lock(&blocked_delegations_lock);
1002                 if (ktime_get_seconds() - bd->swap_time > 30) {
1003                         bd->entries -= bd->old_entries;
1004                         bd->old_entries = bd->entries;
1005                         memset(bd->set[bd->new], 0,
1006                                sizeof(bd->set[0]));
1007                         bd->new = 1-bd->new;
1008                         bd->swap_time = ktime_get_seconds();
1009                 }
1010                 spin_unlock(&blocked_delegations_lock);
1011         }
1012         hash = jhash(&fh->fh_base, fh->fh_size, 0);
1013         if (test_bit(hash&255, bd->set[0]) &&
1014             test_bit((hash>>8)&255, bd->set[0]) &&
1015             test_bit((hash>>16)&255, bd->set[0]))
1016                 return 1;
1017
1018         if (test_bit(hash&255, bd->set[1]) &&
1019             test_bit((hash>>8)&255, bd->set[1]) &&
1020             test_bit((hash>>16)&255, bd->set[1]))
1021                 return 1;
1022
1023         return 0;
1024 }
1025
1026 static void block_delegations(struct knfsd_fh *fh)
1027 {
1028         u32 hash;
1029         struct bloom_pair *bd = &blocked_delegations;
1030
1031         hash = jhash(&fh->fh_base, fh->fh_size, 0);
1032
1033         spin_lock(&blocked_delegations_lock);
1034         __set_bit(hash&255, bd->set[bd->new]);
1035         __set_bit((hash>>8)&255, bd->set[bd->new]);
1036         __set_bit((hash>>16)&255, bd->set[bd->new]);
1037         if (bd->entries == 0)
1038                 bd->swap_time = ktime_get_seconds();
1039         bd->entries += 1;
1040         spin_unlock(&blocked_delegations_lock);
1041 }
1042
1043 static struct nfs4_delegation *
1044 alloc_init_deleg(struct nfs4_client *clp, struct nfs4_file *fp,
1045                  struct svc_fh *current_fh,
1046                  struct nfs4_clnt_odstate *odstate)
1047 {
1048         struct nfs4_delegation *dp;
1049         long n;
1050
1051         dprintk("NFSD alloc_init_deleg\n");
1052         n = atomic_long_inc_return(&num_delegations);
1053         if (n < 0 || n > max_delegations)
1054                 goto out_dec;
1055         if (delegation_blocked(&current_fh->fh_handle))
1056                 goto out_dec;
1057         dp = delegstateid(nfs4_alloc_stid(clp, deleg_slab, nfs4_free_deleg));
1058         if (dp == NULL)
1059                 goto out_dec;
1060
1061         /*
1062          * delegation seqid's are never incremented.  The 4.1 special
1063          * meaning of seqid 0 isn't meaningful, really, but let's avoid
1064          * 0 anyway just for consistency and use 1:
1065          */
1066         dp->dl_stid.sc_stateid.si_generation = 1;
1067         INIT_LIST_HEAD(&dp->dl_perfile);
1068         INIT_LIST_HEAD(&dp->dl_perclnt);
1069         INIT_LIST_HEAD(&dp->dl_recall_lru);
1070         dp->dl_clnt_odstate = odstate;
1071         get_clnt_odstate(odstate);
1072         dp->dl_type = NFS4_OPEN_DELEGATE_READ;
1073         dp->dl_retries = 1;
1074         nfsd4_init_cb(&dp->dl_recall, dp->dl_stid.sc_client,
1075                       &nfsd4_cb_recall_ops, NFSPROC4_CLNT_CB_RECALL);
1076         get_nfs4_file(fp);
1077         dp->dl_stid.sc_file = fp;
1078         return dp;
1079 out_dec:
1080         atomic_long_dec(&num_delegations);
1081         return NULL;
1082 }
1083
1084 void
1085 nfs4_put_stid(struct nfs4_stid *s)
1086 {
1087         struct nfs4_file *fp = s->sc_file;
1088         struct nfs4_client *clp = s->sc_client;
1089
1090         might_lock(&clp->cl_lock);
1091
1092         if (!refcount_dec_and_lock(&s->sc_count, &clp->cl_lock)) {
1093                 wake_up_all(&close_wq);
1094                 return;
1095         }
1096         idr_remove(&clp->cl_stateids, s->sc_stateid.si_opaque.so_id);
1097         nfs4_free_cpntf_statelist(clp->net, s);
1098         spin_unlock(&clp->cl_lock);
1099         s->sc_free(s);
1100         if (fp)
1101                 put_nfs4_file(fp);
1102 }
1103
1104 void
1105 nfs4_inc_and_copy_stateid(stateid_t *dst, struct nfs4_stid *stid)
1106 {
1107         stateid_t *src = &stid->sc_stateid;
1108
1109         spin_lock(&stid->sc_lock);
1110         if (unlikely(++src->si_generation == 0))
1111                 src->si_generation = 1;
1112         memcpy(dst, src, sizeof(*dst));
1113         spin_unlock(&stid->sc_lock);
1114 }
1115
1116 static void put_deleg_file(struct nfs4_file *fp)
1117 {
1118         struct nfsd_file *nf = NULL;
1119
1120         spin_lock(&fp->fi_lock);
1121         if (--fp->fi_delegees == 0)
1122                 swap(nf, fp->fi_deleg_file);
1123         spin_unlock(&fp->fi_lock);
1124
1125         if (nf)
1126                 nfsd_file_put(nf);
1127 }
1128
1129 static void nfs4_unlock_deleg_lease(struct nfs4_delegation *dp)
1130 {
1131         struct nfs4_file *fp = dp->dl_stid.sc_file;
1132         struct nfsd_file *nf = fp->fi_deleg_file;
1133
1134         WARN_ON_ONCE(!fp->fi_delegees);
1135
1136         vfs_setlease(nf->nf_file, F_UNLCK, NULL, (void **)&dp);
1137         put_deleg_file(fp);
1138 }
1139
1140 static void destroy_unhashed_deleg(struct nfs4_delegation *dp)
1141 {
1142         put_clnt_odstate(dp->dl_clnt_odstate);
1143         nfs4_unlock_deleg_lease(dp);
1144         nfs4_put_stid(&dp->dl_stid);
1145 }
1146
1147 void nfs4_unhash_stid(struct nfs4_stid *s)
1148 {
1149         s->sc_type = 0;
1150 }
1151
1152 /**
1153  * nfs4_delegation_exists - Discover if this delegation already exists
1154  * @clp:     a pointer to the nfs4_client we're granting a delegation to
1155  * @fp:      a pointer to the nfs4_file we're granting a delegation on
1156  *
1157  * Return:
1158  *      On success: true iff an existing delegation is found
1159  */
1160
1161 static bool
1162 nfs4_delegation_exists(struct nfs4_client *clp, struct nfs4_file *fp)
1163 {
1164         struct nfs4_delegation *searchdp = NULL;
1165         struct nfs4_client *searchclp = NULL;
1166
1167         lockdep_assert_held(&state_lock);
1168         lockdep_assert_held(&fp->fi_lock);
1169
1170         list_for_each_entry(searchdp, &fp->fi_delegations, dl_perfile) {
1171                 searchclp = searchdp->dl_stid.sc_client;
1172                 if (clp == searchclp) {
1173                         return true;
1174                 }
1175         }
1176         return false;
1177 }
1178
1179 /**
1180  * hash_delegation_locked - Add a delegation to the appropriate lists
1181  * @dp:     a pointer to the nfs4_delegation we are adding.
1182  * @fp:     a pointer to the nfs4_file we're granting a delegation on
1183  *
1184  * Return:
1185  *      On success: NULL if the delegation was successfully hashed.
1186  *
1187  *      On error: -EAGAIN if one was previously granted to this
1188  *                 nfs4_client for this nfs4_file. Delegation is not hashed.
1189  *
1190  */
1191
1192 static int
1193 hash_delegation_locked(struct nfs4_delegation *dp, struct nfs4_file *fp)
1194 {
1195         struct nfs4_client *clp = dp->dl_stid.sc_client;
1196
1197         lockdep_assert_held(&state_lock);
1198         lockdep_assert_held(&fp->fi_lock);
1199
1200         if (nfs4_delegation_exists(clp, fp))
1201                 return -EAGAIN;
1202         refcount_inc(&dp->dl_stid.sc_count);
1203         dp->dl_stid.sc_type = NFS4_DELEG_STID;
1204         list_add(&dp->dl_perfile, &fp->fi_delegations);
1205         list_add(&dp->dl_perclnt, &clp->cl_delegations);
1206         return 0;
1207 }
1208
1209 static bool
1210 unhash_delegation_locked(struct nfs4_delegation *dp)
1211 {
1212         struct nfs4_file *fp = dp->dl_stid.sc_file;
1213
1214         lockdep_assert_held(&state_lock);
1215
1216         if (list_empty(&dp->dl_perfile))
1217                 return false;
1218
1219         dp->dl_stid.sc_type = NFS4_CLOSED_DELEG_STID;
1220         /* Ensure that deleg break won't try to requeue it */
1221         ++dp->dl_time;
1222         spin_lock(&fp->fi_lock);
1223         list_del_init(&dp->dl_perclnt);
1224         list_del_init(&dp->dl_recall_lru);
1225         list_del_init(&dp->dl_perfile);
1226         spin_unlock(&fp->fi_lock);
1227         return true;
1228 }
1229
1230 static void destroy_delegation(struct nfs4_delegation *dp)
1231 {
1232         bool unhashed;
1233
1234         spin_lock(&state_lock);
1235         unhashed = unhash_delegation_locked(dp);
1236         spin_unlock(&state_lock);
1237         if (unhashed)
1238                 destroy_unhashed_deleg(dp);
1239 }
1240
1241 static void revoke_delegation(struct nfs4_delegation *dp)
1242 {
1243         struct nfs4_client *clp = dp->dl_stid.sc_client;
1244
1245         WARN_ON(!list_empty(&dp->dl_recall_lru));
1246
1247         if (clp->cl_minorversion) {
1248                 dp->dl_stid.sc_type = NFS4_REVOKED_DELEG_STID;
1249                 refcount_inc(&dp->dl_stid.sc_count);
1250                 spin_lock(&clp->cl_lock);
1251                 list_add(&dp->dl_recall_lru, &clp->cl_revoked);
1252                 spin_unlock(&clp->cl_lock);
1253         }
1254         destroy_unhashed_deleg(dp);
1255 }
1256
1257 /* 
1258  * SETCLIENTID state 
1259  */
1260
1261 static unsigned int clientid_hashval(u32 id)
1262 {
1263         return id & CLIENT_HASH_MASK;
1264 }
1265
1266 static unsigned int clientstr_hashval(struct xdr_netobj name)
1267 {
1268         return opaque_hashval(name.data, 8) & CLIENT_HASH_MASK;
1269 }
1270
1271 /*
1272  * A stateid that had a deny mode associated with it is being released
1273  * or downgraded. Recalculate the deny mode on the file.
1274  */
1275 static void
1276 recalculate_deny_mode(struct nfs4_file *fp)
1277 {
1278         struct nfs4_ol_stateid *stp;
1279
1280         spin_lock(&fp->fi_lock);
1281         fp->fi_share_deny = 0;
1282         list_for_each_entry(stp, &fp->fi_stateids, st_perfile)
1283                 fp->fi_share_deny |= bmap_to_share_mode(stp->st_deny_bmap);
1284         spin_unlock(&fp->fi_lock);
1285 }
1286
1287 static void
1288 reset_union_bmap_deny(u32 deny, struct nfs4_ol_stateid *stp)
1289 {
1290         int i;
1291         bool change = false;
1292
1293         for (i = 1; i < 4; i++) {
1294                 if ((i & deny) != i) {
1295                         change = true;
1296                         clear_deny(i, stp);
1297                 }
1298         }
1299
1300         /* Recalculate per-file deny mode if there was a change */
1301         if (change)
1302                 recalculate_deny_mode(stp->st_stid.sc_file);
1303 }
1304
1305 /* release all access and file references for a given stateid */
1306 static void
1307 release_all_access(struct nfs4_ol_stateid *stp)
1308 {
1309         int i;
1310         struct nfs4_file *fp = stp->st_stid.sc_file;
1311
1312         if (fp && stp->st_deny_bmap != 0)
1313                 recalculate_deny_mode(fp);
1314
1315         for (i = 1; i < 4; i++) {
1316                 if (test_access(i, stp))
1317                         nfs4_file_put_access(stp->st_stid.sc_file, i);
1318                 clear_access(i, stp);
1319         }
1320 }
1321
1322 static inline void nfs4_free_stateowner(struct nfs4_stateowner *sop)
1323 {
1324         kfree(sop->so_owner.data);
1325         sop->so_ops->so_free(sop);
1326 }
1327
1328 static void nfs4_put_stateowner(struct nfs4_stateowner *sop)
1329 {
1330         struct nfs4_client *clp = sop->so_client;
1331
1332         might_lock(&clp->cl_lock);
1333
1334         if (!atomic_dec_and_lock(&sop->so_count, &clp->cl_lock))
1335                 return;
1336         sop->so_ops->so_unhash(sop);
1337         spin_unlock(&clp->cl_lock);
1338         nfs4_free_stateowner(sop);
1339 }
1340
1341 static bool
1342 nfs4_ol_stateid_unhashed(const struct nfs4_ol_stateid *stp)
1343 {
1344         return list_empty(&stp->st_perfile);
1345 }
1346
1347 static bool unhash_ol_stateid(struct nfs4_ol_stateid *stp)
1348 {
1349         struct nfs4_file *fp = stp->st_stid.sc_file;
1350
1351         lockdep_assert_held(&stp->st_stateowner->so_client->cl_lock);
1352
1353         if (list_empty(&stp->st_perfile))
1354                 return false;
1355
1356         spin_lock(&fp->fi_lock);
1357         list_del_init(&stp->st_perfile);
1358         spin_unlock(&fp->fi_lock);
1359         list_del(&stp->st_perstateowner);
1360         return true;
1361 }
1362
1363 static void nfs4_free_ol_stateid(struct nfs4_stid *stid)
1364 {
1365         struct nfs4_ol_stateid *stp = openlockstateid(stid);
1366
1367         put_clnt_odstate(stp->st_clnt_odstate);
1368         release_all_access(stp);
1369         if (stp->st_stateowner)
1370                 nfs4_put_stateowner(stp->st_stateowner);
1371         kmem_cache_free(stateid_slab, stid);
1372 }
1373
1374 static void nfs4_free_lock_stateid(struct nfs4_stid *stid)
1375 {
1376         struct nfs4_ol_stateid *stp = openlockstateid(stid);
1377         struct nfs4_lockowner *lo = lockowner(stp->st_stateowner);
1378         struct nfsd_file *nf;
1379
1380         nf = find_any_file(stp->st_stid.sc_file);
1381         if (nf) {
1382                 get_file(nf->nf_file);
1383                 filp_close(nf->nf_file, (fl_owner_t)lo);
1384                 nfsd_file_put(nf);
1385         }
1386         nfs4_free_ol_stateid(stid);
1387 }
1388
1389 /*
1390  * Put the persistent reference to an already unhashed generic stateid, while
1391  * holding the cl_lock. If it's the last reference, then put it onto the
1392  * reaplist for later destruction.
1393  */
1394 static void put_ol_stateid_locked(struct nfs4_ol_stateid *stp,
1395                                        struct list_head *reaplist)
1396 {
1397         struct nfs4_stid *s = &stp->st_stid;
1398         struct nfs4_client *clp = s->sc_client;
1399
1400         lockdep_assert_held(&clp->cl_lock);
1401
1402         WARN_ON_ONCE(!list_empty(&stp->st_locks));
1403
1404         if (!refcount_dec_and_test(&s->sc_count)) {
1405                 wake_up_all(&close_wq);
1406                 return;
1407         }
1408
1409         idr_remove(&clp->cl_stateids, s->sc_stateid.si_opaque.so_id);
1410         list_add(&stp->st_locks, reaplist);
1411 }
1412
1413 static bool unhash_lock_stateid(struct nfs4_ol_stateid *stp)
1414 {
1415         lockdep_assert_held(&stp->st_stid.sc_client->cl_lock);
1416
1417         if (!unhash_ol_stateid(stp))
1418                 return false;
1419         list_del_init(&stp->st_locks);
1420         nfs4_unhash_stid(&stp->st_stid);
1421         return true;
1422 }
1423
1424 static void release_lock_stateid(struct nfs4_ol_stateid *stp)
1425 {
1426         struct nfs4_client *clp = stp->st_stid.sc_client;
1427         bool unhashed;
1428
1429         spin_lock(&clp->cl_lock);
1430         unhashed = unhash_lock_stateid(stp);
1431         spin_unlock(&clp->cl_lock);
1432         if (unhashed)
1433                 nfs4_put_stid(&stp->st_stid);
1434 }
1435
1436 static void unhash_lockowner_locked(struct nfs4_lockowner *lo)
1437 {
1438         struct nfs4_client *clp = lo->lo_owner.so_client;
1439
1440         lockdep_assert_held(&clp->cl_lock);
1441
1442         list_del_init(&lo->lo_owner.so_strhash);
1443 }
1444
1445 /*
1446  * Free a list of generic stateids that were collected earlier after being
1447  * fully unhashed.
1448  */
1449 static void
1450 free_ol_stateid_reaplist(struct list_head *reaplist)
1451 {
1452         struct nfs4_ol_stateid *stp;
1453         struct nfs4_file *fp;
1454
1455         might_sleep();
1456
1457         while (!list_empty(reaplist)) {
1458                 stp = list_first_entry(reaplist, struct nfs4_ol_stateid,
1459                                        st_locks);
1460                 list_del(&stp->st_locks);
1461                 fp = stp->st_stid.sc_file;
1462                 stp->st_stid.sc_free(&stp->st_stid);
1463                 if (fp)
1464                         put_nfs4_file(fp);
1465         }
1466 }
1467
1468 static void release_open_stateid_locks(struct nfs4_ol_stateid *open_stp,
1469                                        struct list_head *reaplist)
1470 {
1471         struct nfs4_ol_stateid *stp;
1472
1473         lockdep_assert_held(&open_stp->st_stid.sc_client->cl_lock);
1474
1475         while (!list_empty(&open_stp->st_locks)) {
1476                 stp = list_entry(open_stp->st_locks.next,
1477                                 struct nfs4_ol_stateid, st_locks);
1478                 WARN_ON(!unhash_lock_stateid(stp));
1479                 put_ol_stateid_locked(stp, reaplist);
1480         }
1481 }
1482
1483 static bool unhash_open_stateid(struct nfs4_ol_stateid *stp,
1484                                 struct list_head *reaplist)
1485 {
1486         lockdep_assert_held(&stp->st_stid.sc_client->cl_lock);
1487
1488         if (!unhash_ol_stateid(stp))
1489                 return false;
1490         release_open_stateid_locks(stp, reaplist);
1491         return true;
1492 }
1493
1494 static void release_open_stateid(struct nfs4_ol_stateid *stp)
1495 {
1496         LIST_HEAD(reaplist);
1497
1498         spin_lock(&stp->st_stid.sc_client->cl_lock);
1499         if (unhash_open_stateid(stp, &reaplist))
1500                 put_ol_stateid_locked(stp, &reaplist);
1501         spin_unlock(&stp->st_stid.sc_client->cl_lock);
1502         free_ol_stateid_reaplist(&reaplist);
1503 }
1504
1505 static void unhash_openowner_locked(struct nfs4_openowner *oo)
1506 {
1507         struct nfs4_client *clp = oo->oo_owner.so_client;
1508
1509         lockdep_assert_held(&clp->cl_lock);
1510
1511         list_del_init(&oo->oo_owner.so_strhash);
1512         list_del_init(&oo->oo_perclient);
1513 }
1514
1515 static void release_last_closed_stateid(struct nfs4_openowner *oo)
1516 {
1517         struct nfsd_net *nn = net_generic(oo->oo_owner.so_client->net,
1518                                           nfsd_net_id);
1519         struct nfs4_ol_stateid *s;
1520
1521         spin_lock(&nn->client_lock);
1522         s = oo->oo_last_closed_stid;
1523         if (s) {
1524                 list_del_init(&oo->oo_close_lru);
1525                 oo->oo_last_closed_stid = NULL;
1526         }
1527         spin_unlock(&nn->client_lock);
1528         if (s)
1529                 nfs4_put_stid(&s->st_stid);
1530 }
1531
1532 static void release_openowner(struct nfs4_openowner *oo)
1533 {
1534         struct nfs4_ol_stateid *stp;
1535         struct nfs4_client *clp = oo->oo_owner.so_client;
1536         struct list_head reaplist;
1537
1538         INIT_LIST_HEAD(&reaplist);
1539
1540         spin_lock(&clp->cl_lock);
1541         unhash_openowner_locked(oo);
1542         while (!list_empty(&oo->oo_owner.so_stateids)) {
1543                 stp = list_first_entry(&oo->oo_owner.so_stateids,
1544                                 struct nfs4_ol_stateid, st_perstateowner);
1545                 if (unhash_open_stateid(stp, &reaplist))
1546                         put_ol_stateid_locked(stp, &reaplist);
1547         }
1548         spin_unlock(&clp->cl_lock);
1549         free_ol_stateid_reaplist(&reaplist);
1550         release_last_closed_stateid(oo);
1551         nfs4_put_stateowner(&oo->oo_owner);
1552 }
1553
1554 static inline int
1555 hash_sessionid(struct nfs4_sessionid *sessionid)
1556 {
1557         struct nfsd4_sessionid *sid = (struct nfsd4_sessionid *)sessionid;
1558
1559         return sid->sequence % SESSION_HASH_SIZE;
1560 }
1561
1562 #ifdef CONFIG_SUNRPC_DEBUG
1563 static inline void
1564 dump_sessionid(const char *fn, struct nfs4_sessionid *sessionid)
1565 {
1566         u32 *ptr = (u32 *)(&sessionid->data[0]);
1567         dprintk("%s: %u:%u:%u:%u\n", fn, ptr[0], ptr[1], ptr[2], ptr[3]);
1568 }
1569 #else
1570 static inline void
1571 dump_sessionid(const char *fn, struct nfs4_sessionid *sessionid)
1572 {
1573 }
1574 #endif
1575
1576 /*
1577  * Bump the seqid on cstate->replay_owner, and clear replay_owner if it
1578  * won't be used for replay.
1579  */
1580 void nfsd4_bump_seqid(struct nfsd4_compound_state *cstate, __be32 nfserr)
1581 {
1582         struct nfs4_stateowner *so = cstate->replay_owner;
1583
1584         if (nfserr == nfserr_replay_me)
1585                 return;
1586
1587         if (!seqid_mutating_err(ntohl(nfserr))) {
1588                 nfsd4_cstate_clear_replay(cstate);
1589                 return;
1590         }
1591         if (!so)
1592                 return;
1593         if (so->so_is_open_owner)
1594                 release_last_closed_stateid(openowner(so));
1595         so->so_seqid++;
1596         return;
1597 }
1598
1599 static void
1600 gen_sessionid(struct nfsd4_session *ses)
1601 {
1602         struct nfs4_client *clp = ses->se_client;
1603         struct nfsd4_sessionid *sid;
1604
1605         sid = (struct nfsd4_sessionid *)ses->se_sessionid.data;
1606         sid->clientid = clp->cl_clientid;
1607         sid->sequence = current_sessionid++;
1608         sid->reserved = 0;
1609 }
1610
1611 /*
1612  * The protocol defines ca_maxresponssize_cached to include the size of
1613  * the rpc header, but all we need to cache is the data starting after
1614  * the end of the initial SEQUENCE operation--the rest we regenerate
1615  * each time.  Therefore we can advertise a ca_maxresponssize_cached
1616  * value that is the number of bytes in our cache plus a few additional
1617  * bytes.  In order to stay on the safe side, and not promise more than
1618  * we can cache, those additional bytes must be the minimum possible: 24
1619  * bytes of rpc header (xid through accept state, with AUTH_NULL
1620  * verifier), 12 for the compound header (with zero-length tag), and 44
1621  * for the SEQUENCE op response:
1622  */
1623 #define NFSD_MIN_HDR_SEQ_SZ  (24 + 12 + 44)
1624
1625 static void
1626 free_session_slots(struct nfsd4_session *ses)
1627 {
1628         int i;
1629
1630         for (i = 0; i < ses->se_fchannel.maxreqs; i++) {
1631                 free_svc_cred(&ses->se_slots[i]->sl_cred);
1632                 kfree(ses->se_slots[i]);
1633         }
1634 }
1635
1636 /*
1637  * We don't actually need to cache the rpc and session headers, so we
1638  * can allocate a little less for each slot:
1639  */
1640 static inline u32 slot_bytes(struct nfsd4_channel_attrs *ca)
1641 {
1642         u32 size;
1643
1644         if (ca->maxresp_cached < NFSD_MIN_HDR_SEQ_SZ)
1645                 size = 0;
1646         else
1647                 size = ca->maxresp_cached - NFSD_MIN_HDR_SEQ_SZ;
1648         return size + sizeof(struct nfsd4_slot);
1649 }
1650
1651 /*
1652  * XXX: If we run out of reserved DRC memory we could (up to a point)
1653  * re-negotiate active sessions and reduce their slot usage to make
1654  * room for new connections. For now we just fail the create session.
1655  */
1656 static u32 nfsd4_get_drc_mem(struct nfsd4_channel_attrs *ca, struct nfsd_net *nn)
1657 {
1658         u32 slotsize = slot_bytes(ca);
1659         u32 num = ca->maxreqs;
1660         unsigned long avail, total_avail;
1661         unsigned int scale_factor;
1662
1663         spin_lock(&nfsd_drc_lock);
1664         if (nfsd_drc_max_mem > nfsd_drc_mem_used)
1665                 total_avail = nfsd_drc_max_mem - nfsd_drc_mem_used;
1666         else
1667                 /* We have handed out more space than we chose in
1668                  * set_max_drc() to allow.  That isn't really a
1669                  * problem as long as that doesn't make us think we
1670                  * have lots more due to integer overflow.
1671                  */
1672                 total_avail = 0;
1673         avail = min((unsigned long)NFSD_MAX_MEM_PER_SESSION, total_avail);
1674         /*
1675          * Never use more than a fraction of the remaining memory,
1676          * unless it's the only way to give this client a slot.
1677          * The chosen fraction is either 1/8 or 1/number of threads,
1678          * whichever is smaller.  This ensures there are adequate
1679          * slots to support multiple clients per thread.
1680          * Give the client one slot even if that would require
1681          * over-allocation--it is better than failure.
1682          */
1683         scale_factor = max_t(unsigned int, 8, nn->nfsd_serv->sv_nrthreads);
1684
1685         avail = clamp_t(unsigned long, avail, slotsize,
1686                         total_avail/scale_factor);
1687         num = min_t(int, num, avail / slotsize);
1688         num = max_t(int, num, 1);
1689         nfsd_drc_mem_used += num * slotsize;
1690         spin_unlock(&nfsd_drc_lock);
1691
1692         return num;
1693 }
1694
1695 static void nfsd4_put_drc_mem(struct nfsd4_channel_attrs *ca)
1696 {
1697         int slotsize = slot_bytes(ca);
1698
1699         spin_lock(&nfsd_drc_lock);
1700         nfsd_drc_mem_used -= slotsize * ca->maxreqs;
1701         spin_unlock(&nfsd_drc_lock);
1702 }
1703
1704 static struct nfsd4_session *alloc_session(struct nfsd4_channel_attrs *fattrs,
1705                                            struct nfsd4_channel_attrs *battrs)
1706 {
1707         int numslots = fattrs->maxreqs;
1708         int slotsize = slot_bytes(fattrs);
1709         struct nfsd4_session *new;
1710         int mem, i;
1711
1712         BUILD_BUG_ON(NFSD_MAX_SLOTS_PER_SESSION * sizeof(struct nfsd4_slot *)
1713                         + sizeof(struct nfsd4_session) > PAGE_SIZE);
1714         mem = numslots * sizeof(struct nfsd4_slot *);
1715
1716         new = kzalloc(sizeof(*new) + mem, GFP_KERNEL);
1717         if (!new)
1718                 return NULL;
1719         /* allocate each struct nfsd4_slot and data cache in one piece */
1720         for (i = 0; i < numslots; i++) {
1721                 new->se_slots[i] = kzalloc(slotsize, GFP_KERNEL);
1722                 if (!new->se_slots[i])
1723                         goto out_free;
1724         }
1725
1726         memcpy(&new->se_fchannel, fattrs, sizeof(struct nfsd4_channel_attrs));
1727         memcpy(&new->se_bchannel, battrs, sizeof(struct nfsd4_channel_attrs));
1728
1729         return new;
1730 out_free:
1731         while (i--)
1732                 kfree(new->se_slots[i]);
1733         kfree(new);
1734         return NULL;
1735 }
1736
1737 static void free_conn(struct nfsd4_conn *c)
1738 {
1739         svc_xprt_put(c->cn_xprt);
1740         kfree(c);
1741 }
1742
1743 static void nfsd4_conn_lost(struct svc_xpt_user *u)
1744 {
1745         struct nfsd4_conn *c = container_of(u, struct nfsd4_conn, cn_xpt_user);
1746         struct nfs4_client *clp = c->cn_session->se_client;
1747
1748         spin_lock(&clp->cl_lock);
1749         if (!list_empty(&c->cn_persession)) {
1750                 list_del(&c->cn_persession);
1751                 free_conn(c);
1752         }
1753         nfsd4_probe_callback(clp);
1754         spin_unlock(&clp->cl_lock);
1755 }
1756
1757 static struct nfsd4_conn *alloc_conn(struct svc_rqst *rqstp, u32 flags)
1758 {
1759         struct nfsd4_conn *conn;
1760
1761         conn = kmalloc(sizeof(struct nfsd4_conn), GFP_KERNEL);
1762         if (!conn)
1763                 return NULL;
1764         svc_xprt_get(rqstp->rq_xprt);
1765         conn->cn_xprt = rqstp->rq_xprt;
1766         conn->cn_flags = flags;
1767         INIT_LIST_HEAD(&conn->cn_xpt_user.list);
1768         return conn;
1769 }
1770
1771 static void __nfsd4_hash_conn(struct nfsd4_conn *conn, struct nfsd4_session *ses)
1772 {
1773         conn->cn_session = ses;
1774         list_add(&conn->cn_persession, &ses->se_conns);
1775 }
1776
1777 static void nfsd4_hash_conn(struct nfsd4_conn *conn, struct nfsd4_session *ses)
1778 {
1779         struct nfs4_client *clp = ses->se_client;
1780
1781         spin_lock(&clp->cl_lock);
1782         __nfsd4_hash_conn(conn, ses);
1783         spin_unlock(&clp->cl_lock);
1784 }
1785
1786 static int nfsd4_register_conn(struct nfsd4_conn *conn)
1787 {
1788         conn->cn_xpt_user.callback = nfsd4_conn_lost;
1789         return register_xpt_user(conn->cn_xprt, &conn->cn_xpt_user);
1790 }
1791
1792 static void nfsd4_init_conn(struct svc_rqst *rqstp, struct nfsd4_conn *conn, struct nfsd4_session *ses)
1793 {
1794         int ret;
1795
1796         nfsd4_hash_conn(conn, ses);
1797         ret = nfsd4_register_conn(conn);
1798         if (ret)
1799                 /* oops; xprt is already down: */
1800                 nfsd4_conn_lost(&conn->cn_xpt_user);
1801         /* We may have gained or lost a callback channel: */
1802         nfsd4_probe_callback_sync(ses->se_client);
1803 }
1804
1805 static struct nfsd4_conn *alloc_conn_from_crses(struct svc_rqst *rqstp, struct nfsd4_create_session *cses)
1806 {
1807         u32 dir = NFS4_CDFC4_FORE;
1808
1809         if (cses->flags & SESSION4_BACK_CHAN)
1810                 dir |= NFS4_CDFC4_BACK;
1811         return alloc_conn(rqstp, dir);
1812 }
1813
1814 /* must be called under client_lock */
1815 static void nfsd4_del_conns(struct nfsd4_session *s)
1816 {
1817         struct nfs4_client *clp = s->se_client;
1818         struct nfsd4_conn *c;
1819
1820         spin_lock(&clp->cl_lock);
1821         while (!list_empty(&s->se_conns)) {
1822                 c = list_first_entry(&s->se_conns, struct nfsd4_conn, cn_persession);
1823                 list_del_init(&c->cn_persession);
1824                 spin_unlock(&clp->cl_lock);
1825
1826                 unregister_xpt_user(c->cn_xprt, &c->cn_xpt_user);
1827                 free_conn(c);
1828
1829                 spin_lock(&clp->cl_lock);
1830         }
1831         spin_unlock(&clp->cl_lock);
1832 }
1833
1834 static void __free_session(struct nfsd4_session *ses)
1835 {
1836         free_session_slots(ses);
1837         kfree(ses);
1838 }
1839
1840 static void free_session(struct nfsd4_session *ses)
1841 {
1842         nfsd4_del_conns(ses);
1843         nfsd4_put_drc_mem(&ses->se_fchannel);
1844         __free_session(ses);
1845 }
1846
1847 static void init_session(struct svc_rqst *rqstp, struct nfsd4_session *new, struct nfs4_client *clp, struct nfsd4_create_session *cses)
1848 {
1849         int idx;
1850         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
1851
1852         new->se_client = clp;
1853         gen_sessionid(new);
1854
1855         INIT_LIST_HEAD(&new->se_conns);
1856
1857         new->se_cb_seq_nr = 1;
1858         new->se_flags = cses->flags;
1859         new->se_cb_prog = cses->callback_prog;
1860         new->se_cb_sec = cses->cb_sec;
1861         atomic_set(&new->se_ref, 0);
1862         idx = hash_sessionid(&new->se_sessionid);
1863         list_add(&new->se_hash, &nn->sessionid_hashtbl[idx]);
1864         spin_lock(&clp->cl_lock);
1865         list_add(&new->se_perclnt, &clp->cl_sessions);
1866         spin_unlock(&clp->cl_lock);
1867
1868         {
1869                 struct sockaddr *sa = svc_addr(rqstp);
1870                 /*
1871                  * This is a little silly; with sessions there's no real
1872                  * use for the callback address.  Use the peer address
1873                  * as a reasonable default for now, but consider fixing
1874                  * the rpc client not to require an address in the
1875                  * future:
1876                  */
1877                 rpc_copy_addr((struct sockaddr *)&clp->cl_cb_conn.cb_addr, sa);
1878                 clp->cl_cb_conn.cb_addrlen = svc_addr_len(sa);
1879         }
1880 }
1881
1882 /* caller must hold client_lock */
1883 static struct nfsd4_session *
1884 __find_in_sessionid_hashtbl(struct nfs4_sessionid *sessionid, struct net *net)
1885 {
1886         struct nfsd4_session *elem;
1887         int idx;
1888         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
1889
1890         lockdep_assert_held(&nn->client_lock);
1891
1892         dump_sessionid(__func__, sessionid);
1893         idx = hash_sessionid(sessionid);
1894         /* Search in the appropriate list */
1895         list_for_each_entry(elem, &nn->sessionid_hashtbl[idx], se_hash) {
1896                 if (!memcmp(elem->se_sessionid.data, sessionid->data,
1897                             NFS4_MAX_SESSIONID_LEN)) {
1898                         return elem;
1899                 }
1900         }
1901
1902         dprintk("%s: session not found\n", __func__);
1903         return NULL;
1904 }
1905
1906 static struct nfsd4_session *
1907 find_in_sessionid_hashtbl(struct nfs4_sessionid *sessionid, struct net *net,
1908                 __be32 *ret)
1909 {
1910         struct nfsd4_session *session;
1911         __be32 status = nfserr_badsession;
1912
1913         session = __find_in_sessionid_hashtbl(sessionid, net);
1914         if (!session)
1915                 goto out;
1916         status = nfsd4_get_session_locked(session);
1917         if (status)
1918                 session = NULL;
1919 out:
1920         *ret = status;
1921         return session;
1922 }
1923
1924 /* caller must hold client_lock */
1925 static void
1926 unhash_session(struct nfsd4_session *ses)
1927 {
1928         struct nfs4_client *clp = ses->se_client;
1929         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
1930
1931         lockdep_assert_held(&nn->client_lock);
1932
1933         list_del(&ses->se_hash);
1934         spin_lock(&ses->se_client->cl_lock);
1935         list_del(&ses->se_perclnt);
1936         spin_unlock(&ses->se_client->cl_lock);
1937 }
1938
1939 /* SETCLIENTID and SETCLIENTID_CONFIRM Helper functions */
1940 static int
1941 STALE_CLIENTID(clientid_t *clid, struct nfsd_net *nn)
1942 {
1943         /*
1944          * We're assuming the clid was not given out from a boot
1945          * precisely 2^32 (about 136 years) before this one.  That seems
1946          * a safe assumption:
1947          */
1948         if (clid->cl_boot == (u32)nn->boot_time)
1949                 return 0;
1950         trace_nfsd_clid_stale(clid);
1951         return 1;
1952 }
1953
1954 /* 
1955  * XXX Should we use a slab cache ?
1956  * This type of memory management is somewhat inefficient, but we use it
1957  * anyway since SETCLIENTID is not a common operation.
1958  */
1959 static struct nfs4_client *alloc_client(struct xdr_netobj name)
1960 {
1961         struct nfs4_client *clp;
1962         int i;
1963
1964         clp = kmem_cache_zalloc(client_slab, GFP_KERNEL);
1965         if (clp == NULL)
1966                 return NULL;
1967         xdr_netobj_dup(&clp->cl_name, &name, GFP_KERNEL);
1968         if (clp->cl_name.data == NULL)
1969                 goto err_no_name;
1970         clp->cl_ownerstr_hashtbl = kmalloc_array(OWNER_HASH_SIZE,
1971                                                  sizeof(struct list_head),
1972                                                  GFP_KERNEL);
1973         if (!clp->cl_ownerstr_hashtbl)
1974                 goto err_no_hashtbl;
1975         for (i = 0; i < OWNER_HASH_SIZE; i++)
1976                 INIT_LIST_HEAD(&clp->cl_ownerstr_hashtbl[i]);
1977         INIT_LIST_HEAD(&clp->cl_sessions);
1978         idr_init(&clp->cl_stateids);
1979         atomic_set(&clp->cl_rpc_users, 0);
1980         clp->cl_cb_state = NFSD4_CB_UNKNOWN;
1981         INIT_LIST_HEAD(&clp->cl_idhash);
1982         INIT_LIST_HEAD(&clp->cl_openowners);
1983         INIT_LIST_HEAD(&clp->cl_delegations);
1984         INIT_LIST_HEAD(&clp->cl_lru);
1985         INIT_LIST_HEAD(&clp->cl_revoked);
1986 #ifdef CONFIG_NFSD_PNFS
1987         INIT_LIST_HEAD(&clp->cl_lo_states);
1988 #endif
1989         INIT_LIST_HEAD(&clp->async_copies);
1990         spin_lock_init(&clp->async_lock);
1991         spin_lock_init(&clp->cl_lock);
1992         rpc_init_wait_queue(&clp->cl_cb_waitq, "Backchannel slot table");
1993         return clp;
1994 err_no_hashtbl:
1995         kfree(clp->cl_name.data);
1996 err_no_name:
1997         kmem_cache_free(client_slab, clp);
1998         return NULL;
1999 }
2000
2001 static void __free_client(struct kref *k)
2002 {
2003         struct nfsdfs_client *c = container_of(k, struct nfsdfs_client, cl_ref);
2004         struct nfs4_client *clp = container_of(c, struct nfs4_client, cl_nfsdfs);
2005
2006         free_svc_cred(&clp->cl_cred);
2007         kfree(clp->cl_ownerstr_hashtbl);
2008         kfree(clp->cl_name.data);
2009         kfree(clp->cl_nii_domain.data);
2010         kfree(clp->cl_nii_name.data);
2011         idr_destroy(&clp->cl_stateids);
2012         kmem_cache_free(client_slab, clp);
2013 }
2014
2015 static void drop_client(struct nfs4_client *clp)
2016 {
2017         kref_put(&clp->cl_nfsdfs.cl_ref, __free_client);
2018 }
2019
2020 static void
2021 free_client(struct nfs4_client *clp)
2022 {
2023         while (!list_empty(&clp->cl_sessions)) {
2024                 struct nfsd4_session *ses;
2025                 ses = list_entry(clp->cl_sessions.next, struct nfsd4_session,
2026                                 se_perclnt);
2027                 list_del(&ses->se_perclnt);
2028                 WARN_ON_ONCE(atomic_read(&ses->se_ref));
2029                 free_session(ses);
2030         }
2031         rpc_destroy_wait_queue(&clp->cl_cb_waitq);
2032         if (clp->cl_nfsd_dentry) {
2033                 nfsd_client_rmdir(clp->cl_nfsd_dentry);
2034                 clp->cl_nfsd_dentry = NULL;
2035                 wake_up_all(&expiry_wq);
2036         }
2037         drop_client(clp);
2038 }
2039
2040 /* must be called under the client_lock */
2041 static void
2042 unhash_client_locked(struct nfs4_client *clp)
2043 {
2044         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
2045         struct nfsd4_session *ses;
2046
2047         lockdep_assert_held(&nn->client_lock);
2048
2049         /* Mark the client as expired! */
2050         clp->cl_time = 0;
2051         /* Make it invisible */
2052         if (!list_empty(&clp->cl_idhash)) {
2053                 list_del_init(&clp->cl_idhash);
2054                 if (test_bit(NFSD4_CLIENT_CONFIRMED, &clp->cl_flags))
2055                         rb_erase(&clp->cl_namenode, &nn->conf_name_tree);
2056                 else
2057                         rb_erase(&clp->cl_namenode, &nn->unconf_name_tree);
2058         }
2059         list_del_init(&clp->cl_lru);
2060         spin_lock(&clp->cl_lock);
2061         list_for_each_entry(ses, &clp->cl_sessions, se_perclnt)
2062                 list_del_init(&ses->se_hash);
2063         spin_unlock(&clp->cl_lock);
2064 }
2065
2066 static void
2067 unhash_client(struct nfs4_client *clp)
2068 {
2069         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
2070
2071         spin_lock(&nn->client_lock);
2072         unhash_client_locked(clp);
2073         spin_unlock(&nn->client_lock);
2074 }
2075
2076 static __be32 mark_client_expired_locked(struct nfs4_client *clp)
2077 {
2078         if (atomic_read(&clp->cl_rpc_users))
2079                 return nfserr_jukebox;
2080         unhash_client_locked(clp);
2081         return nfs_ok;
2082 }
2083
2084 static void
2085 __destroy_client(struct nfs4_client *clp)
2086 {
2087         int i;
2088         struct nfs4_openowner *oo;
2089         struct nfs4_delegation *dp;
2090         struct list_head reaplist;
2091
2092         INIT_LIST_HEAD(&reaplist);
2093         spin_lock(&state_lock);
2094         while (!list_empty(&clp->cl_delegations)) {
2095                 dp = list_entry(clp->cl_delegations.next, struct nfs4_delegation, dl_perclnt);
2096                 WARN_ON(!unhash_delegation_locked(dp));
2097                 list_add(&dp->dl_recall_lru, &reaplist);
2098         }
2099         spin_unlock(&state_lock);
2100         while (!list_empty(&reaplist)) {
2101                 dp = list_entry(reaplist.next, struct nfs4_delegation, dl_recall_lru);
2102                 list_del_init(&dp->dl_recall_lru);
2103                 destroy_unhashed_deleg(dp);
2104         }
2105         while (!list_empty(&clp->cl_revoked)) {
2106                 dp = list_entry(clp->cl_revoked.next, struct nfs4_delegation, dl_recall_lru);
2107                 list_del_init(&dp->dl_recall_lru);
2108                 nfs4_put_stid(&dp->dl_stid);
2109         }
2110         while (!list_empty(&clp->cl_openowners)) {
2111                 oo = list_entry(clp->cl_openowners.next, struct nfs4_openowner, oo_perclient);
2112                 nfs4_get_stateowner(&oo->oo_owner);
2113                 release_openowner(oo);
2114         }
2115         for (i = 0; i < OWNER_HASH_SIZE; i++) {
2116                 struct nfs4_stateowner *so, *tmp;
2117
2118                 list_for_each_entry_safe(so, tmp, &clp->cl_ownerstr_hashtbl[i],
2119                                          so_strhash) {
2120                         /* Should be no openowners at this point */
2121                         WARN_ON_ONCE(so->so_is_open_owner);
2122                         remove_blocked_locks(lockowner(so));
2123                 }
2124         }
2125         nfsd4_return_all_client_layouts(clp);
2126         nfsd4_shutdown_copy(clp);
2127         nfsd4_shutdown_callback(clp);
2128         if (clp->cl_cb_conn.cb_xprt)
2129                 svc_xprt_put(clp->cl_cb_conn.cb_xprt);
2130         free_client(clp);
2131         wake_up_all(&expiry_wq);
2132 }
2133
2134 static void
2135 destroy_client(struct nfs4_client *clp)
2136 {
2137         unhash_client(clp);
2138         __destroy_client(clp);
2139 }
2140
2141 static void inc_reclaim_complete(struct nfs4_client *clp)
2142 {
2143         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
2144
2145         if (!nn->track_reclaim_completes)
2146                 return;
2147         if (!nfsd4_find_reclaim_client(clp->cl_name, nn))
2148                 return;
2149         if (atomic_inc_return(&nn->nr_reclaim_complete) ==
2150                         nn->reclaim_str_hashtbl_size) {
2151                 printk(KERN_INFO "NFSD: all clients done reclaiming, ending NFSv4 grace period (net %x)\n",
2152                                 clp->net->ns.inum);
2153                 nfsd4_end_grace(nn);
2154         }
2155 }
2156
2157 static void expire_client(struct nfs4_client *clp)
2158 {
2159         unhash_client(clp);
2160         nfsd4_client_record_remove(clp);
2161         __destroy_client(clp);
2162 }
2163
2164 static void copy_verf(struct nfs4_client *target, nfs4_verifier *source)
2165 {
2166         memcpy(target->cl_verifier.data, source->data,
2167                         sizeof(target->cl_verifier.data));
2168 }
2169
2170 static void copy_clid(struct nfs4_client *target, struct nfs4_client *source)
2171 {
2172         target->cl_clientid.cl_boot = source->cl_clientid.cl_boot; 
2173         target->cl_clientid.cl_id = source->cl_clientid.cl_id; 
2174 }
2175
2176 static int copy_cred(struct svc_cred *target, struct svc_cred *source)
2177 {
2178         target->cr_principal = kstrdup(source->cr_principal, GFP_KERNEL);
2179         target->cr_raw_principal = kstrdup(source->cr_raw_principal,
2180                                                                 GFP_KERNEL);
2181         target->cr_targ_princ = kstrdup(source->cr_targ_princ, GFP_KERNEL);
2182         if ((source->cr_principal && !target->cr_principal) ||
2183             (source->cr_raw_principal && !target->cr_raw_principal) ||
2184             (source->cr_targ_princ && !target->cr_targ_princ))
2185                 return -ENOMEM;
2186
2187         target->cr_flavor = source->cr_flavor;
2188         target->cr_uid = source->cr_uid;
2189         target->cr_gid = source->cr_gid;
2190         target->cr_group_info = source->cr_group_info;
2191         get_group_info(target->cr_group_info);
2192         target->cr_gss_mech = source->cr_gss_mech;
2193         if (source->cr_gss_mech)
2194                 gss_mech_get(source->cr_gss_mech);
2195         return 0;
2196 }
2197
2198 static int
2199 compare_blob(const struct xdr_netobj *o1, const struct xdr_netobj *o2)
2200 {
2201         if (o1->len < o2->len)
2202                 return -1;
2203         if (o1->len > o2->len)
2204                 return 1;
2205         return memcmp(o1->data, o2->data, o1->len);
2206 }
2207
2208 static int
2209 same_verf(nfs4_verifier *v1, nfs4_verifier *v2)
2210 {
2211         return 0 == memcmp(v1->data, v2->data, sizeof(v1->data));
2212 }
2213
2214 static int
2215 same_clid(clientid_t *cl1, clientid_t *cl2)
2216 {
2217         return (cl1->cl_boot == cl2->cl_boot) && (cl1->cl_id == cl2->cl_id);
2218 }
2219
2220 static bool groups_equal(struct group_info *g1, struct group_info *g2)
2221 {
2222         int i;
2223
2224         if (g1->ngroups != g2->ngroups)
2225                 return false;
2226         for (i=0; i<g1->ngroups; i++)
2227                 if (!gid_eq(g1->gid[i], g2->gid[i]))
2228                         return false;
2229         return true;
2230 }
2231
2232 /*
2233  * RFC 3530 language requires clid_inuse be returned when the
2234  * "principal" associated with a requests differs from that previously
2235  * used.  We use uid, gid's, and gss principal string as our best
2236  * approximation.  We also don't want to allow non-gss use of a client
2237  * established using gss: in theory cr_principal should catch that
2238  * change, but in practice cr_principal can be null even in the gss case
2239  * since gssd doesn't always pass down a principal string.
2240  */
2241 static bool is_gss_cred(struct svc_cred *cr)
2242 {
2243         /* Is cr_flavor one of the gss "pseudoflavors"?: */
2244         return (cr->cr_flavor > RPC_AUTH_MAXFLAVOR);
2245 }
2246
2247
2248 static bool
2249 same_creds(struct svc_cred *cr1, struct svc_cred *cr2)
2250 {
2251         if ((is_gss_cred(cr1) != is_gss_cred(cr2))
2252                 || (!uid_eq(cr1->cr_uid, cr2->cr_uid))
2253                 || (!gid_eq(cr1->cr_gid, cr2->cr_gid))
2254                 || !groups_equal(cr1->cr_group_info, cr2->cr_group_info))
2255                 return false;
2256         /* XXX: check that cr_targ_princ fields match ? */
2257         if (cr1->cr_principal == cr2->cr_principal)
2258                 return true;
2259         if (!cr1->cr_principal || !cr2->cr_principal)
2260                 return false;
2261         return 0 == strcmp(cr1->cr_principal, cr2->cr_principal);
2262 }
2263
2264 static bool svc_rqst_integrity_protected(struct svc_rqst *rqstp)
2265 {
2266         struct svc_cred *cr = &rqstp->rq_cred;
2267         u32 service;
2268
2269         if (!cr->cr_gss_mech)
2270                 return false;
2271         service = gss_pseudoflavor_to_service(cr->cr_gss_mech, cr->cr_flavor);
2272         return service == RPC_GSS_SVC_INTEGRITY ||
2273                service == RPC_GSS_SVC_PRIVACY;
2274 }
2275
2276 bool nfsd4_mach_creds_match(struct nfs4_client *cl, struct svc_rqst *rqstp)
2277 {
2278         struct svc_cred *cr = &rqstp->rq_cred;
2279
2280         if (!cl->cl_mach_cred)
2281                 return true;
2282         if (cl->cl_cred.cr_gss_mech != cr->cr_gss_mech)
2283                 return false;
2284         if (!svc_rqst_integrity_protected(rqstp))
2285                 return false;
2286         if (cl->cl_cred.cr_raw_principal)
2287                 return 0 == strcmp(cl->cl_cred.cr_raw_principal,
2288                                                 cr->cr_raw_principal);
2289         if (!cr->cr_principal)
2290                 return false;
2291         return 0 == strcmp(cl->cl_cred.cr_principal, cr->cr_principal);
2292 }
2293
2294 static void gen_confirm(struct nfs4_client *clp, struct nfsd_net *nn)
2295 {
2296         __be32 verf[2];
2297
2298         /*
2299          * This is opaque to client, so no need to byte-swap. Use
2300          * __force to keep sparse happy
2301          */
2302         verf[0] = (__force __be32)(u32)ktime_get_real_seconds();
2303         verf[1] = (__force __be32)nn->clverifier_counter++;
2304         memcpy(clp->cl_confirm.data, verf, sizeof(clp->cl_confirm.data));
2305 }
2306
2307 static void gen_clid(struct nfs4_client *clp, struct nfsd_net *nn)
2308 {
2309         clp->cl_clientid.cl_boot = (u32)nn->boot_time;
2310         clp->cl_clientid.cl_id = nn->clientid_counter++;
2311         gen_confirm(clp, nn);
2312 }
2313
2314 static struct nfs4_stid *
2315 find_stateid_locked(struct nfs4_client *cl, stateid_t *t)
2316 {
2317         struct nfs4_stid *ret;
2318
2319         ret = idr_find(&cl->cl_stateids, t->si_opaque.so_id);
2320         if (!ret || !ret->sc_type)
2321                 return NULL;
2322         return ret;
2323 }
2324
2325 static struct nfs4_stid *
2326 find_stateid_by_type(struct nfs4_client *cl, stateid_t *t, char typemask)
2327 {
2328         struct nfs4_stid *s;
2329
2330         spin_lock(&cl->cl_lock);
2331         s = find_stateid_locked(cl, t);
2332         if (s != NULL) {
2333                 if (typemask & s->sc_type)
2334                         refcount_inc(&s->sc_count);
2335                 else
2336                         s = NULL;
2337         }
2338         spin_unlock(&cl->cl_lock);
2339         return s;
2340 }
2341
2342 static struct nfs4_client *get_nfsdfs_clp(struct inode *inode)
2343 {
2344         struct nfsdfs_client *nc;
2345         nc = get_nfsdfs_client(inode);
2346         if (!nc)
2347                 return NULL;
2348         return container_of(nc, struct nfs4_client, cl_nfsdfs);
2349 }
2350
2351 static void seq_quote_mem(struct seq_file *m, char *data, int len)
2352 {
2353         seq_printf(m, "\"");
2354         seq_escape_mem_ascii(m, data, len);
2355         seq_printf(m, "\"");
2356 }
2357
2358 static int client_info_show(struct seq_file *m, void *v)
2359 {
2360         struct inode *inode = m->private;
2361         struct nfs4_client *clp;
2362         u64 clid;
2363
2364         clp = get_nfsdfs_clp(inode);
2365         if (!clp)
2366                 return -ENXIO;
2367         memcpy(&clid, &clp->cl_clientid, sizeof(clid));
2368         seq_printf(m, "clientid: 0x%llx\n", clid);
2369         seq_printf(m, "address: \"%pISpc\"\n", (struct sockaddr *)&clp->cl_addr);
2370         if (test_bit(NFSD4_CLIENT_CONFIRMED, &clp->cl_flags))
2371                 seq_puts(m, "status: confirmed\n");
2372         else
2373                 seq_puts(m, "status: unconfirmed\n");
2374         seq_printf(m, "name: ");
2375         seq_quote_mem(m, clp->cl_name.data, clp->cl_name.len);
2376         seq_printf(m, "\nminor version: %d\n", clp->cl_minorversion);
2377         if (clp->cl_nii_domain.data) {
2378                 seq_printf(m, "Implementation domain: ");
2379                 seq_quote_mem(m, clp->cl_nii_domain.data,
2380                                         clp->cl_nii_domain.len);
2381                 seq_printf(m, "\nImplementation name: ");
2382                 seq_quote_mem(m, clp->cl_nii_name.data, clp->cl_nii_name.len);
2383                 seq_printf(m, "\nImplementation time: [%lld, %ld]\n",
2384                         clp->cl_nii_time.tv_sec, clp->cl_nii_time.tv_nsec);
2385         }
2386         drop_client(clp);
2387
2388         return 0;
2389 }
2390
2391 static int client_info_open(struct inode *inode, struct file *file)
2392 {
2393         return single_open(file, client_info_show, inode);
2394 }
2395
2396 static const struct file_operations client_info_fops = {
2397         .open           = client_info_open,
2398         .read           = seq_read,
2399         .llseek         = seq_lseek,
2400         .release        = single_release,
2401 };
2402
2403 static void *states_start(struct seq_file *s, loff_t *pos)
2404         __acquires(&clp->cl_lock)
2405 {
2406         struct nfs4_client *clp = s->private;
2407         unsigned long id = *pos;
2408         void *ret;
2409
2410         spin_lock(&clp->cl_lock);
2411         ret = idr_get_next_ul(&clp->cl_stateids, &id);
2412         *pos = id;
2413         return ret;
2414 }
2415
2416 static void *states_next(struct seq_file *s, void *v, loff_t *pos)
2417 {
2418         struct nfs4_client *clp = s->private;
2419         unsigned long id = *pos;
2420         void *ret;
2421
2422         id = *pos;
2423         id++;
2424         ret = idr_get_next_ul(&clp->cl_stateids, &id);
2425         *pos = id;
2426         return ret;
2427 }
2428
2429 static void states_stop(struct seq_file *s, void *v)
2430         __releases(&clp->cl_lock)
2431 {
2432         struct nfs4_client *clp = s->private;
2433
2434         spin_unlock(&clp->cl_lock);
2435 }
2436
2437 static void nfs4_show_fname(struct seq_file *s, struct nfsd_file *f)
2438 {
2439          seq_printf(s, "filename: \"%pD2\"", f->nf_file);
2440 }
2441
2442 static void nfs4_show_superblock(struct seq_file *s, struct nfsd_file *f)
2443 {
2444         struct inode *inode = f->nf_inode;
2445
2446         seq_printf(s, "superblock: \"%02x:%02x:%ld\"",
2447                                         MAJOR(inode->i_sb->s_dev),
2448                                          MINOR(inode->i_sb->s_dev),
2449                                          inode->i_ino);
2450 }
2451
2452 static void nfs4_show_owner(struct seq_file *s, struct nfs4_stateowner *oo)
2453 {
2454         seq_printf(s, "owner: ");
2455         seq_quote_mem(s, oo->so_owner.data, oo->so_owner.len);
2456 }
2457
2458 static void nfs4_show_stateid(struct seq_file *s, stateid_t *stid)
2459 {
2460         seq_printf(s, "0x%.8x", stid->si_generation);
2461         seq_printf(s, "%12phN", &stid->si_opaque);
2462 }
2463
2464 static int nfs4_show_open(struct seq_file *s, struct nfs4_stid *st)
2465 {
2466         struct nfs4_ol_stateid *ols;
2467         struct nfs4_file *nf;
2468         struct nfsd_file *file;
2469         struct nfs4_stateowner *oo;
2470         unsigned int access, deny;
2471
2472         if (st->sc_type != NFS4_OPEN_STID && st->sc_type != NFS4_LOCK_STID)
2473                 return 0; /* XXX: or SEQ_SKIP? */
2474         ols = openlockstateid(st);
2475         oo = ols->st_stateowner;
2476         nf = st->sc_file;
2477         file = find_any_file(nf);
2478         if (!file)
2479                 return 0;
2480
2481         seq_printf(s, "- ");
2482         nfs4_show_stateid(s, &st->sc_stateid);
2483         seq_printf(s, ": { type: open, ");
2484
2485         access = bmap_to_share_mode(ols->st_access_bmap);
2486         deny   = bmap_to_share_mode(ols->st_deny_bmap);
2487
2488         seq_printf(s, "access: %s%s, ",
2489                 access & NFS4_SHARE_ACCESS_READ ? "r" : "-",
2490                 access & NFS4_SHARE_ACCESS_WRITE ? "w" : "-");
2491         seq_printf(s, "deny: %s%s, ",
2492                 deny & NFS4_SHARE_ACCESS_READ ? "r" : "-",
2493                 deny & NFS4_SHARE_ACCESS_WRITE ? "w" : "-");
2494
2495         nfs4_show_superblock(s, file);
2496         seq_printf(s, ", ");
2497         nfs4_show_fname(s, file);
2498         seq_printf(s, ", ");
2499         nfs4_show_owner(s, oo);
2500         seq_printf(s, " }\n");
2501         nfsd_file_put(file);
2502
2503         return 0;
2504 }
2505
2506 static int nfs4_show_lock(struct seq_file *s, struct nfs4_stid *st)
2507 {
2508         struct nfs4_ol_stateid *ols;
2509         struct nfs4_file *nf;
2510         struct nfsd_file *file;
2511         struct nfs4_stateowner *oo;
2512
2513         ols = openlockstateid(st);
2514         oo = ols->st_stateowner;
2515         nf = st->sc_file;
2516         file = find_any_file(nf);
2517         if (!file)
2518                 return 0;
2519
2520         seq_printf(s, "- ");
2521         nfs4_show_stateid(s, &st->sc_stateid);
2522         seq_printf(s, ": { type: lock, ");
2523
2524         /*
2525          * Note: a lock stateid isn't really the same thing as a lock,
2526          * it's the locking state held by one owner on a file, and there
2527          * may be multiple (or no) lock ranges associated with it.
2528          * (Same for the matter is true of open stateids.)
2529          */
2530
2531         nfs4_show_superblock(s, file);
2532         /* XXX: open stateid? */
2533         seq_printf(s, ", ");
2534         nfs4_show_fname(s, file);
2535         seq_printf(s, ", ");
2536         nfs4_show_owner(s, oo);
2537         seq_printf(s, " }\n");
2538         nfsd_file_put(file);
2539
2540         return 0;
2541 }
2542
2543 static int nfs4_show_deleg(struct seq_file *s, struct nfs4_stid *st)
2544 {
2545         struct nfs4_delegation *ds;
2546         struct nfs4_file *nf;
2547         struct nfsd_file *file;
2548
2549         ds = delegstateid(st);
2550         nf = st->sc_file;
2551         file = find_deleg_file(nf);
2552         if (!file)
2553                 return 0;
2554
2555         seq_printf(s, "- ");
2556         nfs4_show_stateid(s, &st->sc_stateid);
2557         seq_printf(s, ": { type: deleg, ");
2558
2559         /* Kinda dead code as long as we only support read delegs: */
2560         seq_printf(s, "access: %s, ",
2561                 ds->dl_type == NFS4_OPEN_DELEGATE_READ ? "r" : "w");
2562
2563         /* XXX: lease time, whether it's being recalled. */
2564
2565         nfs4_show_superblock(s, file);
2566         seq_printf(s, ", ");
2567         nfs4_show_fname(s, file);
2568         seq_printf(s, " }\n");
2569         nfsd_file_put(file);
2570
2571         return 0;
2572 }
2573
2574 static int nfs4_show_layout(struct seq_file *s, struct nfs4_stid *st)
2575 {
2576         struct nfs4_layout_stateid *ls;
2577         struct nfsd_file *file;
2578
2579         ls = container_of(st, struct nfs4_layout_stateid, ls_stid);
2580         file = ls->ls_file;
2581
2582         seq_printf(s, "- ");
2583         nfs4_show_stateid(s, &st->sc_stateid);
2584         seq_printf(s, ": { type: layout, ");
2585
2586         /* XXX: What else would be useful? */
2587
2588         nfs4_show_superblock(s, file);
2589         seq_printf(s, ", ");
2590         nfs4_show_fname(s, file);
2591         seq_printf(s, " }\n");
2592
2593         return 0;
2594 }
2595
2596 static int states_show(struct seq_file *s, void *v)
2597 {
2598         struct nfs4_stid *st = v;
2599
2600         switch (st->sc_type) {
2601         case NFS4_OPEN_STID:
2602                 return nfs4_show_open(s, st);
2603         case NFS4_LOCK_STID:
2604                 return nfs4_show_lock(s, st);
2605         case NFS4_DELEG_STID:
2606                 return nfs4_show_deleg(s, st);
2607         case NFS4_LAYOUT_STID:
2608                 return nfs4_show_layout(s, st);
2609         default:
2610                 return 0; /* XXX: or SEQ_SKIP? */
2611         }
2612         /* XXX: copy stateids? */
2613 }
2614
2615 static struct seq_operations states_seq_ops = {
2616         .start = states_start,
2617         .next = states_next,
2618         .stop = states_stop,
2619         .show = states_show
2620 };
2621
2622 static int client_states_open(struct inode *inode, struct file *file)
2623 {
2624         struct seq_file *s;
2625         struct nfs4_client *clp;
2626         int ret;
2627
2628         clp = get_nfsdfs_clp(inode);
2629         if (!clp)
2630                 return -ENXIO;
2631
2632         ret = seq_open(file, &states_seq_ops);
2633         if (ret)
2634                 return ret;
2635         s = file->private_data;
2636         s->private = clp;
2637         return 0;
2638 }
2639
2640 static int client_opens_release(struct inode *inode, struct file *file)
2641 {
2642         struct seq_file *m = file->private_data;
2643         struct nfs4_client *clp = m->private;
2644
2645         /* XXX: alternatively, we could get/drop in seq start/stop */
2646         drop_client(clp);
2647         return 0;
2648 }
2649
2650 static const struct file_operations client_states_fops = {
2651         .open           = client_states_open,
2652         .read           = seq_read,
2653         .llseek         = seq_lseek,
2654         .release        = client_opens_release,
2655 };
2656
2657 /*
2658  * Normally we refuse to destroy clients that are in use, but here the
2659  * administrator is telling us to just do it.  We also want to wait
2660  * so the caller has a guarantee that the client's locks are gone by
2661  * the time the write returns:
2662  */
2663 static void force_expire_client(struct nfs4_client *clp)
2664 {
2665         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
2666         bool already_expired;
2667
2668         spin_lock(&clp->cl_lock);
2669         clp->cl_time = 0;
2670         spin_unlock(&clp->cl_lock);
2671
2672         wait_event(expiry_wq, atomic_read(&clp->cl_rpc_users) == 0);
2673         spin_lock(&nn->client_lock);
2674         already_expired = list_empty(&clp->cl_lru);
2675         if (!already_expired)
2676                 unhash_client_locked(clp);
2677         spin_unlock(&nn->client_lock);
2678
2679         if (!already_expired)
2680                 expire_client(clp);
2681         else
2682                 wait_event(expiry_wq, clp->cl_nfsd_dentry == NULL);
2683 }
2684
2685 static ssize_t client_ctl_write(struct file *file, const char __user *buf,
2686                                    size_t size, loff_t *pos)
2687 {
2688         char *data;
2689         struct nfs4_client *clp;
2690
2691         data = simple_transaction_get(file, buf, size);
2692         if (IS_ERR(data))
2693                 return PTR_ERR(data);
2694         if (size != 7 || 0 != memcmp(data, "expire\n", 7))
2695                 return -EINVAL;
2696         clp = get_nfsdfs_clp(file_inode(file));
2697         if (!clp)
2698                 return -ENXIO;
2699         force_expire_client(clp);
2700         drop_client(clp);
2701         return 7;
2702 }
2703
2704 static const struct file_operations client_ctl_fops = {
2705         .write          = client_ctl_write,
2706         .release        = simple_transaction_release,
2707 };
2708
2709 static const struct tree_descr client_files[] = {
2710         [0] = {"info", &client_info_fops, S_IRUSR},
2711         [1] = {"states", &client_states_fops, S_IRUSR},
2712         [2] = {"ctl", &client_ctl_fops, S_IWUSR},
2713         [3] = {""},
2714 };
2715
2716 static struct nfs4_client *create_client(struct xdr_netobj name,
2717                 struct svc_rqst *rqstp, nfs4_verifier *verf)
2718 {
2719         struct nfs4_client *clp;
2720         struct sockaddr *sa = svc_addr(rqstp);
2721         int ret;
2722         struct net *net = SVC_NET(rqstp);
2723         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
2724         struct dentry *dentries[ARRAY_SIZE(client_files)];
2725
2726         clp = alloc_client(name);
2727         if (clp == NULL)
2728                 return NULL;
2729
2730         ret = copy_cred(&clp->cl_cred, &rqstp->rq_cred);
2731         if (ret) {
2732                 free_client(clp);
2733                 return NULL;
2734         }
2735         gen_clid(clp, nn);
2736         kref_init(&clp->cl_nfsdfs.cl_ref);
2737         nfsd4_init_cb(&clp->cl_cb_null, clp, NULL, NFSPROC4_CLNT_CB_NULL);
2738         clp->cl_time = ktime_get_boottime_seconds();
2739         clear_bit(0, &clp->cl_cb_slot_busy);
2740         copy_verf(clp, verf);
2741         memcpy(&clp->cl_addr, sa, sizeof(struct sockaddr_storage));
2742         clp->cl_cb_session = NULL;
2743         clp->net = net;
2744         clp->cl_nfsd_dentry = nfsd_client_mkdir(
2745                 nn, &clp->cl_nfsdfs,
2746                 clp->cl_clientid.cl_id - nn->clientid_base,
2747                 client_files, dentries);
2748         clp->cl_nfsd_info_dentry = dentries[0];
2749         if (!clp->cl_nfsd_dentry) {
2750                 free_client(clp);
2751                 return NULL;
2752         }
2753         return clp;
2754 }
2755
2756 static void
2757 add_clp_to_name_tree(struct nfs4_client *new_clp, struct rb_root *root)
2758 {
2759         struct rb_node **new = &(root->rb_node), *parent = NULL;
2760         struct nfs4_client *clp;
2761
2762         while (*new) {
2763                 clp = rb_entry(*new, struct nfs4_client, cl_namenode);
2764                 parent = *new;
2765
2766                 if (compare_blob(&clp->cl_name, &new_clp->cl_name) > 0)
2767                         new = &((*new)->rb_left);
2768                 else
2769                         new = &((*new)->rb_right);
2770         }
2771
2772         rb_link_node(&new_clp->cl_namenode, parent, new);
2773         rb_insert_color(&new_clp->cl_namenode, root);
2774 }
2775
2776 static struct nfs4_client *
2777 find_clp_in_name_tree(struct xdr_netobj *name, struct rb_root *root)
2778 {
2779         int cmp;
2780         struct rb_node *node = root->rb_node;
2781         struct nfs4_client *clp;
2782
2783         while (node) {
2784                 clp = rb_entry(node, struct nfs4_client, cl_namenode);
2785                 cmp = compare_blob(&clp->cl_name, name);
2786                 if (cmp > 0)
2787                         node = node->rb_left;
2788                 else if (cmp < 0)
2789                         node = node->rb_right;
2790                 else
2791                         return clp;
2792         }
2793         return NULL;
2794 }
2795
2796 static void
2797 add_to_unconfirmed(struct nfs4_client *clp)
2798 {
2799         unsigned int idhashval;
2800         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
2801
2802         lockdep_assert_held(&nn->client_lock);
2803
2804         clear_bit(NFSD4_CLIENT_CONFIRMED, &clp->cl_flags);
2805         add_clp_to_name_tree(clp, &nn->unconf_name_tree);
2806         idhashval = clientid_hashval(clp->cl_clientid.cl_id);
2807         list_add(&clp->cl_idhash, &nn->unconf_id_hashtbl[idhashval]);
2808         renew_client_locked(clp);
2809 }
2810
2811 static void
2812 move_to_confirmed(struct nfs4_client *clp)
2813 {
2814         unsigned int idhashval = clientid_hashval(clp->cl_clientid.cl_id);
2815         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
2816
2817         lockdep_assert_held(&nn->client_lock);
2818
2819         list_move(&clp->cl_idhash, &nn->conf_id_hashtbl[idhashval]);
2820         rb_erase(&clp->cl_namenode, &nn->unconf_name_tree);
2821         add_clp_to_name_tree(clp, &nn->conf_name_tree);
2822         set_bit(NFSD4_CLIENT_CONFIRMED, &clp->cl_flags);
2823         trace_nfsd_clid_confirmed(&clp->cl_clientid);
2824         renew_client_locked(clp);
2825 }
2826
2827 static struct nfs4_client *
2828 find_client_in_id_table(struct list_head *tbl, clientid_t *clid, bool sessions)
2829 {
2830         struct nfs4_client *clp;
2831         unsigned int idhashval = clientid_hashval(clid->cl_id);
2832
2833         list_for_each_entry(clp, &tbl[idhashval], cl_idhash) {
2834                 if (same_clid(&clp->cl_clientid, clid)) {
2835                         if ((bool)clp->cl_minorversion != sessions)
2836                                 return NULL;
2837                         renew_client_locked(clp);
2838                         return clp;
2839                 }
2840         }
2841         return NULL;
2842 }
2843
2844 static struct nfs4_client *
2845 find_confirmed_client(clientid_t *clid, bool sessions, struct nfsd_net *nn)
2846 {
2847         struct list_head *tbl = nn->conf_id_hashtbl;
2848
2849         lockdep_assert_held(&nn->client_lock);
2850         return find_client_in_id_table(tbl, clid, sessions);
2851 }
2852
2853 static struct nfs4_client *
2854 find_unconfirmed_client(clientid_t *clid, bool sessions, struct nfsd_net *nn)
2855 {
2856         struct list_head *tbl = nn->unconf_id_hashtbl;
2857
2858         lockdep_assert_held(&nn->client_lock);
2859         return find_client_in_id_table(tbl, clid, sessions);
2860 }
2861
2862 static bool clp_used_exchangeid(struct nfs4_client *clp)
2863 {
2864         return clp->cl_exchange_flags != 0;
2865
2866
2867 static struct nfs4_client *
2868 find_confirmed_client_by_name(struct xdr_netobj *name, struct nfsd_net *nn)
2869 {
2870         lockdep_assert_held(&nn->client_lock);
2871         return find_clp_in_name_tree(name, &nn->conf_name_tree);
2872 }
2873
2874 static struct nfs4_client *
2875 find_unconfirmed_client_by_name(struct xdr_netobj *name, struct nfsd_net *nn)
2876 {
2877         lockdep_assert_held(&nn->client_lock);
2878         return find_clp_in_name_tree(name, &nn->unconf_name_tree);
2879 }
2880
2881 static void
2882 gen_callback(struct nfs4_client *clp, struct nfsd4_setclientid *se, struct svc_rqst *rqstp)
2883 {
2884         struct nfs4_cb_conn *conn = &clp->cl_cb_conn;
2885         struct sockaddr *sa = svc_addr(rqstp);
2886         u32 scopeid = rpc_get_scope_id(sa);
2887         unsigned short expected_family;
2888
2889         /* Currently, we only support tcp and tcp6 for the callback channel */
2890         if (se->se_callback_netid_len == 3 &&
2891             !memcmp(se->se_callback_netid_val, "tcp", 3))
2892                 expected_family = AF_INET;
2893         else if (se->se_callback_netid_len == 4 &&
2894                  !memcmp(se->se_callback_netid_val, "tcp6", 4))
2895                 expected_family = AF_INET6;
2896         else
2897                 goto out_err;
2898
2899         conn->cb_addrlen = rpc_uaddr2sockaddr(clp->net, se->se_callback_addr_val,
2900                                             se->se_callback_addr_len,
2901                                             (struct sockaddr *)&conn->cb_addr,
2902                                             sizeof(conn->cb_addr));
2903
2904         if (!conn->cb_addrlen || conn->cb_addr.ss_family != expected_family)
2905                 goto out_err;
2906
2907         if (conn->cb_addr.ss_family == AF_INET6)
2908                 ((struct sockaddr_in6 *)&conn->cb_addr)->sin6_scope_id = scopeid;
2909
2910         conn->cb_prog = se->se_callback_prog;
2911         conn->cb_ident = se->se_callback_ident;
2912         memcpy(&conn->cb_saddr, &rqstp->rq_daddr, rqstp->rq_daddrlen);
2913         trace_nfsd_cb_args(clp, conn);
2914         return;
2915 out_err:
2916         conn->cb_addr.ss_family = AF_UNSPEC;
2917         conn->cb_addrlen = 0;
2918         trace_nfsd_cb_nodelegs(clp);
2919         return;
2920 }
2921
2922 /*
2923  * Cache a reply. nfsd4_check_resp_size() has bounded the cache size.
2924  */
2925 static void
2926 nfsd4_store_cache_entry(struct nfsd4_compoundres *resp)
2927 {
2928         struct xdr_buf *buf = resp->xdr->buf;
2929         struct nfsd4_slot *slot = resp->cstate.slot;
2930         unsigned int base;
2931
2932         dprintk("--> %s slot %p\n", __func__, slot);
2933
2934         slot->sl_flags |= NFSD4_SLOT_INITIALIZED;
2935         slot->sl_opcnt = resp->opcnt;
2936         slot->sl_status = resp->cstate.status;
2937         free_svc_cred(&slot->sl_cred);
2938         copy_cred(&slot->sl_cred, &resp->rqstp->rq_cred);
2939
2940         if (!nfsd4_cache_this(resp)) {
2941                 slot->sl_flags &= ~NFSD4_SLOT_CACHED;
2942                 return;
2943         }
2944         slot->sl_flags |= NFSD4_SLOT_CACHED;
2945
2946         base = resp->cstate.data_offset;
2947         slot->sl_datalen = buf->len - base;
2948         if (read_bytes_from_xdr_buf(buf, base, slot->sl_data, slot->sl_datalen))
2949                 WARN(1, "%s: sessions DRC could not cache compound\n",
2950                      __func__);
2951         return;
2952 }
2953
2954 /*
2955  * Encode the replay sequence operation from the slot values.
2956  * If cachethis is FALSE encode the uncached rep error on the next
2957  * operation which sets resp->p and increments resp->opcnt for
2958  * nfs4svc_encode_compoundres.
2959  *
2960  */
2961 static __be32
2962 nfsd4_enc_sequence_replay(struct nfsd4_compoundargs *args,
2963                           struct nfsd4_compoundres *resp)
2964 {
2965         struct nfsd4_op *op;
2966         struct nfsd4_slot *slot = resp->cstate.slot;
2967
2968         /* Encode the replayed sequence operation */
2969         op = &args->ops[resp->opcnt - 1];
2970         nfsd4_encode_operation(resp, op);
2971
2972         if (slot->sl_flags & NFSD4_SLOT_CACHED)
2973                 return op->status;
2974         if (args->opcnt == 1) {
2975                 /*
2976                  * The original operation wasn't a solo sequence--we
2977                  * always cache those--so this retry must not match the
2978                  * original:
2979                  */
2980                 op->status = nfserr_seq_false_retry;
2981         } else {
2982                 op = &args->ops[resp->opcnt++];
2983                 op->status = nfserr_retry_uncached_rep;
2984                 nfsd4_encode_operation(resp, op);
2985         }
2986         return op->status;
2987 }
2988
2989 /*
2990  * The sequence operation is not cached because we can use the slot and
2991  * session values.
2992  */
2993 static __be32
2994 nfsd4_replay_cache_entry(struct nfsd4_compoundres *resp,
2995                          struct nfsd4_sequence *seq)
2996 {
2997         struct nfsd4_slot *slot = resp->cstate.slot;
2998         struct xdr_stream *xdr = resp->xdr;
2999         __be32 *p;
3000         __be32 status;
3001
3002         dprintk("--> %s slot %p\n", __func__, slot);
3003
3004         status = nfsd4_enc_sequence_replay(resp->rqstp->rq_argp, resp);
3005         if (status)
3006                 return status;
3007
3008         p = xdr_reserve_space(xdr, slot->sl_datalen);
3009         if (!p) {
3010                 WARN_ON_ONCE(1);
3011                 return nfserr_serverfault;
3012         }
3013         xdr_encode_opaque_fixed(p, slot->sl_data, slot->sl_datalen);
3014         xdr_commit_encode(xdr);
3015
3016         resp->opcnt = slot->sl_opcnt;
3017         return slot->sl_status;
3018 }
3019
3020 /*
3021  * Set the exchange_id flags returned by the server.
3022  */
3023 static void
3024 nfsd4_set_ex_flags(struct nfs4_client *new, struct nfsd4_exchange_id *clid)
3025 {
3026 #ifdef CONFIG_NFSD_PNFS
3027         new->cl_exchange_flags |= EXCHGID4_FLAG_USE_PNFS_MDS;
3028 #else
3029         new->cl_exchange_flags |= EXCHGID4_FLAG_USE_NON_PNFS;
3030 #endif
3031
3032         /* Referrals are supported, Migration is not. */
3033         new->cl_exchange_flags |= EXCHGID4_FLAG_SUPP_MOVED_REFER;
3034
3035         /* set the wire flags to return to client. */
3036         clid->flags = new->cl_exchange_flags;
3037 }
3038
3039 static bool client_has_openowners(struct nfs4_client *clp)
3040 {
3041         struct nfs4_openowner *oo;
3042
3043         list_for_each_entry(oo, &clp->cl_openowners, oo_perclient) {
3044                 if (!list_empty(&oo->oo_owner.so_stateids))
3045                         return true;
3046         }
3047         return false;
3048 }
3049
3050 static bool client_has_state(struct nfs4_client *clp)
3051 {
3052         return client_has_openowners(clp)
3053 #ifdef CONFIG_NFSD_PNFS
3054                 || !list_empty(&clp->cl_lo_states)
3055 #endif
3056                 || !list_empty(&clp->cl_delegations)
3057                 || !list_empty(&clp->cl_sessions)
3058                 || !list_empty(&clp->async_copies);
3059 }
3060
3061 static __be32 copy_impl_id(struct nfs4_client *clp,
3062                                 struct nfsd4_exchange_id *exid)
3063 {
3064         if (!exid->nii_domain.data)
3065                 return 0;
3066         xdr_netobj_dup(&clp->cl_nii_domain, &exid->nii_domain, GFP_KERNEL);
3067         if (!clp->cl_nii_domain.data)
3068                 return nfserr_jukebox;
3069         xdr_netobj_dup(&clp->cl_nii_name, &exid->nii_name, GFP_KERNEL);
3070         if (!clp->cl_nii_name.data)
3071                 return nfserr_jukebox;
3072         clp->cl_nii_time = exid->nii_time;
3073         return 0;
3074 }
3075
3076 __be32
3077 nfsd4_exchange_id(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3078                 union nfsd4_op_u *u)
3079 {
3080         struct nfsd4_exchange_id *exid = &u->exchange_id;
3081         struct nfs4_client *conf, *new;
3082         struct nfs4_client *unconf = NULL;
3083         __be32 status;
3084         char                    addr_str[INET6_ADDRSTRLEN];
3085         nfs4_verifier           verf = exid->verifier;
3086         struct sockaddr         *sa = svc_addr(rqstp);
3087         bool    update = exid->flags & EXCHGID4_FLAG_UPD_CONFIRMED_REC_A;
3088         struct nfsd_net         *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
3089
3090         rpc_ntop(sa, addr_str, sizeof(addr_str));
3091         dprintk("%s rqstp=%p exid=%p clname.len=%u clname.data=%p "
3092                 "ip_addr=%s flags %x, spa_how %u\n",
3093                 __func__, rqstp, exid, exid->clname.len, exid->clname.data,
3094                 addr_str, exid->flags, exid->spa_how);
3095
3096         if (exid->flags & ~EXCHGID4_FLAG_MASK_A)
3097                 return nfserr_inval;
3098
3099         new = create_client(exid->clname, rqstp, &verf);
3100         if (new == NULL)
3101                 return nfserr_jukebox;
3102         status = copy_impl_id(new, exid);
3103         if (status)
3104                 goto out_nolock;
3105
3106         switch (exid->spa_how) {
3107         case SP4_MACH_CRED:
3108                 exid->spo_must_enforce[0] = 0;
3109                 exid->spo_must_enforce[1] = (
3110                         1 << (OP_BIND_CONN_TO_SESSION - 32) |
3111                         1 << (OP_EXCHANGE_ID - 32) |
3112                         1 << (OP_CREATE_SESSION - 32) |
3113                         1 << (OP_DESTROY_SESSION - 32) |
3114                         1 << (OP_DESTROY_CLIENTID - 32));
3115
3116                 exid->spo_must_allow[0] &= (1 << (OP_CLOSE) |
3117                                         1 << (OP_OPEN_DOWNGRADE) |
3118                                         1 << (OP_LOCKU) |
3119                                         1 << (OP_DELEGRETURN));
3120
3121                 exid->spo_must_allow[1] &= (
3122                                         1 << (OP_TEST_STATEID - 32) |
3123                                         1 << (OP_FREE_STATEID - 32));
3124                 if (!svc_rqst_integrity_protected(rqstp)) {
3125                         status = nfserr_inval;
3126                         goto out_nolock;
3127                 }
3128                 /*
3129                  * Sometimes userspace doesn't give us a principal.
3130                  * Which is a bug, really.  Anyway, we can't enforce
3131                  * MACH_CRED in that case, better to give up now:
3132                  */
3133                 if (!new->cl_cred.cr_principal &&
3134                                         !new->cl_cred.cr_raw_principal) {
3135                         status = nfserr_serverfault;
3136                         goto out_nolock;
3137                 }
3138                 new->cl_mach_cred = true;
3139                 break;
3140         case SP4_NONE:
3141                 break;
3142         default:                                /* checked by xdr code */
3143                 WARN_ON_ONCE(1);
3144                 fallthrough;
3145         case SP4_SSV:
3146                 status = nfserr_encr_alg_unsupp;
3147                 goto out_nolock;
3148         }
3149
3150         /* Cases below refer to rfc 5661 section 18.35.4: */
3151         spin_lock(&nn->client_lock);
3152         conf = find_confirmed_client_by_name(&exid->clname, nn);
3153         if (conf) {
3154                 bool creds_match = same_creds(&conf->cl_cred, &rqstp->rq_cred);
3155                 bool verfs_match = same_verf(&verf, &conf->cl_verifier);
3156
3157                 if (update) {
3158                         if (!clp_used_exchangeid(conf)) { /* buggy client */
3159                                 status = nfserr_inval;
3160                                 goto out;
3161                         }
3162                         if (!nfsd4_mach_creds_match(conf, rqstp)) {
3163                                 status = nfserr_wrong_cred;
3164                                 goto out;
3165                         }
3166                         if (!creds_match) { /* case 9 */
3167                                 status = nfserr_perm;
3168                                 goto out;
3169                         }
3170                         if (!verfs_match) { /* case 8 */
3171                                 status = nfserr_not_same;
3172                                 goto out;
3173                         }
3174                         /* case 6 */
3175                         exid->flags |= EXCHGID4_FLAG_CONFIRMED_R;
3176                         goto out_copy;
3177                 }
3178                 if (!creds_match) { /* case 3 */
3179                         if (client_has_state(conf)) {
3180                                 status = nfserr_clid_inuse;
3181                                 goto out;
3182                         }
3183                         goto out_new;
3184                 }
3185                 if (verfs_match) { /* case 2 */
3186                         conf->cl_exchange_flags |= EXCHGID4_FLAG_CONFIRMED_R;
3187                         goto out_copy;
3188                 }
3189                 /* case 5, client reboot */
3190                 conf = NULL;
3191                 goto out_new;
3192         }
3193
3194         if (update) { /* case 7 */
3195                 status = nfserr_noent;
3196                 goto out;
3197         }
3198
3199         unconf  = find_unconfirmed_client_by_name(&exid->clname, nn);
3200         if (unconf) /* case 4, possible retry or client restart */
3201                 unhash_client_locked(unconf);
3202
3203         /* case 1 (normal case) */
3204 out_new:
3205         if (conf) {
3206                 status = mark_client_expired_locked(conf);
3207                 if (status)
3208                         goto out;
3209         }
3210         new->cl_minorversion = cstate->minorversion;
3211         new->cl_spo_must_allow.u.words[0] = exid->spo_must_allow[0];
3212         new->cl_spo_must_allow.u.words[1] = exid->spo_must_allow[1];
3213
3214         add_to_unconfirmed(new);
3215         swap(new, conf);
3216 out_copy:
3217         exid->clientid.cl_boot = conf->cl_clientid.cl_boot;
3218         exid->clientid.cl_id = conf->cl_clientid.cl_id;
3219
3220         exid->seqid = conf->cl_cs_slot.sl_seqid + 1;
3221         nfsd4_set_ex_flags(conf, exid);
3222
3223         dprintk("nfsd4_exchange_id seqid %d flags %x\n",
3224                 conf->cl_cs_slot.sl_seqid, conf->cl_exchange_flags);
3225         status = nfs_ok;
3226
3227 out:
3228         spin_unlock(&nn->client_lock);
3229 out_nolock:
3230         if (new)
3231                 expire_client(new);
3232         if (unconf)
3233                 expire_client(unconf);
3234         return status;
3235 }
3236
3237 static __be32
3238 check_slot_seqid(u32 seqid, u32 slot_seqid, int slot_inuse)
3239 {
3240         dprintk("%s enter. seqid %d slot_seqid %d\n", __func__, seqid,
3241                 slot_seqid);
3242
3243         /* The slot is in use, and no response has been sent. */
3244         if (slot_inuse) {
3245                 if (seqid == slot_seqid)
3246                         return nfserr_jukebox;
3247                 else
3248                         return nfserr_seq_misordered;
3249         }
3250         /* Note unsigned 32-bit arithmetic handles wraparound: */
3251         if (likely(seqid == slot_seqid + 1))
3252                 return nfs_ok;
3253         if (seqid == slot_seqid)
3254                 return nfserr_replay_cache;
3255         return nfserr_seq_misordered;
3256 }
3257
3258 /*
3259  * Cache the create session result into the create session single DRC
3260  * slot cache by saving the xdr structure. sl_seqid has been set.
3261  * Do this for solo or embedded create session operations.
3262  */
3263 static void
3264 nfsd4_cache_create_session(struct nfsd4_create_session *cr_ses,
3265                            struct nfsd4_clid_slot *slot, __be32 nfserr)
3266 {
3267         slot->sl_status = nfserr;
3268         memcpy(&slot->sl_cr_ses, cr_ses, sizeof(*cr_ses));
3269 }
3270
3271 static __be32
3272 nfsd4_replay_create_session(struct nfsd4_create_session *cr_ses,
3273                             struct nfsd4_clid_slot *slot)
3274 {
3275         memcpy(cr_ses, &slot->sl_cr_ses, sizeof(*cr_ses));
3276         return slot->sl_status;
3277 }
3278
3279 #define NFSD_MIN_REQ_HDR_SEQ_SZ ((\
3280                         2 * 2 + /* credential,verifier: AUTH_NULL, length 0 */ \
3281                         1 +     /* MIN tag is length with zero, only length */ \
3282                         3 +     /* version, opcount, opcode */ \
3283                         XDR_QUADLEN(NFS4_MAX_SESSIONID_LEN) + \
3284                                 /* seqid, slotID, slotID, cache */ \
3285                         4 ) * sizeof(__be32))
3286
3287 #define NFSD_MIN_RESP_HDR_SEQ_SZ ((\
3288                         2 +     /* verifier: AUTH_NULL, length 0 */\
3289                         1 +     /* status */ \
3290                         1 +     /* MIN tag is length with zero, only length */ \
3291                         3 +     /* opcount, opcode, opstatus*/ \
3292                         XDR_QUADLEN(NFS4_MAX_SESSIONID_LEN) + \
3293                                 /* seqid, slotID, slotID, slotID, status */ \
3294                         5 ) * sizeof(__be32))
3295
3296 static __be32 check_forechannel_attrs(struct nfsd4_channel_attrs *ca, struct nfsd_net *nn)
3297 {
3298         u32 maxrpc = nn->nfsd_serv->sv_max_mesg;
3299
3300         if (ca->maxreq_sz < NFSD_MIN_REQ_HDR_SEQ_SZ)
3301                 return nfserr_toosmall;
3302         if (ca->maxresp_sz < NFSD_MIN_RESP_HDR_SEQ_SZ)
3303                 return nfserr_toosmall;
3304         ca->headerpadsz = 0;
3305         ca->maxreq_sz = min_t(u32, ca->maxreq_sz, maxrpc);
3306         ca->maxresp_sz = min_t(u32, ca->maxresp_sz, maxrpc);
3307         ca->maxops = min_t(u32, ca->maxops, NFSD_MAX_OPS_PER_COMPOUND);
3308         ca->maxresp_cached = min_t(u32, ca->maxresp_cached,
3309                         NFSD_SLOT_CACHE_SIZE + NFSD_MIN_HDR_SEQ_SZ);
3310         ca->maxreqs = min_t(u32, ca->maxreqs, NFSD_MAX_SLOTS_PER_SESSION);
3311         /*
3312          * Note decreasing slot size below client's request may make it
3313          * difficult for client to function correctly, whereas
3314          * decreasing the number of slots will (just?) affect
3315          * performance.  When short on memory we therefore prefer to
3316          * decrease number of slots instead of their size.  Clients that
3317          * request larger slots than they need will get poor results:
3318          * Note that we always allow at least one slot, because our
3319          * accounting is soft and provides no guarantees either way.
3320          */
3321         ca->maxreqs = nfsd4_get_drc_mem(ca, nn);
3322
3323         return nfs_ok;
3324 }
3325
3326 /*
3327  * Server's NFSv4.1 backchannel support is AUTH_SYS-only for now.
3328  * These are based on similar macros in linux/sunrpc/msg_prot.h .
3329  */
3330 #define RPC_MAX_HEADER_WITH_AUTH_SYS \
3331         (RPC_CALLHDRSIZE + 2 * (2 + UNX_CALLSLACK))
3332
3333 #define RPC_MAX_REPHEADER_WITH_AUTH_SYS \
3334         (RPC_REPHDRSIZE + (2 + NUL_REPLYSLACK))
3335
3336 #define NFSD_CB_MAX_REQ_SZ      ((NFS4_enc_cb_recall_sz + \
3337                                  RPC_MAX_HEADER_WITH_AUTH_SYS) * sizeof(__be32))
3338 #define NFSD_CB_MAX_RESP_SZ     ((NFS4_dec_cb_recall_sz + \
3339                                  RPC_MAX_REPHEADER_WITH_AUTH_SYS) * \
3340                                  sizeof(__be32))
3341
3342 static __be32 check_backchannel_attrs(struct nfsd4_channel_attrs *ca)
3343 {
3344         ca->headerpadsz = 0;
3345
3346         if (ca->maxreq_sz < NFSD_CB_MAX_REQ_SZ)
3347                 return nfserr_toosmall;
3348         if (ca->maxresp_sz < NFSD_CB_MAX_RESP_SZ)
3349                 return nfserr_toosmall;
3350         ca->maxresp_cached = 0;
3351         if (ca->maxops < 2)
3352                 return nfserr_toosmall;
3353
3354         return nfs_ok;
3355 }
3356
3357 static __be32 nfsd4_check_cb_sec(struct nfsd4_cb_sec *cbs)
3358 {
3359         switch (cbs->flavor) {
3360         case RPC_AUTH_NULL:
3361         case RPC_AUTH_UNIX:
3362                 return nfs_ok;
3363         default:
3364                 /*
3365                  * GSS case: the spec doesn't allow us to return this
3366                  * error.  But it also doesn't allow us not to support
3367                  * GSS.
3368                  * I'd rather this fail hard than return some error the
3369                  * client might think it can already handle:
3370                  */
3371                 return nfserr_encr_alg_unsupp;
3372         }
3373 }
3374
3375 __be32
3376 nfsd4_create_session(struct svc_rqst *rqstp,
3377                 struct nfsd4_compound_state *cstate, union nfsd4_op_u *u)
3378 {
3379         struct nfsd4_create_session *cr_ses = &u->create_session;
3380         struct sockaddr *sa = svc_addr(rqstp);
3381         struct nfs4_client *conf, *unconf;
3382         struct nfs4_client *old = NULL;
3383         struct nfsd4_session *new;
3384         struct nfsd4_conn *conn;
3385         struct nfsd4_clid_slot *cs_slot = NULL;
3386         __be32 status = 0;
3387         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
3388
3389         if (cr_ses->flags & ~SESSION4_FLAG_MASK_A)
3390                 return nfserr_inval;
3391         status = nfsd4_check_cb_sec(&cr_ses->cb_sec);
3392         if (status)
3393                 return status;
3394         status = check_forechannel_attrs(&cr_ses->fore_channel, nn);
3395         if (status)
3396                 return status;
3397         status = check_backchannel_attrs(&cr_ses->back_channel);
3398         if (status)
3399                 goto out_release_drc_mem;
3400         status = nfserr_jukebox;
3401         new = alloc_session(&cr_ses->fore_channel, &cr_ses->back_channel);
3402         if (!new)
3403                 goto out_release_drc_mem;
3404         conn = alloc_conn_from_crses(rqstp, cr_ses);
3405         if (!conn)
3406                 goto out_free_session;
3407
3408         spin_lock(&nn->client_lock);
3409         unconf = find_unconfirmed_client(&cr_ses->clientid, true, nn);
3410         conf = find_confirmed_client(&cr_ses->clientid, true, nn);
3411         WARN_ON_ONCE(conf && unconf);
3412
3413         if (conf) {
3414                 status = nfserr_wrong_cred;
3415                 if (!nfsd4_mach_creds_match(conf, rqstp))
3416                         goto out_free_conn;
3417                 cs_slot = &conf->cl_cs_slot;
3418                 status = check_slot_seqid(cr_ses->seqid, cs_slot->sl_seqid, 0);
3419                 if (status) {
3420                         if (status == nfserr_replay_cache)
3421                                 status = nfsd4_replay_create_session(cr_ses, cs_slot);
3422                         goto out_free_conn;
3423                 }
3424         } else if (unconf) {
3425                 if (!same_creds(&unconf->cl_cred, &rqstp->rq_cred) ||
3426                     !rpc_cmp_addr(sa, (struct sockaddr *) &unconf->cl_addr)) {
3427                         status = nfserr_clid_inuse;
3428                         goto out_free_conn;
3429                 }
3430                 status = nfserr_wrong_cred;
3431                 if (!nfsd4_mach_creds_match(unconf, rqstp))
3432                         goto out_free_conn;
3433                 cs_slot = &unconf->cl_cs_slot;
3434                 status = check_slot_seqid(cr_ses->seqid, cs_slot->sl_seqid, 0);
3435                 if (status) {
3436                         /* an unconfirmed replay returns misordered */
3437                         status = nfserr_seq_misordered;
3438                         goto out_free_conn;
3439                 }
3440                 old = find_confirmed_client_by_name(&unconf->cl_name, nn);
3441                 if (old) {
3442                         status = mark_client_expired_locked(old);
3443                         if (status) {
3444                                 old = NULL;
3445                                 goto out_free_conn;
3446                         }
3447                 }
3448                 move_to_confirmed(unconf);
3449                 conf = unconf;
3450         } else {
3451                 status = nfserr_stale_clientid;
3452                 goto out_free_conn;
3453         }
3454         status = nfs_ok;
3455         /* Persistent sessions are not supported */
3456         cr_ses->flags &= ~SESSION4_PERSIST;
3457         /* Upshifting from TCP to RDMA is not supported */
3458         cr_ses->flags &= ~SESSION4_RDMA;
3459
3460         init_session(rqstp, new, conf, cr_ses);
3461         nfsd4_get_session_locked(new);
3462
3463         memcpy(cr_ses->sessionid.data, new->se_sessionid.data,
3464                NFS4_MAX_SESSIONID_LEN);
3465         cs_slot->sl_seqid++;
3466         cr_ses->seqid = cs_slot->sl_seqid;
3467
3468         /* cache solo and embedded create sessions under the client_lock */
3469         nfsd4_cache_create_session(cr_ses, cs_slot, status);
3470         spin_unlock(&nn->client_lock);
3471         if (conf == unconf)
3472                 fsnotify_dentry(conf->cl_nfsd_info_dentry, FS_MODIFY);
3473         /* init connection and backchannel */
3474         nfsd4_init_conn(rqstp, conn, new);
3475         nfsd4_put_session(new);
3476         if (old)
3477                 expire_client(old);
3478         return status;
3479 out_free_conn:
3480         spin_unlock(&nn->client_lock);
3481         free_conn(conn);
3482         if (old)
3483                 expire_client(old);
3484 out_free_session:
3485         __free_session(new);
3486 out_release_drc_mem:
3487         nfsd4_put_drc_mem(&cr_ses->fore_channel);
3488         return status;
3489 }
3490
3491 static __be32 nfsd4_map_bcts_dir(u32 *dir)
3492 {
3493         switch (*dir) {
3494         case NFS4_CDFC4_FORE:
3495         case NFS4_CDFC4_BACK:
3496                 return nfs_ok;
3497         case NFS4_CDFC4_FORE_OR_BOTH:
3498         case NFS4_CDFC4_BACK_OR_BOTH:
3499                 *dir = NFS4_CDFC4_BOTH;
3500                 return nfs_ok;
3501         }
3502         return nfserr_inval;
3503 }
3504
3505 __be32 nfsd4_backchannel_ctl(struct svc_rqst *rqstp,
3506                 struct nfsd4_compound_state *cstate,
3507                 union nfsd4_op_u *u)
3508 {
3509         struct nfsd4_backchannel_ctl *bc = &u->backchannel_ctl;
3510         struct nfsd4_session *session = cstate->session;
3511         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
3512         __be32 status;
3513
3514         status = nfsd4_check_cb_sec(&bc->bc_cb_sec);
3515         if (status)
3516                 return status;
3517         spin_lock(&nn->client_lock);
3518         session->se_cb_prog = bc->bc_cb_program;
3519         session->se_cb_sec = bc->bc_cb_sec;
3520         spin_unlock(&nn->client_lock);
3521
3522         nfsd4_probe_callback(session->se_client);
3523
3524         return nfs_ok;
3525 }
3526
3527 static struct nfsd4_conn *__nfsd4_find_conn(struct svc_xprt *xpt, struct nfsd4_session *s)
3528 {
3529         struct nfsd4_conn *c;
3530
3531         list_for_each_entry(c, &s->se_conns, cn_persession) {
3532                 if (c->cn_xprt == xpt) {
3533                         return c;
3534                 }
3535         }
3536         return NULL;
3537 }
3538
3539 static __be32 nfsd4_match_existing_connection(struct svc_rqst *rqst,
3540                                 struct nfsd4_session *session, u32 req)
3541 {
3542         struct nfs4_client *clp = session->se_client;
3543         struct svc_xprt *xpt = rqst->rq_xprt;
3544         struct nfsd4_conn *c;
3545         __be32 status;
3546
3547         /* Following the last paragraph of RFC 5661 Section 18.34.3: */
3548         spin_lock(&clp->cl_lock);
3549         c = __nfsd4_find_conn(xpt, session);
3550         if (!c)
3551                 status = nfserr_noent;
3552         else if (req == c->cn_flags)
3553                 status = nfs_ok;
3554         else if (req == NFS4_CDFC4_FORE_OR_BOTH &&
3555                                 c->cn_flags != NFS4_CDFC4_BACK)
3556                 status = nfs_ok;
3557         else if (req == NFS4_CDFC4_BACK_OR_BOTH &&
3558                                 c->cn_flags != NFS4_CDFC4_FORE)
3559                 status = nfs_ok;
3560         else
3561                 status = nfserr_inval;
3562         spin_unlock(&clp->cl_lock);
3563         return status;
3564 }
3565
3566 __be32 nfsd4_bind_conn_to_session(struct svc_rqst *rqstp,
3567                      struct nfsd4_compound_state *cstate,
3568                      union nfsd4_op_u *u)
3569 {
3570         struct nfsd4_bind_conn_to_session *bcts = &u->bind_conn_to_session;
3571         __be32 status;
3572         struct nfsd4_conn *conn;
3573         struct nfsd4_session *session;
3574         struct net *net = SVC_NET(rqstp);
3575         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
3576
3577         if (!nfsd4_last_compound_op(rqstp))
3578                 return nfserr_not_only_op;
3579         spin_lock(&nn->client_lock);
3580         session = find_in_sessionid_hashtbl(&bcts->sessionid, net, &status);
3581         spin_unlock(&nn->client_lock);
3582         if (!session)
3583                 goto out_no_session;
3584         status = nfserr_wrong_cred;
3585         if (!nfsd4_mach_creds_match(session->se_client, rqstp))
3586                 goto out;
3587         status = nfsd4_match_existing_connection(rqstp, session, bcts->dir);
3588         if (status == nfs_ok || status == nfserr_inval)
3589                 goto out;
3590         status = nfsd4_map_bcts_dir(&bcts->dir);
3591         if (status)
3592                 goto out;
3593         conn = alloc_conn(rqstp, bcts->dir);
3594         status = nfserr_jukebox;
3595         if (!conn)
3596                 goto out;
3597         nfsd4_init_conn(rqstp, conn, session);
3598         status = nfs_ok;
3599 out:
3600         nfsd4_put_session(session);
3601 out_no_session:
3602         return status;
3603 }
3604
3605 static bool nfsd4_compound_in_session(struct nfsd4_compound_state *cstate, struct nfs4_sessionid *sid)
3606 {
3607         if (!cstate->session)
3608                 return false;
3609         return !memcmp(sid, &cstate->session->se_sessionid, sizeof(*sid));
3610 }
3611
3612 __be32
3613 nfsd4_destroy_session(struct svc_rqst *r, struct nfsd4_compound_state *cstate,
3614                 union nfsd4_op_u *u)
3615 {
3616         struct nfs4_sessionid *sessionid = &u->destroy_session.sessionid;
3617         struct nfsd4_session *ses;
3618         __be32 status;
3619         int ref_held_by_me = 0;
3620         struct net *net = SVC_NET(r);
3621         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
3622
3623         status = nfserr_not_only_op;
3624         if (nfsd4_compound_in_session(cstate, sessionid)) {
3625                 if (!nfsd4_last_compound_op(r))
3626                         goto out;
3627                 ref_held_by_me++;
3628         }
3629         dump_sessionid(__func__, sessionid);
3630         spin_lock(&nn->client_lock);
3631         ses = find_in_sessionid_hashtbl(sessionid, net, &status);
3632         if (!ses)
3633                 goto out_client_lock;
3634         status = nfserr_wrong_cred;
3635         if (!nfsd4_mach_creds_match(ses->se_client, r))
3636                 goto out_put_session;
3637         status = mark_session_dead_locked(ses, 1 + ref_held_by_me);
3638         if (status)
3639                 goto out_put_session;
3640         unhash_session(ses);
3641         spin_unlock(&nn->client_lock);
3642
3643         nfsd4_probe_callback_sync(ses->se_client);
3644
3645         spin_lock(&nn->client_lock);
3646         status = nfs_ok;
3647 out_put_session:
3648         nfsd4_put_session_locked(ses);
3649 out_client_lock:
3650         spin_unlock(&nn->client_lock);
3651 out:
3652         return status;
3653 }
3654
3655 static __be32 nfsd4_sequence_check_conn(struct nfsd4_conn *new, struct nfsd4_session *ses)
3656 {
3657         struct nfs4_client *clp = ses->se_client;
3658         struct nfsd4_conn *c;
3659         __be32 status = nfs_ok;
3660         int ret;
3661
3662         spin_lock(&clp->cl_lock);
3663         c = __nfsd4_find_conn(new->cn_xprt, ses);
3664         if (c)
3665                 goto out_free;
3666         status = nfserr_conn_not_bound_to_session;
3667         if (clp->cl_mach_cred)
3668                 goto out_free;
3669         __nfsd4_hash_conn(new, ses);
3670         spin_unlock(&clp->cl_lock);
3671         ret = nfsd4_register_conn(new);
3672         if (ret)
3673                 /* oops; xprt is already down: */
3674                 nfsd4_conn_lost(&new->cn_xpt_user);
3675         return nfs_ok;
3676 out_free:
3677         spin_unlock(&clp->cl_lock);
3678         free_conn(new);
3679         return status;
3680 }
3681
3682 static bool nfsd4_session_too_many_ops(struct svc_rqst *rqstp, struct nfsd4_session *session)
3683 {
3684         struct nfsd4_compoundargs *args = rqstp->rq_argp;
3685
3686         return args->opcnt > session->se_fchannel.maxops;
3687 }
3688
3689 static bool nfsd4_request_too_big(struct svc_rqst *rqstp,
3690                                   struct nfsd4_session *session)
3691 {
3692         struct xdr_buf *xb = &rqstp->rq_arg;
3693
3694         return xb->len > session->se_fchannel.maxreq_sz;
3695 }
3696
3697 static bool replay_matches_cache(struct svc_rqst *rqstp,
3698                  struct nfsd4_sequence *seq, struct nfsd4_slot *slot)
3699 {
3700         struct nfsd4_compoundargs *argp = rqstp->rq_argp;
3701
3702         if ((bool)(slot->sl_flags & NFSD4_SLOT_CACHETHIS) !=
3703             (bool)seq->cachethis)
3704                 return false;
3705         /*
3706          * If there's an error then the reply can have fewer ops than
3707          * the call.
3708          */
3709         if (slot->sl_opcnt < argp->opcnt && !slot->sl_status)
3710                 return false;
3711         /*
3712          * But if we cached a reply with *more* ops than the call you're
3713          * sending us now, then this new call is clearly not really a
3714          * replay of the old one:
3715          */
3716         if (slot->sl_opcnt > argp->opcnt)
3717                 return false;
3718         /* This is the only check explicitly called by spec: */
3719         if (!same_creds(&rqstp->rq_cred, &slot->sl_cred))
3720                 return false;
3721         /*
3722          * There may be more comparisons we could actually do, but the
3723          * spec doesn't require us to catch every case where the calls
3724          * don't match (that would require caching the call as well as
3725          * the reply), so we don't bother.
3726          */
3727         return true;
3728 }
3729
3730 __be32
3731 nfsd4_sequence(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3732                 union nfsd4_op_u *u)
3733 {
3734         struct nfsd4_sequence *seq = &u->sequence;
3735         struct nfsd4_compoundres *resp = rqstp->rq_resp;
3736         struct xdr_stream *xdr = resp->xdr;
3737         struct nfsd4_session *session;
3738         struct nfs4_client *clp;
3739         struct nfsd4_slot *slot;
3740         struct nfsd4_conn *conn;
3741         __be32 status;
3742         int buflen;
3743         struct net *net = SVC_NET(rqstp);
3744         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
3745
3746         if (resp->opcnt != 1)
3747                 return nfserr_sequence_pos;
3748
3749         /*
3750          * Will be either used or freed by nfsd4_sequence_check_conn
3751          * below.
3752          */
3753         conn = alloc_conn(rqstp, NFS4_CDFC4_FORE);
3754         if (!conn)
3755                 return nfserr_jukebox;
3756
3757         spin_lock(&nn->client_lock);
3758         session = find_in_sessionid_hashtbl(&seq->sessionid, net, &status);
3759         if (!session)
3760                 goto out_no_session;
3761         clp = session->se_client;
3762
3763         status = nfserr_too_many_ops;
3764         if (nfsd4_session_too_many_ops(rqstp, session))
3765                 goto out_put_session;
3766
3767         status = nfserr_req_too_big;
3768         if (nfsd4_request_too_big(rqstp, session))
3769                 goto out_put_session;
3770
3771         status = nfserr_badslot;
3772         if (seq->slotid >= session->se_fchannel.maxreqs)
3773                 goto out_put_session;
3774
3775         slot = session->se_slots[seq->slotid];
3776         dprintk("%s: slotid %d\n", __func__, seq->slotid);
3777
3778         /* We do not negotiate the number of slots yet, so set the
3779          * maxslots to the session maxreqs which is used to encode
3780          * sr_highest_slotid and the sr_target_slot id to maxslots */
3781         seq->maxslots = session->se_fchannel.maxreqs;
3782
3783         status = check_slot_seqid(seq->seqid, slot->sl_seqid,
3784                                         slot->sl_flags & NFSD4_SLOT_INUSE);
3785         if (status == nfserr_replay_cache) {
3786                 status = nfserr_seq_misordered;
3787                 if (!(slot->sl_flags & NFSD4_SLOT_INITIALIZED))
3788                         goto out_put_session;
3789                 status = nfserr_seq_false_retry;
3790                 if (!replay_matches_cache(rqstp, seq, slot))
3791                         goto out_put_session;
3792                 cstate->slot = slot;
3793                 cstate->session = session;
3794                 cstate->clp = clp;
3795                 /* Return the cached reply status and set cstate->status
3796                  * for nfsd4_proc_compound processing */
3797                 status = nfsd4_replay_cache_entry(resp, seq);
3798                 cstate->status = nfserr_replay_cache;
3799                 goto out;
3800         }
3801         if (status)
3802                 goto out_put_session;
3803
3804         status = nfsd4_sequence_check_conn(conn, session);
3805         conn = NULL;
3806         if (status)
3807                 goto out_put_session;
3808
3809         buflen = (seq->cachethis) ?
3810                         session->se_fchannel.maxresp_cached :
3811                         session->se_fchannel.maxresp_sz;
3812         status = (seq->cachethis) ? nfserr_rep_too_big_to_cache :
3813                                     nfserr_rep_too_big;
3814         if (xdr_restrict_buflen(xdr, buflen - rqstp->rq_auth_slack))
3815                 goto out_put_session;
3816         svc_reserve(rqstp, buflen);
3817
3818         status = nfs_ok;
3819         /* Success! bump slot seqid */
3820         slot->sl_seqid = seq->seqid;
3821         slot->sl_flags |= NFSD4_SLOT_INUSE;
3822         if (seq->cachethis)
3823                 slot->sl_flags |= NFSD4_SLOT_CACHETHIS;
3824         else
3825                 slot->sl_flags &= ~NFSD4_SLOT_CACHETHIS;
3826
3827         cstate->slot = slot;
3828         cstate->session = session;
3829         cstate->clp = clp;
3830
3831 out:
3832         switch (clp->cl_cb_state) {
3833         case NFSD4_CB_DOWN:
3834                 seq->status_flags = SEQ4_STATUS_CB_PATH_DOWN;
3835                 break;
3836         case NFSD4_CB_FAULT:
3837                 seq->status_flags = SEQ4_STATUS_BACKCHANNEL_FAULT;
3838                 break;
3839         default:
3840                 seq->status_flags = 0;
3841         }
3842         if (!list_empty(&clp->cl_revoked))
3843                 seq->status_flags |= SEQ4_STATUS_RECALLABLE_STATE_REVOKED;
3844 out_no_session:
3845         if (conn)
3846                 free_conn(conn);
3847         spin_unlock(&nn->client_lock);
3848         return status;
3849 out_put_session:
3850         nfsd4_put_session_locked(session);
3851         goto out_no_session;
3852 }
3853
3854 void
3855 nfsd4_sequence_done(struct nfsd4_compoundres *resp)
3856 {
3857         struct nfsd4_compound_state *cs = &resp->cstate;
3858
3859         if (nfsd4_has_session(cs)) {
3860                 if (cs->status != nfserr_replay_cache) {
3861                         nfsd4_store_cache_entry(resp);
3862                         cs->slot->sl_flags &= ~NFSD4_SLOT_INUSE;
3863                 }
3864                 /* Drop session reference that was taken in nfsd4_sequence() */
3865                 nfsd4_put_session(cs->session);
3866         } else if (cs->clp)
3867                 put_client_renew(cs->clp);
3868 }
3869
3870 __be32
3871 nfsd4_destroy_clientid(struct svc_rqst *rqstp,
3872                 struct nfsd4_compound_state *cstate,
3873                 union nfsd4_op_u *u)
3874 {
3875         struct nfsd4_destroy_clientid *dc = &u->destroy_clientid;
3876         struct nfs4_client *conf, *unconf;
3877         struct nfs4_client *clp = NULL;
3878         __be32 status = 0;
3879         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
3880
3881         spin_lock(&nn->client_lock);
3882         unconf = find_unconfirmed_client(&dc->clientid, true, nn);
3883         conf = find_confirmed_client(&dc->clientid, true, nn);
3884         WARN_ON_ONCE(conf && unconf);
3885
3886         if (conf) {
3887                 if (client_has_state(conf)) {
3888                         status = nfserr_clientid_busy;
3889                         goto out;
3890                 }
3891                 status = mark_client_expired_locked(conf);
3892                 if (status)
3893                         goto out;
3894                 clp = conf;
3895         } else if (unconf)
3896                 clp = unconf;
3897         else {
3898                 status = nfserr_stale_clientid;
3899                 goto out;
3900         }
3901         if (!nfsd4_mach_creds_match(clp, rqstp)) {
3902                 clp = NULL;
3903                 status = nfserr_wrong_cred;
3904                 goto out;
3905         }
3906         unhash_client_locked(clp);
3907 out:
3908         spin_unlock(&nn->client_lock);
3909         if (clp)
3910                 expire_client(clp);
3911         return status;
3912 }
3913
3914 __be32
3915 nfsd4_reclaim_complete(struct svc_rqst *rqstp,
3916                 struct nfsd4_compound_state *cstate, union nfsd4_op_u *u)
3917 {
3918         struct nfsd4_reclaim_complete *rc = &u->reclaim_complete;
3919         struct nfs4_client *clp = cstate->clp;
3920         __be32 status = 0;
3921
3922         if (rc->rca_one_fs) {
3923                 if (!cstate->current_fh.fh_dentry)
3924                         return nfserr_nofilehandle;
3925                 /*
3926                  * We don't take advantage of the rca_one_fs case.
3927                  * That's OK, it's optional, we can safely ignore it.
3928                  */
3929                 return nfs_ok;
3930         }
3931
3932         status = nfserr_complete_already;
3933         if (test_and_set_bit(NFSD4_CLIENT_RECLAIM_COMPLETE, &clp->cl_flags))
3934                 goto out;
3935
3936         status = nfserr_stale_clientid;
3937         if (is_client_expired(clp))
3938                 /*
3939                  * The following error isn't really legal.
3940                  * But we only get here if the client just explicitly
3941                  * destroyed the client.  Surely it no longer cares what
3942                  * error it gets back on an operation for the dead
3943                  * client.
3944                  */
3945                 goto out;
3946
3947         status = nfs_ok;
3948         nfsd4_client_record_create(clp);
3949         inc_reclaim_complete(clp);
3950 out:
3951         return status;
3952 }
3953
3954 __be32
3955 nfsd4_setclientid(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3956                   union nfsd4_op_u *u)
3957 {
3958         struct nfsd4_setclientid *setclid = &u->setclientid;
3959         struct xdr_netobj       clname = setclid->se_name;
3960         nfs4_verifier           clverifier = setclid->se_verf;
3961         struct nfs4_client      *conf, *new;
3962         struct nfs4_client      *unconf = NULL;
3963         __be32                  status;
3964         struct nfsd_net         *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
3965
3966         new = create_client(clname, rqstp, &clverifier);
3967         if (new == NULL)
3968                 return nfserr_jukebox;
3969         /* Cases below refer to rfc 3530 section 14.2.33: */
3970         spin_lock(&nn->client_lock);
3971         conf = find_confirmed_client_by_name(&clname, nn);
3972         if (conf && client_has_state(conf)) {
3973                 /* case 0: */
3974                 status = nfserr_clid_inuse;
3975                 if (clp_used_exchangeid(conf))
3976                         goto out;
3977                 if (!same_creds(&conf->cl_cred, &rqstp->rq_cred)) {
3978                         trace_nfsd_clid_inuse_err(conf);
3979                         goto out;
3980                 }
3981         }
3982         unconf = find_unconfirmed_client_by_name(&clname, nn);
3983         if (unconf)
3984                 unhash_client_locked(unconf);
3985         /* We need to handle only case 1: probable callback update */
3986         if (conf && same_verf(&conf->cl_verifier, &clverifier)) {
3987                 copy_clid(new, conf);
3988                 gen_confirm(new, nn);
3989         }
3990         new->cl_minorversion = 0;
3991         gen_callback(new, setclid, rqstp);
3992         add_to_unconfirmed(new);
3993         setclid->se_clientid.cl_boot = new->cl_clientid.cl_boot;
3994         setclid->se_clientid.cl_id = new->cl_clientid.cl_id;
3995         memcpy(setclid->se_confirm.data, new->cl_confirm.data, sizeof(setclid->se_confirm.data));
3996         new = NULL;
3997         status = nfs_ok;
3998 out:
3999         spin_unlock(&nn->client_lock);
4000         if (new)
4001                 free_client(new);
4002         if (unconf)
4003                 expire_client(unconf);
4004         return status;
4005 }
4006
4007
4008 __be32
4009 nfsd4_setclientid_confirm(struct svc_rqst *rqstp,
4010                         struct nfsd4_compound_state *cstate,
4011                         union nfsd4_op_u *u)
4012 {
4013         struct nfsd4_setclientid_confirm *setclientid_confirm =
4014                         &u->setclientid_confirm;
4015         struct nfs4_client *conf, *unconf;
4016         struct nfs4_client *old = NULL;
4017         nfs4_verifier confirm = setclientid_confirm->sc_confirm; 
4018         clientid_t * clid = &setclientid_confirm->sc_clientid;
4019         __be32 status;
4020         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
4021
4022         if (STALE_CLIENTID(clid, nn))
4023                 return nfserr_stale_clientid;
4024
4025         spin_lock(&nn->client_lock);
4026         conf = find_confirmed_client(clid, false, nn);
4027         unconf = find_unconfirmed_client(clid, false, nn);
4028         /*
4029          * We try hard to give out unique clientid's, so if we get an
4030          * attempt to confirm the same clientid with a different cred,
4031          * the client may be buggy; this should never happen.
4032          *
4033          * Nevertheless, RFC 7530 recommends INUSE for this case:
4034          */
4035         status = nfserr_clid_inuse;
4036         if (unconf && !same_creds(&unconf->cl_cred, &rqstp->rq_cred))
4037                 goto out;
4038         if (conf && !same_creds(&conf->cl_cred, &rqstp->rq_cred))
4039                 goto out;
4040         /* cases below refer to rfc 3530 section 14.2.34: */
4041         if (!unconf || !same_verf(&confirm, &unconf->cl_confirm)) {
4042                 if (conf && same_verf(&confirm, &conf->cl_confirm)) {
4043                         /* case 2: probable retransmit */
4044                         status = nfs_ok;
4045                 } else /* case 4: client hasn't noticed we rebooted yet? */
4046                         status = nfserr_stale_clientid;
4047                 goto out;
4048         }
4049         status = nfs_ok;
4050         if (conf) { /* case 1: callback update */
4051                 old = unconf;
4052                 unhash_client_locked(old);
4053                 nfsd4_change_callback(conf, &unconf->cl_cb_conn);
4054         } else { /* case 3: normal case; new or rebooted client */
4055                 old = find_confirmed_client_by_name(&unconf->cl_name, nn);
4056                 if (old) {
4057                         status = nfserr_clid_inuse;
4058                         if (client_has_state(old)
4059                                         && !same_creds(&unconf->cl_cred,
4060                                                         &old->cl_cred))
4061                                 goto out;
4062                         status = mark_client_expired_locked(old);
4063                         if (status) {
4064                                 old = NULL;
4065                                 goto out;
4066                         }
4067                 }
4068                 move_to_confirmed(unconf);
4069                 conf = unconf;
4070         }
4071         get_client_locked(conf);
4072         spin_unlock(&nn->client_lock);
4073         if (conf == unconf)
4074                 fsnotify_dentry(conf->cl_nfsd_info_dentry, FS_MODIFY);
4075         nfsd4_probe_callback(conf);
4076         spin_lock(&nn->client_lock);
4077         put_client_renew_locked(conf);
4078 out:
4079         spin_unlock(&nn->client_lock);
4080         if (old)
4081                 expire_client(old);
4082         return status;
4083 }
4084
4085 static struct nfs4_file *nfsd4_alloc_file(void)
4086 {
4087         return kmem_cache_alloc(file_slab, GFP_KERNEL);
4088 }
4089
4090 /* OPEN Share state helper functions */
4091 static void nfsd4_init_file(struct svc_fh *fh, unsigned int hashval,
4092                                 struct nfs4_file *fp)
4093 {
4094         lockdep_assert_held(&state_lock);
4095
4096         refcount_set(&fp->fi_ref, 1);
4097         spin_lock_init(&fp->fi_lock);
4098         INIT_LIST_HEAD(&fp->fi_stateids);
4099         INIT_LIST_HEAD(&fp->fi_delegations);
4100         INIT_LIST_HEAD(&fp->fi_clnt_odstate);
4101         fh_copy_shallow(&fp->fi_fhandle, &fh->fh_handle);
4102         fp->fi_deleg_file = NULL;
4103         fp->fi_had_conflict = false;
4104         fp->fi_share_deny = 0;
4105         memset(fp->fi_fds, 0, sizeof(fp->fi_fds));
4106         memset(fp->fi_access, 0, sizeof(fp->fi_access));
4107         fp->fi_aliased = false;
4108         fp->fi_inode = d_inode(fh->fh_dentry);
4109 #ifdef CONFIG_NFSD_PNFS
4110         INIT_LIST_HEAD(&fp->fi_lo_states);
4111         atomic_set(&fp->fi_lo_recalls, 0);
4112 #endif
4113         hlist_add_head_rcu(&fp->fi_hash, &file_hashtbl[hashval]);
4114 }
4115
4116 void
4117 nfsd4_free_slabs(void)
4118 {
4119         kmem_cache_destroy(client_slab);
4120         kmem_cache_destroy(openowner_slab);
4121         kmem_cache_destroy(lockowner_slab);
4122         kmem_cache_destroy(file_slab);
4123         kmem_cache_destroy(stateid_slab);
4124         kmem_cache_destroy(deleg_slab);
4125         kmem_cache_destroy(odstate_slab);
4126 }
4127
4128 int
4129 nfsd4_init_slabs(void)
4130 {
4131         client_slab = kmem_cache_create("nfsd4_clients",
4132                         sizeof(struct nfs4_client), 0, 0, NULL);
4133         if (client_slab == NULL)
4134                 goto out;
4135         openowner_slab = kmem_cache_create("nfsd4_openowners",
4136                         sizeof(struct nfs4_openowner), 0, 0, NULL);
4137         if (openowner_slab == NULL)
4138                 goto out_free_client_slab;
4139         lockowner_slab = kmem_cache_create("nfsd4_lockowners",
4140                         sizeof(struct nfs4_lockowner), 0, 0, NULL);
4141         if (lockowner_slab == NULL)
4142                 goto out_free_openowner_slab;
4143         file_slab = kmem_cache_create("nfsd4_files",
4144                         sizeof(struct nfs4_file), 0, 0, NULL);
4145         if (file_slab == NULL)
4146                 goto out_free_lockowner_slab;
4147         stateid_slab = kmem_cache_create("nfsd4_stateids",
4148                         sizeof(struct nfs4_ol_stateid), 0, 0, NULL);
4149         if (stateid_slab == NULL)
4150                 goto out_free_file_slab;
4151         deleg_slab = kmem_cache_create("nfsd4_delegations",
4152                         sizeof(struct nfs4_delegation), 0, 0, NULL);
4153         if (deleg_slab == NULL)
4154                 goto out_free_stateid_slab;
4155         odstate_slab = kmem_cache_create("nfsd4_odstate",
4156                         sizeof(struct nfs4_clnt_odstate), 0, 0, NULL);
4157         if (odstate_slab == NULL)
4158                 goto out_free_deleg_slab;
4159         return 0;
4160
4161 out_free_deleg_slab:
4162         kmem_cache_destroy(deleg_slab);
4163 out_free_stateid_slab:
4164         kmem_cache_destroy(stateid_slab);
4165 out_free_file_slab:
4166         kmem_cache_destroy(file_slab);
4167 out_free_lockowner_slab:
4168         kmem_cache_destroy(lockowner_slab);
4169 out_free_openowner_slab:
4170         kmem_cache_destroy(openowner_slab);
4171 out_free_client_slab:
4172         kmem_cache_destroy(client_slab);
4173 out:
4174         return -ENOMEM;
4175 }
4176
4177 static void init_nfs4_replay(struct nfs4_replay *rp)
4178 {
4179         rp->rp_status = nfserr_serverfault;
4180         rp->rp_buflen = 0;
4181         rp->rp_buf = rp->rp_ibuf;
4182         mutex_init(&rp->rp_mutex);
4183 }
4184
4185 static void nfsd4_cstate_assign_replay(struct nfsd4_compound_state *cstate,
4186                 struct nfs4_stateowner *so)
4187 {
4188         if (!nfsd4_has_session(cstate)) {
4189                 mutex_lock(&so->so_replay.rp_mutex);
4190                 cstate->replay_owner = nfs4_get_stateowner(so);
4191         }
4192 }
4193
4194 void nfsd4_cstate_clear_replay(struct nfsd4_compound_state *cstate)
4195 {
4196         struct nfs4_stateowner *so = cstate->replay_owner;
4197
4198         if (so != NULL) {
4199                 cstate->replay_owner = NULL;
4200                 mutex_unlock(&so->so_replay.rp_mutex);
4201                 nfs4_put_stateowner(so);
4202         }
4203 }
4204
4205 static inline void *alloc_stateowner(struct kmem_cache *slab, struct xdr_netobj *owner, struct nfs4_client *clp)
4206 {
4207         struct nfs4_stateowner *sop;
4208
4209         sop = kmem_cache_alloc(slab, GFP_KERNEL);
4210         if (!sop)
4211                 return NULL;
4212
4213         xdr_netobj_dup(&sop->so_owner, owner, GFP_KERNEL);
4214         if (!sop->so_owner.data) {
4215                 kmem_cache_free(slab, sop);
4216                 return NULL;
4217         }
4218
4219         INIT_LIST_HEAD(&sop->so_stateids);
4220         sop->so_client = clp;
4221         init_nfs4_replay(&sop->so_replay);
4222         atomic_set(&sop->so_count, 1);
4223         return sop;
4224 }
4225
4226 static void hash_openowner(struct nfs4_openowner *oo, struct nfs4_client *clp, unsigned int strhashval)
4227 {
4228         lockdep_assert_held(&clp->cl_lock);
4229
4230         list_add(&oo->oo_owner.so_strhash,
4231                  &clp->cl_ownerstr_hashtbl[strhashval]);
4232         list_add(&oo->oo_perclient, &clp->cl_openowners);
4233 }
4234
4235 static void nfs4_unhash_openowner(struct nfs4_stateowner *so)
4236 {
4237         unhash_openowner_locked(openowner(so));
4238 }
4239
4240 static void nfs4_free_openowner(struct nfs4_stateowner *so)
4241 {
4242         struct nfs4_openowner *oo = openowner(so);
4243
4244         kmem_cache_free(openowner_slab, oo);
4245 }
4246
4247 static const struct nfs4_stateowner_operations openowner_ops = {
4248         .so_unhash =    nfs4_unhash_openowner,
4249         .so_free =      nfs4_free_openowner,
4250 };
4251
4252 static struct nfs4_ol_stateid *
4253 nfsd4_find_existing_open(struct nfs4_file *fp, struct nfsd4_open *open)
4254 {
4255         struct nfs4_ol_stateid *local, *ret = NULL;
4256         struct nfs4_openowner *oo = open->op_openowner;
4257
4258         lockdep_assert_held(&fp->fi_lock);
4259
4260         list_for_each_entry(local, &fp->fi_stateids, st_perfile) {
4261                 /* ignore lock owners */
4262                 if (local->st_stateowner->so_is_open_owner == 0)
4263                         continue;
4264                 if (local->st_stateowner != &oo->oo_owner)
4265                         continue;
4266                 if (local->st_stid.sc_type == NFS4_OPEN_STID) {
4267                         ret = local;
4268                         refcount_inc(&ret->st_stid.sc_count);
4269                         break;
4270                 }
4271         }
4272         return ret;
4273 }
4274
4275 static __be32
4276 nfsd4_verify_open_stid(struct nfs4_stid *s)
4277 {
4278         __be32 ret = nfs_ok;
4279
4280         switch (s->sc_type) {
4281         default:
4282                 break;
4283         case 0:
4284         case NFS4_CLOSED_STID:
4285         case NFS4_CLOSED_DELEG_STID:
4286                 ret = nfserr_bad_stateid;
4287                 break;
4288         case NFS4_REVOKED_DELEG_STID:
4289                 ret = nfserr_deleg_revoked;
4290         }
4291         return ret;
4292 }
4293
4294 /* Lock the stateid st_mutex, and deal with races with CLOSE */
4295 static __be32
4296 nfsd4_lock_ol_stateid(struct nfs4_ol_stateid *stp)
4297 {
4298         __be32 ret;
4299
4300         mutex_lock_nested(&stp->st_mutex, LOCK_STATEID_MUTEX);
4301         ret = nfsd4_verify_open_stid(&stp->st_stid);
4302         if (ret != nfs_ok)
4303                 mutex_unlock(&stp->st_mutex);
4304         return ret;
4305 }
4306
4307 static struct nfs4_ol_stateid *
4308 nfsd4_find_and_lock_existing_open(struct nfs4_file *fp, struct nfsd4_open *open)
4309 {
4310         struct nfs4_ol_stateid *stp;
4311         for (;;) {
4312                 spin_lock(&fp->fi_lock);
4313                 stp = nfsd4_find_existing_open(fp, open);
4314                 spin_unlock(&fp->fi_lock);
4315                 if (!stp || nfsd4_lock_ol_stateid(stp) == nfs_ok)
4316                         break;
4317                 nfs4_put_stid(&stp->st_stid);
4318         }
4319         return stp;
4320 }
4321
4322 static struct nfs4_openowner *
4323 alloc_init_open_stateowner(unsigned int strhashval, struct nfsd4_open *open,
4324                            struct nfsd4_compound_state *cstate)
4325 {
4326         struct nfs4_client *clp = cstate->clp;
4327         struct nfs4_openowner *oo, *ret;
4328
4329         oo = alloc_stateowner(openowner_slab, &open->op_owner, clp);
4330         if (!oo)
4331                 return NULL;
4332         oo->oo_owner.so_ops = &openowner_ops;
4333         oo->oo_owner.so_is_open_owner = 1;
4334         oo->oo_owner.so_seqid = open->op_seqid;
4335         oo->oo_flags = 0;
4336         if (nfsd4_has_session(cstate))
4337                 oo->oo_flags |= NFS4_OO_CONFIRMED;
4338         oo->oo_time = 0;
4339         oo->oo_last_closed_stid = NULL;
4340         INIT_LIST_HEAD(&oo->oo_close_lru);
4341         spin_lock(&clp->cl_lock);
4342         ret = find_openstateowner_str_locked(strhashval, open, clp);
4343         if (ret == NULL) {
4344                 hash_openowner(oo, clp, strhashval);
4345                 ret = oo;
4346         } else
4347                 nfs4_free_stateowner(&oo->oo_owner);
4348
4349         spin_unlock(&clp->cl_lock);
4350         return ret;
4351 }
4352
4353 static struct nfs4_ol_stateid *
4354 init_open_stateid(struct nfs4_file *fp, struct nfsd4_open *open)
4355 {
4356
4357         struct nfs4_openowner *oo = open->op_openowner;
4358         struct nfs4_ol_stateid *retstp = NULL;
4359         struct nfs4_ol_stateid *stp;
4360
4361         stp = open->op_stp;
4362         /* We are moving these outside of the spinlocks to avoid the warnings */
4363         mutex_init(&stp->st_mutex);
4364         mutex_lock_nested(&stp->st_mutex, OPEN_STATEID_MUTEX);
4365
4366 retry:
4367         spin_lock(&oo->oo_owner.so_client->cl_lock);
4368         spin_lock(&fp->fi_lock);
4369
4370         retstp = nfsd4_find_existing_open(fp, open);
4371         if (retstp)
4372                 goto out_unlock;
4373
4374         open->op_stp = NULL;
4375         refcount_inc(&stp->st_stid.sc_count);
4376         stp->st_stid.sc_type = NFS4_OPEN_STID;
4377         INIT_LIST_HEAD(&stp->st_locks);
4378         stp->st_stateowner = nfs4_get_stateowner(&oo->oo_owner);
4379         get_nfs4_file(fp);
4380         stp->st_stid.sc_file = fp;
4381         stp->st_access_bmap = 0;
4382         stp->st_deny_bmap = 0;
4383         stp->st_openstp = NULL;
4384         list_add(&stp->st_perstateowner, &oo->oo_owner.so_stateids);
4385         list_add(&stp->st_perfile, &fp->fi_stateids);
4386
4387 out_unlock:
4388         spin_unlock(&fp->fi_lock);
4389         spin_unlock(&oo->oo_owner.so_client->cl_lock);
4390         if (retstp) {
4391                 /* Handle races with CLOSE */
4392                 if (nfsd4_lock_ol_stateid(retstp) != nfs_ok) {
4393                         nfs4_put_stid(&retstp->st_stid);
4394                         goto retry;
4395                 }
4396                 /* To keep mutex tracking happy */
4397                 mutex_unlock(&stp->st_mutex);
4398                 stp = retstp;
4399         }
4400         return stp;
4401 }
4402
4403 /*
4404  * In the 4.0 case we need to keep the owners around a little while to handle
4405  * CLOSE replay. We still do need to release any file access that is held by
4406  * them before returning however.
4407  */
4408 static void
4409 move_to_close_lru(struct nfs4_ol_stateid *s, struct net *net)
4410 {
4411         struct nfs4_ol_stateid *last;
4412         struct nfs4_openowner *oo = openowner(s->st_stateowner);
4413         struct nfsd_net *nn = net_generic(s->st_stid.sc_client->net,
4414                                                 nfsd_net_id);
4415
4416         dprintk("NFSD: move_to_close_lru nfs4_openowner %p\n", oo);
4417
4418         /*
4419          * We know that we hold one reference via nfsd4_close, and another
4420          * "persistent" reference for the client. If the refcount is higher
4421          * than 2, then there are still calls in progress that are using this
4422          * stateid. We can't put the sc_file reference until they are finished.
4423          * Wait for the refcount to drop to 2. Since it has been unhashed,
4424          * there should be no danger of the refcount going back up again at
4425          * this point.
4426          */
4427         wait_event(close_wq, refcount_read(&s->st_stid.sc_count) == 2);
4428
4429         release_all_access(s);
4430         if (s->st_stid.sc_file) {
4431                 put_nfs4_file(s->st_stid.sc_file);
4432                 s->st_stid.sc_file = NULL;
4433         }
4434
4435         spin_lock(&nn->client_lock);
4436         last = oo->oo_last_closed_stid;
4437         oo->oo_last_closed_stid = s;
4438         list_move_tail(&oo->oo_close_lru, &nn->close_lru);
4439         oo->oo_time = ktime_get_boottime_seconds();
4440         spin_unlock(&nn->client_lock);
4441         if (last)
4442                 nfs4_put_stid(&last->st_stid);
4443 }
4444
4445 /* search file_hashtbl[] for file */
4446 static struct nfs4_file *
4447 find_file_locked(struct svc_fh *fh, unsigned int hashval)
4448 {
4449         struct nfs4_file *fp;
4450
4451         hlist_for_each_entry_rcu(fp, &file_hashtbl[hashval], fi_hash,
4452                                 lockdep_is_held(&state_lock)) {
4453                 if (fh_match(&fp->fi_fhandle, &fh->fh_handle)) {
4454                         if (refcount_inc_not_zero(&fp->fi_ref))
4455                                 return fp;
4456                 }
4457         }
4458         return NULL;
4459 }
4460
4461 static struct nfs4_file *insert_file(struct nfs4_file *new, struct svc_fh *fh,
4462                                      unsigned int hashval)
4463 {
4464         struct nfs4_file *fp;
4465         struct nfs4_file *ret = NULL;
4466         bool alias_found = false;
4467
4468         spin_lock(&state_lock);
4469         hlist_for_each_entry_rcu(fp, &file_hashtbl[hashval], fi_hash,
4470                                  lockdep_is_held(&state_lock)) {
4471                 if (fh_match(&fp->fi_fhandle, &fh->fh_handle)) {
4472                         if (refcount_inc_not_zero(&fp->fi_ref))
4473                                 ret = fp;
4474                 } else if (d_inode(fh->fh_dentry) == fp->fi_inode)
4475                         fp->fi_aliased = alias_found = true;
4476         }
4477         if (likely(ret == NULL)) {
4478                 nfsd4_init_file(fh, hashval, new);
4479                 new->fi_aliased = alias_found;
4480                 ret = new;
4481         }
4482         spin_unlock(&state_lock);
4483         return ret;
4484 }
4485
4486 static struct nfs4_file * find_file(struct svc_fh *fh)
4487 {
4488         struct nfs4_file *fp;
4489         unsigned int hashval = file_hashval(fh);
4490
4491         rcu_read_lock();
4492         fp = find_file_locked(fh, hashval);
4493         rcu_read_unlock();
4494         return fp;
4495 }
4496
4497 static struct nfs4_file *
4498 find_or_add_file(struct nfs4_file *new, struct svc_fh *fh)
4499 {
4500         struct nfs4_file *fp;
4501         unsigned int hashval = file_hashval(fh);
4502
4503         rcu_read_lock();
4504         fp = find_file_locked(fh, hashval);
4505         rcu_read_unlock();
4506         if (fp)
4507                 return fp;
4508
4509         return insert_file(new, fh, hashval);
4510 }
4511
4512 /*
4513  * Called to check deny when READ with all zero stateid or
4514  * WRITE with all zero or all one stateid
4515  */
4516 static __be32
4517 nfs4_share_conflict(struct svc_fh *current_fh, unsigned int deny_type)
4518 {
4519         struct nfs4_file *fp;
4520         __be32 ret = nfs_ok;
4521
4522         fp = find_file(current_fh);
4523         if (!fp)
4524                 return ret;
4525         /* Check for conflicting share reservations */
4526         spin_lock(&fp->fi_lock);
4527         if (fp->fi_share_deny & deny_type)
4528                 ret = nfserr_locked;
4529         spin_unlock(&fp->fi_lock);
4530         put_nfs4_file(fp);
4531         return ret;
4532 }
4533
4534 static void nfsd4_cb_recall_prepare(struct nfsd4_callback *cb)
4535 {
4536         struct nfs4_delegation *dp = cb_to_delegation(cb);
4537         struct nfsd_net *nn = net_generic(dp->dl_stid.sc_client->net,
4538                                           nfsd_net_id);
4539
4540         block_delegations(&dp->dl_stid.sc_file->fi_fhandle);
4541
4542         /*
4543          * We can't do this in nfsd_break_deleg_cb because it is
4544          * already holding inode->i_lock.
4545          *
4546          * If the dl_time != 0, then we know that it has already been
4547          * queued for a lease break. Don't queue it again.
4548          */
4549         spin_lock(&state_lock);
4550         if (dp->dl_time == 0) {
4551                 dp->dl_time = ktime_get_boottime_seconds();
4552                 list_add_tail(&dp->dl_recall_lru, &nn->del_recall_lru);
4553         }
4554         spin_unlock(&state_lock);
4555 }
4556
4557 static int nfsd4_cb_recall_done(struct nfsd4_callback *cb,
4558                 struct rpc_task *task)
4559 {
4560         struct nfs4_delegation *dp = cb_to_delegation(cb);
4561
4562         if (dp->dl_stid.sc_type == NFS4_CLOSED_DELEG_STID ||
4563             dp->dl_stid.sc_type == NFS4_REVOKED_DELEG_STID)
4564                 return 1;
4565
4566         switch (task->tk_status) {
4567         case 0:
4568                 return 1;
4569         case -NFS4ERR_DELAY:
4570                 rpc_delay(task, 2 * HZ);
4571                 return 0;
4572         case -EBADHANDLE:
4573         case -NFS4ERR_BAD_STATEID:
4574                 /*
4575                  * Race: client probably got cb_recall before open reply
4576                  * granting delegation.
4577                  */
4578                 if (dp->dl_retries--) {
4579                         rpc_delay(task, 2 * HZ);
4580                         return 0;
4581                 }
4582                 fallthrough;
4583         default:
4584                 return 1;
4585         }
4586 }
4587
4588 static void nfsd4_cb_recall_release(struct nfsd4_callback *cb)
4589 {
4590         struct nfs4_delegation *dp = cb_to_delegation(cb);
4591
4592         nfs4_put_stid(&dp->dl_stid);
4593 }
4594
4595 static const struct nfsd4_callback_ops nfsd4_cb_recall_ops = {
4596         .prepare        = nfsd4_cb_recall_prepare,
4597         .done           = nfsd4_cb_recall_done,
4598         .release        = nfsd4_cb_recall_release,
4599 };
4600
4601 static void nfsd_break_one_deleg(struct nfs4_delegation *dp)
4602 {
4603         /*
4604          * We're assuming the state code never drops its reference
4605          * without first removing the lease.  Since we're in this lease
4606          * callback (and since the lease code is serialized by the
4607          * i_lock) we know the server hasn't removed the lease yet, and
4608          * we know it's safe to take a reference.
4609          */
4610         refcount_inc(&dp->dl_stid.sc_count);
4611         nfsd4_run_cb(&dp->dl_recall);
4612 }
4613
4614 /* Called from break_lease() with i_lock held. */
4615 static bool
4616 nfsd_break_deleg_cb(struct file_lock *fl)
4617 {
4618         bool ret = false;
4619         struct nfs4_delegation *dp = (struct nfs4_delegation *)fl->fl_owner;
4620         struct nfs4_file *fp = dp->dl_stid.sc_file;
4621
4622         trace_nfsd_deleg_break(&dp->dl_stid.sc_stateid);
4623
4624         /*
4625          * We don't want the locks code to timeout the lease for us;
4626          * we'll remove it ourself if a delegation isn't returned
4627          * in time:
4628          */
4629         fl->fl_break_time = 0;
4630
4631         spin_lock(&fp->fi_lock);
4632         fp->fi_had_conflict = true;
4633         nfsd_break_one_deleg(dp);
4634         spin_unlock(&fp->fi_lock);
4635         return ret;
4636 }
4637
4638 static bool nfsd_breaker_owns_lease(struct file_lock *fl)
4639 {
4640         struct nfs4_delegation *dl = fl->fl_owner;
4641         struct svc_rqst *rqst;
4642         struct nfs4_client *clp;
4643
4644         if (!i_am_nfsd())
4645                 return NULL;
4646         rqst = kthread_data(current);
4647         /* Note rq_prog == NFS_ACL_PROGRAM is also possible: */
4648         if (rqst->rq_prog != NFS_PROGRAM || rqst->rq_vers < 4)
4649                 return NULL;
4650         clp = *(rqst->rq_lease_breaker);
4651         return dl->dl_stid.sc_client == clp;
4652 }
4653
4654 static int
4655 nfsd_change_deleg_cb(struct file_lock *onlist, int arg,
4656                      struct list_head *dispose)
4657 {
4658         if (arg & F_UNLCK)
4659                 return lease_modify(onlist, arg, dispose);
4660         else
4661                 return -EAGAIN;
4662 }
4663
4664 static const struct lock_manager_operations nfsd_lease_mng_ops = {
4665         .lm_breaker_owns_lease = nfsd_breaker_owns_lease,
4666         .lm_break = nfsd_break_deleg_cb,
4667         .lm_change = nfsd_change_deleg_cb,
4668 };
4669
4670 static __be32 nfsd4_check_seqid(struct nfsd4_compound_state *cstate, struct nfs4_stateowner *so, u32 seqid)
4671 {
4672         if (nfsd4_has_session(cstate))
4673                 return nfs_ok;
4674         if (seqid == so->so_seqid - 1)
4675                 return nfserr_replay_me;
4676         if (seqid == so->so_seqid)
4677                 return nfs_ok;
4678         return nfserr_bad_seqid;
4679 }
4680
4681 static struct nfs4_client *lookup_clientid(clientid_t *clid, bool sessions,
4682                                                 struct nfsd_net *nn)
4683 {
4684         struct nfs4_client *found;
4685
4686         spin_lock(&nn->client_lock);
4687         found = find_confirmed_client(clid, sessions, nn);
4688         if (found)
4689                 atomic_inc(&found->cl_rpc_users);
4690         spin_unlock(&nn->client_lock);
4691         return found;
4692 }
4693
4694 static __be32 set_client(clientid_t *clid,
4695                 struct nfsd4_compound_state *cstate,
4696                 struct nfsd_net *nn)
4697 {
4698         if (cstate->clp) {
4699                 if (!same_clid(&cstate->clp->cl_clientid, clid))
4700                         return nfserr_stale_clientid;
4701                 return nfs_ok;
4702         }
4703         if (STALE_CLIENTID(clid, nn))
4704                 return nfserr_stale_clientid;
4705         /*
4706          * We're in the 4.0 case (otherwise the SEQUENCE op would have
4707          * set cstate->clp), so session = false:
4708          */
4709         cstate->clp = lookup_clientid(clid, false, nn);
4710         if (!cstate->clp)
4711                 return nfserr_expired;
4712         return nfs_ok;
4713 }
4714
4715 __be32
4716 nfsd4_process_open1(struct nfsd4_compound_state *cstate,
4717                     struct nfsd4_open *open, struct nfsd_net *nn)
4718 {
4719         clientid_t *clientid = &open->op_clientid;
4720         struct nfs4_client *clp = NULL;
4721         unsigned int strhashval;
4722         struct nfs4_openowner *oo = NULL;
4723         __be32 status;
4724
4725         /*
4726          * In case we need it later, after we've already created the
4727          * file and don't want to risk a further failure:
4728          */
4729         open->op_file = nfsd4_alloc_file();
4730         if (open->op_file == NULL)
4731                 return nfserr_jukebox;
4732
4733         status = set_client(clientid, cstate, nn);
4734         if (status)
4735                 return status;
4736         clp = cstate->clp;
4737
4738         strhashval = ownerstr_hashval(&open->op_owner);
4739         oo = find_openstateowner_str(strhashval, open, clp);
4740         open->op_openowner = oo;
4741         if (!oo) {
4742                 goto new_owner;
4743         }
4744         if (!(oo->oo_flags & NFS4_OO_CONFIRMED)) {
4745                 /* Replace unconfirmed owners without checking for replay. */
4746                 release_openowner(oo);
4747                 open->op_openowner = NULL;
4748                 goto new_owner;
4749         }
4750         status = nfsd4_check_seqid(cstate, &oo->oo_owner, open->op_seqid);
4751         if (status)
4752                 return status;
4753         goto alloc_stateid;
4754 new_owner:
4755         oo = alloc_init_open_stateowner(strhashval, open, cstate);
4756         if (oo == NULL)
4757                 return nfserr_jukebox;
4758         open->op_openowner = oo;
4759 alloc_stateid:
4760         open->op_stp = nfs4_alloc_open_stateid(clp);
4761         if (!open->op_stp)
4762                 return nfserr_jukebox;
4763
4764         if (nfsd4_has_session(cstate) &&
4765             (cstate->current_fh.fh_export->ex_flags & NFSEXP_PNFS)) {
4766                 open->op_odstate = alloc_clnt_odstate(clp);
4767                 if (!open->op_odstate)
4768                         return nfserr_jukebox;
4769         }
4770
4771         return nfs_ok;
4772 }
4773
4774 static inline __be32
4775 nfs4_check_delegmode(struct nfs4_delegation *dp, int flags)
4776 {
4777         if ((flags & WR_STATE) && (dp->dl_type == NFS4_OPEN_DELEGATE_READ))
4778                 return nfserr_openmode;
4779         else
4780                 return nfs_ok;
4781 }
4782
4783 static int share_access_to_flags(u32 share_access)
4784 {
4785         return share_access == NFS4_SHARE_ACCESS_READ ? RD_STATE : WR_STATE;
4786 }
4787
4788 static struct nfs4_delegation *find_deleg_stateid(struct nfs4_client *cl, stateid_t *s)
4789 {
4790         struct nfs4_stid *ret;
4791
4792         ret = find_stateid_by_type(cl, s,
4793                                 NFS4_DELEG_STID|NFS4_REVOKED_DELEG_STID);
4794         if (!ret)
4795                 return NULL;
4796         return delegstateid(ret);
4797 }
4798
4799 static bool nfsd4_is_deleg_cur(struct nfsd4_open *open)
4800 {
4801         return open->op_claim_type == NFS4_OPEN_CLAIM_DELEGATE_CUR ||
4802                open->op_claim_type == NFS4_OPEN_CLAIM_DELEG_CUR_FH;
4803 }
4804
4805 static __be32
4806 nfs4_check_deleg(struct nfs4_client *cl, struct nfsd4_open *open,
4807                 struct nfs4_delegation **dp)
4808 {
4809         int flags;
4810         __be32 status = nfserr_bad_stateid;
4811         struct nfs4_delegation *deleg;
4812
4813         deleg = find_deleg_stateid(cl, &open->op_delegate_stateid);
4814         if (deleg == NULL)
4815                 goto out;
4816         if (deleg->dl_stid.sc_type == NFS4_REVOKED_DELEG_STID) {
4817                 nfs4_put_stid(&deleg->dl_stid);
4818                 if (cl->cl_minorversion)
4819                         status = nfserr_deleg_revoked;
4820                 goto out;
4821         }
4822         flags = share_access_to_flags(open->op_share_access);
4823         status = nfs4_check_delegmode(deleg, flags);
4824         if (status) {
4825                 nfs4_put_stid(&deleg->dl_stid);
4826                 goto out;
4827         }
4828         *dp = deleg;
4829 out:
4830         if (!nfsd4_is_deleg_cur(open))
4831                 return nfs_ok;
4832         if (status)
4833                 return status;
4834         open->op_openowner->oo_flags |= NFS4_OO_CONFIRMED;
4835         return nfs_ok;
4836 }
4837
4838 static inline int nfs4_access_to_access(u32 nfs4_access)
4839 {
4840         int flags = 0;
4841
4842         if (nfs4_access & NFS4_SHARE_ACCESS_READ)
4843                 flags |= NFSD_MAY_READ;
4844         if (nfs4_access & NFS4_SHARE_ACCESS_WRITE)
4845                 flags |= NFSD_MAY_WRITE;
4846         return flags;
4847 }
4848
4849 static inline __be32
4850 nfsd4_truncate(struct svc_rqst *rqstp, struct svc_fh *fh,
4851                 struct nfsd4_open *open)
4852 {
4853         struct iattr iattr = {
4854                 .ia_valid = ATTR_SIZE,
4855                 .ia_size = 0,
4856         };
4857         if (!open->op_truncate)
4858                 return 0;
4859         if (!(open->op_share_access & NFS4_SHARE_ACCESS_WRITE))
4860                 return nfserr_inval;
4861         return nfsd_setattr(rqstp, fh, &iattr, 0, (time64_t)0);
4862 }
4863
4864 static __be32 nfs4_get_vfs_file(struct svc_rqst *rqstp, struct nfs4_file *fp,
4865                 struct svc_fh *cur_fh, struct nfs4_ol_stateid *stp,
4866                 struct nfsd4_open *open)
4867 {
4868         struct nfsd_file *nf = NULL;
4869         __be32 status;
4870         int oflag = nfs4_access_to_omode(open->op_share_access);
4871         int access = nfs4_access_to_access(open->op_share_access);
4872         unsigned char old_access_bmap, old_deny_bmap;
4873
4874         spin_lock(&fp->fi_lock);
4875
4876         /*
4877          * Are we trying to set a deny mode that would conflict with
4878          * current access?
4879          */
4880         status = nfs4_file_check_deny(fp, open->op_share_deny);
4881         if (status != nfs_ok) {
4882                 spin_unlock(&fp->fi_lock);
4883                 goto out;
4884         }
4885
4886         /* set access to the file */
4887         status = nfs4_file_get_access(fp, open->op_share_access);
4888         if (status != nfs_ok) {
4889                 spin_unlock(&fp->fi_lock);
4890                 goto out;
4891         }
4892
4893         /* Set access bits in stateid */
4894         old_access_bmap = stp->st_access_bmap;
4895         set_access(open->op_share_access, stp);
4896
4897         /* Set new deny mask */
4898         old_deny_bmap = stp->st_deny_bmap;
4899         set_deny(open->op_share_deny, stp);
4900         fp->fi_share_deny |= (open->op_share_deny & NFS4_SHARE_DENY_BOTH);
4901
4902         if (!fp->fi_fds[oflag]) {
4903                 spin_unlock(&fp->fi_lock);
4904                 status = nfsd_file_acquire(rqstp, cur_fh, access, &nf);
4905                 if (status)
4906                         goto out_put_access;
4907                 spin_lock(&fp->fi_lock);
4908                 if (!fp->fi_fds[oflag]) {
4909                         fp->fi_fds[oflag] = nf;
4910                         nf = NULL;
4911                 }
4912         }
4913         spin_unlock(&fp->fi_lock);
4914         if (nf)
4915                 nfsd_file_put(nf);
4916
4917         status = nfserrno(nfsd_open_break_lease(cur_fh->fh_dentry->d_inode,
4918                                                                 access));
4919         if (status)
4920                 goto out_put_access;
4921
4922         status = nfsd4_truncate(rqstp, cur_fh, open);
4923         if (status)
4924                 goto out_put_access;
4925 out:
4926         return status;
4927 out_put_access:
4928         stp->st_access_bmap = old_access_bmap;
4929         nfs4_file_put_access(fp, open->op_share_access);
4930         reset_union_bmap_deny(bmap_to_share_mode(old_deny_bmap), stp);
4931         goto out;
4932 }
4933
4934 static __be32
4935 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)
4936 {
4937         __be32 status;
4938         unsigned char old_deny_bmap = stp->st_deny_bmap;
4939
4940         if (!test_access(open->op_share_access, stp))
4941                 return nfs4_get_vfs_file(rqstp, fp, cur_fh, stp, open);
4942
4943         /* test and set deny mode */
4944         spin_lock(&fp->fi_lock);
4945         status = nfs4_file_check_deny(fp, open->op_share_deny);
4946         if (status == nfs_ok) {
4947                 set_deny(open->op_share_deny, stp);
4948                 fp->fi_share_deny |=
4949                                 (open->op_share_deny & NFS4_SHARE_DENY_BOTH);
4950         }
4951         spin_unlock(&fp->fi_lock);
4952
4953         if (status != nfs_ok)
4954                 return status;
4955
4956         status = nfsd4_truncate(rqstp, cur_fh, open);
4957         if (status != nfs_ok)
4958                 reset_union_bmap_deny(old_deny_bmap, stp);
4959         return status;
4960 }
4961
4962 /* Should we give out recallable state?: */
4963 static bool nfsd4_cb_channel_good(struct nfs4_client *clp)
4964 {
4965         if (clp->cl_cb_state == NFSD4_CB_UP)
4966                 return true;
4967         /*
4968          * In the sessions case, since we don't have to establish a
4969          * separate connection for callbacks, we assume it's OK
4970          * until we hear otherwise:
4971          */
4972         return clp->cl_minorversion && clp->cl_cb_state == NFSD4_CB_UNKNOWN;
4973 }
4974
4975 static struct file_lock *nfs4_alloc_init_lease(struct nfs4_delegation *dp,
4976                                                 int flag)
4977 {
4978         struct file_lock *fl;
4979
4980         fl = locks_alloc_lock();
4981         if (!fl)
4982                 return NULL;
4983         fl->fl_lmops = &nfsd_lease_mng_ops;
4984         fl->fl_flags = FL_DELEG;
4985         fl->fl_type = flag == NFS4_OPEN_DELEGATE_READ? F_RDLCK: F_WRLCK;
4986         fl->fl_end = OFFSET_MAX;
4987         fl->fl_owner = (fl_owner_t)dp;
4988         fl->fl_pid = current->tgid;
4989         fl->fl_file = dp->dl_stid.sc_file->fi_deleg_file->nf_file;
4990         return fl;
4991 }
4992
4993 static int nfsd4_check_conflicting_opens(struct nfs4_client *clp,
4994                                          struct nfs4_file *fp)
4995 {
4996         struct nfs4_ol_stateid *st;
4997         struct file *f = fp->fi_deleg_file->nf_file;
4998         struct inode *ino = locks_inode(f);
4999         int writes;
5000
5001         writes = atomic_read(&ino->i_writecount);
5002         if (!writes)
5003                 return 0;
5004         /*
5005          * There could be multiple filehandles (hence multiple
5006          * nfs4_files) referencing this file, but that's not too
5007          * common; let's just give up in that case rather than
5008          * trying to go look up all the clients using that other
5009          * nfs4_file as well:
5010          */
5011         if (fp->fi_aliased)
5012                 return -EAGAIN;
5013         /*
5014          * If there's a close in progress, make sure that we see it
5015          * clear any fi_fds[] entries before we see it decrement
5016          * i_writecount:
5017          */
5018         smp_mb__after_atomic();
5019
5020         if (fp->fi_fds[O_WRONLY])
5021                 writes--;
5022         if (fp->fi_fds[O_RDWR])
5023                 writes--;
5024         if (writes > 0)
5025                 return -EAGAIN; /* There may be non-NFSv4 writers */
5026         /*
5027          * It's possible there are non-NFSv4 write opens in progress,
5028          * but if they haven't incremented i_writecount yet then they
5029          * also haven't called break lease yet; so, they'll break this
5030          * lease soon enough.  So, all that's left to check for is NFSv4
5031          * opens:
5032          */
5033         spin_lock(&fp->fi_lock);
5034         list_for_each_entry(st, &fp->fi_stateids, st_perfile) {
5035                 if (st->st_openstp == NULL /* it's an open */ &&
5036                     access_permit_write(st) &&
5037                     st->st_stid.sc_client != clp) {
5038                         spin_unlock(&fp->fi_lock);
5039                         return -EAGAIN;
5040                 }
5041         }
5042         spin_unlock(&fp->fi_lock);
5043         /*
5044          * There's a small chance that we could be racing with another
5045          * NFSv4 open.  However, any open that hasn't added itself to
5046          * the fi_stateids list also hasn't called break_lease yet; so,
5047          * they'll break this lease soon enough.
5048          */
5049         return 0;
5050 }
5051
5052 static struct nfs4_delegation *
5053 nfs4_set_delegation(struct nfs4_client *clp, struct svc_fh *fh,
5054                     struct nfs4_file *fp, struct nfs4_clnt_odstate *odstate)
5055 {
5056         int status = 0;
5057         struct nfs4_delegation *dp;
5058         struct nfsd_file *nf;
5059         struct file_lock *fl;
5060
5061         /*
5062          * The fi_had_conflict and nfs_get_existing_delegation checks
5063          * here are just optimizations; we'll need to recheck them at
5064          * the end:
5065          */
5066         if (fp->fi_had_conflict)
5067                 return ERR_PTR(-EAGAIN);
5068
5069         nf = find_readable_file(fp);
5070         if (!nf) {
5071                 /*
5072                  * We probably could attempt another open and get a read
5073                  * delegation, but for now, don't bother until the
5074                  * client actually sends us one.
5075                  */
5076                 return ERR_PTR(-EAGAIN);
5077         }
5078         spin_lock(&state_lock);
5079         spin_lock(&fp->fi_lock);
5080         if (nfs4_delegation_exists(clp, fp))
5081                 status = -EAGAIN;
5082         else if (!fp->fi_deleg_file) {
5083                 fp->fi_deleg_file = nf;
5084                 /* increment early to prevent fi_deleg_file from being
5085                  * cleared */
5086                 fp->fi_delegees = 1;
5087                 nf = NULL;
5088         } else
5089                 fp->fi_delegees++;
5090         spin_unlock(&fp->fi_lock);
5091         spin_unlock(&state_lock);
5092         if (nf)
5093                 nfsd_file_put(nf);
5094         if (status)
5095                 return ERR_PTR(status);
5096
5097         status = -ENOMEM;
5098         dp = alloc_init_deleg(clp, fp, fh, odstate);
5099         if (!dp)
5100                 goto out_delegees;
5101
5102         fl = nfs4_alloc_init_lease(dp, NFS4_OPEN_DELEGATE_READ);
5103         if (!fl)
5104                 goto out_clnt_odstate;
5105
5106         status = vfs_setlease(fp->fi_deleg_file->nf_file, fl->fl_type, &fl, NULL);
5107         if (fl)
5108                 locks_free_lock(fl);
5109         if (status)
5110                 goto out_clnt_odstate;
5111         status = nfsd4_check_conflicting_opens(clp, fp);
5112         if (status)
5113                 goto out_unlock;
5114
5115         spin_lock(&state_lock);
5116         spin_lock(&fp->fi_lock);
5117         if (fp->fi_had_conflict)
5118                 status = -EAGAIN;
5119         else
5120                 status = hash_delegation_locked(dp, fp);
5121         spin_unlock(&fp->fi_lock);
5122         spin_unlock(&state_lock);
5123
5124         if (status)
5125                 goto out_unlock;
5126
5127         return dp;
5128 out_unlock:
5129         vfs_setlease(fp->fi_deleg_file->nf_file, F_UNLCK, NULL, (void **)&dp);
5130 out_clnt_odstate:
5131         put_clnt_odstate(dp->dl_clnt_odstate);
5132         nfs4_put_stid(&dp->dl_stid);
5133 out_delegees:
5134         put_deleg_file(fp);
5135         return ERR_PTR(status);
5136 }
5137
5138 static void nfsd4_open_deleg_none_ext(struct nfsd4_open *open, int status)
5139 {
5140         open->op_delegate_type = NFS4_OPEN_DELEGATE_NONE_EXT;
5141         if (status == -EAGAIN)
5142                 open->op_why_no_deleg = WND4_CONTENTION;
5143         else {
5144                 open->op_why_no_deleg = WND4_RESOURCE;
5145                 switch (open->op_deleg_want) {
5146                 case NFS4_SHARE_WANT_READ_DELEG:
5147                 case NFS4_SHARE_WANT_WRITE_DELEG:
5148                 case NFS4_SHARE_WANT_ANY_DELEG:
5149                         break;
5150                 case NFS4_SHARE_WANT_CANCEL:
5151                         open->op_why_no_deleg = WND4_CANCELLED;
5152                         break;
5153                 case NFS4_SHARE_WANT_NO_DELEG:
5154                         WARN_ON_ONCE(1);
5155                 }
5156         }
5157 }
5158
5159 /*
5160  * Attempt to hand out a delegation.
5161  *
5162  * Note we don't support write delegations, and won't until the vfs has
5163  * proper support for them.
5164  */
5165 static void
5166 nfs4_open_delegation(struct svc_fh *fh, struct nfsd4_open *open,
5167                         struct nfs4_ol_stateid *stp)
5168 {
5169         struct nfs4_delegation *dp;
5170         struct nfs4_openowner *oo = openowner(stp->st_stateowner);
5171         struct nfs4_client *clp = stp->st_stid.sc_client;
5172         int cb_up;
5173         int status = 0;
5174
5175         cb_up = nfsd4_cb_channel_good(oo->oo_owner.so_client);
5176         open->op_recall = 0;
5177         switch (open->op_claim_type) {
5178                 case NFS4_OPEN_CLAIM_PREVIOUS:
5179                         if (!cb_up)
5180                                 open->op_recall = 1;
5181                         if (open->op_delegate_type != NFS4_OPEN_DELEGATE_READ)
5182                                 goto out_no_deleg;
5183                         break;
5184                 case NFS4_OPEN_CLAIM_NULL:
5185                 case NFS4_OPEN_CLAIM_FH:
5186                         /*
5187                          * Let's not give out any delegations till everyone's
5188                          * had the chance to reclaim theirs, *and* until
5189                          * NLM locks have all been reclaimed:
5190                          */
5191                         if (locks_in_grace(clp->net))
5192                                 goto out_no_deleg;
5193                         if (!cb_up || !(oo->oo_flags & NFS4_OO_CONFIRMED))
5194                                 goto out_no_deleg;
5195                         break;
5196                 default:
5197                         goto out_no_deleg;
5198         }
5199         dp = nfs4_set_delegation(clp, fh, stp->st_stid.sc_file, stp->st_clnt_odstate);
5200         if (IS_ERR(dp))
5201                 goto out_no_deleg;
5202
5203         memcpy(&open->op_delegate_stateid, &dp->dl_stid.sc_stateid, sizeof(dp->dl_stid.sc_stateid));
5204
5205         trace_nfsd_deleg_read(&dp->dl_stid.sc_stateid);
5206         open->op_delegate_type = NFS4_OPEN_DELEGATE_READ;
5207         nfs4_put_stid(&dp->dl_stid);
5208         return;
5209 out_no_deleg:
5210         open->op_delegate_type = NFS4_OPEN_DELEGATE_NONE;
5211         if (open->op_claim_type == NFS4_OPEN_CLAIM_PREVIOUS &&
5212             open->op_delegate_type != NFS4_OPEN_DELEGATE_NONE) {
5213                 dprintk("NFSD: WARNING: refusing delegation reclaim\n");
5214                 open->op_recall = 1;
5215         }
5216
5217         /* 4.1 client asking for a delegation? */
5218         if (open->op_deleg_want)
5219                 nfsd4_open_deleg_none_ext(open, status);
5220         return;
5221 }
5222
5223 static void nfsd4_deleg_xgrade_none_ext(struct nfsd4_open *open,
5224                                         struct nfs4_delegation *dp)
5225 {
5226         if (open->op_deleg_want == NFS4_SHARE_WANT_READ_DELEG &&
5227             dp->dl_type == NFS4_OPEN_DELEGATE_WRITE) {
5228                 open->op_delegate_type = NFS4_OPEN_DELEGATE_NONE_EXT;
5229                 open->op_why_no_deleg = WND4_NOT_SUPP_DOWNGRADE;
5230         } else if (open->op_deleg_want == NFS4_SHARE_WANT_WRITE_DELEG &&
5231                    dp->dl_type == NFS4_OPEN_DELEGATE_WRITE) {
5232                 open->op_delegate_type = NFS4_OPEN_DELEGATE_NONE_EXT;
5233                 open->op_why_no_deleg = WND4_NOT_SUPP_UPGRADE;
5234         }
5235         /* Otherwise the client must be confused wanting a delegation
5236          * it already has, therefore we don't return
5237          * NFS4_OPEN_DELEGATE_NONE_EXT and reason.
5238          */
5239 }
5240
5241 __be32
5242 nfsd4_process_open2(struct svc_rqst *rqstp, struct svc_fh *current_fh, struct nfsd4_open *open)
5243 {
5244         struct nfsd4_compoundres *resp = rqstp->rq_resp;
5245         struct nfs4_client *cl = open->op_openowner->oo_owner.so_client;
5246         struct nfs4_file *fp = NULL;
5247         struct nfs4_ol_stateid *stp = NULL;
5248         struct nfs4_delegation *dp = NULL;
5249         __be32 status;
5250         bool new_stp = false;
5251
5252         /*
5253          * Lookup file; if found, lookup stateid and check open request,
5254          * and check for delegations in the process of being recalled.
5255          * If not found, create the nfs4_file struct
5256          */
5257         fp = find_or_add_file(open->op_file, current_fh);
5258         if (fp != open->op_file) {
5259                 status = nfs4_check_deleg(cl, open, &dp);
5260                 if (status)
5261                         goto out;
5262                 stp = nfsd4_find_and_lock_existing_open(fp, open);
5263         } else {
5264                 open->op_file = NULL;
5265                 status = nfserr_bad_stateid;
5266                 if (nfsd4_is_deleg_cur(open))
5267                         goto out;
5268         }
5269
5270         if (!stp) {
5271                 stp = init_open_stateid(fp, open);
5272                 if (!open->op_stp)
5273                         new_stp = true;
5274         }
5275
5276         /*
5277          * OPEN the file, or upgrade an existing OPEN.
5278          * If truncate fails, the OPEN fails.
5279          *
5280          * stp is already locked.
5281          */
5282         if (!new_stp) {
5283                 /* Stateid was found, this is an OPEN upgrade */
5284                 status = nfs4_upgrade_open(rqstp, fp, current_fh, stp, open);
5285                 if (status) {
5286                         mutex_unlock(&stp->st_mutex);
5287                         goto out;
5288                 }
5289         } else {
5290                 status = nfs4_get_vfs_file(rqstp, fp, current_fh, stp, open);
5291                 if (status) {
5292                         stp->st_stid.sc_type = NFS4_CLOSED_STID;
5293                         release_open_stateid(stp);
5294                         mutex_unlock(&stp->st_mutex);
5295                         goto out;
5296                 }
5297
5298                 stp->st_clnt_odstate = find_or_hash_clnt_odstate(fp,
5299                                                         open->op_odstate);
5300                 if (stp->st_clnt_odstate == open->op_odstate)
5301                         open->op_odstate = NULL;
5302         }
5303
5304         nfs4_inc_and_copy_stateid(&open->op_stateid, &stp->st_stid);
5305         mutex_unlock(&stp->st_mutex);
5306
5307         if (nfsd4_has_session(&resp->cstate)) {
5308                 if (open->op_deleg_want & NFS4_SHARE_WANT_NO_DELEG) {
5309                         open->op_delegate_type = NFS4_OPEN_DELEGATE_NONE_EXT;
5310                         open->op_why_no_deleg = WND4_NOT_WANTED;
5311                         goto nodeleg;
5312                 }
5313         }
5314
5315         /*
5316         * Attempt to hand out a delegation. No error return, because the
5317         * OPEN succeeds even if we fail.
5318         */
5319         nfs4_open_delegation(current_fh, open, stp);
5320 nodeleg:
5321         status = nfs_ok;
5322         trace_nfsd_open(&stp->st_stid.sc_stateid);
5323 out:
5324         /* 4.1 client trying to upgrade/downgrade delegation? */
5325         if (open->op_delegate_type == NFS4_OPEN_DELEGATE_NONE && dp &&
5326             open->op_deleg_want)
5327                 nfsd4_deleg_xgrade_none_ext(open, dp);
5328
5329         if (fp)
5330                 put_nfs4_file(fp);
5331         if (status == 0 && open->op_claim_type == NFS4_OPEN_CLAIM_PREVIOUS)
5332                 open->op_openowner->oo_flags |= NFS4_OO_CONFIRMED;
5333         /*
5334         * To finish the open response, we just need to set the rflags.
5335         */
5336         open->op_rflags = NFS4_OPEN_RESULT_LOCKTYPE_POSIX;
5337         if (nfsd4_has_session(&resp->cstate))
5338                 open->op_rflags |= NFS4_OPEN_RESULT_MAY_NOTIFY_LOCK;
5339         else if (!(open->op_openowner->oo_flags & NFS4_OO_CONFIRMED))
5340                 open->op_rflags |= NFS4_OPEN_RESULT_CONFIRM;
5341
5342         if (dp)
5343                 nfs4_put_stid(&dp->dl_stid);
5344         if (stp)
5345                 nfs4_put_stid(&stp->st_stid);
5346
5347         return status;
5348 }
5349
5350 void nfsd4_cleanup_open_state(struct nfsd4_compound_state *cstate,
5351                               struct nfsd4_open *open)
5352 {
5353         if (open->op_openowner) {
5354                 struct nfs4_stateowner *so = &open->op_openowner->oo_owner;
5355
5356                 nfsd4_cstate_assign_replay(cstate, so);
5357                 nfs4_put_stateowner(so);
5358         }
5359         if (open->op_file)
5360                 kmem_cache_free(file_slab, open->op_file);
5361         if (open->op_stp)
5362                 nfs4_put_stid(&open->op_stp->st_stid);
5363         if (open->op_odstate)
5364                 kmem_cache_free(odstate_slab, open->op_odstate);
5365 }
5366
5367 __be32
5368 nfsd4_renew(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
5369             union nfsd4_op_u *u)
5370 {
5371         clientid_t *clid = &u->renew;
5372         struct nfs4_client *clp;
5373         __be32 status;
5374         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
5375
5376         trace_nfsd_clid_renew(clid);
5377         status = set_client(clid, cstate, nn);
5378         if (status)
5379                 return status;
5380         clp = cstate->clp;
5381         if (!list_empty(&clp->cl_delegations)
5382                         && clp->cl_cb_state != NFSD4_CB_UP)
5383                 return nfserr_cb_path_down;
5384         return nfs_ok;
5385 }
5386
5387 void
5388 nfsd4_end_grace(struct nfsd_net *nn)
5389 {
5390         /* do nothing if grace period already ended */
5391         if (nn->grace_ended)
5392                 return;
5393
5394         trace_nfsd_grace_complete(nn);
5395         nn->grace_ended = true;
5396         /*
5397          * If the server goes down again right now, an NFSv4
5398          * client will still be allowed to reclaim after it comes back up,
5399          * even if it hasn't yet had a chance to reclaim state this time.
5400          *
5401          */
5402         nfsd4_record_grace_done(nn);
5403         /*
5404          * At this point, NFSv4 clients can still reclaim.  But if the
5405          * server crashes, any that have not yet reclaimed will be out
5406          * of luck on the next boot.
5407          *
5408          * (NFSv4.1+ clients are considered to have reclaimed once they
5409          * call RECLAIM_COMPLETE.  NFSv4.0 clients are considered to
5410          * have reclaimed after their first OPEN.)
5411          */
5412         locks_end_grace(&nn->nfsd4_manager);
5413         /*
5414          * At this point, and once lockd and/or any other containers
5415          * exit their grace period, further reclaims will fail and
5416          * regular locking can resume.
5417          */
5418 }
5419
5420 /*
5421  * If we've waited a lease period but there are still clients trying to
5422  * reclaim, wait a little longer to give them a chance to finish.
5423  */
5424 static bool clients_still_reclaiming(struct nfsd_net *nn)
5425 {
5426         time64_t double_grace_period_end = nn->boot_time +
5427                                            2 * nn->nfsd4_lease;
5428
5429         if (nn->track_reclaim_completes &&
5430                         atomic_read(&nn->nr_reclaim_complete) ==
5431                         nn->reclaim_str_hashtbl_size)
5432                 return false;
5433         if (!nn->somebody_reclaimed)
5434                 return false;
5435         nn->somebody_reclaimed = false;
5436         /*
5437          * If we've given them *two* lease times to reclaim, and they're
5438          * still not done, give up:
5439          */
5440         if (ktime_get_boottime_seconds() > double_grace_period_end)
5441                 return false;
5442         return true;
5443 }
5444
5445 struct laundry_time {
5446         time64_t cutoff;
5447         time64_t new_timeo;
5448 };
5449
5450 static bool state_expired(struct laundry_time *lt, time64_t last_refresh)
5451 {
5452         time64_t time_remaining;
5453
5454         if (last_refresh < lt->cutoff)
5455                 return true;
5456         time_remaining = last_refresh - lt->cutoff;
5457         lt->new_timeo = min(lt->new_timeo, time_remaining);
5458         return false;
5459 }
5460
5461 static time64_t
5462 nfs4_laundromat(struct nfsd_net *nn)
5463 {
5464         struct nfs4_client *clp;
5465         struct nfs4_openowner *oo;
5466         struct nfs4_delegation *dp;
5467         struct nfs4_ol_stateid *stp;
5468         struct nfsd4_blocked_lock *nbl;
5469         struct list_head *pos, *next, reaplist;
5470         struct laundry_time lt = {
5471                 .cutoff = ktime_get_boottime_seconds() - nn->nfsd4_lease,
5472                 .new_timeo = nn->nfsd4_lease
5473         };
5474         struct nfs4_cpntf_state *cps;
5475         copy_stateid_t *cps_t;
5476         int i;
5477
5478         if (clients_still_reclaiming(nn)) {
5479                 lt.new_timeo = 0;
5480                 goto out;
5481         }
5482         nfsd4_end_grace(nn);
5483         INIT_LIST_HEAD(&reaplist);
5484
5485         spin_lock(&nn->s2s_cp_lock);
5486         idr_for_each_entry(&nn->s2s_cp_stateids, cps_t, i) {
5487                 cps = container_of(cps_t, struct nfs4_cpntf_state, cp_stateid);
5488                 if (cps->cp_stateid.sc_type == NFS4_COPYNOTIFY_STID &&
5489                                 state_expired(&lt, cps->cpntf_time))
5490                         _free_cpntf_state_locked(nn, cps);
5491         }
5492         spin_unlock(&nn->s2s_cp_lock);
5493
5494         spin_lock(&nn->client_lock);
5495         list_for_each_safe(pos, next, &nn->client_lru) {
5496                 clp = list_entry(pos, struct nfs4_client, cl_lru);
5497                 if (!state_expired(&lt, clp->cl_time))
5498                         break;
5499                 if (mark_client_expired_locked(clp)) {
5500                         trace_nfsd_clid_expired(&clp->cl_clientid);
5501                         continue;
5502                 }
5503                 list_add(&clp->cl_lru, &reaplist);
5504         }
5505         spin_unlock(&nn->client_lock);
5506         list_for_each_safe(pos, next, &reaplist) {
5507                 clp = list_entry(pos, struct nfs4_client, cl_lru);
5508                 trace_nfsd_clid_purged(&clp->cl_clientid);
5509                 list_del_init(&clp->cl_lru);
5510                 expire_client(clp);
5511         }
5512         spin_lock(&state_lock);
5513         list_for_each_safe(pos, next, &nn->del_recall_lru) {
5514                 dp = list_entry (pos, struct nfs4_delegation, dl_recall_lru);
5515                 if (!state_expired(&lt, dp->dl_time))
5516                         break;
5517                 WARN_ON(!unhash_delegation_locked(dp));
5518                 list_add(&dp->dl_recall_lru, &reaplist);
5519         }
5520         spin_unlock(&state_lock);
5521         while (!list_empty(&reaplist)) {
5522                 dp = list_first_entry(&reaplist, struct nfs4_delegation,
5523                                         dl_recall_lru);
5524                 list_del_init(&dp->dl_recall_lru);
5525                 revoke_delegation(dp);
5526         }
5527
5528         spin_lock(&nn->client_lock);
5529         while (!list_empty(&nn->close_lru)) {
5530                 oo = list_first_entry(&nn->close_lru, struct nfs4_openowner,
5531                                         oo_close_lru);
5532                 if (!state_expired(&lt, oo->oo_time))
5533                         break;
5534                 list_del_init(&oo->oo_close_lru);
5535                 stp = oo->oo_last_closed_stid;
5536                 oo->oo_last_closed_stid = NULL;
5537                 spin_unlock(&nn->client_lock);
5538                 nfs4_put_stid(&stp->st_stid);
5539                 spin_lock(&nn->client_lock);
5540         }
5541         spin_unlock(&nn->client_lock);
5542
5543         /*
5544          * It's possible for a client to try and acquire an already held lock
5545          * that is being held for a long time, and then lose interest in it.
5546          * So, we clean out any un-revisited request after a lease period
5547          * under the assumption that the client is no longer interested.
5548          *
5549          * RFC5661, sec. 9.6 states that the client must not rely on getting
5550          * notifications and must continue to poll for locks, even when the
5551          * server supports them. Thus this shouldn't lead to clients blocking
5552          * indefinitely once the lock does become free.
5553          */
5554         BUG_ON(!list_empty(&reaplist));
5555         spin_lock(&nn->blocked_locks_lock);
5556         while (!list_empty(&nn->blocked_locks_lru)) {
5557                 nbl = list_first_entry(&nn->blocked_locks_lru,
5558                                         struct nfsd4_blocked_lock, nbl_lru);
5559                 if (!state_expired(&lt, nbl->nbl_time))
5560                         break;
5561                 list_move(&nbl->nbl_lru, &reaplist);
5562                 list_del_init(&nbl->nbl_list);
5563         }
5564         spin_unlock(&nn->blocked_locks_lock);
5565
5566         while (!list_empty(&reaplist)) {
5567                 nbl = list_first_entry(&reaplist,
5568                                         struct nfsd4_blocked_lock, nbl_lru);
5569                 list_del_init(&nbl->nbl_lru);
5570                 free_blocked_lock(nbl);
5571         }
5572 out:
5573         return max_t(time64_t, lt.new_timeo, NFSD_LAUNDROMAT_MINTIMEOUT);
5574 }
5575
5576 static struct workqueue_struct *laundry_wq;
5577 static void laundromat_main(struct work_struct *);
5578
5579 static void
5580 laundromat_main(struct work_struct *laundry)
5581 {
5582         time64_t t;
5583         struct delayed_work *dwork = to_delayed_work(laundry);
5584         struct nfsd_net *nn = container_of(dwork, struct nfsd_net,
5585                                            laundromat_work);
5586
5587         t = nfs4_laundromat(nn);
5588         queue_delayed_work(laundry_wq, &nn->laundromat_work, t*HZ);
5589 }
5590
5591 static inline __be32 nfs4_check_fh(struct svc_fh *fhp, struct nfs4_stid *stp)
5592 {
5593         if (!fh_match(&fhp->fh_handle, &stp->sc_file->fi_fhandle))
5594                 return nfserr_bad_stateid;
5595         return nfs_ok;
5596 }
5597
5598 static
5599 __be32 nfs4_check_openmode(struct nfs4_ol_stateid *stp, int flags)
5600 {
5601         __be32 status = nfserr_openmode;
5602
5603         /* For lock stateid's, we test the parent open, not the lock: */
5604         if (stp->st_openstp)
5605                 stp = stp->st_openstp;
5606         if ((flags & WR_STATE) && !access_permit_write(stp))
5607                 goto out;
5608         if ((flags & RD_STATE) && !access_permit_read(stp))
5609                 goto out;
5610         status = nfs_ok;
5611 out:
5612         return status;
5613 }
5614
5615 static inline __be32
5616 check_special_stateids(struct net *net, svc_fh *current_fh, stateid_t *stateid, int flags)
5617 {
5618         if (ONE_STATEID(stateid) && (flags & RD_STATE))
5619                 return nfs_ok;
5620         else if (opens_in_grace(net)) {
5621                 /* Answer in remaining cases depends on existence of
5622                  * conflicting state; so we must wait out the grace period. */
5623                 return nfserr_grace;
5624         } else if (flags & WR_STATE)
5625                 return nfs4_share_conflict(current_fh,
5626                                 NFS4_SHARE_DENY_WRITE);
5627         else /* (flags & RD_STATE) && ZERO_STATEID(stateid) */
5628                 return nfs4_share_conflict(current_fh,
5629                                 NFS4_SHARE_DENY_READ);
5630 }
5631
5632 /*
5633  * Allow READ/WRITE during grace period on recovered state only for files
5634  * that are not able to provide mandatory locking.
5635  */
5636 static inline int
5637 grace_disallows_io(struct net *net, struct inode *inode)
5638 {
5639         return opens_in_grace(net) && mandatory_lock(inode);
5640 }
5641
5642 static __be32 check_stateid_generation(stateid_t *in, stateid_t *ref, bool has_session)
5643 {
5644         /*
5645          * When sessions are used the stateid generation number is ignored
5646          * when it is zero.
5647          */
5648         if (has_session && in->si_generation == 0)
5649                 return nfs_ok;
5650
5651         if (in->si_generation == ref->si_generation)
5652                 return nfs_ok;
5653
5654         /* If the client sends us a stateid from the future, it's buggy: */
5655         if (nfsd4_stateid_generation_after(in, ref))
5656                 return nfserr_bad_stateid;
5657         /*
5658          * However, we could see a stateid from the past, even from a
5659          * non-buggy client.  For example, if the client sends a lock
5660          * while some IO is outstanding, the lock may bump si_generation
5661          * while the IO is still in flight.  The client could avoid that
5662          * situation by waiting for responses on all the IO requests,
5663          * but better performance may result in retrying IO that
5664          * receives an old_stateid error if requests are rarely
5665          * reordered in flight:
5666          */
5667         return nfserr_old_stateid;
5668 }
5669
5670 static __be32 nfsd4_stid_check_stateid_generation(stateid_t *in, struct nfs4_stid *s, bool has_session)
5671 {
5672         __be32 ret;
5673
5674         spin_lock(&s->sc_lock);
5675         ret = nfsd4_verify_open_stid(s);
5676         if (ret == nfs_ok)
5677                 ret = check_stateid_generation(in, &s->sc_stateid, has_session);
5678         spin_unlock(&s->sc_lock);
5679         return ret;
5680 }
5681
5682 static __be32 nfsd4_check_openowner_confirmed(struct nfs4_ol_stateid *ols)
5683 {
5684         if (ols->st_stateowner->so_is_open_owner &&
5685             !(openowner(ols->st_stateowner)->oo_flags & NFS4_OO_CONFIRMED))
5686                 return nfserr_bad_stateid;
5687         return nfs_ok;
5688 }
5689
5690 static __be32 nfsd4_validate_stateid(struct nfs4_client *cl, stateid_t *stateid)
5691 {
5692         struct nfs4_stid *s;
5693         __be32 status = nfserr_bad_stateid;
5694
5695         if (ZERO_STATEID(stateid) || ONE_STATEID(stateid) ||
5696                 CLOSE_STATEID(stateid))
5697                 return status;
5698         if (!same_clid(&stateid->si_opaque.so_clid, &cl->cl_clientid))
5699                 return status;
5700         spin_lock(&cl->cl_lock);
5701         s = find_stateid_locked(cl, stateid);
5702         if (!s)
5703                 goto out_unlock;
5704         status = nfsd4_stid_check_stateid_generation(stateid, s, 1);
5705         if (status)
5706                 goto out_unlock;
5707         switch (s->sc_type) {
5708         case NFS4_DELEG_STID:
5709                 status = nfs_ok;
5710                 break;
5711         case NFS4_REVOKED_DELEG_STID:
5712                 status = nfserr_deleg_revoked;
5713                 break;
5714         case NFS4_OPEN_STID:
5715         case NFS4_LOCK_STID:
5716                 status = nfsd4_check_openowner_confirmed(openlockstateid(s));
5717                 break;
5718         default:
5719                 printk("unknown stateid type %x\n", s->sc_type);
5720                 fallthrough;
5721         case NFS4_CLOSED_STID:
5722         case NFS4_CLOSED_DELEG_STID:
5723                 status = nfserr_bad_stateid;
5724         }
5725 out_unlock:
5726         spin_unlock(&cl->cl_lock);
5727         return status;
5728 }
5729
5730 __be32
5731 nfsd4_lookup_stateid(struct nfsd4_compound_state *cstate,
5732                      stateid_t *stateid, unsigned char typemask,
5733                      struct nfs4_stid **s, struct nfsd_net *nn)
5734 {
5735         __be32 status;
5736         bool return_revoked = false;
5737
5738         /*
5739          *  only return revoked delegations if explicitly asked.
5740          *  otherwise we report revoked or bad_stateid status.
5741          */
5742         if (typemask & NFS4_REVOKED_DELEG_STID)
5743                 return_revoked = true;
5744         else if (typemask & NFS4_DELEG_STID)
5745                 typemask |= NFS4_REVOKED_DELEG_STID;
5746
5747         if (ZERO_STATEID(stateid) || ONE_STATEID(stateid) ||
5748                 CLOSE_STATEID(stateid))
5749                 return nfserr_bad_stateid;
5750         status = set_client(&stateid->si_opaque.so_clid, cstate, nn);
5751         if (status == nfserr_stale_clientid) {
5752                 if (cstate->session)
5753                         return nfserr_bad_stateid;
5754                 return nfserr_stale_stateid;
5755         }
5756         if (status)
5757                 return status;
5758         *s = find_stateid_by_type(cstate->clp, stateid, typemask);
5759         if (!*s)
5760                 return nfserr_bad_stateid;
5761         if (((*s)->sc_type == NFS4_REVOKED_DELEG_STID) && !return_revoked) {
5762                 nfs4_put_stid(*s);
5763                 if (cstate->minorversion)
5764                         return nfserr_deleg_revoked;
5765                 return nfserr_bad_stateid;
5766         }
5767         return nfs_ok;
5768 }
5769
5770 static struct nfsd_file *
5771 nfs4_find_file(struct nfs4_stid *s, int flags)
5772 {
5773         if (!s)
5774                 return NULL;
5775
5776         switch (s->sc_type) {
5777         case NFS4_DELEG_STID:
5778                 if (WARN_ON_ONCE(!s->sc_file->fi_deleg_file))
5779                         return NULL;
5780                 return nfsd_file_get(s->sc_file->fi_deleg_file);
5781         case NFS4_OPEN_STID:
5782         case NFS4_LOCK_STID:
5783                 if (flags & RD_STATE)
5784                         return find_readable_file(s->sc_file);
5785                 else
5786                         return find_writeable_file(s->sc_file);
5787         }
5788
5789         return NULL;
5790 }
5791
5792 static __be32
5793 nfs4_check_olstateid(struct nfs4_ol_stateid *ols, int flags)
5794 {
5795         __be32 status;
5796
5797         status = nfsd4_check_openowner_confirmed(ols);
5798         if (status)
5799                 return status;
5800         return nfs4_check_openmode(ols, flags);
5801 }
5802
5803 static __be32
5804 nfs4_check_file(struct svc_rqst *rqstp, struct svc_fh *fhp, struct nfs4_stid *s,
5805                 struct nfsd_file **nfp, int flags)
5806 {
5807         int acc = (flags & RD_STATE) ? NFSD_MAY_READ : NFSD_MAY_WRITE;
5808         struct nfsd_file *nf;
5809         __be32 status;
5810
5811         nf = nfs4_find_file(s, flags);
5812         if (nf) {
5813                 status = nfsd_permission(rqstp, fhp->fh_export, fhp->fh_dentry,
5814                                 acc | NFSD_MAY_OWNER_OVERRIDE);
5815                 if (status) {
5816                         nfsd_file_put(nf);
5817                         goto out;
5818                 }
5819         } else {
5820                 status = nfsd_file_acquire(rqstp, fhp, acc, &nf);
5821                 if (status)
5822                         return status;
5823         }
5824         *nfp = nf;
5825 out:
5826         return status;
5827 }
5828 static void
5829 _free_cpntf_state_locked(struct nfsd_net *nn, struct nfs4_cpntf_state *cps)
5830 {
5831         WARN_ON_ONCE(cps->cp_stateid.sc_type != NFS4_COPYNOTIFY_STID);
5832         if (!refcount_dec_and_test(&cps->cp_stateid.sc_count))
5833                 return;
5834         list_del(&cps->cp_list);
5835         idr_remove(&nn->s2s_cp_stateids,
5836                    cps->cp_stateid.stid.si_opaque.so_id);
5837         kfree(cps);
5838 }
5839 /*
5840  * A READ from an inter server to server COPY will have a
5841  * copy stateid. Look up the copy notify stateid from the
5842  * idr structure and take a reference on it.
5843  */
5844 __be32 manage_cpntf_state(struct nfsd_net *nn, stateid_t *st,
5845                           struct nfs4_client *clp,
5846                           struct nfs4_cpntf_state **cps)
5847 {
5848         copy_stateid_t *cps_t;
5849         struct nfs4_cpntf_state *state = NULL;
5850
5851         if (st->si_opaque.so_clid.cl_id != nn->s2s_cp_cl_id)
5852                 return nfserr_bad_stateid;
5853         spin_lock(&nn->s2s_cp_lock);
5854         cps_t = idr_find(&nn->s2s_cp_stateids, st->si_opaque.so_id);
5855         if (cps_t) {
5856                 state = container_of(cps_t, struct nfs4_cpntf_state,
5857                                      cp_stateid);
5858                 if (state->cp_stateid.sc_type != NFS4_COPYNOTIFY_STID) {
5859                         state = NULL;
5860                         goto unlock;
5861                 }
5862                 if (!clp)
5863                         refcount_inc(&state->cp_stateid.sc_count);
5864                 else
5865                         _free_cpntf_state_locked(nn, state);
5866         }
5867 unlock:
5868         spin_unlock(&nn->s2s_cp_lock);
5869         if (!state)
5870                 return nfserr_bad_stateid;
5871         if (!clp && state)
5872                 *cps = state;
5873         return 0;
5874 }
5875
5876 static __be32 find_cpntf_state(struct nfsd_net *nn, stateid_t *st,
5877                                struct nfs4_stid **stid)
5878 {
5879         __be32 status;
5880         struct nfs4_cpntf_state *cps = NULL;
5881         struct nfs4_client *found;
5882
5883         status = manage_cpntf_state(nn, st, NULL, &cps);
5884         if (status)
5885                 return status;
5886
5887         cps->cpntf_time = ktime_get_boottime_seconds();
5888
5889         status = nfserr_expired;
5890         found = lookup_clientid(&cps->cp_p_clid, true, nn);
5891         if (!found)
5892                 goto out;
5893
5894         *stid = find_stateid_by_type(found, &cps->cp_p_stateid,
5895                         NFS4_DELEG_STID|NFS4_OPEN_STID|NFS4_LOCK_STID);
5896         if (*stid)
5897                 status = nfs_ok;
5898         else
5899                 status = nfserr_bad_stateid;
5900
5901         put_client_renew(found);
5902 out:
5903         nfs4_put_cpntf_state(nn, cps);
5904         return status;
5905 }
5906
5907 void nfs4_put_cpntf_state(struct nfsd_net *nn, struct nfs4_cpntf_state *cps)
5908 {
5909         spin_lock(&nn->s2s_cp_lock);
5910         _free_cpntf_state_locked(nn, cps);
5911         spin_unlock(&nn->s2s_cp_lock);
5912 }
5913
5914 /*
5915  * Checks for stateid operations
5916  */
5917 __be32
5918 nfs4_preprocess_stateid_op(struct svc_rqst *rqstp,
5919                 struct nfsd4_compound_state *cstate, struct svc_fh *fhp,
5920                 stateid_t *stateid, int flags, struct nfsd_file **nfp,
5921                 struct nfs4_stid **cstid)
5922 {
5923         struct inode *ino = d_inode(fhp->fh_dentry);
5924         struct net *net = SVC_NET(rqstp);
5925         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
5926         struct nfs4_stid *s = NULL;
5927         __be32 status;
5928
5929         if (nfp)
5930                 *nfp = NULL;
5931
5932         if (grace_disallows_io(net, ino))
5933                 return nfserr_grace;
5934
5935         if (ZERO_STATEID(stateid) || ONE_STATEID(stateid)) {
5936                 status = check_special_stateids(net, fhp, stateid, flags);
5937                 goto done;
5938         }
5939
5940         status = nfsd4_lookup_stateid(cstate, stateid,
5941                                 NFS4_DELEG_STID|NFS4_OPEN_STID|NFS4_LOCK_STID,
5942                                 &s, nn);
5943         if (status == nfserr_bad_stateid)
5944                 status = find_cpntf_state(nn, stateid, &s);
5945         if (status)
5946                 return status;
5947         status = nfsd4_stid_check_stateid_generation(stateid, s,
5948                         nfsd4_has_session(cstate));
5949         if (status)
5950                 goto out;
5951
5952         switch (s->sc_type) {
5953         case NFS4_DELEG_STID:
5954                 status = nfs4_check_delegmode(delegstateid(s), flags);
5955                 break;
5956         case NFS4_OPEN_STID:
5957         case NFS4_LOCK_STID:
5958                 status = nfs4_check_olstateid(openlockstateid(s), flags);
5959                 break;
5960         default:
5961                 status = nfserr_bad_stateid;
5962                 break;
5963         }
5964         if (status)
5965                 goto out;
5966         status = nfs4_check_fh(fhp, s);
5967
5968 done:
5969         if (status == nfs_ok && nfp)
5970                 status = nfs4_check_file(rqstp, fhp, s, nfp, flags);
5971 out:
5972         if (s) {
5973                 if (!status && cstid)
5974                         *cstid = s;
5975                 else
5976                         nfs4_put_stid(s);
5977         }
5978         return status;
5979 }
5980
5981 /*
5982  * Test if the stateid is valid
5983  */
5984 __be32
5985 nfsd4_test_stateid(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
5986                    union nfsd4_op_u *u)
5987 {
5988         struct nfsd4_test_stateid *test_stateid = &u->test_stateid;
5989         struct nfsd4_test_stateid_id *stateid;
5990         struct nfs4_client *cl = cstate->clp;
5991
5992         list_for_each_entry(stateid, &test_stateid->ts_stateid_list, ts_id_list)
5993                 stateid->ts_id_status =
5994                         nfsd4_validate_stateid(cl, &stateid->ts_id_stateid);
5995
5996         return nfs_ok;
5997 }
5998
5999 static __be32
6000 nfsd4_free_lock_stateid(stateid_t *stateid, struct nfs4_stid *s)
6001 {
6002         struct nfs4_ol_stateid *stp = openlockstateid(s);
6003         __be32 ret;
6004
6005         ret = nfsd4_lock_ol_stateid(stp);
6006         if (ret)
6007                 goto out_put_stid;
6008
6009         ret = check_stateid_generation(stateid, &s->sc_stateid, 1);
6010         if (ret)
6011                 goto out;
6012
6013         ret = nfserr_locks_held;
6014         if (check_for_locks(stp->st_stid.sc_file,
6015                             lockowner(stp->st_stateowner)))
6016                 goto out;
6017
6018         release_lock_stateid(stp);
6019         ret = nfs_ok;
6020
6021 out:
6022         mutex_unlock(&stp->st_mutex);
6023 out_put_stid:
6024         nfs4_put_stid(s);
6025         return ret;
6026 }
6027
6028 __be32
6029 nfsd4_free_stateid(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
6030                    union nfsd4_op_u *u)
6031 {
6032         struct nfsd4_free_stateid *free_stateid = &u->free_stateid;
6033         stateid_t *stateid = &free_stateid->fr_stateid;
6034         struct nfs4_stid *s;
6035         struct nfs4_delegation *dp;
6036         struct nfs4_client *cl = cstate->clp;
6037         __be32 ret = nfserr_bad_stateid;
6038
6039         spin_lock(&cl->cl_lock);
6040         s = find_stateid_locked(cl, stateid);
6041         if (!s)
6042                 goto out_unlock;
6043         spin_lock(&s->sc_lock);
6044         switch (s->sc_type) {
6045         case NFS4_DELEG_STID:
6046                 ret = nfserr_locks_held;
6047                 break;
6048         case NFS4_OPEN_STID:
6049                 ret = check_stateid_generation(stateid, &s->sc_stateid, 1);
6050                 if (ret)
6051                         break;
6052                 ret = nfserr_locks_held;
6053                 break;
6054         case NFS4_LOCK_STID:
6055                 spin_unlock(&s->sc_lock);
6056                 refcount_inc(&s->sc_count);
6057                 spin_unlock(&cl->cl_lock);
6058                 ret = nfsd4_free_lock_stateid(stateid, s);
6059                 goto out;
6060         case NFS4_REVOKED_DELEG_STID:
6061                 spin_unlock(&s->sc_lock);
6062                 dp = delegstateid(s);
6063                 list_del_init(&dp->dl_recall_lru);
6064                 spin_unlock(&cl->cl_lock);
6065                 nfs4_put_stid(s);
6066                 ret = nfs_ok;
6067                 goto out;
6068         /* Default falls through and returns nfserr_bad_stateid */
6069         }
6070         spin_unlock(&s->sc_lock);
6071 out_unlock:
6072         spin_unlock(&cl->cl_lock);
6073 out:
6074         return ret;
6075 }
6076
6077 static inline int
6078 setlkflg (int type)
6079 {
6080         return (type == NFS4_READW_LT || type == NFS4_READ_LT) ?
6081                 RD_STATE : WR_STATE;
6082 }
6083
6084 static __be32 nfs4_seqid_op_checks(struct nfsd4_compound_state *cstate, stateid_t *stateid, u32 seqid, struct nfs4_ol_stateid *stp)
6085 {
6086         struct svc_fh *current_fh = &cstate->current_fh;
6087         struct nfs4_stateowner *sop = stp->st_stateowner;
6088         __be32 status;
6089
6090         status = nfsd4_check_seqid(cstate, sop, seqid);
6091         if (status)
6092                 return status;
6093         status = nfsd4_lock_ol_stateid(stp);
6094         if (status != nfs_ok)
6095                 return status;
6096         status = check_stateid_generation(stateid, &stp->st_stid.sc_stateid, nfsd4_has_session(cstate));
6097         if (status == nfs_ok)
6098                 status = nfs4_check_fh(current_fh, &stp->st_stid);
6099         if (status != nfs_ok)
6100                 mutex_unlock(&stp->st_mutex);
6101         return status;
6102 }
6103
6104 /* 
6105  * Checks for sequence id mutating operations. 
6106  */
6107 static __be32
6108 nfs4_preprocess_seqid_op(struct nfsd4_compound_state *cstate, u32 seqid,
6109                          stateid_t *stateid, char typemask,
6110                          struct nfs4_ol_stateid **stpp,
6111                          struct nfsd_net *nn)
6112 {
6113         __be32 status;
6114         struct nfs4_stid *s;
6115         struct nfs4_ol_stateid *stp = NULL;
6116
6117         trace_nfsd_preprocess(seqid, stateid);
6118
6119         *stpp = NULL;
6120         status = nfsd4_lookup_stateid(cstate, stateid, typemask, &s, nn);
6121         if (status)
6122                 return status;
6123         stp = openlockstateid(s);
6124         nfsd4_cstate_assign_replay(cstate, stp->st_stateowner);
6125
6126         status = nfs4_seqid_op_checks(cstate, stateid, seqid, stp);
6127         if (!status)
6128                 *stpp = stp;
6129         else
6130                 nfs4_put_stid(&stp->st_stid);
6131         return status;
6132 }
6133
6134 static __be32 nfs4_preprocess_confirmed_seqid_op(struct nfsd4_compound_state *cstate, u32 seqid,
6135                                                  stateid_t *stateid, struct nfs4_ol_stateid **stpp, struct nfsd_net *nn)
6136 {
6137         __be32 status;
6138         struct nfs4_openowner *oo;
6139         struct nfs4_ol_stateid *stp;
6140
6141         status = nfs4_preprocess_seqid_op(cstate, seqid, stateid,
6142                                                 NFS4_OPEN_STID, &stp, nn);
6143         if (status)
6144                 return status;
6145         oo = openowner(stp->st_stateowner);
6146         if (!(oo->oo_flags & NFS4_OO_CONFIRMED)) {
6147                 mutex_unlock(&stp->st_mutex);
6148                 nfs4_put_stid(&stp->st_stid);
6149                 return nfserr_bad_stateid;
6150         }
6151         *stpp = stp;
6152         return nfs_ok;
6153 }
6154
6155 __be32
6156 nfsd4_open_confirm(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
6157                    union nfsd4_op_u *u)
6158 {
6159         struct nfsd4_open_confirm *oc = &u->open_confirm;
6160         __be32 status;
6161         struct nfs4_openowner *oo;
6162         struct nfs4_ol_stateid *stp;
6163         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
6164
6165         dprintk("NFSD: nfsd4_open_confirm on file %pd\n",
6166                         cstate->current_fh.fh_dentry);
6167
6168         status = fh_verify(rqstp, &cstate->current_fh, S_IFREG, 0);
6169         if (status)
6170                 return status;
6171
6172         status = nfs4_preprocess_seqid_op(cstate,
6173                                         oc->oc_seqid, &oc->oc_req_stateid,
6174                                         NFS4_OPEN_STID, &stp, nn);
6175         if (status)
6176                 goto out;
6177         oo = openowner(stp->st_stateowner);
6178         status = nfserr_bad_stateid;
6179         if (oo->oo_flags & NFS4_OO_CONFIRMED) {
6180                 mutex_unlock(&stp->st_mutex);
6181                 goto put_stateid;
6182         }
6183         oo->oo_flags |= NFS4_OO_CONFIRMED;
6184         nfs4_inc_and_copy_stateid(&oc->oc_resp_stateid, &stp->st_stid);
6185         mutex_unlock(&stp->st_mutex);
6186         trace_nfsd_open_confirm(oc->oc_seqid, &stp->st_stid.sc_stateid);
6187         nfsd4_client_record_create(oo->oo_owner.so_client);
6188         status = nfs_ok;
6189 put_stateid:
6190         nfs4_put_stid(&stp->st_stid);
6191 out:
6192         nfsd4_bump_seqid(cstate, status);
6193         return status;
6194 }
6195
6196 static inline void nfs4_stateid_downgrade_bit(struct nfs4_ol_stateid *stp, u32 access)
6197 {
6198         if (!test_access(access, stp))
6199                 return;
6200         nfs4_file_put_access(stp->st_stid.sc_file, access);
6201         clear_access(access, stp);
6202 }
6203
6204 static inline void nfs4_stateid_downgrade(struct nfs4_ol_stateid *stp, u32 to_access)
6205 {
6206         switch (to_access) {
6207         case NFS4_SHARE_ACCESS_READ:
6208                 nfs4_stateid_downgrade_bit(stp, NFS4_SHARE_ACCESS_WRITE);
6209                 nfs4_stateid_downgrade_bit(stp, NFS4_SHARE_ACCESS_BOTH);
6210                 break;
6211         case NFS4_SHARE_ACCESS_WRITE:
6212                 nfs4_stateid_downgrade_bit(stp, NFS4_SHARE_ACCESS_READ);
6213                 nfs4_stateid_downgrade_bit(stp, NFS4_SHARE_ACCESS_BOTH);
6214                 break;
6215         case NFS4_SHARE_ACCESS_BOTH:
6216                 break;
6217         default:
6218                 WARN_ON_ONCE(1);
6219         }
6220 }
6221
6222 __be32
6223 nfsd4_open_downgrade(struct svc_rqst *rqstp,
6224                      struct nfsd4_compound_state *cstate, union nfsd4_op_u *u)
6225 {
6226         struct nfsd4_open_downgrade *od = &u->open_downgrade;
6227         __be32 status;
6228         struct nfs4_ol_stateid *stp;
6229         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
6230
6231         dprintk("NFSD: nfsd4_open_downgrade on file %pd\n", 
6232                         cstate->current_fh.fh_dentry);
6233
6234         /* We don't yet support WANT bits: */
6235         if (od->od_deleg_want)
6236                 dprintk("NFSD: %s: od_deleg_want=0x%x ignored\n", __func__,
6237                         od->od_deleg_want);
6238
6239         status = nfs4_preprocess_confirmed_seqid_op(cstate, od->od_seqid,
6240                                         &od->od_stateid, &stp, nn);
6241         if (status)
6242                 goto out; 
6243         status = nfserr_inval;
6244         if (!test_access(od->od_share_access, stp)) {
6245                 dprintk("NFSD: access not a subset of current bitmap: 0x%hhx, input access=%08x\n",
6246                         stp->st_access_bmap, od->od_share_access);
6247                 goto put_stateid;
6248         }
6249         if (!test_deny(od->od_share_deny, stp)) {
6250                 dprintk("NFSD: deny not a subset of current bitmap: 0x%hhx, input deny=%08x\n",
6251                         stp->st_deny_bmap, od->od_share_deny);
6252                 goto put_stateid;
6253         }
6254         nfs4_stateid_downgrade(stp, od->od_share_access);
6255         reset_union_bmap_deny(od->od_share_deny, stp);
6256         nfs4_inc_and_copy_stateid(&od->od_stateid, &stp->st_stid);
6257         status = nfs_ok;
6258 put_stateid:
6259         mutex_unlock(&stp->st_mutex);
6260         nfs4_put_stid(&stp->st_stid);
6261 out:
6262         nfsd4_bump_seqid(cstate, status);
6263         return status;
6264 }
6265
6266 static void nfsd4_close_open_stateid(struct nfs4_ol_stateid *s)
6267 {
6268         struct nfs4_client *clp = s->st_stid.sc_client;
6269         bool unhashed;
6270         LIST_HEAD(reaplist);
6271
6272         spin_lock(&clp->cl_lock);
6273         unhashed = unhash_open_stateid(s, &reaplist);
6274
6275         if (clp->cl_minorversion) {
6276                 if (unhashed)
6277                         put_ol_stateid_locked(s, &reaplist);
6278                 spin_unlock(&clp->cl_lock);
6279                 free_ol_stateid_reaplist(&reaplist);
6280         } else {
6281                 spin_unlock(&clp->cl_lock);
6282                 free_ol_stateid_reaplist(&reaplist);
6283                 if (unhashed)
6284                         move_to_close_lru(s, clp->net);
6285         }
6286 }
6287
6288 /*
6289  * nfs4_unlock_state() called after encode
6290  */
6291 __be32
6292 nfsd4_close(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
6293                 union nfsd4_op_u *u)
6294 {
6295         struct nfsd4_close *close = &u->close;
6296         __be32 status;
6297         struct nfs4_ol_stateid *stp;
6298         struct net *net = SVC_NET(rqstp);
6299         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
6300
6301         dprintk("NFSD: nfsd4_close on file %pd\n", 
6302                         cstate->current_fh.fh_dentry);
6303
6304         status = nfs4_preprocess_seqid_op(cstate, close->cl_seqid,
6305                                         &close->cl_stateid,
6306                                         NFS4_OPEN_STID|NFS4_CLOSED_STID,
6307                                         &stp, nn);
6308         nfsd4_bump_seqid(cstate, status);
6309         if (status)
6310                 goto out; 
6311
6312         stp->st_stid.sc_type = NFS4_CLOSED_STID;
6313
6314         /*
6315          * Technically we don't _really_ have to increment or copy it, since
6316          * it should just be gone after this operation and we clobber the
6317          * copied value below, but we continue to do so here just to ensure
6318          * that racing ops see that there was a state change.
6319          */
6320         nfs4_inc_and_copy_stateid(&close->cl_stateid, &stp->st_stid);
6321
6322         nfsd4_close_open_stateid(stp);
6323         mutex_unlock(&stp->st_mutex);
6324
6325         /* v4.1+ suggests that we send a special stateid in here, since the
6326          * clients should just ignore this anyway. Since this is not useful
6327          * for v4.0 clients either, we set it to the special close_stateid
6328          * universally.
6329          *
6330          * See RFC5661 section 18.2.4, and RFC7530 section 16.2.5
6331          */
6332         memcpy(&close->cl_stateid, &close_stateid, sizeof(close->cl_stateid));
6333
6334         /* put reference from nfs4_preprocess_seqid_op */
6335         nfs4_put_stid(&stp->st_stid);
6336 out:
6337         return status;
6338 }
6339
6340 __be32
6341 nfsd4_delegreturn(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
6342                   union nfsd4_op_u *u)
6343 {
6344         struct nfsd4_delegreturn *dr = &u->delegreturn;
6345         struct nfs4_delegation *dp;
6346         stateid_t *stateid = &dr->dr_stateid;
6347         struct nfs4_stid *s;
6348         __be32 status;
6349         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
6350
6351         if ((status = fh_verify(rqstp, &cstate->current_fh, S_IFREG, 0)))
6352                 return status;
6353
6354         status = nfsd4_lookup_stateid(cstate, stateid, NFS4_DELEG_STID, &s, nn);
6355         if (status)
6356                 goto out;
6357         dp = delegstateid(s);
6358         status = nfsd4_stid_check_stateid_generation(stateid, &dp->dl_stid, nfsd4_has_session(cstate));
6359         if (status)
6360                 goto put_stateid;
6361
6362         destroy_delegation(dp);
6363 put_stateid:
6364         nfs4_put_stid(&dp->dl_stid);
6365 out:
6366         return status;
6367 }
6368
6369 /* last octet in a range */
6370 static inline u64
6371 last_byte_offset(u64 start, u64 len)
6372 {
6373         u64 end;
6374
6375         WARN_ON_ONCE(!len);
6376         end = start + len;
6377         return end > start ? end - 1: NFS4_MAX_UINT64;
6378 }
6379
6380 /*
6381  * TODO: Linux file offsets are _signed_ 64-bit quantities, which means that
6382  * we can't properly handle lock requests that go beyond the (2^63 - 1)-th
6383  * byte, because of sign extension problems.  Since NFSv4 calls for 64-bit
6384  * locking, this prevents us from being completely protocol-compliant.  The
6385  * real solution to this problem is to start using unsigned file offsets in
6386  * the VFS, but this is a very deep change!
6387  */
6388 static inline void
6389 nfs4_transform_lock_offset(struct file_lock *lock)
6390 {
6391         if (lock->fl_start < 0)
6392                 lock->fl_start = OFFSET_MAX;
6393         if (lock->fl_end < 0)
6394                 lock->fl_end = OFFSET_MAX;
6395 }
6396
6397 static fl_owner_t
6398 nfsd4_fl_get_owner(fl_owner_t owner)
6399 {
6400         struct nfs4_lockowner *lo = (struct nfs4_lockowner *)owner;
6401
6402         nfs4_get_stateowner(&lo->lo_owner);
6403         return owner;
6404 }
6405
6406 static void
6407 nfsd4_fl_put_owner(fl_owner_t owner)
6408 {
6409         struct nfs4_lockowner *lo = (struct nfs4_lockowner *)owner;
6410
6411         if (lo)
6412                 nfs4_put_stateowner(&lo->lo_owner);
6413 }
6414
6415 static void
6416 nfsd4_lm_notify(struct file_lock *fl)
6417 {
6418         struct nfs4_lockowner           *lo = (struct nfs4_lockowner *)fl->fl_owner;
6419         struct net                      *net = lo->lo_owner.so_client->net;
6420         struct nfsd_net                 *nn = net_generic(net, nfsd_net_id);
6421         struct nfsd4_blocked_lock       *nbl = container_of(fl,
6422                                                 struct nfsd4_blocked_lock, nbl_lock);
6423         bool queue = false;
6424
6425         /* An empty list means that something else is going to be using it */
6426         spin_lock(&nn->blocked_locks_lock);
6427         if (!list_empty(&nbl->nbl_list)) {
6428                 list_del_init(&nbl->nbl_list);
6429                 list_del_init(&nbl->nbl_lru);
6430                 queue = true;
6431         }
6432         spin_unlock(&nn->blocked_locks_lock);
6433
6434         if (queue)
6435                 nfsd4_run_cb(&nbl->nbl_cb);
6436 }
6437
6438 static const struct lock_manager_operations nfsd_posix_mng_ops  = {
6439         .lm_notify = nfsd4_lm_notify,
6440         .lm_get_owner = nfsd4_fl_get_owner,
6441         .lm_put_owner = nfsd4_fl_put_owner,
6442 };
6443
6444 static inline void
6445 nfs4_set_lock_denied(struct file_lock *fl, struct nfsd4_lock_denied *deny)
6446 {
6447         struct nfs4_lockowner *lo;
6448
6449         if (fl->fl_lmops == &nfsd_posix_mng_ops) {
6450                 lo = (struct nfs4_lockowner *) fl->fl_owner;
6451                 xdr_netobj_dup(&deny->ld_owner, &lo->lo_owner.so_owner,
6452                                                 GFP_KERNEL);
6453                 if (!deny->ld_owner.data)
6454                         /* We just don't care that much */
6455                         goto nevermind;
6456                 deny->ld_clientid = lo->lo_owner.so_client->cl_clientid;
6457         } else {
6458 nevermind:
6459                 deny->ld_owner.len = 0;
6460                 deny->ld_owner.data = NULL;
6461                 deny->ld_clientid.cl_boot = 0;
6462                 deny->ld_clientid.cl_id = 0;
6463         }
6464         deny->ld_start = fl->fl_start;
6465         deny->ld_length = NFS4_MAX_UINT64;
6466         if (fl->fl_end != NFS4_MAX_UINT64)
6467                 deny->ld_length = fl->fl_end - fl->fl_start + 1;        
6468         deny->ld_type = NFS4_READ_LT;
6469         if (fl->fl_type != F_RDLCK)
6470                 deny->ld_type = NFS4_WRITE_LT;
6471 }
6472
6473 static struct nfs4_lockowner *
6474 find_lockowner_str_locked(struct nfs4_client *clp, struct xdr_netobj *owner)
6475 {
6476         unsigned int strhashval = ownerstr_hashval(owner);
6477         struct nfs4_stateowner *so;
6478
6479         lockdep_assert_held(&clp->cl_lock);
6480
6481         list_for_each_entry(so, &clp->cl_ownerstr_hashtbl[strhashval],
6482                             so_strhash) {
6483                 if (so->so_is_open_owner)
6484                         continue;
6485                 if (same_owner_str(so, owner))
6486                         return lockowner(nfs4_get_stateowner(so));
6487         }
6488         return NULL;
6489 }
6490
6491 static struct nfs4_lockowner *
6492 find_lockowner_str(struct nfs4_client *clp, struct xdr_netobj *owner)
6493 {
6494         struct nfs4_lockowner *lo;
6495
6496         spin_lock(&clp->cl_lock);
6497         lo = find_lockowner_str_locked(clp, owner);
6498         spin_unlock(&clp->cl_lock);
6499         return lo;
6500 }
6501
6502 static void nfs4_unhash_lockowner(struct nfs4_stateowner *sop)
6503 {
6504         unhash_lockowner_locked(lockowner(sop));
6505 }
6506
6507 static void nfs4_free_lockowner(struct nfs4_stateowner *sop)
6508 {
6509         struct nfs4_lockowner *lo = lockowner(sop);
6510
6511         kmem_cache_free(lockowner_slab, lo);
6512 }
6513
6514 static const struct nfs4_stateowner_operations lockowner_ops = {
6515         .so_unhash =    nfs4_unhash_lockowner,
6516         .so_free =      nfs4_free_lockowner,
6517 };
6518
6519 /*
6520  * Alloc a lock owner structure.
6521  * Called in nfsd4_lock - therefore, OPEN and OPEN_CONFIRM (if needed) has 
6522  * occurred. 
6523  *
6524  * strhashval = ownerstr_hashval
6525  */
6526 static struct nfs4_lockowner *
6527 alloc_init_lock_stateowner(unsigned int strhashval, struct nfs4_client *clp,
6528                            struct nfs4_ol_stateid *open_stp,
6529                            struct nfsd4_lock *lock)
6530 {
6531         struct nfs4_lockowner *lo, *ret;
6532
6533         lo = alloc_stateowner(lockowner_slab, &lock->lk_new_owner, clp);
6534         if (!lo)
6535                 return NULL;
6536         INIT_LIST_HEAD(&lo->lo_blocked);
6537         INIT_LIST_HEAD(&lo->lo_owner.so_stateids);
6538         lo->lo_owner.so_is_open_owner = 0;
6539         lo->lo_owner.so_seqid = lock->lk_new_lock_seqid;
6540         lo->lo_owner.so_ops = &lockowner_ops;
6541         spin_lock(&clp->cl_lock);
6542         ret = find_lockowner_str_locked(clp, &lock->lk_new_owner);
6543         if (ret == NULL) {
6544                 list_add(&lo->lo_owner.so_strhash,
6545                          &clp->cl_ownerstr_hashtbl[strhashval]);
6546                 ret = lo;
6547         } else
6548                 nfs4_free_stateowner(&lo->lo_owner);
6549
6550         spin_unlock(&clp->cl_lock);
6551         return ret;
6552 }
6553
6554 static struct nfs4_ol_stateid *
6555 find_lock_stateid(const struct nfs4_lockowner *lo,
6556                   const struct nfs4_ol_stateid *ost)
6557 {
6558         struct nfs4_ol_stateid *lst;
6559
6560         lockdep_assert_held(&ost->st_stid.sc_client->cl_lock);
6561
6562         /* If ost is not hashed, ost->st_locks will not be valid */
6563         if (!nfs4_ol_stateid_unhashed(ost))
6564                 list_for_each_entry(lst, &ost->st_locks, st_locks) {
6565                         if (lst->st_stateowner == &lo->lo_owner) {
6566                                 refcount_inc(&lst->st_stid.sc_count);
6567                                 return lst;
6568                         }
6569                 }
6570         return NULL;
6571 }
6572
6573 static struct nfs4_ol_stateid *
6574 init_lock_stateid(struct nfs4_ol_stateid *stp, struct nfs4_lockowner *lo,
6575                   struct nfs4_file *fp, struct inode *inode,
6576                   struct nfs4_ol_stateid *open_stp)
6577 {
6578         struct nfs4_client *clp = lo->lo_owner.so_client;
6579         struct nfs4_ol_stateid *retstp;
6580
6581         mutex_init(&stp->st_mutex);
6582         mutex_lock_nested(&stp->st_mutex, OPEN_STATEID_MUTEX);
6583 retry:
6584         spin_lock(&clp->cl_lock);
6585         if (nfs4_ol_stateid_unhashed(open_stp))
6586                 goto out_close;
6587         retstp = find_lock_stateid(lo, open_stp);
6588         if (retstp)
6589                 goto out_found;
6590         refcount_inc(&stp->st_stid.sc_count);
6591         stp->st_stid.sc_type = NFS4_LOCK_STID;
6592         stp->st_stateowner = nfs4_get_stateowner(&lo->lo_owner);
6593         get_nfs4_file(fp);
6594         stp->st_stid.sc_file = fp;
6595         stp->st_access_bmap = 0;
6596         stp->st_deny_bmap = open_stp->st_deny_bmap;
6597         stp->st_openstp = open_stp;
6598         spin_lock(&fp->fi_lock);
6599         list_add(&stp->st_locks, &open_stp->st_locks);
6600         list_add(&stp->st_perstateowner, &lo->lo_owner.so_stateids);
6601         list_add(&stp->st_perfile, &fp->fi_stateids);
6602         spin_unlock(&fp->fi_lock);
6603         spin_unlock(&clp->cl_lock);
6604         return stp;
6605 out_found:
6606         spin_unlock(&clp->cl_lock);
6607         if (nfsd4_lock_ol_stateid(retstp) != nfs_ok) {
6608                 nfs4_put_stid(&retstp->st_stid);
6609                 goto retry;
6610         }
6611         /* To keep mutex tracking happy */
6612         mutex_unlock(&stp->st_mutex);
6613         return retstp;
6614 out_close:
6615         spin_unlock(&clp->cl_lock);
6616         mutex_unlock(&stp->st_mutex);
6617         return NULL;
6618 }
6619
6620 static struct nfs4_ol_stateid *
6621 find_or_create_lock_stateid(struct nfs4_lockowner *lo, struct nfs4_file *fi,
6622                             struct inode *inode, struct nfs4_ol_stateid *ost,
6623                             bool *new)
6624 {
6625         struct nfs4_stid *ns = NULL;
6626         struct nfs4_ol_stateid *lst;
6627         struct nfs4_openowner *oo = openowner(ost->st_stateowner);
6628         struct nfs4_client *clp = oo->oo_owner.so_client;
6629
6630         *new = false;
6631         spin_lock(&clp->cl_lock);
6632         lst = find_lock_stateid(lo, ost);
6633         spin_unlock(&clp->cl_lock);
6634         if (lst != NULL) {
6635                 if (nfsd4_lock_ol_stateid(lst) == nfs_ok)
6636                         goto out;
6637                 nfs4_put_stid(&lst->st_stid);
6638         }
6639         ns = nfs4_alloc_stid(clp, stateid_slab, nfs4_free_lock_stateid);
6640         if (ns == NULL)
6641                 return NULL;
6642
6643         lst = init_lock_stateid(openlockstateid(ns), lo, fi, inode, ost);
6644         if (lst == openlockstateid(ns))
6645                 *new = true;
6646         else
6647                 nfs4_put_stid(ns);
6648 out:
6649         return lst;
6650 }
6651
6652 static int
6653 check_lock_length(u64 offset, u64 length)
6654 {
6655         return ((length == 0) || ((length != NFS4_MAX_UINT64) &&
6656                 (length > ~offset)));
6657 }
6658
6659 static void get_lock_access(struct nfs4_ol_stateid *lock_stp, u32 access)
6660 {
6661         struct nfs4_file *fp = lock_stp->st_stid.sc_file;
6662
6663         lockdep_assert_held(&fp->fi_lock);
6664
6665         if (test_access(access, lock_stp))
6666                 return;
6667         __nfs4_file_get_access(fp, access);
6668         set_access(access, lock_stp);
6669 }
6670
6671 static __be32
6672 lookup_or_create_lock_state(struct nfsd4_compound_state *cstate,
6673                             struct nfs4_ol_stateid *ost,
6674                             struct nfsd4_lock *lock,
6675                             struct nfs4_ol_stateid **plst, bool *new)
6676 {
6677         __be32 status;
6678         struct nfs4_file *fi = ost->st_stid.sc_file;
6679         struct nfs4_openowner *oo = openowner(ost->st_stateowner);
6680         struct nfs4_client *cl = oo->oo_owner.so_client;
6681         struct inode *inode = d_inode(cstate->current_fh.fh_dentry);
6682         struct nfs4_lockowner *lo;
6683         struct nfs4_ol_stateid *lst;
6684         unsigned int strhashval;
6685
6686         lo = find_lockowner_str(cl, &lock->lk_new_owner);
6687         if (!lo) {
6688                 strhashval = ownerstr_hashval(&lock->lk_new_owner);
6689                 lo = alloc_init_lock_stateowner(strhashval, cl, ost, lock);
6690                 if (lo == NULL)
6691                         return nfserr_jukebox;
6692         } else {
6693                 /* with an existing lockowner, seqids must be the same */
6694                 status = nfserr_bad_seqid;
6695                 if (!cstate->minorversion &&
6696                     lock->lk_new_lock_seqid != lo->lo_owner.so_seqid)
6697                         goto out;
6698         }
6699
6700         lst = find_or_create_lock_stateid(lo, fi, inode, ost, new);
6701         if (lst == NULL) {
6702                 status = nfserr_jukebox;
6703                 goto out;
6704         }
6705
6706         status = nfs_ok;
6707         *plst = lst;
6708 out:
6709         nfs4_put_stateowner(&lo->lo_owner);
6710         return status;
6711 }
6712
6713 /*
6714  *  LOCK operation 
6715  */
6716 __be32
6717 nfsd4_lock(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
6718            union nfsd4_op_u *u)
6719 {
6720         struct nfsd4_lock *lock = &u->lock;
6721         struct nfs4_openowner *open_sop = NULL;
6722         struct nfs4_lockowner *lock_sop = NULL;
6723         struct nfs4_ol_stateid *lock_stp = NULL;
6724         struct nfs4_ol_stateid *open_stp = NULL;
6725         struct nfs4_file *fp;
6726         struct nfsd_file *nf = NULL;
6727         struct nfsd4_blocked_lock *nbl = NULL;
6728         struct file_lock *file_lock = NULL;
6729         struct file_lock *conflock = NULL;
6730         __be32 status = 0;
6731         int lkflg;
6732         int err;
6733         bool new = false;
6734         unsigned char fl_type;
6735         unsigned int fl_flags = FL_POSIX;
6736         struct net *net = SVC_NET(rqstp);
6737         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
6738
6739         dprintk("NFSD: nfsd4_lock: start=%Ld length=%Ld\n",
6740                 (long long) lock->lk_offset,
6741                 (long long) lock->lk_length);
6742
6743         if (check_lock_length(lock->lk_offset, lock->lk_length))
6744                  return nfserr_inval;
6745
6746         if ((status = fh_verify(rqstp, &cstate->current_fh,
6747                                 S_IFREG, NFSD_MAY_LOCK))) {
6748                 dprintk("NFSD: nfsd4_lock: permission denied!\n");
6749                 return status;
6750         }
6751
6752         if (lock->lk_is_new) {
6753                 if (nfsd4_has_session(cstate))
6754                         /* See rfc 5661 18.10.3: given clientid is ignored: */
6755                         memcpy(&lock->lk_new_clientid,
6756                                 &cstate->clp->cl_clientid,
6757                                 sizeof(clientid_t));
6758
6759                 /* validate and update open stateid and open seqid */
6760                 status = nfs4_preprocess_confirmed_seqid_op(cstate,
6761                                         lock->lk_new_open_seqid,
6762                                         &lock->lk_new_open_stateid,
6763                                         &open_stp, nn);
6764                 if (status)
6765                         goto out;
6766                 mutex_unlock(&open_stp->st_mutex);
6767                 open_sop = openowner(open_stp->st_stateowner);
6768                 status = nfserr_bad_stateid;
6769                 if (!same_clid(&open_sop->oo_owner.so_client->cl_clientid,
6770                                                 &lock->lk_new_clientid))
6771                         goto out;
6772                 status = lookup_or_create_lock_state(cstate, open_stp, lock,
6773                                                         &lock_stp, &new);
6774         } else {
6775                 status = nfs4_preprocess_seqid_op(cstate,
6776                                        lock->lk_old_lock_seqid,
6777                                        &lock->lk_old_lock_stateid,
6778                                        NFS4_LOCK_STID, &lock_stp, nn);
6779         }
6780         if (status)
6781                 goto out;
6782         lock_sop = lockowner(lock_stp->st_stateowner);
6783
6784         lkflg = setlkflg(lock->lk_type);
6785         status = nfs4_check_openmode(lock_stp, lkflg);
6786         if (status)
6787                 goto out;
6788
6789         status = nfserr_grace;
6790         if (locks_in_grace(net) && !lock->lk_reclaim)
6791                 goto out;
6792         status = nfserr_no_grace;
6793         if (!locks_in_grace(net) && lock->lk_reclaim)
6794                 goto out;
6795
6796         fp = lock_stp->st_stid.sc_file;
6797         switch (lock->lk_type) {
6798                 case NFS4_READW_LT:
6799                         if (nfsd4_has_session(cstate))
6800                                 fl_flags |= FL_SLEEP;
6801                         fallthrough;
6802                 case NFS4_READ_LT:
6803                         spin_lock(&fp->fi_lock);
6804                         nf = find_readable_file_locked(fp);
6805                         if (nf)
6806                                 get_lock_access(lock_stp, NFS4_SHARE_ACCESS_READ);
6807                         spin_unlock(&fp->fi_lock);
6808                         fl_type = F_RDLCK;
6809                         break;
6810                 case NFS4_WRITEW_LT:
6811                         if (nfsd4_has_session(cstate))
6812                                 fl_flags |= FL_SLEEP;
6813                         fallthrough;
6814                 case NFS4_WRITE_LT:
6815                         spin_lock(&fp->fi_lock);
6816                         nf = find_writeable_file_locked(fp);
6817                         if (nf)
6818                                 get_lock_access(lock_stp, NFS4_SHARE_ACCESS_WRITE);
6819                         spin_unlock(&fp->fi_lock);
6820                         fl_type = F_WRLCK;
6821                         break;
6822                 default:
6823                         status = nfserr_inval;
6824                 goto out;
6825         }
6826
6827         if (!nf) {
6828                 status = nfserr_openmode;
6829                 goto out;
6830         }
6831
6832         nbl = find_or_allocate_block(lock_sop, &fp->fi_fhandle, nn);
6833         if (!nbl) {
6834                 dprintk("NFSD: %s: unable to allocate block!\n", __func__);
6835                 status = nfserr_jukebox;
6836                 goto out;
6837         }
6838
6839         file_lock = &nbl->nbl_lock;
6840         file_lock->fl_type = fl_type;
6841         file_lock->fl_owner = (fl_owner_t)lockowner(nfs4_get_stateowner(&lock_sop->lo_owner));
6842         file_lock->fl_pid = current->tgid;
6843         file_lock->fl_file = nf->nf_file;
6844         file_lock->fl_flags = fl_flags;
6845         file_lock->fl_lmops = &nfsd_posix_mng_ops;
6846         file_lock->fl_start = lock->lk_offset;
6847         file_lock->fl_end = last_byte_offset(lock->lk_offset, lock->lk_length);
6848         nfs4_transform_lock_offset(file_lock);
6849
6850         conflock = locks_alloc_lock();
6851         if (!conflock) {
6852                 dprintk("NFSD: %s: unable to allocate lock!\n", __func__);
6853                 status = nfserr_jukebox;
6854                 goto out;
6855         }
6856
6857         if (fl_flags & FL_SLEEP) {
6858                 nbl->nbl_time = ktime_get_boottime_seconds();
6859                 spin_lock(&nn->blocked_locks_lock);
6860                 list_add_tail(&nbl->nbl_list, &lock_sop->lo_blocked);
6861                 list_add_tail(&nbl->nbl_lru, &nn->blocked_locks_lru);
6862                 spin_unlock(&nn->blocked_locks_lock);
6863         }
6864
6865         err = vfs_lock_file(nf->nf_file, F_SETLK, file_lock, conflock);
6866         switch (err) {
6867         case 0: /* success! */
6868                 nfs4_inc_and_copy_stateid(&lock->lk_resp_stateid, &lock_stp->st_stid);
6869                 status = 0;
6870                 if (lock->lk_reclaim)
6871                         nn->somebody_reclaimed = true;
6872                 break;
6873         case FILE_LOCK_DEFERRED:
6874                 nbl = NULL;
6875                 fallthrough;
6876         case -EAGAIN:           /* conflock holds conflicting lock */
6877                 status = nfserr_denied;
6878                 dprintk("NFSD: nfsd4_lock: conflicting lock found!\n");
6879                 nfs4_set_lock_denied(conflock, &lock->lk_denied);
6880                 break;
6881         case -EDEADLK:
6882                 status = nfserr_deadlock;
6883                 break;
6884         default:
6885                 dprintk("NFSD: nfsd4_lock: vfs_lock_file() failed! status %d\n",err);
6886                 status = nfserrno(err);
6887                 break;
6888         }
6889 out:
6890         if (nbl) {
6891                 /* dequeue it if we queued it before */
6892                 if (fl_flags & FL_SLEEP) {
6893                         spin_lock(&nn->blocked_locks_lock);
6894                         list_del_init(&nbl->nbl_list);
6895                         list_del_init(&nbl->nbl_lru);
6896                         spin_unlock(&nn->blocked_locks_lock);
6897                 }
6898                 free_blocked_lock(nbl);
6899         }
6900         if (nf)
6901                 nfsd_file_put(nf);
6902         if (lock_stp) {
6903                 /* Bump seqid manually if the 4.0 replay owner is openowner */
6904                 if (cstate->replay_owner &&
6905                     cstate->replay_owner != &lock_sop->lo_owner &&
6906                     seqid_mutating_err(ntohl(status)))
6907                         lock_sop->lo_owner.so_seqid++;
6908
6909                 /*
6910                  * If this is a new, never-before-used stateid, and we are
6911                  * returning an error, then just go ahead and release it.
6912                  */
6913                 if (status && new)
6914                         release_lock_stateid(lock_stp);
6915
6916                 mutex_unlock(&lock_stp->st_mutex);
6917
6918                 nfs4_put_stid(&lock_stp->st_stid);
6919         }
6920         if (open_stp)
6921                 nfs4_put_stid(&open_stp->st_stid);
6922         nfsd4_bump_seqid(cstate, status);
6923         if (conflock)
6924                 locks_free_lock(conflock);
6925         return status;
6926 }
6927
6928 /*
6929  * The NFSv4 spec allows a client to do a LOCKT without holding an OPEN,
6930  * so we do a temporary open here just to get an open file to pass to
6931  * vfs_test_lock.  (Arguably perhaps test_lock should be done with an
6932  * inode operation.)
6933  */
6934 static __be32 nfsd_test_lock(struct svc_rqst *rqstp, struct svc_fh *fhp, struct file_lock *lock)
6935 {
6936         struct nfsd_file *nf;
6937         __be32 err;
6938
6939         err = nfsd_file_acquire(rqstp, fhp, NFSD_MAY_READ, &nf);
6940         if (err)
6941                 return err;
6942         fh_lock(fhp); /* to block new leases till after test_lock: */
6943         err = nfserrno(nfsd_open_break_lease(fhp->fh_dentry->d_inode,
6944                                                         NFSD_MAY_READ));
6945         if (err)
6946                 goto out;
6947         err = nfserrno(vfs_test_lock(nf->nf_file, lock));
6948 out:
6949         fh_unlock(fhp);
6950         nfsd_file_put(nf);
6951         return err;
6952 }
6953
6954 /*
6955  * LOCKT operation
6956  */
6957 __be32
6958 nfsd4_lockt(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
6959             union nfsd4_op_u *u)
6960 {
6961         struct nfsd4_lockt *lockt = &u->lockt;
6962         struct file_lock *file_lock = NULL;
6963         struct nfs4_lockowner *lo = NULL;
6964         __be32 status;
6965         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
6966
6967         if (locks_in_grace(SVC_NET(rqstp)))
6968                 return nfserr_grace;
6969
6970         if (check_lock_length(lockt->lt_offset, lockt->lt_length))
6971                  return nfserr_inval;
6972
6973         if (!nfsd4_has_session(cstate)) {
6974                 status = set_client(&lockt->lt_clientid, cstate, nn);
6975                 if (status)
6976                         goto out;
6977         }
6978
6979         if ((status = fh_verify(rqstp, &cstate->current_fh, S_IFREG, 0)))
6980                 goto out;
6981
6982         file_lock = locks_alloc_lock();
6983         if (!file_lock) {
6984                 dprintk("NFSD: %s: unable to allocate lock!\n", __func__);
6985                 status = nfserr_jukebox;
6986                 goto out;
6987         }
6988
6989         switch (lockt->lt_type) {
6990                 case NFS4_READ_LT:
6991                 case NFS4_READW_LT:
6992                         file_lock->fl_type = F_RDLCK;
6993                         break;
6994                 case NFS4_WRITE_LT:
6995                 case NFS4_WRITEW_LT:
6996                         file_lock->fl_type = F_WRLCK;
6997                         break;
6998                 default:
6999                         dprintk("NFSD: nfs4_lockt: bad lock type!\n");
7000                         status = nfserr_inval;
7001                         goto out;
7002         }
7003
7004         lo = find_lockowner_str(cstate->clp, &lockt->lt_owner);
7005         if (lo)
7006                 file_lock->fl_owner = (fl_owner_t)lo;
7007         file_lock->fl_pid = current->tgid;
7008         file_lock->fl_flags = FL_POSIX;
7009
7010         file_lock->fl_start = lockt->lt_offset;
7011         file_lock->fl_end = last_byte_offset(lockt->lt_offset, lockt->lt_length);
7012
7013         nfs4_transform_lock_offset(file_lock);
7014
7015         status = nfsd_test_lock(rqstp, &cstate->current_fh, file_lock);
7016         if (status)
7017                 goto out;
7018
7019         if (file_lock->fl_type != F_UNLCK) {
7020                 status = nfserr_denied;
7021                 nfs4_set_lock_denied(file_lock, &lockt->lt_denied);
7022         }
7023 out:
7024         if (lo)
7025                 nfs4_put_stateowner(&lo->lo_owner);
7026         if (file_lock)
7027                 locks_free_lock(file_lock);
7028         return status;
7029 }
7030
7031 __be32
7032 nfsd4_locku(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
7033             union nfsd4_op_u *u)
7034 {
7035         struct nfsd4_locku *locku = &u->locku;
7036         struct nfs4_ol_stateid *stp;
7037         struct nfsd_file *nf = NULL;
7038         struct file_lock *file_lock = NULL;
7039         __be32 status;
7040         int err;
7041         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
7042
7043         dprintk("NFSD: nfsd4_locku: start=%Ld length=%Ld\n",
7044                 (long long) locku->lu_offset,
7045                 (long long) locku->lu_length);
7046
7047         if (check_lock_length(locku->lu_offset, locku->lu_length))
7048                  return nfserr_inval;
7049
7050         status = nfs4_preprocess_seqid_op(cstate, locku->lu_seqid,
7051                                         &locku->lu_stateid, NFS4_LOCK_STID,
7052                                         &stp, nn);
7053         if (status)
7054                 goto out;
7055         nf = find_any_file(stp->st_stid.sc_file);
7056         if (!nf) {
7057                 status = nfserr_lock_range;
7058                 goto put_stateid;
7059         }
7060         file_lock = locks_alloc_lock();
7061         if (!file_lock) {
7062                 dprintk("NFSD: %s: unable to allocate lock!\n", __func__);
7063                 status = nfserr_jukebox;
7064                 goto put_file;
7065         }
7066
7067         file_lock->fl_type = F_UNLCK;
7068         file_lock->fl_owner = (fl_owner_t)lockowner(nfs4_get_stateowner(stp->st_stateowner));
7069         file_lock->fl_pid = current->tgid;
7070         file_lock->fl_file = nf->nf_file;
7071         file_lock->fl_flags = FL_POSIX;
7072         file_lock->fl_lmops = &nfsd_posix_mng_ops;
7073         file_lock->fl_start = locku->lu_offset;
7074
7075         file_lock->fl_end = last_byte_offset(locku->lu_offset,
7076                                                 locku->lu_length);
7077         nfs4_transform_lock_offset(file_lock);
7078
7079         err = vfs_lock_file(nf->nf_file, F_SETLK, file_lock, NULL);
7080         if (err) {
7081                 dprintk("NFSD: nfs4_locku: vfs_lock_file failed!\n");
7082                 goto out_nfserr;
7083         }
7084         nfs4_inc_and_copy_stateid(&locku->lu_stateid, &stp->st_stid);
7085 put_file:
7086         nfsd_file_put(nf);
7087 put_stateid:
7088         mutex_unlock(&stp->st_mutex);
7089         nfs4_put_stid(&stp->st_stid);
7090 out:
7091         nfsd4_bump_seqid(cstate, status);
7092         if (file_lock)
7093                 locks_free_lock(file_lock);
7094         return status;
7095
7096 out_nfserr:
7097         status = nfserrno(err);
7098         goto put_file;
7099 }
7100
7101 /*
7102  * returns
7103  *      true:  locks held by lockowner
7104  *      false: no locks held by lockowner
7105  */
7106 static bool
7107 check_for_locks(struct nfs4_file *fp, struct nfs4_lockowner *lowner)
7108 {
7109         struct file_lock *fl;
7110         int status = false;
7111         struct nfsd_file *nf = find_any_file(fp);
7112         struct inode *inode;
7113         struct file_lock_context *flctx;
7114
7115         if (!nf) {
7116                 /* Any valid lock stateid should have some sort of access */
7117                 WARN_ON_ONCE(1);
7118                 return status;
7119         }
7120
7121         inode = locks_inode(nf->nf_file);
7122         flctx = inode->i_flctx;
7123
7124         if (flctx && !list_empty_careful(&flctx->flc_posix)) {
7125                 spin_lock(&flctx->flc_lock);
7126                 list_for_each_entry(fl, &flctx->flc_posix, fl_list) {
7127                         if (fl->fl_owner == (fl_owner_t)lowner) {
7128                                 status = true;
7129                                 break;
7130                         }
7131                 }
7132                 spin_unlock(&flctx->flc_lock);
7133         }
7134         nfsd_file_put(nf);
7135         return status;
7136 }
7137
7138 __be32
7139 nfsd4_release_lockowner(struct svc_rqst *rqstp,
7140                         struct nfsd4_compound_state *cstate,
7141                         union nfsd4_op_u *u)
7142 {
7143         struct nfsd4_release_lockowner *rlockowner = &u->release_lockowner;
7144         clientid_t *clid = &rlockowner->rl_clientid;
7145         struct nfs4_stateowner *sop;
7146         struct nfs4_lockowner *lo = NULL;
7147         struct nfs4_ol_stateid *stp;
7148         struct xdr_netobj *owner = &rlockowner->rl_owner;
7149         unsigned int hashval = ownerstr_hashval(owner);
7150         __be32 status;
7151         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
7152         struct nfs4_client *clp;
7153         LIST_HEAD (reaplist);
7154
7155         dprintk("nfsd4_release_lockowner clientid: (%08x/%08x):\n",
7156                 clid->cl_boot, clid->cl_id);
7157
7158         status = set_client(clid, cstate, nn);
7159         if (status)
7160                 return status;
7161
7162         clp = cstate->clp;
7163         /* Find the matching lock stateowner */
7164         spin_lock(&clp->cl_lock);
7165         list_for_each_entry(sop, &clp->cl_ownerstr_hashtbl[hashval],
7166                             so_strhash) {
7167
7168                 if (sop->so_is_open_owner || !same_owner_str(sop, owner))
7169                         continue;
7170
7171                 /* see if there are still any locks associated with it */
7172                 lo = lockowner(sop);
7173                 list_for_each_entry(stp, &sop->so_stateids, st_perstateowner) {
7174                         if (check_for_locks(stp->st_stid.sc_file, lo)) {
7175                                 status = nfserr_locks_held;
7176                                 spin_unlock(&clp->cl_lock);
7177                                 return status;
7178                         }
7179                 }
7180
7181                 nfs4_get_stateowner(sop);
7182                 break;
7183         }
7184         if (!lo) {
7185                 spin_unlock(&clp->cl_lock);
7186                 return status;
7187         }
7188
7189         unhash_lockowner_locked(lo);
7190         while (!list_empty(&lo->lo_owner.so_stateids)) {
7191                 stp = list_first_entry(&lo->lo_owner.so_stateids,
7192                                        struct nfs4_ol_stateid,
7193                                        st_perstateowner);
7194                 WARN_ON(!unhash_lock_stateid(stp));
7195                 put_ol_stateid_locked(stp, &reaplist);
7196         }
7197         spin_unlock(&clp->cl_lock);
7198         free_ol_stateid_reaplist(&reaplist);
7199         remove_blocked_locks(lo);
7200         nfs4_put_stateowner(&lo->lo_owner);
7201
7202         return status;
7203 }
7204
7205 static inline struct nfs4_client_reclaim *
7206 alloc_reclaim(void)
7207 {
7208         return kmalloc(sizeof(struct nfs4_client_reclaim), GFP_KERNEL);
7209 }
7210
7211 bool
7212 nfs4_has_reclaimed_state(struct xdr_netobj name, struct nfsd_net *nn)
7213 {
7214         struct nfs4_client_reclaim *crp;
7215
7216         crp = nfsd4_find_reclaim_client(name, nn);
7217         return (crp && crp->cr_clp);
7218 }
7219
7220 /*
7221  * failure => all reset bets are off, nfserr_no_grace...
7222  *
7223  * The caller is responsible for freeing name.data if NULL is returned (it
7224  * will be freed in nfs4_remove_reclaim_record in the normal case).
7225  */
7226 struct nfs4_client_reclaim *
7227 nfs4_client_to_reclaim(struct xdr_netobj name, struct xdr_netobj princhash,
7228                 struct nfsd_net *nn)
7229 {
7230         unsigned int strhashval;
7231         struct nfs4_client_reclaim *crp;
7232
7233         crp = alloc_reclaim();
7234         if (crp) {
7235                 strhashval = clientstr_hashval(name);
7236                 INIT_LIST_HEAD(&crp->cr_strhash);
7237                 list_add(&crp->cr_strhash, &nn->reclaim_str_hashtbl[strhashval]);
7238                 crp->cr_name.data = name.data;
7239                 crp->cr_name.len = name.len;
7240                 crp->cr_princhash.data = princhash.data;
7241                 crp->cr_princhash.len = princhash.len;
7242                 crp->cr_clp = NULL;
7243                 nn->reclaim_str_hashtbl_size++;
7244         }
7245         return crp;
7246 }
7247
7248 void
7249 nfs4_remove_reclaim_record(struct nfs4_client_reclaim *crp, struct nfsd_net *nn)
7250 {
7251         list_del(&crp->cr_strhash);
7252         kfree(crp->cr_name.data);
7253         kfree(crp->cr_princhash.data);
7254         kfree(crp);
7255         nn->reclaim_str_hashtbl_size--;
7256 }
7257
7258 void
7259 nfs4_release_reclaim(struct nfsd_net *nn)
7260 {
7261         struct nfs4_client_reclaim *crp = NULL;
7262         int i;
7263
7264         for (i = 0; i < CLIENT_HASH_SIZE; i++) {
7265                 while (!list_empty(&nn->reclaim_str_hashtbl[i])) {
7266                         crp = list_entry(nn->reclaim_str_hashtbl[i].next,
7267                                         struct nfs4_client_reclaim, cr_strhash);
7268                         nfs4_remove_reclaim_record(crp, nn);
7269                 }
7270         }
7271         WARN_ON_ONCE(nn->reclaim_str_hashtbl_size);
7272 }
7273
7274 /*
7275  * called from OPEN, CLAIM_PREVIOUS with a new clientid. */
7276 struct nfs4_client_reclaim *
7277 nfsd4_find_reclaim_client(struct xdr_netobj name, struct nfsd_net *nn)
7278 {
7279         unsigned int strhashval;
7280         struct nfs4_client_reclaim *crp = NULL;
7281
7282         strhashval = clientstr_hashval(name);
7283         list_for_each_entry(crp, &nn->reclaim_str_hashtbl[strhashval], cr_strhash) {
7284                 if (compare_blob(&crp->cr_name, &name) == 0) {
7285                         return crp;
7286                 }
7287         }
7288         return NULL;
7289 }
7290
7291 __be32
7292 nfs4_check_open_reclaim(struct nfs4_client *clp)
7293 {
7294         if (test_bit(NFSD4_CLIENT_RECLAIM_COMPLETE, &clp->cl_flags))
7295                 return nfserr_no_grace;
7296
7297         if (nfsd4_client_record_check(clp))
7298                 return nfserr_reclaim_bad;
7299
7300         return nfs_ok;
7301 }
7302
7303 /*
7304  * Since the lifetime of a delegation isn't limited to that of an open, a
7305  * client may quite reasonably hang on to a delegation as long as it has
7306  * the inode cached.  This becomes an obvious problem the first time a
7307  * client's inode cache approaches the size of the server's total memory.
7308  *
7309  * For now we avoid this problem by imposing a hard limit on the number
7310  * of delegations, which varies according to the server's memory size.
7311  */
7312 static void
7313 set_max_delegations(void)
7314 {
7315         /*
7316          * Allow at most 4 delegations per megabyte of RAM.  Quick
7317          * estimates suggest that in the worst case (where every delegation
7318          * is for a different inode), a delegation could take about 1.5K,
7319          * giving a worst case usage of about 6% of memory.
7320          */
7321         max_delegations = nr_free_buffer_pages() >> (20 - 2 - PAGE_SHIFT);
7322 }
7323
7324 static int nfs4_state_create_net(struct net *net)
7325 {
7326         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
7327         int i;
7328
7329         nn->conf_id_hashtbl = kmalloc_array(CLIENT_HASH_SIZE,
7330                                             sizeof(struct list_head),
7331                                             GFP_KERNEL);
7332         if (!nn->conf_id_hashtbl)
7333                 goto err;
7334         nn->unconf_id_hashtbl = kmalloc_array(CLIENT_HASH_SIZE,
7335                                               sizeof(struct list_head),
7336                                               GFP_KERNEL);
7337         if (!nn->unconf_id_hashtbl)
7338                 goto err_unconf_id;
7339         nn->sessionid_hashtbl = kmalloc_array(SESSION_HASH_SIZE,
7340                                               sizeof(struct list_head),
7341                                               GFP_KERNEL);
7342         if (!nn->sessionid_hashtbl)
7343                 goto err_sessionid;
7344
7345         for (i = 0; i < CLIENT_HASH_SIZE; i++) {
7346                 INIT_LIST_HEAD(&nn->conf_id_hashtbl[i]);
7347                 INIT_LIST_HEAD(&nn->unconf_id_hashtbl[i]);
7348         }
7349         for (i = 0; i < SESSION_HASH_SIZE; i++)
7350                 INIT_LIST_HEAD(&nn->sessionid_hashtbl[i]);
7351         nn->conf_name_tree = RB_ROOT;
7352         nn->unconf_name_tree = RB_ROOT;
7353         nn->boot_time = ktime_get_real_seconds();
7354         nn->grace_ended = false;
7355         nn->nfsd4_manager.block_opens = true;
7356         INIT_LIST_HEAD(&nn->nfsd4_manager.list);
7357         INIT_LIST_HEAD(&nn->client_lru);
7358         INIT_LIST_HEAD(&nn->close_lru);
7359         INIT_LIST_HEAD(&nn->del_recall_lru);
7360         spin_lock_init(&nn->client_lock);
7361         spin_lock_init(&nn->s2s_cp_lock);
7362         idr_init(&nn->s2s_cp_stateids);
7363
7364         spin_lock_init(&nn->blocked_locks_lock);
7365         INIT_LIST_HEAD(&nn->blocked_locks_lru);
7366
7367         INIT_DELAYED_WORK(&nn->laundromat_work, laundromat_main);
7368         get_net(net);
7369
7370         return 0;
7371
7372 err_sessionid:
7373         kfree(nn->unconf_id_hashtbl);
7374 err_unconf_id:
7375         kfree(nn->conf_id_hashtbl);
7376 err:
7377         return -ENOMEM;
7378 }
7379
7380 static void
7381 nfs4_state_destroy_net(struct net *net)
7382 {
7383         int i;
7384         struct nfs4_client *clp = NULL;
7385         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
7386
7387         for (i = 0; i < CLIENT_HASH_SIZE; i++) {
7388                 while (!list_empty(&nn->conf_id_hashtbl[i])) {
7389                         clp = list_entry(nn->conf_id_hashtbl[i].next, struct nfs4_client, cl_idhash);
7390                         destroy_client(clp);
7391                 }
7392         }
7393
7394         WARN_ON(!list_empty(&nn->blocked_locks_lru));
7395
7396         for (i = 0; i < CLIENT_HASH_SIZE; i++) {
7397                 while (!list_empty(&nn->unconf_id_hashtbl[i])) {
7398                         clp = list_entry(nn->unconf_id_hashtbl[i].next, struct nfs4_client, cl_idhash);
7399                         destroy_client(clp);
7400                 }
7401         }
7402
7403         kfree(nn->sessionid_hashtbl);
7404         kfree(nn->unconf_id_hashtbl);
7405         kfree(nn->conf_id_hashtbl);
7406         put_net(net);
7407 }
7408
7409 int
7410 nfs4_state_start_net(struct net *net)
7411 {
7412         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
7413         int ret;
7414
7415         ret = nfs4_state_create_net(net);
7416         if (ret)
7417                 return ret;
7418         locks_start_grace(net, &nn->nfsd4_manager);
7419         nfsd4_client_tracking_init(net);
7420         if (nn->track_reclaim_completes && nn->reclaim_str_hashtbl_size == 0)
7421                 goto skip_grace;
7422         printk(KERN_INFO "NFSD: starting %lld-second grace period (net %x)\n",
7423                nn->nfsd4_grace, net->ns.inum);
7424         trace_nfsd_grace_start(nn);
7425         queue_delayed_work(laundry_wq, &nn->laundromat_work, nn->nfsd4_grace * HZ);
7426         return 0;
7427
7428 skip_grace:
7429         printk(KERN_INFO "NFSD: no clients to reclaim, skipping NFSv4 grace period (net %x)\n",
7430                         net->ns.inum);
7431         queue_delayed_work(laundry_wq, &nn->laundromat_work, nn->nfsd4_lease * HZ);
7432         nfsd4_end_grace(nn);
7433         return 0;
7434 }
7435
7436 /* initialization to perform when the nfsd service is started: */
7437
7438 int
7439 nfs4_state_start(void)
7440 {
7441         int ret;
7442
7443         laundry_wq = alloc_workqueue("%s", WQ_UNBOUND, 0, "nfsd4");
7444         if (laundry_wq == NULL) {
7445                 ret = -ENOMEM;
7446                 goto out;
7447         }
7448         ret = nfsd4_create_callback_queue();
7449         if (ret)
7450                 goto out_free_laundry;
7451
7452         set_max_delegations();
7453         return 0;
7454
7455 out_free_laundry:
7456         destroy_workqueue(laundry_wq);
7457 out:
7458         return ret;
7459 }
7460
7461 void
7462 nfs4_state_shutdown_net(struct net *net)
7463 {
7464         struct nfs4_delegation *dp = NULL;
7465         struct list_head *pos, *next, reaplist;
7466         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
7467
7468         cancel_delayed_work_sync(&nn->laundromat_work);
7469         locks_end_grace(&nn->nfsd4_manager);
7470
7471         INIT_LIST_HEAD(&reaplist);
7472         spin_lock(&state_lock);
7473         list_for_each_safe(pos, next, &nn->del_recall_lru) {
7474                 dp = list_entry (pos, struct nfs4_delegation, dl_recall_lru);
7475                 WARN_ON(!unhash_delegation_locked(dp));
7476                 list_add(&dp->dl_recall_lru, &reaplist);
7477         }
7478         spin_unlock(&state_lock);
7479         list_for_each_safe(pos, next, &reaplist) {
7480                 dp = list_entry (pos, struct nfs4_delegation, dl_recall_lru);
7481                 list_del_init(&dp->dl_recall_lru);
7482                 destroy_unhashed_deleg(dp);
7483         }
7484
7485         nfsd4_client_tracking_exit(net);
7486         nfs4_state_destroy_net(net);
7487 }
7488
7489 void
7490 nfs4_state_shutdown(void)
7491 {
7492         destroy_workqueue(laundry_wq);
7493         nfsd4_destroy_callback_queue();
7494 }
7495
7496 static void
7497 get_stateid(struct nfsd4_compound_state *cstate, stateid_t *stateid)
7498 {
7499         if (HAS_CSTATE_FLAG(cstate, CURRENT_STATE_ID_FLAG) &&
7500             CURRENT_STATEID(stateid))
7501                 memcpy(stateid, &cstate->current_stateid, sizeof(stateid_t));
7502 }
7503
7504 static void
7505 put_stateid(struct nfsd4_compound_state *cstate, stateid_t *stateid)
7506 {
7507         if (cstate->minorversion) {
7508                 memcpy(&cstate->current_stateid, stateid, sizeof(stateid_t));
7509                 SET_CSTATE_FLAG(cstate, CURRENT_STATE_ID_FLAG);
7510         }
7511 }
7512
7513 void
7514 clear_current_stateid(struct nfsd4_compound_state *cstate)
7515 {
7516         CLEAR_CSTATE_FLAG(cstate, CURRENT_STATE_ID_FLAG);
7517 }
7518
7519 /*
7520  * functions to set current state id
7521  */
7522 void
7523 nfsd4_set_opendowngradestateid(struct nfsd4_compound_state *cstate,
7524                 union nfsd4_op_u *u)
7525 {
7526         put_stateid(cstate, &u->open_downgrade.od_stateid);
7527 }
7528
7529 void
7530 nfsd4_set_openstateid(struct nfsd4_compound_state *cstate,
7531                 union nfsd4_op_u *u)
7532 {
7533         put_stateid(cstate, &u->open.op_stateid);
7534 }
7535
7536 void
7537 nfsd4_set_closestateid(struct nfsd4_compound_state *cstate,
7538                 union nfsd4_op_u *u)
7539 {
7540         put_stateid(cstate, &u->close.cl_stateid);
7541 }
7542
7543 void
7544 nfsd4_set_lockstateid(struct nfsd4_compound_state *cstate,
7545                 union nfsd4_op_u *u)
7546 {
7547         put_stateid(cstate, &u->lock.lk_resp_stateid);
7548 }
7549
7550 /*
7551  * functions to consume current state id
7552  */
7553
7554 void
7555 nfsd4_get_opendowngradestateid(struct nfsd4_compound_state *cstate,
7556                 union nfsd4_op_u *u)
7557 {
7558         get_stateid(cstate, &u->open_downgrade.od_stateid);
7559 }
7560
7561 void
7562 nfsd4_get_delegreturnstateid(struct nfsd4_compound_state *cstate,
7563                 union nfsd4_op_u *u)
7564 {
7565         get_stateid(cstate, &u->delegreturn.dr_stateid);
7566 }
7567
7568 void
7569 nfsd4_get_freestateid(struct nfsd4_compound_state *cstate,
7570                 union nfsd4_op_u *u)
7571 {
7572         get_stateid(cstate, &u->free_stateid.fr_stateid);
7573 }
7574
7575 void
7576 nfsd4_get_setattrstateid(struct nfsd4_compound_state *cstate,
7577                 union nfsd4_op_u *u)
7578 {
7579         get_stateid(cstate, &u->setattr.sa_stateid);
7580 }
7581
7582 void
7583 nfsd4_get_closestateid(struct nfsd4_compound_state *cstate,
7584                 union nfsd4_op_u *u)
7585 {
7586         get_stateid(cstate, &u->close.cl_stateid);
7587 }
7588
7589 void
7590 nfsd4_get_lockustateid(struct nfsd4_compound_state *cstate,
7591                 union nfsd4_op_u *u)
7592 {
7593         get_stateid(cstate, &u->locku.lu_stateid);
7594 }
7595
7596 void
7597 nfsd4_get_readstateid(struct nfsd4_compound_state *cstate,
7598                 union nfsd4_op_u *u)
7599 {
7600         get_stateid(cstate, &u->read.rd_stateid);
7601 }
7602
7603 void
7604 nfsd4_get_writestateid(struct nfsd4_compound_state *cstate,
7605                 union nfsd4_op_u *u)
7606 {
7607         get_stateid(cstate, &u->write.wr_stateid);
7608 }