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