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