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