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