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