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