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