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