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