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