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