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