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