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