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