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