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