xref: /linux/fs/nfs/nfs4proc.c (revision d53b8e36925256097a08d7cb749198d85cbf9b2b)
1 /*
2  *  fs/nfs/nfs4proc.c
3  *
4  *  Client-side procedure declarations for NFSv4.
5  *
6  *  Copyright (c) 2002 The Regents of the University of Michigan.
7  *  All rights reserved.
8  *
9  *  Kendrick Smith <kmsmith@umich.edu>
10  *  Andy Adamson   <andros@umich.edu>
11  *
12  *  Redistribution and use in source and binary forms, with or without
13  *  modification, are permitted provided that the following conditions
14  *  are met:
15  *
16  *  1. Redistributions of source code must retain the above copyright
17  *     notice, this list of conditions and the following disclaimer.
18  *  2. Redistributions in binary form must reproduce the above copyright
19  *     notice, this list of conditions and the following disclaimer in the
20  *     documentation and/or other materials provided with the distribution.
21  *  3. Neither the name of the University nor the names of its
22  *     contributors may be used to endorse or promote products derived
23  *     from this software without specific prior written permission.
24  *
25  *  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
26  *  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
27  *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
28  *  DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  *  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30  *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31  *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
32  *  BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33  *  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
34  *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35  *  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36  */
37 
38 #include <linux/mm.h>
39 #include <linux/delay.h>
40 #include <linux/errno.h>
41 #include <linux/string.h>
42 #include <linux/ratelimit.h>
43 #include <linux/printk.h>
44 #include <linux/slab.h>
45 #include <linux/sunrpc/clnt.h>
46 #include <linux/nfs.h>
47 #include <linux/nfs4.h>
48 #include <linux/nfs_fs.h>
49 #include <linux/nfs_page.h>
50 #include <linux/nfs_mount.h>
51 #include <linux/namei.h>
52 #include <linux/mount.h>
53 #include <linux/module.h>
54 #include <linux/xattr.h>
55 #include <linux/utsname.h>
56 #include <linux/freezer.h>
57 #include <linux/iversion.h>
58 
59 #include "nfs4_fs.h"
60 #include "delegation.h"
61 #include "internal.h"
62 #include "iostat.h"
63 #include "callback.h"
64 #include "pnfs.h"
65 #include "netns.h"
66 #include "sysfs.h"
67 #include "nfs4idmap.h"
68 #include "nfs4session.h"
69 #include "fscache.h"
70 #include "nfs42.h"
71 
72 #include "nfs4trace.h"
73 
74 #define NFSDBG_FACILITY		NFSDBG_PROC
75 
76 #define NFS4_BITMASK_SZ		3
77 
78 #define NFS4_POLL_RETRY_MIN	(HZ/10)
79 #define NFS4_POLL_RETRY_MAX	(15*HZ)
80 
81 /* file attributes which can be mapped to nfs attributes */
82 #define NFS4_VALID_ATTRS (ATTR_MODE \
83 	| ATTR_UID \
84 	| ATTR_GID \
85 	| ATTR_SIZE \
86 	| ATTR_ATIME \
87 	| ATTR_MTIME \
88 	| ATTR_CTIME \
89 	| ATTR_ATIME_SET \
90 	| ATTR_MTIME_SET)
91 
92 struct nfs4_opendata;
93 static int _nfs4_recover_proc_open(struct nfs4_opendata *data);
94 static int nfs4_do_fsinfo(struct nfs_server *, struct nfs_fh *, struct nfs_fsinfo *);
95 static void nfs_fixup_referral_attributes(struct nfs_fattr *fattr);
96 static int _nfs4_proc_getattr(struct nfs_server *server, struct nfs_fh *fhandle,
97 			      struct nfs_fattr *fattr, struct inode *inode);
98 static int nfs4_do_setattr(struct inode *inode, const struct cred *cred,
99 			    struct nfs_fattr *fattr, struct iattr *sattr,
100 			    struct nfs_open_context *ctx, struct nfs4_label *ilabel);
101 #ifdef CONFIG_NFS_V4_1
102 static struct rpc_task *_nfs41_proc_sequence(struct nfs_client *clp,
103 		const struct cred *cred,
104 		struct nfs4_slot *slot,
105 		bool is_privileged);
106 static int nfs41_test_stateid(struct nfs_server *, const nfs4_stateid *,
107 			      const struct cred *);
108 static int nfs41_free_stateid(struct nfs_server *, const nfs4_stateid *,
109 			      const struct cred *, bool);
110 #endif
111 
112 #ifdef CONFIG_NFS_V4_SECURITY_LABEL
113 static inline struct nfs4_label *
114 nfs4_label_init_security(struct inode *dir, struct dentry *dentry,
115 	struct iattr *sattr, struct nfs4_label *label)
116 {
117 	int err;
118 
119 	if (label == NULL)
120 		return NULL;
121 
122 	if (nfs_server_capable(dir, NFS_CAP_SECURITY_LABEL) == 0)
123 		return NULL;
124 
125 	label->lfs = 0;
126 	label->pi = 0;
127 	label->len = 0;
128 	label->label = NULL;
129 
130 	err = security_dentry_init_security(dentry, sattr->ia_mode,
131 				&dentry->d_name, NULL,
132 				(void **)&label->label, &label->len);
133 	if (err == 0)
134 		return label;
135 
136 	return NULL;
137 }
138 static inline void
139 nfs4_label_release_security(struct nfs4_label *label)
140 {
141 	if (label)
142 		security_release_secctx(label->label, label->len);
143 }
144 static inline u32 *nfs4_bitmask(struct nfs_server *server, struct nfs4_label *label)
145 {
146 	if (label)
147 		return server->attr_bitmask;
148 
149 	return server->attr_bitmask_nl;
150 }
151 #else
152 static inline struct nfs4_label *
153 nfs4_label_init_security(struct inode *dir, struct dentry *dentry,
154 	struct iattr *sattr, struct nfs4_label *l)
155 { return NULL; }
156 static inline void
157 nfs4_label_release_security(struct nfs4_label *label)
158 { return; }
159 static inline u32 *
160 nfs4_bitmask(struct nfs_server *server, struct nfs4_label *label)
161 { return server->attr_bitmask; }
162 #endif
163 
164 /* Prevent leaks of NFSv4 errors into userland */
165 static int nfs4_map_errors(int err)
166 {
167 	if (err >= -1000)
168 		return err;
169 	switch (err) {
170 	case -NFS4ERR_RESOURCE:
171 	case -NFS4ERR_LAYOUTTRYLATER:
172 	case -NFS4ERR_RECALLCONFLICT:
173 	case -NFS4ERR_RETURNCONFLICT:
174 		return -EREMOTEIO;
175 	case -NFS4ERR_WRONGSEC:
176 	case -NFS4ERR_WRONG_CRED:
177 		return -EPERM;
178 	case -NFS4ERR_BADOWNER:
179 	case -NFS4ERR_BADNAME:
180 		return -EINVAL;
181 	case -NFS4ERR_SHARE_DENIED:
182 		return -EACCES;
183 	case -NFS4ERR_MINOR_VERS_MISMATCH:
184 		return -EPROTONOSUPPORT;
185 	case -NFS4ERR_FILE_OPEN:
186 		return -EBUSY;
187 	case -NFS4ERR_NOT_SAME:
188 		return -ENOTSYNC;
189 	default:
190 		dprintk("%s could not handle NFSv4 error %d\n",
191 				__func__, -err);
192 		break;
193 	}
194 	return -EIO;
195 }
196 
197 /*
198  * This is our standard bitmap for GETATTR requests.
199  */
200 const u32 nfs4_fattr_bitmap[3] = {
201 	FATTR4_WORD0_TYPE
202 	| FATTR4_WORD0_CHANGE
203 	| FATTR4_WORD0_SIZE
204 	| FATTR4_WORD0_FSID
205 	| FATTR4_WORD0_FILEID,
206 	FATTR4_WORD1_MODE
207 	| FATTR4_WORD1_NUMLINKS
208 	| FATTR4_WORD1_OWNER
209 	| FATTR4_WORD1_OWNER_GROUP
210 	| FATTR4_WORD1_RAWDEV
211 	| FATTR4_WORD1_SPACE_USED
212 	| FATTR4_WORD1_TIME_ACCESS
213 	| FATTR4_WORD1_TIME_METADATA
214 	| FATTR4_WORD1_TIME_MODIFY
215 	| FATTR4_WORD1_MOUNTED_ON_FILEID,
216 #ifdef CONFIG_NFS_V4_SECURITY_LABEL
217 	FATTR4_WORD2_SECURITY_LABEL
218 #endif
219 };
220 
221 static const u32 nfs4_pnfs_open_bitmap[3] = {
222 	FATTR4_WORD0_TYPE
223 	| FATTR4_WORD0_CHANGE
224 	| FATTR4_WORD0_SIZE
225 	| FATTR4_WORD0_FSID
226 	| FATTR4_WORD0_FILEID,
227 	FATTR4_WORD1_MODE
228 	| FATTR4_WORD1_NUMLINKS
229 	| FATTR4_WORD1_OWNER
230 	| FATTR4_WORD1_OWNER_GROUP
231 	| FATTR4_WORD1_RAWDEV
232 	| FATTR4_WORD1_SPACE_USED
233 	| FATTR4_WORD1_TIME_ACCESS
234 	| FATTR4_WORD1_TIME_METADATA
235 	| FATTR4_WORD1_TIME_MODIFY,
236 	FATTR4_WORD2_MDSTHRESHOLD
237 #ifdef CONFIG_NFS_V4_SECURITY_LABEL
238 	| FATTR4_WORD2_SECURITY_LABEL
239 #endif
240 };
241 
242 static const u32 nfs4_open_noattr_bitmap[3] = {
243 	FATTR4_WORD0_TYPE
244 	| FATTR4_WORD0_FILEID,
245 };
246 
247 const u32 nfs4_statfs_bitmap[3] = {
248 	FATTR4_WORD0_FILES_AVAIL
249 	| FATTR4_WORD0_FILES_FREE
250 	| FATTR4_WORD0_FILES_TOTAL,
251 	FATTR4_WORD1_SPACE_AVAIL
252 	| FATTR4_WORD1_SPACE_FREE
253 	| FATTR4_WORD1_SPACE_TOTAL
254 };
255 
256 const u32 nfs4_pathconf_bitmap[3] = {
257 	FATTR4_WORD0_MAXLINK
258 	| FATTR4_WORD0_MAXNAME,
259 	0
260 };
261 
262 const u32 nfs4_fsinfo_bitmap[3] = { FATTR4_WORD0_MAXFILESIZE
263 			| FATTR4_WORD0_MAXREAD
264 			| FATTR4_WORD0_MAXWRITE
265 			| FATTR4_WORD0_LEASE_TIME,
266 			FATTR4_WORD1_TIME_DELTA
267 			| FATTR4_WORD1_FS_LAYOUT_TYPES,
268 			FATTR4_WORD2_LAYOUT_BLKSIZE
269 			| FATTR4_WORD2_CLONE_BLKSIZE
270 			| FATTR4_WORD2_CHANGE_ATTR_TYPE
271 			| FATTR4_WORD2_XATTR_SUPPORT
272 };
273 
274 const u32 nfs4_fs_locations_bitmap[3] = {
275 	FATTR4_WORD0_CHANGE
276 	| FATTR4_WORD0_SIZE
277 	| FATTR4_WORD0_FSID
278 	| FATTR4_WORD0_FILEID
279 	| FATTR4_WORD0_FS_LOCATIONS,
280 	FATTR4_WORD1_OWNER
281 	| FATTR4_WORD1_OWNER_GROUP
282 	| FATTR4_WORD1_RAWDEV
283 	| FATTR4_WORD1_SPACE_USED
284 	| FATTR4_WORD1_TIME_ACCESS
285 	| FATTR4_WORD1_TIME_METADATA
286 	| FATTR4_WORD1_TIME_MODIFY
287 	| FATTR4_WORD1_MOUNTED_ON_FILEID,
288 };
289 
290 static void nfs4_bitmap_copy_adjust(__u32 *dst, const __u32 *src,
291 				    struct inode *inode, unsigned long flags)
292 {
293 	unsigned long cache_validity;
294 
295 	memcpy(dst, src, NFS4_BITMASK_SZ*sizeof(*dst));
296 	if (!inode || !nfs_have_read_or_write_delegation(inode))
297 		return;
298 
299 	cache_validity = READ_ONCE(NFS_I(inode)->cache_validity) | flags;
300 
301 	/* Remove the attributes over which we have full control */
302 	dst[1] &= ~FATTR4_WORD1_RAWDEV;
303 	if (!(cache_validity & NFS_INO_INVALID_SIZE))
304 		dst[0] &= ~FATTR4_WORD0_SIZE;
305 
306 	if (!(cache_validity & NFS_INO_INVALID_CHANGE))
307 		dst[0] &= ~FATTR4_WORD0_CHANGE;
308 
309 	if (!(cache_validity & NFS_INO_INVALID_MODE))
310 		dst[1] &= ~FATTR4_WORD1_MODE;
311 	if (!(cache_validity & NFS_INO_INVALID_OTHER))
312 		dst[1] &= ~(FATTR4_WORD1_OWNER | FATTR4_WORD1_OWNER_GROUP);
313 
314 	if (nfs_have_delegated_mtime(inode)) {
315 		if (!(cache_validity & NFS_INO_INVALID_ATIME))
316 			dst[1] &= ~FATTR4_WORD1_TIME_ACCESS;
317 		if (!(cache_validity & NFS_INO_INVALID_MTIME))
318 			dst[1] &= ~FATTR4_WORD1_TIME_MODIFY;
319 		if (!(cache_validity & NFS_INO_INVALID_CTIME))
320 			dst[1] &= ~FATTR4_WORD1_TIME_METADATA;
321 	} else if (nfs_have_delegated_atime(inode)) {
322 		if (!(cache_validity & NFS_INO_INVALID_ATIME))
323 			dst[1] &= ~FATTR4_WORD1_TIME_ACCESS;
324 	}
325 }
326 
327 static void nfs4_setup_readdir(u64 cookie, __be32 *verifier, struct dentry *dentry,
328 		struct nfs4_readdir_arg *readdir)
329 {
330 	unsigned int attrs = FATTR4_WORD0_FILEID | FATTR4_WORD0_TYPE;
331 	__be32 *start, *p;
332 
333 	if (cookie > 2) {
334 		readdir->cookie = cookie;
335 		memcpy(&readdir->verifier, verifier, sizeof(readdir->verifier));
336 		return;
337 	}
338 
339 	readdir->cookie = 0;
340 	memset(&readdir->verifier, 0, sizeof(readdir->verifier));
341 	if (cookie == 2)
342 		return;
343 
344 	/*
345 	 * NFSv4 servers do not return entries for '.' and '..'
346 	 * Therefore, we fake these entries here.  We let '.'
347 	 * have cookie 0 and '..' have cookie 1.  Note that
348 	 * when talking to the server, we always send cookie 0
349 	 * instead of 1 or 2.
350 	 */
351 	start = p = kmap_atomic(*readdir->pages);
352 
353 	if (cookie == 0) {
354 		*p++ = xdr_one;                                  /* next */
355 		*p++ = xdr_zero;                   /* cookie, first word */
356 		*p++ = xdr_one;                   /* cookie, second word */
357 		*p++ = xdr_one;                             /* entry len */
358 		memcpy(p, ".\0\0\0", 4);                        /* entry */
359 		p++;
360 		*p++ = xdr_one;                         /* bitmap length */
361 		*p++ = htonl(attrs);                           /* bitmap */
362 		*p++ = htonl(12);             /* attribute buffer length */
363 		*p++ = htonl(NF4DIR);
364 		p = xdr_encode_hyper(p, NFS_FILEID(d_inode(dentry)));
365 	}
366 
367 	*p++ = xdr_one;                                  /* next */
368 	*p++ = xdr_zero;                   /* cookie, first word */
369 	*p++ = xdr_two;                   /* cookie, second word */
370 	*p++ = xdr_two;                             /* entry len */
371 	memcpy(p, "..\0\0", 4);                         /* entry */
372 	p++;
373 	*p++ = xdr_one;                         /* bitmap length */
374 	*p++ = htonl(attrs);                           /* bitmap */
375 	*p++ = htonl(12);             /* attribute buffer length */
376 	*p++ = htonl(NF4DIR);
377 	p = xdr_encode_hyper(p, NFS_FILEID(d_inode(dentry->d_parent)));
378 
379 	readdir->pgbase = (char *)p - (char *)start;
380 	readdir->count -= readdir->pgbase;
381 	kunmap_atomic(start);
382 }
383 
384 static void nfs4_fattr_set_prechange(struct nfs_fattr *fattr, u64 version)
385 {
386 	if (!(fattr->valid & NFS_ATTR_FATTR_PRECHANGE)) {
387 		fattr->pre_change_attr = version;
388 		fattr->valid |= NFS_ATTR_FATTR_PRECHANGE;
389 	}
390 }
391 
392 static void nfs4_test_and_free_stateid(struct nfs_server *server,
393 		nfs4_stateid *stateid,
394 		const struct cred *cred)
395 {
396 	const struct nfs4_minor_version_ops *ops = server->nfs_client->cl_mvops;
397 
398 	ops->test_and_free_expired(server, stateid, cred);
399 }
400 
401 static void __nfs4_free_revoked_stateid(struct nfs_server *server,
402 		nfs4_stateid *stateid,
403 		const struct cred *cred)
404 {
405 	stateid->type = NFS4_REVOKED_STATEID_TYPE;
406 	nfs4_test_and_free_stateid(server, stateid, cred);
407 }
408 
409 static void nfs4_free_revoked_stateid(struct nfs_server *server,
410 		const nfs4_stateid *stateid,
411 		const struct cred *cred)
412 {
413 	nfs4_stateid tmp;
414 
415 	nfs4_stateid_copy(&tmp, stateid);
416 	__nfs4_free_revoked_stateid(server, &tmp, cred);
417 }
418 
419 static long nfs4_update_delay(long *timeout)
420 {
421 	long ret;
422 	if (!timeout)
423 		return NFS4_POLL_RETRY_MAX;
424 	if (*timeout <= 0)
425 		*timeout = NFS4_POLL_RETRY_MIN;
426 	if (*timeout > NFS4_POLL_RETRY_MAX)
427 		*timeout = NFS4_POLL_RETRY_MAX;
428 	ret = *timeout;
429 	*timeout <<= 1;
430 	return ret;
431 }
432 
433 static int nfs4_delay_killable(long *timeout)
434 {
435 	might_sleep();
436 
437 	__set_current_state(TASK_KILLABLE|TASK_FREEZABLE_UNSAFE);
438 	schedule_timeout(nfs4_update_delay(timeout));
439 	if (!__fatal_signal_pending(current))
440 		return 0;
441 	return -EINTR;
442 }
443 
444 static int nfs4_delay_interruptible(long *timeout)
445 {
446 	might_sleep();
447 
448 	__set_current_state(TASK_INTERRUPTIBLE|TASK_FREEZABLE_UNSAFE);
449 	schedule_timeout(nfs4_update_delay(timeout));
450 	if (!signal_pending(current))
451 		return 0;
452 	return __fatal_signal_pending(current) ? -EINTR :-ERESTARTSYS;
453 }
454 
455 static int nfs4_delay(long *timeout, bool interruptible)
456 {
457 	if (interruptible)
458 		return nfs4_delay_interruptible(timeout);
459 	return nfs4_delay_killable(timeout);
460 }
461 
462 static const nfs4_stateid *
463 nfs4_recoverable_stateid(const nfs4_stateid *stateid)
464 {
465 	if (!stateid)
466 		return NULL;
467 	switch (stateid->type) {
468 	case NFS4_OPEN_STATEID_TYPE:
469 	case NFS4_LOCK_STATEID_TYPE:
470 	case NFS4_DELEGATION_STATEID_TYPE:
471 		return stateid;
472 	default:
473 		break;
474 	}
475 	return NULL;
476 }
477 
478 /* This is the error handling routine for processes that are allowed
479  * to sleep.
480  */
481 static int nfs4_do_handle_exception(struct nfs_server *server,
482 		int errorcode, struct nfs4_exception *exception)
483 {
484 	struct nfs_client *clp = server->nfs_client;
485 	struct nfs4_state *state = exception->state;
486 	const nfs4_stateid *stateid;
487 	struct inode *inode = exception->inode;
488 	int ret = errorcode;
489 
490 	exception->delay = 0;
491 	exception->recovering = 0;
492 	exception->retry = 0;
493 
494 	stateid = nfs4_recoverable_stateid(exception->stateid);
495 	if (stateid == NULL && state != NULL)
496 		stateid = nfs4_recoverable_stateid(&state->stateid);
497 
498 	switch(errorcode) {
499 		case 0:
500 			return 0;
501 		case -NFS4ERR_BADHANDLE:
502 		case -ESTALE:
503 			if (inode != NULL && S_ISREG(inode->i_mode))
504 				pnfs_destroy_layout(NFS_I(inode));
505 			break;
506 		case -NFS4ERR_DELEG_REVOKED:
507 		case -NFS4ERR_ADMIN_REVOKED:
508 		case -NFS4ERR_EXPIRED:
509 		case -NFS4ERR_BAD_STATEID:
510 		case -NFS4ERR_PARTNER_NO_AUTH:
511 			if (inode != NULL && stateid != NULL) {
512 				nfs_inode_find_state_and_recover(inode,
513 						stateid);
514 				goto wait_on_recovery;
515 			}
516 			fallthrough;
517 		case -NFS4ERR_OPENMODE:
518 			if (inode) {
519 				int err;
520 
521 				err = nfs_async_inode_return_delegation(inode,
522 						stateid);
523 				if (err == 0)
524 					goto wait_on_recovery;
525 				if (stateid != NULL && stateid->type == NFS4_DELEGATION_STATEID_TYPE) {
526 					exception->retry = 1;
527 					break;
528 				}
529 			}
530 			if (state == NULL)
531 				break;
532 			ret = nfs4_schedule_stateid_recovery(server, state);
533 			if (ret < 0)
534 				break;
535 			goto wait_on_recovery;
536 		case -NFS4ERR_STALE_STATEID:
537 		case -NFS4ERR_STALE_CLIENTID:
538 			nfs4_schedule_lease_recovery(clp);
539 			goto wait_on_recovery;
540 		case -NFS4ERR_MOVED:
541 			ret = nfs4_schedule_migration_recovery(server);
542 			if (ret < 0)
543 				break;
544 			goto wait_on_recovery;
545 		case -NFS4ERR_LEASE_MOVED:
546 			nfs4_schedule_lease_moved_recovery(clp);
547 			goto wait_on_recovery;
548 #if defined(CONFIG_NFS_V4_1)
549 		case -NFS4ERR_BADSESSION:
550 		case -NFS4ERR_BADSLOT:
551 		case -NFS4ERR_BAD_HIGH_SLOT:
552 		case -NFS4ERR_CONN_NOT_BOUND_TO_SESSION:
553 		case -NFS4ERR_DEADSESSION:
554 		case -NFS4ERR_SEQ_FALSE_RETRY:
555 		case -NFS4ERR_SEQ_MISORDERED:
556 			/* Handled in nfs41_sequence_process() */
557 			goto wait_on_recovery;
558 #endif /* defined(CONFIG_NFS_V4_1) */
559 		case -NFS4ERR_FILE_OPEN:
560 			if (exception->timeout > HZ) {
561 				/* We have retried a decent amount, time to
562 				 * fail
563 				 */
564 				ret = -EBUSY;
565 				break;
566 			}
567 			fallthrough;
568 		case -NFS4ERR_DELAY:
569 			nfs_inc_server_stats(server, NFSIOS_DELAY);
570 			fallthrough;
571 		case -NFS4ERR_GRACE:
572 		case -NFS4ERR_LAYOUTTRYLATER:
573 		case -NFS4ERR_RECALLCONFLICT:
574 		case -NFS4ERR_RETURNCONFLICT:
575 			exception->delay = 1;
576 			return 0;
577 
578 		case -NFS4ERR_RETRY_UNCACHED_REP:
579 		case -NFS4ERR_OLD_STATEID:
580 			exception->retry = 1;
581 			break;
582 		case -NFS4ERR_BADOWNER:
583 			/* The following works around a Linux server bug! */
584 		case -NFS4ERR_BADNAME:
585 			if (server->caps & NFS_CAP_UIDGID_NOMAP) {
586 				server->caps &= ~NFS_CAP_UIDGID_NOMAP;
587 				exception->retry = 1;
588 				printk(KERN_WARNING "NFS: v4 server %s "
589 						"does not accept raw "
590 						"uid/gids. "
591 						"Reenabling the idmapper.\n",
592 						server->nfs_client->cl_hostname);
593 			}
594 	}
595 	/* We failed to handle the error */
596 	return nfs4_map_errors(ret);
597 wait_on_recovery:
598 	exception->recovering = 1;
599 	return 0;
600 }
601 
602 /*
603  * Track the number of NFS4ERR_DELAY related retransmissions and return
604  * EAGAIN if the 'softerr' mount option is set, and we've exceeded the limit
605  * set by 'nfs_delay_retrans'.
606  */
607 static int nfs4_exception_should_retrans(const struct nfs_server *server,
608 					 struct nfs4_exception *exception)
609 {
610 	if (server->flags & NFS_MOUNT_SOFTERR && nfs_delay_retrans >= 0) {
611 		if (exception->retrans++ >= (unsigned short)nfs_delay_retrans)
612 			return -EAGAIN;
613 	}
614 	return 0;
615 }
616 
617 /* This is the error handling routine for processes that are allowed
618  * to sleep.
619  */
620 int nfs4_handle_exception(struct nfs_server *server, int errorcode, struct nfs4_exception *exception)
621 {
622 	struct nfs_client *clp = server->nfs_client;
623 	int ret;
624 
625 	ret = nfs4_do_handle_exception(server, errorcode, exception);
626 	if (exception->delay) {
627 		int ret2 = nfs4_exception_should_retrans(server, exception);
628 		if (ret2 < 0) {
629 			exception->retry = 0;
630 			return ret2;
631 		}
632 		ret = nfs4_delay(&exception->timeout,
633 				exception->interruptible);
634 		goto out_retry;
635 	}
636 	if (exception->recovering) {
637 		if (exception->task_is_privileged)
638 			return -EDEADLOCK;
639 		ret = nfs4_wait_clnt_recover(clp);
640 		if (test_bit(NFS_MIG_FAILED, &server->mig_status))
641 			return -EIO;
642 		goto out_retry;
643 	}
644 	return ret;
645 out_retry:
646 	if (ret == 0)
647 		exception->retry = 1;
648 	return ret;
649 }
650 
651 static int
652 nfs4_async_handle_exception(struct rpc_task *task, struct nfs_server *server,
653 		int errorcode, struct nfs4_exception *exception)
654 {
655 	struct nfs_client *clp = server->nfs_client;
656 	int ret;
657 
658 	ret = nfs4_do_handle_exception(server, errorcode, exception);
659 	if (exception->delay) {
660 		int ret2 = nfs4_exception_should_retrans(server, exception);
661 		if (ret2 < 0) {
662 			exception->retry = 0;
663 			return ret2;
664 		}
665 		rpc_delay(task, nfs4_update_delay(&exception->timeout));
666 		goto out_retry;
667 	}
668 	if (exception->recovering) {
669 		if (exception->task_is_privileged)
670 			return -EDEADLOCK;
671 		rpc_sleep_on(&clp->cl_rpcwaitq, task, NULL);
672 		if (test_bit(NFS4CLNT_MANAGER_RUNNING, &clp->cl_state) == 0)
673 			rpc_wake_up_queued_task(&clp->cl_rpcwaitq, task);
674 		goto out_retry;
675 	}
676 	if (test_bit(NFS_MIG_FAILED, &server->mig_status))
677 		ret = -EIO;
678 	return ret;
679 out_retry:
680 	if (ret == 0) {
681 		exception->retry = 1;
682 		/*
683 		 * For NFS4ERR_MOVED, the client transport will need to
684 		 * be recomputed after migration recovery has completed.
685 		 */
686 		if (errorcode == -NFS4ERR_MOVED)
687 			rpc_task_release_transport(task);
688 	}
689 	return ret;
690 }
691 
692 int
693 nfs4_async_handle_error(struct rpc_task *task, struct nfs_server *server,
694 			struct nfs4_state *state, long *timeout)
695 {
696 	struct nfs4_exception exception = {
697 		.state = state,
698 	};
699 
700 	if (task->tk_status >= 0)
701 		return 0;
702 	if (timeout)
703 		exception.timeout = *timeout;
704 	task->tk_status = nfs4_async_handle_exception(task, server,
705 			task->tk_status,
706 			&exception);
707 	if (exception.delay && timeout)
708 		*timeout = exception.timeout;
709 	if (exception.retry)
710 		return -EAGAIN;
711 	return 0;
712 }
713 
714 /*
715  * Return 'true' if 'clp' is using an rpc_client that is integrity protected
716  * or 'false' otherwise.
717  */
718 static bool _nfs4_is_integrity_protected(struct nfs_client *clp)
719 {
720 	rpc_authflavor_t flavor = clp->cl_rpcclient->cl_auth->au_flavor;
721 	return (flavor == RPC_AUTH_GSS_KRB5I) || (flavor == RPC_AUTH_GSS_KRB5P);
722 }
723 
724 static void do_renew_lease(struct nfs_client *clp, unsigned long timestamp)
725 {
726 	spin_lock(&clp->cl_lock);
727 	if (time_before(clp->cl_last_renewal,timestamp))
728 		clp->cl_last_renewal = timestamp;
729 	spin_unlock(&clp->cl_lock);
730 }
731 
732 static void renew_lease(const struct nfs_server *server, unsigned long timestamp)
733 {
734 	struct nfs_client *clp = server->nfs_client;
735 
736 	if (!nfs4_has_session(clp))
737 		do_renew_lease(clp, timestamp);
738 }
739 
740 struct nfs4_call_sync_data {
741 	const struct nfs_server *seq_server;
742 	struct nfs4_sequence_args *seq_args;
743 	struct nfs4_sequence_res *seq_res;
744 };
745 
746 void nfs4_init_sequence(struct nfs4_sequence_args *args,
747 			struct nfs4_sequence_res *res, int cache_reply,
748 			int privileged)
749 {
750 	args->sa_slot = NULL;
751 	args->sa_cache_this = cache_reply;
752 	args->sa_privileged = privileged;
753 
754 	res->sr_slot = NULL;
755 }
756 
757 static void nfs40_sequence_free_slot(struct nfs4_sequence_res *res)
758 {
759 	struct nfs4_slot *slot = res->sr_slot;
760 	struct nfs4_slot_table *tbl;
761 
762 	tbl = slot->table;
763 	spin_lock(&tbl->slot_tbl_lock);
764 	if (!nfs41_wake_and_assign_slot(tbl, slot))
765 		nfs4_free_slot(tbl, slot);
766 	spin_unlock(&tbl->slot_tbl_lock);
767 
768 	res->sr_slot = NULL;
769 }
770 
771 static int nfs40_sequence_done(struct rpc_task *task,
772 			       struct nfs4_sequence_res *res)
773 {
774 	if (res->sr_slot != NULL)
775 		nfs40_sequence_free_slot(res);
776 	return 1;
777 }
778 
779 #if defined(CONFIG_NFS_V4_1)
780 
781 static void nfs41_release_slot(struct nfs4_slot *slot)
782 {
783 	struct nfs4_session *session;
784 	struct nfs4_slot_table *tbl;
785 	bool send_new_highest_used_slotid = false;
786 
787 	if (!slot)
788 		return;
789 	tbl = slot->table;
790 	session = tbl->session;
791 
792 	/* Bump the slot sequence number */
793 	if (slot->seq_done)
794 		slot->seq_nr++;
795 	slot->seq_done = 0;
796 
797 	spin_lock(&tbl->slot_tbl_lock);
798 	/* Be nice to the server: try to ensure that the last transmitted
799 	 * value for highest_user_slotid <= target_highest_slotid
800 	 */
801 	if (tbl->highest_used_slotid > tbl->target_highest_slotid)
802 		send_new_highest_used_slotid = true;
803 
804 	if (nfs41_wake_and_assign_slot(tbl, slot)) {
805 		send_new_highest_used_slotid = false;
806 		goto out_unlock;
807 	}
808 	nfs4_free_slot(tbl, slot);
809 
810 	if (tbl->highest_used_slotid != NFS4_NO_SLOT)
811 		send_new_highest_used_slotid = false;
812 out_unlock:
813 	spin_unlock(&tbl->slot_tbl_lock);
814 	if (send_new_highest_used_slotid)
815 		nfs41_notify_server(session->clp);
816 	if (waitqueue_active(&tbl->slot_waitq))
817 		wake_up_all(&tbl->slot_waitq);
818 }
819 
820 static void nfs41_sequence_free_slot(struct nfs4_sequence_res *res)
821 {
822 	nfs41_release_slot(res->sr_slot);
823 	res->sr_slot = NULL;
824 }
825 
826 static void nfs4_slot_sequence_record_sent(struct nfs4_slot *slot,
827 		u32 seqnr)
828 {
829 	if ((s32)(seqnr - slot->seq_nr_highest_sent) > 0)
830 		slot->seq_nr_highest_sent = seqnr;
831 }
832 static void nfs4_slot_sequence_acked(struct nfs4_slot *slot, u32 seqnr)
833 {
834 	nfs4_slot_sequence_record_sent(slot, seqnr);
835 	slot->seq_nr_last_acked = seqnr;
836 }
837 
838 static void nfs4_probe_sequence(struct nfs_client *client, const struct cred *cred,
839 				struct nfs4_slot *slot)
840 {
841 	struct rpc_task *task = _nfs41_proc_sequence(client, cred, slot, true);
842 	if (!IS_ERR(task))
843 		rpc_put_task_async(task);
844 }
845 
846 static int nfs41_sequence_process(struct rpc_task *task,
847 		struct nfs4_sequence_res *res)
848 {
849 	struct nfs4_session *session;
850 	struct nfs4_slot *slot = res->sr_slot;
851 	struct nfs_client *clp;
852 	int status;
853 	int ret = 1;
854 
855 	if (slot == NULL)
856 		goto out_noaction;
857 	/* don't increment the sequence number if the task wasn't sent */
858 	if (!RPC_WAS_SENT(task) || slot->seq_done)
859 		goto out;
860 
861 	session = slot->table->session;
862 	clp = session->clp;
863 
864 	trace_nfs4_sequence_done(session, res);
865 
866 	status = res->sr_status;
867 	if (task->tk_status == -NFS4ERR_DEADSESSION)
868 		status = -NFS4ERR_DEADSESSION;
869 
870 	/* Check the SEQUENCE operation status */
871 	switch (status) {
872 	case 0:
873 		/* Mark this sequence number as having been acked */
874 		nfs4_slot_sequence_acked(slot, slot->seq_nr);
875 		/* Update the slot's sequence and clientid lease timer */
876 		slot->seq_done = 1;
877 		do_renew_lease(clp, res->sr_timestamp);
878 		/* Check sequence flags */
879 		nfs41_handle_sequence_flag_errors(clp, res->sr_status_flags,
880 				!!slot->privileged);
881 		nfs41_update_target_slotid(slot->table, slot, res);
882 		break;
883 	case 1:
884 		/*
885 		 * sr_status remains 1 if an RPC level error occurred.
886 		 * The server may or may not have processed the sequence
887 		 * operation..
888 		 */
889 		nfs4_slot_sequence_record_sent(slot, slot->seq_nr);
890 		slot->seq_done = 1;
891 		goto out;
892 	case -NFS4ERR_DELAY:
893 		/* The server detected a resend of the RPC call and
894 		 * returned NFS4ERR_DELAY as per Section 2.10.6.2
895 		 * of RFC5661.
896 		 */
897 		dprintk("%s: slot=%u seq=%u: Operation in progress\n",
898 			__func__,
899 			slot->slot_nr,
900 			slot->seq_nr);
901 		goto out_retry;
902 	case -NFS4ERR_RETRY_UNCACHED_REP:
903 	case -NFS4ERR_SEQ_FALSE_RETRY:
904 		/*
905 		 * The server thinks we tried to replay a request.
906 		 * Retry the call after bumping the sequence ID.
907 		 */
908 		nfs4_slot_sequence_acked(slot, slot->seq_nr);
909 		goto retry_new_seq;
910 	case -NFS4ERR_BADSLOT:
911 		/*
912 		 * The slot id we used was probably retired. Try again
913 		 * using a different slot id.
914 		 */
915 		if (slot->slot_nr < slot->table->target_highest_slotid)
916 			goto session_recover;
917 		goto retry_nowait;
918 	case -NFS4ERR_SEQ_MISORDERED:
919 		nfs4_slot_sequence_record_sent(slot, slot->seq_nr);
920 		/*
921 		 * Were one or more calls using this slot interrupted?
922 		 * If the server never received the request, then our
923 		 * transmitted slot sequence number may be too high. However,
924 		 * if the server did receive the request then it might
925 		 * accidentally give us a reply with a mismatched operation.
926 		 * We can sort this out by sending a lone sequence operation
927 		 * to the server on the same slot.
928 		 */
929 		if ((s32)(slot->seq_nr - slot->seq_nr_last_acked) > 1) {
930 			slot->seq_nr--;
931 			if (task->tk_msg.rpc_proc != &nfs4_procedures[NFSPROC4_CLNT_SEQUENCE]) {
932 				nfs4_probe_sequence(clp, task->tk_msg.rpc_cred, slot);
933 				res->sr_slot = NULL;
934 			}
935 			goto retry_nowait;
936 		}
937 		/*
938 		 * RFC5661:
939 		 * A retry might be sent while the original request is
940 		 * still in progress on the replier. The replier SHOULD
941 		 * deal with the issue by returning NFS4ERR_DELAY as the
942 		 * reply to SEQUENCE or CB_SEQUENCE operation, but
943 		 * implementations MAY return NFS4ERR_SEQ_MISORDERED.
944 		 *
945 		 * Restart the search after a delay.
946 		 */
947 		slot->seq_nr = slot->seq_nr_highest_sent;
948 		goto out_retry;
949 	case -NFS4ERR_BADSESSION:
950 	case -NFS4ERR_DEADSESSION:
951 	case -NFS4ERR_CONN_NOT_BOUND_TO_SESSION:
952 		goto session_recover;
953 	default:
954 		/* Just update the slot sequence no. */
955 		slot->seq_done = 1;
956 	}
957 out:
958 	/* The session may be reset by one of the error handlers. */
959 	dprintk("%s: Error %d free the slot \n", __func__, res->sr_status);
960 out_noaction:
961 	return ret;
962 session_recover:
963 	set_bit(NFS4_SLOT_TBL_DRAINING, &session->fc_slot_table.slot_tbl_state);
964 	nfs4_schedule_session_recovery(session, status);
965 	dprintk("%s ERROR: %d Reset session\n", __func__, status);
966 	nfs41_sequence_free_slot(res);
967 	goto out;
968 retry_new_seq:
969 	++slot->seq_nr;
970 retry_nowait:
971 	if (rpc_restart_call_prepare(task)) {
972 		nfs41_sequence_free_slot(res);
973 		task->tk_status = 0;
974 		ret = 0;
975 	}
976 	goto out;
977 out_retry:
978 	if (!rpc_restart_call(task))
979 		goto out;
980 	rpc_delay(task, NFS4_POLL_RETRY_MAX);
981 	return 0;
982 }
983 
984 int nfs41_sequence_done(struct rpc_task *task, struct nfs4_sequence_res *res)
985 {
986 	if (!nfs41_sequence_process(task, res))
987 		return 0;
988 	if (res->sr_slot != NULL)
989 		nfs41_sequence_free_slot(res);
990 	return 1;
991 
992 }
993 EXPORT_SYMBOL_GPL(nfs41_sequence_done);
994 
995 static int nfs4_sequence_process(struct rpc_task *task, struct nfs4_sequence_res *res)
996 {
997 	if (res->sr_slot == NULL)
998 		return 1;
999 	if (res->sr_slot->table->session != NULL)
1000 		return nfs41_sequence_process(task, res);
1001 	return nfs40_sequence_done(task, res);
1002 }
1003 
1004 static void nfs4_sequence_free_slot(struct nfs4_sequence_res *res)
1005 {
1006 	if (res->sr_slot != NULL) {
1007 		if (res->sr_slot->table->session != NULL)
1008 			nfs41_sequence_free_slot(res);
1009 		else
1010 			nfs40_sequence_free_slot(res);
1011 	}
1012 }
1013 
1014 int nfs4_sequence_done(struct rpc_task *task, struct nfs4_sequence_res *res)
1015 {
1016 	if (res->sr_slot == NULL)
1017 		return 1;
1018 	if (!res->sr_slot->table->session)
1019 		return nfs40_sequence_done(task, res);
1020 	return nfs41_sequence_done(task, res);
1021 }
1022 EXPORT_SYMBOL_GPL(nfs4_sequence_done);
1023 
1024 static void nfs41_call_sync_prepare(struct rpc_task *task, void *calldata)
1025 {
1026 	struct nfs4_call_sync_data *data = calldata;
1027 
1028 	dprintk("--> %s data->seq_server %p\n", __func__, data->seq_server);
1029 
1030 	nfs4_setup_sequence(data->seq_server->nfs_client,
1031 			    data->seq_args, data->seq_res, task);
1032 }
1033 
1034 static void nfs41_call_sync_done(struct rpc_task *task, void *calldata)
1035 {
1036 	struct nfs4_call_sync_data *data = calldata;
1037 
1038 	nfs41_sequence_done(task, data->seq_res);
1039 }
1040 
1041 static const struct rpc_call_ops nfs41_call_sync_ops = {
1042 	.rpc_call_prepare = nfs41_call_sync_prepare,
1043 	.rpc_call_done = nfs41_call_sync_done,
1044 };
1045 
1046 #else	/* !CONFIG_NFS_V4_1 */
1047 
1048 static int nfs4_sequence_process(struct rpc_task *task, struct nfs4_sequence_res *res)
1049 {
1050 	return nfs40_sequence_done(task, res);
1051 }
1052 
1053 static void nfs4_sequence_free_slot(struct nfs4_sequence_res *res)
1054 {
1055 	if (res->sr_slot != NULL)
1056 		nfs40_sequence_free_slot(res);
1057 }
1058 
1059 int nfs4_sequence_done(struct rpc_task *task,
1060 		       struct nfs4_sequence_res *res)
1061 {
1062 	return nfs40_sequence_done(task, res);
1063 }
1064 EXPORT_SYMBOL_GPL(nfs4_sequence_done);
1065 
1066 #endif	/* !CONFIG_NFS_V4_1 */
1067 
1068 static void nfs41_sequence_res_init(struct nfs4_sequence_res *res)
1069 {
1070 	res->sr_timestamp = jiffies;
1071 	res->sr_status_flags = 0;
1072 	res->sr_status = 1;
1073 }
1074 
1075 static
1076 void nfs4_sequence_attach_slot(struct nfs4_sequence_args *args,
1077 		struct nfs4_sequence_res *res,
1078 		struct nfs4_slot *slot)
1079 {
1080 	if (!slot)
1081 		return;
1082 	slot->privileged = args->sa_privileged ? 1 : 0;
1083 	args->sa_slot = slot;
1084 
1085 	res->sr_slot = slot;
1086 }
1087 
1088 int nfs4_setup_sequence(struct nfs_client *client,
1089 			struct nfs4_sequence_args *args,
1090 			struct nfs4_sequence_res *res,
1091 			struct rpc_task *task)
1092 {
1093 	struct nfs4_session *session = nfs4_get_session(client);
1094 	struct nfs4_slot_table *tbl  = client->cl_slot_tbl;
1095 	struct nfs4_slot *slot;
1096 
1097 	/* slot already allocated? */
1098 	if (res->sr_slot != NULL)
1099 		goto out_start;
1100 
1101 	if (session)
1102 		tbl = &session->fc_slot_table;
1103 
1104 	spin_lock(&tbl->slot_tbl_lock);
1105 	/* The state manager will wait until the slot table is empty */
1106 	if (nfs4_slot_tbl_draining(tbl) && !args->sa_privileged)
1107 		goto out_sleep;
1108 
1109 	slot = nfs4_alloc_slot(tbl);
1110 	if (IS_ERR(slot)) {
1111 		if (slot == ERR_PTR(-ENOMEM))
1112 			goto out_sleep_timeout;
1113 		goto out_sleep;
1114 	}
1115 	spin_unlock(&tbl->slot_tbl_lock);
1116 
1117 	nfs4_sequence_attach_slot(args, res, slot);
1118 
1119 	trace_nfs4_setup_sequence(session, args);
1120 out_start:
1121 	nfs41_sequence_res_init(res);
1122 	rpc_call_start(task);
1123 	return 0;
1124 out_sleep_timeout:
1125 	/* Try again in 1/4 second */
1126 	if (args->sa_privileged)
1127 		rpc_sleep_on_priority_timeout(&tbl->slot_tbl_waitq, task,
1128 				jiffies + (HZ >> 2), RPC_PRIORITY_PRIVILEGED);
1129 	else
1130 		rpc_sleep_on_timeout(&tbl->slot_tbl_waitq, task,
1131 				NULL, jiffies + (HZ >> 2));
1132 	spin_unlock(&tbl->slot_tbl_lock);
1133 	return -EAGAIN;
1134 out_sleep:
1135 	if (args->sa_privileged)
1136 		rpc_sleep_on_priority(&tbl->slot_tbl_waitq, task,
1137 				RPC_PRIORITY_PRIVILEGED);
1138 	else
1139 		rpc_sleep_on(&tbl->slot_tbl_waitq, task, NULL);
1140 	spin_unlock(&tbl->slot_tbl_lock);
1141 	return -EAGAIN;
1142 }
1143 EXPORT_SYMBOL_GPL(nfs4_setup_sequence);
1144 
1145 static void nfs40_call_sync_prepare(struct rpc_task *task, void *calldata)
1146 {
1147 	struct nfs4_call_sync_data *data = calldata;
1148 	nfs4_setup_sequence(data->seq_server->nfs_client,
1149 				data->seq_args, data->seq_res, task);
1150 }
1151 
1152 static void nfs40_call_sync_done(struct rpc_task *task, void *calldata)
1153 {
1154 	struct nfs4_call_sync_data *data = calldata;
1155 	nfs4_sequence_done(task, data->seq_res);
1156 }
1157 
1158 static const struct rpc_call_ops nfs40_call_sync_ops = {
1159 	.rpc_call_prepare = nfs40_call_sync_prepare,
1160 	.rpc_call_done = nfs40_call_sync_done,
1161 };
1162 
1163 static int nfs4_call_sync_custom(struct rpc_task_setup *task_setup)
1164 {
1165 	int ret;
1166 	struct rpc_task *task;
1167 
1168 	task = rpc_run_task(task_setup);
1169 	if (IS_ERR(task))
1170 		return PTR_ERR(task);
1171 
1172 	ret = task->tk_status;
1173 	rpc_put_task(task);
1174 	return ret;
1175 }
1176 
1177 static int nfs4_do_call_sync(struct rpc_clnt *clnt,
1178 			     struct nfs_server *server,
1179 			     struct rpc_message *msg,
1180 			     struct nfs4_sequence_args *args,
1181 			     struct nfs4_sequence_res *res,
1182 			     unsigned short task_flags)
1183 {
1184 	struct nfs_client *clp = server->nfs_client;
1185 	struct nfs4_call_sync_data data = {
1186 		.seq_server = server,
1187 		.seq_args = args,
1188 		.seq_res = res,
1189 	};
1190 	struct rpc_task_setup task_setup = {
1191 		.rpc_client = clnt,
1192 		.rpc_message = msg,
1193 		.callback_ops = clp->cl_mvops->call_sync_ops,
1194 		.callback_data = &data,
1195 		.flags = task_flags,
1196 	};
1197 
1198 	return nfs4_call_sync_custom(&task_setup);
1199 }
1200 
1201 static int nfs4_call_sync_sequence(struct rpc_clnt *clnt,
1202 				   struct nfs_server *server,
1203 				   struct rpc_message *msg,
1204 				   struct nfs4_sequence_args *args,
1205 				   struct nfs4_sequence_res *res)
1206 {
1207 	unsigned short task_flags = 0;
1208 
1209 	if (server->caps & NFS_CAP_MOVEABLE)
1210 		task_flags = RPC_TASK_MOVEABLE;
1211 	return nfs4_do_call_sync(clnt, server, msg, args, res, task_flags);
1212 }
1213 
1214 
1215 int nfs4_call_sync(struct rpc_clnt *clnt,
1216 		   struct nfs_server *server,
1217 		   struct rpc_message *msg,
1218 		   struct nfs4_sequence_args *args,
1219 		   struct nfs4_sequence_res *res,
1220 		   int cache_reply)
1221 {
1222 	nfs4_init_sequence(args, res, cache_reply, 0);
1223 	return nfs4_call_sync_sequence(clnt, server, msg, args, res);
1224 }
1225 
1226 static void
1227 nfs4_inc_nlink_locked(struct inode *inode)
1228 {
1229 	nfs_set_cache_invalid(inode, NFS_INO_INVALID_CHANGE |
1230 					     NFS_INO_INVALID_CTIME |
1231 					     NFS_INO_INVALID_NLINK);
1232 	inc_nlink(inode);
1233 }
1234 
1235 static void
1236 nfs4_inc_nlink(struct inode *inode)
1237 {
1238 	spin_lock(&inode->i_lock);
1239 	nfs4_inc_nlink_locked(inode);
1240 	spin_unlock(&inode->i_lock);
1241 }
1242 
1243 static void
1244 nfs4_dec_nlink_locked(struct inode *inode)
1245 {
1246 	nfs_set_cache_invalid(inode, NFS_INO_INVALID_CHANGE |
1247 					     NFS_INO_INVALID_CTIME |
1248 					     NFS_INO_INVALID_NLINK);
1249 	drop_nlink(inode);
1250 }
1251 
1252 static void
1253 nfs4_update_changeattr_locked(struct inode *inode,
1254 		struct nfs4_change_info *cinfo,
1255 		unsigned long timestamp, unsigned long cache_validity)
1256 {
1257 	struct nfs_inode *nfsi = NFS_I(inode);
1258 	u64 change_attr = inode_peek_iversion_raw(inode);
1259 
1260 	if (!nfs_have_delegated_mtime(inode))
1261 		cache_validity |= NFS_INO_INVALID_CTIME | NFS_INO_INVALID_MTIME;
1262 	if (S_ISDIR(inode->i_mode))
1263 		cache_validity |= NFS_INO_INVALID_DATA;
1264 
1265 	switch (NFS_SERVER(inode)->change_attr_type) {
1266 	case NFS4_CHANGE_TYPE_IS_UNDEFINED:
1267 		if (cinfo->after == change_attr)
1268 			goto out;
1269 		break;
1270 	default:
1271 		if ((s64)(change_attr - cinfo->after) >= 0)
1272 			goto out;
1273 	}
1274 
1275 	inode_set_iversion_raw(inode, cinfo->after);
1276 	if (!cinfo->atomic || cinfo->before != change_attr) {
1277 		if (S_ISDIR(inode->i_mode))
1278 			nfs_force_lookup_revalidate(inode);
1279 
1280 		if (!nfs_have_delegated_attributes(inode))
1281 			cache_validity |=
1282 				NFS_INO_INVALID_ACCESS | NFS_INO_INVALID_ACL |
1283 				NFS_INO_INVALID_SIZE | NFS_INO_INVALID_OTHER |
1284 				NFS_INO_INVALID_BLOCKS | NFS_INO_INVALID_NLINK |
1285 				NFS_INO_INVALID_MODE | NFS_INO_INVALID_XATTR;
1286 		nfsi->attrtimeo = NFS_MINATTRTIMEO(inode);
1287 	}
1288 	nfsi->attrtimeo_timestamp = jiffies;
1289 	nfsi->read_cache_jiffies = timestamp;
1290 	nfsi->attr_gencount = nfs_inc_attr_generation_counter();
1291 	nfsi->cache_validity &= ~NFS_INO_INVALID_CHANGE;
1292 out:
1293 	nfs_set_cache_invalid(inode, cache_validity);
1294 }
1295 
1296 void
1297 nfs4_update_changeattr(struct inode *dir, struct nfs4_change_info *cinfo,
1298 		unsigned long timestamp, unsigned long cache_validity)
1299 {
1300 	spin_lock(&dir->i_lock);
1301 	nfs4_update_changeattr_locked(dir, cinfo, timestamp, cache_validity);
1302 	spin_unlock(&dir->i_lock);
1303 }
1304 
1305 struct nfs4_open_createattrs {
1306 	struct nfs4_label *label;
1307 	struct iattr *sattr;
1308 	const __u32 verf[2];
1309 };
1310 
1311 static bool nfs4_clear_cap_atomic_open_v1(struct nfs_server *server,
1312 		int err, struct nfs4_exception *exception)
1313 {
1314 	if (err != -EINVAL)
1315 		return false;
1316 	if (!(server->caps & NFS_CAP_ATOMIC_OPEN_V1))
1317 		return false;
1318 	server->caps &= ~NFS_CAP_ATOMIC_OPEN_V1;
1319 	exception->retry = 1;
1320 	return true;
1321 }
1322 
1323 static fmode_t _nfs4_ctx_to_accessmode(const struct nfs_open_context *ctx)
1324 {
1325 	 return ctx->mode & (FMODE_READ|FMODE_WRITE|FMODE_EXEC);
1326 }
1327 
1328 static fmode_t _nfs4_ctx_to_openmode(const struct nfs_open_context *ctx)
1329 {
1330 	fmode_t ret = ctx->mode & (FMODE_READ|FMODE_WRITE);
1331 
1332 	return (ctx->mode & FMODE_EXEC) ? FMODE_READ | ret : ret;
1333 }
1334 
1335 static u32
1336 nfs4_fmode_to_share_access(fmode_t fmode)
1337 {
1338 	u32 res = 0;
1339 
1340 	switch (fmode & (FMODE_READ | FMODE_WRITE)) {
1341 	case FMODE_READ:
1342 		res = NFS4_SHARE_ACCESS_READ;
1343 		break;
1344 	case FMODE_WRITE:
1345 		res = NFS4_SHARE_ACCESS_WRITE;
1346 		break;
1347 	case FMODE_READ|FMODE_WRITE:
1348 		res = NFS4_SHARE_ACCESS_BOTH;
1349 	}
1350 	return res;
1351 }
1352 
1353 static u32
1354 nfs4_map_atomic_open_share(struct nfs_server *server,
1355 		fmode_t fmode, int openflags)
1356 {
1357 	u32 res = nfs4_fmode_to_share_access(fmode);
1358 
1359 	if (!(server->caps & NFS_CAP_ATOMIC_OPEN_V1))
1360 		goto out;
1361 	/* Want no delegation if we're using O_DIRECT */
1362 	if (openflags & O_DIRECT) {
1363 		res |= NFS4_SHARE_WANT_NO_DELEG;
1364 		goto out;
1365 	}
1366 	/* res |= NFS4_SHARE_WANT_NO_PREFERENCE; */
1367 	if (server->caps & NFS_CAP_DELEGTIME)
1368 		res |= NFS4_SHARE_WANT_DELEG_TIMESTAMPS;
1369 	if (server->caps & NFS_CAP_OPEN_XOR)
1370 		res |= NFS4_SHARE_WANT_OPEN_XOR_DELEGATION;
1371 out:
1372 	return res;
1373 }
1374 
1375 static enum open_claim_type4
1376 nfs4_map_atomic_open_claim(struct nfs_server *server,
1377 		enum open_claim_type4 claim)
1378 {
1379 	if (server->caps & NFS_CAP_ATOMIC_OPEN_V1)
1380 		return claim;
1381 	switch (claim) {
1382 	default:
1383 		return claim;
1384 	case NFS4_OPEN_CLAIM_FH:
1385 		return NFS4_OPEN_CLAIM_NULL;
1386 	case NFS4_OPEN_CLAIM_DELEG_CUR_FH:
1387 		return NFS4_OPEN_CLAIM_DELEGATE_CUR;
1388 	case NFS4_OPEN_CLAIM_DELEG_PREV_FH:
1389 		return NFS4_OPEN_CLAIM_DELEGATE_PREV;
1390 	}
1391 }
1392 
1393 static void nfs4_init_opendata_res(struct nfs4_opendata *p)
1394 {
1395 	p->o_res.f_attr = &p->f_attr;
1396 	p->o_res.seqid = p->o_arg.seqid;
1397 	p->c_res.seqid = p->c_arg.seqid;
1398 	p->o_res.server = p->o_arg.server;
1399 	p->o_res.access_request = p->o_arg.access;
1400 	nfs_fattr_init(&p->f_attr);
1401 	nfs_fattr_init_names(&p->f_attr, &p->owner_name, &p->group_name);
1402 }
1403 
1404 static struct nfs4_opendata *nfs4_opendata_alloc(struct dentry *dentry,
1405 		struct nfs4_state_owner *sp, fmode_t fmode, int flags,
1406 		const struct nfs4_open_createattrs *c,
1407 		enum open_claim_type4 claim,
1408 		gfp_t gfp_mask)
1409 {
1410 	struct dentry *parent = dget_parent(dentry);
1411 	struct inode *dir = d_inode(parent);
1412 	struct nfs_server *server = NFS_SERVER(dir);
1413 	struct nfs_seqid *(*alloc_seqid)(struct nfs_seqid_counter *, gfp_t);
1414 	struct nfs4_label *label = (c != NULL) ? c->label : NULL;
1415 	struct nfs4_opendata *p;
1416 
1417 	p = kzalloc(sizeof(*p), gfp_mask);
1418 	if (p == NULL)
1419 		goto err;
1420 
1421 	p->f_attr.label = nfs4_label_alloc(server, gfp_mask);
1422 	if (IS_ERR(p->f_attr.label))
1423 		goto err_free_p;
1424 
1425 	p->a_label = nfs4_label_alloc(server, gfp_mask);
1426 	if (IS_ERR(p->a_label))
1427 		goto err_free_f;
1428 
1429 	alloc_seqid = server->nfs_client->cl_mvops->alloc_seqid;
1430 	p->o_arg.seqid = alloc_seqid(&sp->so_seqid, gfp_mask);
1431 	if (IS_ERR(p->o_arg.seqid))
1432 		goto err_free_label;
1433 	nfs_sb_active(dentry->d_sb);
1434 	p->dentry = dget(dentry);
1435 	p->dir = parent;
1436 	p->owner = sp;
1437 	atomic_inc(&sp->so_count);
1438 	p->o_arg.open_flags = flags;
1439 	p->o_arg.fmode = fmode & (FMODE_READ|FMODE_WRITE);
1440 	p->o_arg.claim = nfs4_map_atomic_open_claim(server, claim);
1441 	p->o_arg.share_access = nfs4_map_atomic_open_share(server,
1442 			fmode, flags);
1443 	if (flags & O_CREAT) {
1444 		p->o_arg.umask = current_umask();
1445 		p->o_arg.label = nfs4_label_copy(p->a_label, label);
1446 		if (c->sattr != NULL && c->sattr->ia_valid != 0) {
1447 			p->o_arg.u.attrs = &p->attrs;
1448 			memcpy(&p->attrs, c->sattr, sizeof(p->attrs));
1449 
1450 			memcpy(p->o_arg.u.verifier.data, c->verf,
1451 					sizeof(p->o_arg.u.verifier.data));
1452 		}
1453 	}
1454 	/* ask server to check for all possible rights as results
1455 	 * are cached */
1456 	switch (p->o_arg.claim) {
1457 	default:
1458 		break;
1459 	case NFS4_OPEN_CLAIM_NULL:
1460 	case NFS4_OPEN_CLAIM_FH:
1461 		p->o_arg.access = NFS4_ACCESS_READ | NFS4_ACCESS_MODIFY |
1462 				  NFS4_ACCESS_EXTEND | NFS4_ACCESS_DELETE |
1463 				  NFS4_ACCESS_EXECUTE |
1464 				  nfs_access_xattr_mask(server);
1465 	}
1466 	p->o_arg.clientid = server->nfs_client->cl_clientid;
1467 	p->o_arg.id.create_time = ktime_to_ns(sp->so_seqid.create_time);
1468 	p->o_arg.id.uniquifier = sp->so_seqid.owner_id;
1469 	p->o_arg.name = &dentry->d_name;
1470 	p->o_arg.server = server;
1471 	p->o_arg.bitmask = nfs4_bitmask(server, label);
1472 	p->o_arg.open_bitmap = &nfs4_fattr_bitmap[0];
1473 	switch (p->o_arg.claim) {
1474 	case NFS4_OPEN_CLAIM_NULL:
1475 	case NFS4_OPEN_CLAIM_DELEGATE_CUR:
1476 	case NFS4_OPEN_CLAIM_DELEGATE_PREV:
1477 		p->o_arg.fh = NFS_FH(dir);
1478 		break;
1479 	case NFS4_OPEN_CLAIM_PREVIOUS:
1480 	case NFS4_OPEN_CLAIM_FH:
1481 	case NFS4_OPEN_CLAIM_DELEG_CUR_FH:
1482 	case NFS4_OPEN_CLAIM_DELEG_PREV_FH:
1483 		p->o_arg.fh = NFS_FH(d_inode(dentry));
1484 	}
1485 	p->c_arg.fh = &p->o_res.fh;
1486 	p->c_arg.stateid = &p->o_res.stateid;
1487 	p->c_arg.seqid = p->o_arg.seqid;
1488 	nfs4_init_opendata_res(p);
1489 	kref_init(&p->kref);
1490 	return p;
1491 
1492 err_free_label:
1493 	nfs4_label_free(p->a_label);
1494 err_free_f:
1495 	nfs4_label_free(p->f_attr.label);
1496 err_free_p:
1497 	kfree(p);
1498 err:
1499 	dput(parent);
1500 	return NULL;
1501 }
1502 
1503 static void nfs4_opendata_free(struct kref *kref)
1504 {
1505 	struct nfs4_opendata *p = container_of(kref,
1506 			struct nfs4_opendata, kref);
1507 	struct super_block *sb = p->dentry->d_sb;
1508 
1509 	nfs4_lgopen_release(p->lgp);
1510 	nfs_free_seqid(p->o_arg.seqid);
1511 	nfs4_sequence_free_slot(&p->o_res.seq_res);
1512 	if (p->state != NULL)
1513 		nfs4_put_open_state(p->state);
1514 	nfs4_put_state_owner(p->owner);
1515 
1516 	nfs4_label_free(p->a_label);
1517 	nfs4_label_free(p->f_attr.label);
1518 
1519 	dput(p->dir);
1520 	dput(p->dentry);
1521 	nfs_sb_deactive(sb);
1522 	nfs_fattr_free_names(&p->f_attr);
1523 	kfree(p->f_attr.mdsthreshold);
1524 	kfree(p);
1525 }
1526 
1527 static void nfs4_opendata_put(struct nfs4_opendata *p)
1528 {
1529 	if (p != NULL)
1530 		kref_put(&p->kref, nfs4_opendata_free);
1531 }
1532 
1533 static bool nfs4_mode_match_open_stateid(struct nfs4_state *state,
1534 		fmode_t fmode)
1535 {
1536 	switch(fmode & (FMODE_READ|FMODE_WRITE)) {
1537 	case FMODE_READ|FMODE_WRITE:
1538 		return state->n_rdwr != 0;
1539 	case FMODE_WRITE:
1540 		return state->n_wronly != 0;
1541 	case FMODE_READ:
1542 		return state->n_rdonly != 0;
1543 	}
1544 	WARN_ON_ONCE(1);
1545 	return false;
1546 }
1547 
1548 static int can_open_cached(struct nfs4_state *state, fmode_t mode,
1549 		int open_mode, enum open_claim_type4 claim)
1550 {
1551 	int ret = 0;
1552 
1553 	if (open_mode & (O_EXCL|O_TRUNC))
1554 		goto out;
1555 	switch (claim) {
1556 	case NFS4_OPEN_CLAIM_NULL:
1557 	case NFS4_OPEN_CLAIM_FH:
1558 		goto out;
1559 	default:
1560 		break;
1561 	}
1562 	switch (mode & (FMODE_READ|FMODE_WRITE)) {
1563 		case FMODE_READ:
1564 			ret |= test_bit(NFS_O_RDONLY_STATE, &state->flags) != 0
1565 				&& state->n_rdonly != 0;
1566 			break;
1567 		case FMODE_WRITE:
1568 			ret |= test_bit(NFS_O_WRONLY_STATE, &state->flags) != 0
1569 				&& state->n_wronly != 0;
1570 			break;
1571 		case FMODE_READ|FMODE_WRITE:
1572 			ret |= test_bit(NFS_O_RDWR_STATE, &state->flags) != 0
1573 				&& state->n_rdwr != 0;
1574 	}
1575 out:
1576 	return ret;
1577 }
1578 
1579 static int can_open_delegated(struct nfs_delegation *delegation, fmode_t fmode,
1580 		enum open_claim_type4 claim)
1581 {
1582 	if (delegation == NULL)
1583 		return 0;
1584 	if ((delegation->type & fmode) != fmode)
1585 		return 0;
1586 	switch (claim) {
1587 	case NFS4_OPEN_CLAIM_NULL:
1588 	case NFS4_OPEN_CLAIM_FH:
1589 		break;
1590 	case NFS4_OPEN_CLAIM_PREVIOUS:
1591 		if (!test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags))
1592 			break;
1593 		fallthrough;
1594 	default:
1595 		return 0;
1596 	}
1597 	nfs_mark_delegation_referenced(delegation);
1598 	return 1;
1599 }
1600 
1601 static void update_open_stateflags(struct nfs4_state *state, fmode_t fmode)
1602 {
1603 	switch (fmode) {
1604 		case FMODE_WRITE:
1605 			state->n_wronly++;
1606 			break;
1607 		case FMODE_READ:
1608 			state->n_rdonly++;
1609 			break;
1610 		case FMODE_READ|FMODE_WRITE:
1611 			state->n_rdwr++;
1612 	}
1613 	nfs4_state_set_mode_locked(state, state->state | fmode);
1614 }
1615 
1616 #ifdef CONFIG_NFS_V4_1
1617 static bool nfs_open_stateid_recover_openmode(struct nfs4_state *state)
1618 {
1619 	if (state->n_rdonly && !test_bit(NFS_O_RDONLY_STATE, &state->flags))
1620 		return true;
1621 	if (state->n_wronly && !test_bit(NFS_O_WRONLY_STATE, &state->flags))
1622 		return true;
1623 	if (state->n_rdwr && !test_bit(NFS_O_RDWR_STATE, &state->flags))
1624 		return true;
1625 	return false;
1626 }
1627 #endif /* CONFIG_NFS_V4_1 */
1628 
1629 static void nfs_state_log_update_open_stateid(struct nfs4_state *state)
1630 {
1631 	if (test_and_clear_bit(NFS_STATE_CHANGE_WAIT, &state->flags))
1632 		wake_up_all(&state->waitq);
1633 }
1634 
1635 static void nfs_test_and_clear_all_open_stateid(struct nfs4_state *state)
1636 {
1637 	struct nfs_client *clp = state->owner->so_server->nfs_client;
1638 	bool need_recover = false;
1639 
1640 	if (test_and_clear_bit(NFS_O_RDONLY_STATE, &state->flags) && state->n_rdonly)
1641 		need_recover = true;
1642 	if (test_and_clear_bit(NFS_O_WRONLY_STATE, &state->flags) && state->n_wronly)
1643 		need_recover = true;
1644 	if (test_and_clear_bit(NFS_O_RDWR_STATE, &state->flags) && state->n_rdwr)
1645 		need_recover = true;
1646 	if (need_recover)
1647 		nfs4_state_mark_reclaim_nograce(clp, state);
1648 }
1649 
1650 /*
1651  * Check for whether or not the caller may update the open stateid
1652  * to the value passed in by stateid.
1653  *
1654  * Note: This function relies heavily on the server implementing
1655  * RFC7530 Section 9.1.4.2, and RFC5661 Section 8.2.2
1656  * correctly.
1657  * i.e. The stateid seqids have to be initialised to 1, and
1658  * are then incremented on every state transition.
1659  */
1660 static bool nfs_stateid_is_sequential(struct nfs4_state *state,
1661 		const nfs4_stateid *stateid)
1662 {
1663 	if (test_bit(NFS_OPEN_STATE, &state->flags)) {
1664 		/* The common case - we're updating to a new sequence number */
1665 		if (nfs4_stateid_match_other(stateid, &state->open_stateid)) {
1666 			if (nfs4_stateid_is_next(&state->open_stateid, stateid))
1667 				return true;
1668 			return false;
1669 		}
1670 		/* The server returned a new stateid */
1671 	}
1672 	/* This is the first OPEN in this generation */
1673 	if (stateid->seqid == cpu_to_be32(1))
1674 		return true;
1675 	return false;
1676 }
1677 
1678 static void nfs_resync_open_stateid_locked(struct nfs4_state *state)
1679 {
1680 	if (!(state->n_wronly || state->n_rdonly || state->n_rdwr))
1681 		return;
1682 	if (state->n_wronly)
1683 		set_bit(NFS_O_WRONLY_STATE, &state->flags);
1684 	if (state->n_rdonly)
1685 		set_bit(NFS_O_RDONLY_STATE, &state->flags);
1686 	if (state->n_rdwr)
1687 		set_bit(NFS_O_RDWR_STATE, &state->flags);
1688 	set_bit(NFS_OPEN_STATE, &state->flags);
1689 }
1690 
1691 static void nfs_clear_open_stateid_locked(struct nfs4_state *state,
1692 		nfs4_stateid *stateid, fmode_t fmode)
1693 {
1694 	clear_bit(NFS_O_RDWR_STATE, &state->flags);
1695 	switch (fmode & (FMODE_READ|FMODE_WRITE)) {
1696 	case FMODE_WRITE:
1697 		clear_bit(NFS_O_RDONLY_STATE, &state->flags);
1698 		break;
1699 	case FMODE_READ:
1700 		clear_bit(NFS_O_WRONLY_STATE, &state->flags);
1701 		break;
1702 	case 0:
1703 		clear_bit(NFS_O_RDONLY_STATE, &state->flags);
1704 		clear_bit(NFS_O_WRONLY_STATE, &state->flags);
1705 		clear_bit(NFS_OPEN_STATE, &state->flags);
1706 	}
1707 	if (stateid == NULL)
1708 		return;
1709 	/* Handle OPEN+OPEN_DOWNGRADE races */
1710 	if (nfs4_stateid_match_other(stateid, &state->open_stateid) &&
1711 	    !nfs4_stateid_is_newer(stateid, &state->open_stateid)) {
1712 		nfs_resync_open_stateid_locked(state);
1713 		goto out;
1714 	}
1715 	if (test_bit(NFS_DELEGATED_STATE, &state->flags) == 0)
1716 		nfs4_stateid_copy(&state->stateid, stateid);
1717 	nfs4_stateid_copy(&state->open_stateid, stateid);
1718 	trace_nfs4_open_stateid_update(state->inode, stateid, 0);
1719 out:
1720 	nfs_state_log_update_open_stateid(state);
1721 }
1722 
1723 static void nfs_clear_open_stateid(struct nfs4_state *state,
1724 	nfs4_stateid *arg_stateid,
1725 	nfs4_stateid *stateid, fmode_t fmode)
1726 {
1727 	write_seqlock(&state->seqlock);
1728 	/* Ignore, if the CLOSE argment doesn't match the current stateid */
1729 	if (nfs4_state_match_open_stateid_other(state, arg_stateid))
1730 		nfs_clear_open_stateid_locked(state, stateid, fmode);
1731 	write_sequnlock(&state->seqlock);
1732 	if (test_bit(NFS_STATE_RECLAIM_NOGRACE, &state->flags))
1733 		nfs4_schedule_state_manager(state->owner->so_server->nfs_client);
1734 }
1735 
1736 static void nfs_set_open_stateid_locked(struct nfs4_state *state,
1737 		const nfs4_stateid *stateid, nfs4_stateid *freeme)
1738 	__must_hold(&state->owner->so_lock)
1739 	__must_hold(&state->seqlock)
1740 	__must_hold(RCU)
1741 
1742 {
1743 	DEFINE_WAIT(wait);
1744 	int status = 0;
1745 	for (;;) {
1746 
1747 		if (nfs_stateid_is_sequential(state, stateid))
1748 			break;
1749 
1750 		if (status)
1751 			break;
1752 		/* Rely on seqids for serialisation with NFSv4.0 */
1753 		if (!nfs4_has_session(NFS_SERVER(state->inode)->nfs_client))
1754 			break;
1755 
1756 		set_bit(NFS_STATE_CHANGE_WAIT, &state->flags);
1757 		prepare_to_wait(&state->waitq, &wait, TASK_KILLABLE);
1758 		/*
1759 		 * Ensure we process the state changes in the same order
1760 		 * in which the server processed them by delaying the
1761 		 * update of the stateid until we are in sequence.
1762 		 */
1763 		write_sequnlock(&state->seqlock);
1764 		spin_unlock(&state->owner->so_lock);
1765 		rcu_read_unlock();
1766 		trace_nfs4_open_stateid_update_wait(state->inode, stateid, 0);
1767 
1768 		if (!fatal_signal_pending(current)) {
1769 			if (schedule_timeout(5*HZ) == 0)
1770 				status = -EAGAIN;
1771 			else
1772 				status = 0;
1773 		} else
1774 			status = -EINTR;
1775 		finish_wait(&state->waitq, &wait);
1776 		rcu_read_lock();
1777 		spin_lock(&state->owner->so_lock);
1778 		write_seqlock(&state->seqlock);
1779 	}
1780 
1781 	if (test_bit(NFS_OPEN_STATE, &state->flags) &&
1782 	    !nfs4_stateid_match_other(stateid, &state->open_stateid)) {
1783 		nfs4_stateid_copy(freeme, &state->open_stateid);
1784 		nfs_test_and_clear_all_open_stateid(state);
1785 	}
1786 
1787 	if (test_bit(NFS_DELEGATED_STATE, &state->flags) == 0)
1788 		nfs4_stateid_copy(&state->stateid, stateid);
1789 	nfs4_stateid_copy(&state->open_stateid, stateid);
1790 	trace_nfs4_open_stateid_update(state->inode, stateid, status);
1791 	nfs_state_log_update_open_stateid(state);
1792 }
1793 
1794 static void nfs_state_set_open_stateid(struct nfs4_state *state,
1795 		const nfs4_stateid *open_stateid,
1796 		fmode_t fmode,
1797 		nfs4_stateid *freeme)
1798 {
1799 	/*
1800 	 * Protect the call to nfs4_state_set_mode_locked and
1801 	 * serialise the stateid update
1802 	 */
1803 	write_seqlock(&state->seqlock);
1804 	nfs_set_open_stateid_locked(state, open_stateid, freeme);
1805 	switch (fmode) {
1806 	case FMODE_READ:
1807 		set_bit(NFS_O_RDONLY_STATE, &state->flags);
1808 		break;
1809 	case FMODE_WRITE:
1810 		set_bit(NFS_O_WRONLY_STATE, &state->flags);
1811 		break;
1812 	case FMODE_READ|FMODE_WRITE:
1813 		set_bit(NFS_O_RDWR_STATE, &state->flags);
1814 	}
1815 	set_bit(NFS_OPEN_STATE, &state->flags);
1816 	write_sequnlock(&state->seqlock);
1817 }
1818 
1819 static void nfs_state_clear_open_state_flags(struct nfs4_state *state)
1820 {
1821 	clear_bit(NFS_O_RDWR_STATE, &state->flags);
1822 	clear_bit(NFS_O_WRONLY_STATE, &state->flags);
1823 	clear_bit(NFS_O_RDONLY_STATE, &state->flags);
1824 	clear_bit(NFS_OPEN_STATE, &state->flags);
1825 }
1826 
1827 static void nfs_state_set_delegation(struct nfs4_state *state,
1828 		const nfs4_stateid *deleg_stateid,
1829 		fmode_t fmode)
1830 {
1831 	/*
1832 	 * Protect the call to nfs4_state_set_mode_locked and
1833 	 * serialise the stateid update
1834 	 */
1835 	write_seqlock(&state->seqlock);
1836 	nfs4_stateid_copy(&state->stateid, deleg_stateid);
1837 	set_bit(NFS_DELEGATED_STATE, &state->flags);
1838 	write_sequnlock(&state->seqlock);
1839 }
1840 
1841 static void nfs_state_clear_delegation(struct nfs4_state *state)
1842 {
1843 	write_seqlock(&state->seqlock);
1844 	nfs4_stateid_copy(&state->stateid, &state->open_stateid);
1845 	clear_bit(NFS_DELEGATED_STATE, &state->flags);
1846 	write_sequnlock(&state->seqlock);
1847 }
1848 
1849 int update_open_stateid(struct nfs4_state *state,
1850 		const nfs4_stateid *open_stateid,
1851 		const nfs4_stateid *delegation,
1852 		fmode_t fmode)
1853 {
1854 	struct nfs_server *server = NFS_SERVER(state->inode);
1855 	struct nfs_client *clp = server->nfs_client;
1856 	struct nfs_inode *nfsi = NFS_I(state->inode);
1857 	struct nfs_delegation *deleg_cur;
1858 	nfs4_stateid freeme = { };
1859 	int ret = 0;
1860 
1861 	fmode &= (FMODE_READ|FMODE_WRITE);
1862 
1863 	rcu_read_lock();
1864 	spin_lock(&state->owner->so_lock);
1865 	if (open_stateid != NULL) {
1866 		nfs_state_set_open_stateid(state, open_stateid, fmode, &freeme);
1867 		ret = 1;
1868 	}
1869 
1870 	deleg_cur = nfs4_get_valid_delegation(state->inode);
1871 	if (deleg_cur == NULL)
1872 		goto no_delegation;
1873 
1874 	spin_lock(&deleg_cur->lock);
1875 	if (rcu_dereference(nfsi->delegation) != deleg_cur ||
1876 	   test_bit(NFS_DELEGATION_RETURNING, &deleg_cur->flags) ||
1877 	    (deleg_cur->type & fmode) != fmode)
1878 		goto no_delegation_unlock;
1879 
1880 	if (delegation == NULL)
1881 		delegation = &deleg_cur->stateid;
1882 	else if (!nfs4_stateid_match_other(&deleg_cur->stateid, delegation))
1883 		goto no_delegation_unlock;
1884 
1885 	nfs_mark_delegation_referenced(deleg_cur);
1886 	nfs_state_set_delegation(state, &deleg_cur->stateid, fmode);
1887 	ret = 1;
1888 no_delegation_unlock:
1889 	spin_unlock(&deleg_cur->lock);
1890 no_delegation:
1891 	if (ret)
1892 		update_open_stateflags(state, fmode);
1893 	spin_unlock(&state->owner->so_lock);
1894 	rcu_read_unlock();
1895 
1896 	if (test_bit(NFS_STATE_RECLAIM_NOGRACE, &state->flags))
1897 		nfs4_schedule_state_manager(clp);
1898 	if (freeme.type != 0)
1899 		nfs4_test_and_free_stateid(server, &freeme,
1900 				state->owner->so_cred);
1901 
1902 	return ret;
1903 }
1904 
1905 static bool nfs4_update_lock_stateid(struct nfs4_lock_state *lsp,
1906 		const nfs4_stateid *stateid)
1907 {
1908 	struct nfs4_state *state = lsp->ls_state;
1909 	bool ret = false;
1910 
1911 	spin_lock(&state->state_lock);
1912 	if (!nfs4_stateid_match_other(stateid, &lsp->ls_stateid))
1913 		goto out_noupdate;
1914 	if (!nfs4_stateid_is_newer(stateid, &lsp->ls_stateid))
1915 		goto out_noupdate;
1916 	nfs4_stateid_copy(&lsp->ls_stateid, stateid);
1917 	ret = true;
1918 out_noupdate:
1919 	spin_unlock(&state->state_lock);
1920 	return ret;
1921 }
1922 
1923 static void nfs4_return_incompatible_delegation(struct inode *inode, fmode_t fmode)
1924 {
1925 	struct nfs_delegation *delegation;
1926 
1927 	fmode &= FMODE_READ|FMODE_WRITE;
1928 	rcu_read_lock();
1929 	delegation = nfs4_get_valid_delegation(inode);
1930 	if (delegation == NULL || (delegation->type & fmode) == fmode) {
1931 		rcu_read_unlock();
1932 		return;
1933 	}
1934 	rcu_read_unlock();
1935 	nfs4_inode_return_delegation(inode);
1936 }
1937 
1938 static struct nfs4_state *nfs4_try_open_cached(struct nfs4_opendata *opendata)
1939 {
1940 	struct nfs4_state *state = opendata->state;
1941 	struct nfs_delegation *delegation;
1942 	int open_mode = opendata->o_arg.open_flags;
1943 	fmode_t fmode = opendata->o_arg.fmode;
1944 	enum open_claim_type4 claim = opendata->o_arg.claim;
1945 	nfs4_stateid stateid;
1946 	int ret = -EAGAIN;
1947 
1948 	for (;;) {
1949 		spin_lock(&state->owner->so_lock);
1950 		if (can_open_cached(state, fmode, open_mode, claim)) {
1951 			update_open_stateflags(state, fmode);
1952 			spin_unlock(&state->owner->so_lock);
1953 			goto out_return_state;
1954 		}
1955 		spin_unlock(&state->owner->so_lock);
1956 		rcu_read_lock();
1957 		delegation = nfs4_get_valid_delegation(state->inode);
1958 		if (!can_open_delegated(delegation, fmode, claim)) {
1959 			rcu_read_unlock();
1960 			break;
1961 		}
1962 		/* Save the delegation */
1963 		nfs4_stateid_copy(&stateid, &delegation->stateid);
1964 		rcu_read_unlock();
1965 		nfs_release_seqid(opendata->o_arg.seqid);
1966 		if (!opendata->is_recover) {
1967 			ret = nfs_may_open(state->inode, state->owner->so_cred, open_mode);
1968 			if (ret != 0)
1969 				goto out;
1970 		}
1971 		ret = -EAGAIN;
1972 
1973 		/* Try to update the stateid using the delegation */
1974 		if (update_open_stateid(state, NULL, &stateid, fmode))
1975 			goto out_return_state;
1976 	}
1977 out:
1978 	return ERR_PTR(ret);
1979 out_return_state:
1980 	refcount_inc(&state->count);
1981 	return state;
1982 }
1983 
1984 static void
1985 nfs4_process_delegation(struct inode *inode, const struct cred *cred,
1986 			enum open_claim_type4 claim,
1987 			const struct nfs4_open_delegation *delegation)
1988 {
1989 	switch (delegation->open_delegation_type) {
1990 	case NFS4_OPEN_DELEGATE_READ:
1991 	case NFS4_OPEN_DELEGATE_WRITE:
1992 	case NFS4_OPEN_DELEGATE_READ_ATTRS_DELEG:
1993 	case NFS4_OPEN_DELEGATE_WRITE_ATTRS_DELEG:
1994 		break;
1995 	default:
1996 		return;
1997 	}
1998 	switch (claim) {
1999 	case NFS4_OPEN_CLAIM_DELEGATE_CUR:
2000 	case NFS4_OPEN_CLAIM_DELEG_CUR_FH:
2001 		pr_err_ratelimited("NFS: Broken NFSv4 server %s is "
2002 				   "returning a delegation for "
2003 				   "OPEN(CLAIM_DELEGATE_CUR)\n",
2004 				   NFS_SERVER(inode)->nfs_client->cl_hostname);
2005 		break;
2006 	case NFS4_OPEN_CLAIM_PREVIOUS:
2007 		nfs_inode_reclaim_delegation(inode, cred, delegation->type,
2008 					     &delegation->stateid,
2009 					     delegation->pagemod_limit,
2010 					     delegation->open_delegation_type);
2011 		break;
2012 	default:
2013 		nfs_inode_set_delegation(inode, cred, delegation->type,
2014 					 &delegation->stateid,
2015 					 delegation->pagemod_limit,
2016 					 delegation->open_delegation_type);
2017 	}
2018 	if (delegation->do_recall)
2019 		nfs_async_inode_return_delegation(inode, &delegation->stateid);
2020 }
2021 
2022 /*
2023  * Check the inode attributes against the CLAIM_PREVIOUS returned attributes
2024  * and update the nfs4_state.
2025  */
2026 static struct nfs4_state *
2027 _nfs4_opendata_reclaim_to_nfs4_state(struct nfs4_opendata *data)
2028 {
2029 	struct inode *inode = data->state->inode;
2030 	struct nfs4_state *state = data->state;
2031 	int ret;
2032 
2033 	if (!data->rpc_done) {
2034 		if (data->rpc_status)
2035 			return ERR_PTR(data->rpc_status);
2036 		return nfs4_try_open_cached(data);
2037 	}
2038 
2039 	ret = nfs_refresh_inode(inode, &data->f_attr);
2040 	if (ret)
2041 		return ERR_PTR(ret);
2042 
2043 	nfs4_process_delegation(state->inode,
2044 				data->owner->so_cred,
2045 				data->o_arg.claim,
2046 				&data->o_res.delegation);
2047 
2048 	if (!(data->o_res.rflags & NFS4_OPEN_RESULT_NO_OPEN_STATEID)) {
2049 		if (!update_open_stateid(state, &data->o_res.stateid,
2050 					 NULL, data->o_arg.fmode))
2051 			return ERR_PTR(-EAGAIN);
2052 	} else if (!update_open_stateid(state, NULL, NULL, data->o_arg.fmode))
2053 		return ERR_PTR(-EAGAIN);
2054 	refcount_inc(&state->count);
2055 
2056 	return state;
2057 }
2058 
2059 static struct inode *
2060 nfs4_opendata_get_inode(struct nfs4_opendata *data)
2061 {
2062 	struct inode *inode;
2063 
2064 	switch (data->o_arg.claim) {
2065 	case NFS4_OPEN_CLAIM_NULL:
2066 	case NFS4_OPEN_CLAIM_DELEGATE_CUR:
2067 	case NFS4_OPEN_CLAIM_DELEGATE_PREV:
2068 		if (!(data->f_attr.valid & NFS_ATTR_FATTR))
2069 			return ERR_PTR(-EAGAIN);
2070 		inode = nfs_fhget(data->dir->d_sb, &data->o_res.fh,
2071 				&data->f_attr);
2072 		break;
2073 	default:
2074 		inode = d_inode(data->dentry);
2075 		ihold(inode);
2076 		nfs_refresh_inode(inode, &data->f_attr);
2077 	}
2078 	return inode;
2079 }
2080 
2081 static struct nfs4_state *
2082 nfs4_opendata_find_nfs4_state(struct nfs4_opendata *data)
2083 {
2084 	struct nfs4_state *state;
2085 	struct inode *inode;
2086 
2087 	inode = nfs4_opendata_get_inode(data);
2088 	if (IS_ERR(inode))
2089 		return ERR_CAST(inode);
2090 	if (data->state != NULL && data->state->inode == inode) {
2091 		state = data->state;
2092 		refcount_inc(&state->count);
2093 	} else
2094 		state = nfs4_get_open_state(inode, data->owner);
2095 	iput(inode);
2096 	if (state == NULL)
2097 		state = ERR_PTR(-ENOMEM);
2098 	return state;
2099 }
2100 
2101 static struct nfs4_state *
2102 _nfs4_opendata_to_nfs4_state(struct nfs4_opendata *data)
2103 {
2104 	struct nfs4_state *state;
2105 
2106 	if (!data->rpc_done) {
2107 		state = nfs4_try_open_cached(data);
2108 		trace_nfs4_cached_open(data->state);
2109 		goto out;
2110 	}
2111 
2112 	state = nfs4_opendata_find_nfs4_state(data);
2113 	if (IS_ERR(state))
2114 		goto out;
2115 
2116 	nfs4_process_delegation(state->inode,
2117 				data->owner->so_cred,
2118 				data->o_arg.claim,
2119 				&data->o_res.delegation);
2120 
2121 	if (!(data->o_res.rflags & NFS4_OPEN_RESULT_NO_OPEN_STATEID)) {
2122 		if (!update_open_stateid(state, &data->o_res.stateid,
2123 					 NULL, data->o_arg.fmode)) {
2124 			nfs4_put_open_state(state);
2125 			state = ERR_PTR(-EAGAIN);
2126 		}
2127 	} else if (!update_open_stateid(state, NULL, NULL, data->o_arg.fmode)) {
2128 		nfs4_put_open_state(state);
2129 		state = ERR_PTR(-EAGAIN);
2130 	}
2131 out:
2132 	nfs_release_seqid(data->o_arg.seqid);
2133 	return state;
2134 }
2135 
2136 static struct nfs4_state *
2137 nfs4_opendata_to_nfs4_state(struct nfs4_opendata *data)
2138 {
2139 	struct nfs4_state *ret;
2140 
2141 	if (data->o_arg.claim == NFS4_OPEN_CLAIM_PREVIOUS)
2142 		ret =_nfs4_opendata_reclaim_to_nfs4_state(data);
2143 	else
2144 		ret = _nfs4_opendata_to_nfs4_state(data);
2145 	nfs4_sequence_free_slot(&data->o_res.seq_res);
2146 	return ret;
2147 }
2148 
2149 static struct nfs_open_context *
2150 nfs4_state_find_open_context_mode(struct nfs4_state *state, fmode_t mode)
2151 {
2152 	struct nfs_inode *nfsi = NFS_I(state->inode);
2153 	struct nfs_open_context *ctx;
2154 
2155 	rcu_read_lock();
2156 	list_for_each_entry_rcu(ctx, &nfsi->open_files, list) {
2157 		if (ctx->state != state)
2158 			continue;
2159 		if ((ctx->mode & mode) != mode)
2160 			continue;
2161 		if (!get_nfs_open_context(ctx))
2162 			continue;
2163 		rcu_read_unlock();
2164 		return ctx;
2165 	}
2166 	rcu_read_unlock();
2167 	return ERR_PTR(-ENOENT);
2168 }
2169 
2170 static struct nfs_open_context *
2171 nfs4_state_find_open_context(struct nfs4_state *state)
2172 {
2173 	struct nfs_open_context *ctx;
2174 
2175 	ctx = nfs4_state_find_open_context_mode(state, FMODE_READ|FMODE_WRITE);
2176 	if (!IS_ERR(ctx))
2177 		return ctx;
2178 	ctx = nfs4_state_find_open_context_mode(state, FMODE_WRITE);
2179 	if (!IS_ERR(ctx))
2180 		return ctx;
2181 	return nfs4_state_find_open_context_mode(state, FMODE_READ);
2182 }
2183 
2184 static struct nfs4_opendata *nfs4_open_recoverdata_alloc(struct nfs_open_context *ctx,
2185 		struct nfs4_state *state, enum open_claim_type4 claim)
2186 {
2187 	struct nfs4_opendata *opendata;
2188 
2189 	opendata = nfs4_opendata_alloc(ctx->dentry, state->owner, 0, 0,
2190 			NULL, claim, GFP_NOFS);
2191 	if (opendata == NULL)
2192 		return ERR_PTR(-ENOMEM);
2193 	opendata->state = state;
2194 	refcount_inc(&state->count);
2195 	return opendata;
2196 }
2197 
2198 static int nfs4_open_recover_helper(struct nfs4_opendata *opendata,
2199 				    fmode_t fmode)
2200 {
2201 	struct nfs4_state *newstate;
2202 	struct nfs_server *server = NFS_SB(opendata->dentry->d_sb);
2203 	int openflags = opendata->o_arg.open_flags;
2204 	int ret;
2205 
2206 	if (!nfs4_mode_match_open_stateid(opendata->state, fmode))
2207 		return 0;
2208 	opendata->o_arg.fmode = fmode;
2209 	opendata->o_arg.share_access =
2210 		nfs4_map_atomic_open_share(server, fmode, openflags);
2211 	memset(&opendata->o_res, 0, sizeof(opendata->o_res));
2212 	memset(&opendata->c_res, 0, sizeof(opendata->c_res));
2213 	nfs4_init_opendata_res(opendata);
2214 	ret = _nfs4_recover_proc_open(opendata);
2215 	if (ret != 0)
2216 		return ret;
2217 	newstate = nfs4_opendata_to_nfs4_state(opendata);
2218 	if (IS_ERR(newstate))
2219 		return PTR_ERR(newstate);
2220 	if (newstate != opendata->state)
2221 		ret = -ESTALE;
2222 	nfs4_close_state(newstate, fmode);
2223 	return ret;
2224 }
2225 
2226 static int nfs4_open_recover(struct nfs4_opendata *opendata, struct nfs4_state *state)
2227 {
2228 	int ret;
2229 
2230 	/* memory barrier prior to reading state->n_* */
2231 	smp_rmb();
2232 	ret = nfs4_open_recover_helper(opendata, FMODE_READ|FMODE_WRITE);
2233 	if (ret != 0)
2234 		return ret;
2235 	ret = nfs4_open_recover_helper(opendata, FMODE_WRITE);
2236 	if (ret != 0)
2237 		return ret;
2238 	ret = nfs4_open_recover_helper(opendata, FMODE_READ);
2239 	if (ret != 0)
2240 		return ret;
2241 	/*
2242 	 * We may have performed cached opens for all three recoveries.
2243 	 * Check if we need to update the current stateid.
2244 	 */
2245 	if (test_bit(NFS_DELEGATED_STATE, &state->flags) == 0 &&
2246 	    !nfs4_stateid_match(&state->stateid, &state->open_stateid)) {
2247 		write_seqlock(&state->seqlock);
2248 		if (test_bit(NFS_DELEGATED_STATE, &state->flags) == 0)
2249 			nfs4_stateid_copy(&state->stateid, &state->open_stateid);
2250 		write_sequnlock(&state->seqlock);
2251 	}
2252 	return 0;
2253 }
2254 
2255 /*
2256  * OPEN_RECLAIM:
2257  * 	reclaim state on the server after a reboot.
2258  */
2259 static int _nfs4_do_open_reclaim(struct nfs_open_context *ctx, struct nfs4_state *state)
2260 {
2261 	struct nfs_delegation *delegation;
2262 	struct nfs4_opendata *opendata;
2263 	u32 delegation_type = NFS4_OPEN_DELEGATE_NONE;
2264 	int status;
2265 
2266 	opendata = nfs4_open_recoverdata_alloc(ctx, state,
2267 			NFS4_OPEN_CLAIM_PREVIOUS);
2268 	if (IS_ERR(opendata))
2269 		return PTR_ERR(opendata);
2270 	rcu_read_lock();
2271 	delegation = rcu_dereference(NFS_I(state->inode)->delegation);
2272 	if (delegation != NULL && test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags) != 0) {
2273 		switch(delegation->type) {
2274 		case FMODE_READ:
2275 			delegation_type = NFS4_OPEN_DELEGATE_READ;
2276 			if (test_bit(NFS_DELEGATION_DELEGTIME, &delegation->flags))
2277 				delegation_type = NFS4_OPEN_DELEGATE_READ_ATTRS_DELEG;
2278 			break;
2279 		case FMODE_WRITE:
2280 		case FMODE_READ|FMODE_WRITE:
2281 			delegation_type = NFS4_OPEN_DELEGATE_WRITE;
2282 			if (test_bit(NFS_DELEGATION_DELEGTIME, &delegation->flags))
2283 				delegation_type = NFS4_OPEN_DELEGATE_WRITE_ATTRS_DELEG;
2284 		}
2285 	}
2286 	rcu_read_unlock();
2287 	opendata->o_arg.u.delegation_type = delegation_type;
2288 	status = nfs4_open_recover(opendata, state);
2289 	nfs4_opendata_put(opendata);
2290 	return status;
2291 }
2292 
2293 static int nfs4_do_open_reclaim(struct nfs_open_context *ctx, struct nfs4_state *state)
2294 {
2295 	struct nfs_server *server = NFS_SERVER(state->inode);
2296 	struct nfs4_exception exception = { };
2297 	int err;
2298 	do {
2299 		err = _nfs4_do_open_reclaim(ctx, state);
2300 		trace_nfs4_open_reclaim(ctx, 0, err);
2301 		if (nfs4_clear_cap_atomic_open_v1(server, err, &exception))
2302 			continue;
2303 		if (err != -NFS4ERR_DELAY)
2304 			break;
2305 		nfs4_handle_exception(server, err, &exception);
2306 	} while (exception.retry);
2307 	return err;
2308 }
2309 
2310 static int nfs4_open_reclaim(struct nfs4_state_owner *sp, struct nfs4_state *state)
2311 {
2312 	struct nfs_open_context *ctx;
2313 	int ret;
2314 
2315 	ctx = nfs4_state_find_open_context(state);
2316 	if (IS_ERR(ctx))
2317 		return -EAGAIN;
2318 	clear_bit(NFS_DELEGATED_STATE, &state->flags);
2319 	nfs_state_clear_open_state_flags(state);
2320 	ret = nfs4_do_open_reclaim(ctx, state);
2321 	put_nfs_open_context(ctx);
2322 	return ret;
2323 }
2324 
2325 static int nfs4_handle_delegation_recall_error(struct nfs_server *server, struct nfs4_state *state, const nfs4_stateid *stateid, struct file_lock *fl, int err)
2326 {
2327 	switch (err) {
2328 		default:
2329 			printk(KERN_ERR "NFS: %s: unhandled error "
2330 					"%d.\n", __func__, err);
2331 			fallthrough;
2332 		case 0:
2333 		case -ENOENT:
2334 		case -EAGAIN:
2335 		case -ESTALE:
2336 		case -ETIMEDOUT:
2337 			break;
2338 		case -NFS4ERR_BADSESSION:
2339 		case -NFS4ERR_BADSLOT:
2340 		case -NFS4ERR_BAD_HIGH_SLOT:
2341 		case -NFS4ERR_CONN_NOT_BOUND_TO_SESSION:
2342 		case -NFS4ERR_DEADSESSION:
2343 			return -EAGAIN;
2344 		case -NFS4ERR_STALE_CLIENTID:
2345 		case -NFS4ERR_STALE_STATEID:
2346 			/* Don't recall a delegation if it was lost */
2347 			nfs4_schedule_lease_recovery(server->nfs_client);
2348 			return -EAGAIN;
2349 		case -NFS4ERR_MOVED:
2350 			nfs4_schedule_migration_recovery(server);
2351 			return -EAGAIN;
2352 		case -NFS4ERR_LEASE_MOVED:
2353 			nfs4_schedule_lease_moved_recovery(server->nfs_client);
2354 			return -EAGAIN;
2355 		case -NFS4ERR_DELEG_REVOKED:
2356 		case -NFS4ERR_ADMIN_REVOKED:
2357 		case -NFS4ERR_EXPIRED:
2358 		case -NFS4ERR_BAD_STATEID:
2359 		case -NFS4ERR_OPENMODE:
2360 			nfs_inode_find_state_and_recover(state->inode,
2361 					stateid);
2362 			nfs4_schedule_stateid_recovery(server, state);
2363 			return -EAGAIN;
2364 		case -NFS4ERR_DELAY:
2365 		case -NFS4ERR_GRACE:
2366 			ssleep(1);
2367 			return -EAGAIN;
2368 		case -ENOMEM:
2369 		case -NFS4ERR_DENIED:
2370 			if (fl) {
2371 				struct nfs4_lock_state *lsp = fl->fl_u.nfs4_fl.owner;
2372 				if (lsp)
2373 					set_bit(NFS_LOCK_LOST, &lsp->ls_flags);
2374 			}
2375 			return 0;
2376 	}
2377 	return err;
2378 }
2379 
2380 int nfs4_open_delegation_recall(struct nfs_open_context *ctx,
2381 		struct nfs4_state *state, const nfs4_stateid *stateid)
2382 {
2383 	struct nfs_server *server = NFS_SERVER(state->inode);
2384 	struct nfs4_opendata *opendata;
2385 	int err = 0;
2386 
2387 	opendata = nfs4_open_recoverdata_alloc(ctx, state,
2388 			NFS4_OPEN_CLAIM_DELEG_CUR_FH);
2389 	if (IS_ERR(opendata))
2390 		return PTR_ERR(opendata);
2391 	nfs4_stateid_copy(&opendata->o_arg.u.delegation, stateid);
2392 	if (!test_bit(NFS_O_RDWR_STATE, &state->flags)) {
2393 		err = nfs4_open_recover_helper(opendata, FMODE_READ|FMODE_WRITE);
2394 		if (err)
2395 			goto out;
2396 	}
2397 	if (!test_bit(NFS_O_WRONLY_STATE, &state->flags)) {
2398 		err = nfs4_open_recover_helper(opendata, FMODE_WRITE);
2399 		if (err)
2400 			goto out;
2401 	}
2402 	if (!test_bit(NFS_O_RDONLY_STATE, &state->flags)) {
2403 		err = nfs4_open_recover_helper(opendata, FMODE_READ);
2404 		if (err)
2405 			goto out;
2406 	}
2407 	nfs_state_clear_delegation(state);
2408 out:
2409 	nfs4_opendata_put(opendata);
2410 	return nfs4_handle_delegation_recall_error(server, state, stateid, NULL, err);
2411 }
2412 
2413 static void nfs4_open_confirm_prepare(struct rpc_task *task, void *calldata)
2414 {
2415 	struct nfs4_opendata *data = calldata;
2416 
2417 	nfs4_setup_sequence(data->o_arg.server->nfs_client,
2418 			   &data->c_arg.seq_args, &data->c_res.seq_res, task);
2419 }
2420 
2421 static void nfs4_open_confirm_done(struct rpc_task *task, void *calldata)
2422 {
2423 	struct nfs4_opendata *data = calldata;
2424 
2425 	nfs40_sequence_done(task, &data->c_res.seq_res);
2426 
2427 	data->rpc_status = task->tk_status;
2428 	if (data->rpc_status == 0) {
2429 		nfs4_stateid_copy(&data->o_res.stateid, &data->c_res.stateid);
2430 		nfs_confirm_seqid(&data->owner->so_seqid, 0);
2431 		renew_lease(data->o_res.server, data->timestamp);
2432 		data->rpc_done = true;
2433 	}
2434 }
2435 
2436 static void nfs4_open_confirm_release(void *calldata)
2437 {
2438 	struct nfs4_opendata *data = calldata;
2439 	struct nfs4_state *state = NULL;
2440 
2441 	/* If this request hasn't been cancelled, do nothing */
2442 	if (!data->cancelled)
2443 		goto out_free;
2444 	/* In case of error, no cleanup! */
2445 	if (!data->rpc_done)
2446 		goto out_free;
2447 	state = nfs4_opendata_to_nfs4_state(data);
2448 	if (!IS_ERR(state))
2449 		nfs4_close_state(state, data->o_arg.fmode);
2450 out_free:
2451 	nfs4_opendata_put(data);
2452 }
2453 
2454 static const struct rpc_call_ops nfs4_open_confirm_ops = {
2455 	.rpc_call_prepare = nfs4_open_confirm_prepare,
2456 	.rpc_call_done = nfs4_open_confirm_done,
2457 	.rpc_release = nfs4_open_confirm_release,
2458 };
2459 
2460 /*
2461  * Note: On error, nfs4_proc_open_confirm will free the struct nfs4_opendata
2462  */
2463 static int _nfs4_proc_open_confirm(struct nfs4_opendata *data)
2464 {
2465 	struct nfs_server *server = NFS_SERVER(d_inode(data->dir));
2466 	struct rpc_task *task;
2467 	struct  rpc_message msg = {
2468 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_CONFIRM],
2469 		.rpc_argp = &data->c_arg,
2470 		.rpc_resp = &data->c_res,
2471 		.rpc_cred = data->owner->so_cred,
2472 	};
2473 	struct rpc_task_setup task_setup_data = {
2474 		.rpc_client = server->client,
2475 		.rpc_message = &msg,
2476 		.callback_ops = &nfs4_open_confirm_ops,
2477 		.callback_data = data,
2478 		.workqueue = nfsiod_workqueue,
2479 		.flags = RPC_TASK_ASYNC | RPC_TASK_CRED_NOREF,
2480 	};
2481 	int status;
2482 
2483 	nfs4_init_sequence(&data->c_arg.seq_args, &data->c_res.seq_res, 1,
2484 				data->is_recover);
2485 	kref_get(&data->kref);
2486 	data->rpc_done = false;
2487 	data->rpc_status = 0;
2488 	data->timestamp = jiffies;
2489 	task = rpc_run_task(&task_setup_data);
2490 	if (IS_ERR(task))
2491 		return PTR_ERR(task);
2492 	status = rpc_wait_for_completion_task(task);
2493 	if (status != 0) {
2494 		data->cancelled = true;
2495 		smp_wmb();
2496 	} else
2497 		status = data->rpc_status;
2498 	rpc_put_task(task);
2499 	return status;
2500 }
2501 
2502 static void nfs4_open_prepare(struct rpc_task *task, void *calldata)
2503 {
2504 	struct nfs4_opendata *data = calldata;
2505 	struct nfs4_state_owner *sp = data->owner;
2506 	struct nfs_client *clp = sp->so_server->nfs_client;
2507 	enum open_claim_type4 claim = data->o_arg.claim;
2508 
2509 	if (nfs_wait_on_sequence(data->o_arg.seqid, task) != 0)
2510 		goto out_wait;
2511 	/*
2512 	 * Check if we still need to send an OPEN call, or if we can use
2513 	 * a delegation instead.
2514 	 */
2515 	if (data->state != NULL) {
2516 		struct nfs_delegation *delegation;
2517 
2518 		if (can_open_cached(data->state, data->o_arg.fmode,
2519 					data->o_arg.open_flags, claim))
2520 			goto out_no_action;
2521 		rcu_read_lock();
2522 		delegation = nfs4_get_valid_delegation(data->state->inode);
2523 		if (can_open_delegated(delegation, data->o_arg.fmode, claim))
2524 			goto unlock_no_action;
2525 		rcu_read_unlock();
2526 	}
2527 	/* Update client id. */
2528 	data->o_arg.clientid = clp->cl_clientid;
2529 	switch (claim) {
2530 	default:
2531 		break;
2532 	case NFS4_OPEN_CLAIM_PREVIOUS:
2533 	case NFS4_OPEN_CLAIM_DELEG_CUR_FH:
2534 	case NFS4_OPEN_CLAIM_DELEG_PREV_FH:
2535 		data->o_arg.open_bitmap = &nfs4_open_noattr_bitmap[0];
2536 		fallthrough;
2537 	case NFS4_OPEN_CLAIM_FH:
2538 		task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_NOATTR];
2539 	}
2540 	data->timestamp = jiffies;
2541 	if (nfs4_setup_sequence(data->o_arg.server->nfs_client,
2542 				&data->o_arg.seq_args,
2543 				&data->o_res.seq_res,
2544 				task) != 0)
2545 		nfs_release_seqid(data->o_arg.seqid);
2546 
2547 	/* Set the create mode (note dependency on the session type) */
2548 	data->o_arg.createmode = NFS4_CREATE_UNCHECKED;
2549 	if (data->o_arg.open_flags & O_EXCL) {
2550 		data->o_arg.createmode = NFS4_CREATE_EXCLUSIVE4_1;
2551 		if (clp->cl_mvops->minor_version == 0) {
2552 			data->o_arg.createmode = NFS4_CREATE_EXCLUSIVE;
2553 			/* don't put an ACCESS op in OPEN compound if O_EXCL,
2554 			 * because ACCESS will return permission denied for
2555 			 * all bits until close */
2556 			data->o_res.access_request = data->o_arg.access = 0;
2557 		} else if (nfs4_has_persistent_session(clp))
2558 			data->o_arg.createmode = NFS4_CREATE_GUARDED;
2559 	}
2560 	return;
2561 unlock_no_action:
2562 	trace_nfs4_cached_open(data->state);
2563 	rcu_read_unlock();
2564 out_no_action:
2565 	task->tk_action = NULL;
2566 out_wait:
2567 	nfs4_sequence_done(task, &data->o_res.seq_res);
2568 }
2569 
2570 static void nfs4_open_done(struct rpc_task *task, void *calldata)
2571 {
2572 	struct nfs4_opendata *data = calldata;
2573 
2574 	data->rpc_status = task->tk_status;
2575 
2576 	if (!nfs4_sequence_process(task, &data->o_res.seq_res))
2577 		return;
2578 
2579 	if (task->tk_status == 0) {
2580 		if (data->o_res.f_attr->valid & NFS_ATTR_FATTR_TYPE) {
2581 			switch (data->o_res.f_attr->mode & S_IFMT) {
2582 			case S_IFREG:
2583 				break;
2584 			case S_IFLNK:
2585 				data->rpc_status = -ELOOP;
2586 				break;
2587 			case S_IFDIR:
2588 				data->rpc_status = -EISDIR;
2589 				break;
2590 			default:
2591 				data->rpc_status = -ENOTDIR;
2592 			}
2593 		}
2594 		renew_lease(data->o_res.server, data->timestamp);
2595 		if (!(data->o_res.rflags & NFS4_OPEN_RESULT_CONFIRM))
2596 			nfs_confirm_seqid(&data->owner->so_seqid, 0);
2597 	}
2598 	data->rpc_done = true;
2599 }
2600 
2601 static void nfs4_open_release(void *calldata)
2602 {
2603 	struct nfs4_opendata *data = calldata;
2604 	struct nfs4_state *state = NULL;
2605 
2606 	/* If this request hasn't been cancelled, do nothing */
2607 	if (!data->cancelled)
2608 		goto out_free;
2609 	/* In case of error, no cleanup! */
2610 	if (data->rpc_status != 0 || !data->rpc_done)
2611 		goto out_free;
2612 	/* In case we need an open_confirm, no cleanup! */
2613 	if (data->o_res.rflags & NFS4_OPEN_RESULT_CONFIRM)
2614 		goto out_free;
2615 	state = nfs4_opendata_to_nfs4_state(data);
2616 	if (!IS_ERR(state))
2617 		nfs4_close_state(state, data->o_arg.fmode);
2618 out_free:
2619 	nfs4_opendata_put(data);
2620 }
2621 
2622 static const struct rpc_call_ops nfs4_open_ops = {
2623 	.rpc_call_prepare = nfs4_open_prepare,
2624 	.rpc_call_done = nfs4_open_done,
2625 	.rpc_release = nfs4_open_release,
2626 };
2627 
2628 static int nfs4_run_open_task(struct nfs4_opendata *data,
2629 			      struct nfs_open_context *ctx)
2630 {
2631 	struct inode *dir = d_inode(data->dir);
2632 	struct nfs_server *server = NFS_SERVER(dir);
2633 	struct nfs_openargs *o_arg = &data->o_arg;
2634 	struct nfs_openres *o_res = &data->o_res;
2635 	struct rpc_task *task;
2636 	struct rpc_message msg = {
2637 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN],
2638 		.rpc_argp = o_arg,
2639 		.rpc_resp = o_res,
2640 		.rpc_cred = data->owner->so_cred,
2641 	};
2642 	struct rpc_task_setup task_setup_data = {
2643 		.rpc_client = server->client,
2644 		.rpc_message = &msg,
2645 		.callback_ops = &nfs4_open_ops,
2646 		.callback_data = data,
2647 		.workqueue = nfsiod_workqueue,
2648 		.flags = RPC_TASK_ASYNC | RPC_TASK_CRED_NOREF,
2649 	};
2650 	int status;
2651 
2652 	if (nfs_server_capable(dir, NFS_CAP_MOVEABLE))
2653 		task_setup_data.flags |= RPC_TASK_MOVEABLE;
2654 
2655 	kref_get(&data->kref);
2656 	data->rpc_done = false;
2657 	data->rpc_status = 0;
2658 	data->cancelled = false;
2659 	data->is_recover = false;
2660 	if (!ctx) {
2661 		nfs4_init_sequence(&o_arg->seq_args, &o_res->seq_res, 1, 1);
2662 		data->is_recover = true;
2663 		task_setup_data.flags |= RPC_TASK_TIMEOUT;
2664 	} else {
2665 		nfs4_init_sequence(&o_arg->seq_args, &o_res->seq_res, 1, 0);
2666 		pnfs_lgopen_prepare(data, ctx);
2667 	}
2668 	task = rpc_run_task(&task_setup_data);
2669 	if (IS_ERR(task))
2670 		return PTR_ERR(task);
2671 	status = rpc_wait_for_completion_task(task);
2672 	if (status != 0) {
2673 		data->cancelled = true;
2674 		smp_wmb();
2675 	} else
2676 		status = data->rpc_status;
2677 	rpc_put_task(task);
2678 
2679 	return status;
2680 }
2681 
2682 static int _nfs4_recover_proc_open(struct nfs4_opendata *data)
2683 {
2684 	struct inode *dir = d_inode(data->dir);
2685 	struct nfs_openres *o_res = &data->o_res;
2686 	int status;
2687 
2688 	status = nfs4_run_open_task(data, NULL);
2689 	if (status != 0 || !data->rpc_done)
2690 		return status;
2691 
2692 	nfs_fattr_map_and_free_names(NFS_SERVER(dir), &data->f_attr);
2693 
2694 	if (o_res->rflags & NFS4_OPEN_RESULT_CONFIRM)
2695 		status = _nfs4_proc_open_confirm(data);
2696 
2697 	return status;
2698 }
2699 
2700 /*
2701  * Additional permission checks in order to distinguish between an
2702  * open for read, and an open for execute. This works around the
2703  * fact that NFSv4 OPEN treats read and execute permissions as being
2704  * the same.
2705  * Note that in the non-execute case, we want to turn off permission
2706  * checking if we just created a new file (POSIX open() semantics).
2707  */
2708 static int nfs4_opendata_access(const struct cred *cred,
2709 				struct nfs4_opendata *opendata,
2710 				struct nfs4_state *state, fmode_t fmode)
2711 {
2712 	struct nfs_access_entry cache;
2713 	u32 mask, flags;
2714 
2715 	/* access call failed or for some reason the server doesn't
2716 	 * support any access modes -- defer access call until later */
2717 	if (opendata->o_res.access_supported == 0)
2718 		return 0;
2719 
2720 	mask = 0;
2721 	if (fmode & FMODE_EXEC) {
2722 		/* ONLY check for exec rights */
2723 		if (S_ISDIR(state->inode->i_mode))
2724 			mask = NFS4_ACCESS_LOOKUP;
2725 		else
2726 			mask = NFS4_ACCESS_EXECUTE;
2727 	} else if ((fmode & FMODE_READ) && !opendata->file_created)
2728 		mask = NFS4_ACCESS_READ;
2729 
2730 	nfs_access_set_mask(&cache, opendata->o_res.access_result);
2731 	nfs_access_add_cache(state->inode, &cache, cred);
2732 
2733 	flags = NFS4_ACCESS_READ | NFS4_ACCESS_EXECUTE | NFS4_ACCESS_LOOKUP;
2734 	if ((mask & ~cache.mask & flags) == 0)
2735 		return 0;
2736 
2737 	return -EACCES;
2738 }
2739 
2740 /*
2741  * Note: On error, nfs4_proc_open will free the struct nfs4_opendata
2742  */
2743 static int _nfs4_proc_open(struct nfs4_opendata *data,
2744 			   struct nfs_open_context *ctx)
2745 {
2746 	struct inode *dir = d_inode(data->dir);
2747 	struct nfs_server *server = NFS_SERVER(dir);
2748 	struct nfs_openargs *o_arg = &data->o_arg;
2749 	struct nfs_openres *o_res = &data->o_res;
2750 	int status;
2751 
2752 	status = nfs4_run_open_task(data, ctx);
2753 	if (!data->rpc_done)
2754 		return status;
2755 	if (status != 0) {
2756 		if (status == -NFS4ERR_BADNAME &&
2757 				!(o_arg->open_flags & O_CREAT))
2758 			return -ENOENT;
2759 		return status;
2760 	}
2761 
2762 	nfs_fattr_map_and_free_names(server, &data->f_attr);
2763 
2764 	if (o_arg->open_flags & O_CREAT) {
2765 		if (o_arg->open_flags & O_EXCL)
2766 			data->file_created = true;
2767 		else if (o_res->cinfo.before != o_res->cinfo.after)
2768 			data->file_created = true;
2769 		if (data->file_created ||
2770 		    inode_peek_iversion_raw(dir) != o_res->cinfo.after)
2771 			nfs4_update_changeattr(dir, &o_res->cinfo,
2772 					o_res->f_attr->time_start,
2773 					NFS_INO_INVALID_DATA);
2774 	}
2775 	if ((o_res->rflags & NFS4_OPEN_RESULT_LOCKTYPE_POSIX) == 0)
2776 		server->caps &= ~NFS_CAP_POSIX_LOCK;
2777 	if(o_res->rflags & NFS4_OPEN_RESULT_CONFIRM) {
2778 		status = _nfs4_proc_open_confirm(data);
2779 		if (status != 0)
2780 			return status;
2781 	}
2782 	if (!(o_res->f_attr->valid & NFS_ATTR_FATTR)) {
2783 		struct nfs_fh *fh = &o_res->fh;
2784 
2785 		nfs4_sequence_free_slot(&o_res->seq_res);
2786 		if (o_arg->claim == NFS4_OPEN_CLAIM_FH)
2787 			fh = NFS_FH(d_inode(data->dentry));
2788 		nfs4_proc_getattr(server, fh, o_res->f_attr, NULL);
2789 	}
2790 	return 0;
2791 }
2792 
2793 /*
2794  * OPEN_EXPIRED:
2795  * 	reclaim state on the server after a network partition.
2796  * 	Assumes caller holds the appropriate lock
2797  */
2798 static int _nfs4_open_expired(struct nfs_open_context *ctx, struct nfs4_state *state)
2799 {
2800 	struct nfs4_opendata *opendata;
2801 	int ret;
2802 
2803 	opendata = nfs4_open_recoverdata_alloc(ctx, state, NFS4_OPEN_CLAIM_FH);
2804 	if (IS_ERR(opendata))
2805 		return PTR_ERR(opendata);
2806 	/*
2807 	 * We're not recovering a delegation, so ask for no delegation.
2808 	 * Otherwise the recovery thread could deadlock with an outstanding
2809 	 * delegation return.
2810 	 */
2811 	opendata->o_arg.open_flags = O_DIRECT;
2812 	ret = nfs4_open_recover(opendata, state);
2813 	if (ret == -ESTALE)
2814 		d_drop(ctx->dentry);
2815 	nfs4_opendata_put(opendata);
2816 	return ret;
2817 }
2818 
2819 static int nfs4_do_open_expired(struct nfs_open_context *ctx, struct nfs4_state *state)
2820 {
2821 	struct nfs_server *server = NFS_SERVER(state->inode);
2822 	struct nfs4_exception exception = { };
2823 	int err;
2824 
2825 	do {
2826 		err = _nfs4_open_expired(ctx, state);
2827 		trace_nfs4_open_expired(ctx, 0, err);
2828 		if (nfs4_clear_cap_atomic_open_v1(server, err, &exception))
2829 			continue;
2830 		switch (err) {
2831 		default:
2832 			goto out;
2833 		case -NFS4ERR_GRACE:
2834 		case -NFS4ERR_DELAY:
2835 			nfs4_handle_exception(server, err, &exception);
2836 			err = 0;
2837 		}
2838 	} while (exception.retry);
2839 out:
2840 	return err;
2841 }
2842 
2843 static int nfs4_open_expired(struct nfs4_state_owner *sp, struct nfs4_state *state)
2844 {
2845 	struct nfs_open_context *ctx;
2846 	int ret;
2847 
2848 	ctx = nfs4_state_find_open_context(state);
2849 	if (IS_ERR(ctx))
2850 		return -EAGAIN;
2851 	ret = nfs4_do_open_expired(ctx, state);
2852 	put_nfs_open_context(ctx);
2853 	return ret;
2854 }
2855 
2856 static void nfs_finish_clear_delegation_stateid(struct nfs4_state *state,
2857 		const nfs4_stateid *stateid)
2858 {
2859 	nfs_remove_bad_delegation(state->inode, stateid);
2860 	nfs_state_clear_delegation(state);
2861 }
2862 
2863 static void nfs40_clear_delegation_stateid(struct nfs4_state *state)
2864 {
2865 	if (rcu_access_pointer(NFS_I(state->inode)->delegation) != NULL)
2866 		nfs_finish_clear_delegation_stateid(state, NULL);
2867 }
2868 
2869 static int nfs40_open_expired(struct nfs4_state_owner *sp, struct nfs4_state *state)
2870 {
2871 	/* NFSv4.0 doesn't allow for delegation recovery on open expire */
2872 	nfs40_clear_delegation_stateid(state);
2873 	nfs_state_clear_open_state_flags(state);
2874 	return nfs4_open_expired(sp, state);
2875 }
2876 
2877 static int nfs40_test_and_free_expired_stateid(struct nfs_server *server,
2878 					       const nfs4_stateid *stateid,
2879 					       const struct cred *cred)
2880 {
2881 	return -NFS4ERR_BAD_STATEID;
2882 }
2883 
2884 #if defined(CONFIG_NFS_V4_1)
2885 static int nfs41_test_and_free_expired_stateid(struct nfs_server *server,
2886 					       const nfs4_stateid *stateid,
2887 					       const struct cred *cred)
2888 {
2889 	int status;
2890 
2891 	switch (stateid->type) {
2892 	default:
2893 		break;
2894 	case NFS4_INVALID_STATEID_TYPE:
2895 	case NFS4_SPECIAL_STATEID_TYPE:
2896 		return -NFS4ERR_BAD_STATEID;
2897 	case NFS4_REVOKED_STATEID_TYPE:
2898 		goto out_free;
2899 	}
2900 
2901 	status = nfs41_test_stateid(server, stateid, cred);
2902 	switch (status) {
2903 	case -NFS4ERR_EXPIRED:
2904 	case -NFS4ERR_ADMIN_REVOKED:
2905 	case -NFS4ERR_DELEG_REVOKED:
2906 		break;
2907 	default:
2908 		return status;
2909 	}
2910 out_free:
2911 	/* Ack the revoked state to the server */
2912 	nfs41_free_stateid(server, stateid, cred, true);
2913 	return -NFS4ERR_EXPIRED;
2914 }
2915 
2916 static int nfs41_check_delegation_stateid(struct nfs4_state *state)
2917 {
2918 	struct nfs_server *server = NFS_SERVER(state->inode);
2919 	nfs4_stateid stateid;
2920 	struct nfs_delegation *delegation;
2921 	const struct cred *cred = NULL;
2922 	int status, ret = NFS_OK;
2923 
2924 	/* Get the delegation credential for use by test/free_stateid */
2925 	rcu_read_lock();
2926 	delegation = rcu_dereference(NFS_I(state->inode)->delegation);
2927 	if (delegation == NULL) {
2928 		rcu_read_unlock();
2929 		nfs_state_clear_delegation(state);
2930 		return NFS_OK;
2931 	}
2932 
2933 	spin_lock(&delegation->lock);
2934 	nfs4_stateid_copy(&stateid, &delegation->stateid);
2935 
2936 	if (!test_and_clear_bit(NFS_DELEGATION_TEST_EXPIRED,
2937 				&delegation->flags)) {
2938 		spin_unlock(&delegation->lock);
2939 		rcu_read_unlock();
2940 		return NFS_OK;
2941 	}
2942 
2943 	if (delegation->cred)
2944 		cred = get_cred(delegation->cred);
2945 	spin_unlock(&delegation->lock);
2946 	rcu_read_unlock();
2947 	status = nfs41_test_and_free_expired_stateid(server, &stateid, cred);
2948 	trace_nfs4_test_delegation_stateid(state, NULL, status);
2949 	if (status == -NFS4ERR_EXPIRED || status == -NFS4ERR_BAD_STATEID)
2950 		nfs_finish_clear_delegation_stateid(state, &stateid);
2951 	else
2952 		ret = status;
2953 
2954 	put_cred(cred);
2955 	return ret;
2956 }
2957 
2958 static void nfs41_delegation_recover_stateid(struct nfs4_state *state)
2959 {
2960 	nfs4_stateid tmp;
2961 
2962 	if (test_bit(NFS_DELEGATED_STATE, &state->flags) &&
2963 	    nfs4_copy_delegation_stateid(state->inode, state->state,
2964 				&tmp, NULL) &&
2965 	    nfs4_stateid_match_other(&state->stateid, &tmp))
2966 		nfs_state_set_delegation(state, &tmp, state->state);
2967 	else
2968 		nfs_state_clear_delegation(state);
2969 }
2970 
2971 /**
2972  * nfs41_check_expired_locks - possibly free a lock stateid
2973  *
2974  * @state: NFSv4 state for an inode
2975  *
2976  * Returns NFS_OK if recovery for this stateid is now finished.
2977  * Otherwise a negative NFS4ERR value is returned.
2978  */
2979 static int nfs41_check_expired_locks(struct nfs4_state *state)
2980 {
2981 	int status, ret = NFS_OK;
2982 	struct nfs4_lock_state *lsp, *prev = NULL;
2983 	struct nfs_server *server = NFS_SERVER(state->inode);
2984 
2985 	if (!test_bit(LK_STATE_IN_USE, &state->flags))
2986 		goto out;
2987 
2988 	spin_lock(&state->state_lock);
2989 	list_for_each_entry(lsp, &state->lock_states, ls_locks) {
2990 		if (test_bit(NFS_LOCK_INITIALIZED, &lsp->ls_flags)) {
2991 			const struct cred *cred = lsp->ls_state->owner->so_cred;
2992 
2993 			refcount_inc(&lsp->ls_count);
2994 			spin_unlock(&state->state_lock);
2995 
2996 			nfs4_put_lock_state(prev);
2997 			prev = lsp;
2998 
2999 			status = nfs41_test_and_free_expired_stateid(server,
3000 					&lsp->ls_stateid,
3001 					cred);
3002 			trace_nfs4_test_lock_stateid(state, lsp, status);
3003 			if (status == -NFS4ERR_EXPIRED ||
3004 			    status == -NFS4ERR_BAD_STATEID) {
3005 				clear_bit(NFS_LOCK_INITIALIZED, &lsp->ls_flags);
3006 				lsp->ls_stateid.type = NFS4_INVALID_STATEID_TYPE;
3007 				if (!recover_lost_locks)
3008 					set_bit(NFS_LOCK_LOST, &lsp->ls_flags);
3009 			} else if (status != NFS_OK) {
3010 				ret = status;
3011 				nfs4_put_lock_state(prev);
3012 				goto out;
3013 			}
3014 			spin_lock(&state->state_lock);
3015 		}
3016 	}
3017 	spin_unlock(&state->state_lock);
3018 	nfs4_put_lock_state(prev);
3019 out:
3020 	return ret;
3021 }
3022 
3023 /**
3024  * nfs41_check_open_stateid - possibly free an open stateid
3025  *
3026  * @state: NFSv4 state for an inode
3027  *
3028  * Returns NFS_OK if recovery for this stateid is now finished.
3029  * Otherwise a negative NFS4ERR value is returned.
3030  */
3031 static int nfs41_check_open_stateid(struct nfs4_state *state)
3032 {
3033 	struct nfs_server *server = NFS_SERVER(state->inode);
3034 	nfs4_stateid *stateid = &state->open_stateid;
3035 	const struct cred *cred = state->owner->so_cred;
3036 	int status;
3037 
3038 	if (test_bit(NFS_OPEN_STATE, &state->flags) == 0)
3039 		return -NFS4ERR_BAD_STATEID;
3040 	status = nfs41_test_and_free_expired_stateid(server, stateid, cred);
3041 	trace_nfs4_test_open_stateid(state, NULL, status);
3042 	if (status == -NFS4ERR_EXPIRED || status == -NFS4ERR_BAD_STATEID) {
3043 		nfs_state_clear_open_state_flags(state);
3044 		stateid->type = NFS4_INVALID_STATEID_TYPE;
3045 		return status;
3046 	}
3047 	if (nfs_open_stateid_recover_openmode(state))
3048 		return -NFS4ERR_OPENMODE;
3049 	return NFS_OK;
3050 }
3051 
3052 static int nfs41_open_expired(struct nfs4_state_owner *sp, struct nfs4_state *state)
3053 {
3054 	int status;
3055 
3056 	status = nfs41_check_delegation_stateid(state);
3057 	if (status != NFS_OK)
3058 		return status;
3059 	nfs41_delegation_recover_stateid(state);
3060 
3061 	status = nfs41_check_expired_locks(state);
3062 	if (status != NFS_OK)
3063 		return status;
3064 	status = nfs41_check_open_stateid(state);
3065 	if (status != NFS_OK)
3066 		status = nfs4_open_expired(sp, state);
3067 	return status;
3068 }
3069 #endif
3070 
3071 /*
3072  * on an EXCLUSIVE create, the server should send back a bitmask with FATTR4-*
3073  * fields corresponding to attributes that were used to store the verifier.
3074  * Make sure we clobber those fields in the later setattr call
3075  */
3076 static unsigned nfs4_exclusive_attrset(struct nfs4_opendata *opendata,
3077 				struct iattr *sattr, struct nfs4_label **label)
3078 {
3079 	const __u32 *bitmask = opendata->o_arg.server->exclcreat_bitmask;
3080 	__u32 attrset[3];
3081 	unsigned ret;
3082 	unsigned i;
3083 
3084 	for (i = 0; i < ARRAY_SIZE(attrset); i++) {
3085 		attrset[i] = opendata->o_res.attrset[i];
3086 		if (opendata->o_arg.createmode == NFS4_CREATE_EXCLUSIVE4_1)
3087 			attrset[i] &= ~bitmask[i];
3088 	}
3089 
3090 	ret = (opendata->o_arg.createmode == NFS4_CREATE_EXCLUSIVE) ?
3091 		sattr->ia_valid : 0;
3092 
3093 	if ((attrset[1] & (FATTR4_WORD1_TIME_ACCESS|FATTR4_WORD1_TIME_ACCESS_SET))) {
3094 		if (sattr->ia_valid & ATTR_ATIME_SET)
3095 			ret |= ATTR_ATIME_SET;
3096 		else
3097 			ret |= ATTR_ATIME;
3098 	}
3099 
3100 	if ((attrset[1] & (FATTR4_WORD1_TIME_MODIFY|FATTR4_WORD1_TIME_MODIFY_SET))) {
3101 		if (sattr->ia_valid & ATTR_MTIME_SET)
3102 			ret |= ATTR_MTIME_SET;
3103 		else
3104 			ret |= ATTR_MTIME;
3105 	}
3106 
3107 	if (!(attrset[2] & FATTR4_WORD2_SECURITY_LABEL))
3108 		*label = NULL;
3109 	return ret;
3110 }
3111 
3112 static int _nfs4_open_and_get_state(struct nfs4_opendata *opendata,
3113 		struct nfs_open_context *ctx)
3114 {
3115 	struct nfs4_state_owner *sp = opendata->owner;
3116 	struct nfs_server *server = sp->so_server;
3117 	struct dentry *dentry;
3118 	struct nfs4_state *state;
3119 	fmode_t acc_mode = _nfs4_ctx_to_accessmode(ctx);
3120 	struct inode *dir = d_inode(opendata->dir);
3121 	unsigned long dir_verifier;
3122 	int ret;
3123 
3124 	dir_verifier = nfs_save_change_attribute(dir);
3125 
3126 	ret = _nfs4_proc_open(opendata, ctx);
3127 	if (ret != 0)
3128 		goto out;
3129 
3130 	state = _nfs4_opendata_to_nfs4_state(opendata);
3131 	ret = PTR_ERR(state);
3132 	if (IS_ERR(state))
3133 		goto out;
3134 	ctx->state = state;
3135 	if (server->caps & NFS_CAP_POSIX_LOCK)
3136 		set_bit(NFS_STATE_POSIX_LOCKS, &state->flags);
3137 	if (opendata->o_res.rflags & NFS4_OPEN_RESULT_MAY_NOTIFY_LOCK)
3138 		set_bit(NFS_STATE_MAY_NOTIFY_LOCK, &state->flags);
3139 	if (opendata->o_res.rflags & NFS4_OPEN_RESULT_PRESERVE_UNLINKED)
3140 		set_bit(NFS_INO_PRESERVE_UNLINKED, &NFS_I(state->inode)->flags);
3141 
3142 	dentry = opendata->dentry;
3143 	if (d_really_is_negative(dentry)) {
3144 		struct dentry *alias;
3145 		d_drop(dentry);
3146 		alias = d_exact_alias(dentry, state->inode);
3147 		if (!alias)
3148 			alias = d_splice_alias(igrab(state->inode), dentry);
3149 		/* d_splice_alias() can't fail here - it's a non-directory */
3150 		if (alias) {
3151 			dput(ctx->dentry);
3152 			ctx->dentry = dentry = alias;
3153 		}
3154 	}
3155 
3156 	switch(opendata->o_arg.claim) {
3157 	default:
3158 		break;
3159 	case NFS4_OPEN_CLAIM_NULL:
3160 	case NFS4_OPEN_CLAIM_DELEGATE_CUR:
3161 	case NFS4_OPEN_CLAIM_DELEGATE_PREV:
3162 		if (!opendata->rpc_done)
3163 			break;
3164 		if (opendata->o_res.delegation.type != 0)
3165 			dir_verifier = nfs_save_change_attribute(dir);
3166 		nfs_set_verifier(dentry, dir_verifier);
3167 	}
3168 
3169 	/* Parse layoutget results before we check for access */
3170 	pnfs_parse_lgopen(state->inode, opendata->lgp, ctx);
3171 
3172 	ret = nfs4_opendata_access(sp->so_cred, opendata, state, acc_mode);
3173 	if (ret != 0)
3174 		goto out;
3175 
3176 	if (d_inode(dentry) == state->inode)
3177 		nfs_inode_attach_open_context(ctx);
3178 
3179 out:
3180 	if (!opendata->cancelled) {
3181 		if (opendata->lgp) {
3182 			nfs4_lgopen_release(opendata->lgp);
3183 			opendata->lgp = NULL;
3184 		}
3185 		nfs4_sequence_free_slot(&opendata->o_res.seq_res);
3186 	}
3187 	return ret;
3188 }
3189 
3190 /*
3191  * Returns a referenced nfs4_state
3192  */
3193 static int _nfs4_do_open(struct inode *dir,
3194 			struct nfs_open_context *ctx,
3195 			int flags,
3196 			const struct nfs4_open_createattrs *c,
3197 			int *opened)
3198 {
3199 	struct nfs4_state_owner  *sp;
3200 	struct nfs4_state     *state = NULL;
3201 	struct nfs_server       *server = NFS_SERVER(dir);
3202 	struct nfs4_opendata *opendata;
3203 	struct dentry *dentry = ctx->dentry;
3204 	const struct cred *cred = ctx->cred;
3205 	struct nfs4_threshold **ctx_th = &ctx->mdsthreshold;
3206 	fmode_t fmode = _nfs4_ctx_to_openmode(ctx);
3207 	enum open_claim_type4 claim = NFS4_OPEN_CLAIM_NULL;
3208 	struct iattr *sattr = c->sattr;
3209 	struct nfs4_label *label = c->label;
3210 	int status;
3211 
3212 	/* Protect against reboot recovery conflicts */
3213 	status = -ENOMEM;
3214 	sp = nfs4_get_state_owner(server, cred, GFP_KERNEL);
3215 	if (sp == NULL) {
3216 		dprintk("nfs4_do_open: nfs4_get_state_owner failed!\n");
3217 		goto out_err;
3218 	}
3219 	status = nfs4_client_recover_expired_lease(server->nfs_client);
3220 	if (status != 0)
3221 		goto err_put_state_owner;
3222 	if (d_really_is_positive(dentry))
3223 		nfs4_return_incompatible_delegation(d_inode(dentry), fmode);
3224 	status = -ENOMEM;
3225 	if (d_really_is_positive(dentry))
3226 		claim = NFS4_OPEN_CLAIM_FH;
3227 	opendata = nfs4_opendata_alloc(dentry, sp, fmode, flags,
3228 			c, claim, GFP_KERNEL);
3229 	if (opendata == NULL)
3230 		goto err_put_state_owner;
3231 
3232 	if (server->attr_bitmask[2] & FATTR4_WORD2_MDSTHRESHOLD) {
3233 		if (!opendata->f_attr.mdsthreshold) {
3234 			opendata->f_attr.mdsthreshold = pnfs_mdsthreshold_alloc();
3235 			if (!opendata->f_attr.mdsthreshold)
3236 				goto err_opendata_put;
3237 		}
3238 		opendata->o_arg.open_bitmap = &nfs4_pnfs_open_bitmap[0];
3239 	}
3240 	if (d_really_is_positive(dentry))
3241 		opendata->state = nfs4_get_open_state(d_inode(dentry), sp);
3242 
3243 	status = _nfs4_open_and_get_state(opendata, ctx);
3244 	if (status != 0)
3245 		goto err_opendata_put;
3246 	state = ctx->state;
3247 
3248 	if ((opendata->o_arg.open_flags & (O_CREAT|O_EXCL)) == (O_CREAT|O_EXCL) &&
3249 	    (opendata->o_arg.createmode != NFS4_CREATE_GUARDED)) {
3250 		unsigned attrs = nfs4_exclusive_attrset(opendata, sattr, &label);
3251 		/*
3252 		 * send create attributes which was not set by open
3253 		 * with an extra setattr.
3254 		 */
3255 		if (attrs || label) {
3256 			unsigned ia_old = sattr->ia_valid;
3257 
3258 			sattr->ia_valid = attrs;
3259 			nfs_fattr_init(opendata->o_res.f_attr);
3260 			status = nfs4_do_setattr(state->inode, cred,
3261 					opendata->o_res.f_attr, sattr,
3262 					ctx, label);
3263 			if (status == 0) {
3264 				nfs_setattr_update_inode(state->inode, sattr,
3265 						opendata->o_res.f_attr);
3266 				nfs_setsecurity(state->inode, opendata->o_res.f_attr);
3267 			}
3268 			sattr->ia_valid = ia_old;
3269 		}
3270 	}
3271 	if (opened && opendata->file_created)
3272 		*opened = 1;
3273 
3274 	if (pnfs_use_threshold(ctx_th, opendata->f_attr.mdsthreshold, server)) {
3275 		*ctx_th = opendata->f_attr.mdsthreshold;
3276 		opendata->f_attr.mdsthreshold = NULL;
3277 	}
3278 
3279 	nfs4_opendata_put(opendata);
3280 	nfs4_put_state_owner(sp);
3281 	return 0;
3282 err_opendata_put:
3283 	nfs4_opendata_put(opendata);
3284 err_put_state_owner:
3285 	nfs4_put_state_owner(sp);
3286 out_err:
3287 	return status;
3288 }
3289 
3290 
3291 static struct nfs4_state *nfs4_do_open(struct inode *dir,
3292 					struct nfs_open_context *ctx,
3293 					int flags,
3294 					struct iattr *sattr,
3295 					struct nfs4_label *label,
3296 					int *opened)
3297 {
3298 	struct nfs_server *server = NFS_SERVER(dir);
3299 	struct nfs4_exception exception = {
3300 		.interruptible = true,
3301 	};
3302 	struct nfs4_state *res;
3303 	struct nfs4_open_createattrs c = {
3304 		.label = label,
3305 		.sattr = sattr,
3306 		.verf = {
3307 			[0] = (__u32)jiffies,
3308 			[1] = (__u32)current->pid,
3309 		},
3310 	};
3311 	int status;
3312 
3313 	do {
3314 		status = _nfs4_do_open(dir, ctx, flags, &c, opened);
3315 		res = ctx->state;
3316 		trace_nfs4_open_file(ctx, flags, status);
3317 		if (status == 0)
3318 			break;
3319 		/* NOTE: BAD_SEQID means the server and client disagree about the
3320 		 * book-keeping w.r.t. state-changing operations
3321 		 * (OPEN/CLOSE/LOCK/LOCKU...)
3322 		 * It is actually a sign of a bug on the client or on the server.
3323 		 *
3324 		 * If we receive a BAD_SEQID error in the particular case of
3325 		 * doing an OPEN, we assume that nfs_increment_open_seqid() will
3326 		 * have unhashed the old state_owner for us, and that we can
3327 		 * therefore safely retry using a new one. We should still warn
3328 		 * the user though...
3329 		 */
3330 		if (status == -NFS4ERR_BAD_SEQID) {
3331 			pr_warn_ratelimited("NFS: v4 server %s "
3332 					" returned a bad sequence-id error!\n",
3333 					NFS_SERVER(dir)->nfs_client->cl_hostname);
3334 			exception.retry = 1;
3335 			continue;
3336 		}
3337 		/*
3338 		 * BAD_STATEID on OPEN means that the server cancelled our
3339 		 * state before it received the OPEN_CONFIRM.
3340 		 * Recover by retrying the request as per the discussion
3341 		 * on Page 181 of RFC3530.
3342 		 */
3343 		if (status == -NFS4ERR_BAD_STATEID) {
3344 			exception.retry = 1;
3345 			continue;
3346 		}
3347 		if (status == -NFS4ERR_EXPIRED) {
3348 			nfs4_schedule_lease_recovery(server->nfs_client);
3349 			exception.retry = 1;
3350 			continue;
3351 		}
3352 		if (status == -EAGAIN) {
3353 			/* We must have found a delegation */
3354 			exception.retry = 1;
3355 			continue;
3356 		}
3357 		if (nfs4_clear_cap_atomic_open_v1(server, status, &exception))
3358 			continue;
3359 		res = ERR_PTR(nfs4_handle_exception(server,
3360 					status, &exception));
3361 	} while (exception.retry);
3362 	return res;
3363 }
3364 
3365 static int _nfs4_do_setattr(struct inode *inode,
3366 			    struct nfs_setattrargs *arg,
3367 			    struct nfs_setattrres *res,
3368 			    const struct cred *cred,
3369 			    struct nfs_open_context *ctx)
3370 {
3371 	struct nfs_server *server = NFS_SERVER(inode);
3372 	struct rpc_message msg = {
3373 		.rpc_proc	= &nfs4_procedures[NFSPROC4_CLNT_SETATTR],
3374 		.rpc_argp	= arg,
3375 		.rpc_resp	= res,
3376 		.rpc_cred	= cred,
3377 	};
3378 	const struct cred *delegation_cred = NULL;
3379 	unsigned long timestamp = jiffies;
3380 	bool truncate;
3381 	int status;
3382 
3383 	nfs_fattr_init(res->fattr);
3384 
3385 	/* Servers should only apply open mode checks for file size changes */
3386 	truncate = (arg->iap->ia_valid & ATTR_SIZE) ? true : false;
3387 	if (!truncate) {
3388 		nfs4_inode_make_writeable(inode);
3389 		goto zero_stateid;
3390 	}
3391 
3392 	if (nfs4_copy_delegation_stateid(inode, FMODE_WRITE, &arg->stateid, &delegation_cred)) {
3393 		/* Use that stateid */
3394 	} else if (ctx != NULL && ctx->state) {
3395 		struct nfs_lock_context *l_ctx;
3396 		if (!nfs4_valid_open_stateid(ctx->state))
3397 			return -EBADF;
3398 		l_ctx = nfs_get_lock_context(ctx);
3399 		if (IS_ERR(l_ctx))
3400 			return PTR_ERR(l_ctx);
3401 		status = nfs4_select_rw_stateid(ctx->state, FMODE_WRITE, l_ctx,
3402 						&arg->stateid, &delegation_cred);
3403 		nfs_put_lock_context(l_ctx);
3404 		if (status == -EIO)
3405 			return -EBADF;
3406 		else if (status == -EAGAIN)
3407 			goto zero_stateid;
3408 	} else {
3409 zero_stateid:
3410 		nfs4_stateid_copy(&arg->stateid, &zero_stateid);
3411 	}
3412 	if (delegation_cred)
3413 		msg.rpc_cred = delegation_cred;
3414 
3415 	status = nfs4_call_sync(server->client, server, &msg, &arg->seq_args, &res->seq_res, 1);
3416 
3417 	put_cred(delegation_cred);
3418 	if (status == 0 && ctx != NULL)
3419 		renew_lease(server, timestamp);
3420 	trace_nfs4_setattr(inode, &arg->stateid, status);
3421 	return status;
3422 }
3423 
3424 static int nfs4_do_setattr(struct inode *inode, const struct cred *cred,
3425 			   struct nfs_fattr *fattr, struct iattr *sattr,
3426 			   struct nfs_open_context *ctx, struct nfs4_label *ilabel)
3427 {
3428 	struct nfs_server *server = NFS_SERVER(inode);
3429 	__u32 bitmask[NFS4_BITMASK_SZ];
3430 	struct nfs4_state *state = ctx ? ctx->state : NULL;
3431 	struct nfs_setattrargs	arg = {
3432 		.fh		= NFS_FH(inode),
3433 		.iap		= sattr,
3434 		.server		= server,
3435 		.bitmask = bitmask,
3436 		.label		= ilabel,
3437 	};
3438 	struct nfs_setattrres  res = {
3439 		.fattr		= fattr,
3440 		.server		= server,
3441 	};
3442 	struct nfs4_exception exception = {
3443 		.state = state,
3444 		.inode = inode,
3445 		.stateid = &arg.stateid,
3446 	};
3447 	unsigned long adjust_flags = NFS_INO_INVALID_CHANGE |
3448 				     NFS_INO_INVALID_CTIME;
3449 	int err;
3450 
3451 	if (sattr->ia_valid & (ATTR_MODE | ATTR_KILL_SUID | ATTR_KILL_SGID))
3452 		adjust_flags |= NFS_INO_INVALID_MODE;
3453 	if (sattr->ia_valid & (ATTR_UID | ATTR_GID))
3454 		adjust_flags |= NFS_INO_INVALID_OTHER;
3455 
3456 	do {
3457 		nfs4_bitmap_copy_adjust(bitmask, nfs4_bitmask(server, fattr->label),
3458 					inode, adjust_flags);
3459 
3460 		err = _nfs4_do_setattr(inode, &arg, &res, cred, ctx);
3461 		switch (err) {
3462 		case -NFS4ERR_OPENMODE:
3463 			if (!(sattr->ia_valid & ATTR_SIZE)) {
3464 				pr_warn_once("NFSv4: server %s is incorrectly "
3465 						"applying open mode checks to "
3466 						"a SETATTR that is not "
3467 						"changing file size.\n",
3468 						server->nfs_client->cl_hostname);
3469 			}
3470 			if (state && !(state->state & FMODE_WRITE)) {
3471 				err = -EBADF;
3472 				if (sattr->ia_valid & ATTR_OPEN)
3473 					err = -EACCES;
3474 				goto out;
3475 			}
3476 		}
3477 		err = nfs4_handle_exception(server, err, &exception);
3478 	} while (exception.retry);
3479 out:
3480 	return err;
3481 }
3482 
3483 static bool
3484 nfs4_wait_on_layoutreturn(struct inode *inode, struct rpc_task *task)
3485 {
3486 	if (inode == NULL || !nfs_have_layout(inode))
3487 		return false;
3488 
3489 	return pnfs_wait_on_layoutreturn(inode, task);
3490 }
3491 
3492 /*
3493  * Update the seqid of an open stateid
3494  */
3495 static void nfs4_sync_open_stateid(nfs4_stateid *dst,
3496 		struct nfs4_state *state)
3497 {
3498 	__be32 seqid_open;
3499 	u32 dst_seqid;
3500 	int seq;
3501 
3502 	for (;;) {
3503 		if (!nfs4_valid_open_stateid(state))
3504 			break;
3505 		seq = read_seqbegin(&state->seqlock);
3506 		if (!nfs4_state_match_open_stateid_other(state, dst)) {
3507 			nfs4_stateid_copy(dst, &state->open_stateid);
3508 			if (read_seqretry(&state->seqlock, seq))
3509 				continue;
3510 			break;
3511 		}
3512 		seqid_open = state->open_stateid.seqid;
3513 		if (read_seqretry(&state->seqlock, seq))
3514 			continue;
3515 
3516 		dst_seqid = be32_to_cpu(dst->seqid);
3517 		if ((s32)(dst_seqid - be32_to_cpu(seqid_open)) < 0)
3518 			dst->seqid = seqid_open;
3519 		break;
3520 	}
3521 }
3522 
3523 /*
3524  * Update the seqid of an open stateid after receiving
3525  * NFS4ERR_OLD_STATEID
3526  */
3527 static bool nfs4_refresh_open_old_stateid(nfs4_stateid *dst,
3528 		struct nfs4_state *state)
3529 {
3530 	__be32 seqid_open;
3531 	u32 dst_seqid;
3532 	bool ret;
3533 	int seq, status = -EAGAIN;
3534 	DEFINE_WAIT(wait);
3535 
3536 	for (;;) {
3537 		ret = false;
3538 		if (!nfs4_valid_open_stateid(state))
3539 			break;
3540 		seq = read_seqbegin(&state->seqlock);
3541 		if (!nfs4_state_match_open_stateid_other(state, dst)) {
3542 			if (read_seqretry(&state->seqlock, seq))
3543 				continue;
3544 			break;
3545 		}
3546 
3547 		write_seqlock(&state->seqlock);
3548 		seqid_open = state->open_stateid.seqid;
3549 
3550 		dst_seqid = be32_to_cpu(dst->seqid);
3551 
3552 		/* Did another OPEN bump the state's seqid?  try again: */
3553 		if ((s32)(be32_to_cpu(seqid_open) - dst_seqid) > 0) {
3554 			dst->seqid = seqid_open;
3555 			write_sequnlock(&state->seqlock);
3556 			ret = true;
3557 			break;
3558 		}
3559 
3560 		/* server says we're behind but we haven't seen the update yet */
3561 		set_bit(NFS_STATE_CHANGE_WAIT, &state->flags);
3562 		prepare_to_wait(&state->waitq, &wait, TASK_KILLABLE);
3563 		write_sequnlock(&state->seqlock);
3564 		trace_nfs4_close_stateid_update_wait(state->inode, dst, 0);
3565 
3566 		if (fatal_signal_pending(current))
3567 			status = -EINTR;
3568 		else
3569 			if (schedule_timeout(5*HZ) != 0)
3570 				status = 0;
3571 
3572 		finish_wait(&state->waitq, &wait);
3573 
3574 		if (!status)
3575 			continue;
3576 		if (status == -EINTR)
3577 			break;
3578 
3579 		/* we slept the whole 5 seconds, we must have lost a seqid */
3580 		dst->seqid = cpu_to_be32(dst_seqid + 1);
3581 		ret = true;
3582 		break;
3583 	}
3584 
3585 	return ret;
3586 }
3587 
3588 struct nfs4_closedata {
3589 	struct inode *inode;
3590 	struct nfs4_state *state;
3591 	struct nfs_closeargs arg;
3592 	struct nfs_closeres res;
3593 	struct {
3594 		struct nfs4_layoutreturn_args arg;
3595 		struct nfs4_layoutreturn_res res;
3596 		struct nfs4_xdr_opaque_data ld_private;
3597 		u32 roc_barrier;
3598 		bool roc;
3599 	} lr;
3600 	struct nfs_fattr fattr;
3601 	unsigned long timestamp;
3602 };
3603 
3604 static void nfs4_free_closedata(void *data)
3605 {
3606 	struct nfs4_closedata *calldata = data;
3607 	struct nfs4_state_owner *sp = calldata->state->owner;
3608 	struct super_block *sb = calldata->state->inode->i_sb;
3609 
3610 	if (calldata->lr.roc)
3611 		pnfs_roc_release(&calldata->lr.arg, &calldata->lr.res,
3612 				calldata->res.lr_ret);
3613 	nfs4_put_open_state(calldata->state);
3614 	nfs_free_seqid(calldata->arg.seqid);
3615 	nfs4_put_state_owner(sp);
3616 	nfs_sb_deactive(sb);
3617 	kfree(calldata);
3618 }
3619 
3620 static void nfs4_close_done(struct rpc_task *task, void *data)
3621 {
3622 	struct nfs4_closedata *calldata = data;
3623 	struct nfs4_state *state = calldata->state;
3624 	struct nfs_server *server = NFS_SERVER(calldata->inode);
3625 	nfs4_stateid *res_stateid = NULL;
3626 	struct nfs4_exception exception = {
3627 		.state = state,
3628 		.inode = calldata->inode,
3629 		.stateid = &calldata->arg.stateid,
3630 	};
3631 
3632 	if (!nfs4_sequence_done(task, &calldata->res.seq_res))
3633 		return;
3634 	trace_nfs4_close(state, &calldata->arg, &calldata->res, task->tk_status);
3635 
3636 	/* Handle Layoutreturn errors */
3637 	if (pnfs_roc_done(task, &calldata->arg.lr_args, &calldata->res.lr_res,
3638 			  &calldata->res.lr_ret) == -EAGAIN)
3639 		goto out_restart;
3640 
3641 	/* hmm. we are done with the inode, and in the process of freeing
3642 	 * the state_owner. we keep this around to process errors
3643 	 */
3644 	switch (task->tk_status) {
3645 		case 0:
3646 			res_stateid = &calldata->res.stateid;
3647 			renew_lease(server, calldata->timestamp);
3648 			break;
3649 		case -NFS4ERR_ACCESS:
3650 			if (calldata->arg.bitmask != NULL) {
3651 				calldata->arg.bitmask = NULL;
3652 				calldata->res.fattr = NULL;
3653 				goto out_restart;
3654 
3655 			}
3656 			break;
3657 		case -NFS4ERR_OLD_STATEID:
3658 			/* Did we race with OPEN? */
3659 			if (nfs4_refresh_open_old_stateid(&calldata->arg.stateid,
3660 						state))
3661 				goto out_restart;
3662 			goto out_release;
3663 		case -NFS4ERR_ADMIN_REVOKED:
3664 		case -NFS4ERR_STALE_STATEID:
3665 		case -NFS4ERR_EXPIRED:
3666 			nfs4_free_revoked_stateid(server,
3667 					&calldata->arg.stateid,
3668 					task->tk_msg.rpc_cred);
3669 			fallthrough;
3670 		case -NFS4ERR_BAD_STATEID:
3671 			if (calldata->arg.fmode == 0)
3672 				break;
3673 			fallthrough;
3674 		default:
3675 			task->tk_status = nfs4_async_handle_exception(task,
3676 					server, task->tk_status, &exception);
3677 			if (exception.retry)
3678 				goto out_restart;
3679 	}
3680 	nfs_clear_open_stateid(state, &calldata->arg.stateid,
3681 			res_stateid, calldata->arg.fmode);
3682 out_release:
3683 	task->tk_status = 0;
3684 	nfs_release_seqid(calldata->arg.seqid);
3685 	nfs_refresh_inode(calldata->inode, &calldata->fattr);
3686 	dprintk("%s: ret = %d\n", __func__, task->tk_status);
3687 	return;
3688 out_restart:
3689 	task->tk_status = 0;
3690 	rpc_restart_call_prepare(task);
3691 	goto out_release;
3692 }
3693 
3694 static void nfs4_close_prepare(struct rpc_task *task, void *data)
3695 {
3696 	struct nfs4_closedata *calldata = data;
3697 	struct nfs4_state *state = calldata->state;
3698 	struct inode *inode = calldata->inode;
3699 	struct nfs_server *server = NFS_SERVER(inode);
3700 	struct pnfs_layout_hdr *lo;
3701 	bool is_rdonly, is_wronly, is_rdwr;
3702 	int call_close = 0;
3703 
3704 	if (nfs_wait_on_sequence(calldata->arg.seqid, task) != 0)
3705 		goto out_wait;
3706 
3707 	task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_DOWNGRADE];
3708 	spin_lock(&state->owner->so_lock);
3709 	is_rdwr = test_bit(NFS_O_RDWR_STATE, &state->flags);
3710 	is_rdonly = test_bit(NFS_O_RDONLY_STATE, &state->flags);
3711 	is_wronly = test_bit(NFS_O_WRONLY_STATE, &state->flags);
3712 	/* Calculate the change in open mode */
3713 	calldata->arg.fmode = 0;
3714 	if (state->n_rdwr == 0) {
3715 		if (state->n_rdonly == 0)
3716 			call_close |= is_rdonly;
3717 		else if (is_rdonly)
3718 			calldata->arg.fmode |= FMODE_READ;
3719 		if (state->n_wronly == 0)
3720 			call_close |= is_wronly;
3721 		else if (is_wronly)
3722 			calldata->arg.fmode |= FMODE_WRITE;
3723 		if (calldata->arg.fmode != (FMODE_READ|FMODE_WRITE))
3724 			call_close |= is_rdwr;
3725 	} else if (is_rdwr)
3726 		calldata->arg.fmode |= FMODE_READ|FMODE_WRITE;
3727 
3728 	nfs4_sync_open_stateid(&calldata->arg.stateid, state);
3729 	if (!nfs4_valid_open_stateid(state))
3730 		call_close = 0;
3731 	spin_unlock(&state->owner->so_lock);
3732 
3733 	if (!call_close) {
3734 		/* Note: exit _without_ calling nfs4_close_done */
3735 		goto out_no_action;
3736 	}
3737 
3738 	if (!calldata->lr.roc && nfs4_wait_on_layoutreturn(inode, task)) {
3739 		nfs_release_seqid(calldata->arg.seqid);
3740 		goto out_wait;
3741 	}
3742 
3743 	lo = calldata->arg.lr_args ? calldata->arg.lr_args->layout : NULL;
3744 	if (lo && !pnfs_layout_is_valid(lo)) {
3745 		calldata->arg.lr_args = NULL;
3746 		calldata->res.lr_res = NULL;
3747 	}
3748 
3749 	if (calldata->arg.fmode == 0)
3750 		task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_CLOSE];
3751 
3752 	if (calldata->arg.fmode == 0 || calldata->arg.fmode == FMODE_READ) {
3753 		/* Close-to-open cache consistency revalidation */
3754 		if (!nfs4_have_delegation(inode, FMODE_READ, 0)) {
3755 			nfs4_bitmask_set(calldata->arg.bitmask_store,
3756 					 server->cache_consistency_bitmask,
3757 					 inode, 0);
3758 			calldata->arg.bitmask = calldata->arg.bitmask_store;
3759 		} else
3760 			calldata->arg.bitmask = NULL;
3761 	}
3762 
3763 	calldata->arg.share_access =
3764 		nfs4_fmode_to_share_access(calldata->arg.fmode);
3765 
3766 	if (calldata->res.fattr == NULL)
3767 		calldata->arg.bitmask = NULL;
3768 	else if (calldata->arg.bitmask == NULL)
3769 		calldata->res.fattr = NULL;
3770 	calldata->timestamp = jiffies;
3771 	if (nfs4_setup_sequence(NFS_SERVER(inode)->nfs_client,
3772 				&calldata->arg.seq_args,
3773 				&calldata->res.seq_res,
3774 				task) != 0)
3775 		nfs_release_seqid(calldata->arg.seqid);
3776 	return;
3777 out_no_action:
3778 	task->tk_action = NULL;
3779 out_wait:
3780 	nfs4_sequence_done(task, &calldata->res.seq_res);
3781 }
3782 
3783 static const struct rpc_call_ops nfs4_close_ops = {
3784 	.rpc_call_prepare = nfs4_close_prepare,
3785 	.rpc_call_done = nfs4_close_done,
3786 	.rpc_release = nfs4_free_closedata,
3787 };
3788 
3789 /*
3790  * It is possible for data to be read/written from a mem-mapped file
3791  * after the sys_close call (which hits the vfs layer as a flush).
3792  * This means that we can't safely call nfsv4 close on a file until
3793  * the inode is cleared. This in turn means that we are not good
3794  * NFSv4 citizens - we do not indicate to the server to update the file's
3795  * share state even when we are done with one of the three share
3796  * stateid's in the inode.
3797  *
3798  * NOTE: Caller must be holding the sp->so_owner semaphore!
3799  */
3800 int nfs4_do_close(struct nfs4_state *state, gfp_t gfp_mask, int wait)
3801 {
3802 	struct nfs_server *server = NFS_SERVER(state->inode);
3803 	struct nfs_seqid *(*alloc_seqid)(struct nfs_seqid_counter *, gfp_t);
3804 	struct nfs4_closedata *calldata;
3805 	struct nfs4_state_owner *sp = state->owner;
3806 	struct rpc_task *task;
3807 	struct rpc_message msg = {
3808 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_CLOSE],
3809 		.rpc_cred = state->owner->so_cred,
3810 	};
3811 	struct rpc_task_setup task_setup_data = {
3812 		.rpc_client = server->client,
3813 		.rpc_message = &msg,
3814 		.callback_ops = &nfs4_close_ops,
3815 		.workqueue = nfsiod_workqueue,
3816 		.flags = RPC_TASK_ASYNC | RPC_TASK_CRED_NOREF,
3817 	};
3818 	int status = -ENOMEM;
3819 
3820 	if (nfs_server_capable(state->inode, NFS_CAP_MOVEABLE))
3821 		task_setup_data.flags |= RPC_TASK_MOVEABLE;
3822 
3823 	nfs4_state_protect(server->nfs_client, NFS_SP4_MACH_CRED_CLEANUP,
3824 		&task_setup_data.rpc_client, &msg);
3825 
3826 	calldata = kzalloc(sizeof(*calldata), gfp_mask);
3827 	if (calldata == NULL)
3828 		goto out;
3829 	nfs4_init_sequence(&calldata->arg.seq_args, &calldata->res.seq_res, 1, 0);
3830 	calldata->inode = state->inode;
3831 	calldata->state = state;
3832 	calldata->arg.fh = NFS_FH(state->inode);
3833 	if (!nfs4_copy_open_stateid(&calldata->arg.stateid, state))
3834 		goto out_free_calldata;
3835 	/* Serialization for the sequence id */
3836 	alloc_seqid = server->nfs_client->cl_mvops->alloc_seqid;
3837 	calldata->arg.seqid = alloc_seqid(&state->owner->so_seqid, gfp_mask);
3838 	if (IS_ERR(calldata->arg.seqid))
3839 		goto out_free_calldata;
3840 	nfs_fattr_init(&calldata->fattr);
3841 	calldata->arg.fmode = 0;
3842 	calldata->lr.arg.ld_private = &calldata->lr.ld_private;
3843 	calldata->res.fattr = &calldata->fattr;
3844 	calldata->res.seqid = calldata->arg.seqid;
3845 	calldata->res.server = server;
3846 	calldata->res.lr_ret = -NFS4ERR_NOMATCHING_LAYOUT;
3847 	calldata->lr.roc = pnfs_roc(state->inode,
3848 			&calldata->lr.arg, &calldata->lr.res, msg.rpc_cred);
3849 	if (calldata->lr.roc) {
3850 		calldata->arg.lr_args = &calldata->lr.arg;
3851 		calldata->res.lr_res = &calldata->lr.res;
3852 	}
3853 	nfs_sb_active(calldata->inode->i_sb);
3854 
3855 	msg.rpc_argp = &calldata->arg;
3856 	msg.rpc_resp = &calldata->res;
3857 	task_setup_data.callback_data = calldata;
3858 	task = rpc_run_task(&task_setup_data);
3859 	if (IS_ERR(task))
3860 		return PTR_ERR(task);
3861 	status = 0;
3862 	if (wait)
3863 		status = rpc_wait_for_completion_task(task);
3864 	rpc_put_task(task);
3865 	return status;
3866 out_free_calldata:
3867 	kfree(calldata);
3868 out:
3869 	nfs4_put_open_state(state);
3870 	nfs4_put_state_owner(sp);
3871 	return status;
3872 }
3873 
3874 static struct inode *
3875 nfs4_atomic_open(struct inode *dir, struct nfs_open_context *ctx,
3876 		int open_flags, struct iattr *attr, int *opened)
3877 {
3878 	struct nfs4_state *state;
3879 	struct nfs4_label l, *label;
3880 
3881 	label = nfs4_label_init_security(dir, ctx->dentry, attr, &l);
3882 
3883 	/* Protect against concurrent sillydeletes */
3884 	state = nfs4_do_open(dir, ctx, open_flags, attr, label, opened);
3885 
3886 	nfs4_label_release_security(label);
3887 
3888 	if (IS_ERR(state))
3889 		return ERR_CAST(state);
3890 	return state->inode;
3891 }
3892 
3893 static void nfs4_close_context(struct nfs_open_context *ctx, int is_sync)
3894 {
3895 	if (ctx->state == NULL)
3896 		return;
3897 	if (is_sync)
3898 		nfs4_close_sync(ctx->state, _nfs4_ctx_to_openmode(ctx));
3899 	else
3900 		nfs4_close_state(ctx->state, _nfs4_ctx_to_openmode(ctx));
3901 }
3902 
3903 #define FATTR4_WORD1_NFS40_MASK (2*FATTR4_WORD1_MOUNTED_ON_FILEID - 1UL)
3904 #define FATTR4_WORD2_NFS41_MASK (2*FATTR4_WORD2_SUPPATTR_EXCLCREAT - 1UL)
3905 #define FATTR4_WORD2_NFS42_MASK (2*FATTR4_WORD2_OPEN_ARGUMENTS - 1UL)
3906 
3907 static int _nfs4_server_capabilities(struct nfs_server *server, struct nfs_fh *fhandle)
3908 {
3909 	u32 minorversion = server->nfs_client->cl_minorversion;
3910 	u32 bitmask[3] = {
3911 		[0] = FATTR4_WORD0_SUPPORTED_ATTRS,
3912 	};
3913 	struct nfs4_server_caps_arg args = {
3914 		.fhandle = fhandle,
3915 		.bitmask = bitmask,
3916 	};
3917 	struct nfs4_server_caps_res res = {};
3918 	struct rpc_message msg = {
3919 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_SERVER_CAPS],
3920 		.rpc_argp = &args,
3921 		.rpc_resp = &res,
3922 	};
3923 	int status;
3924 	int i;
3925 
3926 	bitmask[0] = FATTR4_WORD0_SUPPORTED_ATTRS |
3927 		     FATTR4_WORD0_FH_EXPIRE_TYPE |
3928 		     FATTR4_WORD0_LINK_SUPPORT |
3929 		     FATTR4_WORD0_SYMLINK_SUPPORT |
3930 		     FATTR4_WORD0_ACLSUPPORT |
3931 		     FATTR4_WORD0_CASE_INSENSITIVE |
3932 		     FATTR4_WORD0_CASE_PRESERVING;
3933 	if (minorversion)
3934 		bitmask[2] = FATTR4_WORD2_SUPPATTR_EXCLCREAT |
3935 			     FATTR4_WORD2_OPEN_ARGUMENTS;
3936 
3937 	status = nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 0);
3938 	if (status == 0) {
3939 		bitmask[0] = (FATTR4_WORD0_SUPPORTED_ATTRS |
3940 			      FATTR4_WORD0_FH_EXPIRE_TYPE |
3941 			      FATTR4_WORD0_LINK_SUPPORT |
3942 			      FATTR4_WORD0_SYMLINK_SUPPORT |
3943 			      FATTR4_WORD0_ACLSUPPORT |
3944 			      FATTR4_WORD0_CASE_INSENSITIVE |
3945 			      FATTR4_WORD0_CASE_PRESERVING) &
3946 			     res.attr_bitmask[0];
3947 		/* Sanity check the server answers */
3948 		switch (minorversion) {
3949 		case 0:
3950 			res.attr_bitmask[1] &= FATTR4_WORD1_NFS40_MASK;
3951 			res.attr_bitmask[2] = 0;
3952 			break;
3953 		case 1:
3954 			res.attr_bitmask[2] &= FATTR4_WORD2_NFS41_MASK;
3955 			bitmask[2] = FATTR4_WORD2_SUPPATTR_EXCLCREAT &
3956 				     res.attr_bitmask[2];
3957 			break;
3958 		case 2:
3959 			res.attr_bitmask[2] &= FATTR4_WORD2_NFS42_MASK;
3960 			bitmask[2] = (FATTR4_WORD2_SUPPATTR_EXCLCREAT |
3961 				      FATTR4_WORD2_OPEN_ARGUMENTS) &
3962 				     res.attr_bitmask[2];
3963 		}
3964 		memcpy(server->attr_bitmask, res.attr_bitmask, sizeof(server->attr_bitmask));
3965 		server->caps &= ~(NFS_CAP_ACLS | NFS_CAP_HARDLINKS |
3966 				  NFS_CAP_SYMLINKS| NFS_CAP_SECURITY_LABEL);
3967 		server->fattr_valid = NFS_ATTR_FATTR_V4;
3968 		if (res.attr_bitmask[0] & FATTR4_WORD0_ACL &&
3969 				res.acl_bitmask & ACL4_SUPPORT_ALLOW_ACL)
3970 			server->caps |= NFS_CAP_ACLS;
3971 		if (res.has_links != 0)
3972 			server->caps |= NFS_CAP_HARDLINKS;
3973 		if (res.has_symlinks != 0)
3974 			server->caps |= NFS_CAP_SYMLINKS;
3975 		if (res.case_insensitive)
3976 			server->caps |= NFS_CAP_CASE_INSENSITIVE;
3977 		if (res.case_preserving)
3978 			server->caps |= NFS_CAP_CASE_PRESERVING;
3979 #ifdef CONFIG_NFS_V4_SECURITY_LABEL
3980 		if (res.attr_bitmask[2] & FATTR4_WORD2_SECURITY_LABEL)
3981 			server->caps |= NFS_CAP_SECURITY_LABEL;
3982 #endif
3983 		if (res.attr_bitmask[0] & FATTR4_WORD0_FS_LOCATIONS)
3984 			server->caps |= NFS_CAP_FS_LOCATIONS;
3985 		if (res.attr_bitmask[2] & FATTR4_WORD2_TIME_DELEG_MODIFY)
3986 			server->caps |= NFS_CAP_DELEGTIME;
3987 		if (!(res.attr_bitmask[0] & FATTR4_WORD0_FILEID))
3988 			server->fattr_valid &= ~NFS_ATTR_FATTR_FILEID;
3989 		if (!(res.attr_bitmask[1] & FATTR4_WORD1_MODE))
3990 			server->fattr_valid &= ~NFS_ATTR_FATTR_MODE;
3991 		if (!(res.attr_bitmask[1] & FATTR4_WORD1_NUMLINKS))
3992 			server->fattr_valid &= ~NFS_ATTR_FATTR_NLINK;
3993 		if (!(res.attr_bitmask[1] & FATTR4_WORD1_OWNER))
3994 			server->fattr_valid &= ~(NFS_ATTR_FATTR_OWNER |
3995 				NFS_ATTR_FATTR_OWNER_NAME);
3996 		if (!(res.attr_bitmask[1] & FATTR4_WORD1_OWNER_GROUP))
3997 			server->fattr_valid &= ~(NFS_ATTR_FATTR_GROUP |
3998 				NFS_ATTR_FATTR_GROUP_NAME);
3999 		if (!(res.attr_bitmask[1] & FATTR4_WORD1_SPACE_USED))
4000 			server->fattr_valid &= ~NFS_ATTR_FATTR_SPACE_USED;
4001 		if (!(res.attr_bitmask[1] & FATTR4_WORD1_TIME_ACCESS))
4002 			server->fattr_valid &= ~NFS_ATTR_FATTR_ATIME;
4003 		if (!(res.attr_bitmask[1] & FATTR4_WORD1_TIME_METADATA))
4004 			server->fattr_valid &= ~NFS_ATTR_FATTR_CTIME;
4005 		if (!(res.attr_bitmask[1] & FATTR4_WORD1_TIME_MODIFY))
4006 			server->fattr_valid &= ~NFS_ATTR_FATTR_MTIME;
4007 		memcpy(server->attr_bitmask_nl, res.attr_bitmask,
4008 				sizeof(server->attr_bitmask));
4009 		server->attr_bitmask_nl[2] &= ~FATTR4_WORD2_SECURITY_LABEL;
4010 
4011 		if (res.open_caps.oa_share_access_want[0] &
4012 		    NFS4_SHARE_WANT_OPEN_XOR_DELEGATION)
4013 			server->caps |= NFS_CAP_OPEN_XOR;
4014 
4015 		memcpy(server->cache_consistency_bitmask, res.attr_bitmask, sizeof(server->cache_consistency_bitmask));
4016 		server->cache_consistency_bitmask[0] &= FATTR4_WORD0_CHANGE|FATTR4_WORD0_SIZE;
4017 		server->cache_consistency_bitmask[1] &= FATTR4_WORD1_TIME_METADATA|FATTR4_WORD1_TIME_MODIFY;
4018 		server->cache_consistency_bitmask[2] = 0;
4019 
4020 		/* Avoid a regression due to buggy server */
4021 		for (i = 0; i < ARRAY_SIZE(res.exclcreat_bitmask); i++)
4022 			res.exclcreat_bitmask[i] &= res.attr_bitmask[i];
4023 		memcpy(server->exclcreat_bitmask, res.exclcreat_bitmask,
4024 			sizeof(server->exclcreat_bitmask));
4025 
4026 		server->acl_bitmask = res.acl_bitmask;
4027 		server->fh_expire_type = res.fh_expire_type;
4028 	}
4029 
4030 	return status;
4031 }
4032 
4033 int nfs4_server_capabilities(struct nfs_server *server, struct nfs_fh *fhandle)
4034 {
4035 	struct nfs4_exception exception = {
4036 		.interruptible = true,
4037 	};
4038 	int err;
4039 
4040 	nfs4_server_set_init_caps(server);
4041 	do {
4042 		err = nfs4_handle_exception(server,
4043 				_nfs4_server_capabilities(server, fhandle),
4044 				&exception);
4045 	} while (exception.retry);
4046 	return err;
4047 }
4048 
4049 static void test_fs_location_for_trunking(struct nfs4_fs_location *location,
4050 					  struct nfs_client *clp,
4051 					  struct nfs_server *server)
4052 {
4053 	int i;
4054 
4055 	for (i = 0; i < location->nservers; i++) {
4056 		struct nfs4_string *srv_loc = &location->servers[i];
4057 		struct sockaddr_storage addr;
4058 		size_t addrlen;
4059 		struct xprt_create xprt_args = {
4060 			.ident = 0,
4061 			.net = clp->cl_net,
4062 		};
4063 		struct nfs4_add_xprt_data xprtdata = {
4064 			.clp = clp,
4065 		};
4066 		struct rpc_add_xprt_test rpcdata = {
4067 			.add_xprt_test = clp->cl_mvops->session_trunk,
4068 			.data = &xprtdata,
4069 		};
4070 		char *servername = NULL;
4071 
4072 		if (!srv_loc->len)
4073 			continue;
4074 
4075 		addrlen = nfs_parse_server_name(srv_loc->data, srv_loc->len,
4076 						&addr, sizeof(addr),
4077 						clp->cl_net, server->port);
4078 		if (!addrlen)
4079 			return;
4080 		xprt_args.dstaddr = (struct sockaddr *)&addr;
4081 		xprt_args.addrlen = addrlen;
4082 		servername = kmalloc(srv_loc->len + 1, GFP_KERNEL);
4083 		if (!servername)
4084 			return;
4085 		memcpy(servername, srv_loc->data, srv_loc->len);
4086 		servername[srv_loc->len] = '\0';
4087 		xprt_args.servername = servername;
4088 
4089 		xprtdata.cred = nfs4_get_clid_cred(clp);
4090 		rpc_clnt_add_xprt(clp->cl_rpcclient, &xprt_args,
4091 				  rpc_clnt_setup_test_and_add_xprt,
4092 				  &rpcdata);
4093 		if (xprtdata.cred)
4094 			put_cred(xprtdata.cred);
4095 		kfree(servername);
4096 	}
4097 }
4098 
4099 static bool _is_same_nfs4_pathname(struct nfs4_pathname *path1,
4100 				   struct nfs4_pathname *path2)
4101 {
4102 	int i;
4103 
4104 	if (path1->ncomponents != path2->ncomponents)
4105 		return false;
4106 	for (i = 0; i < path1->ncomponents; i++) {
4107 		if (path1->components[i].len != path2->components[i].len)
4108 			return false;
4109 		if (memcmp(path1->components[i].data, path2->components[i].data,
4110 				path1->components[i].len))
4111 			return false;
4112 	}
4113 	return true;
4114 }
4115 
4116 static int _nfs4_discover_trunking(struct nfs_server *server,
4117 				   struct nfs_fh *fhandle)
4118 {
4119 	struct nfs4_fs_locations *locations = NULL;
4120 	struct page *page;
4121 	const struct cred *cred;
4122 	struct nfs_client *clp = server->nfs_client;
4123 	const struct nfs4_state_maintenance_ops *ops =
4124 		clp->cl_mvops->state_renewal_ops;
4125 	int status = -ENOMEM, i;
4126 
4127 	cred = ops->get_state_renewal_cred(clp);
4128 	if (cred == NULL) {
4129 		cred = nfs4_get_clid_cred(clp);
4130 		if (cred == NULL)
4131 			return -ENOKEY;
4132 	}
4133 
4134 	page = alloc_page(GFP_KERNEL);
4135 	if (!page)
4136 		goto out_put_cred;
4137 	locations = kmalloc(sizeof(struct nfs4_fs_locations), GFP_KERNEL);
4138 	if (!locations)
4139 		goto out_free;
4140 	locations->fattr = nfs_alloc_fattr();
4141 	if (!locations->fattr)
4142 		goto out_free_2;
4143 
4144 	status = nfs4_proc_get_locations(server, fhandle, locations, page,
4145 					 cred);
4146 	if (status)
4147 		goto out_free_3;
4148 
4149 	for (i = 0; i < locations->nlocations; i++) {
4150 		if (!_is_same_nfs4_pathname(&locations->fs_path,
4151 					&locations->locations[i].rootpath))
4152 			continue;
4153 		test_fs_location_for_trunking(&locations->locations[i], clp,
4154 					      server);
4155 	}
4156 out_free_3:
4157 	kfree(locations->fattr);
4158 out_free_2:
4159 	kfree(locations);
4160 out_free:
4161 	__free_page(page);
4162 out_put_cred:
4163 	put_cred(cred);
4164 	return status;
4165 }
4166 
4167 static int nfs4_discover_trunking(struct nfs_server *server,
4168 				  struct nfs_fh *fhandle)
4169 {
4170 	struct nfs4_exception exception = {
4171 		.interruptible = true,
4172 	};
4173 	struct nfs_client *clp = server->nfs_client;
4174 	int err = 0;
4175 
4176 	if (!nfs4_has_session(clp))
4177 		goto out;
4178 	do {
4179 		err = nfs4_handle_exception(server,
4180 				_nfs4_discover_trunking(server, fhandle),
4181 				&exception);
4182 	} while (exception.retry);
4183 out:
4184 	return err;
4185 }
4186 
4187 static int _nfs4_lookup_root(struct nfs_server *server, struct nfs_fh *fhandle,
4188 		struct nfs_fsinfo *info)
4189 {
4190 	u32 bitmask[3];
4191 	struct nfs4_lookup_root_arg args = {
4192 		.bitmask = bitmask,
4193 	};
4194 	struct nfs4_lookup_res res = {
4195 		.server = server,
4196 		.fattr = info->fattr,
4197 		.fh = fhandle,
4198 	};
4199 	struct rpc_message msg = {
4200 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_LOOKUP_ROOT],
4201 		.rpc_argp = &args,
4202 		.rpc_resp = &res,
4203 	};
4204 
4205 	bitmask[0] = nfs4_fattr_bitmap[0];
4206 	bitmask[1] = nfs4_fattr_bitmap[1];
4207 	/*
4208 	 * Process the label in the upcoming getfattr
4209 	 */
4210 	bitmask[2] = nfs4_fattr_bitmap[2] & ~FATTR4_WORD2_SECURITY_LABEL;
4211 
4212 	nfs_fattr_init(info->fattr);
4213 	return nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 0);
4214 }
4215 
4216 static int nfs4_lookup_root(struct nfs_server *server, struct nfs_fh *fhandle,
4217 		struct nfs_fsinfo *info)
4218 {
4219 	struct nfs4_exception exception = {
4220 		.interruptible = true,
4221 	};
4222 	int err;
4223 	do {
4224 		err = _nfs4_lookup_root(server, fhandle, info);
4225 		trace_nfs4_lookup_root(server, fhandle, info->fattr, err);
4226 		switch (err) {
4227 		case 0:
4228 		case -NFS4ERR_WRONGSEC:
4229 			goto out;
4230 		default:
4231 			err = nfs4_handle_exception(server, err, &exception);
4232 		}
4233 	} while (exception.retry);
4234 out:
4235 	return err;
4236 }
4237 
4238 static int nfs4_lookup_root_sec(struct nfs_server *server, struct nfs_fh *fhandle,
4239 				struct nfs_fsinfo *info, rpc_authflavor_t flavor)
4240 {
4241 	struct rpc_auth_create_args auth_args = {
4242 		.pseudoflavor = flavor,
4243 	};
4244 	struct rpc_auth *auth;
4245 
4246 	auth = rpcauth_create(&auth_args, server->client);
4247 	if (IS_ERR(auth))
4248 		return -EACCES;
4249 	return nfs4_lookup_root(server, fhandle, info);
4250 }
4251 
4252 /*
4253  * Retry pseudoroot lookup with various security flavors.  We do this when:
4254  *
4255  *   NFSv4.0: the PUTROOTFH operation returns NFS4ERR_WRONGSEC
4256  *   NFSv4.1: the server does not support the SECINFO_NO_NAME operation
4257  *
4258  * Returns zero on success, or a negative NFS4ERR value, or a
4259  * negative errno value.
4260  */
4261 static int nfs4_find_root_sec(struct nfs_server *server, struct nfs_fh *fhandle,
4262 			      struct nfs_fsinfo *info)
4263 {
4264 	/* Per 3530bis 15.33.5 */
4265 	static const rpc_authflavor_t flav_array[] = {
4266 		RPC_AUTH_GSS_KRB5P,
4267 		RPC_AUTH_GSS_KRB5I,
4268 		RPC_AUTH_GSS_KRB5,
4269 		RPC_AUTH_UNIX,			/* courtesy */
4270 		RPC_AUTH_NULL,
4271 	};
4272 	int status = -EPERM;
4273 	size_t i;
4274 
4275 	if (server->auth_info.flavor_len > 0) {
4276 		/* try each flavor specified by user */
4277 		for (i = 0; i < server->auth_info.flavor_len; i++) {
4278 			status = nfs4_lookup_root_sec(server, fhandle, info,
4279 						server->auth_info.flavors[i]);
4280 			if (status == -NFS4ERR_WRONGSEC || status == -EACCES)
4281 				continue;
4282 			break;
4283 		}
4284 	} else {
4285 		/* no flavors specified by user, try default list */
4286 		for (i = 0; i < ARRAY_SIZE(flav_array); i++) {
4287 			status = nfs4_lookup_root_sec(server, fhandle, info,
4288 						      flav_array[i]);
4289 			if (status == -NFS4ERR_WRONGSEC || status == -EACCES)
4290 				continue;
4291 			break;
4292 		}
4293 	}
4294 
4295 	/*
4296 	 * -EACCES could mean that the user doesn't have correct permissions
4297 	 * to access the mount.  It could also mean that we tried to mount
4298 	 * with a gss auth flavor, but rpc.gssd isn't running.  Either way,
4299 	 * existing mount programs don't handle -EACCES very well so it should
4300 	 * be mapped to -EPERM instead.
4301 	 */
4302 	if (status == -EACCES)
4303 		status = -EPERM;
4304 	return status;
4305 }
4306 
4307 /**
4308  * nfs4_proc_get_rootfh - get file handle for server's pseudoroot
4309  * @server: initialized nfs_server handle
4310  * @fhandle: we fill in the pseudo-fs root file handle
4311  * @info: we fill in an FSINFO struct
4312  * @auth_probe: probe the auth flavours
4313  *
4314  * Returns zero on success, or a negative errno.
4315  */
4316 int nfs4_proc_get_rootfh(struct nfs_server *server, struct nfs_fh *fhandle,
4317 			 struct nfs_fsinfo *info,
4318 			 bool auth_probe)
4319 {
4320 	int status = 0;
4321 
4322 	if (!auth_probe)
4323 		status = nfs4_lookup_root(server, fhandle, info);
4324 
4325 	if (auth_probe || status == NFS4ERR_WRONGSEC)
4326 		status = server->nfs_client->cl_mvops->find_root_sec(server,
4327 				fhandle, info);
4328 
4329 	if (status == 0)
4330 		status = nfs4_server_capabilities(server, fhandle);
4331 	if (status == 0)
4332 		status = nfs4_do_fsinfo(server, fhandle, info);
4333 
4334 	return nfs4_map_errors(status);
4335 }
4336 
4337 static int nfs4_proc_get_root(struct nfs_server *server, struct nfs_fh *mntfh,
4338 			      struct nfs_fsinfo *info)
4339 {
4340 	int error;
4341 	struct nfs_fattr *fattr = info->fattr;
4342 
4343 	error = nfs4_server_capabilities(server, mntfh);
4344 	if (error < 0) {
4345 		dprintk("nfs4_get_root: getcaps error = %d\n", -error);
4346 		return error;
4347 	}
4348 
4349 	error = nfs4_proc_getattr(server, mntfh, fattr, NULL);
4350 	if (error < 0) {
4351 		dprintk("nfs4_get_root: getattr error = %d\n", -error);
4352 		goto out;
4353 	}
4354 
4355 	if (fattr->valid & NFS_ATTR_FATTR_FSID &&
4356 	    !nfs_fsid_equal(&server->fsid, &fattr->fsid))
4357 		memcpy(&server->fsid, &fattr->fsid, sizeof(server->fsid));
4358 
4359 out:
4360 	return error;
4361 }
4362 
4363 /*
4364  * Get locations and (maybe) other attributes of a referral.
4365  * Note that we'll actually follow the referral later when
4366  * we detect fsid mismatch in inode revalidation
4367  */
4368 static int nfs4_get_referral(struct rpc_clnt *client, struct inode *dir,
4369 			     const struct qstr *name, struct nfs_fattr *fattr,
4370 			     struct nfs_fh *fhandle)
4371 {
4372 	int status = -ENOMEM;
4373 	struct page *page = NULL;
4374 	struct nfs4_fs_locations *locations = NULL;
4375 
4376 	page = alloc_page(GFP_KERNEL);
4377 	if (page == NULL)
4378 		goto out;
4379 	locations = kmalloc(sizeof(struct nfs4_fs_locations), GFP_KERNEL);
4380 	if (locations == NULL)
4381 		goto out;
4382 
4383 	locations->fattr = fattr;
4384 
4385 	status = nfs4_proc_fs_locations(client, dir, name, locations, page);
4386 	if (status != 0)
4387 		goto out;
4388 
4389 	/*
4390 	 * If the fsid didn't change, this is a migration event, not a
4391 	 * referral.  Cause us to drop into the exception handler, which
4392 	 * will kick off migration recovery.
4393 	 */
4394 	if (nfs_fsid_equal(&NFS_SERVER(dir)->fsid, &fattr->fsid)) {
4395 		dprintk("%s: server did not return a different fsid for"
4396 			" a referral at %s\n", __func__, name->name);
4397 		status = -NFS4ERR_MOVED;
4398 		goto out;
4399 	}
4400 	/* Fixup attributes for the nfs_lookup() call to nfs_fhget() */
4401 	nfs_fixup_referral_attributes(fattr);
4402 	memset(fhandle, 0, sizeof(struct nfs_fh));
4403 out:
4404 	if (page)
4405 		__free_page(page);
4406 	kfree(locations);
4407 	return status;
4408 }
4409 
4410 static int _nfs4_proc_getattr(struct nfs_server *server, struct nfs_fh *fhandle,
4411 				struct nfs_fattr *fattr, struct inode *inode)
4412 {
4413 	__u32 bitmask[NFS4_BITMASK_SZ];
4414 	struct nfs4_getattr_arg args = {
4415 		.fh = fhandle,
4416 		.bitmask = bitmask,
4417 	};
4418 	struct nfs4_getattr_res res = {
4419 		.fattr = fattr,
4420 		.server = server,
4421 	};
4422 	struct rpc_message msg = {
4423 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETATTR],
4424 		.rpc_argp = &args,
4425 		.rpc_resp = &res,
4426 	};
4427 	unsigned short task_flags = 0;
4428 
4429 	if (nfs4_has_session(server->nfs_client))
4430 		task_flags = RPC_TASK_MOVEABLE;
4431 
4432 	/* Is this is an attribute revalidation, subject to softreval? */
4433 	if (inode && (server->flags & NFS_MOUNT_SOFTREVAL))
4434 		task_flags |= RPC_TASK_TIMEOUT;
4435 
4436 	nfs4_bitmap_copy_adjust(bitmask, nfs4_bitmask(server, fattr->label), inode, 0);
4437 	nfs_fattr_init(fattr);
4438 	nfs4_init_sequence(&args.seq_args, &res.seq_res, 0, 0);
4439 	return nfs4_do_call_sync(server->client, server, &msg,
4440 			&args.seq_args, &res.seq_res, task_flags);
4441 }
4442 
4443 int nfs4_proc_getattr(struct nfs_server *server, struct nfs_fh *fhandle,
4444 				struct nfs_fattr *fattr, struct inode *inode)
4445 {
4446 	struct nfs4_exception exception = {
4447 		.interruptible = true,
4448 	};
4449 	int err;
4450 	do {
4451 		err = _nfs4_proc_getattr(server, fhandle, fattr, inode);
4452 		trace_nfs4_getattr(server, fhandle, fattr, err);
4453 		err = nfs4_handle_exception(server, err,
4454 				&exception);
4455 	} while (exception.retry);
4456 	return err;
4457 }
4458 
4459 /*
4460  * The file is not closed if it is opened due to the a request to change
4461  * the size of the file. The open call will not be needed once the
4462  * VFS layer lookup-intents are implemented.
4463  *
4464  * Close is called when the inode is destroyed.
4465  * If we haven't opened the file for O_WRONLY, we
4466  * need to in the size_change case to obtain a stateid.
4467  *
4468  * Got race?
4469  * Because OPEN is always done by name in nfsv4, it is
4470  * possible that we opened a different file by the same
4471  * name.  We can recognize this race condition, but we
4472  * can't do anything about it besides returning an error.
4473  *
4474  * This will be fixed with VFS changes (lookup-intent).
4475  */
4476 static int
4477 nfs4_proc_setattr(struct dentry *dentry, struct nfs_fattr *fattr,
4478 		  struct iattr *sattr)
4479 {
4480 	struct inode *inode = d_inode(dentry);
4481 	const struct cred *cred = NULL;
4482 	struct nfs_open_context *ctx = NULL;
4483 	int status;
4484 
4485 	if (pnfs_ld_layoutret_on_setattr(inode) &&
4486 	    sattr->ia_valid & ATTR_SIZE &&
4487 	    sattr->ia_size < i_size_read(inode))
4488 		pnfs_commit_and_return_layout(inode);
4489 
4490 	nfs_fattr_init(fattr);
4491 
4492 	/* Deal with open(O_TRUNC) */
4493 	if (sattr->ia_valid & ATTR_OPEN)
4494 		sattr->ia_valid &= ~(ATTR_MTIME|ATTR_CTIME);
4495 
4496 	/* Optimization: if the end result is no change, don't RPC */
4497 	if ((sattr->ia_valid & ~(ATTR_FILE|ATTR_OPEN)) == 0)
4498 		return 0;
4499 
4500 	/* Search for an existing open(O_WRITE) file */
4501 	if (sattr->ia_valid & ATTR_FILE) {
4502 
4503 		ctx = nfs_file_open_context(sattr->ia_file);
4504 		if (ctx)
4505 			cred = ctx->cred;
4506 	}
4507 
4508 	/* Return any delegations if we're going to change ACLs */
4509 	if ((sattr->ia_valid & (ATTR_MODE|ATTR_UID|ATTR_GID)) != 0)
4510 		nfs4_inode_make_writeable(inode);
4511 
4512 	status = nfs4_do_setattr(inode, cred, fattr, sattr, ctx, NULL);
4513 	if (status == 0) {
4514 		nfs_setattr_update_inode(inode, sattr, fattr);
4515 		nfs_setsecurity(inode, fattr);
4516 	}
4517 	return status;
4518 }
4519 
4520 static int _nfs4_proc_lookup(struct rpc_clnt *clnt, struct inode *dir,
4521 		struct dentry *dentry, struct nfs_fh *fhandle,
4522 		struct nfs_fattr *fattr)
4523 {
4524 	struct nfs_server *server = NFS_SERVER(dir);
4525 	int		       status;
4526 	struct nfs4_lookup_arg args = {
4527 		.bitmask = server->attr_bitmask,
4528 		.dir_fh = NFS_FH(dir),
4529 		.name = &dentry->d_name,
4530 	};
4531 	struct nfs4_lookup_res res = {
4532 		.server = server,
4533 		.fattr = fattr,
4534 		.fh = fhandle,
4535 	};
4536 	struct rpc_message msg = {
4537 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_LOOKUP],
4538 		.rpc_argp = &args,
4539 		.rpc_resp = &res,
4540 	};
4541 	unsigned short task_flags = 0;
4542 
4543 	if (nfs_server_capable(dir, NFS_CAP_MOVEABLE))
4544 		task_flags = RPC_TASK_MOVEABLE;
4545 
4546 	/* Is this is an attribute revalidation, subject to softreval? */
4547 	if (nfs_lookup_is_soft_revalidate(dentry))
4548 		task_flags |= RPC_TASK_TIMEOUT;
4549 
4550 	args.bitmask = nfs4_bitmask(server, fattr->label);
4551 
4552 	nfs_fattr_init(fattr);
4553 
4554 	dprintk("NFS call  lookup %pd2\n", dentry);
4555 	nfs4_init_sequence(&args.seq_args, &res.seq_res, 0, 0);
4556 	status = nfs4_do_call_sync(clnt, server, &msg,
4557 			&args.seq_args, &res.seq_res, task_flags);
4558 	dprintk("NFS reply lookup: %d\n", status);
4559 	return status;
4560 }
4561 
4562 static void nfs_fixup_secinfo_attributes(struct nfs_fattr *fattr)
4563 {
4564 	fattr->valid |= NFS_ATTR_FATTR_TYPE | NFS_ATTR_FATTR_MODE |
4565 		NFS_ATTR_FATTR_NLINK | NFS_ATTR_FATTR_MOUNTPOINT;
4566 	fattr->mode = S_IFDIR | S_IRUGO | S_IXUGO;
4567 	fattr->nlink = 2;
4568 }
4569 
4570 static int nfs4_proc_lookup_common(struct rpc_clnt **clnt, struct inode *dir,
4571 				   struct dentry *dentry, struct nfs_fh *fhandle,
4572 				   struct nfs_fattr *fattr)
4573 {
4574 	struct nfs4_exception exception = {
4575 		.interruptible = true,
4576 	};
4577 	struct rpc_clnt *client = *clnt;
4578 	const struct qstr *name = &dentry->d_name;
4579 	int err;
4580 	do {
4581 		err = _nfs4_proc_lookup(client, dir, dentry, fhandle, fattr);
4582 		trace_nfs4_lookup(dir, name, err);
4583 		switch (err) {
4584 		case -NFS4ERR_BADNAME:
4585 			err = -ENOENT;
4586 			goto out;
4587 		case -NFS4ERR_MOVED:
4588 			err = nfs4_get_referral(client, dir, name, fattr, fhandle);
4589 			if (err == -NFS4ERR_MOVED)
4590 				err = nfs4_handle_exception(NFS_SERVER(dir), err, &exception);
4591 			goto out;
4592 		case -NFS4ERR_WRONGSEC:
4593 			err = -EPERM;
4594 			if (client != *clnt)
4595 				goto out;
4596 			client = nfs4_negotiate_security(client, dir, name);
4597 			if (IS_ERR(client))
4598 				return PTR_ERR(client);
4599 
4600 			exception.retry = 1;
4601 			break;
4602 		default:
4603 			err = nfs4_handle_exception(NFS_SERVER(dir), err, &exception);
4604 		}
4605 	} while (exception.retry);
4606 
4607 out:
4608 	if (err == 0)
4609 		*clnt = client;
4610 	else if (client != *clnt)
4611 		rpc_shutdown_client(client);
4612 
4613 	return err;
4614 }
4615 
4616 static int nfs4_proc_lookup(struct inode *dir, struct dentry *dentry,
4617 			    struct nfs_fh *fhandle, struct nfs_fattr *fattr)
4618 {
4619 	int status;
4620 	struct rpc_clnt *client = NFS_CLIENT(dir);
4621 
4622 	status = nfs4_proc_lookup_common(&client, dir, dentry, fhandle, fattr);
4623 	if (client != NFS_CLIENT(dir)) {
4624 		rpc_shutdown_client(client);
4625 		nfs_fixup_secinfo_attributes(fattr);
4626 	}
4627 	return status;
4628 }
4629 
4630 struct rpc_clnt *
4631 nfs4_proc_lookup_mountpoint(struct inode *dir, struct dentry *dentry,
4632 			    struct nfs_fh *fhandle, struct nfs_fattr *fattr)
4633 {
4634 	struct rpc_clnt *client = NFS_CLIENT(dir);
4635 	int status;
4636 
4637 	status = nfs4_proc_lookup_common(&client, dir, dentry, fhandle, fattr);
4638 	if (status < 0)
4639 		return ERR_PTR(status);
4640 	return (client == NFS_CLIENT(dir)) ? rpc_clone_client(client) : client;
4641 }
4642 
4643 static int _nfs4_proc_lookupp(struct inode *inode,
4644 		struct nfs_fh *fhandle, struct nfs_fattr *fattr)
4645 {
4646 	struct rpc_clnt *clnt = NFS_CLIENT(inode);
4647 	struct nfs_server *server = NFS_SERVER(inode);
4648 	int		       status;
4649 	struct nfs4_lookupp_arg args = {
4650 		.bitmask = server->attr_bitmask,
4651 		.fh = NFS_FH(inode),
4652 	};
4653 	struct nfs4_lookupp_res res = {
4654 		.server = server,
4655 		.fattr = fattr,
4656 		.fh = fhandle,
4657 	};
4658 	struct rpc_message msg = {
4659 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_LOOKUPP],
4660 		.rpc_argp = &args,
4661 		.rpc_resp = &res,
4662 	};
4663 	unsigned short task_flags = 0;
4664 
4665 	if (NFS_SERVER(inode)->flags & NFS_MOUNT_SOFTREVAL)
4666 		task_flags |= RPC_TASK_TIMEOUT;
4667 
4668 	args.bitmask = nfs4_bitmask(server, fattr->label);
4669 
4670 	nfs_fattr_init(fattr);
4671 
4672 	dprintk("NFS call  lookupp ino=0x%lx\n", inode->i_ino);
4673 	status = nfs4_call_sync(clnt, server, &msg, &args.seq_args,
4674 				&res.seq_res, task_flags);
4675 	dprintk("NFS reply lookupp: %d\n", status);
4676 	return status;
4677 }
4678 
4679 static int nfs4_proc_lookupp(struct inode *inode, struct nfs_fh *fhandle,
4680 			     struct nfs_fattr *fattr)
4681 {
4682 	struct nfs4_exception exception = {
4683 		.interruptible = true,
4684 	};
4685 	int err;
4686 	do {
4687 		err = _nfs4_proc_lookupp(inode, fhandle, fattr);
4688 		trace_nfs4_lookupp(inode, err);
4689 		err = nfs4_handle_exception(NFS_SERVER(inode), err,
4690 				&exception);
4691 	} while (exception.retry);
4692 	return err;
4693 }
4694 
4695 static int _nfs4_proc_access(struct inode *inode, struct nfs_access_entry *entry,
4696 			     const struct cred *cred)
4697 {
4698 	struct nfs_server *server = NFS_SERVER(inode);
4699 	struct nfs4_accessargs args = {
4700 		.fh = NFS_FH(inode),
4701 		.access = entry->mask,
4702 	};
4703 	struct nfs4_accessres res = {
4704 		.server = server,
4705 	};
4706 	struct rpc_message msg = {
4707 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_ACCESS],
4708 		.rpc_argp = &args,
4709 		.rpc_resp = &res,
4710 		.rpc_cred = cred,
4711 	};
4712 	int status = 0;
4713 
4714 	if (!nfs4_have_delegation(inode, FMODE_READ, 0)) {
4715 		res.fattr = nfs_alloc_fattr();
4716 		if (res.fattr == NULL)
4717 			return -ENOMEM;
4718 		args.bitmask = server->cache_consistency_bitmask;
4719 	}
4720 	status = nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 0);
4721 	if (!status) {
4722 		nfs_access_set_mask(entry, res.access);
4723 		if (res.fattr)
4724 			nfs_refresh_inode(inode, res.fattr);
4725 	}
4726 	nfs_free_fattr(res.fattr);
4727 	return status;
4728 }
4729 
4730 static int nfs4_proc_access(struct inode *inode, struct nfs_access_entry *entry,
4731 			    const struct cred *cred)
4732 {
4733 	struct nfs4_exception exception = {
4734 		.interruptible = true,
4735 	};
4736 	int err;
4737 	do {
4738 		err = _nfs4_proc_access(inode, entry, cred);
4739 		trace_nfs4_access(inode, err);
4740 		err = nfs4_handle_exception(NFS_SERVER(inode), err,
4741 				&exception);
4742 	} while (exception.retry);
4743 	return err;
4744 }
4745 
4746 /*
4747  * TODO: For the time being, we don't try to get any attributes
4748  * along with any of the zero-copy operations READ, READDIR,
4749  * READLINK, WRITE.
4750  *
4751  * In the case of the first three, we want to put the GETATTR
4752  * after the read-type operation -- this is because it is hard
4753  * to predict the length of a GETATTR response in v4, and thus
4754  * align the READ data correctly.  This means that the GETATTR
4755  * may end up partially falling into the page cache, and we should
4756  * shift it into the 'tail' of the xdr_buf before processing.
4757  * To do this efficiently, we need to know the total length
4758  * of data received, which doesn't seem to be available outside
4759  * of the RPC layer.
4760  *
4761  * In the case of WRITE, we also want to put the GETATTR after
4762  * the operation -- in this case because we want to make sure
4763  * we get the post-operation mtime and size.
4764  *
4765  * Both of these changes to the XDR layer would in fact be quite
4766  * minor, but I decided to leave them for a subsequent patch.
4767  */
4768 static int _nfs4_proc_readlink(struct inode *inode, struct page *page,
4769 		unsigned int pgbase, unsigned int pglen)
4770 {
4771 	struct nfs4_readlink args = {
4772 		.fh       = NFS_FH(inode),
4773 		.pgbase	  = pgbase,
4774 		.pglen    = pglen,
4775 		.pages    = &page,
4776 	};
4777 	struct nfs4_readlink_res res;
4778 	struct rpc_message msg = {
4779 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_READLINK],
4780 		.rpc_argp = &args,
4781 		.rpc_resp = &res,
4782 	};
4783 
4784 	return nfs4_call_sync(NFS_SERVER(inode)->client, NFS_SERVER(inode), &msg, &args.seq_args, &res.seq_res, 0);
4785 }
4786 
4787 static int nfs4_proc_readlink(struct inode *inode, struct page *page,
4788 		unsigned int pgbase, unsigned int pglen)
4789 {
4790 	struct nfs4_exception exception = {
4791 		.interruptible = true,
4792 	};
4793 	int err;
4794 	do {
4795 		err = _nfs4_proc_readlink(inode, page, pgbase, pglen);
4796 		trace_nfs4_readlink(inode, err);
4797 		err = nfs4_handle_exception(NFS_SERVER(inode), err,
4798 				&exception);
4799 	} while (exception.retry);
4800 	return err;
4801 }
4802 
4803 /*
4804  * This is just for mknod.  open(O_CREAT) will always do ->open_context().
4805  */
4806 static int
4807 nfs4_proc_create(struct inode *dir, struct dentry *dentry, struct iattr *sattr,
4808 		 int flags)
4809 {
4810 	struct nfs_server *server = NFS_SERVER(dir);
4811 	struct nfs4_label l, *ilabel;
4812 	struct nfs_open_context *ctx;
4813 	struct nfs4_state *state;
4814 	int status = 0;
4815 
4816 	ctx = alloc_nfs_open_context(dentry, FMODE_READ, NULL);
4817 	if (IS_ERR(ctx))
4818 		return PTR_ERR(ctx);
4819 
4820 	ilabel = nfs4_label_init_security(dir, dentry, sattr, &l);
4821 
4822 	if (!(server->attr_bitmask[2] & FATTR4_WORD2_MODE_UMASK))
4823 		sattr->ia_mode &= ~current_umask();
4824 	state = nfs4_do_open(dir, ctx, flags, sattr, ilabel, NULL);
4825 	if (IS_ERR(state)) {
4826 		status = PTR_ERR(state);
4827 		goto out;
4828 	}
4829 out:
4830 	nfs4_label_release_security(ilabel);
4831 	put_nfs_open_context(ctx);
4832 	return status;
4833 }
4834 
4835 static int
4836 _nfs4_proc_remove(struct inode *dir, const struct qstr *name, u32 ftype)
4837 {
4838 	struct nfs_server *server = NFS_SERVER(dir);
4839 	struct nfs_removeargs args = {
4840 		.fh = NFS_FH(dir),
4841 		.name = *name,
4842 	};
4843 	struct nfs_removeres res = {
4844 		.server = server,
4845 	};
4846 	struct rpc_message msg = {
4847 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_REMOVE],
4848 		.rpc_argp = &args,
4849 		.rpc_resp = &res,
4850 	};
4851 	unsigned long timestamp = jiffies;
4852 	int status;
4853 
4854 	status = nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 1);
4855 	if (status == 0) {
4856 		spin_lock(&dir->i_lock);
4857 		/* Removing a directory decrements nlink in the parent */
4858 		if (ftype == NF4DIR && dir->i_nlink > 2)
4859 			nfs4_dec_nlink_locked(dir);
4860 		nfs4_update_changeattr_locked(dir, &res.cinfo, timestamp,
4861 					      NFS_INO_INVALID_DATA);
4862 		spin_unlock(&dir->i_lock);
4863 	}
4864 	return status;
4865 }
4866 
4867 static int nfs4_proc_remove(struct inode *dir, struct dentry *dentry)
4868 {
4869 	struct nfs4_exception exception = {
4870 		.interruptible = true,
4871 	};
4872 	struct inode *inode = d_inode(dentry);
4873 	int err;
4874 
4875 	if (inode) {
4876 		if (inode->i_nlink == 1)
4877 			nfs4_inode_return_delegation(inode);
4878 		else
4879 			nfs4_inode_make_writeable(inode);
4880 	}
4881 	do {
4882 		err = _nfs4_proc_remove(dir, &dentry->d_name, NF4REG);
4883 		trace_nfs4_remove(dir, &dentry->d_name, err);
4884 		err = nfs4_handle_exception(NFS_SERVER(dir), err,
4885 				&exception);
4886 	} while (exception.retry);
4887 	return err;
4888 }
4889 
4890 static int nfs4_proc_rmdir(struct inode *dir, const struct qstr *name)
4891 {
4892 	struct nfs4_exception exception = {
4893 		.interruptible = true,
4894 	};
4895 	int err;
4896 
4897 	do {
4898 		err = _nfs4_proc_remove(dir, name, NF4DIR);
4899 		trace_nfs4_remove(dir, name, err);
4900 		err = nfs4_handle_exception(NFS_SERVER(dir), err,
4901 				&exception);
4902 	} while (exception.retry);
4903 	return err;
4904 }
4905 
4906 static void nfs4_proc_unlink_setup(struct rpc_message *msg,
4907 		struct dentry *dentry,
4908 		struct inode *inode)
4909 {
4910 	struct nfs_removeargs *args = msg->rpc_argp;
4911 	struct nfs_removeres *res = msg->rpc_resp;
4912 
4913 	res->server = NFS_SB(dentry->d_sb);
4914 	msg->rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_REMOVE];
4915 	nfs4_init_sequence(&args->seq_args, &res->seq_res, 1, 0);
4916 
4917 	nfs_fattr_init(res->dir_attr);
4918 
4919 	if (inode) {
4920 		nfs4_inode_return_delegation(inode);
4921 		nfs_d_prune_case_insensitive_aliases(inode);
4922 	}
4923 }
4924 
4925 static void nfs4_proc_unlink_rpc_prepare(struct rpc_task *task, struct nfs_unlinkdata *data)
4926 {
4927 	nfs4_setup_sequence(NFS_SB(data->dentry->d_sb)->nfs_client,
4928 			&data->args.seq_args,
4929 			&data->res.seq_res,
4930 			task);
4931 }
4932 
4933 static int nfs4_proc_unlink_done(struct rpc_task *task, struct inode *dir)
4934 {
4935 	struct nfs_unlinkdata *data = task->tk_calldata;
4936 	struct nfs_removeres *res = &data->res;
4937 
4938 	if (!nfs4_sequence_done(task, &res->seq_res))
4939 		return 0;
4940 	if (nfs4_async_handle_error(task, res->server, NULL,
4941 				    &data->timeout) == -EAGAIN)
4942 		return 0;
4943 	if (task->tk_status == 0)
4944 		nfs4_update_changeattr(dir, &res->cinfo,
4945 				res->dir_attr->time_start,
4946 				NFS_INO_INVALID_DATA);
4947 	return 1;
4948 }
4949 
4950 static void nfs4_proc_rename_setup(struct rpc_message *msg,
4951 		struct dentry *old_dentry,
4952 		struct dentry *new_dentry)
4953 {
4954 	struct nfs_renameargs *arg = msg->rpc_argp;
4955 	struct nfs_renameres *res = msg->rpc_resp;
4956 	struct inode *old_inode = d_inode(old_dentry);
4957 	struct inode *new_inode = d_inode(new_dentry);
4958 
4959 	if (old_inode)
4960 		nfs4_inode_make_writeable(old_inode);
4961 	if (new_inode)
4962 		nfs4_inode_return_delegation(new_inode);
4963 	msg->rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_RENAME];
4964 	res->server = NFS_SB(old_dentry->d_sb);
4965 	nfs4_init_sequence(&arg->seq_args, &res->seq_res, 1, 0);
4966 }
4967 
4968 static void nfs4_proc_rename_rpc_prepare(struct rpc_task *task, struct nfs_renamedata *data)
4969 {
4970 	nfs4_setup_sequence(NFS_SERVER(data->old_dir)->nfs_client,
4971 			&data->args.seq_args,
4972 			&data->res.seq_res,
4973 			task);
4974 }
4975 
4976 static int nfs4_proc_rename_done(struct rpc_task *task, struct inode *old_dir,
4977 				 struct inode *new_dir)
4978 {
4979 	struct nfs_renamedata *data = task->tk_calldata;
4980 	struct nfs_renameres *res = &data->res;
4981 
4982 	if (!nfs4_sequence_done(task, &res->seq_res))
4983 		return 0;
4984 	if (nfs4_async_handle_error(task, res->server, NULL, &data->timeout) == -EAGAIN)
4985 		return 0;
4986 
4987 	if (task->tk_status == 0) {
4988 		nfs_d_prune_case_insensitive_aliases(d_inode(data->old_dentry));
4989 		if (new_dir != old_dir) {
4990 			/* Note: If we moved a directory, nlink will change */
4991 			nfs4_update_changeattr(old_dir, &res->old_cinfo,
4992 					res->old_fattr->time_start,
4993 					NFS_INO_INVALID_NLINK |
4994 					    NFS_INO_INVALID_DATA);
4995 			nfs4_update_changeattr(new_dir, &res->new_cinfo,
4996 					res->new_fattr->time_start,
4997 					NFS_INO_INVALID_NLINK |
4998 					    NFS_INO_INVALID_DATA);
4999 		} else
5000 			nfs4_update_changeattr(old_dir, &res->old_cinfo,
5001 					res->old_fattr->time_start,
5002 					NFS_INO_INVALID_DATA);
5003 	}
5004 	return 1;
5005 }
5006 
5007 static int _nfs4_proc_link(struct inode *inode, struct inode *dir, const struct qstr *name)
5008 {
5009 	struct nfs_server *server = NFS_SERVER(inode);
5010 	__u32 bitmask[NFS4_BITMASK_SZ];
5011 	struct nfs4_link_arg arg = {
5012 		.fh     = NFS_FH(inode),
5013 		.dir_fh = NFS_FH(dir),
5014 		.name   = name,
5015 		.bitmask = bitmask,
5016 	};
5017 	struct nfs4_link_res res = {
5018 		.server = server,
5019 	};
5020 	struct rpc_message msg = {
5021 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_LINK],
5022 		.rpc_argp = &arg,
5023 		.rpc_resp = &res,
5024 	};
5025 	int status = -ENOMEM;
5026 
5027 	res.fattr = nfs_alloc_fattr_with_label(server);
5028 	if (res.fattr == NULL)
5029 		goto out;
5030 
5031 	nfs4_inode_make_writeable(inode);
5032 	nfs4_bitmap_copy_adjust(bitmask, nfs4_bitmask(server, res.fattr->label),
5033 				inode,
5034 				NFS_INO_INVALID_CHANGE | NFS_INO_INVALID_CTIME);
5035 	status = nfs4_call_sync(server->client, server, &msg, &arg.seq_args, &res.seq_res, 1);
5036 	if (!status) {
5037 		nfs4_update_changeattr(dir, &res.cinfo, res.fattr->time_start,
5038 				       NFS_INO_INVALID_DATA);
5039 		nfs4_inc_nlink(inode);
5040 		status = nfs_post_op_update_inode(inode, res.fattr);
5041 		if (!status)
5042 			nfs_setsecurity(inode, res.fattr);
5043 	}
5044 
5045 out:
5046 	nfs_free_fattr(res.fattr);
5047 	return status;
5048 }
5049 
5050 static int nfs4_proc_link(struct inode *inode, struct inode *dir, const struct qstr *name)
5051 {
5052 	struct nfs4_exception exception = {
5053 		.interruptible = true,
5054 	};
5055 	int err;
5056 	do {
5057 		err = nfs4_handle_exception(NFS_SERVER(inode),
5058 				_nfs4_proc_link(inode, dir, name),
5059 				&exception);
5060 	} while (exception.retry);
5061 	return err;
5062 }
5063 
5064 struct nfs4_createdata {
5065 	struct rpc_message msg;
5066 	struct nfs4_create_arg arg;
5067 	struct nfs4_create_res res;
5068 	struct nfs_fh fh;
5069 	struct nfs_fattr fattr;
5070 };
5071 
5072 static struct nfs4_createdata *nfs4_alloc_createdata(struct inode *dir,
5073 		const struct qstr *name, struct iattr *sattr, u32 ftype)
5074 {
5075 	struct nfs4_createdata *data;
5076 
5077 	data = kzalloc(sizeof(*data), GFP_KERNEL);
5078 	if (data != NULL) {
5079 		struct nfs_server *server = NFS_SERVER(dir);
5080 
5081 		data->fattr.label = nfs4_label_alloc(server, GFP_KERNEL);
5082 		if (IS_ERR(data->fattr.label))
5083 			goto out_free;
5084 
5085 		data->msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_CREATE];
5086 		data->msg.rpc_argp = &data->arg;
5087 		data->msg.rpc_resp = &data->res;
5088 		data->arg.dir_fh = NFS_FH(dir);
5089 		data->arg.server = server;
5090 		data->arg.name = name;
5091 		data->arg.attrs = sattr;
5092 		data->arg.ftype = ftype;
5093 		data->arg.bitmask = nfs4_bitmask(server, data->fattr.label);
5094 		data->arg.umask = current_umask();
5095 		data->res.server = server;
5096 		data->res.fh = &data->fh;
5097 		data->res.fattr = &data->fattr;
5098 		nfs_fattr_init(data->res.fattr);
5099 	}
5100 	return data;
5101 out_free:
5102 	kfree(data);
5103 	return NULL;
5104 }
5105 
5106 static int nfs4_do_create(struct inode *dir, struct dentry *dentry, struct nfs4_createdata *data)
5107 {
5108 	int status = nfs4_call_sync(NFS_SERVER(dir)->client, NFS_SERVER(dir), &data->msg,
5109 				    &data->arg.seq_args, &data->res.seq_res, 1);
5110 	if (status == 0) {
5111 		spin_lock(&dir->i_lock);
5112 		/* Creating a directory bumps nlink in the parent */
5113 		if (data->arg.ftype == NF4DIR)
5114 			nfs4_inc_nlink_locked(dir);
5115 		nfs4_update_changeattr_locked(dir, &data->res.dir_cinfo,
5116 					      data->res.fattr->time_start,
5117 					      NFS_INO_INVALID_DATA);
5118 		spin_unlock(&dir->i_lock);
5119 		status = nfs_instantiate(dentry, data->res.fh, data->res.fattr);
5120 	}
5121 	return status;
5122 }
5123 
5124 static void nfs4_free_createdata(struct nfs4_createdata *data)
5125 {
5126 	nfs4_label_free(data->fattr.label);
5127 	kfree(data);
5128 }
5129 
5130 static int _nfs4_proc_symlink(struct inode *dir, struct dentry *dentry,
5131 		struct folio *folio, unsigned int len, struct iattr *sattr,
5132 		struct nfs4_label *label)
5133 {
5134 	struct page *page = &folio->page;
5135 	struct nfs4_createdata *data;
5136 	int status = -ENAMETOOLONG;
5137 
5138 	if (len > NFS4_MAXPATHLEN)
5139 		goto out;
5140 
5141 	status = -ENOMEM;
5142 	data = nfs4_alloc_createdata(dir, &dentry->d_name, sattr, NF4LNK);
5143 	if (data == NULL)
5144 		goto out;
5145 
5146 	data->msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_SYMLINK];
5147 	data->arg.u.symlink.pages = &page;
5148 	data->arg.u.symlink.len = len;
5149 	data->arg.label = label;
5150 
5151 	status = nfs4_do_create(dir, dentry, data);
5152 
5153 	nfs4_free_createdata(data);
5154 out:
5155 	return status;
5156 }
5157 
5158 static int nfs4_proc_symlink(struct inode *dir, struct dentry *dentry,
5159 		struct folio *folio, unsigned int len, struct iattr *sattr)
5160 {
5161 	struct nfs4_exception exception = {
5162 		.interruptible = true,
5163 	};
5164 	struct nfs4_label l, *label;
5165 	int err;
5166 
5167 	label = nfs4_label_init_security(dir, dentry, sattr, &l);
5168 
5169 	do {
5170 		err = _nfs4_proc_symlink(dir, dentry, folio, len, sattr, label);
5171 		trace_nfs4_symlink(dir, &dentry->d_name, err);
5172 		err = nfs4_handle_exception(NFS_SERVER(dir), err,
5173 				&exception);
5174 	} while (exception.retry);
5175 
5176 	nfs4_label_release_security(label);
5177 	return err;
5178 }
5179 
5180 static int _nfs4_proc_mkdir(struct inode *dir, struct dentry *dentry,
5181 		struct iattr *sattr, struct nfs4_label *label)
5182 {
5183 	struct nfs4_createdata *data;
5184 	int status = -ENOMEM;
5185 
5186 	data = nfs4_alloc_createdata(dir, &dentry->d_name, sattr, NF4DIR);
5187 	if (data == NULL)
5188 		goto out;
5189 
5190 	data->arg.label = label;
5191 	status = nfs4_do_create(dir, dentry, data);
5192 
5193 	nfs4_free_createdata(data);
5194 out:
5195 	return status;
5196 }
5197 
5198 static int nfs4_proc_mkdir(struct inode *dir, struct dentry *dentry,
5199 		struct iattr *sattr)
5200 {
5201 	struct nfs_server *server = NFS_SERVER(dir);
5202 	struct nfs4_exception exception = {
5203 		.interruptible = true,
5204 	};
5205 	struct nfs4_label l, *label;
5206 	int err;
5207 
5208 	label = nfs4_label_init_security(dir, dentry, sattr, &l);
5209 
5210 	if (!(server->attr_bitmask[2] & FATTR4_WORD2_MODE_UMASK))
5211 		sattr->ia_mode &= ~current_umask();
5212 	do {
5213 		err = _nfs4_proc_mkdir(dir, dentry, sattr, label);
5214 		trace_nfs4_mkdir(dir, &dentry->d_name, err);
5215 		err = nfs4_handle_exception(NFS_SERVER(dir), err,
5216 				&exception);
5217 	} while (exception.retry);
5218 	nfs4_label_release_security(label);
5219 
5220 	return err;
5221 }
5222 
5223 static int _nfs4_proc_readdir(struct nfs_readdir_arg *nr_arg,
5224 			      struct nfs_readdir_res *nr_res)
5225 {
5226 	struct inode		*dir = d_inode(nr_arg->dentry);
5227 	struct nfs_server	*server = NFS_SERVER(dir);
5228 	struct nfs4_readdir_arg args = {
5229 		.fh = NFS_FH(dir),
5230 		.pages = nr_arg->pages,
5231 		.pgbase = 0,
5232 		.count = nr_arg->page_len,
5233 		.plus = nr_arg->plus,
5234 	};
5235 	struct nfs4_readdir_res res;
5236 	struct rpc_message msg = {
5237 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_READDIR],
5238 		.rpc_argp = &args,
5239 		.rpc_resp = &res,
5240 		.rpc_cred = nr_arg->cred,
5241 	};
5242 	int			status;
5243 
5244 	dprintk("%s: dentry = %pd2, cookie = %llu\n", __func__,
5245 		nr_arg->dentry, (unsigned long long)nr_arg->cookie);
5246 	if (!(server->caps & NFS_CAP_SECURITY_LABEL))
5247 		args.bitmask = server->attr_bitmask_nl;
5248 	else
5249 		args.bitmask = server->attr_bitmask;
5250 
5251 	nfs4_setup_readdir(nr_arg->cookie, nr_arg->verf, nr_arg->dentry, &args);
5252 	res.pgbase = args.pgbase;
5253 	status = nfs4_call_sync(server->client, server, &msg, &args.seq_args,
5254 			&res.seq_res, 0);
5255 	if (status >= 0) {
5256 		memcpy(nr_res->verf, res.verifier.data, NFS4_VERIFIER_SIZE);
5257 		status += args.pgbase;
5258 	}
5259 
5260 	nfs_invalidate_atime(dir);
5261 
5262 	dprintk("%s: returns %d\n", __func__, status);
5263 	return status;
5264 }
5265 
5266 static int nfs4_proc_readdir(struct nfs_readdir_arg *arg,
5267 			     struct nfs_readdir_res *res)
5268 {
5269 	struct nfs4_exception exception = {
5270 		.interruptible = true,
5271 	};
5272 	int err;
5273 	do {
5274 		err = _nfs4_proc_readdir(arg, res);
5275 		trace_nfs4_readdir(d_inode(arg->dentry), err);
5276 		err = nfs4_handle_exception(NFS_SERVER(d_inode(arg->dentry)),
5277 					    err, &exception);
5278 	} while (exception.retry);
5279 	return err;
5280 }
5281 
5282 static int _nfs4_proc_mknod(struct inode *dir, struct dentry *dentry,
5283 		struct iattr *sattr, struct nfs4_label *label, dev_t rdev)
5284 {
5285 	struct nfs4_createdata *data;
5286 	int mode = sattr->ia_mode;
5287 	int status = -ENOMEM;
5288 
5289 	data = nfs4_alloc_createdata(dir, &dentry->d_name, sattr, NF4SOCK);
5290 	if (data == NULL)
5291 		goto out;
5292 
5293 	if (S_ISFIFO(mode))
5294 		data->arg.ftype = NF4FIFO;
5295 	else if (S_ISBLK(mode)) {
5296 		data->arg.ftype = NF4BLK;
5297 		data->arg.u.device.specdata1 = MAJOR(rdev);
5298 		data->arg.u.device.specdata2 = MINOR(rdev);
5299 	}
5300 	else if (S_ISCHR(mode)) {
5301 		data->arg.ftype = NF4CHR;
5302 		data->arg.u.device.specdata1 = MAJOR(rdev);
5303 		data->arg.u.device.specdata2 = MINOR(rdev);
5304 	} else if (!S_ISSOCK(mode)) {
5305 		status = -EINVAL;
5306 		goto out_free;
5307 	}
5308 
5309 	data->arg.label = label;
5310 	status = nfs4_do_create(dir, dentry, data);
5311 out_free:
5312 	nfs4_free_createdata(data);
5313 out:
5314 	return status;
5315 }
5316 
5317 static int nfs4_proc_mknod(struct inode *dir, struct dentry *dentry,
5318 		struct iattr *sattr, dev_t rdev)
5319 {
5320 	struct nfs_server *server = NFS_SERVER(dir);
5321 	struct nfs4_exception exception = {
5322 		.interruptible = true,
5323 	};
5324 	struct nfs4_label l, *label;
5325 	int err;
5326 
5327 	label = nfs4_label_init_security(dir, dentry, sattr, &l);
5328 
5329 	if (!(server->attr_bitmask[2] & FATTR4_WORD2_MODE_UMASK))
5330 		sattr->ia_mode &= ~current_umask();
5331 	do {
5332 		err = _nfs4_proc_mknod(dir, dentry, sattr, label, rdev);
5333 		trace_nfs4_mknod(dir, &dentry->d_name, err);
5334 		err = nfs4_handle_exception(NFS_SERVER(dir), err,
5335 				&exception);
5336 	} while (exception.retry);
5337 
5338 	nfs4_label_release_security(label);
5339 
5340 	return err;
5341 }
5342 
5343 static int _nfs4_proc_statfs(struct nfs_server *server, struct nfs_fh *fhandle,
5344 		 struct nfs_fsstat *fsstat)
5345 {
5346 	struct nfs4_statfs_arg args = {
5347 		.fh = fhandle,
5348 		.bitmask = server->attr_bitmask,
5349 	};
5350 	struct nfs4_statfs_res res = {
5351 		.fsstat = fsstat,
5352 	};
5353 	struct rpc_message msg = {
5354 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_STATFS],
5355 		.rpc_argp = &args,
5356 		.rpc_resp = &res,
5357 	};
5358 
5359 	nfs_fattr_init(fsstat->fattr);
5360 	return  nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 0);
5361 }
5362 
5363 static int nfs4_proc_statfs(struct nfs_server *server, struct nfs_fh *fhandle, struct nfs_fsstat *fsstat)
5364 {
5365 	struct nfs4_exception exception = {
5366 		.interruptible = true,
5367 	};
5368 	int err;
5369 	do {
5370 		err = nfs4_handle_exception(server,
5371 				_nfs4_proc_statfs(server, fhandle, fsstat),
5372 				&exception);
5373 	} while (exception.retry);
5374 	return err;
5375 }
5376 
5377 static int _nfs4_do_fsinfo(struct nfs_server *server, struct nfs_fh *fhandle,
5378 		struct nfs_fsinfo *fsinfo)
5379 {
5380 	struct nfs4_fsinfo_arg args = {
5381 		.fh = fhandle,
5382 		.bitmask = server->attr_bitmask,
5383 	};
5384 	struct nfs4_fsinfo_res res = {
5385 		.fsinfo = fsinfo,
5386 	};
5387 	struct rpc_message msg = {
5388 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_FSINFO],
5389 		.rpc_argp = &args,
5390 		.rpc_resp = &res,
5391 	};
5392 
5393 	return nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 0);
5394 }
5395 
5396 static int nfs4_do_fsinfo(struct nfs_server *server, struct nfs_fh *fhandle, struct nfs_fsinfo *fsinfo)
5397 {
5398 	struct nfs4_exception exception = {
5399 		.interruptible = true,
5400 	};
5401 	int err;
5402 
5403 	do {
5404 		err = _nfs4_do_fsinfo(server, fhandle, fsinfo);
5405 		trace_nfs4_fsinfo(server, fhandle, fsinfo->fattr, err);
5406 		if (err == 0) {
5407 			nfs4_set_lease_period(server->nfs_client, fsinfo->lease_time * HZ);
5408 			break;
5409 		}
5410 		err = nfs4_handle_exception(server, err, &exception);
5411 	} while (exception.retry);
5412 	return err;
5413 }
5414 
5415 static int nfs4_proc_fsinfo(struct nfs_server *server, struct nfs_fh *fhandle, struct nfs_fsinfo *fsinfo)
5416 {
5417 	int error;
5418 
5419 	nfs_fattr_init(fsinfo->fattr);
5420 	error = nfs4_do_fsinfo(server, fhandle, fsinfo);
5421 	if (error == 0) {
5422 		/* block layout checks this! */
5423 		server->pnfs_blksize = fsinfo->blksize;
5424 		set_pnfs_layoutdriver(server, fhandle, fsinfo);
5425 	}
5426 
5427 	return error;
5428 }
5429 
5430 static int _nfs4_proc_pathconf(struct nfs_server *server, struct nfs_fh *fhandle,
5431 		struct nfs_pathconf *pathconf)
5432 {
5433 	struct nfs4_pathconf_arg args = {
5434 		.fh = fhandle,
5435 		.bitmask = server->attr_bitmask,
5436 	};
5437 	struct nfs4_pathconf_res res = {
5438 		.pathconf = pathconf,
5439 	};
5440 	struct rpc_message msg = {
5441 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_PATHCONF],
5442 		.rpc_argp = &args,
5443 		.rpc_resp = &res,
5444 	};
5445 
5446 	/* None of the pathconf attributes are mandatory to implement */
5447 	if ((args.bitmask[0] & nfs4_pathconf_bitmap[0]) == 0) {
5448 		memset(pathconf, 0, sizeof(*pathconf));
5449 		return 0;
5450 	}
5451 
5452 	nfs_fattr_init(pathconf->fattr);
5453 	return nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 0);
5454 }
5455 
5456 static int nfs4_proc_pathconf(struct nfs_server *server, struct nfs_fh *fhandle,
5457 		struct nfs_pathconf *pathconf)
5458 {
5459 	struct nfs4_exception exception = {
5460 		.interruptible = true,
5461 	};
5462 	int err;
5463 
5464 	do {
5465 		err = nfs4_handle_exception(server,
5466 				_nfs4_proc_pathconf(server, fhandle, pathconf),
5467 				&exception);
5468 	} while (exception.retry);
5469 	return err;
5470 }
5471 
5472 int nfs4_set_rw_stateid(nfs4_stateid *stateid,
5473 		const struct nfs_open_context *ctx,
5474 		const struct nfs_lock_context *l_ctx,
5475 		fmode_t fmode)
5476 {
5477 	return nfs4_select_rw_stateid(ctx->state, fmode, l_ctx, stateid, NULL);
5478 }
5479 EXPORT_SYMBOL_GPL(nfs4_set_rw_stateid);
5480 
5481 static bool nfs4_stateid_is_current(nfs4_stateid *stateid,
5482 		const struct nfs_open_context *ctx,
5483 		const struct nfs_lock_context *l_ctx,
5484 		fmode_t fmode)
5485 {
5486 	nfs4_stateid _current_stateid;
5487 
5488 	/* If the current stateid represents a lost lock, then exit */
5489 	if (nfs4_set_rw_stateid(&_current_stateid, ctx, l_ctx, fmode) == -EIO)
5490 		return true;
5491 	return nfs4_stateid_match(stateid, &_current_stateid);
5492 }
5493 
5494 static bool nfs4_error_stateid_expired(int err)
5495 {
5496 	switch (err) {
5497 	case -NFS4ERR_DELEG_REVOKED:
5498 	case -NFS4ERR_ADMIN_REVOKED:
5499 	case -NFS4ERR_BAD_STATEID:
5500 	case -NFS4ERR_STALE_STATEID:
5501 	case -NFS4ERR_OLD_STATEID:
5502 	case -NFS4ERR_OPENMODE:
5503 	case -NFS4ERR_EXPIRED:
5504 		return true;
5505 	}
5506 	return false;
5507 }
5508 
5509 static int nfs4_read_done_cb(struct rpc_task *task, struct nfs_pgio_header *hdr)
5510 {
5511 	struct nfs_server *server = NFS_SERVER(hdr->inode);
5512 
5513 	trace_nfs4_read(hdr, task->tk_status);
5514 	if (task->tk_status < 0) {
5515 		struct nfs4_exception exception = {
5516 			.inode = hdr->inode,
5517 			.state = hdr->args.context->state,
5518 			.stateid = &hdr->args.stateid,
5519 		};
5520 		task->tk_status = nfs4_async_handle_exception(task,
5521 				server, task->tk_status, &exception);
5522 		if (exception.retry) {
5523 			rpc_restart_call_prepare(task);
5524 			return -EAGAIN;
5525 		}
5526 	}
5527 
5528 	if (task->tk_status > 0)
5529 		renew_lease(server, hdr->timestamp);
5530 	return 0;
5531 }
5532 
5533 static bool nfs4_read_stateid_changed(struct rpc_task *task,
5534 		struct nfs_pgio_args *args)
5535 {
5536 
5537 	if (!nfs4_error_stateid_expired(task->tk_status) ||
5538 		nfs4_stateid_is_current(&args->stateid,
5539 				args->context,
5540 				args->lock_context,
5541 				FMODE_READ))
5542 		return false;
5543 	rpc_restart_call_prepare(task);
5544 	return true;
5545 }
5546 
5547 static bool nfs4_read_plus_not_supported(struct rpc_task *task,
5548 					 struct nfs_pgio_header *hdr)
5549 {
5550 	struct nfs_server *server = NFS_SERVER(hdr->inode);
5551 	struct rpc_message *msg = &task->tk_msg;
5552 
5553 	if (msg->rpc_proc == &nfs4_procedures[NFSPROC4_CLNT_READ_PLUS] &&
5554 	    task->tk_status == -ENOTSUPP) {
5555 		server->caps &= ~NFS_CAP_READ_PLUS;
5556 		msg->rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_READ];
5557 		rpc_restart_call_prepare(task);
5558 		return true;
5559 	}
5560 	return false;
5561 }
5562 
5563 static int nfs4_read_done(struct rpc_task *task, struct nfs_pgio_header *hdr)
5564 {
5565 	if (!nfs4_sequence_done(task, &hdr->res.seq_res))
5566 		return -EAGAIN;
5567 	if (nfs4_read_stateid_changed(task, &hdr->args))
5568 		return -EAGAIN;
5569 	if (nfs4_read_plus_not_supported(task, hdr))
5570 		return -EAGAIN;
5571 	if (task->tk_status > 0)
5572 		nfs_invalidate_atime(hdr->inode);
5573 	return hdr->pgio_done_cb ? hdr->pgio_done_cb(task, hdr) :
5574 				    nfs4_read_done_cb(task, hdr);
5575 }
5576 
5577 #if defined CONFIG_NFS_V4_2 && defined CONFIG_NFS_V4_2_READ_PLUS
5578 static bool nfs42_read_plus_support(struct nfs_pgio_header *hdr,
5579 				    struct rpc_message *msg)
5580 {
5581 	/* Note: We don't use READ_PLUS with pNFS yet */
5582 	if (nfs_server_capable(hdr->inode, NFS_CAP_READ_PLUS) && !hdr->ds_clp) {
5583 		msg->rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_READ_PLUS];
5584 		return nfs_read_alloc_scratch(hdr, READ_PLUS_SCRATCH_SIZE);
5585 	}
5586 	return false;
5587 }
5588 #else
5589 static bool nfs42_read_plus_support(struct nfs_pgio_header *hdr,
5590 				    struct rpc_message *msg)
5591 {
5592 	return false;
5593 }
5594 #endif /* CONFIG_NFS_V4_2 */
5595 
5596 static void nfs4_proc_read_setup(struct nfs_pgio_header *hdr,
5597 				 struct rpc_message *msg)
5598 {
5599 	hdr->timestamp   = jiffies;
5600 	if (!hdr->pgio_done_cb)
5601 		hdr->pgio_done_cb = nfs4_read_done_cb;
5602 	if (!nfs42_read_plus_support(hdr, msg))
5603 		msg->rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_READ];
5604 	nfs4_init_sequence(&hdr->args.seq_args, &hdr->res.seq_res, 0, 0);
5605 }
5606 
5607 static int nfs4_proc_pgio_rpc_prepare(struct rpc_task *task,
5608 				      struct nfs_pgio_header *hdr)
5609 {
5610 	if (nfs4_setup_sequence(NFS_SERVER(hdr->inode)->nfs_client,
5611 			&hdr->args.seq_args,
5612 			&hdr->res.seq_res,
5613 			task))
5614 		return 0;
5615 	if (nfs4_set_rw_stateid(&hdr->args.stateid, hdr->args.context,
5616 				hdr->args.lock_context,
5617 				hdr->rw_mode) == -EIO)
5618 		return -EIO;
5619 	if (unlikely(test_bit(NFS_CONTEXT_BAD, &hdr->args.context->flags)))
5620 		return -EIO;
5621 	return 0;
5622 }
5623 
5624 static int nfs4_write_done_cb(struct rpc_task *task,
5625 			      struct nfs_pgio_header *hdr)
5626 {
5627 	struct inode *inode = hdr->inode;
5628 
5629 	trace_nfs4_write(hdr, task->tk_status);
5630 	if (task->tk_status < 0) {
5631 		struct nfs4_exception exception = {
5632 			.inode = hdr->inode,
5633 			.state = hdr->args.context->state,
5634 			.stateid = &hdr->args.stateid,
5635 		};
5636 		task->tk_status = nfs4_async_handle_exception(task,
5637 				NFS_SERVER(inode), task->tk_status,
5638 				&exception);
5639 		if (exception.retry) {
5640 			rpc_restart_call_prepare(task);
5641 			return -EAGAIN;
5642 		}
5643 	}
5644 	if (task->tk_status >= 0) {
5645 		renew_lease(NFS_SERVER(inode), hdr->timestamp);
5646 		nfs_writeback_update_inode(hdr);
5647 	}
5648 	return 0;
5649 }
5650 
5651 static bool nfs4_write_stateid_changed(struct rpc_task *task,
5652 		struct nfs_pgio_args *args)
5653 {
5654 
5655 	if (!nfs4_error_stateid_expired(task->tk_status) ||
5656 		nfs4_stateid_is_current(&args->stateid,
5657 				args->context,
5658 				args->lock_context,
5659 				FMODE_WRITE))
5660 		return false;
5661 	rpc_restart_call_prepare(task);
5662 	return true;
5663 }
5664 
5665 static int nfs4_write_done(struct rpc_task *task, struct nfs_pgio_header *hdr)
5666 {
5667 	if (!nfs4_sequence_done(task, &hdr->res.seq_res))
5668 		return -EAGAIN;
5669 	if (nfs4_write_stateid_changed(task, &hdr->args))
5670 		return -EAGAIN;
5671 	return hdr->pgio_done_cb ? hdr->pgio_done_cb(task, hdr) :
5672 		nfs4_write_done_cb(task, hdr);
5673 }
5674 
5675 static
5676 bool nfs4_write_need_cache_consistency_data(struct nfs_pgio_header *hdr)
5677 {
5678 	/* Don't request attributes for pNFS or O_DIRECT writes */
5679 	if (hdr->ds_clp != NULL || hdr->dreq != NULL)
5680 		return false;
5681 	/* Otherwise, request attributes if and only if we don't hold
5682 	 * a delegation
5683 	 */
5684 	return nfs4_have_delegation(hdr->inode, FMODE_READ, 0) == 0;
5685 }
5686 
5687 void nfs4_bitmask_set(__u32 bitmask[], const __u32 src[],
5688 		      struct inode *inode, unsigned long cache_validity)
5689 {
5690 	struct nfs_server *server = NFS_SERVER(inode);
5691 	unsigned int i;
5692 
5693 	memcpy(bitmask, src, sizeof(*bitmask) * NFS4_BITMASK_SZ);
5694 	cache_validity |= READ_ONCE(NFS_I(inode)->cache_validity);
5695 
5696 	if (cache_validity & NFS_INO_INVALID_CHANGE)
5697 		bitmask[0] |= FATTR4_WORD0_CHANGE;
5698 	if (cache_validity & NFS_INO_INVALID_ATIME)
5699 		bitmask[1] |= FATTR4_WORD1_TIME_ACCESS;
5700 	if (cache_validity & NFS_INO_INVALID_MODE)
5701 		bitmask[1] |= FATTR4_WORD1_MODE;
5702 	if (cache_validity & NFS_INO_INVALID_OTHER)
5703 		bitmask[1] |= FATTR4_WORD1_OWNER | FATTR4_WORD1_OWNER_GROUP;
5704 	if (cache_validity & NFS_INO_INVALID_NLINK)
5705 		bitmask[1] |= FATTR4_WORD1_NUMLINKS;
5706 	if (cache_validity & NFS_INO_INVALID_CTIME)
5707 		bitmask[1] |= FATTR4_WORD1_TIME_METADATA;
5708 	if (cache_validity & NFS_INO_INVALID_MTIME)
5709 		bitmask[1] |= FATTR4_WORD1_TIME_MODIFY;
5710 	if (cache_validity & NFS_INO_INVALID_BLOCKS)
5711 		bitmask[1] |= FATTR4_WORD1_SPACE_USED;
5712 
5713 	if (cache_validity & NFS_INO_INVALID_SIZE)
5714 		bitmask[0] |= FATTR4_WORD0_SIZE;
5715 
5716 	for (i = 0; i < NFS4_BITMASK_SZ; i++)
5717 		bitmask[i] &= server->attr_bitmask[i];
5718 }
5719 
5720 static void nfs4_proc_write_setup(struct nfs_pgio_header *hdr,
5721 				  struct rpc_message *msg,
5722 				  struct rpc_clnt **clnt)
5723 {
5724 	struct nfs_server *server = NFS_SERVER(hdr->inode);
5725 
5726 	if (!nfs4_write_need_cache_consistency_data(hdr)) {
5727 		hdr->args.bitmask = NULL;
5728 		hdr->res.fattr = NULL;
5729 	} else {
5730 		nfs4_bitmask_set(hdr->args.bitmask_store,
5731 				 server->cache_consistency_bitmask,
5732 				 hdr->inode, NFS_INO_INVALID_BLOCKS);
5733 		hdr->args.bitmask = hdr->args.bitmask_store;
5734 	}
5735 
5736 	if (!hdr->pgio_done_cb)
5737 		hdr->pgio_done_cb = nfs4_write_done_cb;
5738 	hdr->res.server = server;
5739 	hdr->timestamp   = jiffies;
5740 
5741 	msg->rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_WRITE];
5742 	nfs4_init_sequence(&hdr->args.seq_args, &hdr->res.seq_res, 0, 0);
5743 	nfs4_state_protect_write(hdr->ds_clp ? hdr->ds_clp : server->nfs_client, clnt, msg, hdr);
5744 }
5745 
5746 static void nfs4_proc_commit_rpc_prepare(struct rpc_task *task, struct nfs_commit_data *data)
5747 {
5748 	nfs4_setup_sequence(NFS_SERVER(data->inode)->nfs_client,
5749 			&data->args.seq_args,
5750 			&data->res.seq_res,
5751 			task);
5752 }
5753 
5754 static int nfs4_commit_done_cb(struct rpc_task *task, struct nfs_commit_data *data)
5755 {
5756 	struct inode *inode = data->inode;
5757 
5758 	trace_nfs4_commit(data, task->tk_status);
5759 	if (nfs4_async_handle_error(task, NFS_SERVER(inode),
5760 				    NULL, NULL) == -EAGAIN) {
5761 		rpc_restart_call_prepare(task);
5762 		return -EAGAIN;
5763 	}
5764 	return 0;
5765 }
5766 
5767 static int nfs4_commit_done(struct rpc_task *task, struct nfs_commit_data *data)
5768 {
5769 	if (!nfs4_sequence_done(task, &data->res.seq_res))
5770 		return -EAGAIN;
5771 	return data->commit_done_cb(task, data);
5772 }
5773 
5774 static void nfs4_proc_commit_setup(struct nfs_commit_data *data, struct rpc_message *msg,
5775 				   struct rpc_clnt **clnt)
5776 {
5777 	struct nfs_server *server = NFS_SERVER(data->inode);
5778 
5779 	if (data->commit_done_cb == NULL)
5780 		data->commit_done_cb = nfs4_commit_done_cb;
5781 	data->res.server = server;
5782 	msg->rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_COMMIT];
5783 	nfs4_init_sequence(&data->args.seq_args, &data->res.seq_res, 1, 0);
5784 	nfs4_state_protect(data->ds_clp ? data->ds_clp : server->nfs_client,
5785 			NFS_SP4_MACH_CRED_COMMIT, clnt, msg);
5786 }
5787 
5788 static int _nfs4_proc_commit(struct file *dst, struct nfs_commitargs *args,
5789 				struct nfs_commitres *res)
5790 {
5791 	struct inode *dst_inode = file_inode(dst);
5792 	struct nfs_server *server = NFS_SERVER(dst_inode);
5793 	struct rpc_message msg = {
5794 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_COMMIT],
5795 		.rpc_argp = args,
5796 		.rpc_resp = res,
5797 	};
5798 
5799 	args->fh = NFS_FH(dst_inode);
5800 	return nfs4_call_sync(server->client, server, &msg,
5801 			&args->seq_args, &res->seq_res, 1);
5802 }
5803 
5804 int nfs4_proc_commit(struct file *dst, __u64 offset, __u32 count, struct nfs_commitres *res)
5805 {
5806 	struct nfs_commitargs args = {
5807 		.offset = offset,
5808 		.count = count,
5809 	};
5810 	struct nfs_server *dst_server = NFS_SERVER(file_inode(dst));
5811 	struct nfs4_exception exception = { };
5812 	int status;
5813 
5814 	do {
5815 		status = _nfs4_proc_commit(dst, &args, res);
5816 		status = nfs4_handle_exception(dst_server, status, &exception);
5817 	} while (exception.retry);
5818 
5819 	return status;
5820 }
5821 
5822 struct nfs4_renewdata {
5823 	struct nfs_client	*client;
5824 	unsigned long		timestamp;
5825 };
5826 
5827 /*
5828  * nfs4_proc_async_renew(): This is not one of the nfs_rpc_ops; it is a special
5829  * standalone procedure for queueing an asynchronous RENEW.
5830  */
5831 static void nfs4_renew_release(void *calldata)
5832 {
5833 	struct nfs4_renewdata *data = calldata;
5834 	struct nfs_client *clp = data->client;
5835 
5836 	if (refcount_read(&clp->cl_count) > 1)
5837 		nfs4_schedule_state_renewal(clp);
5838 	nfs_put_client(clp);
5839 	kfree(data);
5840 }
5841 
5842 static void nfs4_renew_done(struct rpc_task *task, void *calldata)
5843 {
5844 	struct nfs4_renewdata *data = calldata;
5845 	struct nfs_client *clp = data->client;
5846 	unsigned long timestamp = data->timestamp;
5847 
5848 	trace_nfs4_renew_async(clp, task->tk_status);
5849 	switch (task->tk_status) {
5850 	case 0:
5851 		break;
5852 	case -NFS4ERR_LEASE_MOVED:
5853 		nfs4_schedule_lease_moved_recovery(clp);
5854 		break;
5855 	default:
5856 		/* Unless we're shutting down, schedule state recovery! */
5857 		if (test_bit(NFS_CS_RENEWD, &clp->cl_res_state) == 0)
5858 			return;
5859 		if (task->tk_status != NFS4ERR_CB_PATH_DOWN) {
5860 			nfs4_schedule_lease_recovery(clp);
5861 			return;
5862 		}
5863 		nfs4_schedule_path_down_recovery(clp);
5864 	}
5865 	do_renew_lease(clp, timestamp);
5866 }
5867 
5868 static const struct rpc_call_ops nfs4_renew_ops = {
5869 	.rpc_call_done = nfs4_renew_done,
5870 	.rpc_release = nfs4_renew_release,
5871 };
5872 
5873 static int nfs4_proc_async_renew(struct nfs_client *clp, const struct cred *cred, unsigned renew_flags)
5874 {
5875 	struct rpc_message msg = {
5876 		.rpc_proc	= &nfs4_procedures[NFSPROC4_CLNT_RENEW],
5877 		.rpc_argp	= clp,
5878 		.rpc_cred	= cred,
5879 	};
5880 	struct nfs4_renewdata *data;
5881 
5882 	if (renew_flags == 0)
5883 		return 0;
5884 	if (!refcount_inc_not_zero(&clp->cl_count))
5885 		return -EIO;
5886 	data = kmalloc(sizeof(*data), GFP_NOFS);
5887 	if (data == NULL) {
5888 		nfs_put_client(clp);
5889 		return -ENOMEM;
5890 	}
5891 	data->client = clp;
5892 	data->timestamp = jiffies;
5893 	return rpc_call_async(clp->cl_rpcclient, &msg, RPC_TASK_TIMEOUT,
5894 			&nfs4_renew_ops, data);
5895 }
5896 
5897 static int nfs4_proc_renew(struct nfs_client *clp, const struct cred *cred)
5898 {
5899 	struct rpc_message msg = {
5900 		.rpc_proc	= &nfs4_procedures[NFSPROC4_CLNT_RENEW],
5901 		.rpc_argp	= clp,
5902 		.rpc_cred	= cred,
5903 	};
5904 	unsigned long now = jiffies;
5905 	int status;
5906 
5907 	status = rpc_call_sync(clp->cl_rpcclient, &msg, RPC_TASK_TIMEOUT);
5908 	if (status < 0)
5909 		return status;
5910 	do_renew_lease(clp, now);
5911 	return 0;
5912 }
5913 
5914 static bool nfs4_server_supports_acls(const struct nfs_server *server,
5915 				      enum nfs4_acl_type type)
5916 {
5917 	switch (type) {
5918 	default:
5919 		return server->attr_bitmask[0] & FATTR4_WORD0_ACL;
5920 	case NFS4ACL_DACL:
5921 		return server->attr_bitmask[1] & FATTR4_WORD1_DACL;
5922 	case NFS4ACL_SACL:
5923 		return server->attr_bitmask[1] & FATTR4_WORD1_SACL;
5924 	}
5925 }
5926 
5927 /* Assuming that XATTR_SIZE_MAX is a multiple of PAGE_SIZE, and that
5928  * it's OK to put sizeof(void) * (XATTR_SIZE_MAX/PAGE_SIZE) bytes on
5929  * the stack.
5930  */
5931 #define NFS4ACL_MAXPAGES DIV_ROUND_UP(XATTR_SIZE_MAX, PAGE_SIZE)
5932 
5933 int nfs4_buf_to_pages_noslab(const void *buf, size_t buflen,
5934 		struct page **pages)
5935 {
5936 	struct page *newpage, **spages;
5937 	int rc = 0;
5938 	size_t len;
5939 	spages = pages;
5940 
5941 	do {
5942 		len = min_t(size_t, PAGE_SIZE, buflen);
5943 		newpage = alloc_page(GFP_KERNEL);
5944 
5945 		if (newpage == NULL)
5946 			goto unwind;
5947 		memcpy(page_address(newpage), buf, len);
5948 		buf += len;
5949 		buflen -= len;
5950 		*pages++ = newpage;
5951 		rc++;
5952 	} while (buflen != 0);
5953 
5954 	return rc;
5955 
5956 unwind:
5957 	for(; rc > 0; rc--)
5958 		__free_page(spages[rc-1]);
5959 	return -ENOMEM;
5960 }
5961 
5962 struct nfs4_cached_acl {
5963 	enum nfs4_acl_type type;
5964 	int cached;
5965 	size_t len;
5966 	char data[];
5967 };
5968 
5969 static void nfs4_set_cached_acl(struct inode *inode, struct nfs4_cached_acl *acl)
5970 {
5971 	struct nfs_inode *nfsi = NFS_I(inode);
5972 
5973 	spin_lock(&inode->i_lock);
5974 	kfree(nfsi->nfs4_acl);
5975 	nfsi->nfs4_acl = acl;
5976 	spin_unlock(&inode->i_lock);
5977 }
5978 
5979 static void nfs4_zap_acl_attr(struct inode *inode)
5980 {
5981 	nfs4_set_cached_acl(inode, NULL);
5982 }
5983 
5984 static ssize_t nfs4_read_cached_acl(struct inode *inode, char *buf,
5985 				    size_t buflen, enum nfs4_acl_type type)
5986 {
5987 	struct nfs_inode *nfsi = NFS_I(inode);
5988 	struct nfs4_cached_acl *acl;
5989 	int ret = -ENOENT;
5990 
5991 	spin_lock(&inode->i_lock);
5992 	acl = nfsi->nfs4_acl;
5993 	if (acl == NULL)
5994 		goto out;
5995 	if (acl->type != type)
5996 		goto out;
5997 	if (buf == NULL) /* user is just asking for length */
5998 		goto out_len;
5999 	if (acl->cached == 0)
6000 		goto out;
6001 	ret = -ERANGE; /* see getxattr(2) man page */
6002 	if (acl->len > buflen)
6003 		goto out;
6004 	memcpy(buf, acl->data, acl->len);
6005 out_len:
6006 	ret = acl->len;
6007 out:
6008 	spin_unlock(&inode->i_lock);
6009 	return ret;
6010 }
6011 
6012 static void nfs4_write_cached_acl(struct inode *inode, struct page **pages,
6013 				  size_t pgbase, size_t acl_len,
6014 				  enum nfs4_acl_type type)
6015 {
6016 	struct nfs4_cached_acl *acl;
6017 	size_t buflen = sizeof(*acl) + acl_len;
6018 
6019 	if (buflen <= PAGE_SIZE) {
6020 		acl = kmalloc(buflen, GFP_KERNEL);
6021 		if (acl == NULL)
6022 			goto out;
6023 		acl->cached = 1;
6024 		_copy_from_pages(acl->data, pages, pgbase, acl_len);
6025 	} else {
6026 		acl = kmalloc(sizeof(*acl), GFP_KERNEL);
6027 		if (acl == NULL)
6028 			goto out;
6029 		acl->cached = 0;
6030 	}
6031 	acl->type = type;
6032 	acl->len = acl_len;
6033 out:
6034 	nfs4_set_cached_acl(inode, acl);
6035 }
6036 
6037 /*
6038  * The getxattr API returns the required buffer length when called with a
6039  * NULL buf. The NFSv4 acl tool then calls getxattr again after allocating
6040  * the required buf.  On a NULL buf, we send a page of data to the server
6041  * guessing that the ACL request can be serviced by a page. If so, we cache
6042  * up to the page of ACL data, and the 2nd call to getxattr is serviced by
6043  * the cache. If not so, we throw away the page, and cache the required
6044  * length. The next getxattr call will then produce another round trip to
6045  * the server, this time with the input buf of the required size.
6046  */
6047 static ssize_t __nfs4_get_acl_uncached(struct inode *inode, void *buf,
6048 				       size_t buflen, enum nfs4_acl_type type)
6049 {
6050 	struct page **pages;
6051 	struct nfs_getaclargs args = {
6052 		.fh = NFS_FH(inode),
6053 		.acl_type = type,
6054 		.acl_len = buflen,
6055 	};
6056 	struct nfs_getaclres res = {
6057 		.acl_type = type,
6058 		.acl_len = buflen,
6059 	};
6060 	struct rpc_message msg = {
6061 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETACL],
6062 		.rpc_argp = &args,
6063 		.rpc_resp = &res,
6064 	};
6065 	unsigned int npages;
6066 	int ret = -ENOMEM, i;
6067 	struct nfs_server *server = NFS_SERVER(inode);
6068 
6069 	if (buflen == 0)
6070 		buflen = server->rsize;
6071 
6072 	npages = DIV_ROUND_UP(buflen, PAGE_SIZE) + 1;
6073 	pages = kmalloc_array(npages, sizeof(struct page *), GFP_KERNEL);
6074 	if (!pages)
6075 		return -ENOMEM;
6076 
6077 	args.acl_pages = pages;
6078 
6079 	for (i = 0; i < npages; i++) {
6080 		pages[i] = alloc_page(GFP_KERNEL);
6081 		if (!pages[i])
6082 			goto out_free;
6083 	}
6084 
6085 	/* for decoding across pages */
6086 	res.acl_scratch = alloc_page(GFP_KERNEL);
6087 	if (!res.acl_scratch)
6088 		goto out_free;
6089 
6090 	args.acl_len = npages * PAGE_SIZE;
6091 
6092 	dprintk("%s  buf %p buflen %zu npages %d args.acl_len %zu\n",
6093 		__func__, buf, buflen, npages, args.acl_len);
6094 	ret = nfs4_call_sync(NFS_SERVER(inode)->client, NFS_SERVER(inode),
6095 			     &msg, &args.seq_args, &res.seq_res, 0);
6096 	if (ret)
6097 		goto out_free;
6098 
6099 	/* Handle the case where the passed-in buffer is too short */
6100 	if (res.acl_flags & NFS4_ACL_TRUNC) {
6101 		/* Did the user only issue a request for the acl length? */
6102 		if (buf == NULL)
6103 			goto out_ok;
6104 		ret = -ERANGE;
6105 		goto out_free;
6106 	}
6107 	nfs4_write_cached_acl(inode, pages, res.acl_data_offset, res.acl_len,
6108 			      type);
6109 	if (buf) {
6110 		if (res.acl_len > buflen) {
6111 			ret = -ERANGE;
6112 			goto out_free;
6113 		}
6114 		_copy_from_pages(buf, pages, res.acl_data_offset, res.acl_len);
6115 	}
6116 out_ok:
6117 	ret = res.acl_len;
6118 out_free:
6119 	while (--i >= 0)
6120 		__free_page(pages[i]);
6121 	if (res.acl_scratch)
6122 		__free_page(res.acl_scratch);
6123 	kfree(pages);
6124 	return ret;
6125 }
6126 
6127 static ssize_t nfs4_get_acl_uncached(struct inode *inode, void *buf,
6128 				     size_t buflen, enum nfs4_acl_type type)
6129 {
6130 	struct nfs4_exception exception = {
6131 		.interruptible = true,
6132 	};
6133 	ssize_t ret;
6134 	do {
6135 		ret = __nfs4_get_acl_uncached(inode, buf, buflen, type);
6136 		trace_nfs4_get_acl(inode, ret);
6137 		if (ret >= 0)
6138 			break;
6139 		ret = nfs4_handle_exception(NFS_SERVER(inode), ret, &exception);
6140 	} while (exception.retry);
6141 	return ret;
6142 }
6143 
6144 static ssize_t nfs4_proc_get_acl(struct inode *inode, void *buf, size_t buflen,
6145 				 enum nfs4_acl_type type)
6146 {
6147 	struct nfs_server *server = NFS_SERVER(inode);
6148 	int ret;
6149 
6150 	if (!nfs4_server_supports_acls(server, type))
6151 		return -EOPNOTSUPP;
6152 	ret = nfs_revalidate_inode(inode, NFS_INO_INVALID_CHANGE);
6153 	if (ret < 0)
6154 		return ret;
6155 	if (NFS_I(inode)->cache_validity & NFS_INO_INVALID_ACL)
6156 		nfs_zap_acl_cache(inode);
6157 	ret = nfs4_read_cached_acl(inode, buf, buflen, type);
6158 	if (ret != -ENOENT)
6159 		/* -ENOENT is returned if there is no ACL or if there is an ACL
6160 		 * but no cached acl data, just the acl length */
6161 		return ret;
6162 	return nfs4_get_acl_uncached(inode, buf, buflen, type);
6163 }
6164 
6165 static int __nfs4_proc_set_acl(struct inode *inode, const void *buf,
6166 			       size_t buflen, enum nfs4_acl_type type)
6167 {
6168 	struct nfs_server *server = NFS_SERVER(inode);
6169 	struct page *pages[NFS4ACL_MAXPAGES];
6170 	struct nfs_setaclargs arg = {
6171 		.fh = NFS_FH(inode),
6172 		.acl_type = type,
6173 		.acl_len = buflen,
6174 		.acl_pages = pages,
6175 	};
6176 	struct nfs_setaclres res;
6177 	struct rpc_message msg = {
6178 		.rpc_proc	= &nfs4_procedures[NFSPROC4_CLNT_SETACL],
6179 		.rpc_argp	= &arg,
6180 		.rpc_resp	= &res,
6181 	};
6182 	unsigned int npages = DIV_ROUND_UP(buflen, PAGE_SIZE);
6183 	int ret, i;
6184 
6185 	/* You can't remove system.nfs4_acl: */
6186 	if (buflen == 0)
6187 		return -EINVAL;
6188 	if (!nfs4_server_supports_acls(server, type))
6189 		return -EOPNOTSUPP;
6190 	if (npages > ARRAY_SIZE(pages))
6191 		return -ERANGE;
6192 	i = nfs4_buf_to_pages_noslab(buf, buflen, arg.acl_pages);
6193 	if (i < 0)
6194 		return i;
6195 	nfs4_inode_make_writeable(inode);
6196 	ret = nfs4_call_sync(server->client, server, &msg, &arg.seq_args, &res.seq_res, 1);
6197 
6198 	/*
6199 	 * Free each page after tx, so the only ref left is
6200 	 * held by the network stack
6201 	 */
6202 	for (; i > 0; i--)
6203 		put_page(pages[i-1]);
6204 
6205 	/*
6206 	 * Acl update can result in inode attribute update.
6207 	 * so mark the attribute cache invalid.
6208 	 */
6209 	spin_lock(&inode->i_lock);
6210 	nfs_set_cache_invalid(inode, NFS_INO_INVALID_CHANGE |
6211 					     NFS_INO_INVALID_CTIME |
6212 					     NFS_INO_REVAL_FORCED);
6213 	spin_unlock(&inode->i_lock);
6214 	nfs_access_zap_cache(inode);
6215 	nfs_zap_acl_cache(inode);
6216 	return ret;
6217 }
6218 
6219 static int nfs4_proc_set_acl(struct inode *inode, const void *buf,
6220 			     size_t buflen, enum nfs4_acl_type type)
6221 {
6222 	struct nfs4_exception exception = { };
6223 	int err;
6224 	do {
6225 		err = __nfs4_proc_set_acl(inode, buf, buflen, type);
6226 		trace_nfs4_set_acl(inode, err);
6227 		if (err == -NFS4ERR_BADOWNER || err == -NFS4ERR_BADNAME) {
6228 			/*
6229 			 * no need to retry since the kernel
6230 			 * isn't involved in encoding the ACEs.
6231 			 */
6232 			err = -EINVAL;
6233 			break;
6234 		}
6235 		err = nfs4_handle_exception(NFS_SERVER(inode), err,
6236 				&exception);
6237 	} while (exception.retry);
6238 	return err;
6239 }
6240 
6241 #ifdef CONFIG_NFS_V4_SECURITY_LABEL
6242 static int _nfs4_get_security_label(struct inode *inode, void *buf,
6243 					size_t buflen)
6244 {
6245 	struct nfs_server *server = NFS_SERVER(inode);
6246 	struct nfs4_label label = {0, 0, buflen, buf};
6247 
6248 	u32 bitmask[3] = { 0, 0, FATTR4_WORD2_SECURITY_LABEL };
6249 	struct nfs_fattr fattr = {
6250 		.label = &label,
6251 	};
6252 	struct nfs4_getattr_arg arg = {
6253 		.fh		= NFS_FH(inode),
6254 		.bitmask	= bitmask,
6255 	};
6256 	struct nfs4_getattr_res res = {
6257 		.fattr		= &fattr,
6258 		.server		= server,
6259 	};
6260 	struct rpc_message msg = {
6261 		.rpc_proc	= &nfs4_procedures[NFSPROC4_CLNT_GETATTR],
6262 		.rpc_argp	= &arg,
6263 		.rpc_resp	= &res,
6264 	};
6265 	int ret;
6266 
6267 	nfs_fattr_init(&fattr);
6268 
6269 	ret = nfs4_call_sync(server->client, server, &msg, &arg.seq_args, &res.seq_res, 0);
6270 	if (ret)
6271 		return ret;
6272 	if (!(fattr.valid & NFS_ATTR_FATTR_V4_SECURITY_LABEL))
6273 		return -ENOENT;
6274 	return label.len;
6275 }
6276 
6277 static int nfs4_get_security_label(struct inode *inode, void *buf,
6278 					size_t buflen)
6279 {
6280 	struct nfs4_exception exception = {
6281 		.interruptible = true,
6282 	};
6283 	int err;
6284 
6285 	if (!nfs_server_capable(inode, NFS_CAP_SECURITY_LABEL))
6286 		return -EOPNOTSUPP;
6287 
6288 	do {
6289 		err = _nfs4_get_security_label(inode, buf, buflen);
6290 		trace_nfs4_get_security_label(inode, err);
6291 		err = nfs4_handle_exception(NFS_SERVER(inode), err,
6292 				&exception);
6293 	} while (exception.retry);
6294 	return err;
6295 }
6296 
6297 static int _nfs4_do_set_security_label(struct inode *inode,
6298 		struct nfs4_label *ilabel,
6299 		struct nfs_fattr *fattr)
6300 {
6301 
6302 	struct iattr sattr = {0};
6303 	struct nfs_server *server = NFS_SERVER(inode);
6304 	const u32 bitmask[3] = { 0, 0, FATTR4_WORD2_SECURITY_LABEL };
6305 	struct nfs_setattrargs arg = {
6306 		.fh		= NFS_FH(inode),
6307 		.iap		= &sattr,
6308 		.server		= server,
6309 		.bitmask	= bitmask,
6310 		.label		= ilabel,
6311 	};
6312 	struct nfs_setattrres res = {
6313 		.fattr		= fattr,
6314 		.server		= server,
6315 	};
6316 	struct rpc_message msg = {
6317 		.rpc_proc	= &nfs4_procedures[NFSPROC4_CLNT_SETATTR],
6318 		.rpc_argp	= &arg,
6319 		.rpc_resp	= &res,
6320 	};
6321 	int status;
6322 
6323 	nfs4_stateid_copy(&arg.stateid, &zero_stateid);
6324 
6325 	status = nfs4_call_sync(server->client, server, &msg, &arg.seq_args, &res.seq_res, 1);
6326 	if (status)
6327 		dprintk("%s failed: %d\n", __func__, status);
6328 
6329 	return status;
6330 }
6331 
6332 static int nfs4_do_set_security_label(struct inode *inode,
6333 		struct nfs4_label *ilabel,
6334 		struct nfs_fattr *fattr)
6335 {
6336 	struct nfs4_exception exception = { };
6337 	int err;
6338 
6339 	do {
6340 		err = _nfs4_do_set_security_label(inode, ilabel, fattr);
6341 		trace_nfs4_set_security_label(inode, err);
6342 		err = nfs4_handle_exception(NFS_SERVER(inode), err,
6343 				&exception);
6344 	} while (exception.retry);
6345 	return err;
6346 }
6347 
6348 static int
6349 nfs4_set_security_label(struct inode *inode, const void *buf, size_t buflen)
6350 {
6351 	struct nfs4_label ilabel = {0, 0, buflen, (char *)buf };
6352 	struct nfs_fattr *fattr;
6353 	int status;
6354 
6355 	if (!nfs_server_capable(inode, NFS_CAP_SECURITY_LABEL))
6356 		return -EOPNOTSUPP;
6357 
6358 	fattr = nfs_alloc_fattr_with_label(NFS_SERVER(inode));
6359 	if (fattr == NULL)
6360 		return -ENOMEM;
6361 
6362 	status = nfs4_do_set_security_label(inode, &ilabel, fattr);
6363 	if (status == 0)
6364 		nfs_setsecurity(inode, fattr);
6365 
6366 	nfs_free_fattr(fattr);
6367 	return status;
6368 }
6369 #endif	/* CONFIG_NFS_V4_SECURITY_LABEL */
6370 
6371 
6372 static void nfs4_init_boot_verifier(const struct nfs_client *clp,
6373 				    nfs4_verifier *bootverf)
6374 {
6375 	__be32 verf[2];
6376 
6377 	if (test_bit(NFS4CLNT_PURGE_STATE, &clp->cl_state)) {
6378 		/* An impossible timestamp guarantees this value
6379 		 * will never match a generated boot time. */
6380 		verf[0] = cpu_to_be32(U32_MAX);
6381 		verf[1] = cpu_to_be32(U32_MAX);
6382 	} else {
6383 		struct nfs_net *nn = net_generic(clp->cl_net, nfs_net_id);
6384 		u64 ns = ktime_to_ns(nn->boot_time);
6385 
6386 		verf[0] = cpu_to_be32(ns >> 32);
6387 		verf[1] = cpu_to_be32(ns);
6388 	}
6389 	memcpy(bootverf->data, verf, sizeof(bootverf->data));
6390 }
6391 
6392 static size_t
6393 nfs4_get_uniquifier(struct nfs_client *clp, char *buf, size_t buflen)
6394 {
6395 	struct nfs_net *nn = net_generic(clp->cl_net, nfs_net_id);
6396 	struct nfs_netns_client *nn_clp = nn->nfs_client;
6397 	const char *id;
6398 
6399 	buf[0] = '\0';
6400 
6401 	if (nn_clp) {
6402 		rcu_read_lock();
6403 		id = rcu_dereference(nn_clp->identifier);
6404 		if (id)
6405 			strscpy(buf, id, buflen);
6406 		rcu_read_unlock();
6407 	}
6408 
6409 	if (nfs4_client_id_uniquifier[0] != '\0' && buf[0] == '\0')
6410 		strscpy(buf, nfs4_client_id_uniquifier, buflen);
6411 
6412 	return strlen(buf);
6413 }
6414 
6415 static int
6416 nfs4_init_nonuniform_client_string(struct nfs_client *clp)
6417 {
6418 	char buf[NFS4_CLIENT_ID_UNIQ_LEN];
6419 	size_t buflen;
6420 	size_t len;
6421 	char *str;
6422 
6423 	if (clp->cl_owner_id != NULL)
6424 		return 0;
6425 
6426 	rcu_read_lock();
6427 	len = 14 +
6428 		strlen(clp->cl_rpcclient->cl_nodename) +
6429 		1 +
6430 		strlen(rpc_peeraddr2str(clp->cl_rpcclient, RPC_DISPLAY_ADDR)) +
6431 		1;
6432 	rcu_read_unlock();
6433 
6434 	buflen = nfs4_get_uniquifier(clp, buf, sizeof(buf));
6435 	if (buflen)
6436 		len += buflen + 1;
6437 
6438 	if (len > NFS4_OPAQUE_LIMIT + 1)
6439 		return -EINVAL;
6440 
6441 	/*
6442 	 * Since this string is allocated at mount time, and held until the
6443 	 * nfs_client is destroyed, we can use GFP_KERNEL here w/o worrying
6444 	 * about a memory-reclaim deadlock.
6445 	 */
6446 	str = kmalloc(len, GFP_KERNEL);
6447 	if (!str)
6448 		return -ENOMEM;
6449 
6450 	rcu_read_lock();
6451 	if (buflen)
6452 		scnprintf(str, len, "Linux NFSv4.0 %s/%s/%s",
6453 			  clp->cl_rpcclient->cl_nodename, buf,
6454 			  rpc_peeraddr2str(clp->cl_rpcclient,
6455 					   RPC_DISPLAY_ADDR));
6456 	else
6457 		scnprintf(str, len, "Linux NFSv4.0 %s/%s",
6458 			  clp->cl_rpcclient->cl_nodename,
6459 			  rpc_peeraddr2str(clp->cl_rpcclient,
6460 					   RPC_DISPLAY_ADDR));
6461 	rcu_read_unlock();
6462 
6463 	clp->cl_owner_id = str;
6464 	return 0;
6465 }
6466 
6467 static int
6468 nfs4_init_uniform_client_string(struct nfs_client *clp)
6469 {
6470 	char buf[NFS4_CLIENT_ID_UNIQ_LEN];
6471 	size_t buflen;
6472 	size_t len;
6473 	char *str;
6474 
6475 	if (clp->cl_owner_id != NULL)
6476 		return 0;
6477 
6478 	len = 10 + 10 + 1 + 10 + 1 +
6479 		strlen(clp->cl_rpcclient->cl_nodename) + 1;
6480 
6481 	buflen = nfs4_get_uniquifier(clp, buf, sizeof(buf));
6482 	if (buflen)
6483 		len += buflen + 1;
6484 
6485 	if (len > NFS4_OPAQUE_LIMIT + 1)
6486 		return -EINVAL;
6487 
6488 	/*
6489 	 * Since this string is allocated at mount time, and held until the
6490 	 * nfs_client is destroyed, we can use GFP_KERNEL here w/o worrying
6491 	 * about a memory-reclaim deadlock.
6492 	 */
6493 	str = kmalloc(len, GFP_KERNEL);
6494 	if (!str)
6495 		return -ENOMEM;
6496 
6497 	if (buflen)
6498 		scnprintf(str, len, "Linux NFSv%u.%u %s/%s",
6499 			  clp->rpc_ops->version, clp->cl_minorversion,
6500 			  buf, clp->cl_rpcclient->cl_nodename);
6501 	else
6502 		scnprintf(str, len, "Linux NFSv%u.%u %s",
6503 			  clp->rpc_ops->version, clp->cl_minorversion,
6504 			  clp->cl_rpcclient->cl_nodename);
6505 	clp->cl_owner_id = str;
6506 	return 0;
6507 }
6508 
6509 /*
6510  * nfs4_callback_up_net() starts only "tcp" and "tcp6" callback
6511  * services.  Advertise one based on the address family of the
6512  * clientaddr.
6513  */
6514 static unsigned int
6515 nfs4_init_callback_netid(const struct nfs_client *clp, char *buf, size_t len)
6516 {
6517 	if (strchr(clp->cl_ipaddr, ':') != NULL)
6518 		return scnprintf(buf, len, "tcp6");
6519 	else
6520 		return scnprintf(buf, len, "tcp");
6521 }
6522 
6523 static void nfs4_setclientid_done(struct rpc_task *task, void *calldata)
6524 {
6525 	struct nfs4_setclientid *sc = calldata;
6526 
6527 	if (task->tk_status == 0)
6528 		sc->sc_cred = get_rpccred(task->tk_rqstp->rq_cred);
6529 }
6530 
6531 static const struct rpc_call_ops nfs4_setclientid_ops = {
6532 	.rpc_call_done = nfs4_setclientid_done,
6533 };
6534 
6535 /**
6536  * nfs4_proc_setclientid - Negotiate client ID
6537  * @clp: state data structure
6538  * @program: RPC program for NFSv4 callback service
6539  * @port: IP port number for NFS4 callback service
6540  * @cred: credential to use for this call
6541  * @res: where to place the result
6542  *
6543  * Returns zero, a negative errno, or a negative NFS4ERR status code.
6544  */
6545 int nfs4_proc_setclientid(struct nfs_client *clp, u32 program,
6546 		unsigned short port, const struct cred *cred,
6547 		struct nfs4_setclientid_res *res)
6548 {
6549 	nfs4_verifier sc_verifier;
6550 	struct nfs4_setclientid setclientid = {
6551 		.sc_verifier = &sc_verifier,
6552 		.sc_prog = program,
6553 		.sc_clnt = clp,
6554 	};
6555 	struct rpc_message msg = {
6556 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_SETCLIENTID],
6557 		.rpc_argp = &setclientid,
6558 		.rpc_resp = res,
6559 		.rpc_cred = cred,
6560 	};
6561 	struct rpc_task_setup task_setup_data = {
6562 		.rpc_client = clp->cl_rpcclient,
6563 		.rpc_message = &msg,
6564 		.callback_ops = &nfs4_setclientid_ops,
6565 		.callback_data = &setclientid,
6566 		.flags = RPC_TASK_TIMEOUT | RPC_TASK_NO_ROUND_ROBIN,
6567 	};
6568 	unsigned long now = jiffies;
6569 	int status;
6570 
6571 	/* nfs_client_id4 */
6572 	nfs4_init_boot_verifier(clp, &sc_verifier);
6573 
6574 	if (test_bit(NFS_CS_MIGRATION, &clp->cl_flags))
6575 		status = nfs4_init_uniform_client_string(clp);
6576 	else
6577 		status = nfs4_init_nonuniform_client_string(clp);
6578 
6579 	if (status)
6580 		goto out;
6581 
6582 	/* cb_client4 */
6583 	setclientid.sc_netid_len =
6584 				nfs4_init_callback_netid(clp,
6585 						setclientid.sc_netid,
6586 						sizeof(setclientid.sc_netid));
6587 	setclientid.sc_uaddr_len = scnprintf(setclientid.sc_uaddr,
6588 				sizeof(setclientid.sc_uaddr), "%s.%u.%u",
6589 				clp->cl_ipaddr, port >> 8, port & 255);
6590 
6591 	dprintk("NFS call  setclientid auth=%s, '%s'\n",
6592 		clp->cl_rpcclient->cl_auth->au_ops->au_name,
6593 		clp->cl_owner_id);
6594 
6595 	status = nfs4_call_sync_custom(&task_setup_data);
6596 	if (setclientid.sc_cred) {
6597 		kfree(clp->cl_acceptor);
6598 		clp->cl_acceptor = rpcauth_stringify_acceptor(setclientid.sc_cred);
6599 		put_rpccred(setclientid.sc_cred);
6600 	}
6601 
6602 	if (status == 0)
6603 		do_renew_lease(clp, now);
6604 out:
6605 	trace_nfs4_setclientid(clp, status);
6606 	dprintk("NFS reply setclientid: %d\n", status);
6607 	return status;
6608 }
6609 
6610 /**
6611  * nfs4_proc_setclientid_confirm - Confirm client ID
6612  * @clp: state data structure
6613  * @arg: result of a previous SETCLIENTID
6614  * @cred: credential to use for this call
6615  *
6616  * Returns zero, a negative errno, or a negative NFS4ERR status code.
6617  */
6618 int nfs4_proc_setclientid_confirm(struct nfs_client *clp,
6619 		struct nfs4_setclientid_res *arg,
6620 		const struct cred *cred)
6621 {
6622 	struct rpc_message msg = {
6623 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_SETCLIENTID_CONFIRM],
6624 		.rpc_argp = arg,
6625 		.rpc_cred = cred,
6626 	};
6627 	int status;
6628 
6629 	dprintk("NFS call  setclientid_confirm auth=%s, (client ID %llx)\n",
6630 		clp->cl_rpcclient->cl_auth->au_ops->au_name,
6631 		clp->cl_clientid);
6632 	status = rpc_call_sync(clp->cl_rpcclient, &msg,
6633 			       RPC_TASK_TIMEOUT | RPC_TASK_NO_ROUND_ROBIN);
6634 	trace_nfs4_setclientid_confirm(clp, status);
6635 	dprintk("NFS reply setclientid_confirm: %d\n", status);
6636 	return status;
6637 }
6638 
6639 struct nfs4_delegreturndata {
6640 	struct nfs4_delegreturnargs args;
6641 	struct nfs4_delegreturnres res;
6642 	struct nfs_fh fh;
6643 	nfs4_stateid stateid;
6644 	unsigned long timestamp;
6645 	struct {
6646 		struct nfs4_layoutreturn_args arg;
6647 		struct nfs4_layoutreturn_res res;
6648 		struct nfs4_xdr_opaque_data ld_private;
6649 		u32 roc_barrier;
6650 		bool roc;
6651 	} lr;
6652 	struct nfs4_delegattr sattr;
6653 	struct nfs_fattr fattr;
6654 	int rpc_status;
6655 	struct inode *inode;
6656 };
6657 
6658 static void nfs4_delegreturn_done(struct rpc_task *task, void *calldata)
6659 {
6660 	struct nfs4_delegreturndata *data = calldata;
6661 	struct nfs4_exception exception = {
6662 		.inode = data->inode,
6663 		.stateid = &data->stateid,
6664 		.task_is_privileged = data->args.seq_args.sa_privileged,
6665 	};
6666 
6667 	if (!nfs4_sequence_done(task, &data->res.seq_res))
6668 		return;
6669 
6670 	trace_nfs4_delegreturn_exit(&data->args, &data->res, task->tk_status);
6671 
6672 	/* Handle Layoutreturn errors */
6673 	if (pnfs_roc_done(task, &data->args.lr_args, &data->res.lr_res,
6674 			  &data->res.lr_ret) == -EAGAIN)
6675 		goto out_restart;
6676 
6677 	if (data->args.sattr_args && task->tk_status != 0) {
6678 		switch(data->res.sattr_ret) {
6679 		case 0:
6680 			data->args.sattr_args = NULL;
6681 			data->res.sattr_res = false;
6682 			break;
6683 		case -NFS4ERR_ADMIN_REVOKED:
6684 		case -NFS4ERR_DELEG_REVOKED:
6685 		case -NFS4ERR_EXPIRED:
6686 		case -NFS4ERR_BAD_STATEID:
6687 			/* Let the main handler below do stateid recovery */
6688 			break;
6689 		case -NFS4ERR_OLD_STATEID:
6690 			if (nfs4_refresh_delegation_stateid(&data->stateid,
6691 						data->inode))
6692 				goto out_restart;
6693 			fallthrough;
6694 		default:
6695 			data->args.sattr_args = NULL;
6696 			data->res.sattr_res = false;
6697 			goto out_restart;
6698 		}
6699 	}
6700 
6701 	switch (task->tk_status) {
6702 	case 0:
6703 		renew_lease(data->res.server, data->timestamp);
6704 		break;
6705 	case -NFS4ERR_ADMIN_REVOKED:
6706 	case -NFS4ERR_DELEG_REVOKED:
6707 	case -NFS4ERR_EXPIRED:
6708 		nfs4_free_revoked_stateid(data->res.server,
6709 				data->args.stateid,
6710 				task->tk_msg.rpc_cred);
6711 		fallthrough;
6712 	case -NFS4ERR_BAD_STATEID:
6713 	case -NFS4ERR_STALE_STATEID:
6714 	case -ETIMEDOUT:
6715 		task->tk_status = 0;
6716 		break;
6717 	case -NFS4ERR_OLD_STATEID:
6718 		if (!nfs4_refresh_delegation_stateid(&data->stateid, data->inode))
6719 			nfs4_stateid_seqid_inc(&data->stateid);
6720 		if (data->args.bitmask) {
6721 			data->args.bitmask = NULL;
6722 			data->res.fattr = NULL;
6723 		}
6724 		goto out_restart;
6725 	case -NFS4ERR_ACCESS:
6726 		if (data->args.bitmask) {
6727 			data->args.bitmask = NULL;
6728 			data->res.fattr = NULL;
6729 			goto out_restart;
6730 		}
6731 		fallthrough;
6732 	default:
6733 		task->tk_status = nfs4_async_handle_exception(task,
6734 				data->res.server, task->tk_status,
6735 				&exception);
6736 		if (exception.retry)
6737 			goto out_restart;
6738 	}
6739 	nfs_delegation_mark_returned(data->inode, data->args.stateid);
6740 	data->rpc_status = task->tk_status;
6741 	return;
6742 out_restart:
6743 	task->tk_status = 0;
6744 	rpc_restart_call_prepare(task);
6745 }
6746 
6747 static void nfs4_delegreturn_release(void *calldata)
6748 {
6749 	struct nfs4_delegreturndata *data = calldata;
6750 	struct inode *inode = data->inode;
6751 
6752 	if (data->lr.roc)
6753 		pnfs_roc_release(&data->lr.arg, &data->lr.res,
6754 				 data->res.lr_ret);
6755 	if (inode) {
6756 		nfs4_fattr_set_prechange(&data->fattr,
6757 					 inode_peek_iversion_raw(inode));
6758 		nfs_refresh_inode(inode, &data->fattr);
6759 		nfs_iput_and_deactive(inode);
6760 	}
6761 	kfree(calldata);
6762 }
6763 
6764 static void nfs4_delegreturn_prepare(struct rpc_task *task, void *data)
6765 {
6766 	struct nfs4_delegreturndata *d_data;
6767 	struct pnfs_layout_hdr *lo;
6768 
6769 	d_data = data;
6770 
6771 	if (!d_data->lr.roc && nfs4_wait_on_layoutreturn(d_data->inode, task)) {
6772 		nfs4_sequence_done(task, &d_data->res.seq_res);
6773 		return;
6774 	}
6775 
6776 	lo = d_data->args.lr_args ? d_data->args.lr_args->layout : NULL;
6777 	if (lo && !pnfs_layout_is_valid(lo)) {
6778 		d_data->args.lr_args = NULL;
6779 		d_data->res.lr_res = NULL;
6780 	}
6781 
6782 	nfs4_setup_sequence(d_data->res.server->nfs_client,
6783 			&d_data->args.seq_args,
6784 			&d_data->res.seq_res,
6785 			task);
6786 }
6787 
6788 static const struct rpc_call_ops nfs4_delegreturn_ops = {
6789 	.rpc_call_prepare = nfs4_delegreturn_prepare,
6790 	.rpc_call_done = nfs4_delegreturn_done,
6791 	.rpc_release = nfs4_delegreturn_release,
6792 };
6793 
6794 static int _nfs4_proc_delegreturn(struct inode *inode, const struct cred *cred,
6795 				  const nfs4_stateid *stateid,
6796 				  struct nfs_delegation *delegation,
6797 				  int issync)
6798 {
6799 	struct nfs4_delegreturndata *data;
6800 	struct nfs_server *server = NFS_SERVER(inode);
6801 	struct rpc_task *task;
6802 	struct rpc_message msg = {
6803 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_DELEGRETURN],
6804 		.rpc_cred = cred,
6805 	};
6806 	struct rpc_task_setup task_setup_data = {
6807 		.rpc_client = server->client,
6808 		.rpc_message = &msg,
6809 		.callback_ops = &nfs4_delegreturn_ops,
6810 		.flags = RPC_TASK_ASYNC | RPC_TASK_TIMEOUT,
6811 	};
6812 	int status = 0;
6813 
6814 	if (nfs_server_capable(inode, NFS_CAP_MOVEABLE))
6815 		task_setup_data.flags |= RPC_TASK_MOVEABLE;
6816 
6817 	data = kzalloc(sizeof(*data), GFP_KERNEL);
6818 	if (data == NULL)
6819 		return -ENOMEM;
6820 
6821 	nfs4_state_protect(server->nfs_client,
6822 			NFS_SP4_MACH_CRED_CLEANUP,
6823 			&task_setup_data.rpc_client, &msg);
6824 
6825 	data->args.fhandle = &data->fh;
6826 	data->args.stateid = &data->stateid;
6827 	nfs4_bitmask_set(data->args.bitmask_store,
6828 			 server->cache_consistency_bitmask, inode, 0);
6829 	data->args.bitmask = data->args.bitmask_store;
6830 	nfs_copy_fh(&data->fh, NFS_FH(inode));
6831 	nfs4_stateid_copy(&data->stateid, stateid);
6832 	data->res.fattr = &data->fattr;
6833 	data->res.server = server;
6834 	data->res.lr_ret = -NFS4ERR_NOMATCHING_LAYOUT;
6835 	data->lr.arg.ld_private = &data->lr.ld_private;
6836 	nfs_fattr_init(data->res.fattr);
6837 	data->timestamp = jiffies;
6838 	data->rpc_status = 0;
6839 	data->inode = nfs_igrab_and_active(inode);
6840 	if (data->inode || issync) {
6841 		data->lr.roc = pnfs_roc(inode, &data->lr.arg, &data->lr.res,
6842 					cred);
6843 		if (data->lr.roc) {
6844 			data->args.lr_args = &data->lr.arg;
6845 			data->res.lr_res = &data->lr.res;
6846 		}
6847 	}
6848 
6849 	if (delegation &&
6850 	    test_bit(NFS_DELEGATION_DELEGTIME, &delegation->flags)) {
6851 		if (delegation->type & FMODE_READ) {
6852 			data->sattr.atime = inode_get_atime(inode);
6853 			data->sattr.atime_set = true;
6854 		}
6855 		if (delegation->type & FMODE_WRITE) {
6856 			data->sattr.mtime = inode_get_mtime(inode);
6857 			data->sattr.mtime_set = true;
6858 		}
6859 		data->args.sattr_args = &data->sattr;
6860 		data->res.sattr_res = true;
6861 	}
6862 
6863 	if (!data->inode)
6864 		nfs4_init_sequence(&data->args.seq_args, &data->res.seq_res, 1,
6865 				   1);
6866 	else
6867 		nfs4_init_sequence(&data->args.seq_args, &data->res.seq_res, 1,
6868 				   0);
6869 
6870 	task_setup_data.callback_data = data;
6871 	msg.rpc_argp = &data->args;
6872 	msg.rpc_resp = &data->res;
6873 	task = rpc_run_task(&task_setup_data);
6874 	if (IS_ERR(task))
6875 		return PTR_ERR(task);
6876 	if (!issync)
6877 		goto out;
6878 	status = rpc_wait_for_completion_task(task);
6879 	if (status != 0)
6880 		goto out;
6881 	status = data->rpc_status;
6882 out:
6883 	rpc_put_task(task);
6884 	return status;
6885 }
6886 
6887 int nfs4_proc_delegreturn(struct inode *inode, const struct cred *cred,
6888 			  const nfs4_stateid *stateid,
6889 			  struct nfs_delegation *delegation, int issync)
6890 {
6891 	struct nfs_server *server = NFS_SERVER(inode);
6892 	struct nfs4_exception exception = { };
6893 	int err;
6894 	do {
6895 		err = _nfs4_proc_delegreturn(inode, cred, stateid,
6896 					     delegation, issync);
6897 		trace_nfs4_delegreturn(inode, stateid, err);
6898 		switch (err) {
6899 			case -NFS4ERR_STALE_STATEID:
6900 			case -NFS4ERR_EXPIRED:
6901 			case 0:
6902 				return 0;
6903 		}
6904 		err = nfs4_handle_exception(server, err, &exception);
6905 	} while (exception.retry);
6906 	return err;
6907 }
6908 
6909 static int _nfs4_proc_getlk(struct nfs4_state *state, int cmd, struct file_lock *request)
6910 {
6911 	struct inode *inode = state->inode;
6912 	struct nfs_server *server = NFS_SERVER(inode);
6913 	struct nfs_client *clp = server->nfs_client;
6914 	struct nfs_lockt_args arg = {
6915 		.fh = NFS_FH(inode),
6916 		.fl = request,
6917 	};
6918 	struct nfs_lockt_res res = {
6919 		.denied = request,
6920 	};
6921 	struct rpc_message msg = {
6922 		.rpc_proc	= &nfs4_procedures[NFSPROC4_CLNT_LOCKT],
6923 		.rpc_argp	= &arg,
6924 		.rpc_resp	= &res,
6925 		.rpc_cred	= state->owner->so_cred,
6926 	};
6927 	struct nfs4_lock_state *lsp;
6928 	int status;
6929 
6930 	arg.lock_owner.clientid = clp->cl_clientid;
6931 	status = nfs4_set_lock_state(state, request);
6932 	if (status != 0)
6933 		goto out;
6934 	lsp = request->fl_u.nfs4_fl.owner;
6935 	arg.lock_owner.id = lsp->ls_seqid.owner_id;
6936 	arg.lock_owner.s_dev = server->s_dev;
6937 	status = nfs4_call_sync(server->client, server, &msg, &arg.seq_args, &res.seq_res, 1);
6938 	switch (status) {
6939 		case 0:
6940 			request->c.flc_type = F_UNLCK;
6941 			break;
6942 		case -NFS4ERR_DENIED:
6943 			status = 0;
6944 	}
6945 	request->fl_ops->fl_release_private(request);
6946 	request->fl_ops = NULL;
6947 out:
6948 	return status;
6949 }
6950 
6951 static int nfs4_proc_getlk(struct nfs4_state *state, int cmd, struct file_lock *request)
6952 {
6953 	struct nfs4_exception exception = {
6954 		.interruptible = true,
6955 	};
6956 	int err;
6957 
6958 	do {
6959 		err = _nfs4_proc_getlk(state, cmd, request);
6960 		trace_nfs4_get_lock(request, state, cmd, err);
6961 		err = nfs4_handle_exception(NFS_SERVER(state->inode), err,
6962 				&exception);
6963 	} while (exception.retry);
6964 	return err;
6965 }
6966 
6967 /*
6968  * Update the seqid of a lock stateid after receiving
6969  * NFS4ERR_OLD_STATEID
6970  */
6971 static bool nfs4_refresh_lock_old_stateid(nfs4_stateid *dst,
6972 		struct nfs4_lock_state *lsp)
6973 {
6974 	struct nfs4_state *state = lsp->ls_state;
6975 	bool ret = false;
6976 
6977 	spin_lock(&state->state_lock);
6978 	if (!nfs4_stateid_match_other(dst, &lsp->ls_stateid))
6979 		goto out;
6980 	if (!nfs4_stateid_is_newer(&lsp->ls_stateid, dst))
6981 		nfs4_stateid_seqid_inc(dst);
6982 	else
6983 		dst->seqid = lsp->ls_stateid.seqid;
6984 	ret = true;
6985 out:
6986 	spin_unlock(&state->state_lock);
6987 	return ret;
6988 }
6989 
6990 static bool nfs4_sync_lock_stateid(nfs4_stateid *dst,
6991 		struct nfs4_lock_state *lsp)
6992 {
6993 	struct nfs4_state *state = lsp->ls_state;
6994 	bool ret;
6995 
6996 	spin_lock(&state->state_lock);
6997 	ret = !nfs4_stateid_match_other(dst, &lsp->ls_stateid);
6998 	nfs4_stateid_copy(dst, &lsp->ls_stateid);
6999 	spin_unlock(&state->state_lock);
7000 	return ret;
7001 }
7002 
7003 struct nfs4_unlockdata {
7004 	struct nfs_locku_args arg;
7005 	struct nfs_locku_res res;
7006 	struct nfs4_lock_state *lsp;
7007 	struct nfs_open_context *ctx;
7008 	struct nfs_lock_context *l_ctx;
7009 	struct file_lock fl;
7010 	struct nfs_server *server;
7011 	unsigned long timestamp;
7012 };
7013 
7014 static struct nfs4_unlockdata *nfs4_alloc_unlockdata(struct file_lock *fl,
7015 		struct nfs_open_context *ctx,
7016 		struct nfs4_lock_state *lsp,
7017 		struct nfs_seqid *seqid)
7018 {
7019 	struct nfs4_unlockdata *p;
7020 	struct nfs4_state *state = lsp->ls_state;
7021 	struct inode *inode = state->inode;
7022 
7023 	p = kzalloc(sizeof(*p), GFP_KERNEL);
7024 	if (p == NULL)
7025 		return NULL;
7026 	p->arg.fh = NFS_FH(inode);
7027 	p->arg.fl = &p->fl;
7028 	p->arg.seqid = seqid;
7029 	p->res.seqid = seqid;
7030 	p->lsp = lsp;
7031 	/* Ensure we don't close file until we're done freeing locks! */
7032 	p->ctx = get_nfs_open_context(ctx);
7033 	p->l_ctx = nfs_get_lock_context(ctx);
7034 	locks_init_lock(&p->fl);
7035 	locks_copy_lock(&p->fl, fl);
7036 	p->server = NFS_SERVER(inode);
7037 	spin_lock(&state->state_lock);
7038 	nfs4_stateid_copy(&p->arg.stateid, &lsp->ls_stateid);
7039 	spin_unlock(&state->state_lock);
7040 	return p;
7041 }
7042 
7043 static void nfs4_locku_release_calldata(void *data)
7044 {
7045 	struct nfs4_unlockdata *calldata = data;
7046 	nfs_free_seqid(calldata->arg.seqid);
7047 	nfs4_put_lock_state(calldata->lsp);
7048 	nfs_put_lock_context(calldata->l_ctx);
7049 	put_nfs_open_context(calldata->ctx);
7050 	kfree(calldata);
7051 }
7052 
7053 static void nfs4_locku_done(struct rpc_task *task, void *data)
7054 {
7055 	struct nfs4_unlockdata *calldata = data;
7056 	struct nfs4_exception exception = {
7057 		.inode = calldata->lsp->ls_state->inode,
7058 		.stateid = &calldata->arg.stateid,
7059 	};
7060 
7061 	if (!nfs4_sequence_done(task, &calldata->res.seq_res))
7062 		return;
7063 	switch (task->tk_status) {
7064 		case 0:
7065 			renew_lease(calldata->server, calldata->timestamp);
7066 			locks_lock_inode_wait(calldata->lsp->ls_state->inode, &calldata->fl);
7067 			if (nfs4_update_lock_stateid(calldata->lsp,
7068 					&calldata->res.stateid))
7069 				break;
7070 			fallthrough;
7071 		case -NFS4ERR_ADMIN_REVOKED:
7072 		case -NFS4ERR_EXPIRED:
7073 			nfs4_free_revoked_stateid(calldata->server,
7074 					&calldata->arg.stateid,
7075 					task->tk_msg.rpc_cred);
7076 			fallthrough;
7077 		case -NFS4ERR_BAD_STATEID:
7078 		case -NFS4ERR_STALE_STATEID:
7079 			if (nfs4_sync_lock_stateid(&calldata->arg.stateid,
7080 						calldata->lsp))
7081 				rpc_restart_call_prepare(task);
7082 			break;
7083 		case -NFS4ERR_OLD_STATEID:
7084 			if (nfs4_refresh_lock_old_stateid(&calldata->arg.stateid,
7085 						calldata->lsp))
7086 				rpc_restart_call_prepare(task);
7087 			break;
7088 		default:
7089 			task->tk_status = nfs4_async_handle_exception(task,
7090 					calldata->server, task->tk_status,
7091 					&exception);
7092 			if (exception.retry)
7093 				rpc_restart_call_prepare(task);
7094 	}
7095 	nfs_release_seqid(calldata->arg.seqid);
7096 }
7097 
7098 static void nfs4_locku_prepare(struct rpc_task *task, void *data)
7099 {
7100 	struct nfs4_unlockdata *calldata = data;
7101 
7102 	if (test_bit(NFS_CONTEXT_UNLOCK, &calldata->l_ctx->open_context->flags) &&
7103 		nfs_async_iocounter_wait(task, calldata->l_ctx))
7104 		return;
7105 
7106 	if (nfs_wait_on_sequence(calldata->arg.seqid, task) != 0)
7107 		goto out_wait;
7108 	if (test_bit(NFS_LOCK_INITIALIZED, &calldata->lsp->ls_flags) == 0) {
7109 		/* Note: exit _without_ running nfs4_locku_done */
7110 		goto out_no_action;
7111 	}
7112 	calldata->timestamp = jiffies;
7113 	if (nfs4_setup_sequence(calldata->server->nfs_client,
7114 				&calldata->arg.seq_args,
7115 				&calldata->res.seq_res,
7116 				task) != 0)
7117 		nfs_release_seqid(calldata->arg.seqid);
7118 	return;
7119 out_no_action:
7120 	task->tk_action = NULL;
7121 out_wait:
7122 	nfs4_sequence_done(task, &calldata->res.seq_res);
7123 }
7124 
7125 static const struct rpc_call_ops nfs4_locku_ops = {
7126 	.rpc_call_prepare = nfs4_locku_prepare,
7127 	.rpc_call_done = nfs4_locku_done,
7128 	.rpc_release = nfs4_locku_release_calldata,
7129 };
7130 
7131 static struct rpc_task *nfs4_do_unlck(struct file_lock *fl,
7132 		struct nfs_open_context *ctx,
7133 		struct nfs4_lock_state *lsp,
7134 		struct nfs_seqid *seqid)
7135 {
7136 	struct nfs4_unlockdata *data;
7137 	struct rpc_message msg = {
7138 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_LOCKU],
7139 		.rpc_cred = ctx->cred,
7140 	};
7141 	struct rpc_task_setup task_setup_data = {
7142 		.rpc_client = NFS_CLIENT(lsp->ls_state->inode),
7143 		.rpc_message = &msg,
7144 		.callback_ops = &nfs4_locku_ops,
7145 		.workqueue = nfsiod_workqueue,
7146 		.flags = RPC_TASK_ASYNC,
7147 	};
7148 
7149 	if (nfs_server_capable(lsp->ls_state->inode, NFS_CAP_MOVEABLE))
7150 		task_setup_data.flags |= RPC_TASK_MOVEABLE;
7151 
7152 	nfs4_state_protect(NFS_SERVER(lsp->ls_state->inode)->nfs_client,
7153 		NFS_SP4_MACH_CRED_CLEANUP, &task_setup_data.rpc_client, &msg);
7154 
7155 	/* Ensure this is an unlock - when canceling a lock, the
7156 	 * canceled lock is passed in, and it won't be an unlock.
7157 	 */
7158 	fl->c.flc_type = F_UNLCK;
7159 	if (fl->c.flc_flags & FL_CLOSE)
7160 		set_bit(NFS_CONTEXT_UNLOCK, &ctx->flags);
7161 
7162 	data = nfs4_alloc_unlockdata(fl, ctx, lsp, seqid);
7163 	if (data == NULL) {
7164 		nfs_free_seqid(seqid);
7165 		return ERR_PTR(-ENOMEM);
7166 	}
7167 
7168 	nfs4_init_sequence(&data->arg.seq_args, &data->res.seq_res, 1, 0);
7169 	msg.rpc_argp = &data->arg;
7170 	msg.rpc_resp = &data->res;
7171 	task_setup_data.callback_data = data;
7172 	return rpc_run_task(&task_setup_data);
7173 }
7174 
7175 static int nfs4_proc_unlck(struct nfs4_state *state, int cmd, struct file_lock *request)
7176 {
7177 	struct inode *inode = state->inode;
7178 	struct nfs4_state_owner *sp = state->owner;
7179 	struct nfs_inode *nfsi = NFS_I(inode);
7180 	struct nfs_seqid *seqid;
7181 	struct nfs4_lock_state *lsp;
7182 	struct rpc_task *task;
7183 	struct nfs_seqid *(*alloc_seqid)(struct nfs_seqid_counter *, gfp_t);
7184 	int status = 0;
7185 	unsigned char saved_flags = request->c.flc_flags;
7186 
7187 	status = nfs4_set_lock_state(state, request);
7188 	/* Unlock _before_ we do the RPC call */
7189 	request->c.flc_flags |= FL_EXISTS;
7190 	/* Exclude nfs_delegation_claim_locks() */
7191 	mutex_lock(&sp->so_delegreturn_mutex);
7192 	/* Exclude nfs4_reclaim_open_stateid() - note nesting! */
7193 	down_read(&nfsi->rwsem);
7194 	if (locks_lock_inode_wait(inode, request) == -ENOENT) {
7195 		up_read(&nfsi->rwsem);
7196 		mutex_unlock(&sp->so_delegreturn_mutex);
7197 		goto out;
7198 	}
7199 	lsp = request->fl_u.nfs4_fl.owner;
7200 	set_bit(NFS_LOCK_UNLOCKING, &lsp->ls_flags);
7201 	up_read(&nfsi->rwsem);
7202 	mutex_unlock(&sp->so_delegreturn_mutex);
7203 	if (status != 0)
7204 		goto out;
7205 	/* Is this a delegated lock? */
7206 	if (test_bit(NFS_LOCK_INITIALIZED, &lsp->ls_flags) == 0)
7207 		goto out;
7208 	alloc_seqid = NFS_SERVER(inode)->nfs_client->cl_mvops->alloc_seqid;
7209 	seqid = alloc_seqid(&lsp->ls_seqid, GFP_KERNEL);
7210 	status = -ENOMEM;
7211 	if (IS_ERR(seqid))
7212 		goto out;
7213 	task = nfs4_do_unlck(request,
7214 			     nfs_file_open_context(request->c.flc_file),
7215 			     lsp, seqid);
7216 	status = PTR_ERR(task);
7217 	if (IS_ERR(task))
7218 		goto out;
7219 	status = rpc_wait_for_completion_task(task);
7220 	rpc_put_task(task);
7221 out:
7222 	request->c.flc_flags = saved_flags;
7223 	trace_nfs4_unlock(request, state, F_SETLK, status);
7224 	return status;
7225 }
7226 
7227 struct nfs4_lockdata {
7228 	struct nfs_lock_args arg;
7229 	struct nfs_lock_res res;
7230 	struct nfs4_lock_state *lsp;
7231 	struct nfs_open_context *ctx;
7232 	struct file_lock fl;
7233 	unsigned long timestamp;
7234 	int rpc_status;
7235 	int cancelled;
7236 	struct nfs_server *server;
7237 };
7238 
7239 static struct nfs4_lockdata *nfs4_alloc_lockdata(struct file_lock *fl,
7240 		struct nfs_open_context *ctx, struct nfs4_lock_state *lsp,
7241 		gfp_t gfp_mask)
7242 {
7243 	struct nfs4_lockdata *p;
7244 	struct inode *inode = lsp->ls_state->inode;
7245 	struct nfs_server *server = NFS_SERVER(inode);
7246 	struct nfs_seqid *(*alloc_seqid)(struct nfs_seqid_counter *, gfp_t);
7247 
7248 	p = kzalloc(sizeof(*p), gfp_mask);
7249 	if (p == NULL)
7250 		return NULL;
7251 
7252 	p->arg.fh = NFS_FH(inode);
7253 	p->arg.fl = &p->fl;
7254 	p->arg.open_seqid = nfs_alloc_seqid(&lsp->ls_state->owner->so_seqid, gfp_mask);
7255 	if (IS_ERR(p->arg.open_seqid))
7256 		goto out_free;
7257 	alloc_seqid = server->nfs_client->cl_mvops->alloc_seqid;
7258 	p->arg.lock_seqid = alloc_seqid(&lsp->ls_seqid, gfp_mask);
7259 	if (IS_ERR(p->arg.lock_seqid))
7260 		goto out_free_seqid;
7261 	p->arg.lock_owner.clientid = server->nfs_client->cl_clientid;
7262 	p->arg.lock_owner.id = lsp->ls_seqid.owner_id;
7263 	p->arg.lock_owner.s_dev = server->s_dev;
7264 	p->res.lock_seqid = p->arg.lock_seqid;
7265 	p->lsp = lsp;
7266 	p->server = server;
7267 	p->ctx = get_nfs_open_context(ctx);
7268 	locks_init_lock(&p->fl);
7269 	locks_copy_lock(&p->fl, fl);
7270 	return p;
7271 out_free_seqid:
7272 	nfs_free_seqid(p->arg.open_seqid);
7273 out_free:
7274 	kfree(p);
7275 	return NULL;
7276 }
7277 
7278 static void nfs4_lock_prepare(struct rpc_task *task, void *calldata)
7279 {
7280 	struct nfs4_lockdata *data = calldata;
7281 	struct nfs4_state *state = data->lsp->ls_state;
7282 
7283 	if (nfs_wait_on_sequence(data->arg.lock_seqid, task) != 0)
7284 		goto out_wait;
7285 	/* Do we need to do an open_to_lock_owner? */
7286 	if (!test_bit(NFS_LOCK_INITIALIZED, &data->lsp->ls_flags)) {
7287 		if (nfs_wait_on_sequence(data->arg.open_seqid, task) != 0) {
7288 			goto out_release_lock_seqid;
7289 		}
7290 		nfs4_stateid_copy(&data->arg.open_stateid,
7291 				&state->open_stateid);
7292 		data->arg.new_lock_owner = 1;
7293 		data->res.open_seqid = data->arg.open_seqid;
7294 	} else {
7295 		data->arg.new_lock_owner = 0;
7296 		nfs4_stateid_copy(&data->arg.lock_stateid,
7297 				&data->lsp->ls_stateid);
7298 	}
7299 	if (!nfs4_valid_open_stateid(state)) {
7300 		data->rpc_status = -EBADF;
7301 		task->tk_action = NULL;
7302 		goto out_release_open_seqid;
7303 	}
7304 	data->timestamp = jiffies;
7305 	if (nfs4_setup_sequence(data->server->nfs_client,
7306 				&data->arg.seq_args,
7307 				&data->res.seq_res,
7308 				task) == 0)
7309 		return;
7310 out_release_open_seqid:
7311 	nfs_release_seqid(data->arg.open_seqid);
7312 out_release_lock_seqid:
7313 	nfs_release_seqid(data->arg.lock_seqid);
7314 out_wait:
7315 	nfs4_sequence_done(task, &data->res.seq_res);
7316 	dprintk("%s: ret = %d\n", __func__, data->rpc_status);
7317 }
7318 
7319 static void nfs4_lock_done(struct rpc_task *task, void *calldata)
7320 {
7321 	struct nfs4_lockdata *data = calldata;
7322 	struct nfs4_lock_state *lsp = data->lsp;
7323 
7324 	if (!nfs4_sequence_done(task, &data->res.seq_res))
7325 		return;
7326 
7327 	data->rpc_status = task->tk_status;
7328 	switch (task->tk_status) {
7329 	case 0:
7330 		renew_lease(NFS_SERVER(d_inode(data->ctx->dentry)),
7331 				data->timestamp);
7332 		if (data->arg.new_lock && !data->cancelled) {
7333 			data->fl.c.flc_flags &= ~(FL_SLEEP | FL_ACCESS);
7334 			if (locks_lock_inode_wait(lsp->ls_state->inode, &data->fl) < 0)
7335 				goto out_restart;
7336 		}
7337 		if (data->arg.new_lock_owner != 0) {
7338 			nfs_confirm_seqid(&lsp->ls_seqid, 0);
7339 			nfs4_stateid_copy(&lsp->ls_stateid, &data->res.stateid);
7340 			set_bit(NFS_LOCK_INITIALIZED, &lsp->ls_flags);
7341 		} else if (!nfs4_update_lock_stateid(lsp, &data->res.stateid))
7342 			goto out_restart;
7343 		break;
7344 	case -NFS4ERR_OLD_STATEID:
7345 		if (data->arg.new_lock_owner != 0 &&
7346 			nfs4_refresh_open_old_stateid(&data->arg.open_stateid,
7347 					lsp->ls_state))
7348 			goto out_restart;
7349 		if (nfs4_refresh_lock_old_stateid(&data->arg.lock_stateid, lsp))
7350 			goto out_restart;
7351 		fallthrough;
7352 	case -NFS4ERR_BAD_STATEID:
7353 	case -NFS4ERR_STALE_STATEID:
7354 	case -NFS4ERR_EXPIRED:
7355 		if (data->arg.new_lock_owner != 0) {
7356 			if (!nfs4_stateid_match(&data->arg.open_stateid,
7357 						&lsp->ls_state->open_stateid))
7358 				goto out_restart;
7359 		} else if (!nfs4_stateid_match(&data->arg.lock_stateid,
7360 						&lsp->ls_stateid))
7361 				goto out_restart;
7362 	}
7363 out_done:
7364 	dprintk("%s: ret = %d!\n", __func__, data->rpc_status);
7365 	return;
7366 out_restart:
7367 	if (!data->cancelled)
7368 		rpc_restart_call_prepare(task);
7369 	goto out_done;
7370 }
7371 
7372 static void nfs4_lock_release(void *calldata)
7373 {
7374 	struct nfs4_lockdata *data = calldata;
7375 
7376 	nfs_free_seqid(data->arg.open_seqid);
7377 	if (data->cancelled && data->rpc_status == 0) {
7378 		struct rpc_task *task;
7379 		task = nfs4_do_unlck(&data->fl, data->ctx, data->lsp,
7380 				data->arg.lock_seqid);
7381 		if (!IS_ERR(task))
7382 			rpc_put_task_async(task);
7383 		dprintk("%s: cancelling lock!\n", __func__);
7384 	} else
7385 		nfs_free_seqid(data->arg.lock_seqid);
7386 	nfs4_put_lock_state(data->lsp);
7387 	put_nfs_open_context(data->ctx);
7388 	kfree(data);
7389 }
7390 
7391 static const struct rpc_call_ops nfs4_lock_ops = {
7392 	.rpc_call_prepare = nfs4_lock_prepare,
7393 	.rpc_call_done = nfs4_lock_done,
7394 	.rpc_release = nfs4_lock_release,
7395 };
7396 
7397 static void nfs4_handle_setlk_error(struct nfs_server *server, struct nfs4_lock_state *lsp, int new_lock_owner, int error)
7398 {
7399 	switch (error) {
7400 	case -NFS4ERR_ADMIN_REVOKED:
7401 	case -NFS4ERR_EXPIRED:
7402 	case -NFS4ERR_BAD_STATEID:
7403 		lsp->ls_seqid.flags &= ~NFS_SEQID_CONFIRMED;
7404 		if (new_lock_owner != 0 ||
7405 		   test_bit(NFS_LOCK_INITIALIZED, &lsp->ls_flags) != 0)
7406 			nfs4_schedule_stateid_recovery(server, lsp->ls_state);
7407 		break;
7408 	case -NFS4ERR_STALE_STATEID:
7409 		lsp->ls_seqid.flags &= ~NFS_SEQID_CONFIRMED;
7410 		nfs4_schedule_lease_recovery(server->nfs_client);
7411 	}
7412 }
7413 
7414 static int _nfs4_do_setlk(struct nfs4_state *state, int cmd, struct file_lock *fl, int recovery_type)
7415 {
7416 	struct nfs4_lockdata *data;
7417 	struct rpc_task *task;
7418 	struct rpc_message msg = {
7419 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_LOCK],
7420 		.rpc_cred = state->owner->so_cred,
7421 	};
7422 	struct rpc_task_setup task_setup_data = {
7423 		.rpc_client = NFS_CLIENT(state->inode),
7424 		.rpc_message = &msg,
7425 		.callback_ops = &nfs4_lock_ops,
7426 		.workqueue = nfsiod_workqueue,
7427 		.flags = RPC_TASK_ASYNC | RPC_TASK_CRED_NOREF,
7428 	};
7429 	int ret;
7430 
7431 	if (nfs_server_capable(state->inode, NFS_CAP_MOVEABLE))
7432 		task_setup_data.flags |= RPC_TASK_MOVEABLE;
7433 
7434 	data = nfs4_alloc_lockdata(fl,
7435 				   nfs_file_open_context(fl->c.flc_file),
7436 				   fl->fl_u.nfs4_fl.owner, GFP_KERNEL);
7437 	if (data == NULL)
7438 		return -ENOMEM;
7439 	if (IS_SETLKW(cmd))
7440 		data->arg.block = 1;
7441 	nfs4_init_sequence(&data->arg.seq_args, &data->res.seq_res, 1,
7442 				recovery_type > NFS_LOCK_NEW);
7443 	msg.rpc_argp = &data->arg;
7444 	msg.rpc_resp = &data->res;
7445 	task_setup_data.callback_data = data;
7446 	if (recovery_type > NFS_LOCK_NEW) {
7447 		if (recovery_type == NFS_LOCK_RECLAIM)
7448 			data->arg.reclaim = NFS_LOCK_RECLAIM;
7449 	} else
7450 		data->arg.new_lock = 1;
7451 	task = rpc_run_task(&task_setup_data);
7452 	if (IS_ERR(task))
7453 		return PTR_ERR(task);
7454 	ret = rpc_wait_for_completion_task(task);
7455 	if (ret == 0) {
7456 		ret = data->rpc_status;
7457 		if (ret)
7458 			nfs4_handle_setlk_error(data->server, data->lsp,
7459 					data->arg.new_lock_owner, ret);
7460 	} else
7461 		data->cancelled = true;
7462 	trace_nfs4_set_lock(fl, state, &data->res.stateid, cmd, ret);
7463 	rpc_put_task(task);
7464 	dprintk("%s: ret = %d\n", __func__, ret);
7465 	return ret;
7466 }
7467 
7468 static int nfs4_lock_reclaim(struct nfs4_state *state, struct file_lock *request)
7469 {
7470 	struct nfs_server *server = NFS_SERVER(state->inode);
7471 	struct nfs4_exception exception = {
7472 		.inode = state->inode,
7473 	};
7474 	int err;
7475 
7476 	do {
7477 		/* Cache the lock if possible... */
7478 		if (test_bit(NFS_DELEGATED_STATE, &state->flags) != 0)
7479 			return 0;
7480 		err = _nfs4_do_setlk(state, F_SETLK, request, NFS_LOCK_RECLAIM);
7481 		if (err != -NFS4ERR_DELAY)
7482 			break;
7483 		nfs4_handle_exception(server, err, &exception);
7484 	} while (exception.retry);
7485 	return err;
7486 }
7487 
7488 static int nfs4_lock_expired(struct nfs4_state *state, struct file_lock *request)
7489 {
7490 	struct nfs_server *server = NFS_SERVER(state->inode);
7491 	struct nfs4_exception exception = {
7492 		.inode = state->inode,
7493 	};
7494 	int err;
7495 
7496 	err = nfs4_set_lock_state(state, request);
7497 	if (err != 0)
7498 		return err;
7499 	if (!recover_lost_locks) {
7500 		set_bit(NFS_LOCK_LOST, &request->fl_u.nfs4_fl.owner->ls_flags);
7501 		return 0;
7502 	}
7503 	do {
7504 		if (test_bit(NFS_DELEGATED_STATE, &state->flags) != 0)
7505 			return 0;
7506 		err = _nfs4_do_setlk(state, F_SETLK, request, NFS_LOCK_EXPIRED);
7507 		switch (err) {
7508 		default:
7509 			goto out;
7510 		case -NFS4ERR_GRACE:
7511 		case -NFS4ERR_DELAY:
7512 			nfs4_handle_exception(server, err, &exception);
7513 			err = 0;
7514 		}
7515 	} while (exception.retry);
7516 out:
7517 	return err;
7518 }
7519 
7520 #if defined(CONFIG_NFS_V4_1)
7521 static int nfs41_lock_expired(struct nfs4_state *state, struct file_lock *request)
7522 {
7523 	struct nfs4_lock_state *lsp;
7524 	int status;
7525 
7526 	status = nfs4_set_lock_state(state, request);
7527 	if (status != 0)
7528 		return status;
7529 	lsp = request->fl_u.nfs4_fl.owner;
7530 	if (test_bit(NFS_LOCK_INITIALIZED, &lsp->ls_flags) ||
7531 	    test_bit(NFS_LOCK_LOST, &lsp->ls_flags))
7532 		return 0;
7533 	return nfs4_lock_expired(state, request);
7534 }
7535 #endif
7536 
7537 static int _nfs4_proc_setlk(struct nfs4_state *state, int cmd, struct file_lock *request)
7538 {
7539 	struct nfs_inode *nfsi = NFS_I(state->inode);
7540 	struct nfs4_state_owner *sp = state->owner;
7541 	unsigned char flags = request->c.flc_flags;
7542 	int status;
7543 
7544 	request->c.flc_flags |= FL_ACCESS;
7545 	status = locks_lock_inode_wait(state->inode, request);
7546 	if (status < 0)
7547 		goto out;
7548 	mutex_lock(&sp->so_delegreturn_mutex);
7549 	down_read(&nfsi->rwsem);
7550 	if (test_bit(NFS_DELEGATED_STATE, &state->flags)) {
7551 		/* Yes: cache locks! */
7552 		/* ...but avoid races with delegation recall... */
7553 		request->c.flc_flags = flags & ~FL_SLEEP;
7554 		status = locks_lock_inode_wait(state->inode, request);
7555 		up_read(&nfsi->rwsem);
7556 		mutex_unlock(&sp->so_delegreturn_mutex);
7557 		goto out;
7558 	}
7559 	up_read(&nfsi->rwsem);
7560 	mutex_unlock(&sp->so_delegreturn_mutex);
7561 	status = _nfs4_do_setlk(state, cmd, request, NFS_LOCK_NEW);
7562 out:
7563 	request->c.flc_flags = flags;
7564 	return status;
7565 }
7566 
7567 static int nfs4_proc_setlk(struct nfs4_state *state, int cmd, struct file_lock *request)
7568 {
7569 	struct nfs4_exception exception = {
7570 		.state = state,
7571 		.inode = state->inode,
7572 		.interruptible = true,
7573 	};
7574 	int err;
7575 
7576 	do {
7577 		err = _nfs4_proc_setlk(state, cmd, request);
7578 		if (err == -NFS4ERR_DENIED)
7579 			err = -EAGAIN;
7580 		err = nfs4_handle_exception(NFS_SERVER(state->inode),
7581 				err, &exception);
7582 	} while (exception.retry);
7583 	return err;
7584 }
7585 
7586 #define NFS4_LOCK_MINTIMEOUT (1 * HZ)
7587 #define NFS4_LOCK_MAXTIMEOUT (30 * HZ)
7588 
7589 static int
7590 nfs4_retry_setlk_simple(struct nfs4_state *state, int cmd,
7591 			struct file_lock *request)
7592 {
7593 	int		status = -ERESTARTSYS;
7594 	unsigned long	timeout = NFS4_LOCK_MINTIMEOUT;
7595 
7596 	while(!signalled()) {
7597 		status = nfs4_proc_setlk(state, cmd, request);
7598 		if ((status != -EAGAIN) || IS_SETLK(cmd))
7599 			break;
7600 		__set_current_state(TASK_INTERRUPTIBLE|TASK_FREEZABLE);
7601 		schedule_timeout(timeout);
7602 		timeout *= 2;
7603 		timeout = min_t(unsigned long, NFS4_LOCK_MAXTIMEOUT, timeout);
7604 		status = -ERESTARTSYS;
7605 	}
7606 	return status;
7607 }
7608 
7609 #ifdef CONFIG_NFS_V4_1
7610 struct nfs4_lock_waiter {
7611 	struct inode		*inode;
7612 	struct nfs_lowner	owner;
7613 	wait_queue_entry_t	wait;
7614 };
7615 
7616 static int
7617 nfs4_wake_lock_waiter(wait_queue_entry_t *wait, unsigned int mode, int flags, void *key)
7618 {
7619 	struct nfs4_lock_waiter	*waiter	=
7620 		container_of(wait, struct nfs4_lock_waiter, wait);
7621 
7622 	/* NULL key means to wake up everyone */
7623 	if (key) {
7624 		struct cb_notify_lock_args	*cbnl = key;
7625 		struct nfs_lowner		*lowner = &cbnl->cbnl_owner,
7626 						*wowner = &waiter->owner;
7627 
7628 		/* Only wake if the callback was for the same owner. */
7629 		if (lowner->id != wowner->id || lowner->s_dev != wowner->s_dev)
7630 			return 0;
7631 
7632 		/* Make sure it's for the right inode */
7633 		if (nfs_compare_fh(NFS_FH(waiter->inode), &cbnl->cbnl_fh))
7634 			return 0;
7635 	}
7636 
7637 	return woken_wake_function(wait, mode, flags, key);
7638 }
7639 
7640 static int
7641 nfs4_retry_setlk(struct nfs4_state *state, int cmd, struct file_lock *request)
7642 {
7643 	struct nfs4_lock_state *lsp = request->fl_u.nfs4_fl.owner;
7644 	struct nfs_server *server = NFS_SERVER(state->inode);
7645 	struct nfs_client *clp = server->nfs_client;
7646 	wait_queue_head_t *q = &clp->cl_lock_waitq;
7647 	struct nfs4_lock_waiter waiter = {
7648 		.inode = state->inode,
7649 		.owner = { .clientid = clp->cl_clientid,
7650 			   .id = lsp->ls_seqid.owner_id,
7651 			   .s_dev = server->s_dev },
7652 	};
7653 	int status;
7654 
7655 	/* Don't bother with waitqueue if we don't expect a callback */
7656 	if (!test_bit(NFS_STATE_MAY_NOTIFY_LOCK, &state->flags))
7657 		return nfs4_retry_setlk_simple(state, cmd, request);
7658 
7659 	init_wait(&waiter.wait);
7660 	waiter.wait.func = nfs4_wake_lock_waiter;
7661 	add_wait_queue(q, &waiter.wait);
7662 
7663 	do {
7664 		status = nfs4_proc_setlk(state, cmd, request);
7665 		if (status != -EAGAIN || IS_SETLK(cmd))
7666 			break;
7667 
7668 		status = -ERESTARTSYS;
7669 		wait_woken(&waiter.wait, TASK_INTERRUPTIBLE|TASK_FREEZABLE,
7670 			   NFS4_LOCK_MAXTIMEOUT);
7671 	} while (!signalled());
7672 
7673 	remove_wait_queue(q, &waiter.wait);
7674 
7675 	return status;
7676 }
7677 #else /* !CONFIG_NFS_V4_1 */
7678 static inline int
7679 nfs4_retry_setlk(struct nfs4_state *state, int cmd, struct file_lock *request)
7680 {
7681 	return nfs4_retry_setlk_simple(state, cmd, request);
7682 }
7683 #endif
7684 
7685 static int
7686 nfs4_proc_lock(struct file *filp, int cmd, struct file_lock *request)
7687 {
7688 	struct nfs_open_context *ctx;
7689 	struct nfs4_state *state;
7690 	int status;
7691 
7692 	/* verify open state */
7693 	ctx = nfs_file_open_context(filp);
7694 	state = ctx->state;
7695 
7696 	if (IS_GETLK(cmd)) {
7697 		if (state != NULL)
7698 			return nfs4_proc_getlk(state, F_GETLK, request);
7699 		return 0;
7700 	}
7701 
7702 	if (!(IS_SETLK(cmd) || IS_SETLKW(cmd)))
7703 		return -EINVAL;
7704 
7705 	if (lock_is_unlock(request)) {
7706 		if (state != NULL)
7707 			return nfs4_proc_unlck(state, cmd, request);
7708 		return 0;
7709 	}
7710 
7711 	if (state == NULL)
7712 		return -ENOLCK;
7713 
7714 	if ((request->c.flc_flags & FL_POSIX) &&
7715 	    !test_bit(NFS_STATE_POSIX_LOCKS, &state->flags))
7716 		return -ENOLCK;
7717 
7718 	/*
7719 	 * Don't rely on the VFS having checked the file open mode,
7720 	 * since it won't do this for flock() locks.
7721 	 */
7722 	switch (request->c.flc_type) {
7723 	case F_RDLCK:
7724 		if (!(filp->f_mode & FMODE_READ))
7725 			return -EBADF;
7726 		break;
7727 	case F_WRLCK:
7728 		if (!(filp->f_mode & FMODE_WRITE))
7729 			return -EBADF;
7730 	}
7731 
7732 	status = nfs4_set_lock_state(state, request);
7733 	if (status != 0)
7734 		return status;
7735 
7736 	return nfs4_retry_setlk(state, cmd, request);
7737 }
7738 
7739 static int nfs4_delete_lease(struct file *file, void **priv)
7740 {
7741 	return generic_setlease(file, F_UNLCK, NULL, priv);
7742 }
7743 
7744 static int nfs4_add_lease(struct file *file, int arg, struct file_lease **lease,
7745 			  void **priv)
7746 {
7747 	struct inode *inode = file_inode(file);
7748 	fmode_t type = arg == F_RDLCK ? FMODE_READ : FMODE_WRITE;
7749 	int ret;
7750 
7751 	/* No delegation, no lease */
7752 	if (!nfs4_have_delegation(inode, type, 0))
7753 		return -EAGAIN;
7754 	ret = generic_setlease(file, arg, lease, priv);
7755 	if (ret || nfs4_have_delegation(inode, type, 0))
7756 		return ret;
7757 	/* We raced with a delegation return */
7758 	nfs4_delete_lease(file, priv);
7759 	return -EAGAIN;
7760 }
7761 
7762 int nfs4_proc_setlease(struct file *file, int arg, struct file_lease **lease,
7763 		       void **priv)
7764 {
7765 	switch (arg) {
7766 	case F_RDLCK:
7767 	case F_WRLCK:
7768 		return nfs4_add_lease(file, arg, lease, priv);
7769 	case F_UNLCK:
7770 		return nfs4_delete_lease(file, priv);
7771 	default:
7772 		return -EINVAL;
7773 	}
7774 }
7775 
7776 int nfs4_lock_delegation_recall(struct file_lock *fl, struct nfs4_state *state, const nfs4_stateid *stateid)
7777 {
7778 	struct nfs_server *server = NFS_SERVER(state->inode);
7779 	int err;
7780 
7781 	err = nfs4_set_lock_state(state, fl);
7782 	if (err != 0)
7783 		return err;
7784 	do {
7785 		err = _nfs4_do_setlk(state, F_SETLK, fl, NFS_LOCK_NEW);
7786 		if (err != -NFS4ERR_DELAY)
7787 			break;
7788 		ssleep(1);
7789 	} while (err == -NFS4ERR_DELAY);
7790 	return nfs4_handle_delegation_recall_error(server, state, stateid, fl, err);
7791 }
7792 
7793 struct nfs_release_lockowner_data {
7794 	struct nfs4_lock_state *lsp;
7795 	struct nfs_server *server;
7796 	struct nfs_release_lockowner_args args;
7797 	struct nfs_release_lockowner_res res;
7798 	unsigned long timestamp;
7799 };
7800 
7801 static void nfs4_release_lockowner_prepare(struct rpc_task *task, void *calldata)
7802 {
7803 	struct nfs_release_lockowner_data *data = calldata;
7804 	struct nfs_server *server = data->server;
7805 	nfs4_setup_sequence(server->nfs_client, &data->args.seq_args,
7806 			   &data->res.seq_res, task);
7807 	data->args.lock_owner.clientid = server->nfs_client->cl_clientid;
7808 	data->timestamp = jiffies;
7809 }
7810 
7811 static void nfs4_release_lockowner_done(struct rpc_task *task, void *calldata)
7812 {
7813 	struct nfs_release_lockowner_data *data = calldata;
7814 	struct nfs_server *server = data->server;
7815 
7816 	nfs40_sequence_done(task, &data->res.seq_res);
7817 
7818 	switch (task->tk_status) {
7819 	case 0:
7820 		renew_lease(server, data->timestamp);
7821 		break;
7822 	case -NFS4ERR_STALE_CLIENTID:
7823 	case -NFS4ERR_EXPIRED:
7824 		nfs4_schedule_lease_recovery(server->nfs_client);
7825 		break;
7826 	case -NFS4ERR_LEASE_MOVED:
7827 	case -NFS4ERR_DELAY:
7828 		if (nfs4_async_handle_error(task, server,
7829 					    NULL, NULL) == -EAGAIN)
7830 			rpc_restart_call_prepare(task);
7831 	}
7832 }
7833 
7834 static void nfs4_release_lockowner_release(void *calldata)
7835 {
7836 	struct nfs_release_lockowner_data *data = calldata;
7837 	nfs4_free_lock_state(data->server, data->lsp);
7838 	kfree(calldata);
7839 }
7840 
7841 static const struct rpc_call_ops nfs4_release_lockowner_ops = {
7842 	.rpc_call_prepare = nfs4_release_lockowner_prepare,
7843 	.rpc_call_done = nfs4_release_lockowner_done,
7844 	.rpc_release = nfs4_release_lockowner_release,
7845 };
7846 
7847 static void
7848 nfs4_release_lockowner(struct nfs_server *server, struct nfs4_lock_state *lsp)
7849 {
7850 	struct nfs_release_lockowner_data *data;
7851 	struct rpc_message msg = {
7852 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_RELEASE_LOCKOWNER],
7853 	};
7854 
7855 	if (server->nfs_client->cl_mvops->minor_version != 0)
7856 		return;
7857 
7858 	data = kmalloc(sizeof(*data), GFP_KERNEL);
7859 	if (!data)
7860 		return;
7861 	data->lsp = lsp;
7862 	data->server = server;
7863 	data->args.lock_owner.clientid = server->nfs_client->cl_clientid;
7864 	data->args.lock_owner.id = lsp->ls_seqid.owner_id;
7865 	data->args.lock_owner.s_dev = server->s_dev;
7866 
7867 	msg.rpc_argp = &data->args;
7868 	msg.rpc_resp = &data->res;
7869 	nfs4_init_sequence(&data->args.seq_args, &data->res.seq_res, 0, 0);
7870 	rpc_call_async(server->client, &msg, 0, &nfs4_release_lockowner_ops, data);
7871 }
7872 
7873 #define XATTR_NAME_NFSV4_ACL "system.nfs4_acl"
7874 
7875 static int nfs4_xattr_set_nfs4_acl(const struct xattr_handler *handler,
7876 				   struct mnt_idmap *idmap,
7877 				   struct dentry *unused, struct inode *inode,
7878 				   const char *key, const void *buf,
7879 				   size_t buflen, int flags)
7880 {
7881 	return nfs4_proc_set_acl(inode, buf, buflen, NFS4ACL_ACL);
7882 }
7883 
7884 static int nfs4_xattr_get_nfs4_acl(const struct xattr_handler *handler,
7885 				   struct dentry *unused, struct inode *inode,
7886 				   const char *key, void *buf, size_t buflen)
7887 {
7888 	return nfs4_proc_get_acl(inode, buf, buflen, NFS4ACL_ACL);
7889 }
7890 
7891 static bool nfs4_xattr_list_nfs4_acl(struct dentry *dentry)
7892 {
7893 	return nfs4_server_supports_acls(NFS_SB(dentry->d_sb), NFS4ACL_ACL);
7894 }
7895 
7896 #if defined(CONFIG_NFS_V4_1)
7897 #define XATTR_NAME_NFSV4_DACL "system.nfs4_dacl"
7898 
7899 static int nfs4_xattr_set_nfs4_dacl(const struct xattr_handler *handler,
7900 				    struct mnt_idmap *idmap,
7901 				    struct dentry *unused, struct inode *inode,
7902 				    const char *key, const void *buf,
7903 				    size_t buflen, int flags)
7904 {
7905 	return nfs4_proc_set_acl(inode, buf, buflen, NFS4ACL_DACL);
7906 }
7907 
7908 static int nfs4_xattr_get_nfs4_dacl(const struct xattr_handler *handler,
7909 				    struct dentry *unused, struct inode *inode,
7910 				    const char *key, void *buf, size_t buflen)
7911 {
7912 	return nfs4_proc_get_acl(inode, buf, buflen, NFS4ACL_DACL);
7913 }
7914 
7915 static bool nfs4_xattr_list_nfs4_dacl(struct dentry *dentry)
7916 {
7917 	return nfs4_server_supports_acls(NFS_SB(dentry->d_sb), NFS4ACL_DACL);
7918 }
7919 
7920 #define XATTR_NAME_NFSV4_SACL "system.nfs4_sacl"
7921 
7922 static int nfs4_xattr_set_nfs4_sacl(const struct xattr_handler *handler,
7923 				    struct mnt_idmap *idmap,
7924 				    struct dentry *unused, struct inode *inode,
7925 				    const char *key, const void *buf,
7926 				    size_t buflen, int flags)
7927 {
7928 	return nfs4_proc_set_acl(inode, buf, buflen, NFS4ACL_SACL);
7929 }
7930 
7931 static int nfs4_xattr_get_nfs4_sacl(const struct xattr_handler *handler,
7932 				    struct dentry *unused, struct inode *inode,
7933 				    const char *key, void *buf, size_t buflen)
7934 {
7935 	return nfs4_proc_get_acl(inode, buf, buflen, NFS4ACL_SACL);
7936 }
7937 
7938 static bool nfs4_xattr_list_nfs4_sacl(struct dentry *dentry)
7939 {
7940 	return nfs4_server_supports_acls(NFS_SB(dentry->d_sb), NFS4ACL_SACL);
7941 }
7942 
7943 #endif
7944 
7945 #ifdef CONFIG_NFS_V4_SECURITY_LABEL
7946 
7947 static int nfs4_xattr_set_nfs4_label(const struct xattr_handler *handler,
7948 				     struct mnt_idmap *idmap,
7949 				     struct dentry *unused, struct inode *inode,
7950 				     const char *key, const void *buf,
7951 				     size_t buflen, int flags)
7952 {
7953 	if (security_ismaclabel(key))
7954 		return nfs4_set_security_label(inode, buf, buflen);
7955 
7956 	return -EOPNOTSUPP;
7957 }
7958 
7959 static int nfs4_xattr_get_nfs4_label(const struct xattr_handler *handler,
7960 				     struct dentry *unused, struct inode *inode,
7961 				     const char *key, void *buf, size_t buflen)
7962 {
7963 	if (security_ismaclabel(key))
7964 		return nfs4_get_security_label(inode, buf, buflen);
7965 	return -EOPNOTSUPP;
7966 }
7967 
7968 static ssize_t
7969 nfs4_listxattr_nfs4_label(struct inode *inode, char *list, size_t list_len)
7970 {
7971 	int len = 0;
7972 
7973 	if (nfs_server_capable(inode, NFS_CAP_SECURITY_LABEL)) {
7974 		len = security_inode_listsecurity(inode, list, list_len);
7975 		if (len >= 0 && list_len && len > list_len)
7976 			return -ERANGE;
7977 	}
7978 	return len;
7979 }
7980 
7981 static const struct xattr_handler nfs4_xattr_nfs4_label_handler = {
7982 	.prefix = XATTR_SECURITY_PREFIX,
7983 	.get	= nfs4_xattr_get_nfs4_label,
7984 	.set	= nfs4_xattr_set_nfs4_label,
7985 };
7986 
7987 #else
7988 
7989 static ssize_t
7990 nfs4_listxattr_nfs4_label(struct inode *inode, char *list, size_t list_len)
7991 {
7992 	return 0;
7993 }
7994 
7995 #endif
7996 
7997 #ifdef CONFIG_NFS_V4_2
7998 static int nfs4_xattr_set_nfs4_user(const struct xattr_handler *handler,
7999 				    struct mnt_idmap *idmap,
8000 				    struct dentry *unused, struct inode *inode,
8001 				    const char *key, const void *buf,
8002 				    size_t buflen, int flags)
8003 {
8004 	u32 mask;
8005 	int ret;
8006 
8007 	if (!nfs_server_capable(inode, NFS_CAP_XATTR))
8008 		return -EOPNOTSUPP;
8009 
8010 	/*
8011 	 * There is no mapping from the MAY_* flags to the NFS_ACCESS_XA*
8012 	 * flags right now. Handling of xattr operations use the normal
8013 	 * file read/write permissions.
8014 	 *
8015 	 * Just in case the server has other ideas (which RFC 8276 allows),
8016 	 * do a cached access check for the XA* flags to possibly avoid
8017 	 * doing an RPC and getting EACCES back.
8018 	 */
8019 	if (!nfs_access_get_cached(inode, current_cred(), &mask, true)) {
8020 		if (!(mask & NFS_ACCESS_XAWRITE))
8021 			return -EACCES;
8022 	}
8023 
8024 	if (buf == NULL) {
8025 		ret = nfs42_proc_removexattr(inode, key);
8026 		if (!ret)
8027 			nfs4_xattr_cache_remove(inode, key);
8028 	} else {
8029 		ret = nfs42_proc_setxattr(inode, key, buf, buflen, flags);
8030 		if (!ret)
8031 			nfs4_xattr_cache_add(inode, key, buf, NULL, buflen);
8032 	}
8033 
8034 	return ret;
8035 }
8036 
8037 static int nfs4_xattr_get_nfs4_user(const struct xattr_handler *handler,
8038 				    struct dentry *unused, struct inode *inode,
8039 				    const char *key, void *buf, size_t buflen)
8040 {
8041 	u32 mask;
8042 	ssize_t ret;
8043 
8044 	if (!nfs_server_capable(inode, NFS_CAP_XATTR))
8045 		return -EOPNOTSUPP;
8046 
8047 	if (!nfs_access_get_cached(inode, current_cred(), &mask, true)) {
8048 		if (!(mask & NFS_ACCESS_XAREAD))
8049 			return -EACCES;
8050 	}
8051 
8052 	ret = nfs_revalidate_inode(inode, NFS_INO_INVALID_CHANGE);
8053 	if (ret)
8054 		return ret;
8055 
8056 	ret = nfs4_xattr_cache_get(inode, key, buf, buflen);
8057 	if (ret >= 0 || (ret < 0 && ret != -ENOENT))
8058 		return ret;
8059 
8060 	ret = nfs42_proc_getxattr(inode, key, buf, buflen);
8061 
8062 	return ret;
8063 }
8064 
8065 static ssize_t
8066 nfs4_listxattr_nfs4_user(struct inode *inode, char *list, size_t list_len)
8067 {
8068 	u64 cookie;
8069 	bool eof;
8070 	ssize_t ret, size;
8071 	char *buf;
8072 	size_t buflen;
8073 	u32 mask;
8074 
8075 	if (!nfs_server_capable(inode, NFS_CAP_XATTR))
8076 		return 0;
8077 
8078 	if (!nfs_access_get_cached(inode, current_cred(), &mask, true)) {
8079 		if (!(mask & NFS_ACCESS_XALIST))
8080 			return 0;
8081 	}
8082 
8083 	ret = nfs_revalidate_inode(inode, NFS_INO_INVALID_CHANGE);
8084 	if (ret)
8085 		return ret;
8086 
8087 	ret = nfs4_xattr_cache_list(inode, list, list_len);
8088 	if (ret >= 0 || (ret < 0 && ret != -ENOENT))
8089 		return ret;
8090 
8091 	cookie = 0;
8092 	eof = false;
8093 	buflen = list_len ? list_len : XATTR_LIST_MAX;
8094 	buf = list_len ? list : NULL;
8095 	size = 0;
8096 
8097 	while (!eof) {
8098 		ret = nfs42_proc_listxattrs(inode, buf, buflen,
8099 		    &cookie, &eof);
8100 		if (ret < 0)
8101 			return ret;
8102 
8103 		if (list_len) {
8104 			buf += ret;
8105 			buflen -= ret;
8106 		}
8107 		size += ret;
8108 	}
8109 
8110 	if (list_len)
8111 		nfs4_xattr_cache_set_list(inode, list, size);
8112 
8113 	return size;
8114 }
8115 
8116 #else
8117 
8118 static ssize_t
8119 nfs4_listxattr_nfs4_user(struct inode *inode, char *list, size_t list_len)
8120 {
8121 	return 0;
8122 }
8123 #endif /* CONFIG_NFS_V4_2 */
8124 
8125 /*
8126  * nfs_fhget will use either the mounted_on_fileid or the fileid
8127  */
8128 static void nfs_fixup_referral_attributes(struct nfs_fattr *fattr)
8129 {
8130 	if (!(((fattr->valid & NFS_ATTR_FATTR_MOUNTED_ON_FILEID) ||
8131 	       (fattr->valid & NFS_ATTR_FATTR_FILEID)) &&
8132 	      (fattr->valid & NFS_ATTR_FATTR_FSID) &&
8133 	      (fattr->valid & NFS_ATTR_FATTR_V4_LOCATIONS)))
8134 		return;
8135 
8136 	fattr->valid |= NFS_ATTR_FATTR_TYPE | NFS_ATTR_FATTR_MODE |
8137 		NFS_ATTR_FATTR_NLINK | NFS_ATTR_FATTR_V4_REFERRAL;
8138 	fattr->mode = S_IFDIR | S_IRUGO | S_IXUGO;
8139 	fattr->nlink = 2;
8140 }
8141 
8142 static int _nfs4_proc_fs_locations(struct rpc_clnt *client, struct inode *dir,
8143 				   const struct qstr *name,
8144 				   struct nfs4_fs_locations *fs_locations,
8145 				   struct page *page)
8146 {
8147 	struct nfs_server *server = NFS_SERVER(dir);
8148 	u32 bitmask[3];
8149 	struct nfs4_fs_locations_arg args = {
8150 		.dir_fh = NFS_FH(dir),
8151 		.name = name,
8152 		.page = page,
8153 		.bitmask = bitmask,
8154 	};
8155 	struct nfs4_fs_locations_res res = {
8156 		.fs_locations = fs_locations,
8157 	};
8158 	struct rpc_message msg = {
8159 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_FS_LOCATIONS],
8160 		.rpc_argp = &args,
8161 		.rpc_resp = &res,
8162 	};
8163 	int status;
8164 
8165 	dprintk("%s: start\n", __func__);
8166 
8167 	bitmask[0] = nfs4_fattr_bitmap[0] | FATTR4_WORD0_FS_LOCATIONS;
8168 	bitmask[1] = nfs4_fattr_bitmap[1];
8169 
8170 	/* Ask for the fileid of the absent filesystem if mounted_on_fileid
8171 	 * is not supported */
8172 	if (NFS_SERVER(dir)->attr_bitmask[1] & FATTR4_WORD1_MOUNTED_ON_FILEID)
8173 		bitmask[0] &= ~FATTR4_WORD0_FILEID;
8174 	else
8175 		bitmask[1] &= ~FATTR4_WORD1_MOUNTED_ON_FILEID;
8176 
8177 	nfs_fattr_init(fs_locations->fattr);
8178 	fs_locations->server = server;
8179 	fs_locations->nlocations = 0;
8180 	status = nfs4_call_sync(client, server, &msg, &args.seq_args, &res.seq_res, 0);
8181 	dprintk("%s: returned status = %d\n", __func__, status);
8182 	return status;
8183 }
8184 
8185 int nfs4_proc_fs_locations(struct rpc_clnt *client, struct inode *dir,
8186 			   const struct qstr *name,
8187 			   struct nfs4_fs_locations *fs_locations,
8188 			   struct page *page)
8189 {
8190 	struct nfs4_exception exception = {
8191 		.interruptible = true,
8192 	};
8193 	int err;
8194 	do {
8195 		err = _nfs4_proc_fs_locations(client, dir, name,
8196 				fs_locations, page);
8197 		trace_nfs4_get_fs_locations(dir, name, err);
8198 		err = nfs4_handle_exception(NFS_SERVER(dir), err,
8199 				&exception);
8200 	} while (exception.retry);
8201 	return err;
8202 }
8203 
8204 /*
8205  * This operation also signals the server that this client is
8206  * performing migration recovery.  The server can stop returning
8207  * NFS4ERR_LEASE_MOVED to this client.  A RENEW operation is
8208  * appended to this compound to identify the client ID which is
8209  * performing recovery.
8210  */
8211 static int _nfs40_proc_get_locations(struct nfs_server *server,
8212 				     struct nfs_fh *fhandle,
8213 				     struct nfs4_fs_locations *locations,
8214 				     struct page *page, const struct cred *cred)
8215 {
8216 	struct rpc_clnt *clnt = server->client;
8217 	u32 bitmask[2] = {
8218 		[0] = FATTR4_WORD0_FSID | FATTR4_WORD0_FS_LOCATIONS,
8219 	};
8220 	struct nfs4_fs_locations_arg args = {
8221 		.clientid	= server->nfs_client->cl_clientid,
8222 		.fh		= fhandle,
8223 		.page		= page,
8224 		.bitmask	= bitmask,
8225 		.migration	= 1,		/* skip LOOKUP */
8226 		.renew		= 1,		/* append RENEW */
8227 	};
8228 	struct nfs4_fs_locations_res res = {
8229 		.fs_locations	= locations,
8230 		.migration	= 1,
8231 		.renew		= 1,
8232 	};
8233 	struct rpc_message msg = {
8234 		.rpc_proc	= &nfs4_procedures[NFSPROC4_CLNT_FS_LOCATIONS],
8235 		.rpc_argp	= &args,
8236 		.rpc_resp	= &res,
8237 		.rpc_cred	= cred,
8238 	};
8239 	unsigned long now = jiffies;
8240 	int status;
8241 
8242 	nfs_fattr_init(locations->fattr);
8243 	locations->server = server;
8244 	locations->nlocations = 0;
8245 
8246 	nfs4_init_sequence(&args.seq_args, &res.seq_res, 0, 1);
8247 	status = nfs4_call_sync_sequence(clnt, server, &msg,
8248 					&args.seq_args, &res.seq_res);
8249 	if (status)
8250 		return status;
8251 
8252 	renew_lease(server, now);
8253 	return 0;
8254 }
8255 
8256 #ifdef CONFIG_NFS_V4_1
8257 
8258 /*
8259  * This operation also signals the server that this client is
8260  * performing migration recovery.  The server can stop asserting
8261  * SEQ4_STATUS_LEASE_MOVED for this client.  The client ID
8262  * performing this operation is identified in the SEQUENCE
8263  * operation in this compound.
8264  *
8265  * When the client supports GETATTR(fs_locations_info), it can
8266  * be plumbed in here.
8267  */
8268 static int _nfs41_proc_get_locations(struct nfs_server *server,
8269 				     struct nfs_fh *fhandle,
8270 				     struct nfs4_fs_locations *locations,
8271 				     struct page *page, const struct cred *cred)
8272 {
8273 	struct rpc_clnt *clnt = server->client;
8274 	u32 bitmask[2] = {
8275 		[0] = FATTR4_WORD0_FSID | FATTR4_WORD0_FS_LOCATIONS,
8276 	};
8277 	struct nfs4_fs_locations_arg args = {
8278 		.fh		= fhandle,
8279 		.page		= page,
8280 		.bitmask	= bitmask,
8281 		.migration	= 1,		/* skip LOOKUP */
8282 	};
8283 	struct nfs4_fs_locations_res res = {
8284 		.fs_locations	= locations,
8285 		.migration	= 1,
8286 	};
8287 	struct rpc_message msg = {
8288 		.rpc_proc	= &nfs4_procedures[NFSPROC4_CLNT_FS_LOCATIONS],
8289 		.rpc_argp	= &args,
8290 		.rpc_resp	= &res,
8291 		.rpc_cred	= cred,
8292 	};
8293 	struct nfs4_call_sync_data data = {
8294 		.seq_server = server,
8295 		.seq_args = &args.seq_args,
8296 		.seq_res = &res.seq_res,
8297 	};
8298 	struct rpc_task_setup task_setup_data = {
8299 		.rpc_client = clnt,
8300 		.rpc_message = &msg,
8301 		.callback_ops = server->nfs_client->cl_mvops->call_sync_ops,
8302 		.callback_data = &data,
8303 		.flags = RPC_TASK_NO_ROUND_ROBIN,
8304 	};
8305 	int status;
8306 
8307 	nfs_fattr_init(locations->fattr);
8308 	locations->server = server;
8309 	locations->nlocations = 0;
8310 
8311 	nfs4_init_sequence(&args.seq_args, &res.seq_res, 0, 1);
8312 	status = nfs4_call_sync_custom(&task_setup_data);
8313 	if (status == NFS4_OK &&
8314 	    res.seq_res.sr_status_flags & SEQ4_STATUS_LEASE_MOVED)
8315 		status = -NFS4ERR_LEASE_MOVED;
8316 	return status;
8317 }
8318 
8319 #endif	/* CONFIG_NFS_V4_1 */
8320 
8321 /**
8322  * nfs4_proc_get_locations - discover locations for a migrated FSID
8323  * @server: pointer to nfs_server to process
8324  * @fhandle: pointer to the kernel NFS client file handle
8325  * @locations: result of query
8326  * @page: buffer
8327  * @cred: credential to use for this operation
8328  *
8329  * Returns NFS4_OK on success, a negative NFS4ERR status code if the
8330  * operation failed, or a negative errno if a local error occurred.
8331  *
8332  * On success, "locations" is filled in, but if the server has
8333  * no locations information, NFS_ATTR_FATTR_V4_LOCATIONS is not
8334  * asserted.
8335  *
8336  * -NFS4ERR_LEASE_MOVED is returned if the server still has leases
8337  * from this client that require migration recovery.
8338  */
8339 int nfs4_proc_get_locations(struct nfs_server *server,
8340 			    struct nfs_fh *fhandle,
8341 			    struct nfs4_fs_locations *locations,
8342 			    struct page *page, const struct cred *cred)
8343 {
8344 	struct nfs_client *clp = server->nfs_client;
8345 	const struct nfs4_mig_recovery_ops *ops =
8346 					clp->cl_mvops->mig_recovery_ops;
8347 	struct nfs4_exception exception = {
8348 		.interruptible = true,
8349 	};
8350 	int status;
8351 
8352 	dprintk("%s: FSID %llx:%llx on \"%s\"\n", __func__,
8353 		(unsigned long long)server->fsid.major,
8354 		(unsigned long long)server->fsid.minor,
8355 		clp->cl_hostname);
8356 	nfs_display_fhandle(fhandle, __func__);
8357 
8358 	do {
8359 		status = ops->get_locations(server, fhandle, locations, page,
8360 					    cred);
8361 		if (status != -NFS4ERR_DELAY)
8362 			break;
8363 		nfs4_handle_exception(server, status, &exception);
8364 	} while (exception.retry);
8365 	return status;
8366 }
8367 
8368 /*
8369  * This operation also signals the server that this client is
8370  * performing "lease moved" recovery.  The server can stop
8371  * returning NFS4ERR_LEASE_MOVED to this client.  A RENEW operation
8372  * is appended to this compound to identify the client ID which is
8373  * performing recovery.
8374  */
8375 static int _nfs40_proc_fsid_present(struct inode *inode, const struct cred *cred)
8376 {
8377 	struct nfs_server *server = NFS_SERVER(inode);
8378 	struct nfs_client *clp = NFS_SERVER(inode)->nfs_client;
8379 	struct rpc_clnt *clnt = server->client;
8380 	struct nfs4_fsid_present_arg args = {
8381 		.fh		= NFS_FH(inode),
8382 		.clientid	= clp->cl_clientid,
8383 		.renew		= 1,		/* append RENEW */
8384 	};
8385 	struct nfs4_fsid_present_res res = {
8386 		.renew		= 1,
8387 	};
8388 	struct rpc_message msg = {
8389 		.rpc_proc	= &nfs4_procedures[NFSPROC4_CLNT_FSID_PRESENT],
8390 		.rpc_argp	= &args,
8391 		.rpc_resp	= &res,
8392 		.rpc_cred	= cred,
8393 	};
8394 	unsigned long now = jiffies;
8395 	int status;
8396 
8397 	res.fh = nfs_alloc_fhandle();
8398 	if (res.fh == NULL)
8399 		return -ENOMEM;
8400 
8401 	nfs4_init_sequence(&args.seq_args, &res.seq_res, 0, 1);
8402 	status = nfs4_call_sync_sequence(clnt, server, &msg,
8403 						&args.seq_args, &res.seq_res);
8404 	nfs_free_fhandle(res.fh);
8405 	if (status)
8406 		return status;
8407 
8408 	do_renew_lease(clp, now);
8409 	return 0;
8410 }
8411 
8412 #ifdef CONFIG_NFS_V4_1
8413 
8414 /*
8415  * This operation also signals the server that this client is
8416  * performing "lease moved" recovery.  The server can stop asserting
8417  * SEQ4_STATUS_LEASE_MOVED for this client.  The client ID performing
8418  * this operation is identified in the SEQUENCE operation in this
8419  * compound.
8420  */
8421 static int _nfs41_proc_fsid_present(struct inode *inode, const struct cred *cred)
8422 {
8423 	struct nfs_server *server = NFS_SERVER(inode);
8424 	struct rpc_clnt *clnt = server->client;
8425 	struct nfs4_fsid_present_arg args = {
8426 		.fh		= NFS_FH(inode),
8427 	};
8428 	struct nfs4_fsid_present_res res = {
8429 	};
8430 	struct rpc_message msg = {
8431 		.rpc_proc	= &nfs4_procedures[NFSPROC4_CLNT_FSID_PRESENT],
8432 		.rpc_argp	= &args,
8433 		.rpc_resp	= &res,
8434 		.rpc_cred	= cred,
8435 	};
8436 	int status;
8437 
8438 	res.fh = nfs_alloc_fhandle();
8439 	if (res.fh == NULL)
8440 		return -ENOMEM;
8441 
8442 	nfs4_init_sequence(&args.seq_args, &res.seq_res, 0, 1);
8443 	status = nfs4_call_sync_sequence(clnt, server, &msg,
8444 						&args.seq_args, &res.seq_res);
8445 	nfs_free_fhandle(res.fh);
8446 	if (status == NFS4_OK &&
8447 	    res.seq_res.sr_status_flags & SEQ4_STATUS_LEASE_MOVED)
8448 		status = -NFS4ERR_LEASE_MOVED;
8449 	return status;
8450 }
8451 
8452 #endif	/* CONFIG_NFS_V4_1 */
8453 
8454 /**
8455  * nfs4_proc_fsid_present - Is this FSID present or absent on server?
8456  * @inode: inode on FSID to check
8457  * @cred: credential to use for this operation
8458  *
8459  * Server indicates whether the FSID is present, moved, or not
8460  * recognized.  This operation is necessary to clear a LEASE_MOVED
8461  * condition for this client ID.
8462  *
8463  * Returns NFS4_OK if the FSID is present on this server,
8464  * -NFS4ERR_MOVED if the FSID is no longer present, a negative
8465  *  NFS4ERR code if some error occurred on the server, or a
8466  *  negative errno if a local failure occurred.
8467  */
8468 int nfs4_proc_fsid_present(struct inode *inode, const struct cred *cred)
8469 {
8470 	struct nfs_server *server = NFS_SERVER(inode);
8471 	struct nfs_client *clp = server->nfs_client;
8472 	const struct nfs4_mig_recovery_ops *ops =
8473 					clp->cl_mvops->mig_recovery_ops;
8474 	struct nfs4_exception exception = {
8475 		.interruptible = true,
8476 	};
8477 	int status;
8478 
8479 	dprintk("%s: FSID %llx:%llx on \"%s\"\n", __func__,
8480 		(unsigned long long)server->fsid.major,
8481 		(unsigned long long)server->fsid.minor,
8482 		clp->cl_hostname);
8483 	nfs_display_fhandle(NFS_FH(inode), __func__);
8484 
8485 	do {
8486 		status = ops->fsid_present(inode, cred);
8487 		if (status != -NFS4ERR_DELAY)
8488 			break;
8489 		nfs4_handle_exception(server, status, &exception);
8490 	} while (exception.retry);
8491 	return status;
8492 }
8493 
8494 /*
8495  * If 'use_integrity' is true and the state managment nfs_client
8496  * cl_rpcclient is using krb5i/p, use the integrity protected cl_rpcclient
8497  * and the machine credential as per RFC3530bis and RFC5661 Security
8498  * Considerations sections. Otherwise, just use the user cred with the
8499  * filesystem's rpc_client.
8500  */
8501 static int _nfs4_proc_secinfo(struct inode *dir, const struct qstr *name, struct nfs4_secinfo_flavors *flavors, bool use_integrity)
8502 {
8503 	int status;
8504 	struct rpc_clnt *clnt = NFS_SERVER(dir)->client;
8505 	struct nfs_client *clp = NFS_SERVER(dir)->nfs_client;
8506 	struct nfs4_secinfo_arg args = {
8507 		.dir_fh = NFS_FH(dir),
8508 		.name   = name,
8509 	};
8510 	struct nfs4_secinfo_res res = {
8511 		.flavors     = flavors,
8512 	};
8513 	struct rpc_message msg = {
8514 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_SECINFO],
8515 		.rpc_argp = &args,
8516 		.rpc_resp = &res,
8517 	};
8518 	struct nfs4_call_sync_data data = {
8519 		.seq_server = NFS_SERVER(dir),
8520 		.seq_args = &args.seq_args,
8521 		.seq_res = &res.seq_res,
8522 	};
8523 	struct rpc_task_setup task_setup = {
8524 		.rpc_client = clnt,
8525 		.rpc_message = &msg,
8526 		.callback_ops = clp->cl_mvops->call_sync_ops,
8527 		.callback_data = &data,
8528 		.flags = RPC_TASK_NO_ROUND_ROBIN,
8529 	};
8530 	const struct cred *cred = NULL;
8531 
8532 	if (use_integrity) {
8533 		clnt = clp->cl_rpcclient;
8534 		task_setup.rpc_client = clnt;
8535 
8536 		cred = nfs4_get_clid_cred(clp);
8537 		msg.rpc_cred = cred;
8538 	}
8539 
8540 	dprintk("NFS call  secinfo %s\n", name->name);
8541 
8542 	nfs4_state_protect(clp, NFS_SP4_MACH_CRED_SECINFO, &clnt, &msg);
8543 	nfs4_init_sequence(&args.seq_args, &res.seq_res, 0, 0);
8544 	status = nfs4_call_sync_custom(&task_setup);
8545 
8546 	dprintk("NFS reply  secinfo: %d\n", status);
8547 
8548 	put_cred(cred);
8549 	return status;
8550 }
8551 
8552 int nfs4_proc_secinfo(struct inode *dir, const struct qstr *name,
8553 		      struct nfs4_secinfo_flavors *flavors)
8554 {
8555 	struct nfs4_exception exception = {
8556 		.interruptible = true,
8557 	};
8558 	int err;
8559 	do {
8560 		err = -NFS4ERR_WRONGSEC;
8561 
8562 		/* try to use integrity protection with machine cred */
8563 		if (_nfs4_is_integrity_protected(NFS_SERVER(dir)->nfs_client))
8564 			err = _nfs4_proc_secinfo(dir, name, flavors, true);
8565 
8566 		/*
8567 		 * if unable to use integrity protection, or SECINFO with
8568 		 * integrity protection returns NFS4ERR_WRONGSEC (which is
8569 		 * disallowed by spec, but exists in deployed servers) use
8570 		 * the current filesystem's rpc_client and the user cred.
8571 		 */
8572 		if (err == -NFS4ERR_WRONGSEC)
8573 			err = _nfs4_proc_secinfo(dir, name, flavors, false);
8574 
8575 		trace_nfs4_secinfo(dir, name, err);
8576 		err = nfs4_handle_exception(NFS_SERVER(dir), err,
8577 				&exception);
8578 	} while (exception.retry);
8579 	return err;
8580 }
8581 
8582 #ifdef CONFIG_NFS_V4_1
8583 /*
8584  * Check the exchange flags returned by the server for invalid flags, having
8585  * both PNFS and NON_PNFS flags set, and not having one of NON_PNFS, PNFS, or
8586  * DS flags set.
8587  */
8588 static int nfs4_check_cl_exchange_flags(u32 flags, u32 version)
8589 {
8590 	if (version >= 2 && (flags & ~EXCHGID4_2_FLAG_MASK_R))
8591 		goto out_inval;
8592 	else if (version < 2 && (flags & ~EXCHGID4_FLAG_MASK_R))
8593 		goto out_inval;
8594 	if ((flags & EXCHGID4_FLAG_USE_PNFS_MDS) &&
8595 	    (flags & EXCHGID4_FLAG_USE_NON_PNFS))
8596 		goto out_inval;
8597 	if (!(flags & (EXCHGID4_FLAG_MASK_PNFS)))
8598 		goto out_inval;
8599 	return NFS_OK;
8600 out_inval:
8601 	return -NFS4ERR_INVAL;
8602 }
8603 
8604 static bool
8605 nfs41_same_server_scope(struct nfs41_server_scope *a,
8606 			struct nfs41_server_scope *b)
8607 {
8608 	if (a->server_scope_sz != b->server_scope_sz)
8609 		return false;
8610 	return memcmp(a->server_scope, b->server_scope, a->server_scope_sz) == 0;
8611 }
8612 
8613 static void
8614 nfs4_bind_one_conn_to_session_done(struct rpc_task *task, void *calldata)
8615 {
8616 	struct nfs41_bind_conn_to_session_args *args = task->tk_msg.rpc_argp;
8617 	struct nfs41_bind_conn_to_session_res *res = task->tk_msg.rpc_resp;
8618 	struct nfs_client *clp = args->client;
8619 
8620 	switch (task->tk_status) {
8621 	case -NFS4ERR_BADSESSION:
8622 	case -NFS4ERR_DEADSESSION:
8623 		nfs4_schedule_session_recovery(clp->cl_session,
8624 				task->tk_status);
8625 		return;
8626 	}
8627 	if (args->dir == NFS4_CDFC4_FORE_OR_BOTH &&
8628 			res->dir != NFS4_CDFS4_BOTH) {
8629 		rpc_task_close_connection(task);
8630 		if (args->retries++ < MAX_BIND_CONN_TO_SESSION_RETRIES)
8631 			rpc_restart_call(task);
8632 	}
8633 }
8634 
8635 static const struct rpc_call_ops nfs4_bind_one_conn_to_session_ops = {
8636 	.rpc_call_done =  nfs4_bind_one_conn_to_session_done,
8637 };
8638 
8639 /*
8640  * nfs4_proc_bind_one_conn_to_session()
8641  *
8642  * The 4.1 client currently uses the same TCP connection for the
8643  * fore and backchannel.
8644  */
8645 static
8646 int nfs4_proc_bind_one_conn_to_session(struct rpc_clnt *clnt,
8647 		struct rpc_xprt *xprt,
8648 		struct nfs_client *clp,
8649 		const struct cred *cred)
8650 {
8651 	int status;
8652 	struct nfs41_bind_conn_to_session_args args = {
8653 		.client = clp,
8654 		.dir = NFS4_CDFC4_FORE_OR_BOTH,
8655 		.retries = 0,
8656 	};
8657 	struct nfs41_bind_conn_to_session_res res;
8658 	struct rpc_message msg = {
8659 		.rpc_proc =
8660 			&nfs4_procedures[NFSPROC4_CLNT_BIND_CONN_TO_SESSION],
8661 		.rpc_argp = &args,
8662 		.rpc_resp = &res,
8663 		.rpc_cred = cred,
8664 	};
8665 	struct rpc_task_setup task_setup_data = {
8666 		.rpc_client = clnt,
8667 		.rpc_xprt = xprt,
8668 		.callback_ops = &nfs4_bind_one_conn_to_session_ops,
8669 		.rpc_message = &msg,
8670 		.flags = RPC_TASK_TIMEOUT,
8671 	};
8672 	struct rpc_task *task;
8673 
8674 	nfs4_copy_sessionid(&args.sessionid, &clp->cl_session->sess_id);
8675 	if (!(clp->cl_session->flags & SESSION4_BACK_CHAN))
8676 		args.dir = NFS4_CDFC4_FORE;
8677 
8678 	/* Do not set the backchannel flag unless this is clnt->cl_xprt */
8679 	if (xprt != rcu_access_pointer(clnt->cl_xprt))
8680 		args.dir = NFS4_CDFC4_FORE;
8681 
8682 	task = rpc_run_task(&task_setup_data);
8683 	if (!IS_ERR(task)) {
8684 		status = task->tk_status;
8685 		rpc_put_task(task);
8686 	} else
8687 		status = PTR_ERR(task);
8688 	trace_nfs4_bind_conn_to_session(clp, status);
8689 	if (status == 0) {
8690 		if (memcmp(res.sessionid.data,
8691 		    clp->cl_session->sess_id.data, NFS4_MAX_SESSIONID_LEN)) {
8692 			dprintk("NFS: %s: Session ID mismatch\n", __func__);
8693 			return -EIO;
8694 		}
8695 		if ((res.dir & args.dir) != res.dir || res.dir == 0) {
8696 			dprintk("NFS: %s: Unexpected direction from server\n",
8697 				__func__);
8698 			return -EIO;
8699 		}
8700 		if (res.use_conn_in_rdma_mode != args.use_conn_in_rdma_mode) {
8701 			dprintk("NFS: %s: Server returned RDMA mode = true\n",
8702 				__func__);
8703 			return -EIO;
8704 		}
8705 	}
8706 
8707 	return status;
8708 }
8709 
8710 struct rpc_bind_conn_calldata {
8711 	struct nfs_client *clp;
8712 	const struct cred *cred;
8713 };
8714 
8715 static int
8716 nfs4_proc_bind_conn_to_session_callback(struct rpc_clnt *clnt,
8717 		struct rpc_xprt *xprt,
8718 		void *calldata)
8719 {
8720 	struct rpc_bind_conn_calldata *p = calldata;
8721 
8722 	return nfs4_proc_bind_one_conn_to_session(clnt, xprt, p->clp, p->cred);
8723 }
8724 
8725 int nfs4_proc_bind_conn_to_session(struct nfs_client *clp, const struct cred *cred)
8726 {
8727 	struct rpc_bind_conn_calldata data = {
8728 		.clp = clp,
8729 		.cred = cred,
8730 	};
8731 	return rpc_clnt_iterate_for_each_xprt(clp->cl_rpcclient,
8732 			nfs4_proc_bind_conn_to_session_callback, &data);
8733 }
8734 
8735 /*
8736  * Minimum set of SP4_MACH_CRED operations from RFC 5661 in the enforce map
8737  * and operations we'd like to see to enable certain features in the allow map
8738  */
8739 static const struct nfs41_state_protection nfs4_sp4_mach_cred_request = {
8740 	.how = SP4_MACH_CRED,
8741 	.enforce.u.words = {
8742 		[1] = 1 << (OP_BIND_CONN_TO_SESSION - 32) |
8743 		      1 << (OP_EXCHANGE_ID - 32) |
8744 		      1 << (OP_CREATE_SESSION - 32) |
8745 		      1 << (OP_DESTROY_SESSION - 32) |
8746 		      1 << (OP_DESTROY_CLIENTID - 32)
8747 	},
8748 	.allow.u.words = {
8749 		[0] = 1 << (OP_CLOSE) |
8750 		      1 << (OP_OPEN_DOWNGRADE) |
8751 		      1 << (OP_LOCKU) |
8752 		      1 << (OP_DELEGRETURN) |
8753 		      1 << (OP_COMMIT),
8754 		[1] = 1 << (OP_SECINFO - 32) |
8755 		      1 << (OP_SECINFO_NO_NAME - 32) |
8756 		      1 << (OP_LAYOUTRETURN - 32) |
8757 		      1 << (OP_TEST_STATEID - 32) |
8758 		      1 << (OP_FREE_STATEID - 32) |
8759 		      1 << (OP_WRITE - 32)
8760 	}
8761 };
8762 
8763 /*
8764  * Select the state protection mode for client `clp' given the server results
8765  * from exchange_id in `sp'.
8766  *
8767  * Returns 0 on success, negative errno otherwise.
8768  */
8769 static int nfs4_sp4_select_mode(struct nfs_client *clp,
8770 				 struct nfs41_state_protection *sp)
8771 {
8772 	static const u32 supported_enforce[NFS4_OP_MAP_NUM_WORDS] = {
8773 		[1] = 1 << (OP_BIND_CONN_TO_SESSION - 32) |
8774 		      1 << (OP_EXCHANGE_ID - 32) |
8775 		      1 << (OP_CREATE_SESSION - 32) |
8776 		      1 << (OP_DESTROY_SESSION - 32) |
8777 		      1 << (OP_DESTROY_CLIENTID - 32)
8778 	};
8779 	unsigned long flags = 0;
8780 	unsigned int i;
8781 	int ret = 0;
8782 
8783 	if (sp->how == SP4_MACH_CRED) {
8784 		/* Print state protect result */
8785 		dfprintk(MOUNT, "Server SP4_MACH_CRED support:\n");
8786 		for (i = 0; i <= LAST_NFS4_OP; i++) {
8787 			if (test_bit(i, sp->enforce.u.longs))
8788 				dfprintk(MOUNT, "  enforce op %d\n", i);
8789 			if (test_bit(i, sp->allow.u.longs))
8790 				dfprintk(MOUNT, "  allow op %d\n", i);
8791 		}
8792 
8793 		/* make sure nothing is on enforce list that isn't supported */
8794 		for (i = 0; i < NFS4_OP_MAP_NUM_WORDS; i++) {
8795 			if (sp->enforce.u.words[i] & ~supported_enforce[i]) {
8796 				dfprintk(MOUNT, "sp4_mach_cred: disabled\n");
8797 				ret = -EINVAL;
8798 				goto out;
8799 			}
8800 		}
8801 
8802 		/*
8803 		 * Minimal mode - state operations are allowed to use machine
8804 		 * credential.  Note this already happens by default, so the
8805 		 * client doesn't have to do anything more than the negotiation.
8806 		 *
8807 		 * NOTE: we don't care if EXCHANGE_ID is in the list -
8808 		 *       we're already using the machine cred for exchange_id
8809 		 *       and will never use a different cred.
8810 		 */
8811 		if (test_bit(OP_BIND_CONN_TO_SESSION, sp->enforce.u.longs) &&
8812 		    test_bit(OP_CREATE_SESSION, sp->enforce.u.longs) &&
8813 		    test_bit(OP_DESTROY_SESSION, sp->enforce.u.longs) &&
8814 		    test_bit(OP_DESTROY_CLIENTID, sp->enforce.u.longs)) {
8815 			dfprintk(MOUNT, "sp4_mach_cred:\n");
8816 			dfprintk(MOUNT, "  minimal mode enabled\n");
8817 			__set_bit(NFS_SP4_MACH_CRED_MINIMAL, &flags);
8818 		} else {
8819 			dfprintk(MOUNT, "sp4_mach_cred: disabled\n");
8820 			ret = -EINVAL;
8821 			goto out;
8822 		}
8823 
8824 		if (test_bit(OP_CLOSE, sp->allow.u.longs) &&
8825 		    test_bit(OP_OPEN_DOWNGRADE, sp->allow.u.longs) &&
8826 		    test_bit(OP_DELEGRETURN, sp->allow.u.longs) &&
8827 		    test_bit(OP_LOCKU, sp->allow.u.longs)) {
8828 			dfprintk(MOUNT, "  cleanup mode enabled\n");
8829 			__set_bit(NFS_SP4_MACH_CRED_CLEANUP, &flags);
8830 		}
8831 
8832 		if (test_bit(OP_LAYOUTRETURN, sp->allow.u.longs)) {
8833 			dfprintk(MOUNT, "  pnfs cleanup mode enabled\n");
8834 			__set_bit(NFS_SP4_MACH_CRED_PNFS_CLEANUP, &flags);
8835 		}
8836 
8837 		if (test_bit(OP_SECINFO, sp->allow.u.longs) &&
8838 		    test_bit(OP_SECINFO_NO_NAME, sp->allow.u.longs)) {
8839 			dfprintk(MOUNT, "  secinfo mode enabled\n");
8840 			__set_bit(NFS_SP4_MACH_CRED_SECINFO, &flags);
8841 		}
8842 
8843 		if (test_bit(OP_TEST_STATEID, sp->allow.u.longs) &&
8844 		    test_bit(OP_FREE_STATEID, sp->allow.u.longs)) {
8845 			dfprintk(MOUNT, "  stateid mode enabled\n");
8846 			__set_bit(NFS_SP4_MACH_CRED_STATEID, &flags);
8847 		}
8848 
8849 		if (test_bit(OP_WRITE, sp->allow.u.longs)) {
8850 			dfprintk(MOUNT, "  write mode enabled\n");
8851 			__set_bit(NFS_SP4_MACH_CRED_WRITE, &flags);
8852 		}
8853 
8854 		if (test_bit(OP_COMMIT, sp->allow.u.longs)) {
8855 			dfprintk(MOUNT, "  commit mode enabled\n");
8856 			__set_bit(NFS_SP4_MACH_CRED_COMMIT, &flags);
8857 		}
8858 	}
8859 out:
8860 	clp->cl_sp4_flags = flags;
8861 	return ret;
8862 }
8863 
8864 struct nfs41_exchange_id_data {
8865 	struct nfs41_exchange_id_res res;
8866 	struct nfs41_exchange_id_args args;
8867 };
8868 
8869 static void nfs4_exchange_id_release(void *data)
8870 {
8871 	struct nfs41_exchange_id_data *cdata =
8872 					(struct nfs41_exchange_id_data *)data;
8873 
8874 	nfs_put_client(cdata->args.client);
8875 	kfree(cdata->res.impl_id);
8876 	kfree(cdata->res.server_scope);
8877 	kfree(cdata->res.server_owner);
8878 	kfree(cdata);
8879 }
8880 
8881 static const struct rpc_call_ops nfs4_exchange_id_call_ops = {
8882 	.rpc_release = nfs4_exchange_id_release,
8883 };
8884 
8885 /*
8886  * _nfs4_proc_exchange_id()
8887  *
8888  * Wrapper for EXCHANGE_ID operation.
8889  */
8890 static struct rpc_task *
8891 nfs4_run_exchange_id(struct nfs_client *clp, const struct cred *cred,
8892 			u32 sp4_how, struct rpc_xprt *xprt)
8893 {
8894 	struct rpc_message msg = {
8895 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_EXCHANGE_ID],
8896 		.rpc_cred = cred,
8897 	};
8898 	struct rpc_task_setup task_setup_data = {
8899 		.rpc_client = clp->cl_rpcclient,
8900 		.callback_ops = &nfs4_exchange_id_call_ops,
8901 		.rpc_message = &msg,
8902 		.flags = RPC_TASK_TIMEOUT | RPC_TASK_NO_ROUND_ROBIN,
8903 	};
8904 	struct nfs41_exchange_id_data *calldata;
8905 	int status;
8906 
8907 	if (!refcount_inc_not_zero(&clp->cl_count))
8908 		return ERR_PTR(-EIO);
8909 
8910 	status = -ENOMEM;
8911 	calldata = kzalloc(sizeof(*calldata), GFP_NOFS);
8912 	if (!calldata)
8913 		goto out;
8914 
8915 	nfs4_init_boot_verifier(clp, &calldata->args.verifier);
8916 
8917 	status = nfs4_init_uniform_client_string(clp);
8918 	if (status)
8919 		goto out_calldata;
8920 
8921 	calldata->res.server_owner = kzalloc(sizeof(struct nfs41_server_owner),
8922 						GFP_NOFS);
8923 	status = -ENOMEM;
8924 	if (unlikely(calldata->res.server_owner == NULL))
8925 		goto out_calldata;
8926 
8927 	calldata->res.server_scope = kzalloc(sizeof(struct nfs41_server_scope),
8928 					GFP_NOFS);
8929 	if (unlikely(calldata->res.server_scope == NULL))
8930 		goto out_server_owner;
8931 
8932 	calldata->res.impl_id = kzalloc(sizeof(struct nfs41_impl_id), GFP_NOFS);
8933 	if (unlikely(calldata->res.impl_id == NULL))
8934 		goto out_server_scope;
8935 
8936 	switch (sp4_how) {
8937 	case SP4_NONE:
8938 		calldata->args.state_protect.how = SP4_NONE;
8939 		break;
8940 
8941 	case SP4_MACH_CRED:
8942 		calldata->args.state_protect = nfs4_sp4_mach_cred_request;
8943 		break;
8944 
8945 	default:
8946 		/* unsupported! */
8947 		WARN_ON_ONCE(1);
8948 		status = -EINVAL;
8949 		goto out_impl_id;
8950 	}
8951 	if (xprt) {
8952 		task_setup_data.rpc_xprt = xprt;
8953 		task_setup_data.flags |= RPC_TASK_SOFTCONN;
8954 		memcpy(calldata->args.verifier.data, clp->cl_confirm.data,
8955 				sizeof(calldata->args.verifier.data));
8956 	}
8957 	calldata->args.client = clp;
8958 	calldata->args.flags = EXCHGID4_FLAG_SUPP_MOVED_REFER |
8959 	EXCHGID4_FLAG_BIND_PRINC_STATEID;
8960 #ifdef CONFIG_NFS_V4_1_MIGRATION
8961 	calldata->args.flags |= EXCHGID4_FLAG_SUPP_MOVED_MIGR;
8962 #endif
8963 	if (test_bit(NFS_CS_PNFS, &clp->cl_flags))
8964 		calldata->args.flags |= EXCHGID4_FLAG_USE_PNFS_DS;
8965 	msg.rpc_argp = &calldata->args;
8966 	msg.rpc_resp = &calldata->res;
8967 	task_setup_data.callback_data = calldata;
8968 
8969 	return rpc_run_task(&task_setup_data);
8970 
8971 out_impl_id:
8972 	kfree(calldata->res.impl_id);
8973 out_server_scope:
8974 	kfree(calldata->res.server_scope);
8975 out_server_owner:
8976 	kfree(calldata->res.server_owner);
8977 out_calldata:
8978 	kfree(calldata);
8979 out:
8980 	nfs_put_client(clp);
8981 	return ERR_PTR(status);
8982 }
8983 
8984 /*
8985  * _nfs4_proc_exchange_id()
8986  *
8987  * Wrapper for EXCHANGE_ID operation.
8988  */
8989 static int _nfs4_proc_exchange_id(struct nfs_client *clp, const struct cred *cred,
8990 			u32 sp4_how)
8991 {
8992 	struct rpc_task *task;
8993 	struct nfs41_exchange_id_args *argp;
8994 	struct nfs41_exchange_id_res *resp;
8995 	unsigned long now = jiffies;
8996 	int status;
8997 
8998 	task = nfs4_run_exchange_id(clp, cred, sp4_how, NULL);
8999 	if (IS_ERR(task))
9000 		return PTR_ERR(task);
9001 
9002 	argp = task->tk_msg.rpc_argp;
9003 	resp = task->tk_msg.rpc_resp;
9004 	status = task->tk_status;
9005 	if (status  != 0)
9006 		goto out;
9007 
9008 	status = nfs4_check_cl_exchange_flags(resp->flags,
9009 			clp->cl_mvops->minor_version);
9010 	if (status  != 0)
9011 		goto out;
9012 
9013 	status = nfs4_sp4_select_mode(clp, &resp->state_protect);
9014 	if (status != 0)
9015 		goto out;
9016 
9017 	do_renew_lease(clp, now);
9018 
9019 	clp->cl_clientid = resp->clientid;
9020 	clp->cl_exchange_flags = resp->flags;
9021 	clp->cl_seqid = resp->seqid;
9022 	/* Client ID is not confirmed */
9023 	if (!(resp->flags & EXCHGID4_FLAG_CONFIRMED_R))
9024 		clear_bit(NFS4_SESSION_ESTABLISHED,
9025 			  &clp->cl_session->session_state);
9026 
9027 	if (clp->cl_serverscope != NULL &&
9028 	    !nfs41_same_server_scope(clp->cl_serverscope,
9029 				resp->server_scope)) {
9030 		dprintk("%s: server_scope mismatch detected\n",
9031 			__func__);
9032 		set_bit(NFS4CLNT_SERVER_SCOPE_MISMATCH, &clp->cl_state);
9033 	}
9034 
9035 	swap(clp->cl_serverowner, resp->server_owner);
9036 	swap(clp->cl_serverscope, resp->server_scope);
9037 	swap(clp->cl_implid, resp->impl_id);
9038 
9039 	/* Save the EXCHANGE_ID verifier session trunk tests */
9040 	memcpy(clp->cl_confirm.data, argp->verifier.data,
9041 	       sizeof(clp->cl_confirm.data));
9042 out:
9043 	trace_nfs4_exchange_id(clp, status);
9044 	rpc_put_task(task);
9045 	return status;
9046 }
9047 
9048 /*
9049  * nfs4_proc_exchange_id()
9050  *
9051  * Returns zero, a negative errno, or a negative NFS4ERR status code.
9052  *
9053  * Since the clientid has expired, all compounds using sessions
9054  * associated with the stale clientid will be returning
9055  * NFS4ERR_BADSESSION in the sequence operation, and will therefore
9056  * be in some phase of session reset.
9057  *
9058  * Will attempt to negotiate SP4_MACH_CRED if krb5i / krb5p auth is used.
9059  */
9060 int nfs4_proc_exchange_id(struct nfs_client *clp, const struct cred *cred)
9061 {
9062 	rpc_authflavor_t authflavor = clp->cl_rpcclient->cl_auth->au_flavor;
9063 	int status;
9064 
9065 	/* try SP4_MACH_CRED if krb5i/p	*/
9066 	if (authflavor == RPC_AUTH_GSS_KRB5I ||
9067 	    authflavor == RPC_AUTH_GSS_KRB5P) {
9068 		status = _nfs4_proc_exchange_id(clp, cred, SP4_MACH_CRED);
9069 		if (!status)
9070 			return 0;
9071 	}
9072 
9073 	/* try SP4_NONE */
9074 	return _nfs4_proc_exchange_id(clp, cred, SP4_NONE);
9075 }
9076 
9077 /**
9078  * nfs4_test_session_trunk
9079  *
9080  * This is an add_xprt_test() test function called from
9081  * rpc_clnt_setup_test_and_add_xprt.
9082  *
9083  * The rpc_xprt_switch is referrenced by rpc_clnt_setup_test_and_add_xprt
9084  * and is dereferrenced in nfs4_exchange_id_release
9085  *
9086  * Upon success, add the new transport to the rpc_clnt
9087  *
9088  * @clnt: struct rpc_clnt to get new transport
9089  * @xprt: the rpc_xprt to test
9090  * @data: call data for _nfs4_proc_exchange_id.
9091  */
9092 void nfs4_test_session_trunk(struct rpc_clnt *clnt, struct rpc_xprt *xprt,
9093 			    void *data)
9094 {
9095 	struct nfs4_add_xprt_data *adata = data;
9096 	struct rpc_task *task;
9097 	int status;
9098 
9099 	u32 sp4_how;
9100 
9101 	dprintk("--> %s try %s\n", __func__,
9102 		xprt->address_strings[RPC_DISPLAY_ADDR]);
9103 
9104 	sp4_how = (adata->clp->cl_sp4_flags == 0 ? SP4_NONE : SP4_MACH_CRED);
9105 
9106 try_again:
9107 	/* Test connection for session trunking. Async exchange_id call */
9108 	task = nfs4_run_exchange_id(adata->clp, adata->cred, sp4_how, xprt);
9109 	if (IS_ERR(task))
9110 		return;
9111 
9112 	status = task->tk_status;
9113 	if (status == 0) {
9114 		status = nfs4_detect_session_trunking(adata->clp,
9115 				task->tk_msg.rpc_resp, xprt);
9116 		trace_nfs4_trunked_exchange_id(adata->clp,
9117 			xprt->address_strings[RPC_DISPLAY_ADDR], status);
9118 	}
9119 	if (status == 0)
9120 		rpc_clnt_xprt_switch_add_xprt(clnt, xprt);
9121 	else if (status != -NFS4ERR_DELAY && rpc_clnt_xprt_switch_has_addr(clnt,
9122 				(struct sockaddr *)&xprt->addr))
9123 		rpc_clnt_xprt_switch_remove_xprt(clnt, xprt);
9124 
9125 	rpc_put_task(task);
9126 	if (status == -NFS4ERR_DELAY) {
9127 		ssleep(1);
9128 		goto try_again;
9129 	}
9130 }
9131 EXPORT_SYMBOL_GPL(nfs4_test_session_trunk);
9132 
9133 static int _nfs4_proc_destroy_clientid(struct nfs_client *clp,
9134 		const struct cred *cred)
9135 {
9136 	struct rpc_message msg = {
9137 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_DESTROY_CLIENTID],
9138 		.rpc_argp = clp,
9139 		.rpc_cred = cred,
9140 	};
9141 	int status;
9142 
9143 	status = rpc_call_sync(clp->cl_rpcclient, &msg,
9144 			       RPC_TASK_TIMEOUT | RPC_TASK_NO_ROUND_ROBIN);
9145 	trace_nfs4_destroy_clientid(clp, status);
9146 	if (status)
9147 		dprintk("NFS: Got error %d from the server %s on "
9148 			"DESTROY_CLIENTID.", status, clp->cl_hostname);
9149 	return status;
9150 }
9151 
9152 static int nfs4_proc_destroy_clientid(struct nfs_client *clp,
9153 		const struct cred *cred)
9154 {
9155 	unsigned int loop;
9156 	int ret;
9157 
9158 	for (loop = NFS4_MAX_LOOP_ON_RECOVER; loop != 0; loop--) {
9159 		ret = _nfs4_proc_destroy_clientid(clp, cred);
9160 		switch (ret) {
9161 		case -NFS4ERR_DELAY:
9162 		case -NFS4ERR_CLIENTID_BUSY:
9163 			ssleep(1);
9164 			break;
9165 		default:
9166 			return ret;
9167 		}
9168 	}
9169 	return 0;
9170 }
9171 
9172 int nfs4_destroy_clientid(struct nfs_client *clp)
9173 {
9174 	const struct cred *cred;
9175 	int ret = 0;
9176 
9177 	if (clp->cl_mvops->minor_version < 1)
9178 		goto out;
9179 	if (clp->cl_exchange_flags == 0)
9180 		goto out;
9181 	if (clp->cl_preserve_clid)
9182 		goto out;
9183 	cred = nfs4_get_clid_cred(clp);
9184 	ret = nfs4_proc_destroy_clientid(clp, cred);
9185 	put_cred(cred);
9186 	switch (ret) {
9187 	case 0:
9188 	case -NFS4ERR_STALE_CLIENTID:
9189 		clp->cl_exchange_flags = 0;
9190 	}
9191 out:
9192 	return ret;
9193 }
9194 
9195 #endif /* CONFIG_NFS_V4_1 */
9196 
9197 struct nfs4_get_lease_time_data {
9198 	struct nfs4_get_lease_time_args *args;
9199 	struct nfs4_get_lease_time_res *res;
9200 	struct nfs_client *clp;
9201 };
9202 
9203 static void nfs4_get_lease_time_prepare(struct rpc_task *task,
9204 					void *calldata)
9205 {
9206 	struct nfs4_get_lease_time_data *data =
9207 			(struct nfs4_get_lease_time_data *)calldata;
9208 
9209 	/* just setup sequence, do not trigger session recovery
9210 	   since we're invoked within one */
9211 	nfs4_setup_sequence(data->clp,
9212 			&data->args->la_seq_args,
9213 			&data->res->lr_seq_res,
9214 			task);
9215 }
9216 
9217 /*
9218  * Called from nfs4_state_manager thread for session setup, so don't recover
9219  * from sequence operation or clientid errors.
9220  */
9221 static void nfs4_get_lease_time_done(struct rpc_task *task, void *calldata)
9222 {
9223 	struct nfs4_get_lease_time_data *data =
9224 			(struct nfs4_get_lease_time_data *)calldata;
9225 
9226 	if (!nfs4_sequence_done(task, &data->res->lr_seq_res))
9227 		return;
9228 	switch (task->tk_status) {
9229 	case -NFS4ERR_DELAY:
9230 	case -NFS4ERR_GRACE:
9231 		rpc_delay(task, NFS4_POLL_RETRY_MIN);
9232 		task->tk_status = 0;
9233 		fallthrough;
9234 	case -NFS4ERR_RETRY_UNCACHED_REP:
9235 		rpc_restart_call_prepare(task);
9236 		return;
9237 	}
9238 }
9239 
9240 static const struct rpc_call_ops nfs4_get_lease_time_ops = {
9241 	.rpc_call_prepare = nfs4_get_lease_time_prepare,
9242 	.rpc_call_done = nfs4_get_lease_time_done,
9243 };
9244 
9245 int nfs4_proc_get_lease_time(struct nfs_client *clp, struct nfs_fsinfo *fsinfo)
9246 {
9247 	struct nfs4_get_lease_time_args args;
9248 	struct nfs4_get_lease_time_res res = {
9249 		.lr_fsinfo = fsinfo,
9250 	};
9251 	struct nfs4_get_lease_time_data data = {
9252 		.args = &args,
9253 		.res = &res,
9254 		.clp = clp,
9255 	};
9256 	struct rpc_message msg = {
9257 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GET_LEASE_TIME],
9258 		.rpc_argp = &args,
9259 		.rpc_resp = &res,
9260 	};
9261 	struct rpc_task_setup task_setup = {
9262 		.rpc_client = clp->cl_rpcclient,
9263 		.rpc_message = &msg,
9264 		.callback_ops = &nfs4_get_lease_time_ops,
9265 		.callback_data = &data,
9266 		.flags = RPC_TASK_TIMEOUT,
9267 	};
9268 
9269 	nfs4_init_sequence(&args.la_seq_args, &res.lr_seq_res, 0, 1);
9270 	return nfs4_call_sync_custom(&task_setup);
9271 }
9272 
9273 #ifdef CONFIG_NFS_V4_1
9274 
9275 /*
9276  * Initialize the values to be used by the client in CREATE_SESSION
9277  * If nfs4_init_session set the fore channel request and response sizes,
9278  * use them.
9279  *
9280  * Set the back channel max_resp_sz_cached to zero to force the client to
9281  * always set csa_cachethis to FALSE because the current implementation
9282  * of the back channel DRC only supports caching the CB_SEQUENCE operation.
9283  */
9284 static void nfs4_init_channel_attrs(struct nfs41_create_session_args *args,
9285 				    struct rpc_clnt *clnt)
9286 {
9287 	unsigned int max_rqst_sz, max_resp_sz;
9288 	unsigned int max_bc_payload = rpc_max_bc_payload(clnt);
9289 	unsigned int max_bc_slots = rpc_num_bc_slots(clnt);
9290 
9291 	max_rqst_sz = NFS_MAX_FILE_IO_SIZE + nfs41_maxwrite_overhead;
9292 	max_resp_sz = NFS_MAX_FILE_IO_SIZE + nfs41_maxread_overhead;
9293 
9294 	/* Fore channel attributes */
9295 	args->fc_attrs.max_rqst_sz = max_rqst_sz;
9296 	args->fc_attrs.max_resp_sz = max_resp_sz;
9297 	args->fc_attrs.max_ops = NFS4_MAX_OPS;
9298 	args->fc_attrs.max_reqs = max_session_slots;
9299 
9300 	dprintk("%s: Fore Channel : max_rqst_sz=%u max_resp_sz=%u "
9301 		"max_ops=%u max_reqs=%u\n",
9302 		__func__,
9303 		args->fc_attrs.max_rqst_sz, args->fc_attrs.max_resp_sz,
9304 		args->fc_attrs.max_ops, args->fc_attrs.max_reqs);
9305 
9306 	/* Back channel attributes */
9307 	args->bc_attrs.max_rqst_sz = max_bc_payload;
9308 	args->bc_attrs.max_resp_sz = max_bc_payload;
9309 	args->bc_attrs.max_resp_sz_cached = 0;
9310 	args->bc_attrs.max_ops = NFS4_MAX_BACK_CHANNEL_OPS;
9311 	args->bc_attrs.max_reqs = max_t(unsigned short, max_session_cb_slots, 1);
9312 	if (args->bc_attrs.max_reqs > max_bc_slots)
9313 		args->bc_attrs.max_reqs = max_bc_slots;
9314 
9315 	dprintk("%s: Back Channel : max_rqst_sz=%u max_resp_sz=%u "
9316 		"max_resp_sz_cached=%u max_ops=%u max_reqs=%u\n",
9317 		__func__,
9318 		args->bc_attrs.max_rqst_sz, args->bc_attrs.max_resp_sz,
9319 		args->bc_attrs.max_resp_sz_cached, args->bc_attrs.max_ops,
9320 		args->bc_attrs.max_reqs);
9321 }
9322 
9323 static int nfs4_verify_fore_channel_attrs(struct nfs41_create_session_args *args,
9324 		struct nfs41_create_session_res *res)
9325 {
9326 	struct nfs4_channel_attrs *sent = &args->fc_attrs;
9327 	struct nfs4_channel_attrs *rcvd = &res->fc_attrs;
9328 
9329 	if (rcvd->max_resp_sz > sent->max_resp_sz)
9330 		return -EINVAL;
9331 	/*
9332 	 * Our requested max_ops is the minimum we need; we're not
9333 	 * prepared to break up compounds into smaller pieces than that.
9334 	 * So, no point even trying to continue if the server won't
9335 	 * cooperate:
9336 	 */
9337 	if (rcvd->max_ops < sent->max_ops)
9338 		return -EINVAL;
9339 	if (rcvd->max_reqs == 0)
9340 		return -EINVAL;
9341 	if (rcvd->max_reqs > NFS4_MAX_SLOT_TABLE)
9342 		rcvd->max_reqs = NFS4_MAX_SLOT_TABLE;
9343 	return 0;
9344 }
9345 
9346 static int nfs4_verify_back_channel_attrs(struct nfs41_create_session_args *args,
9347 		struct nfs41_create_session_res *res)
9348 {
9349 	struct nfs4_channel_attrs *sent = &args->bc_attrs;
9350 	struct nfs4_channel_attrs *rcvd = &res->bc_attrs;
9351 
9352 	if (!(res->flags & SESSION4_BACK_CHAN))
9353 		goto out;
9354 	if (rcvd->max_rqst_sz > sent->max_rqst_sz)
9355 		return -EINVAL;
9356 	if (rcvd->max_resp_sz < sent->max_resp_sz)
9357 		return -EINVAL;
9358 	if (rcvd->max_resp_sz_cached > sent->max_resp_sz_cached)
9359 		return -EINVAL;
9360 	if (rcvd->max_ops > sent->max_ops)
9361 		return -EINVAL;
9362 	if (rcvd->max_reqs > sent->max_reqs)
9363 		return -EINVAL;
9364 out:
9365 	return 0;
9366 }
9367 
9368 static int nfs4_verify_channel_attrs(struct nfs41_create_session_args *args,
9369 				     struct nfs41_create_session_res *res)
9370 {
9371 	int ret;
9372 
9373 	ret = nfs4_verify_fore_channel_attrs(args, res);
9374 	if (ret)
9375 		return ret;
9376 	return nfs4_verify_back_channel_attrs(args, res);
9377 }
9378 
9379 static void nfs4_update_session(struct nfs4_session *session,
9380 		struct nfs41_create_session_res *res)
9381 {
9382 	nfs4_copy_sessionid(&session->sess_id, &res->sessionid);
9383 	/* Mark client id and session as being confirmed */
9384 	session->clp->cl_exchange_flags |= EXCHGID4_FLAG_CONFIRMED_R;
9385 	set_bit(NFS4_SESSION_ESTABLISHED, &session->session_state);
9386 	session->flags = res->flags;
9387 	memcpy(&session->fc_attrs, &res->fc_attrs, sizeof(session->fc_attrs));
9388 	if (res->flags & SESSION4_BACK_CHAN)
9389 		memcpy(&session->bc_attrs, &res->bc_attrs,
9390 				sizeof(session->bc_attrs));
9391 }
9392 
9393 static int _nfs4_proc_create_session(struct nfs_client *clp,
9394 		const struct cred *cred)
9395 {
9396 	struct nfs4_session *session = clp->cl_session;
9397 	struct nfs41_create_session_args args = {
9398 		.client = clp,
9399 		.clientid = clp->cl_clientid,
9400 		.seqid = clp->cl_seqid,
9401 		.cb_program = NFS4_CALLBACK,
9402 	};
9403 	struct nfs41_create_session_res res;
9404 
9405 	struct rpc_message msg = {
9406 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_CREATE_SESSION],
9407 		.rpc_argp = &args,
9408 		.rpc_resp = &res,
9409 		.rpc_cred = cred,
9410 	};
9411 	int status;
9412 
9413 	nfs4_init_channel_attrs(&args, clp->cl_rpcclient);
9414 	args.flags = (SESSION4_PERSIST | SESSION4_BACK_CHAN);
9415 
9416 	status = rpc_call_sync(session->clp->cl_rpcclient, &msg,
9417 			       RPC_TASK_TIMEOUT | RPC_TASK_NO_ROUND_ROBIN);
9418 	trace_nfs4_create_session(clp, status);
9419 
9420 	switch (status) {
9421 	case -NFS4ERR_STALE_CLIENTID:
9422 	case -NFS4ERR_DELAY:
9423 	case -ETIMEDOUT:
9424 	case -EACCES:
9425 	case -EAGAIN:
9426 		goto out;
9427 	}
9428 
9429 	clp->cl_seqid++;
9430 	if (!status) {
9431 		/* Verify the session's negotiated channel_attrs values */
9432 		status = nfs4_verify_channel_attrs(&args, &res);
9433 		/* Increment the clientid slot sequence id */
9434 		if (status)
9435 			goto out;
9436 		nfs4_update_session(session, &res);
9437 	}
9438 out:
9439 	return status;
9440 }
9441 
9442 /*
9443  * Issues a CREATE_SESSION operation to the server.
9444  * It is the responsibility of the caller to verify the session is
9445  * expired before calling this routine.
9446  */
9447 int nfs4_proc_create_session(struct nfs_client *clp, const struct cred *cred)
9448 {
9449 	int status;
9450 	unsigned *ptr;
9451 	struct nfs4_session *session = clp->cl_session;
9452 	struct nfs4_add_xprt_data xprtdata = {
9453 		.clp = clp,
9454 	};
9455 	struct rpc_add_xprt_test rpcdata = {
9456 		.add_xprt_test = clp->cl_mvops->session_trunk,
9457 		.data = &xprtdata,
9458 	};
9459 
9460 	dprintk("--> %s clp=%p session=%p\n", __func__, clp, session);
9461 
9462 	status = _nfs4_proc_create_session(clp, cred);
9463 	if (status)
9464 		goto out;
9465 
9466 	/* Init or reset the session slot tables */
9467 	status = nfs4_setup_session_slot_tables(session);
9468 	dprintk("slot table setup returned %d\n", status);
9469 	if (status)
9470 		goto out;
9471 
9472 	ptr = (unsigned *)&session->sess_id.data[0];
9473 	dprintk("%s client>seqid %d sessionid %u:%u:%u:%u\n", __func__,
9474 		clp->cl_seqid, ptr[0], ptr[1], ptr[2], ptr[3]);
9475 	rpc_clnt_probe_trunked_xprts(clp->cl_rpcclient, &rpcdata);
9476 out:
9477 	return status;
9478 }
9479 
9480 /*
9481  * Issue the over-the-wire RPC DESTROY_SESSION.
9482  * The caller must serialize access to this routine.
9483  */
9484 int nfs4_proc_destroy_session(struct nfs4_session *session,
9485 		const struct cred *cred)
9486 {
9487 	struct rpc_message msg = {
9488 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_DESTROY_SESSION],
9489 		.rpc_argp = session,
9490 		.rpc_cred = cred,
9491 	};
9492 	int status = 0;
9493 
9494 	/* session is still being setup */
9495 	if (!test_and_clear_bit(NFS4_SESSION_ESTABLISHED, &session->session_state))
9496 		return 0;
9497 
9498 	status = rpc_call_sync(session->clp->cl_rpcclient, &msg,
9499 			       RPC_TASK_TIMEOUT | RPC_TASK_NO_ROUND_ROBIN);
9500 	trace_nfs4_destroy_session(session->clp, status);
9501 
9502 	if (status)
9503 		dprintk("NFS: Got error %d from the server on DESTROY_SESSION. "
9504 			"Session has been destroyed regardless...\n", status);
9505 	rpc_clnt_manage_trunked_xprts(session->clp->cl_rpcclient);
9506 	return status;
9507 }
9508 
9509 /*
9510  * Renew the cl_session lease.
9511  */
9512 struct nfs4_sequence_data {
9513 	struct nfs_client *clp;
9514 	struct nfs4_sequence_args args;
9515 	struct nfs4_sequence_res res;
9516 };
9517 
9518 static void nfs41_sequence_release(void *data)
9519 {
9520 	struct nfs4_sequence_data *calldata = data;
9521 	struct nfs_client *clp = calldata->clp;
9522 
9523 	if (refcount_read(&clp->cl_count) > 1)
9524 		nfs4_schedule_state_renewal(clp);
9525 	nfs_put_client(clp);
9526 	kfree(calldata);
9527 }
9528 
9529 static int nfs41_sequence_handle_errors(struct rpc_task *task, struct nfs_client *clp)
9530 {
9531 	switch(task->tk_status) {
9532 	case -NFS4ERR_DELAY:
9533 		rpc_delay(task, NFS4_POLL_RETRY_MAX);
9534 		return -EAGAIN;
9535 	default:
9536 		nfs4_schedule_lease_recovery(clp);
9537 	}
9538 	return 0;
9539 }
9540 
9541 static void nfs41_sequence_call_done(struct rpc_task *task, void *data)
9542 {
9543 	struct nfs4_sequence_data *calldata = data;
9544 	struct nfs_client *clp = calldata->clp;
9545 
9546 	if (!nfs41_sequence_done(task, task->tk_msg.rpc_resp))
9547 		return;
9548 
9549 	trace_nfs4_sequence(clp, task->tk_status);
9550 	if (task->tk_status < 0 && !task->tk_client->cl_shutdown) {
9551 		dprintk("%s ERROR %d\n", __func__, task->tk_status);
9552 		if (refcount_read(&clp->cl_count) == 1)
9553 			return;
9554 
9555 		if (nfs41_sequence_handle_errors(task, clp) == -EAGAIN) {
9556 			rpc_restart_call_prepare(task);
9557 			return;
9558 		}
9559 	}
9560 	dprintk("%s rpc_cred %p\n", __func__, task->tk_msg.rpc_cred);
9561 }
9562 
9563 static void nfs41_sequence_prepare(struct rpc_task *task, void *data)
9564 {
9565 	struct nfs4_sequence_data *calldata = data;
9566 	struct nfs_client *clp = calldata->clp;
9567 	struct nfs4_sequence_args *args;
9568 	struct nfs4_sequence_res *res;
9569 
9570 	args = task->tk_msg.rpc_argp;
9571 	res = task->tk_msg.rpc_resp;
9572 
9573 	nfs4_setup_sequence(clp, args, res, task);
9574 }
9575 
9576 static const struct rpc_call_ops nfs41_sequence_ops = {
9577 	.rpc_call_done = nfs41_sequence_call_done,
9578 	.rpc_call_prepare = nfs41_sequence_prepare,
9579 	.rpc_release = nfs41_sequence_release,
9580 };
9581 
9582 static struct rpc_task *_nfs41_proc_sequence(struct nfs_client *clp,
9583 		const struct cred *cred,
9584 		struct nfs4_slot *slot,
9585 		bool is_privileged)
9586 {
9587 	struct nfs4_sequence_data *calldata;
9588 	struct rpc_message msg = {
9589 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_SEQUENCE],
9590 		.rpc_cred = cred,
9591 	};
9592 	struct rpc_task_setup task_setup_data = {
9593 		.rpc_client = clp->cl_rpcclient,
9594 		.rpc_message = &msg,
9595 		.callback_ops = &nfs41_sequence_ops,
9596 		.flags = RPC_TASK_ASYNC | RPC_TASK_TIMEOUT | RPC_TASK_MOVEABLE,
9597 	};
9598 	struct rpc_task *ret;
9599 
9600 	ret = ERR_PTR(-EIO);
9601 	if (!refcount_inc_not_zero(&clp->cl_count))
9602 		goto out_err;
9603 
9604 	ret = ERR_PTR(-ENOMEM);
9605 	calldata = kzalloc(sizeof(*calldata), GFP_KERNEL);
9606 	if (calldata == NULL)
9607 		goto out_put_clp;
9608 	nfs4_init_sequence(&calldata->args, &calldata->res, 0, is_privileged);
9609 	nfs4_sequence_attach_slot(&calldata->args, &calldata->res, slot);
9610 	msg.rpc_argp = &calldata->args;
9611 	msg.rpc_resp = &calldata->res;
9612 	calldata->clp = clp;
9613 	task_setup_data.callback_data = calldata;
9614 
9615 	ret = rpc_run_task(&task_setup_data);
9616 	if (IS_ERR(ret))
9617 		goto out_err;
9618 	return ret;
9619 out_put_clp:
9620 	nfs_put_client(clp);
9621 out_err:
9622 	nfs41_release_slot(slot);
9623 	return ret;
9624 }
9625 
9626 static int nfs41_proc_async_sequence(struct nfs_client *clp, const struct cred *cred, unsigned renew_flags)
9627 {
9628 	struct rpc_task *task;
9629 	int ret = 0;
9630 
9631 	if ((renew_flags & NFS4_RENEW_TIMEOUT) == 0)
9632 		return -EAGAIN;
9633 	task = _nfs41_proc_sequence(clp, cred, NULL, false);
9634 	if (IS_ERR(task))
9635 		ret = PTR_ERR(task);
9636 	else
9637 		rpc_put_task_async(task);
9638 	dprintk("<-- %s status=%d\n", __func__, ret);
9639 	return ret;
9640 }
9641 
9642 static int nfs4_proc_sequence(struct nfs_client *clp, const struct cred *cred)
9643 {
9644 	struct rpc_task *task;
9645 	int ret;
9646 
9647 	task = _nfs41_proc_sequence(clp, cred, NULL, true);
9648 	if (IS_ERR(task)) {
9649 		ret = PTR_ERR(task);
9650 		goto out;
9651 	}
9652 	ret = rpc_wait_for_completion_task(task);
9653 	if (!ret)
9654 		ret = task->tk_status;
9655 	rpc_put_task(task);
9656 out:
9657 	dprintk("<-- %s status=%d\n", __func__, ret);
9658 	return ret;
9659 }
9660 
9661 struct nfs4_reclaim_complete_data {
9662 	struct nfs_client *clp;
9663 	struct nfs41_reclaim_complete_args arg;
9664 	struct nfs41_reclaim_complete_res res;
9665 };
9666 
9667 static void nfs4_reclaim_complete_prepare(struct rpc_task *task, void *data)
9668 {
9669 	struct nfs4_reclaim_complete_data *calldata = data;
9670 
9671 	nfs4_setup_sequence(calldata->clp,
9672 			&calldata->arg.seq_args,
9673 			&calldata->res.seq_res,
9674 			task);
9675 }
9676 
9677 static int nfs41_reclaim_complete_handle_errors(struct rpc_task *task, struct nfs_client *clp)
9678 {
9679 	switch(task->tk_status) {
9680 	case 0:
9681 		wake_up_all(&clp->cl_lock_waitq);
9682 		fallthrough;
9683 	case -NFS4ERR_COMPLETE_ALREADY:
9684 	case -NFS4ERR_WRONG_CRED: /* What to do here? */
9685 		break;
9686 	case -NFS4ERR_DELAY:
9687 		rpc_delay(task, NFS4_POLL_RETRY_MAX);
9688 		fallthrough;
9689 	case -NFS4ERR_RETRY_UNCACHED_REP:
9690 	case -EACCES:
9691 		dprintk("%s: failed to reclaim complete error %d for server %s, retrying\n",
9692 			__func__, task->tk_status, clp->cl_hostname);
9693 		return -EAGAIN;
9694 	case -NFS4ERR_BADSESSION:
9695 	case -NFS4ERR_DEADSESSION:
9696 	case -NFS4ERR_CONN_NOT_BOUND_TO_SESSION:
9697 		break;
9698 	default:
9699 		nfs4_schedule_lease_recovery(clp);
9700 	}
9701 	return 0;
9702 }
9703 
9704 static void nfs4_reclaim_complete_done(struct rpc_task *task, void *data)
9705 {
9706 	struct nfs4_reclaim_complete_data *calldata = data;
9707 	struct nfs_client *clp = calldata->clp;
9708 	struct nfs4_sequence_res *res = &calldata->res.seq_res;
9709 
9710 	if (!nfs41_sequence_done(task, res))
9711 		return;
9712 
9713 	trace_nfs4_reclaim_complete(clp, task->tk_status);
9714 	if (nfs41_reclaim_complete_handle_errors(task, clp) == -EAGAIN) {
9715 		rpc_restart_call_prepare(task);
9716 		return;
9717 	}
9718 }
9719 
9720 static void nfs4_free_reclaim_complete_data(void *data)
9721 {
9722 	struct nfs4_reclaim_complete_data *calldata = data;
9723 
9724 	kfree(calldata);
9725 }
9726 
9727 static const struct rpc_call_ops nfs4_reclaim_complete_call_ops = {
9728 	.rpc_call_prepare = nfs4_reclaim_complete_prepare,
9729 	.rpc_call_done = nfs4_reclaim_complete_done,
9730 	.rpc_release = nfs4_free_reclaim_complete_data,
9731 };
9732 
9733 /*
9734  * Issue a global reclaim complete.
9735  */
9736 static int nfs41_proc_reclaim_complete(struct nfs_client *clp,
9737 		const struct cred *cred)
9738 {
9739 	struct nfs4_reclaim_complete_data *calldata;
9740 	struct rpc_message msg = {
9741 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_RECLAIM_COMPLETE],
9742 		.rpc_cred = cred,
9743 	};
9744 	struct rpc_task_setup task_setup_data = {
9745 		.rpc_client = clp->cl_rpcclient,
9746 		.rpc_message = &msg,
9747 		.callback_ops = &nfs4_reclaim_complete_call_ops,
9748 		.flags = RPC_TASK_NO_ROUND_ROBIN,
9749 	};
9750 	int status = -ENOMEM;
9751 
9752 	calldata = kzalloc(sizeof(*calldata), GFP_NOFS);
9753 	if (calldata == NULL)
9754 		goto out;
9755 	calldata->clp = clp;
9756 	calldata->arg.one_fs = 0;
9757 
9758 	nfs4_init_sequence(&calldata->arg.seq_args, &calldata->res.seq_res, 0, 1);
9759 	msg.rpc_argp = &calldata->arg;
9760 	msg.rpc_resp = &calldata->res;
9761 	task_setup_data.callback_data = calldata;
9762 	status = nfs4_call_sync_custom(&task_setup_data);
9763 out:
9764 	dprintk("<-- %s status=%d\n", __func__, status);
9765 	return status;
9766 }
9767 
9768 static void
9769 nfs4_layoutget_prepare(struct rpc_task *task, void *calldata)
9770 {
9771 	struct nfs4_layoutget *lgp = calldata;
9772 	struct nfs_server *server = NFS_SERVER(lgp->args.inode);
9773 
9774 	nfs4_setup_sequence(server->nfs_client, &lgp->args.seq_args,
9775 				&lgp->res.seq_res, task);
9776 }
9777 
9778 static void nfs4_layoutget_done(struct rpc_task *task, void *calldata)
9779 {
9780 	struct nfs4_layoutget *lgp = calldata;
9781 
9782 	nfs41_sequence_process(task, &lgp->res.seq_res);
9783 }
9784 
9785 static int
9786 nfs4_layoutget_handle_exception(struct rpc_task *task,
9787 		struct nfs4_layoutget *lgp, struct nfs4_exception *exception)
9788 {
9789 	struct inode *inode = lgp->args.inode;
9790 	struct nfs_server *server = NFS_SERVER(inode);
9791 	struct pnfs_layout_hdr *lo = lgp->lo;
9792 	int nfs4err = task->tk_status;
9793 	int err, status = 0;
9794 	LIST_HEAD(head);
9795 
9796 	dprintk("--> %s tk_status => %d\n", __func__, -task->tk_status);
9797 
9798 	nfs4_sequence_free_slot(&lgp->res.seq_res);
9799 
9800 	exception->state = NULL;
9801 	exception->stateid = NULL;
9802 
9803 	switch (nfs4err) {
9804 	case 0:
9805 		goto out;
9806 
9807 	/*
9808 	 * NFS4ERR_LAYOUTUNAVAILABLE means we are not supposed to use pnfs
9809 	 * on the file. set tk_status to -ENODATA to tell upper layer to
9810 	 * retry go inband.
9811 	 */
9812 	case -NFS4ERR_LAYOUTUNAVAILABLE:
9813 		status = -ENODATA;
9814 		goto out;
9815 	/*
9816 	 * NFS4ERR_BADLAYOUT means the MDS cannot return a layout of
9817 	 * length lgp->args.minlength != 0 (see RFC5661 section 18.43.3).
9818 	 */
9819 	case -NFS4ERR_BADLAYOUT:
9820 		status = -EOVERFLOW;
9821 		goto out;
9822 	/*
9823 	 * NFS4ERR_LAYOUTTRYLATER is a conflict with another client
9824 	 * (or clients) writing to the same RAID stripe except when
9825 	 * the minlength argument is 0 (see RFC5661 section 18.43.3).
9826 	 *
9827 	 * Treat it like we would RECALLCONFLICT -- we retry for a little
9828 	 * while, and then eventually give up.
9829 	 */
9830 	case -NFS4ERR_LAYOUTTRYLATER:
9831 		if (lgp->args.minlength == 0) {
9832 			status = -EOVERFLOW;
9833 			goto out;
9834 		}
9835 		status = -EBUSY;
9836 		break;
9837 	case -NFS4ERR_RECALLCONFLICT:
9838 	case -NFS4ERR_RETURNCONFLICT:
9839 		status = -ERECALLCONFLICT;
9840 		break;
9841 	case -NFS4ERR_DELEG_REVOKED:
9842 	case -NFS4ERR_ADMIN_REVOKED:
9843 	case -NFS4ERR_EXPIRED:
9844 	case -NFS4ERR_BAD_STATEID:
9845 		exception->timeout = 0;
9846 		spin_lock(&inode->i_lock);
9847 		/* If the open stateid was bad, then recover it. */
9848 		if (!lo || test_bit(NFS_LAYOUT_INVALID_STID, &lo->plh_flags) ||
9849 		    !nfs4_stateid_match_other(&lgp->args.stateid, &lo->plh_stateid)) {
9850 			spin_unlock(&inode->i_lock);
9851 			exception->state = lgp->args.ctx->state;
9852 			exception->stateid = &lgp->args.stateid;
9853 			break;
9854 		}
9855 
9856 		/*
9857 		 * Mark the bad layout state as invalid, then retry
9858 		 */
9859 		pnfs_mark_layout_stateid_invalid(lo, &head);
9860 		spin_unlock(&inode->i_lock);
9861 		nfs_commit_inode(inode, 0);
9862 		pnfs_free_lseg_list(&head);
9863 		status = -EAGAIN;
9864 		goto out;
9865 	}
9866 
9867 	err = nfs4_handle_exception(server, nfs4err, exception);
9868 	if (!status) {
9869 		if (exception->retry)
9870 			status = -EAGAIN;
9871 		else
9872 			status = err;
9873 	}
9874 out:
9875 	return status;
9876 }
9877 
9878 size_t max_response_pages(struct nfs_server *server)
9879 {
9880 	u32 max_resp_sz = server->nfs_client->cl_session->fc_attrs.max_resp_sz;
9881 	return nfs_page_array_len(0, max_resp_sz);
9882 }
9883 
9884 static void nfs4_layoutget_release(void *calldata)
9885 {
9886 	struct nfs4_layoutget *lgp = calldata;
9887 
9888 	nfs4_sequence_free_slot(&lgp->res.seq_res);
9889 	pnfs_layoutget_free(lgp);
9890 }
9891 
9892 static const struct rpc_call_ops nfs4_layoutget_call_ops = {
9893 	.rpc_call_prepare = nfs4_layoutget_prepare,
9894 	.rpc_call_done = nfs4_layoutget_done,
9895 	.rpc_release = nfs4_layoutget_release,
9896 };
9897 
9898 struct pnfs_layout_segment *
9899 nfs4_proc_layoutget(struct nfs4_layoutget *lgp,
9900 		    struct nfs4_exception *exception)
9901 {
9902 	struct inode *inode = lgp->args.inode;
9903 	struct nfs_server *server = NFS_SERVER(inode);
9904 	struct rpc_task *task;
9905 	struct rpc_message msg = {
9906 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_LAYOUTGET],
9907 		.rpc_argp = &lgp->args,
9908 		.rpc_resp = &lgp->res,
9909 		.rpc_cred = lgp->cred,
9910 	};
9911 	struct rpc_task_setup task_setup_data = {
9912 		.rpc_client = server->client,
9913 		.rpc_message = &msg,
9914 		.callback_ops = &nfs4_layoutget_call_ops,
9915 		.callback_data = lgp,
9916 		.flags = RPC_TASK_ASYNC | RPC_TASK_CRED_NOREF |
9917 			 RPC_TASK_MOVEABLE,
9918 	};
9919 	struct pnfs_layout_segment *lseg = NULL;
9920 	int status = 0;
9921 
9922 	nfs4_init_sequence(&lgp->args.seq_args, &lgp->res.seq_res, 0, 0);
9923 	exception->retry = 0;
9924 
9925 	task = rpc_run_task(&task_setup_data);
9926 	if (IS_ERR(task))
9927 		return ERR_CAST(task);
9928 
9929 	status = rpc_wait_for_completion_task(task);
9930 	if (status != 0)
9931 		goto out;
9932 
9933 	if (task->tk_status < 0) {
9934 		exception->retry = 1;
9935 		status = nfs4_layoutget_handle_exception(task, lgp, exception);
9936 	} else if (lgp->res.layoutp->len == 0) {
9937 		exception->retry = 1;
9938 		status = -EAGAIN;
9939 		nfs4_update_delay(&exception->timeout);
9940 	} else
9941 		lseg = pnfs_layout_process(lgp);
9942 out:
9943 	trace_nfs4_layoutget(lgp->args.ctx,
9944 			&lgp->args.range,
9945 			&lgp->res.range,
9946 			&lgp->res.stateid,
9947 			status);
9948 
9949 	rpc_put_task(task);
9950 	dprintk("<-- %s status=%d\n", __func__, status);
9951 	if (status)
9952 		return ERR_PTR(status);
9953 	return lseg;
9954 }
9955 
9956 static void
9957 nfs4_layoutreturn_prepare(struct rpc_task *task, void *calldata)
9958 {
9959 	struct nfs4_layoutreturn *lrp = calldata;
9960 
9961 	nfs4_setup_sequence(lrp->clp,
9962 			&lrp->args.seq_args,
9963 			&lrp->res.seq_res,
9964 			task);
9965 	if (!pnfs_layout_is_valid(lrp->args.layout))
9966 		rpc_exit(task, 0);
9967 }
9968 
9969 static void nfs4_layoutreturn_done(struct rpc_task *task, void *calldata)
9970 {
9971 	struct nfs4_layoutreturn *lrp = calldata;
9972 	struct nfs_server *server;
9973 
9974 	if (!nfs41_sequence_process(task, &lrp->res.seq_res))
9975 		return;
9976 
9977 	if (task->tk_rpc_status == -ETIMEDOUT) {
9978 		lrp->rpc_status = -EAGAIN;
9979 		lrp->res.lrs_present = 0;
9980 		return;
9981 	}
9982 	/*
9983 	 * Was there an RPC level error? Assume the call succeeded,
9984 	 * and that we need to release the layout
9985 	 */
9986 	if (task->tk_rpc_status != 0 && RPC_WAS_SENT(task)) {
9987 		lrp->res.lrs_present = 0;
9988 		return;
9989 	}
9990 
9991 	server = NFS_SERVER(lrp->args.inode);
9992 	switch (task->tk_status) {
9993 	case -NFS4ERR_OLD_STATEID:
9994 		if (nfs4_layout_refresh_old_stateid(&lrp->args.stateid,
9995 					&lrp->args.range,
9996 					lrp->args.inode))
9997 			goto out_restart;
9998 		fallthrough;
9999 	default:
10000 		task->tk_status = 0;
10001 		lrp->res.lrs_present = 0;
10002 		fallthrough;
10003 	case 0:
10004 		break;
10005 	case -NFS4ERR_BADSESSION:
10006 	case -NFS4ERR_DEADSESSION:
10007 	case -NFS4ERR_CONN_NOT_BOUND_TO_SESSION:
10008 		nfs4_schedule_session_recovery(server->nfs_client->cl_session,
10009 					       task->tk_status);
10010 		lrp->res.lrs_present = 0;
10011 		lrp->rpc_status = -EAGAIN;
10012 		task->tk_status = 0;
10013 		break;
10014 	case -NFS4ERR_DELAY:
10015 		if (nfs4_async_handle_error(task, server, NULL, NULL) ==
10016 		    -EAGAIN)
10017 			goto out_restart;
10018 		lrp->res.lrs_present = 0;
10019 		break;
10020 	}
10021 	return;
10022 out_restart:
10023 	task->tk_status = 0;
10024 	nfs4_sequence_free_slot(&lrp->res.seq_res);
10025 	rpc_restart_call_prepare(task);
10026 }
10027 
10028 static void nfs4_layoutreturn_release(void *calldata)
10029 {
10030 	struct nfs4_layoutreturn *lrp = calldata;
10031 	struct pnfs_layout_hdr *lo = lrp->args.layout;
10032 
10033 	if (lrp->rpc_status == 0 || !lrp->inode)
10034 		pnfs_layoutreturn_free_lsegs(
10035 			lo, &lrp->args.stateid, &lrp->args.range,
10036 			lrp->res.lrs_present ? &lrp->res.stateid : NULL);
10037 	else
10038 		pnfs_layoutreturn_retry_later(lo, &lrp->args.stateid,
10039 					      &lrp->args.range);
10040 	nfs4_sequence_free_slot(&lrp->res.seq_res);
10041 	if (lrp->ld_private.ops && lrp->ld_private.ops->free)
10042 		lrp->ld_private.ops->free(&lrp->ld_private);
10043 	pnfs_put_layout_hdr(lrp->args.layout);
10044 	nfs_iput_and_deactive(lrp->inode);
10045 	put_cred(lrp->cred);
10046 	kfree(calldata);
10047 }
10048 
10049 static const struct rpc_call_ops nfs4_layoutreturn_call_ops = {
10050 	.rpc_call_prepare = nfs4_layoutreturn_prepare,
10051 	.rpc_call_done = nfs4_layoutreturn_done,
10052 	.rpc_release = nfs4_layoutreturn_release,
10053 };
10054 
10055 int nfs4_proc_layoutreturn(struct nfs4_layoutreturn *lrp, unsigned int flags)
10056 {
10057 	struct rpc_task *task;
10058 	struct rpc_message msg = {
10059 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_LAYOUTRETURN],
10060 		.rpc_argp = &lrp->args,
10061 		.rpc_resp = &lrp->res,
10062 		.rpc_cred = lrp->cred,
10063 	};
10064 	struct rpc_task_setup task_setup_data = {
10065 		.rpc_client = NFS_SERVER(lrp->args.inode)->client,
10066 		.rpc_message = &msg,
10067 		.callback_ops = &nfs4_layoutreturn_call_ops,
10068 		.callback_data = lrp,
10069 		.flags = RPC_TASK_MOVEABLE,
10070 	};
10071 	int status = 0;
10072 
10073 	nfs4_state_protect(NFS_SERVER(lrp->args.inode)->nfs_client,
10074 			NFS_SP4_MACH_CRED_PNFS_CLEANUP,
10075 			&task_setup_data.rpc_client, &msg);
10076 
10077 	lrp->inode = nfs_igrab_and_active(lrp->args.inode);
10078 	if (flags & PNFS_FL_LAYOUTRETURN_ASYNC) {
10079 		if (!lrp->inode) {
10080 			nfs4_layoutreturn_release(lrp);
10081 			return -EAGAIN;
10082 		}
10083 		task_setup_data.flags |= RPC_TASK_ASYNC;
10084 	}
10085 	if (!lrp->inode)
10086 		flags |= PNFS_FL_LAYOUTRETURN_PRIVILEGED;
10087 	if (flags & PNFS_FL_LAYOUTRETURN_PRIVILEGED)
10088 		nfs4_init_sequence(&lrp->args.seq_args, &lrp->res.seq_res, 1,
10089 				   1);
10090 	else
10091 		nfs4_init_sequence(&lrp->args.seq_args, &lrp->res.seq_res, 1,
10092 				   0);
10093 	task = rpc_run_task(&task_setup_data);
10094 	if (IS_ERR(task))
10095 		return PTR_ERR(task);
10096 	if (!(flags & PNFS_FL_LAYOUTRETURN_ASYNC))
10097 		status = task->tk_status;
10098 	trace_nfs4_layoutreturn(lrp->args.inode, &lrp->args.stateid, status);
10099 	dprintk("<-- %s status=%d\n", __func__, status);
10100 	rpc_put_task(task);
10101 	return status;
10102 }
10103 
10104 static int
10105 _nfs4_proc_getdeviceinfo(struct nfs_server *server,
10106 		struct pnfs_device *pdev,
10107 		const struct cred *cred)
10108 {
10109 	struct nfs4_getdeviceinfo_args args = {
10110 		.pdev = pdev,
10111 		.notify_types = NOTIFY_DEVICEID4_CHANGE |
10112 			NOTIFY_DEVICEID4_DELETE,
10113 	};
10114 	struct nfs4_getdeviceinfo_res res = {
10115 		.pdev = pdev,
10116 	};
10117 	struct rpc_message msg = {
10118 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETDEVICEINFO],
10119 		.rpc_argp = &args,
10120 		.rpc_resp = &res,
10121 		.rpc_cred = cred,
10122 	};
10123 	int status;
10124 
10125 	status = nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 0);
10126 	if (res.notification & ~args.notify_types)
10127 		dprintk("%s: unsupported notification\n", __func__);
10128 	if (res.notification != args.notify_types)
10129 		pdev->nocache = 1;
10130 
10131 	trace_nfs4_getdeviceinfo(server, &pdev->dev_id, status);
10132 
10133 	dprintk("<-- %s status=%d\n", __func__, status);
10134 
10135 	return status;
10136 }
10137 
10138 int nfs4_proc_getdeviceinfo(struct nfs_server *server,
10139 		struct pnfs_device *pdev,
10140 		const struct cred *cred)
10141 {
10142 	struct nfs4_exception exception = { };
10143 	int err;
10144 
10145 	do {
10146 		err = nfs4_handle_exception(server,
10147 					_nfs4_proc_getdeviceinfo(server, pdev, cred),
10148 					&exception);
10149 	} while (exception.retry);
10150 	return err;
10151 }
10152 EXPORT_SYMBOL_GPL(nfs4_proc_getdeviceinfo);
10153 
10154 static void nfs4_layoutcommit_prepare(struct rpc_task *task, void *calldata)
10155 {
10156 	struct nfs4_layoutcommit_data *data = calldata;
10157 	struct nfs_server *server = NFS_SERVER(data->args.inode);
10158 
10159 	nfs4_setup_sequence(server->nfs_client,
10160 			&data->args.seq_args,
10161 			&data->res.seq_res,
10162 			task);
10163 }
10164 
10165 static void
10166 nfs4_layoutcommit_done(struct rpc_task *task, void *calldata)
10167 {
10168 	struct nfs4_layoutcommit_data *data = calldata;
10169 	struct nfs_server *server = NFS_SERVER(data->args.inode);
10170 
10171 	if (!nfs41_sequence_done(task, &data->res.seq_res))
10172 		return;
10173 
10174 	switch (task->tk_status) { /* Just ignore these failures */
10175 	case -NFS4ERR_DELEG_REVOKED: /* layout was recalled */
10176 	case -NFS4ERR_BADIOMODE:     /* no IOMODE_RW layout for range */
10177 	case -NFS4ERR_BADLAYOUT:     /* no layout */
10178 	case -NFS4ERR_GRACE:	    /* loca_recalim always false */
10179 		task->tk_status = 0;
10180 		break;
10181 	case 0:
10182 		break;
10183 	default:
10184 		if (nfs4_async_handle_error(task, server, NULL, NULL) == -EAGAIN) {
10185 			rpc_restart_call_prepare(task);
10186 			return;
10187 		}
10188 	}
10189 }
10190 
10191 static void nfs4_layoutcommit_release(void *calldata)
10192 {
10193 	struct nfs4_layoutcommit_data *data = calldata;
10194 
10195 	pnfs_cleanup_layoutcommit(data);
10196 	nfs_post_op_update_inode_force_wcc(data->args.inode,
10197 					   data->res.fattr);
10198 	put_cred(data->cred);
10199 	nfs_iput_and_deactive(data->inode);
10200 	kfree(data);
10201 }
10202 
10203 static const struct rpc_call_ops nfs4_layoutcommit_ops = {
10204 	.rpc_call_prepare = nfs4_layoutcommit_prepare,
10205 	.rpc_call_done = nfs4_layoutcommit_done,
10206 	.rpc_release = nfs4_layoutcommit_release,
10207 };
10208 
10209 int
10210 nfs4_proc_layoutcommit(struct nfs4_layoutcommit_data *data, bool sync)
10211 {
10212 	struct rpc_message msg = {
10213 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_LAYOUTCOMMIT],
10214 		.rpc_argp = &data->args,
10215 		.rpc_resp = &data->res,
10216 		.rpc_cred = data->cred,
10217 	};
10218 	struct rpc_task_setup task_setup_data = {
10219 		.task = &data->task,
10220 		.rpc_client = NFS_CLIENT(data->args.inode),
10221 		.rpc_message = &msg,
10222 		.callback_ops = &nfs4_layoutcommit_ops,
10223 		.callback_data = data,
10224 		.flags = RPC_TASK_MOVEABLE,
10225 	};
10226 	struct rpc_task *task;
10227 	int status = 0;
10228 
10229 	dprintk("NFS: initiating layoutcommit call. sync %d "
10230 		"lbw: %llu inode %lu\n", sync,
10231 		data->args.lastbytewritten,
10232 		data->args.inode->i_ino);
10233 
10234 	if (!sync) {
10235 		data->inode = nfs_igrab_and_active(data->args.inode);
10236 		if (data->inode == NULL) {
10237 			nfs4_layoutcommit_release(data);
10238 			return -EAGAIN;
10239 		}
10240 		task_setup_data.flags = RPC_TASK_ASYNC;
10241 	}
10242 	nfs4_init_sequence(&data->args.seq_args, &data->res.seq_res, 1, 0);
10243 	task = rpc_run_task(&task_setup_data);
10244 	if (IS_ERR(task))
10245 		return PTR_ERR(task);
10246 	if (sync)
10247 		status = task->tk_status;
10248 	trace_nfs4_layoutcommit(data->args.inode, &data->args.stateid, status);
10249 	dprintk("%s: status %d\n", __func__, status);
10250 	rpc_put_task(task);
10251 	return status;
10252 }
10253 
10254 /*
10255  * Use the state managment nfs_client cl_rpcclient, which uses krb5i (if
10256  * possible) as per RFC3530bis and RFC5661 Security Considerations sections
10257  */
10258 static int
10259 _nfs41_proc_secinfo_no_name(struct nfs_server *server, struct nfs_fh *fhandle,
10260 		    struct nfs_fsinfo *info,
10261 		    struct nfs4_secinfo_flavors *flavors, bool use_integrity)
10262 {
10263 	struct nfs41_secinfo_no_name_args args = {
10264 		.style = SECINFO_STYLE_CURRENT_FH,
10265 	};
10266 	struct nfs4_secinfo_res res = {
10267 		.flavors = flavors,
10268 	};
10269 	struct rpc_message msg = {
10270 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_SECINFO_NO_NAME],
10271 		.rpc_argp = &args,
10272 		.rpc_resp = &res,
10273 	};
10274 	struct nfs4_call_sync_data data = {
10275 		.seq_server = server,
10276 		.seq_args = &args.seq_args,
10277 		.seq_res = &res.seq_res,
10278 	};
10279 	struct rpc_task_setup task_setup = {
10280 		.rpc_client = server->client,
10281 		.rpc_message = &msg,
10282 		.callback_ops = server->nfs_client->cl_mvops->call_sync_ops,
10283 		.callback_data = &data,
10284 		.flags = RPC_TASK_NO_ROUND_ROBIN,
10285 	};
10286 	const struct cred *cred = NULL;
10287 	int status;
10288 
10289 	if (use_integrity) {
10290 		task_setup.rpc_client = server->nfs_client->cl_rpcclient;
10291 
10292 		cred = nfs4_get_clid_cred(server->nfs_client);
10293 		msg.rpc_cred = cred;
10294 	}
10295 
10296 	nfs4_init_sequence(&args.seq_args, &res.seq_res, 0, 0);
10297 	status = nfs4_call_sync_custom(&task_setup);
10298 	dprintk("<-- %s status=%d\n", __func__, status);
10299 
10300 	put_cred(cred);
10301 
10302 	return status;
10303 }
10304 
10305 static int
10306 nfs41_proc_secinfo_no_name(struct nfs_server *server, struct nfs_fh *fhandle,
10307 			   struct nfs_fsinfo *info, struct nfs4_secinfo_flavors *flavors)
10308 {
10309 	struct nfs4_exception exception = {
10310 		.interruptible = true,
10311 	};
10312 	int err;
10313 	do {
10314 		/* first try using integrity protection */
10315 		err = -NFS4ERR_WRONGSEC;
10316 
10317 		/* try to use integrity protection with machine cred */
10318 		if (_nfs4_is_integrity_protected(server->nfs_client))
10319 			err = _nfs41_proc_secinfo_no_name(server, fhandle, info,
10320 							  flavors, true);
10321 
10322 		/*
10323 		 * if unable to use integrity protection, or SECINFO with
10324 		 * integrity protection returns NFS4ERR_WRONGSEC (which is
10325 		 * disallowed by spec, but exists in deployed servers) use
10326 		 * the current filesystem's rpc_client and the user cred.
10327 		 */
10328 		if (err == -NFS4ERR_WRONGSEC)
10329 			err = _nfs41_proc_secinfo_no_name(server, fhandle, info,
10330 							  flavors, false);
10331 
10332 		switch (err) {
10333 		case 0:
10334 		case -NFS4ERR_WRONGSEC:
10335 		case -ENOTSUPP:
10336 			goto out;
10337 		default:
10338 			err = nfs4_handle_exception(server, err, &exception);
10339 		}
10340 	} while (exception.retry);
10341 out:
10342 	return err;
10343 }
10344 
10345 static int
10346 nfs41_find_root_sec(struct nfs_server *server, struct nfs_fh *fhandle,
10347 		    struct nfs_fsinfo *info)
10348 {
10349 	int err;
10350 	struct page *page;
10351 	rpc_authflavor_t flavor = RPC_AUTH_MAXFLAVOR;
10352 	struct nfs4_secinfo_flavors *flavors;
10353 	struct nfs4_secinfo4 *secinfo;
10354 	int i;
10355 
10356 	page = alloc_page(GFP_KERNEL);
10357 	if (!page) {
10358 		err = -ENOMEM;
10359 		goto out;
10360 	}
10361 
10362 	flavors = page_address(page);
10363 	err = nfs41_proc_secinfo_no_name(server, fhandle, info, flavors);
10364 
10365 	/*
10366 	 * Fall back on "guess and check" method if
10367 	 * the server doesn't support SECINFO_NO_NAME
10368 	 */
10369 	if (err == -NFS4ERR_WRONGSEC || err == -ENOTSUPP) {
10370 		err = nfs4_find_root_sec(server, fhandle, info);
10371 		goto out_freepage;
10372 	}
10373 	if (err)
10374 		goto out_freepage;
10375 
10376 	for (i = 0; i < flavors->num_flavors; i++) {
10377 		secinfo = &flavors->flavors[i];
10378 
10379 		switch (secinfo->flavor) {
10380 		case RPC_AUTH_NULL:
10381 		case RPC_AUTH_UNIX:
10382 		case RPC_AUTH_GSS:
10383 			flavor = rpcauth_get_pseudoflavor(secinfo->flavor,
10384 					&secinfo->flavor_info);
10385 			break;
10386 		default:
10387 			flavor = RPC_AUTH_MAXFLAVOR;
10388 			break;
10389 		}
10390 
10391 		if (!nfs_auth_info_match(&server->auth_info, flavor))
10392 			flavor = RPC_AUTH_MAXFLAVOR;
10393 
10394 		if (flavor != RPC_AUTH_MAXFLAVOR) {
10395 			err = nfs4_lookup_root_sec(server, fhandle,
10396 						   info, flavor);
10397 			if (!err)
10398 				break;
10399 		}
10400 	}
10401 
10402 	if (flavor == RPC_AUTH_MAXFLAVOR)
10403 		err = -EPERM;
10404 
10405 out_freepage:
10406 	put_page(page);
10407 	if (err == -EACCES)
10408 		return -EPERM;
10409 out:
10410 	return err;
10411 }
10412 
10413 static int _nfs41_test_stateid(struct nfs_server *server,
10414 			       const nfs4_stateid *stateid,
10415 			       const struct cred *cred)
10416 {
10417 	int status;
10418 	struct nfs41_test_stateid_args args = {
10419 		.stateid = *stateid,
10420 	};
10421 	struct nfs41_test_stateid_res res;
10422 	struct rpc_message msg = {
10423 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_TEST_STATEID],
10424 		.rpc_argp = &args,
10425 		.rpc_resp = &res,
10426 		.rpc_cred = cred,
10427 	};
10428 	struct rpc_clnt *rpc_client = server->client;
10429 
10430 	nfs4_state_protect(server->nfs_client, NFS_SP4_MACH_CRED_STATEID,
10431 		&rpc_client, &msg);
10432 
10433 	dprintk("NFS call  test_stateid %p\n", stateid);
10434 	nfs4_init_sequence(&args.seq_args, &res.seq_res, 0, 1);
10435 	status = nfs4_call_sync_sequence(rpc_client, server, &msg,
10436 			&args.seq_args, &res.seq_res);
10437 	if (status != NFS_OK) {
10438 		dprintk("NFS reply test_stateid: failed, %d\n", status);
10439 		return status;
10440 	}
10441 	dprintk("NFS reply test_stateid: succeeded, %d\n", -res.status);
10442 	return -res.status;
10443 }
10444 
10445 static void nfs4_handle_delay_or_session_error(struct nfs_server *server,
10446 		int err, struct nfs4_exception *exception)
10447 {
10448 	exception->retry = 0;
10449 	switch(err) {
10450 	case -NFS4ERR_DELAY:
10451 	case -NFS4ERR_RETRY_UNCACHED_REP:
10452 		nfs4_handle_exception(server, err, exception);
10453 		break;
10454 	case -NFS4ERR_BADSESSION:
10455 	case -NFS4ERR_BADSLOT:
10456 	case -NFS4ERR_BAD_HIGH_SLOT:
10457 	case -NFS4ERR_CONN_NOT_BOUND_TO_SESSION:
10458 	case -NFS4ERR_DEADSESSION:
10459 		nfs4_do_handle_exception(server, err, exception);
10460 	}
10461 }
10462 
10463 /**
10464  * nfs41_test_stateid - perform a TEST_STATEID operation
10465  *
10466  * @server: server / transport on which to perform the operation
10467  * @stateid: state ID to test
10468  * @cred: credential
10469  *
10470  * Returns NFS_OK if the server recognizes that "stateid" is valid.
10471  * Otherwise a negative NFS4ERR value is returned if the operation
10472  * failed or the state ID is not currently valid.
10473  */
10474 static int nfs41_test_stateid(struct nfs_server *server,
10475 			      const nfs4_stateid *stateid,
10476 			      const struct cred *cred)
10477 {
10478 	struct nfs4_exception exception = {
10479 		.interruptible = true,
10480 	};
10481 	int err;
10482 	do {
10483 		err = _nfs41_test_stateid(server, stateid, cred);
10484 		nfs4_handle_delay_or_session_error(server, err, &exception);
10485 	} while (exception.retry);
10486 	return err;
10487 }
10488 
10489 struct nfs_free_stateid_data {
10490 	struct nfs_server *server;
10491 	struct nfs41_free_stateid_args args;
10492 	struct nfs41_free_stateid_res res;
10493 };
10494 
10495 static void nfs41_free_stateid_prepare(struct rpc_task *task, void *calldata)
10496 {
10497 	struct nfs_free_stateid_data *data = calldata;
10498 	nfs4_setup_sequence(data->server->nfs_client,
10499 			&data->args.seq_args,
10500 			&data->res.seq_res,
10501 			task);
10502 }
10503 
10504 static void nfs41_free_stateid_done(struct rpc_task *task, void *calldata)
10505 {
10506 	struct nfs_free_stateid_data *data = calldata;
10507 
10508 	nfs41_sequence_done(task, &data->res.seq_res);
10509 
10510 	switch (task->tk_status) {
10511 	case -NFS4ERR_DELAY:
10512 		if (nfs4_async_handle_error(task, data->server, NULL, NULL) == -EAGAIN)
10513 			rpc_restart_call_prepare(task);
10514 	}
10515 }
10516 
10517 static void nfs41_free_stateid_release(void *calldata)
10518 {
10519 	struct nfs_free_stateid_data *data = calldata;
10520 	struct nfs_client *clp = data->server->nfs_client;
10521 
10522 	nfs_put_client(clp);
10523 	kfree(calldata);
10524 }
10525 
10526 static const struct rpc_call_ops nfs41_free_stateid_ops = {
10527 	.rpc_call_prepare = nfs41_free_stateid_prepare,
10528 	.rpc_call_done = nfs41_free_stateid_done,
10529 	.rpc_release = nfs41_free_stateid_release,
10530 };
10531 
10532 /**
10533  * nfs41_free_stateid - perform a FREE_STATEID operation
10534  *
10535  * @server: server / transport on which to perform the operation
10536  * @stateid: state ID to release
10537  * @cred: credential
10538  * @privileged: set to true if this call needs to be privileged
10539  *
10540  * Note: this function is always asynchronous.
10541  */
10542 static int nfs41_free_stateid(struct nfs_server *server,
10543 		const nfs4_stateid *stateid,
10544 		const struct cred *cred,
10545 		bool privileged)
10546 {
10547 	struct rpc_message msg = {
10548 		.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_FREE_STATEID],
10549 		.rpc_cred = cred,
10550 	};
10551 	struct rpc_task_setup task_setup = {
10552 		.rpc_client = server->client,
10553 		.rpc_message = &msg,
10554 		.callback_ops = &nfs41_free_stateid_ops,
10555 		.flags = RPC_TASK_ASYNC | RPC_TASK_MOVEABLE,
10556 	};
10557 	struct nfs_free_stateid_data *data;
10558 	struct rpc_task *task;
10559 	struct nfs_client *clp = server->nfs_client;
10560 
10561 	if (!refcount_inc_not_zero(&clp->cl_count))
10562 		return -EIO;
10563 
10564 	nfs4_state_protect(server->nfs_client, NFS_SP4_MACH_CRED_STATEID,
10565 		&task_setup.rpc_client, &msg);
10566 
10567 	dprintk("NFS call  free_stateid %p\n", stateid);
10568 	data = kmalloc(sizeof(*data), GFP_KERNEL);
10569 	if (!data)
10570 		return -ENOMEM;
10571 	data->server = server;
10572 	nfs4_stateid_copy(&data->args.stateid, stateid);
10573 
10574 	task_setup.callback_data = data;
10575 
10576 	msg.rpc_argp = &data->args;
10577 	msg.rpc_resp = &data->res;
10578 	nfs4_init_sequence(&data->args.seq_args, &data->res.seq_res, 1, privileged);
10579 	task = rpc_run_task(&task_setup);
10580 	if (IS_ERR(task))
10581 		return PTR_ERR(task);
10582 	rpc_put_task(task);
10583 	return 0;
10584 }
10585 
10586 static void
10587 nfs41_free_lock_state(struct nfs_server *server, struct nfs4_lock_state *lsp)
10588 {
10589 	const struct cred *cred = lsp->ls_state->owner->so_cred;
10590 
10591 	nfs41_free_stateid(server, &lsp->ls_stateid, cred, false);
10592 	nfs4_free_lock_state(server, lsp);
10593 }
10594 
10595 static bool nfs41_match_stateid(const nfs4_stateid *s1,
10596 		const nfs4_stateid *s2)
10597 {
10598 	if (s1->type != s2->type)
10599 		return false;
10600 
10601 	if (memcmp(s1->other, s2->other, sizeof(s1->other)) != 0)
10602 		return false;
10603 
10604 	if (s1->seqid == s2->seqid)
10605 		return true;
10606 
10607 	return s1->seqid == 0 || s2->seqid == 0;
10608 }
10609 
10610 #endif /* CONFIG_NFS_V4_1 */
10611 
10612 static bool nfs4_match_stateid(const nfs4_stateid *s1,
10613 		const nfs4_stateid *s2)
10614 {
10615 	return nfs4_stateid_match(s1, s2);
10616 }
10617 
10618 
10619 static const struct nfs4_state_recovery_ops nfs40_reboot_recovery_ops = {
10620 	.owner_flag_bit = NFS_OWNER_RECLAIM_REBOOT,
10621 	.state_flag_bit	= NFS_STATE_RECLAIM_REBOOT,
10622 	.recover_open	= nfs4_open_reclaim,
10623 	.recover_lock	= nfs4_lock_reclaim,
10624 	.establish_clid = nfs4_init_clientid,
10625 	.detect_trunking = nfs40_discover_server_trunking,
10626 };
10627 
10628 #if defined(CONFIG_NFS_V4_1)
10629 static const struct nfs4_state_recovery_ops nfs41_reboot_recovery_ops = {
10630 	.owner_flag_bit = NFS_OWNER_RECLAIM_REBOOT,
10631 	.state_flag_bit	= NFS_STATE_RECLAIM_REBOOT,
10632 	.recover_open	= nfs4_open_reclaim,
10633 	.recover_lock	= nfs4_lock_reclaim,
10634 	.establish_clid = nfs41_init_clientid,
10635 	.reclaim_complete = nfs41_proc_reclaim_complete,
10636 	.detect_trunking = nfs41_discover_server_trunking,
10637 };
10638 #endif /* CONFIG_NFS_V4_1 */
10639 
10640 static const struct nfs4_state_recovery_ops nfs40_nograce_recovery_ops = {
10641 	.owner_flag_bit = NFS_OWNER_RECLAIM_NOGRACE,
10642 	.state_flag_bit	= NFS_STATE_RECLAIM_NOGRACE,
10643 	.recover_open	= nfs40_open_expired,
10644 	.recover_lock	= nfs4_lock_expired,
10645 	.establish_clid = nfs4_init_clientid,
10646 };
10647 
10648 #if defined(CONFIG_NFS_V4_1)
10649 static const struct nfs4_state_recovery_ops nfs41_nograce_recovery_ops = {
10650 	.owner_flag_bit = NFS_OWNER_RECLAIM_NOGRACE,
10651 	.state_flag_bit	= NFS_STATE_RECLAIM_NOGRACE,
10652 	.recover_open	= nfs41_open_expired,
10653 	.recover_lock	= nfs41_lock_expired,
10654 	.establish_clid = nfs41_init_clientid,
10655 };
10656 #endif /* CONFIG_NFS_V4_1 */
10657 
10658 static const struct nfs4_state_maintenance_ops nfs40_state_renewal_ops = {
10659 	.sched_state_renewal = nfs4_proc_async_renew,
10660 	.get_state_renewal_cred = nfs4_get_renew_cred,
10661 	.renew_lease = nfs4_proc_renew,
10662 };
10663 
10664 #if defined(CONFIG_NFS_V4_1)
10665 static const struct nfs4_state_maintenance_ops nfs41_state_renewal_ops = {
10666 	.sched_state_renewal = nfs41_proc_async_sequence,
10667 	.get_state_renewal_cred = nfs4_get_machine_cred,
10668 	.renew_lease = nfs4_proc_sequence,
10669 };
10670 #endif
10671 
10672 static const struct nfs4_mig_recovery_ops nfs40_mig_recovery_ops = {
10673 	.get_locations = _nfs40_proc_get_locations,
10674 	.fsid_present = _nfs40_proc_fsid_present,
10675 };
10676 
10677 #if defined(CONFIG_NFS_V4_1)
10678 static const struct nfs4_mig_recovery_ops nfs41_mig_recovery_ops = {
10679 	.get_locations = _nfs41_proc_get_locations,
10680 	.fsid_present = _nfs41_proc_fsid_present,
10681 };
10682 #endif	/* CONFIG_NFS_V4_1 */
10683 
10684 static const struct nfs4_minor_version_ops nfs_v4_0_minor_ops = {
10685 	.minor_version = 0,
10686 	.init_caps = NFS_CAP_READDIRPLUS
10687 		| NFS_CAP_ATOMIC_OPEN
10688 		| NFS_CAP_POSIX_LOCK,
10689 	.init_client = nfs40_init_client,
10690 	.shutdown_client = nfs40_shutdown_client,
10691 	.match_stateid = nfs4_match_stateid,
10692 	.find_root_sec = nfs4_find_root_sec,
10693 	.free_lock_state = nfs4_release_lockowner,
10694 	.test_and_free_expired = nfs40_test_and_free_expired_stateid,
10695 	.alloc_seqid = nfs_alloc_seqid,
10696 	.call_sync_ops = &nfs40_call_sync_ops,
10697 	.reboot_recovery_ops = &nfs40_reboot_recovery_ops,
10698 	.nograce_recovery_ops = &nfs40_nograce_recovery_ops,
10699 	.state_renewal_ops = &nfs40_state_renewal_ops,
10700 	.mig_recovery_ops = &nfs40_mig_recovery_ops,
10701 };
10702 
10703 #if defined(CONFIG_NFS_V4_1)
10704 static struct nfs_seqid *
10705 nfs_alloc_no_seqid(struct nfs_seqid_counter *arg1, gfp_t arg2)
10706 {
10707 	return NULL;
10708 }
10709 
10710 static const struct nfs4_minor_version_ops nfs_v4_1_minor_ops = {
10711 	.minor_version = 1,
10712 	.init_caps = NFS_CAP_READDIRPLUS
10713 		| NFS_CAP_ATOMIC_OPEN
10714 		| NFS_CAP_POSIX_LOCK
10715 		| NFS_CAP_STATEID_NFSV41
10716 		| NFS_CAP_ATOMIC_OPEN_V1
10717 		| NFS_CAP_LGOPEN
10718 		| NFS_CAP_MOVEABLE,
10719 	.init_client = nfs41_init_client,
10720 	.shutdown_client = nfs41_shutdown_client,
10721 	.match_stateid = nfs41_match_stateid,
10722 	.find_root_sec = nfs41_find_root_sec,
10723 	.free_lock_state = nfs41_free_lock_state,
10724 	.test_and_free_expired = nfs41_test_and_free_expired_stateid,
10725 	.alloc_seqid = nfs_alloc_no_seqid,
10726 	.session_trunk = nfs4_test_session_trunk,
10727 	.call_sync_ops = &nfs41_call_sync_ops,
10728 	.reboot_recovery_ops = &nfs41_reboot_recovery_ops,
10729 	.nograce_recovery_ops = &nfs41_nograce_recovery_ops,
10730 	.state_renewal_ops = &nfs41_state_renewal_ops,
10731 	.mig_recovery_ops = &nfs41_mig_recovery_ops,
10732 };
10733 #endif
10734 
10735 #if defined(CONFIG_NFS_V4_2)
10736 static const struct nfs4_minor_version_ops nfs_v4_2_minor_ops = {
10737 	.minor_version = 2,
10738 	.init_caps = NFS_CAP_READDIRPLUS
10739 		| NFS_CAP_ATOMIC_OPEN
10740 		| NFS_CAP_POSIX_LOCK
10741 		| NFS_CAP_STATEID_NFSV41
10742 		| NFS_CAP_ATOMIC_OPEN_V1
10743 		| NFS_CAP_LGOPEN
10744 		| NFS_CAP_ALLOCATE
10745 		| NFS_CAP_COPY
10746 		| NFS_CAP_OFFLOAD_CANCEL
10747 		| NFS_CAP_COPY_NOTIFY
10748 		| NFS_CAP_DEALLOCATE
10749 		| NFS_CAP_SEEK
10750 		| NFS_CAP_LAYOUTSTATS
10751 		| NFS_CAP_CLONE
10752 		| NFS_CAP_LAYOUTERROR
10753 		| NFS_CAP_READ_PLUS
10754 		| NFS_CAP_MOVEABLE,
10755 	.init_client = nfs41_init_client,
10756 	.shutdown_client = nfs41_shutdown_client,
10757 	.match_stateid = nfs41_match_stateid,
10758 	.find_root_sec = nfs41_find_root_sec,
10759 	.free_lock_state = nfs41_free_lock_state,
10760 	.call_sync_ops = &nfs41_call_sync_ops,
10761 	.test_and_free_expired = nfs41_test_and_free_expired_stateid,
10762 	.alloc_seqid = nfs_alloc_no_seqid,
10763 	.session_trunk = nfs4_test_session_trunk,
10764 	.reboot_recovery_ops = &nfs41_reboot_recovery_ops,
10765 	.nograce_recovery_ops = &nfs41_nograce_recovery_ops,
10766 	.state_renewal_ops = &nfs41_state_renewal_ops,
10767 	.mig_recovery_ops = &nfs41_mig_recovery_ops,
10768 };
10769 #endif
10770 
10771 const struct nfs4_minor_version_ops *nfs_v4_minor_ops[] = {
10772 	[0] = &nfs_v4_0_minor_ops,
10773 #if defined(CONFIG_NFS_V4_1)
10774 	[1] = &nfs_v4_1_minor_ops,
10775 #endif
10776 #if defined(CONFIG_NFS_V4_2)
10777 	[2] = &nfs_v4_2_minor_ops,
10778 #endif
10779 };
10780 
10781 static ssize_t nfs4_listxattr(struct dentry *dentry, char *list, size_t size)
10782 {
10783 	ssize_t error, error2, error3;
10784 	size_t left = size;
10785 
10786 	error = generic_listxattr(dentry, list, left);
10787 	if (error < 0)
10788 		return error;
10789 	if (list) {
10790 		list += error;
10791 		left -= error;
10792 	}
10793 
10794 	error2 = nfs4_listxattr_nfs4_label(d_inode(dentry), list, left);
10795 	if (error2 < 0)
10796 		return error2;
10797 
10798 	if (list) {
10799 		list += error2;
10800 		left -= error2;
10801 	}
10802 
10803 	error3 = nfs4_listxattr_nfs4_user(d_inode(dentry), list, left);
10804 	if (error3 < 0)
10805 		return error3;
10806 
10807 	error += error2 + error3;
10808 	if (size && error > size)
10809 		return -ERANGE;
10810 	return error;
10811 }
10812 
10813 static void nfs4_enable_swap(struct inode *inode)
10814 {
10815 	/* The state manager thread must always be running.
10816 	 * It will notice the client is a swapper, and stay put.
10817 	 */
10818 	struct nfs_client *clp = NFS_SERVER(inode)->nfs_client;
10819 
10820 	nfs4_schedule_state_manager(clp);
10821 }
10822 
10823 static void nfs4_disable_swap(struct inode *inode)
10824 {
10825 	/* The state manager thread will now exit once it is
10826 	 * woken.
10827 	 */
10828 	struct nfs_client *clp = NFS_SERVER(inode)->nfs_client;
10829 
10830 	set_bit(NFS4CLNT_RUN_MANAGER, &clp->cl_state);
10831 	clear_bit(NFS4CLNT_MANAGER_AVAILABLE, &clp->cl_state);
10832 	wake_up_var(&clp->cl_state);
10833 }
10834 
10835 static const struct inode_operations nfs4_dir_inode_operations = {
10836 	.create		= nfs_create,
10837 	.lookup		= nfs_lookup,
10838 	.atomic_open	= nfs_atomic_open,
10839 	.link		= nfs_link,
10840 	.unlink		= nfs_unlink,
10841 	.symlink	= nfs_symlink,
10842 	.mkdir		= nfs_mkdir,
10843 	.rmdir		= nfs_rmdir,
10844 	.mknod		= nfs_mknod,
10845 	.rename		= nfs_rename,
10846 	.permission	= nfs_permission,
10847 	.getattr	= nfs_getattr,
10848 	.setattr	= nfs_setattr,
10849 	.listxattr	= nfs4_listxattr,
10850 };
10851 
10852 static const struct inode_operations nfs4_file_inode_operations = {
10853 	.permission	= nfs_permission,
10854 	.getattr	= nfs_getattr,
10855 	.setattr	= nfs_setattr,
10856 	.listxattr	= nfs4_listxattr,
10857 };
10858 
10859 const struct nfs_rpc_ops nfs_v4_clientops = {
10860 	.version	= 4,			/* protocol version */
10861 	.dentry_ops	= &nfs4_dentry_operations,
10862 	.dir_inode_ops	= &nfs4_dir_inode_operations,
10863 	.file_inode_ops	= &nfs4_file_inode_operations,
10864 	.file_ops	= &nfs4_file_operations,
10865 	.getroot	= nfs4_proc_get_root,
10866 	.submount	= nfs4_submount,
10867 	.try_get_tree	= nfs4_try_get_tree,
10868 	.getattr	= nfs4_proc_getattr,
10869 	.setattr	= nfs4_proc_setattr,
10870 	.lookup		= nfs4_proc_lookup,
10871 	.lookupp	= nfs4_proc_lookupp,
10872 	.access		= nfs4_proc_access,
10873 	.readlink	= nfs4_proc_readlink,
10874 	.create		= nfs4_proc_create,
10875 	.remove		= nfs4_proc_remove,
10876 	.unlink_setup	= nfs4_proc_unlink_setup,
10877 	.unlink_rpc_prepare = nfs4_proc_unlink_rpc_prepare,
10878 	.unlink_done	= nfs4_proc_unlink_done,
10879 	.rename_setup	= nfs4_proc_rename_setup,
10880 	.rename_rpc_prepare = nfs4_proc_rename_rpc_prepare,
10881 	.rename_done	= nfs4_proc_rename_done,
10882 	.link		= nfs4_proc_link,
10883 	.symlink	= nfs4_proc_symlink,
10884 	.mkdir		= nfs4_proc_mkdir,
10885 	.rmdir		= nfs4_proc_rmdir,
10886 	.readdir	= nfs4_proc_readdir,
10887 	.mknod		= nfs4_proc_mknod,
10888 	.statfs		= nfs4_proc_statfs,
10889 	.fsinfo		= nfs4_proc_fsinfo,
10890 	.pathconf	= nfs4_proc_pathconf,
10891 	.set_capabilities = nfs4_server_capabilities,
10892 	.decode_dirent	= nfs4_decode_dirent,
10893 	.pgio_rpc_prepare = nfs4_proc_pgio_rpc_prepare,
10894 	.read_setup	= nfs4_proc_read_setup,
10895 	.read_done	= nfs4_read_done,
10896 	.write_setup	= nfs4_proc_write_setup,
10897 	.write_done	= nfs4_write_done,
10898 	.commit_setup	= nfs4_proc_commit_setup,
10899 	.commit_rpc_prepare = nfs4_proc_commit_rpc_prepare,
10900 	.commit_done	= nfs4_commit_done,
10901 	.lock		= nfs4_proc_lock,
10902 	.clear_acl_cache = nfs4_zap_acl_attr,
10903 	.close_context  = nfs4_close_context,
10904 	.open_context	= nfs4_atomic_open,
10905 	.have_delegation = nfs4_have_delegation,
10906 	.return_delegation = nfs4_inode_return_delegation,
10907 	.alloc_client	= nfs4_alloc_client,
10908 	.init_client	= nfs4_init_client,
10909 	.free_client	= nfs4_free_client,
10910 	.create_server	= nfs4_create_server,
10911 	.clone_server	= nfs_clone_server,
10912 	.discover_trunking = nfs4_discover_trunking,
10913 	.enable_swap	= nfs4_enable_swap,
10914 	.disable_swap	= nfs4_disable_swap,
10915 };
10916 
10917 static const struct xattr_handler nfs4_xattr_nfs4_acl_handler = {
10918 	.name	= XATTR_NAME_NFSV4_ACL,
10919 	.list	= nfs4_xattr_list_nfs4_acl,
10920 	.get	= nfs4_xattr_get_nfs4_acl,
10921 	.set	= nfs4_xattr_set_nfs4_acl,
10922 };
10923 
10924 #if defined(CONFIG_NFS_V4_1)
10925 static const struct xattr_handler nfs4_xattr_nfs4_dacl_handler = {
10926 	.name	= XATTR_NAME_NFSV4_DACL,
10927 	.list	= nfs4_xattr_list_nfs4_dacl,
10928 	.get	= nfs4_xattr_get_nfs4_dacl,
10929 	.set	= nfs4_xattr_set_nfs4_dacl,
10930 };
10931 
10932 static const struct xattr_handler nfs4_xattr_nfs4_sacl_handler = {
10933 	.name	= XATTR_NAME_NFSV4_SACL,
10934 	.list	= nfs4_xattr_list_nfs4_sacl,
10935 	.get	= nfs4_xattr_get_nfs4_sacl,
10936 	.set	= nfs4_xattr_set_nfs4_sacl,
10937 };
10938 #endif
10939 
10940 #ifdef CONFIG_NFS_V4_2
10941 static const struct xattr_handler nfs4_xattr_nfs4_user_handler = {
10942 	.prefix	= XATTR_USER_PREFIX,
10943 	.get	= nfs4_xattr_get_nfs4_user,
10944 	.set	= nfs4_xattr_set_nfs4_user,
10945 };
10946 #endif
10947 
10948 const struct xattr_handler * const nfs4_xattr_handlers[] = {
10949 	&nfs4_xattr_nfs4_acl_handler,
10950 #if defined(CONFIG_NFS_V4_1)
10951 	&nfs4_xattr_nfs4_dacl_handler,
10952 	&nfs4_xattr_nfs4_sacl_handler,
10953 #endif
10954 #ifdef CONFIG_NFS_V4_SECURITY_LABEL
10955 	&nfs4_xattr_nfs4_label_handler,
10956 #endif
10957 #ifdef CONFIG_NFS_V4_2
10958 	&nfs4_xattr_nfs4_user_handler,
10959 #endif
10960 	NULL
10961 };
10962