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