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