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