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