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