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