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