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