Merge tag 'nfs-for-4.8-2' of git://git.linux-nfs.org/projects/trondmy/linux-nfs
[sfrench/cifs-2.6.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 nfs4_state *state, 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 *, nfs4_stateid *,
103                 struct rpc_cred *);
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_CHANGE
230         | FATTR4_WORD0_FILEID,
231 };
232
233 const u32 nfs4_statfs_bitmap[3] = {
234         FATTR4_WORD0_FILES_AVAIL
235         | FATTR4_WORD0_FILES_FREE
236         | FATTR4_WORD0_FILES_TOTAL,
237         FATTR4_WORD1_SPACE_AVAIL
238         | FATTR4_WORD1_SPACE_FREE
239         | FATTR4_WORD1_SPACE_TOTAL
240 };
241
242 const u32 nfs4_pathconf_bitmap[3] = {
243         FATTR4_WORD0_MAXLINK
244         | FATTR4_WORD0_MAXNAME,
245         0
246 };
247
248 const u32 nfs4_fsinfo_bitmap[3] = { FATTR4_WORD0_MAXFILESIZE
249                         | FATTR4_WORD0_MAXREAD
250                         | FATTR4_WORD0_MAXWRITE
251                         | FATTR4_WORD0_LEASE_TIME,
252                         FATTR4_WORD1_TIME_DELTA
253                         | FATTR4_WORD1_FS_LAYOUT_TYPES,
254                         FATTR4_WORD2_LAYOUT_BLKSIZE
255                         | FATTR4_WORD2_CLONE_BLKSIZE
256 };
257
258 const u32 nfs4_fs_locations_bitmap[3] = {
259         FATTR4_WORD0_TYPE
260         | FATTR4_WORD0_CHANGE
261         | FATTR4_WORD0_SIZE
262         | FATTR4_WORD0_FSID
263         | FATTR4_WORD0_FILEID
264         | FATTR4_WORD0_FS_LOCATIONS,
265         FATTR4_WORD1_MODE
266         | FATTR4_WORD1_NUMLINKS
267         | FATTR4_WORD1_OWNER
268         | FATTR4_WORD1_OWNER_GROUP
269         | FATTR4_WORD1_RAWDEV
270         | FATTR4_WORD1_SPACE_USED
271         | FATTR4_WORD1_TIME_ACCESS
272         | FATTR4_WORD1_TIME_METADATA
273         | FATTR4_WORD1_TIME_MODIFY
274         | FATTR4_WORD1_MOUNTED_ON_FILEID,
275 };
276
277 static void nfs4_setup_readdir(u64 cookie, __be32 *verifier, struct dentry *dentry,
278                 struct nfs4_readdir_arg *readdir)
279 {
280         __be32 *start, *p;
281
282         if (cookie > 2) {
283                 readdir->cookie = cookie;
284                 memcpy(&readdir->verifier, verifier, sizeof(readdir->verifier));
285                 return;
286         }
287
288         readdir->cookie = 0;
289         memset(&readdir->verifier, 0, sizeof(readdir->verifier));
290         if (cookie == 2)
291                 return;
292         
293         /*
294          * NFSv4 servers do not return entries for '.' and '..'
295          * Therefore, we fake these entries here.  We let '.'
296          * have cookie 0 and '..' have cookie 1.  Note that
297          * when talking to the server, we always send cookie 0
298          * instead of 1 or 2.
299          */
300         start = p = kmap_atomic(*readdir->pages);
301         
302         if (cookie == 0) {
303                 *p++ = xdr_one;                                  /* next */
304                 *p++ = xdr_zero;                   /* cookie, first word */
305                 *p++ = xdr_one;                   /* cookie, second word */
306                 *p++ = xdr_one;                             /* entry len */
307                 memcpy(p, ".\0\0\0", 4);                        /* entry */
308                 p++;
309                 *p++ = xdr_one;                         /* bitmap length */
310                 *p++ = htonl(FATTR4_WORD0_FILEID);             /* bitmap */
311                 *p++ = htonl(8);              /* attribute buffer length */
312                 p = xdr_encode_hyper(p, NFS_FILEID(d_inode(dentry)));
313         }
314         
315         *p++ = xdr_one;                                  /* next */
316         *p++ = xdr_zero;                   /* cookie, first word */
317         *p++ = xdr_two;                   /* cookie, second word */
318         *p++ = xdr_two;                             /* entry len */
319         memcpy(p, "..\0\0", 4);                         /* entry */
320         p++;
321         *p++ = xdr_one;                         /* bitmap length */
322         *p++ = htonl(FATTR4_WORD0_FILEID);             /* bitmap */
323         *p++ = htonl(8);              /* attribute buffer length */
324         p = xdr_encode_hyper(p, NFS_FILEID(d_inode(dentry->d_parent)));
325
326         readdir->pgbase = (char *)p - (char *)start;
327         readdir->count -= readdir->pgbase;
328         kunmap_atomic(start);
329 }
330
331 static long nfs4_update_delay(long *timeout)
332 {
333         long ret;
334         if (!timeout)
335                 return NFS4_POLL_RETRY_MAX;
336         if (*timeout <= 0)
337                 *timeout = NFS4_POLL_RETRY_MIN;
338         if (*timeout > NFS4_POLL_RETRY_MAX)
339                 *timeout = NFS4_POLL_RETRY_MAX;
340         ret = *timeout;
341         *timeout <<= 1;
342         return ret;
343 }
344
345 static int nfs4_delay(struct rpc_clnt *clnt, long *timeout)
346 {
347         int res = 0;
348
349         might_sleep();
350
351         freezable_schedule_timeout_killable_unsafe(
352                 nfs4_update_delay(timeout));
353         if (fatal_signal_pending(current))
354                 res = -ERESTARTSYS;
355         return res;
356 }
357
358 /* This is the error handling routine for processes that are allowed
359  * to sleep.
360  */
361 static int nfs4_do_handle_exception(struct nfs_server *server,
362                 int errorcode, struct nfs4_exception *exception)
363 {
364         struct nfs_client *clp = server->nfs_client;
365         struct nfs4_state *state = exception->state;
366         const nfs4_stateid *stateid = exception->stateid;
367         struct inode *inode = exception->inode;
368         int ret = errorcode;
369
370         exception->delay = 0;
371         exception->recovering = 0;
372         exception->retry = 0;
373         switch(errorcode) {
374                 case 0:
375                         return 0;
376                 case -NFS4ERR_OPENMODE:
377                 case -NFS4ERR_DELEG_REVOKED:
378                 case -NFS4ERR_ADMIN_REVOKED:
379                 case -NFS4ERR_BAD_STATEID:
380                         if (inode) {
381                                 int err;
382
383                                 err = nfs_async_inode_return_delegation(inode,
384                                                 stateid);
385                                 if (err == 0)
386                                         goto wait_on_recovery;
387                                 if (stateid != NULL && stateid->type == NFS4_DELEGATION_STATEID_TYPE) {
388                                         exception->retry = 1;
389                                         break;
390                                 }
391                         }
392                         if (state == NULL)
393                                 break;
394                         ret = nfs4_schedule_stateid_recovery(server, state);
395                         if (ret < 0)
396                                 break;
397                         goto wait_on_recovery;
398                 case -NFS4ERR_EXPIRED:
399                         if (state != NULL) {
400                                 ret = nfs4_schedule_stateid_recovery(server, state);
401                                 if (ret < 0)
402                                         break;
403                         }
404                 case -NFS4ERR_STALE_STATEID:
405                 case -NFS4ERR_STALE_CLIENTID:
406                         nfs4_schedule_lease_recovery(clp);
407                         goto wait_on_recovery;
408                 case -NFS4ERR_MOVED:
409                         ret = nfs4_schedule_migration_recovery(server);
410                         if (ret < 0)
411                                 break;
412                         goto wait_on_recovery;
413                 case -NFS4ERR_LEASE_MOVED:
414                         nfs4_schedule_lease_moved_recovery(clp);
415                         goto wait_on_recovery;
416 #if defined(CONFIG_NFS_V4_1)
417                 case -NFS4ERR_BADSESSION:
418                 case -NFS4ERR_BADSLOT:
419                 case -NFS4ERR_BAD_HIGH_SLOT:
420                 case -NFS4ERR_CONN_NOT_BOUND_TO_SESSION:
421                 case -NFS4ERR_DEADSESSION:
422                 case -NFS4ERR_SEQ_FALSE_RETRY:
423                 case -NFS4ERR_SEQ_MISORDERED:
424                         dprintk("%s ERROR: %d Reset session\n", __func__,
425                                 errorcode);
426                         nfs4_schedule_session_recovery(clp->cl_session, errorcode);
427                         goto wait_on_recovery;
428 #endif /* defined(CONFIG_NFS_V4_1) */
429                 case -NFS4ERR_FILE_OPEN:
430                         if (exception->timeout > HZ) {
431                                 /* We have retried a decent amount, time to
432                                  * fail
433                                  */
434                                 ret = -EBUSY;
435                                 break;
436                         }
437                 case -NFS4ERR_DELAY:
438                         nfs_inc_server_stats(server, NFSIOS_DELAY);
439                 case -NFS4ERR_GRACE:
440                 case -NFS4ERR_LAYOUTTRYLATER:
441                 case -NFS4ERR_RECALLCONFLICT:
442                         exception->delay = 1;
443                         return 0;
444
445                 case -NFS4ERR_RETRY_UNCACHED_REP:
446                 case -NFS4ERR_OLD_STATEID:
447                         exception->retry = 1;
448                         break;
449                 case -NFS4ERR_BADOWNER:
450                         /* The following works around a Linux server bug! */
451                 case -NFS4ERR_BADNAME:
452                         if (server->caps & NFS_CAP_UIDGID_NOMAP) {
453                                 server->caps &= ~NFS_CAP_UIDGID_NOMAP;
454                                 exception->retry = 1;
455                                 printk(KERN_WARNING "NFS: v4 server %s "
456                                                 "does not accept raw "
457                                                 "uid/gids. "
458                                                 "Reenabling the idmapper.\n",
459                                                 server->nfs_client->cl_hostname);
460                         }
461         }
462         /* We failed to handle the error */
463         return nfs4_map_errors(ret);
464 wait_on_recovery:
465         exception->recovering = 1;
466         return 0;
467 }
468
469 /* This is the error handling routine for processes that are allowed
470  * to sleep.
471  */
472 int nfs4_handle_exception(struct nfs_server *server, int errorcode, struct nfs4_exception *exception)
473 {
474         struct nfs_client *clp = server->nfs_client;
475         int ret;
476
477         ret = nfs4_do_handle_exception(server, errorcode, exception);
478         if (exception->delay) {
479                 ret = nfs4_delay(server->client, &exception->timeout);
480                 goto out_retry;
481         }
482         if (exception->recovering) {
483                 ret = nfs4_wait_clnt_recover(clp);
484                 if (test_bit(NFS_MIG_FAILED, &server->mig_status))
485                         return -EIO;
486                 goto out_retry;
487         }
488         return ret;
489 out_retry:
490         if (ret == 0)
491                 exception->retry = 1;
492         return ret;
493 }
494
495 static int
496 nfs4_async_handle_exception(struct rpc_task *task, struct nfs_server *server,
497                 int errorcode, struct nfs4_exception *exception)
498 {
499         struct nfs_client *clp = server->nfs_client;
500         int ret;
501
502         ret = nfs4_do_handle_exception(server, errorcode, exception);
503         if (exception->delay) {
504                 rpc_delay(task, nfs4_update_delay(&exception->timeout));
505                 goto out_retry;
506         }
507         if (exception->recovering) {
508                 rpc_sleep_on(&clp->cl_rpcwaitq, task, NULL);
509                 if (test_bit(NFS4CLNT_MANAGER_RUNNING, &clp->cl_state) == 0)
510                         rpc_wake_up_queued_task(&clp->cl_rpcwaitq, task);
511                 goto out_retry;
512         }
513         if (test_bit(NFS_MIG_FAILED, &server->mig_status))
514                 ret = -EIO;
515         return ret;
516 out_retry:
517         if (ret == 0)
518                 exception->retry = 1;
519         return ret;
520 }
521
522 static int
523 nfs4_async_handle_error(struct rpc_task *task, struct nfs_server *server,
524                         struct nfs4_state *state, long *timeout)
525 {
526         struct nfs4_exception exception = {
527                 .state = state,
528         };
529
530         if (task->tk_status >= 0)
531                 return 0;
532         if (timeout)
533                 exception.timeout = *timeout;
534         task->tk_status = nfs4_async_handle_exception(task, server,
535                         task->tk_status,
536                         &exception);
537         if (exception.delay && timeout)
538                 *timeout = exception.timeout;
539         if (exception.retry)
540                 return -EAGAIN;
541         return 0;
542 }
543
544 /*
545  * Return 'true' if 'clp' is using an rpc_client that is integrity protected
546  * or 'false' otherwise.
547  */
548 static bool _nfs4_is_integrity_protected(struct nfs_client *clp)
549 {
550         rpc_authflavor_t flavor = clp->cl_rpcclient->cl_auth->au_flavor;
551
552         if (flavor == RPC_AUTH_GSS_KRB5I ||
553             flavor == RPC_AUTH_GSS_KRB5P)
554                 return true;
555
556         return false;
557 }
558
559 static void do_renew_lease(struct nfs_client *clp, unsigned long timestamp)
560 {
561         spin_lock(&clp->cl_lock);
562         if (time_before(clp->cl_last_renewal,timestamp))
563                 clp->cl_last_renewal = timestamp;
564         spin_unlock(&clp->cl_lock);
565 }
566
567 static void renew_lease(const struct nfs_server *server, unsigned long timestamp)
568 {
569         struct nfs_client *clp = server->nfs_client;
570
571         if (!nfs4_has_session(clp))
572                 do_renew_lease(clp, timestamp);
573 }
574
575 struct nfs4_call_sync_data {
576         const struct nfs_server *seq_server;
577         struct nfs4_sequence_args *seq_args;
578         struct nfs4_sequence_res *seq_res;
579 };
580
581 void nfs4_init_sequence(struct nfs4_sequence_args *args,
582                         struct nfs4_sequence_res *res, int cache_reply)
583 {
584         args->sa_slot = NULL;
585         args->sa_cache_this = cache_reply;
586         args->sa_privileged = 0;
587
588         res->sr_slot = NULL;
589 }
590
591 static void nfs4_set_sequence_privileged(struct nfs4_sequence_args *args)
592 {
593         args->sa_privileged = 1;
594 }
595
596 int nfs40_setup_sequence(struct nfs4_slot_table *tbl,
597                          struct nfs4_sequence_args *args,
598                          struct nfs4_sequence_res *res,
599                          struct rpc_task *task)
600 {
601         struct nfs4_slot *slot;
602
603         /* slot already allocated? */
604         if (res->sr_slot != NULL)
605                 goto out_start;
606
607         spin_lock(&tbl->slot_tbl_lock);
608         if (nfs4_slot_tbl_draining(tbl) && !args->sa_privileged)
609                 goto out_sleep;
610
611         slot = nfs4_alloc_slot(tbl);
612         if (IS_ERR(slot)) {
613                 if (slot == ERR_PTR(-ENOMEM))
614                         task->tk_timeout = HZ >> 2;
615                 goto out_sleep;
616         }
617         spin_unlock(&tbl->slot_tbl_lock);
618
619         args->sa_slot = slot;
620         res->sr_slot = slot;
621
622 out_start:
623         rpc_call_start(task);
624         return 0;
625
626 out_sleep:
627         if (args->sa_privileged)
628                 rpc_sleep_on_priority(&tbl->slot_tbl_waitq, task,
629                                 NULL, RPC_PRIORITY_PRIVILEGED);
630         else
631                 rpc_sleep_on(&tbl->slot_tbl_waitq, task, NULL);
632         spin_unlock(&tbl->slot_tbl_lock);
633         return -EAGAIN;
634 }
635 EXPORT_SYMBOL_GPL(nfs40_setup_sequence);
636
637 static int nfs40_sequence_done(struct rpc_task *task,
638                                struct nfs4_sequence_res *res)
639 {
640         struct nfs4_slot *slot = res->sr_slot;
641         struct nfs4_slot_table *tbl;
642
643         if (slot == NULL)
644                 goto out;
645
646         tbl = slot->table;
647         spin_lock(&tbl->slot_tbl_lock);
648         if (!nfs41_wake_and_assign_slot(tbl, slot))
649                 nfs4_free_slot(tbl, slot);
650         spin_unlock(&tbl->slot_tbl_lock);
651
652         res->sr_slot = NULL;
653 out:
654         return 1;
655 }
656
657 #if defined(CONFIG_NFS_V4_1)
658
659 static void nfs41_sequence_free_slot(struct nfs4_sequence_res *res)
660 {
661         struct nfs4_session *session;
662         struct nfs4_slot_table *tbl;
663         struct nfs4_slot *slot = res->sr_slot;
664         bool send_new_highest_used_slotid = false;
665
666         tbl = slot->table;
667         session = tbl->session;
668
669         spin_lock(&tbl->slot_tbl_lock);
670         /* Be nice to the server: try to ensure that the last transmitted
671          * value for highest_user_slotid <= target_highest_slotid
672          */
673         if (tbl->highest_used_slotid > tbl->target_highest_slotid)
674                 send_new_highest_used_slotid = true;
675
676         if (nfs41_wake_and_assign_slot(tbl, slot)) {
677                 send_new_highest_used_slotid = false;
678                 goto out_unlock;
679         }
680         nfs4_free_slot(tbl, slot);
681
682         if (tbl->highest_used_slotid != NFS4_NO_SLOT)
683                 send_new_highest_used_slotid = false;
684 out_unlock:
685         spin_unlock(&tbl->slot_tbl_lock);
686         res->sr_slot = NULL;
687         if (send_new_highest_used_slotid)
688                 nfs41_notify_server(session->clp);
689 }
690
691 int nfs41_sequence_done(struct rpc_task *task, struct nfs4_sequence_res *res)
692 {
693         struct nfs4_session *session;
694         struct nfs4_slot *slot = res->sr_slot;
695         struct nfs_client *clp;
696         bool interrupted = false;
697         int ret = 1;
698
699         if (slot == NULL)
700                 goto out_noaction;
701         /* don't increment the sequence number if the task wasn't sent */
702         if (!RPC_WAS_SENT(task))
703                 goto out;
704
705         session = slot->table->session;
706
707         if (slot->interrupted) {
708                 slot->interrupted = 0;
709                 interrupted = true;
710         }
711
712         trace_nfs4_sequence_done(session, res);
713         /* Check the SEQUENCE operation status */
714         switch (res->sr_status) {
715         case 0:
716                 /* Update the slot's sequence and clientid lease timer */
717                 ++slot->seq_nr;
718                 clp = session->clp;
719                 do_renew_lease(clp, res->sr_timestamp);
720                 /* Check sequence flags */
721                 nfs41_handle_sequence_flag_errors(clp, res->sr_status_flags);
722                 nfs41_update_target_slotid(slot->table, slot, res);
723                 break;
724         case 1:
725                 /*
726                  * sr_status remains 1 if an RPC level error occurred.
727                  * The server may or may not have processed the sequence
728                  * operation..
729                  * Mark the slot as having hosted an interrupted RPC call.
730                  */
731                 slot->interrupted = 1;
732                 goto out;
733         case -NFS4ERR_DELAY:
734                 /* The server detected a resend of the RPC call and
735                  * returned NFS4ERR_DELAY as per Section 2.10.6.2
736                  * of RFC5661.
737                  */
738                 dprintk("%s: slot=%u seq=%u: Operation in progress\n",
739                         __func__,
740                         slot->slot_nr,
741                         slot->seq_nr);
742                 goto out_retry;
743         case -NFS4ERR_BADSLOT:
744                 /*
745                  * The slot id we used was probably retired. Try again
746                  * using a different slot id.
747                  */
748                 goto retry_nowait;
749         case -NFS4ERR_SEQ_MISORDERED:
750                 /*
751                  * Was the last operation on this sequence interrupted?
752                  * If so, retry after bumping the sequence number.
753                  */
754                 if (interrupted) {
755                         ++slot->seq_nr;
756                         goto retry_nowait;
757                 }
758                 /*
759                  * Could this slot have been previously retired?
760                  * If so, then the server may be expecting seq_nr = 1!
761                  */
762                 if (slot->seq_nr != 1) {
763                         slot->seq_nr = 1;
764                         goto retry_nowait;
765                 }
766                 break;
767         case -NFS4ERR_SEQ_FALSE_RETRY:
768                 ++slot->seq_nr;
769                 goto retry_nowait;
770         default:
771                 /* Just update the slot sequence no. */
772                 ++slot->seq_nr;
773         }
774 out:
775         /* The session may be reset by one of the error handlers. */
776         dprintk("%s: Error %d free the slot \n", __func__, res->sr_status);
777         nfs41_sequence_free_slot(res);
778 out_noaction:
779         return ret;
780 retry_nowait:
781         if (rpc_restart_call_prepare(task)) {
782                 task->tk_status = 0;
783                 ret = 0;
784         }
785         goto out;
786 out_retry:
787         if (!rpc_restart_call(task))
788                 goto out;
789         rpc_delay(task, NFS4_POLL_RETRY_MAX);
790         return 0;
791 }
792 EXPORT_SYMBOL_GPL(nfs41_sequence_done);
793
794 int nfs4_sequence_done(struct rpc_task *task, struct nfs4_sequence_res *res)
795 {
796         if (res->sr_slot == NULL)
797                 return 1;
798         if (!res->sr_slot->table->session)
799                 return nfs40_sequence_done(task, res);
800         return nfs41_sequence_done(task, res);
801 }
802 EXPORT_SYMBOL_GPL(nfs4_sequence_done);
803
804 int nfs41_setup_sequence(struct nfs4_session *session,
805                                 struct nfs4_sequence_args *args,
806                                 struct nfs4_sequence_res *res,
807                                 struct rpc_task *task)
808 {
809         struct nfs4_slot *slot;
810         struct nfs4_slot_table *tbl;
811
812         dprintk("--> %s\n", __func__);
813         /* slot already allocated? */
814         if (res->sr_slot != NULL)
815                 goto out_success;
816
817         tbl = &session->fc_slot_table;
818
819         task->tk_timeout = 0;
820
821         spin_lock(&tbl->slot_tbl_lock);
822         if (test_bit(NFS4_SLOT_TBL_DRAINING, &tbl->slot_tbl_state) &&
823             !args->sa_privileged) {
824                 /* The state manager will wait until the slot table is empty */
825                 dprintk("%s session is draining\n", __func__);
826                 goto out_sleep;
827         }
828
829         slot = nfs4_alloc_slot(tbl);
830         if (IS_ERR(slot)) {
831                 /* If out of memory, try again in 1/4 second */
832                 if (slot == ERR_PTR(-ENOMEM))
833                         task->tk_timeout = HZ >> 2;
834                 dprintk("<-- %s: no free slots\n", __func__);
835                 goto out_sleep;
836         }
837         spin_unlock(&tbl->slot_tbl_lock);
838
839         args->sa_slot = slot;
840
841         dprintk("<-- %s slotid=%u seqid=%u\n", __func__,
842                         slot->slot_nr, slot->seq_nr);
843
844         res->sr_slot = slot;
845         res->sr_timestamp = jiffies;
846         res->sr_status_flags = 0;
847         /*
848          * sr_status is only set in decode_sequence, and so will remain
849          * set to 1 if an rpc level failure occurs.
850          */
851         res->sr_status = 1;
852         trace_nfs4_setup_sequence(session, args);
853 out_success:
854         rpc_call_start(task);
855         return 0;
856 out_sleep:
857         /* Privileged tasks are queued with top priority */
858         if (args->sa_privileged)
859                 rpc_sleep_on_priority(&tbl->slot_tbl_waitq, task,
860                                 NULL, RPC_PRIORITY_PRIVILEGED);
861         else
862                 rpc_sleep_on(&tbl->slot_tbl_waitq, task, NULL);
863         spin_unlock(&tbl->slot_tbl_lock);
864         return -EAGAIN;
865 }
866 EXPORT_SYMBOL_GPL(nfs41_setup_sequence);
867
868 static int nfs4_setup_sequence(const struct nfs_server *server,
869                                struct nfs4_sequence_args *args,
870                                struct nfs4_sequence_res *res,
871                                struct rpc_task *task)
872 {
873         struct nfs4_session *session = nfs4_get_session(server);
874         int ret = 0;
875
876         if (!session)
877                 return nfs40_setup_sequence(server->nfs_client->cl_slot_tbl,
878                                             args, res, task);
879
880         dprintk("--> %s clp %p session %p sr_slot %u\n",
881                 __func__, session->clp, session, res->sr_slot ?
882                         res->sr_slot->slot_nr : NFS4_NO_SLOT);
883
884         ret = nfs41_setup_sequence(session, args, res, task);
885
886         dprintk("<-- %s status=%d\n", __func__, ret);
887         return ret;
888 }
889
890 static void nfs41_call_sync_prepare(struct rpc_task *task, void *calldata)
891 {
892         struct nfs4_call_sync_data *data = calldata;
893         struct nfs4_session *session = nfs4_get_session(data->seq_server);
894
895         dprintk("--> %s data->seq_server %p\n", __func__, data->seq_server);
896
897         nfs41_setup_sequence(session, data->seq_args, data->seq_res, task);
898 }
899
900 static void nfs41_call_sync_done(struct rpc_task *task, void *calldata)
901 {
902         struct nfs4_call_sync_data *data = calldata;
903
904         nfs41_sequence_done(task, data->seq_res);
905 }
906
907 static const struct rpc_call_ops nfs41_call_sync_ops = {
908         .rpc_call_prepare = nfs41_call_sync_prepare,
909         .rpc_call_done = nfs41_call_sync_done,
910 };
911
912 #else   /* !CONFIG_NFS_V4_1 */
913
914 static int nfs4_setup_sequence(const struct nfs_server *server,
915                                struct nfs4_sequence_args *args,
916                                struct nfs4_sequence_res *res,
917                                struct rpc_task *task)
918 {
919         return nfs40_setup_sequence(server->nfs_client->cl_slot_tbl,
920                                     args, res, task);
921 }
922
923 int nfs4_sequence_done(struct rpc_task *task,
924                        struct nfs4_sequence_res *res)
925 {
926         return nfs40_sequence_done(task, res);
927 }
928 EXPORT_SYMBOL_GPL(nfs4_sequence_done);
929
930 #endif  /* !CONFIG_NFS_V4_1 */
931
932 static void nfs40_call_sync_prepare(struct rpc_task *task, void *calldata)
933 {
934         struct nfs4_call_sync_data *data = calldata;
935         nfs4_setup_sequence(data->seq_server,
936                                 data->seq_args, data->seq_res, task);
937 }
938
939 static void nfs40_call_sync_done(struct rpc_task *task, void *calldata)
940 {
941         struct nfs4_call_sync_data *data = calldata;
942         nfs4_sequence_done(task, data->seq_res);
943 }
944
945 static const struct rpc_call_ops nfs40_call_sync_ops = {
946         .rpc_call_prepare = nfs40_call_sync_prepare,
947         .rpc_call_done = nfs40_call_sync_done,
948 };
949
950 static int nfs4_call_sync_sequence(struct rpc_clnt *clnt,
951                                    struct nfs_server *server,
952                                    struct rpc_message *msg,
953                                    struct nfs4_sequence_args *args,
954                                    struct nfs4_sequence_res *res)
955 {
956         int ret;
957         struct rpc_task *task;
958         struct nfs_client *clp = server->nfs_client;
959         struct nfs4_call_sync_data data = {
960                 .seq_server = server,
961                 .seq_args = args,
962                 .seq_res = res,
963         };
964         struct rpc_task_setup task_setup = {
965                 .rpc_client = clnt,
966                 .rpc_message = msg,
967                 .callback_ops = clp->cl_mvops->call_sync_ops,
968                 .callback_data = &data
969         };
970
971         task = rpc_run_task(&task_setup);
972         if (IS_ERR(task))
973                 ret = PTR_ERR(task);
974         else {
975                 ret = task->tk_status;
976                 rpc_put_task(task);
977         }
978         return ret;
979 }
980
981 int nfs4_call_sync(struct rpc_clnt *clnt,
982                    struct nfs_server *server,
983                    struct rpc_message *msg,
984                    struct nfs4_sequence_args *args,
985                    struct nfs4_sequence_res *res,
986                    int cache_reply)
987 {
988         nfs4_init_sequence(args, res, cache_reply);
989         return nfs4_call_sync_sequence(clnt, server, msg, args, res);
990 }
991
992 static void update_changeattr(struct inode *dir, struct nfs4_change_info *cinfo)
993 {
994         struct nfs_inode *nfsi = NFS_I(dir);
995
996         spin_lock(&dir->i_lock);
997         nfsi->cache_validity |= NFS_INO_INVALID_ATTR|NFS_INO_INVALID_DATA;
998         if (!cinfo->atomic || cinfo->before != dir->i_version)
999                 nfs_force_lookup_revalidate(dir);
1000         dir->i_version = cinfo->after;
1001         nfsi->attr_gencount = nfs_inc_attr_generation_counter();
1002         nfs_fscache_invalidate(dir);
1003         spin_unlock(&dir->i_lock);
1004 }
1005
1006 struct nfs4_opendata {
1007         struct kref kref;
1008         struct nfs_openargs o_arg;
1009         struct nfs_openres o_res;
1010         struct nfs_open_confirmargs c_arg;
1011         struct nfs_open_confirmres c_res;
1012         struct nfs4_string owner_name;
1013         struct nfs4_string group_name;
1014         struct nfs4_label *a_label;
1015         struct nfs_fattr f_attr;
1016         struct nfs4_label *f_label;
1017         struct dentry *dir;
1018         struct dentry *dentry;
1019         struct nfs4_state_owner *owner;
1020         struct nfs4_state *state;
1021         struct iattr attrs;
1022         unsigned long timestamp;
1023         unsigned int rpc_done : 1;
1024         unsigned int file_created : 1;
1025         unsigned int is_recover : 1;
1026         int rpc_status;
1027         int cancelled;
1028 };
1029
1030 static bool nfs4_clear_cap_atomic_open_v1(struct nfs_server *server,
1031                 int err, struct nfs4_exception *exception)
1032 {
1033         if (err != -EINVAL)
1034                 return false;
1035         if (!(server->caps & NFS_CAP_ATOMIC_OPEN_V1))
1036                 return false;
1037         server->caps &= ~NFS_CAP_ATOMIC_OPEN_V1;
1038         exception->retry = 1;
1039         return true;
1040 }
1041
1042 static u32
1043 nfs4_map_atomic_open_share(struct nfs_server *server,
1044                 fmode_t fmode, int openflags)
1045 {
1046         u32 res = 0;
1047
1048         switch (fmode & (FMODE_READ | FMODE_WRITE)) {
1049         case FMODE_READ:
1050                 res = NFS4_SHARE_ACCESS_READ;
1051                 break;
1052         case FMODE_WRITE:
1053                 res = NFS4_SHARE_ACCESS_WRITE;
1054                 break;
1055         case FMODE_READ|FMODE_WRITE:
1056                 res = NFS4_SHARE_ACCESS_BOTH;
1057         }
1058         if (!(server->caps & NFS_CAP_ATOMIC_OPEN_V1))
1059                 goto out;
1060         /* Want no delegation if we're using O_DIRECT */
1061         if (openflags & O_DIRECT)
1062                 res |= NFS4_SHARE_WANT_NO_DELEG;
1063 out:
1064         return res;
1065 }
1066
1067 static enum open_claim_type4
1068 nfs4_map_atomic_open_claim(struct nfs_server *server,
1069                 enum open_claim_type4 claim)
1070 {
1071         if (server->caps & NFS_CAP_ATOMIC_OPEN_V1)
1072                 return claim;
1073         switch (claim) {
1074         default:
1075                 return claim;
1076         case NFS4_OPEN_CLAIM_FH:
1077                 return NFS4_OPEN_CLAIM_NULL;
1078         case NFS4_OPEN_CLAIM_DELEG_CUR_FH:
1079                 return NFS4_OPEN_CLAIM_DELEGATE_CUR;
1080         case NFS4_OPEN_CLAIM_DELEG_PREV_FH:
1081                 return NFS4_OPEN_CLAIM_DELEGATE_PREV;
1082         }
1083 }
1084
1085 static void nfs4_init_opendata_res(struct nfs4_opendata *p)
1086 {
1087         p->o_res.f_attr = &p->f_attr;
1088         p->o_res.f_label = p->f_label;
1089         p->o_res.seqid = p->o_arg.seqid;
1090         p->c_res.seqid = p->c_arg.seqid;
1091         p->o_res.server = p->o_arg.server;
1092         p->o_res.access_request = p->o_arg.access;
1093         nfs_fattr_init(&p->f_attr);
1094         nfs_fattr_init_names(&p->f_attr, &p->owner_name, &p->group_name);
1095 }
1096
1097 static struct nfs4_opendata *nfs4_opendata_alloc(struct dentry *dentry,
1098                 struct nfs4_state_owner *sp, fmode_t fmode, int flags,
1099                 const struct iattr *attrs,
1100                 struct nfs4_label *label,
1101                 enum open_claim_type4 claim,
1102                 gfp_t gfp_mask)
1103 {
1104         struct dentry *parent = dget_parent(dentry);
1105         struct inode *dir = d_inode(parent);
1106         struct nfs_server *server = NFS_SERVER(dir);
1107         struct nfs_seqid *(*alloc_seqid)(struct nfs_seqid_counter *, gfp_t);
1108         struct nfs4_opendata *p;
1109
1110         p = kzalloc(sizeof(*p), gfp_mask);
1111         if (p == NULL)
1112                 goto err;
1113
1114         p->f_label = nfs4_label_alloc(server, gfp_mask);
1115         if (IS_ERR(p->f_label))
1116                 goto err_free_p;
1117
1118         p->a_label = nfs4_label_alloc(server, gfp_mask);
1119         if (IS_ERR(p->a_label))
1120                 goto err_free_f;
1121
1122         alloc_seqid = server->nfs_client->cl_mvops->alloc_seqid;
1123         p->o_arg.seqid = alloc_seqid(&sp->so_seqid, gfp_mask);
1124         if (IS_ERR(p->o_arg.seqid))
1125                 goto err_free_label;
1126         nfs_sb_active(dentry->d_sb);
1127         p->dentry = dget(dentry);
1128         p->dir = parent;
1129         p->owner = sp;
1130         atomic_inc(&sp->so_count);
1131         p->o_arg.open_flags = flags;
1132         p->o_arg.fmode = fmode & (FMODE_READ|FMODE_WRITE);
1133         p->o_arg.share_access = nfs4_map_atomic_open_share(server,
1134                         fmode, flags);
1135         /* don't put an ACCESS op in OPEN compound if O_EXCL, because ACCESS
1136          * will return permission denied for all bits until close */
1137         if (!(flags & O_EXCL)) {
1138                 /* ask server to check for all possible rights as results
1139                  * are cached */
1140                 p->o_arg.access = NFS4_ACCESS_READ | NFS4_ACCESS_MODIFY |
1141                                   NFS4_ACCESS_EXTEND | NFS4_ACCESS_EXECUTE;
1142         }
1143         p->o_arg.clientid = server->nfs_client->cl_clientid;
1144         p->o_arg.id.create_time = ktime_to_ns(sp->so_seqid.create_time);
1145         p->o_arg.id.uniquifier = sp->so_seqid.owner_id;
1146         p->o_arg.name = &dentry->d_name;
1147         p->o_arg.server = server;
1148         p->o_arg.bitmask = nfs4_bitmask(server, label);
1149         p->o_arg.open_bitmap = &nfs4_fattr_bitmap[0];
1150         p->o_arg.label = nfs4_label_copy(p->a_label, label);
1151         p->o_arg.claim = nfs4_map_atomic_open_claim(server, claim);
1152         switch (p->o_arg.claim) {
1153         case NFS4_OPEN_CLAIM_NULL:
1154         case NFS4_OPEN_CLAIM_DELEGATE_CUR:
1155         case NFS4_OPEN_CLAIM_DELEGATE_PREV:
1156                 p->o_arg.fh = NFS_FH(dir);
1157                 break;
1158         case NFS4_OPEN_CLAIM_PREVIOUS:
1159         case NFS4_OPEN_CLAIM_FH:
1160         case NFS4_OPEN_CLAIM_DELEG_CUR_FH:
1161         case NFS4_OPEN_CLAIM_DELEG_PREV_FH:
1162                 p->o_arg.fh = NFS_FH(d_inode(dentry));
1163         }
1164         if (attrs != NULL && attrs->ia_valid != 0) {
1165                 __u32 verf[2];
1166
1167                 p->o_arg.u.attrs = &p->attrs;
1168                 memcpy(&p->attrs, attrs, sizeof(p->attrs));
1169
1170                 verf[0] = jiffies;
1171                 verf[1] = current->pid;
1172                 memcpy(p->o_arg.u.verifier.data, verf,
1173                                 sizeof(p->o_arg.u.verifier.data));
1174         }
1175         p->c_arg.fh = &p->o_res.fh;
1176         p->c_arg.stateid = &p->o_res.stateid;
1177         p->c_arg.seqid = p->o_arg.seqid;
1178         nfs4_init_opendata_res(p);
1179         kref_init(&p->kref);
1180         return p;
1181
1182 err_free_label:
1183         nfs4_label_free(p->a_label);
1184 err_free_f:
1185         nfs4_label_free(p->f_label);
1186 err_free_p:
1187         kfree(p);
1188 err:
1189         dput(parent);
1190         return NULL;
1191 }
1192
1193 static void nfs4_opendata_free(struct kref *kref)
1194 {
1195         struct nfs4_opendata *p = container_of(kref,
1196                         struct nfs4_opendata, kref);
1197         struct super_block *sb = p->dentry->d_sb;
1198
1199         nfs_free_seqid(p->o_arg.seqid);
1200         if (p->state != NULL)
1201                 nfs4_put_open_state(p->state);
1202         nfs4_put_state_owner(p->owner);
1203
1204         nfs4_label_free(p->a_label);
1205         nfs4_label_free(p->f_label);
1206
1207         dput(p->dir);
1208         dput(p->dentry);
1209         nfs_sb_deactive(sb);
1210         nfs_fattr_free_names(&p->f_attr);
1211         kfree(p->f_attr.mdsthreshold);
1212         kfree(p);
1213 }
1214
1215 static void nfs4_opendata_put(struct nfs4_opendata *p)
1216 {
1217         if (p != NULL)
1218                 kref_put(&p->kref, nfs4_opendata_free);
1219 }
1220
1221 static int nfs4_wait_for_completion_rpc_task(struct rpc_task *task)
1222 {
1223         int ret;
1224
1225         ret = rpc_wait_for_completion_task(task);
1226         return ret;
1227 }
1228
1229 static bool nfs4_mode_match_open_stateid(struct nfs4_state *state,
1230                 fmode_t fmode)
1231 {
1232         switch(fmode & (FMODE_READ|FMODE_WRITE)) {
1233         case FMODE_READ|FMODE_WRITE:
1234                 return state->n_rdwr != 0;
1235         case FMODE_WRITE:
1236                 return state->n_wronly != 0;
1237         case FMODE_READ:
1238                 return state->n_rdonly != 0;
1239         }
1240         WARN_ON_ONCE(1);
1241         return false;
1242 }
1243
1244 static int can_open_cached(struct nfs4_state *state, fmode_t mode, int open_mode)
1245 {
1246         int ret = 0;
1247
1248         if (open_mode & (O_EXCL|O_TRUNC))
1249                 goto out;
1250         switch (mode & (FMODE_READ|FMODE_WRITE)) {
1251                 case FMODE_READ:
1252                         ret |= test_bit(NFS_O_RDONLY_STATE, &state->flags) != 0
1253                                 && state->n_rdonly != 0;
1254                         break;
1255                 case FMODE_WRITE:
1256                         ret |= test_bit(NFS_O_WRONLY_STATE, &state->flags) != 0
1257                                 && state->n_wronly != 0;
1258                         break;
1259                 case FMODE_READ|FMODE_WRITE:
1260                         ret |= test_bit(NFS_O_RDWR_STATE, &state->flags) != 0
1261                                 && state->n_rdwr != 0;
1262         }
1263 out:
1264         return ret;
1265 }
1266
1267 static int can_open_delegated(struct nfs_delegation *delegation, fmode_t fmode,
1268                 enum open_claim_type4 claim)
1269 {
1270         if (delegation == NULL)
1271                 return 0;
1272         if ((delegation->type & fmode) != fmode)
1273                 return 0;
1274         if (test_bit(NFS_DELEGATION_RETURNING, &delegation->flags))
1275                 return 0;
1276         switch (claim) {
1277         case NFS4_OPEN_CLAIM_NULL:
1278         case NFS4_OPEN_CLAIM_FH:
1279                 break;
1280         case NFS4_OPEN_CLAIM_PREVIOUS:
1281                 if (!test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags))
1282                         break;
1283         default:
1284                 return 0;
1285         }
1286         nfs_mark_delegation_referenced(delegation);
1287         return 1;
1288 }
1289
1290 static void update_open_stateflags(struct nfs4_state *state, fmode_t fmode)
1291 {
1292         switch (fmode) {
1293                 case FMODE_WRITE:
1294                         state->n_wronly++;
1295                         break;
1296                 case FMODE_READ:
1297                         state->n_rdonly++;
1298                         break;
1299                 case FMODE_READ|FMODE_WRITE:
1300                         state->n_rdwr++;
1301         }
1302         nfs4_state_set_mode_locked(state, state->state | fmode);
1303 }
1304
1305 static void nfs_test_and_clear_all_open_stateid(struct nfs4_state *state)
1306 {
1307         struct nfs_client *clp = state->owner->so_server->nfs_client;
1308         bool need_recover = false;
1309
1310         if (test_and_clear_bit(NFS_O_RDONLY_STATE, &state->flags) && state->n_rdonly)
1311                 need_recover = true;
1312         if (test_and_clear_bit(NFS_O_WRONLY_STATE, &state->flags) && state->n_wronly)
1313                 need_recover = true;
1314         if (test_and_clear_bit(NFS_O_RDWR_STATE, &state->flags) && state->n_rdwr)
1315                 need_recover = true;
1316         if (need_recover)
1317                 nfs4_state_mark_reclaim_nograce(clp, state);
1318 }
1319
1320 static bool nfs_need_update_open_stateid(struct nfs4_state *state,
1321                 nfs4_stateid *stateid)
1322 {
1323         if (test_and_set_bit(NFS_OPEN_STATE, &state->flags) == 0)
1324                 return true;
1325         if (!nfs4_stateid_match_other(stateid, &state->open_stateid)) {
1326                 nfs_test_and_clear_all_open_stateid(state);
1327                 return true;
1328         }
1329         if (nfs4_stateid_is_newer(stateid, &state->open_stateid))
1330                 return true;
1331         return false;
1332 }
1333
1334 static void nfs_resync_open_stateid_locked(struct nfs4_state *state)
1335 {
1336         if (!(state->n_wronly || state->n_rdonly || state->n_rdwr))
1337                 return;
1338         if (state->n_wronly)
1339                 set_bit(NFS_O_WRONLY_STATE, &state->flags);
1340         if (state->n_rdonly)
1341                 set_bit(NFS_O_RDONLY_STATE, &state->flags);
1342         if (state->n_rdwr)
1343                 set_bit(NFS_O_RDWR_STATE, &state->flags);
1344         set_bit(NFS_OPEN_STATE, &state->flags);
1345 }
1346
1347 static void nfs_clear_open_stateid_locked(struct nfs4_state *state,
1348                 nfs4_stateid *arg_stateid,
1349                 nfs4_stateid *stateid, fmode_t fmode)
1350 {
1351         clear_bit(NFS_O_RDWR_STATE, &state->flags);
1352         switch (fmode & (FMODE_READ|FMODE_WRITE)) {
1353         case FMODE_WRITE:
1354                 clear_bit(NFS_O_RDONLY_STATE, &state->flags);
1355                 break;
1356         case FMODE_READ:
1357                 clear_bit(NFS_O_WRONLY_STATE, &state->flags);
1358                 break;
1359         case 0:
1360                 clear_bit(NFS_O_RDONLY_STATE, &state->flags);
1361                 clear_bit(NFS_O_WRONLY_STATE, &state->flags);
1362                 clear_bit(NFS_OPEN_STATE, &state->flags);
1363         }
1364         if (stateid == NULL)
1365                 return;
1366         /* Handle races with OPEN */
1367         if (!nfs4_stateid_match_other(arg_stateid, &state->open_stateid) ||
1368             (nfs4_stateid_match_other(stateid, &state->open_stateid) &&
1369             !nfs4_stateid_is_newer(stateid, &state->open_stateid))) {
1370                 nfs_resync_open_stateid_locked(state);
1371                 return;
1372         }
1373         if (test_bit(NFS_DELEGATED_STATE, &state->flags) == 0)
1374                 nfs4_stateid_copy(&state->stateid, stateid);
1375         nfs4_stateid_copy(&state->open_stateid, stateid);
1376 }
1377
1378 static void nfs_clear_open_stateid(struct nfs4_state *state,
1379         nfs4_stateid *arg_stateid,
1380         nfs4_stateid *stateid, fmode_t fmode)
1381 {
1382         write_seqlock(&state->seqlock);
1383         nfs_clear_open_stateid_locked(state, arg_stateid, stateid, fmode);
1384         write_sequnlock(&state->seqlock);
1385         if (test_bit(NFS_STATE_RECLAIM_NOGRACE, &state->flags))
1386                 nfs4_schedule_state_manager(state->owner->so_server->nfs_client);
1387 }
1388
1389 static void nfs_set_open_stateid_locked(struct nfs4_state *state, nfs4_stateid *stateid, fmode_t fmode)
1390 {
1391         switch (fmode) {
1392                 case FMODE_READ:
1393                         set_bit(NFS_O_RDONLY_STATE, &state->flags);
1394                         break;
1395                 case FMODE_WRITE:
1396                         set_bit(NFS_O_WRONLY_STATE, &state->flags);
1397                         break;
1398                 case FMODE_READ|FMODE_WRITE:
1399                         set_bit(NFS_O_RDWR_STATE, &state->flags);
1400         }
1401         if (!nfs_need_update_open_stateid(state, stateid))
1402                 return;
1403         if (test_bit(NFS_DELEGATED_STATE, &state->flags) == 0)
1404                 nfs4_stateid_copy(&state->stateid, stateid);
1405         nfs4_stateid_copy(&state->open_stateid, stateid);
1406 }
1407
1408 static void __update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, const nfs4_stateid *deleg_stateid, fmode_t fmode)
1409 {
1410         /*
1411          * Protect the call to nfs4_state_set_mode_locked and
1412          * serialise the stateid update
1413          */
1414         spin_lock(&state->owner->so_lock);
1415         write_seqlock(&state->seqlock);
1416         if (deleg_stateid != NULL) {
1417                 nfs4_stateid_copy(&state->stateid, deleg_stateid);
1418                 set_bit(NFS_DELEGATED_STATE, &state->flags);
1419         }
1420         if (open_stateid != NULL)
1421                 nfs_set_open_stateid_locked(state, open_stateid, fmode);
1422         write_sequnlock(&state->seqlock);
1423         update_open_stateflags(state, fmode);
1424         spin_unlock(&state->owner->so_lock);
1425 }
1426
1427 static int update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, nfs4_stateid *delegation, fmode_t fmode)
1428 {
1429         struct nfs_inode *nfsi = NFS_I(state->inode);
1430         struct nfs_delegation *deleg_cur;
1431         int ret = 0;
1432
1433         fmode &= (FMODE_READ|FMODE_WRITE);
1434
1435         rcu_read_lock();
1436         deleg_cur = rcu_dereference(nfsi->delegation);
1437         if (deleg_cur == NULL)
1438                 goto no_delegation;
1439
1440         spin_lock(&deleg_cur->lock);
1441         if (rcu_dereference(nfsi->delegation) != deleg_cur ||
1442            test_bit(NFS_DELEGATION_RETURNING, &deleg_cur->flags) ||
1443             (deleg_cur->type & fmode) != fmode)
1444                 goto no_delegation_unlock;
1445
1446         if (delegation == NULL)
1447                 delegation = &deleg_cur->stateid;
1448         else if (!nfs4_stateid_match(&deleg_cur->stateid, delegation))
1449                 goto no_delegation_unlock;
1450
1451         nfs_mark_delegation_referenced(deleg_cur);
1452         __update_open_stateid(state, open_stateid, &deleg_cur->stateid, fmode);
1453         ret = 1;
1454 no_delegation_unlock:
1455         spin_unlock(&deleg_cur->lock);
1456 no_delegation:
1457         rcu_read_unlock();
1458
1459         if (!ret && open_stateid != NULL) {
1460                 __update_open_stateid(state, open_stateid, NULL, fmode);
1461                 ret = 1;
1462         }
1463         if (test_bit(NFS_STATE_RECLAIM_NOGRACE, &state->flags))
1464                 nfs4_schedule_state_manager(state->owner->so_server->nfs_client);
1465
1466         return ret;
1467 }
1468
1469 static bool nfs4_update_lock_stateid(struct nfs4_lock_state *lsp,
1470                 const nfs4_stateid *stateid)
1471 {
1472         struct nfs4_state *state = lsp->ls_state;
1473         bool ret = false;
1474
1475         spin_lock(&state->state_lock);
1476         if (!nfs4_stateid_match_other(stateid, &lsp->ls_stateid))
1477                 goto out_noupdate;
1478         if (!nfs4_stateid_is_newer(stateid, &lsp->ls_stateid))
1479                 goto out_noupdate;
1480         nfs4_stateid_copy(&lsp->ls_stateid, stateid);
1481         ret = true;
1482 out_noupdate:
1483         spin_unlock(&state->state_lock);
1484         return ret;
1485 }
1486
1487 static void nfs4_return_incompatible_delegation(struct inode *inode, fmode_t fmode)
1488 {
1489         struct nfs_delegation *delegation;
1490
1491         rcu_read_lock();
1492         delegation = rcu_dereference(NFS_I(inode)->delegation);
1493         if (delegation == NULL || (delegation->type & fmode) == fmode) {
1494                 rcu_read_unlock();
1495                 return;
1496         }
1497         rcu_read_unlock();
1498         nfs4_inode_return_delegation(inode);
1499 }
1500
1501 static struct nfs4_state *nfs4_try_open_cached(struct nfs4_opendata *opendata)
1502 {
1503         struct nfs4_state *state = opendata->state;
1504         struct nfs_inode *nfsi = NFS_I(state->inode);
1505         struct nfs_delegation *delegation;
1506         int open_mode = opendata->o_arg.open_flags;
1507         fmode_t fmode = opendata->o_arg.fmode;
1508         enum open_claim_type4 claim = opendata->o_arg.claim;
1509         nfs4_stateid stateid;
1510         int ret = -EAGAIN;
1511
1512         for (;;) {
1513                 spin_lock(&state->owner->so_lock);
1514                 if (can_open_cached(state, fmode, open_mode)) {
1515                         update_open_stateflags(state, fmode);
1516                         spin_unlock(&state->owner->so_lock);
1517                         goto out_return_state;
1518                 }
1519                 spin_unlock(&state->owner->so_lock);
1520                 rcu_read_lock();
1521                 delegation = rcu_dereference(nfsi->delegation);
1522                 if (!can_open_delegated(delegation, fmode, claim)) {
1523                         rcu_read_unlock();
1524                         break;
1525                 }
1526                 /* Save the delegation */
1527                 nfs4_stateid_copy(&stateid, &delegation->stateid);
1528                 rcu_read_unlock();
1529                 nfs_release_seqid(opendata->o_arg.seqid);
1530                 if (!opendata->is_recover) {
1531                         ret = nfs_may_open(state->inode, state->owner->so_cred, open_mode);
1532                         if (ret != 0)
1533                                 goto out;
1534                 }
1535                 ret = -EAGAIN;
1536
1537                 /* Try to update the stateid using the delegation */
1538                 if (update_open_stateid(state, NULL, &stateid, fmode))
1539                         goto out_return_state;
1540         }
1541 out:
1542         return ERR_PTR(ret);
1543 out_return_state:
1544         atomic_inc(&state->count);
1545         return state;
1546 }
1547
1548 static void
1549 nfs4_opendata_check_deleg(struct nfs4_opendata *data, struct nfs4_state *state)
1550 {
1551         struct nfs_client *clp = NFS_SERVER(state->inode)->nfs_client;
1552         struct nfs_delegation *delegation;
1553         int delegation_flags = 0;
1554
1555         rcu_read_lock();
1556         delegation = rcu_dereference(NFS_I(state->inode)->delegation);
1557         if (delegation)
1558                 delegation_flags = delegation->flags;
1559         rcu_read_unlock();
1560         switch (data->o_arg.claim) {
1561         default:
1562                 break;
1563         case NFS4_OPEN_CLAIM_DELEGATE_CUR:
1564         case NFS4_OPEN_CLAIM_DELEG_CUR_FH:
1565                 pr_err_ratelimited("NFS: Broken NFSv4 server %s is "
1566                                    "returning a delegation for "
1567                                    "OPEN(CLAIM_DELEGATE_CUR)\n",
1568                                    clp->cl_hostname);
1569                 return;
1570         }
1571         if ((delegation_flags & 1UL<<NFS_DELEGATION_NEED_RECLAIM) == 0)
1572                 nfs_inode_set_delegation(state->inode,
1573                                          data->owner->so_cred,
1574                                          &data->o_res);
1575         else
1576                 nfs_inode_reclaim_delegation(state->inode,
1577                                              data->owner->so_cred,
1578                                              &data->o_res);
1579 }
1580
1581 /*
1582  * Check the inode attributes against the CLAIM_PREVIOUS returned attributes
1583  * and update the nfs4_state.
1584  */
1585 static struct nfs4_state *
1586 _nfs4_opendata_reclaim_to_nfs4_state(struct nfs4_opendata *data)
1587 {
1588         struct inode *inode = data->state->inode;
1589         struct nfs4_state *state = data->state;
1590         int ret;
1591
1592         if (!data->rpc_done) {
1593                 if (data->rpc_status) {
1594                         ret = data->rpc_status;
1595                         goto err;
1596                 }
1597                 /* cached opens have already been processed */
1598                 goto update;
1599         }
1600
1601         ret = nfs_refresh_inode(inode, &data->f_attr);
1602         if (ret)
1603                 goto err;
1604
1605         if (data->o_res.delegation_type != 0)
1606                 nfs4_opendata_check_deleg(data, state);
1607 update:
1608         update_open_stateid(state, &data->o_res.stateid, NULL,
1609                             data->o_arg.fmode);
1610         atomic_inc(&state->count);
1611
1612         return state;
1613 err:
1614         return ERR_PTR(ret);
1615
1616 }
1617
1618 static struct nfs4_state *
1619 _nfs4_opendata_to_nfs4_state(struct nfs4_opendata *data)
1620 {
1621         struct inode *inode;
1622         struct nfs4_state *state = NULL;
1623         int ret;
1624
1625         if (!data->rpc_done) {
1626                 state = nfs4_try_open_cached(data);
1627                 trace_nfs4_cached_open(data->state);
1628                 goto out;
1629         }
1630
1631         ret = -EAGAIN;
1632         if (!(data->f_attr.valid & NFS_ATTR_FATTR))
1633                 goto err;
1634         inode = nfs_fhget(data->dir->d_sb, &data->o_res.fh, &data->f_attr, data->f_label);
1635         ret = PTR_ERR(inode);
1636         if (IS_ERR(inode))
1637                 goto err;
1638         ret = -ENOMEM;
1639         state = nfs4_get_open_state(inode, data->owner);
1640         if (state == NULL)
1641                 goto err_put_inode;
1642         if (data->o_res.delegation_type != 0)
1643                 nfs4_opendata_check_deleg(data, state);
1644         update_open_stateid(state, &data->o_res.stateid, NULL,
1645                         data->o_arg.fmode);
1646         iput(inode);
1647 out:
1648         nfs_release_seqid(data->o_arg.seqid);
1649         return state;
1650 err_put_inode:
1651         iput(inode);
1652 err:
1653         return ERR_PTR(ret);
1654 }
1655
1656 static struct nfs4_state *
1657 nfs4_opendata_to_nfs4_state(struct nfs4_opendata *data)
1658 {
1659         if (data->o_arg.claim == NFS4_OPEN_CLAIM_PREVIOUS)
1660                 return _nfs4_opendata_reclaim_to_nfs4_state(data);
1661         return _nfs4_opendata_to_nfs4_state(data);
1662 }
1663
1664 static struct nfs_open_context *nfs4_state_find_open_context(struct nfs4_state *state)
1665 {
1666         struct nfs_inode *nfsi = NFS_I(state->inode);
1667         struct nfs_open_context *ctx;
1668
1669         spin_lock(&state->inode->i_lock);
1670         list_for_each_entry(ctx, &nfsi->open_files, list) {
1671                 if (ctx->state != state)
1672                         continue;
1673                 get_nfs_open_context(ctx);
1674                 spin_unlock(&state->inode->i_lock);
1675                 return ctx;
1676         }
1677         spin_unlock(&state->inode->i_lock);
1678         return ERR_PTR(-ENOENT);
1679 }
1680
1681 static struct nfs4_opendata *nfs4_open_recoverdata_alloc(struct nfs_open_context *ctx,
1682                 struct nfs4_state *state, enum open_claim_type4 claim)
1683 {
1684         struct nfs4_opendata *opendata;
1685
1686         opendata = nfs4_opendata_alloc(ctx->dentry, state->owner, 0, 0,
1687                         NULL, NULL, claim, GFP_NOFS);
1688         if (opendata == NULL)
1689                 return ERR_PTR(-ENOMEM);
1690         opendata->state = state;
1691         atomic_inc(&state->count);
1692         return opendata;
1693 }
1694
1695 static int nfs4_open_recover_helper(struct nfs4_opendata *opendata,
1696                 fmode_t fmode)
1697 {
1698         struct nfs4_state *newstate;
1699         int ret;
1700
1701         if (!nfs4_mode_match_open_stateid(opendata->state, fmode))
1702                 return 0;
1703         opendata->o_arg.open_flags = 0;
1704         opendata->o_arg.fmode = fmode;
1705         opendata->o_arg.share_access = nfs4_map_atomic_open_share(
1706                         NFS_SB(opendata->dentry->d_sb),
1707                         fmode, 0);
1708         memset(&opendata->o_res, 0, sizeof(opendata->o_res));
1709         memset(&opendata->c_res, 0, sizeof(opendata->c_res));
1710         nfs4_init_opendata_res(opendata);
1711         ret = _nfs4_recover_proc_open(opendata);
1712         if (ret != 0)
1713                 return ret; 
1714         newstate = nfs4_opendata_to_nfs4_state(opendata);
1715         if (IS_ERR(newstate))
1716                 return PTR_ERR(newstate);
1717         if (newstate != opendata->state)
1718                 ret = -ESTALE;
1719         nfs4_close_state(newstate, fmode);
1720         return ret;
1721 }
1722
1723 static int nfs4_open_recover(struct nfs4_opendata *opendata, struct nfs4_state *state)
1724 {
1725         int ret;
1726
1727         /* Don't trigger recovery in nfs_test_and_clear_all_open_stateid */
1728         clear_bit(NFS_O_RDWR_STATE, &state->flags);
1729         clear_bit(NFS_O_WRONLY_STATE, &state->flags);
1730         clear_bit(NFS_O_RDONLY_STATE, &state->flags);
1731         /* memory barrier prior to reading state->n_* */
1732         clear_bit(NFS_DELEGATED_STATE, &state->flags);
1733         clear_bit(NFS_OPEN_STATE, &state->flags);
1734         smp_rmb();
1735         ret = nfs4_open_recover_helper(opendata, FMODE_READ|FMODE_WRITE);
1736         if (ret != 0)
1737                 return ret;
1738         ret = nfs4_open_recover_helper(opendata, FMODE_WRITE);
1739         if (ret != 0)
1740                 return ret;
1741         ret = nfs4_open_recover_helper(opendata, FMODE_READ);
1742         if (ret != 0)
1743                 return ret;
1744         /*
1745          * We may have performed cached opens for all three recoveries.
1746          * Check if we need to update the current stateid.
1747          */
1748         if (test_bit(NFS_DELEGATED_STATE, &state->flags) == 0 &&
1749             !nfs4_stateid_match(&state->stateid, &state->open_stateid)) {
1750                 write_seqlock(&state->seqlock);
1751                 if (test_bit(NFS_DELEGATED_STATE, &state->flags) == 0)
1752                         nfs4_stateid_copy(&state->stateid, &state->open_stateid);
1753                 write_sequnlock(&state->seqlock);
1754         }
1755         return 0;
1756 }
1757
1758 /*
1759  * OPEN_RECLAIM:
1760  *      reclaim state on the server after a reboot.
1761  */
1762 static int _nfs4_do_open_reclaim(struct nfs_open_context *ctx, struct nfs4_state *state)
1763 {
1764         struct nfs_delegation *delegation;
1765         struct nfs4_opendata *opendata;
1766         fmode_t delegation_type = 0;
1767         int status;
1768
1769         opendata = nfs4_open_recoverdata_alloc(ctx, state,
1770                         NFS4_OPEN_CLAIM_PREVIOUS);
1771         if (IS_ERR(opendata))
1772                 return PTR_ERR(opendata);
1773         rcu_read_lock();
1774         delegation = rcu_dereference(NFS_I(state->inode)->delegation);
1775         if (delegation != NULL && test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags) != 0)
1776                 delegation_type = delegation->type;
1777         rcu_read_unlock();
1778         opendata->o_arg.u.delegation_type = delegation_type;
1779         status = nfs4_open_recover(opendata, state);
1780         nfs4_opendata_put(opendata);
1781         return status;
1782 }
1783
1784 static int nfs4_do_open_reclaim(struct nfs_open_context *ctx, struct nfs4_state *state)
1785 {
1786         struct nfs_server *server = NFS_SERVER(state->inode);
1787         struct nfs4_exception exception = { };
1788         int err;
1789         do {
1790                 err = _nfs4_do_open_reclaim(ctx, state);
1791                 trace_nfs4_open_reclaim(ctx, 0, err);
1792                 if (nfs4_clear_cap_atomic_open_v1(server, err, &exception))
1793                         continue;
1794                 if (err != -NFS4ERR_DELAY)
1795                         break;
1796                 nfs4_handle_exception(server, err, &exception);
1797         } while (exception.retry);
1798         return err;
1799 }
1800
1801 static int nfs4_open_reclaim(struct nfs4_state_owner *sp, struct nfs4_state *state)
1802 {
1803         struct nfs_open_context *ctx;
1804         int ret;
1805
1806         ctx = nfs4_state_find_open_context(state);
1807         if (IS_ERR(ctx))
1808                 return -EAGAIN;
1809         ret = nfs4_do_open_reclaim(ctx, state);
1810         put_nfs_open_context(ctx);
1811         return ret;
1812 }
1813
1814 static int nfs4_handle_delegation_recall_error(struct nfs_server *server, struct nfs4_state *state, const nfs4_stateid *stateid, int err)
1815 {
1816         switch (err) {
1817                 default:
1818                         printk(KERN_ERR "NFS: %s: unhandled error "
1819                                         "%d.\n", __func__, err);
1820                 case 0:
1821                 case -ENOENT:
1822                 case -EAGAIN:
1823                 case -ESTALE:
1824                         break;
1825                 case -NFS4ERR_BADSESSION:
1826                 case -NFS4ERR_BADSLOT:
1827                 case -NFS4ERR_BAD_HIGH_SLOT:
1828                 case -NFS4ERR_CONN_NOT_BOUND_TO_SESSION:
1829                 case -NFS4ERR_DEADSESSION:
1830                         set_bit(NFS_DELEGATED_STATE, &state->flags);
1831                         nfs4_schedule_session_recovery(server->nfs_client->cl_session, err);
1832                         return -EAGAIN;
1833                 case -NFS4ERR_STALE_CLIENTID:
1834                 case -NFS4ERR_STALE_STATEID:
1835                         set_bit(NFS_DELEGATED_STATE, &state->flags);
1836                 case -NFS4ERR_EXPIRED:
1837                         /* Don't recall a delegation if it was lost */
1838                         nfs4_schedule_lease_recovery(server->nfs_client);
1839                         return -EAGAIN;
1840                 case -NFS4ERR_MOVED:
1841                         nfs4_schedule_migration_recovery(server);
1842                         return -EAGAIN;
1843                 case -NFS4ERR_LEASE_MOVED:
1844                         nfs4_schedule_lease_moved_recovery(server->nfs_client);
1845                         return -EAGAIN;
1846                 case -NFS4ERR_DELEG_REVOKED:
1847                 case -NFS4ERR_ADMIN_REVOKED:
1848                 case -NFS4ERR_BAD_STATEID:
1849                 case -NFS4ERR_OPENMODE:
1850                         nfs_inode_find_state_and_recover(state->inode,
1851                                         stateid);
1852                         nfs4_schedule_stateid_recovery(server, state);
1853                         return -EAGAIN;
1854                 case -NFS4ERR_DELAY:
1855                 case -NFS4ERR_GRACE:
1856                         set_bit(NFS_DELEGATED_STATE, &state->flags);
1857                         ssleep(1);
1858                         return -EAGAIN;
1859                 case -ENOMEM:
1860                 case -NFS4ERR_DENIED:
1861                         /* kill_proc(fl->fl_pid, SIGLOST, 1); */
1862                         return 0;
1863         }
1864         return err;
1865 }
1866
1867 int nfs4_open_delegation_recall(struct nfs_open_context *ctx,
1868                 struct nfs4_state *state, const nfs4_stateid *stateid,
1869                 fmode_t type)
1870 {
1871         struct nfs_server *server = NFS_SERVER(state->inode);
1872         struct nfs4_opendata *opendata;
1873         int err = 0;
1874
1875         opendata = nfs4_open_recoverdata_alloc(ctx, state,
1876                         NFS4_OPEN_CLAIM_DELEG_CUR_FH);
1877         if (IS_ERR(opendata))
1878                 return PTR_ERR(opendata);
1879         nfs4_stateid_copy(&opendata->o_arg.u.delegation, stateid);
1880         write_seqlock(&state->seqlock);
1881         nfs4_stateid_copy(&state->stateid, &state->open_stateid);
1882         write_sequnlock(&state->seqlock);
1883         clear_bit(NFS_DELEGATED_STATE, &state->flags);
1884         switch (type & (FMODE_READ|FMODE_WRITE)) {
1885         case FMODE_READ|FMODE_WRITE:
1886         case FMODE_WRITE:
1887                 err = nfs4_open_recover_helper(opendata, FMODE_READ|FMODE_WRITE);
1888                 if (err)
1889                         break;
1890                 err = nfs4_open_recover_helper(opendata, FMODE_WRITE);
1891                 if (err)
1892                         break;
1893         case FMODE_READ:
1894                 err = nfs4_open_recover_helper(opendata, FMODE_READ);
1895         }
1896         nfs4_opendata_put(opendata);
1897         return nfs4_handle_delegation_recall_error(server, state, stateid, err);
1898 }
1899
1900 static void nfs4_open_confirm_prepare(struct rpc_task *task, void *calldata)
1901 {
1902         struct nfs4_opendata *data = calldata;
1903
1904         nfs40_setup_sequence(data->o_arg.server->nfs_client->cl_slot_tbl,
1905                              &data->c_arg.seq_args, &data->c_res.seq_res, task);
1906 }
1907
1908 static void nfs4_open_confirm_done(struct rpc_task *task, void *calldata)
1909 {
1910         struct nfs4_opendata *data = calldata;
1911
1912         nfs40_sequence_done(task, &data->c_res.seq_res);
1913
1914         data->rpc_status = task->tk_status;
1915         if (data->rpc_status == 0) {
1916                 nfs4_stateid_copy(&data->o_res.stateid, &data->c_res.stateid);
1917                 nfs_confirm_seqid(&data->owner->so_seqid, 0);
1918                 renew_lease(data->o_res.server, data->timestamp);
1919                 data->rpc_done = 1;
1920         }
1921 }
1922
1923 static void nfs4_open_confirm_release(void *calldata)
1924 {
1925         struct nfs4_opendata *data = calldata;
1926         struct nfs4_state *state = NULL;
1927
1928         /* If this request hasn't been cancelled, do nothing */
1929         if (data->cancelled == 0)
1930                 goto out_free;
1931         /* In case of error, no cleanup! */
1932         if (!data->rpc_done)
1933                 goto out_free;
1934         state = nfs4_opendata_to_nfs4_state(data);
1935         if (!IS_ERR(state))
1936                 nfs4_close_state(state, data->o_arg.fmode);
1937 out_free:
1938         nfs4_opendata_put(data);
1939 }
1940
1941 static const struct rpc_call_ops nfs4_open_confirm_ops = {
1942         .rpc_call_prepare = nfs4_open_confirm_prepare,
1943         .rpc_call_done = nfs4_open_confirm_done,
1944         .rpc_release = nfs4_open_confirm_release,
1945 };
1946
1947 /*
1948  * Note: On error, nfs4_proc_open_confirm will free the struct nfs4_opendata
1949  */
1950 static int _nfs4_proc_open_confirm(struct nfs4_opendata *data)
1951 {
1952         struct nfs_server *server = NFS_SERVER(d_inode(data->dir));
1953         struct rpc_task *task;
1954         struct  rpc_message msg = {
1955                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_CONFIRM],
1956                 .rpc_argp = &data->c_arg,
1957                 .rpc_resp = &data->c_res,
1958                 .rpc_cred = data->owner->so_cred,
1959         };
1960         struct rpc_task_setup task_setup_data = {
1961                 .rpc_client = server->client,
1962                 .rpc_message = &msg,
1963                 .callback_ops = &nfs4_open_confirm_ops,
1964                 .callback_data = data,
1965                 .workqueue = nfsiod_workqueue,
1966                 .flags = RPC_TASK_ASYNC,
1967         };
1968         int status;
1969
1970         nfs4_init_sequence(&data->c_arg.seq_args, &data->c_res.seq_res, 1);
1971         kref_get(&data->kref);
1972         data->rpc_done = 0;
1973         data->rpc_status = 0;
1974         data->timestamp = jiffies;
1975         if (data->is_recover)
1976                 nfs4_set_sequence_privileged(&data->c_arg.seq_args);
1977         task = rpc_run_task(&task_setup_data);
1978         if (IS_ERR(task))
1979                 return PTR_ERR(task);
1980         status = nfs4_wait_for_completion_rpc_task(task);
1981         if (status != 0) {
1982                 data->cancelled = 1;
1983                 smp_wmb();
1984         } else
1985                 status = data->rpc_status;
1986         rpc_put_task(task);
1987         return status;
1988 }
1989
1990 static void nfs4_open_prepare(struct rpc_task *task, void *calldata)
1991 {
1992         struct nfs4_opendata *data = calldata;
1993         struct nfs4_state_owner *sp = data->owner;
1994         struct nfs_client *clp = sp->so_server->nfs_client;
1995         enum open_claim_type4 claim = data->o_arg.claim;
1996
1997         if (nfs_wait_on_sequence(data->o_arg.seqid, task) != 0)
1998                 goto out_wait;
1999         /*
2000          * Check if we still need to send an OPEN call, or if we can use
2001          * a delegation instead.
2002          */
2003         if (data->state != NULL) {
2004                 struct nfs_delegation *delegation;
2005
2006                 if (can_open_cached(data->state, data->o_arg.fmode, data->o_arg.open_flags))
2007                         goto out_no_action;
2008                 rcu_read_lock();
2009                 delegation = rcu_dereference(NFS_I(data->state->inode)->delegation);
2010                 if (can_open_delegated(delegation, data->o_arg.fmode, claim))
2011                         goto unlock_no_action;
2012                 rcu_read_unlock();
2013         }
2014         /* Update client id. */
2015         data->o_arg.clientid = clp->cl_clientid;
2016         switch (claim) {
2017         default:
2018                 break;
2019         case NFS4_OPEN_CLAIM_PREVIOUS:
2020         case NFS4_OPEN_CLAIM_DELEG_CUR_FH:
2021         case NFS4_OPEN_CLAIM_DELEG_PREV_FH:
2022                 data->o_arg.open_bitmap = &nfs4_open_noattr_bitmap[0];
2023         case NFS4_OPEN_CLAIM_FH:
2024                 task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_NOATTR];
2025                 nfs_copy_fh(&data->o_res.fh, data->o_arg.fh);
2026         }
2027         data->timestamp = jiffies;
2028         if (nfs4_setup_sequence(data->o_arg.server,
2029                                 &data->o_arg.seq_args,
2030                                 &data->o_res.seq_res,
2031                                 task) != 0)
2032                 nfs_release_seqid(data->o_arg.seqid);
2033
2034         /* Set the create mode (note dependency on the session type) */
2035         data->o_arg.createmode = NFS4_CREATE_UNCHECKED;
2036         if (data->o_arg.open_flags & O_EXCL) {
2037                 data->o_arg.createmode = NFS4_CREATE_EXCLUSIVE;
2038                 if (nfs4_has_persistent_session(clp))
2039                         data->o_arg.createmode = NFS4_CREATE_GUARDED;
2040                 else if (clp->cl_mvops->minor_version > 0)
2041                         data->o_arg.createmode = NFS4_CREATE_EXCLUSIVE4_1;
2042         }
2043         return;
2044 unlock_no_action:
2045         trace_nfs4_cached_open(data->state);
2046         rcu_read_unlock();
2047 out_no_action:
2048         task->tk_action = NULL;
2049 out_wait:
2050         nfs4_sequence_done(task, &data->o_res.seq_res);
2051 }
2052
2053 static void nfs4_open_done(struct rpc_task *task, void *calldata)
2054 {
2055         struct nfs4_opendata *data = calldata;
2056
2057         data->rpc_status = task->tk_status;
2058
2059         if (!nfs4_sequence_done(task, &data->o_res.seq_res))
2060                 return;
2061
2062         if (task->tk_status == 0) {
2063                 if (data->o_res.f_attr->valid & NFS_ATTR_FATTR_TYPE) {
2064                         switch (data->o_res.f_attr->mode & S_IFMT) {
2065                         case S_IFREG:
2066                                 break;
2067                         case S_IFLNK:
2068                                 data->rpc_status = -ELOOP;
2069                                 break;
2070                         case S_IFDIR:
2071                                 data->rpc_status = -EISDIR;
2072                                 break;
2073                         default:
2074                                 data->rpc_status = -ENOTDIR;
2075                         }
2076                 }
2077                 renew_lease(data->o_res.server, data->timestamp);
2078                 if (!(data->o_res.rflags & NFS4_OPEN_RESULT_CONFIRM))
2079                         nfs_confirm_seqid(&data->owner->so_seqid, 0);
2080         }
2081         data->rpc_done = 1;
2082 }
2083
2084 static void nfs4_open_release(void *calldata)
2085 {
2086         struct nfs4_opendata *data = calldata;
2087         struct nfs4_state *state = NULL;
2088
2089         /* If this request hasn't been cancelled, do nothing */
2090         if (data->cancelled == 0)
2091                 goto out_free;
2092         /* In case of error, no cleanup! */
2093         if (data->rpc_status != 0 || !data->rpc_done)
2094                 goto out_free;
2095         /* In case we need an open_confirm, no cleanup! */
2096         if (data->o_res.rflags & NFS4_OPEN_RESULT_CONFIRM)
2097                 goto out_free;
2098         state = nfs4_opendata_to_nfs4_state(data);
2099         if (!IS_ERR(state))
2100                 nfs4_close_state(state, data->o_arg.fmode);
2101 out_free:
2102         nfs4_opendata_put(data);
2103 }
2104
2105 static const struct rpc_call_ops nfs4_open_ops = {
2106         .rpc_call_prepare = nfs4_open_prepare,
2107         .rpc_call_done = nfs4_open_done,
2108         .rpc_release = nfs4_open_release,
2109 };
2110
2111 static int nfs4_run_open_task(struct nfs4_opendata *data, int isrecover)
2112 {
2113         struct inode *dir = d_inode(data->dir);
2114         struct nfs_server *server = NFS_SERVER(dir);
2115         struct nfs_openargs *o_arg = &data->o_arg;
2116         struct nfs_openres *o_res = &data->o_res;
2117         struct rpc_task *task;
2118         struct rpc_message msg = {
2119                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN],
2120                 .rpc_argp = o_arg,
2121                 .rpc_resp = o_res,
2122                 .rpc_cred = data->owner->so_cred,
2123         };
2124         struct rpc_task_setup task_setup_data = {
2125                 .rpc_client = server->client,
2126                 .rpc_message = &msg,
2127                 .callback_ops = &nfs4_open_ops,
2128                 .callback_data = data,
2129                 .workqueue = nfsiod_workqueue,
2130                 .flags = RPC_TASK_ASYNC,
2131         };
2132         int status;
2133
2134         nfs4_init_sequence(&o_arg->seq_args, &o_res->seq_res, 1);
2135         kref_get(&data->kref);
2136         data->rpc_done = 0;
2137         data->rpc_status = 0;
2138         data->cancelled = 0;
2139         data->is_recover = 0;
2140         if (isrecover) {
2141                 nfs4_set_sequence_privileged(&o_arg->seq_args);
2142                 data->is_recover = 1;
2143         }
2144         task = rpc_run_task(&task_setup_data);
2145         if (IS_ERR(task))
2146                 return PTR_ERR(task);
2147         status = nfs4_wait_for_completion_rpc_task(task);
2148         if (status != 0) {
2149                 data->cancelled = 1;
2150                 smp_wmb();
2151         } else
2152                 status = data->rpc_status;
2153         rpc_put_task(task);
2154
2155         return status;
2156 }
2157
2158 static int _nfs4_recover_proc_open(struct nfs4_opendata *data)
2159 {
2160         struct inode *dir = d_inode(data->dir);
2161         struct nfs_openres *o_res = &data->o_res;
2162         int status;
2163
2164         status = nfs4_run_open_task(data, 1);
2165         if (status != 0 || !data->rpc_done)
2166                 return status;
2167
2168         nfs_fattr_map_and_free_names(NFS_SERVER(dir), &data->f_attr);
2169
2170         if (o_res->rflags & NFS4_OPEN_RESULT_CONFIRM) {
2171                 status = _nfs4_proc_open_confirm(data);
2172                 if (status != 0)
2173                         return status;
2174         }
2175
2176         return status;
2177 }
2178
2179 /*
2180  * Additional permission checks in order to distinguish between an
2181  * open for read, and an open for execute. This works around the
2182  * fact that NFSv4 OPEN treats read and execute permissions as being
2183  * the same.
2184  * Note that in the non-execute case, we want to turn off permission
2185  * checking if we just created a new file (POSIX open() semantics).
2186  */
2187 static int nfs4_opendata_access(struct rpc_cred *cred,
2188                                 struct nfs4_opendata *opendata,
2189                                 struct nfs4_state *state, fmode_t fmode,
2190                                 int openflags)
2191 {
2192         struct nfs_access_entry cache;
2193         u32 mask;
2194
2195         /* access call failed or for some reason the server doesn't
2196          * support any access modes -- defer access call until later */
2197         if (opendata->o_res.access_supported == 0)
2198                 return 0;
2199
2200         mask = 0;
2201         /*
2202          * Use openflags to check for exec, because fmode won't
2203          * always have FMODE_EXEC set when file open for exec.
2204          */
2205         if (openflags & __FMODE_EXEC) {
2206                 /* ONLY check for exec rights */
2207                 mask = MAY_EXEC;
2208         } else if ((fmode & FMODE_READ) && !opendata->file_created)
2209                 mask = MAY_READ;
2210
2211         cache.cred = cred;
2212         cache.jiffies = jiffies;
2213         nfs_access_set_mask(&cache, opendata->o_res.access_result);
2214         nfs_access_add_cache(state->inode, &cache);
2215
2216         if ((mask & ~cache.mask & (MAY_READ | MAY_EXEC)) == 0)
2217                 return 0;
2218
2219         /* even though OPEN succeeded, access is denied. Close the file */
2220         nfs4_close_state(state, fmode);
2221         return -EACCES;
2222 }
2223
2224 /*
2225  * Note: On error, nfs4_proc_open will free the struct nfs4_opendata
2226  */
2227 static int _nfs4_proc_open(struct nfs4_opendata *data)
2228 {
2229         struct inode *dir = d_inode(data->dir);
2230         struct nfs_server *server = NFS_SERVER(dir);
2231         struct nfs_openargs *o_arg = &data->o_arg;
2232         struct nfs_openres *o_res = &data->o_res;
2233         int status;
2234
2235         status = nfs4_run_open_task(data, 0);
2236         if (!data->rpc_done)
2237                 return status;
2238         if (status != 0) {
2239                 if (status == -NFS4ERR_BADNAME &&
2240                                 !(o_arg->open_flags & O_CREAT))
2241                         return -ENOENT;
2242                 return status;
2243         }
2244
2245         nfs_fattr_map_and_free_names(server, &data->f_attr);
2246
2247         if (o_arg->open_flags & O_CREAT) {
2248                 update_changeattr(dir, &o_res->cinfo);
2249                 if (o_arg->open_flags & O_EXCL)
2250                         data->file_created = 1;
2251                 else if (o_res->cinfo.before != o_res->cinfo.after)
2252                         data->file_created = 1;
2253         }
2254         if ((o_res->rflags & NFS4_OPEN_RESULT_LOCKTYPE_POSIX) == 0)
2255                 server->caps &= ~NFS_CAP_POSIX_LOCK;
2256         if(o_res->rflags & NFS4_OPEN_RESULT_CONFIRM) {
2257                 status = _nfs4_proc_open_confirm(data);
2258                 if (status != 0)
2259                         return status;
2260         }
2261         if (!(o_res->f_attr->valid & NFS_ATTR_FATTR))
2262                 nfs4_proc_getattr(server, &o_res->fh, o_res->f_attr, o_res->f_label);
2263         return 0;
2264 }
2265
2266 static int nfs4_recover_expired_lease(struct nfs_server *server)
2267 {
2268         return nfs4_client_recover_expired_lease(server->nfs_client);
2269 }
2270
2271 /*
2272  * OPEN_EXPIRED:
2273  *      reclaim state on the server after a network partition.
2274  *      Assumes caller holds the appropriate lock
2275  */
2276 static int _nfs4_open_expired(struct nfs_open_context *ctx, struct nfs4_state *state)
2277 {
2278         struct nfs4_opendata *opendata;
2279         int ret;
2280
2281         opendata = nfs4_open_recoverdata_alloc(ctx, state,
2282                         NFS4_OPEN_CLAIM_FH);
2283         if (IS_ERR(opendata))
2284                 return PTR_ERR(opendata);
2285         ret = nfs4_open_recover(opendata, state);
2286         if (ret == -ESTALE)
2287                 d_drop(ctx->dentry);
2288         nfs4_opendata_put(opendata);
2289         return ret;
2290 }
2291
2292 static int nfs4_do_open_expired(struct nfs_open_context *ctx, struct nfs4_state *state)
2293 {
2294         struct nfs_server *server = NFS_SERVER(state->inode);
2295         struct nfs4_exception exception = { };
2296         int err;
2297
2298         do {
2299                 err = _nfs4_open_expired(ctx, state);
2300                 trace_nfs4_open_expired(ctx, 0, err);
2301                 if (nfs4_clear_cap_atomic_open_v1(server, err, &exception))
2302                         continue;
2303                 switch (err) {
2304                 default:
2305                         goto out;
2306                 case -NFS4ERR_GRACE:
2307                 case -NFS4ERR_DELAY:
2308                         nfs4_handle_exception(server, err, &exception);
2309                         err = 0;
2310                 }
2311         } while (exception.retry);
2312 out:
2313         return err;
2314 }
2315
2316 static int nfs4_open_expired(struct nfs4_state_owner *sp, struct nfs4_state *state)
2317 {
2318         struct nfs_open_context *ctx;
2319         int ret;
2320
2321         ctx = nfs4_state_find_open_context(state);
2322         if (IS_ERR(ctx))
2323                 return -EAGAIN;
2324         ret = nfs4_do_open_expired(ctx, state);
2325         put_nfs_open_context(ctx);
2326         return ret;
2327 }
2328
2329 static void nfs_finish_clear_delegation_stateid(struct nfs4_state *state)
2330 {
2331         nfs_remove_bad_delegation(state->inode);
2332         write_seqlock(&state->seqlock);
2333         nfs4_stateid_copy(&state->stateid, &state->open_stateid);
2334         write_sequnlock(&state->seqlock);
2335         clear_bit(NFS_DELEGATED_STATE, &state->flags);
2336 }
2337
2338 static void nfs40_clear_delegation_stateid(struct nfs4_state *state)
2339 {
2340         if (rcu_access_pointer(NFS_I(state->inode)->delegation) != NULL)
2341                 nfs_finish_clear_delegation_stateid(state);
2342 }
2343
2344 static int nfs40_open_expired(struct nfs4_state_owner *sp, struct nfs4_state *state)
2345 {
2346         /* NFSv4.0 doesn't allow for delegation recovery on open expire */
2347         nfs40_clear_delegation_stateid(state);
2348         return nfs4_open_expired(sp, state);
2349 }
2350
2351 #if defined(CONFIG_NFS_V4_1)
2352 static void nfs41_check_delegation_stateid(struct nfs4_state *state)
2353 {
2354         struct nfs_server *server = NFS_SERVER(state->inode);
2355         nfs4_stateid stateid;
2356         struct nfs_delegation *delegation;
2357         struct rpc_cred *cred;
2358         int status;
2359
2360         /* Get the delegation credential for use by test/free_stateid */
2361         rcu_read_lock();
2362         delegation = rcu_dereference(NFS_I(state->inode)->delegation);
2363         if (delegation == NULL) {
2364                 rcu_read_unlock();
2365                 return;
2366         }
2367
2368         nfs4_stateid_copy(&stateid, &delegation->stateid);
2369         cred = get_rpccred(delegation->cred);
2370         rcu_read_unlock();
2371         status = nfs41_test_stateid(server, &stateid, cred);
2372         trace_nfs4_test_delegation_stateid(state, NULL, status);
2373
2374         if (status != NFS_OK) {
2375                 /* Free the stateid unless the server explicitly
2376                  * informs us the stateid is unrecognized. */
2377                 if (status != -NFS4ERR_BAD_STATEID)
2378                         nfs41_free_stateid(server, &stateid, cred);
2379                 nfs_finish_clear_delegation_stateid(state);
2380         }
2381
2382         put_rpccred(cred);
2383 }
2384
2385 /**
2386  * nfs41_check_open_stateid - possibly free an open stateid
2387  *
2388  * @state: NFSv4 state for an inode
2389  *
2390  * Returns NFS_OK if recovery for this stateid is now finished.
2391  * Otherwise a negative NFS4ERR value is returned.
2392  */
2393 static int nfs41_check_open_stateid(struct nfs4_state *state)
2394 {
2395         struct nfs_server *server = NFS_SERVER(state->inode);
2396         nfs4_stateid *stateid = &state->open_stateid;
2397         struct rpc_cred *cred = state->owner->so_cred;
2398         int status;
2399
2400         /* If a state reset has been done, test_stateid is unneeded */
2401         if ((test_bit(NFS_O_RDONLY_STATE, &state->flags) == 0) &&
2402             (test_bit(NFS_O_WRONLY_STATE, &state->flags) == 0) &&
2403             (test_bit(NFS_O_RDWR_STATE, &state->flags) == 0))
2404                 return -NFS4ERR_BAD_STATEID;
2405
2406         status = nfs41_test_stateid(server, stateid, cred);
2407         trace_nfs4_test_open_stateid(state, NULL, status);
2408         if (status != NFS_OK) {
2409                 /* Free the stateid unless the server explicitly
2410                  * informs us the stateid is unrecognized. */
2411                 if (status != -NFS4ERR_BAD_STATEID)
2412                         nfs41_free_stateid(server, stateid, cred);
2413
2414                 clear_bit(NFS_O_RDONLY_STATE, &state->flags);
2415                 clear_bit(NFS_O_WRONLY_STATE, &state->flags);
2416                 clear_bit(NFS_O_RDWR_STATE, &state->flags);
2417                 clear_bit(NFS_OPEN_STATE, &state->flags);
2418         }
2419         return status;
2420 }
2421
2422 static int nfs41_open_expired(struct nfs4_state_owner *sp, struct nfs4_state *state)
2423 {
2424         int status;
2425
2426         nfs41_check_delegation_stateid(state);
2427         status = nfs41_check_open_stateid(state);
2428         if (status != NFS_OK)
2429                 status = nfs4_open_expired(sp, state);
2430         return status;
2431 }
2432 #endif
2433
2434 /*
2435  * on an EXCLUSIVE create, the server should send back a bitmask with FATTR4-*
2436  * fields corresponding to attributes that were used to store the verifier.
2437  * Make sure we clobber those fields in the later setattr call
2438  */
2439 static inline void nfs4_exclusive_attrset(struct nfs4_opendata *opendata,
2440                                 struct iattr *sattr, struct nfs4_label **label)
2441 {
2442         const u32 *attrset = opendata->o_res.attrset;
2443
2444         if ((attrset[1] & FATTR4_WORD1_TIME_ACCESS) &&
2445             !(sattr->ia_valid & ATTR_ATIME_SET))
2446                 sattr->ia_valid |= ATTR_ATIME;
2447
2448         if ((attrset[1] & FATTR4_WORD1_TIME_MODIFY) &&
2449             !(sattr->ia_valid & ATTR_MTIME_SET))
2450                 sattr->ia_valid |= ATTR_MTIME;
2451
2452         /* Except MODE, it seems harmless of setting twice. */
2453         if ((attrset[1] & FATTR4_WORD1_MODE))
2454                 sattr->ia_valid &= ~ATTR_MODE;
2455
2456         if (attrset[2] & FATTR4_WORD2_SECURITY_LABEL)
2457                 *label = NULL;
2458 }
2459
2460 static int _nfs4_open_and_get_state(struct nfs4_opendata *opendata,
2461                 fmode_t fmode,
2462                 int flags,
2463                 struct nfs_open_context *ctx)
2464 {
2465         struct nfs4_state_owner *sp = opendata->owner;
2466         struct nfs_server *server = sp->so_server;
2467         struct dentry *dentry;
2468         struct nfs4_state *state;
2469         unsigned int seq;
2470         int ret;
2471
2472         seq = raw_seqcount_begin(&sp->so_reclaim_seqcount);
2473
2474         ret = _nfs4_proc_open(opendata);
2475         if (ret != 0)
2476                 goto out;
2477
2478         state = nfs4_opendata_to_nfs4_state(opendata);
2479         ret = PTR_ERR(state);
2480         if (IS_ERR(state))
2481                 goto out;
2482         if (server->caps & NFS_CAP_POSIX_LOCK)
2483                 set_bit(NFS_STATE_POSIX_LOCKS, &state->flags);
2484
2485         dentry = opendata->dentry;
2486         if (d_really_is_negative(dentry)) {
2487                 struct dentry *alias;
2488                 d_drop(dentry);
2489                 alias = d_exact_alias(dentry, state->inode);
2490                 if (!alias)
2491                         alias = d_splice_alias(igrab(state->inode), dentry);
2492                 /* d_splice_alias() can't fail here - it's a non-directory */
2493                 if (alias) {
2494                         dput(ctx->dentry);
2495                         ctx->dentry = dentry = alias;
2496                 }
2497                 nfs_set_verifier(dentry,
2498                                 nfs_save_change_attribute(d_inode(opendata->dir)));
2499         }
2500
2501         ret = nfs4_opendata_access(sp->so_cred, opendata, state, fmode, flags);
2502         if (ret != 0)
2503                 goto out;
2504
2505         ctx->state = state;
2506         if (d_inode(dentry) == state->inode) {
2507                 nfs_inode_attach_open_context(ctx);
2508                 if (read_seqcount_retry(&sp->so_reclaim_seqcount, seq))
2509                         nfs4_schedule_stateid_recovery(server, state);
2510         }
2511 out:
2512         return ret;
2513 }
2514
2515 /*
2516  * Returns a referenced nfs4_state
2517  */
2518 static int _nfs4_do_open(struct inode *dir,
2519                         struct nfs_open_context *ctx,
2520                         int flags,
2521                         struct iattr *sattr,
2522                         struct nfs4_label *label,
2523                         int *opened)
2524 {
2525         struct nfs4_state_owner  *sp;
2526         struct nfs4_state     *state = NULL;
2527         struct nfs_server       *server = NFS_SERVER(dir);
2528         struct nfs4_opendata *opendata;
2529         struct dentry *dentry = ctx->dentry;
2530         struct rpc_cred *cred = ctx->cred;
2531         struct nfs4_threshold **ctx_th = &ctx->mdsthreshold;
2532         fmode_t fmode = ctx->mode & (FMODE_READ|FMODE_WRITE|FMODE_EXEC);
2533         enum open_claim_type4 claim = NFS4_OPEN_CLAIM_NULL;
2534         struct nfs4_label *olabel = NULL;
2535         int status;
2536
2537         /* Protect against reboot recovery conflicts */
2538         status = -ENOMEM;
2539         sp = nfs4_get_state_owner(server, cred, GFP_KERNEL);
2540         if (sp == NULL) {
2541                 dprintk("nfs4_do_open: nfs4_get_state_owner failed!\n");
2542                 goto out_err;
2543         }
2544         status = nfs4_recover_expired_lease(server);
2545         if (status != 0)
2546                 goto err_put_state_owner;
2547         if (d_really_is_positive(dentry))
2548                 nfs4_return_incompatible_delegation(d_inode(dentry), fmode);
2549         status = -ENOMEM;
2550         if (d_really_is_positive(dentry))
2551                 claim = NFS4_OPEN_CLAIM_FH;
2552         opendata = nfs4_opendata_alloc(dentry, sp, fmode, flags, sattr,
2553                         label, claim, GFP_KERNEL);
2554         if (opendata == NULL)
2555                 goto err_put_state_owner;
2556
2557         if (label) {
2558                 olabel = nfs4_label_alloc(server, GFP_KERNEL);
2559                 if (IS_ERR(olabel)) {
2560                         status = PTR_ERR(olabel);
2561                         goto err_opendata_put;
2562                 }
2563         }
2564
2565         if (server->attr_bitmask[2] & FATTR4_WORD2_MDSTHRESHOLD) {
2566                 if (!opendata->f_attr.mdsthreshold) {
2567                         opendata->f_attr.mdsthreshold = pnfs_mdsthreshold_alloc();
2568                         if (!opendata->f_attr.mdsthreshold)
2569                                 goto err_free_label;
2570                 }
2571                 opendata->o_arg.open_bitmap = &nfs4_pnfs_open_bitmap[0];
2572         }
2573         if (d_really_is_positive(dentry))
2574                 opendata->state = nfs4_get_open_state(d_inode(dentry), sp);
2575
2576         status = _nfs4_open_and_get_state(opendata, fmode, flags, ctx);
2577         if (status != 0)
2578                 goto err_free_label;
2579         state = ctx->state;
2580
2581         if ((opendata->o_arg.open_flags & (O_CREAT|O_EXCL)) == (O_CREAT|O_EXCL) &&
2582             (opendata->o_arg.createmode != NFS4_CREATE_GUARDED)) {
2583                 nfs4_exclusive_attrset(opendata, sattr, &label);
2584                 /*
2585                  * send create attributes which was not set by open
2586                  * with an extra setattr.
2587                  */
2588                 if (sattr->ia_valid & NFS4_VALID_ATTRS) {
2589                         nfs_fattr_init(opendata->o_res.f_attr);
2590                         status = nfs4_do_setattr(state->inode, cred,
2591                                         opendata->o_res.f_attr, sattr,
2592                                         state, label, olabel);
2593                         if (status == 0) {
2594                                 nfs_setattr_update_inode(state->inode, sattr,
2595                                                 opendata->o_res.f_attr);
2596                                 nfs_setsecurity(state->inode, opendata->o_res.f_attr, olabel);
2597                         }
2598                 }
2599         }
2600         if (opened && opendata->file_created)
2601                 *opened |= FILE_CREATED;
2602
2603         if (pnfs_use_threshold(ctx_th, opendata->f_attr.mdsthreshold, server)) {
2604                 *ctx_th = opendata->f_attr.mdsthreshold;
2605                 opendata->f_attr.mdsthreshold = NULL;
2606         }
2607
2608         nfs4_label_free(olabel);
2609
2610         nfs4_opendata_put(opendata);
2611         nfs4_put_state_owner(sp);
2612         return 0;
2613 err_free_label:
2614         nfs4_label_free(olabel);
2615 err_opendata_put:
2616         nfs4_opendata_put(opendata);
2617 err_put_state_owner:
2618         nfs4_put_state_owner(sp);
2619 out_err:
2620         return status;
2621 }
2622
2623
2624 static struct nfs4_state *nfs4_do_open(struct inode *dir,
2625                                         struct nfs_open_context *ctx,
2626                                         int flags,
2627                                         struct iattr *sattr,
2628                                         struct nfs4_label *label,
2629                                         int *opened)
2630 {
2631         struct nfs_server *server = NFS_SERVER(dir);
2632         struct nfs4_exception exception = { };
2633         struct nfs4_state *res;
2634         int status;
2635
2636         do {
2637                 status = _nfs4_do_open(dir, ctx, flags, sattr, label, opened);
2638                 res = ctx->state;
2639                 trace_nfs4_open_file(ctx, flags, status);
2640                 if (status == 0)
2641                         break;
2642                 /* NOTE: BAD_SEQID means the server and client disagree about the
2643                  * book-keeping w.r.t. state-changing operations
2644                  * (OPEN/CLOSE/LOCK/LOCKU...)
2645                  * It is actually a sign of a bug on the client or on the server.
2646                  *
2647                  * If we receive a BAD_SEQID error in the particular case of
2648                  * doing an OPEN, we assume that nfs_increment_open_seqid() will
2649                  * have unhashed the old state_owner for us, and that we can
2650                  * therefore safely retry using a new one. We should still warn
2651                  * the user though...
2652                  */
2653                 if (status == -NFS4ERR_BAD_SEQID) {
2654                         pr_warn_ratelimited("NFS: v4 server %s "
2655                                         " returned a bad sequence-id error!\n",
2656                                         NFS_SERVER(dir)->nfs_client->cl_hostname);
2657                         exception.retry = 1;
2658                         continue;
2659                 }
2660                 /*
2661                  * BAD_STATEID on OPEN means that the server cancelled our
2662                  * state before it received the OPEN_CONFIRM.
2663                  * Recover by retrying the request as per the discussion
2664                  * on Page 181 of RFC3530.
2665                  */
2666                 if (status == -NFS4ERR_BAD_STATEID) {
2667                         exception.retry = 1;
2668                         continue;
2669                 }
2670                 if (status == -EAGAIN) {
2671                         /* We must have found a delegation */
2672                         exception.retry = 1;
2673                         continue;
2674                 }
2675                 if (nfs4_clear_cap_atomic_open_v1(server, status, &exception))
2676                         continue;
2677                 res = ERR_PTR(nfs4_handle_exception(server,
2678                                         status, &exception));
2679         } while (exception.retry);
2680         return res;
2681 }
2682
2683 static int _nfs4_do_setattr(struct inode *inode,
2684                             struct nfs_setattrargs *arg,
2685                             struct nfs_setattrres *res,
2686                             struct rpc_cred *cred,
2687                             struct nfs4_state *state)
2688 {
2689         struct nfs_server *server = NFS_SERVER(inode);
2690         struct rpc_message msg = {
2691                 .rpc_proc       = &nfs4_procedures[NFSPROC4_CLNT_SETATTR],
2692                 .rpc_argp       = arg,
2693                 .rpc_resp       = res,
2694                 .rpc_cred       = cred,
2695         };
2696         struct rpc_cred *delegation_cred = NULL;
2697         unsigned long timestamp = jiffies;
2698         fmode_t fmode;
2699         bool truncate;
2700         int status;
2701
2702         nfs_fattr_init(res->fattr);
2703
2704         /* Servers should only apply open mode checks for file size changes */
2705         truncate = (arg->iap->ia_valid & ATTR_SIZE) ? true : false;
2706         fmode = truncate ? FMODE_WRITE : FMODE_READ;
2707
2708         if (nfs4_copy_delegation_stateid(inode, fmode, &arg->stateid, &delegation_cred)) {
2709                 /* Use that stateid */
2710         } else if (truncate && state != NULL) {
2711                 struct nfs_lockowner lockowner = {
2712                         .l_owner = current->files,
2713                         .l_pid = current->tgid,
2714                 };
2715                 if (!nfs4_valid_open_stateid(state))
2716                         return -EBADF;
2717                 if (nfs4_select_rw_stateid(state, FMODE_WRITE, &lockowner,
2718                                 &arg->stateid, &delegation_cred) == -EIO)
2719                         return -EBADF;
2720         } else
2721                 nfs4_stateid_copy(&arg->stateid, &zero_stateid);
2722         if (delegation_cred)
2723                 msg.rpc_cred = delegation_cred;
2724
2725         status = nfs4_call_sync(server->client, server, &msg, &arg->seq_args, &res->seq_res, 1);
2726
2727         put_rpccred(delegation_cred);
2728         if (status == 0 && state != NULL)
2729                 renew_lease(server, timestamp);
2730         trace_nfs4_setattr(inode, &arg->stateid, status);
2731         return status;
2732 }
2733
2734 static int nfs4_do_setattr(struct inode *inode, struct rpc_cred *cred,
2735                            struct nfs_fattr *fattr, struct iattr *sattr,
2736                            struct nfs4_state *state, struct nfs4_label *ilabel,
2737                            struct nfs4_label *olabel)
2738 {
2739         struct nfs_server *server = NFS_SERVER(inode);
2740         struct nfs_setattrargs  arg = {
2741                 .fh             = NFS_FH(inode),
2742                 .iap            = sattr,
2743                 .server         = server,
2744                 .bitmask = server->attr_bitmask,
2745                 .label          = ilabel,
2746         };
2747         struct nfs_setattrres  res = {
2748                 .fattr          = fattr,
2749                 .label          = olabel,
2750                 .server         = server,
2751         };
2752         struct nfs4_exception exception = {
2753                 .state = state,
2754                 .inode = inode,
2755                 .stateid = &arg.stateid,
2756         };
2757         int err;
2758
2759         arg.bitmask = nfs4_bitmask(server, ilabel);
2760         if (ilabel)
2761                 arg.bitmask = nfs4_bitmask(server, olabel);
2762
2763         do {
2764                 err = _nfs4_do_setattr(inode, &arg, &res, cred, state);
2765                 switch (err) {
2766                 case -NFS4ERR_OPENMODE:
2767                         if (!(sattr->ia_valid & ATTR_SIZE)) {
2768                                 pr_warn_once("NFSv4: server %s is incorrectly "
2769                                                 "applying open mode checks to "
2770                                                 "a SETATTR that is not "
2771                                                 "changing file size.\n",
2772                                                 server->nfs_client->cl_hostname);
2773                         }
2774                         if (state && !(state->state & FMODE_WRITE)) {
2775                                 err = -EBADF;
2776                                 if (sattr->ia_valid & ATTR_OPEN)
2777                                         err = -EACCES;
2778                                 goto out;
2779                         }
2780                 }
2781                 err = nfs4_handle_exception(server, err, &exception);
2782         } while (exception.retry);
2783 out:
2784         return err;
2785 }
2786
2787 static bool
2788 nfs4_wait_on_layoutreturn(struct inode *inode, struct rpc_task *task)
2789 {
2790         if (inode == NULL || !nfs_have_layout(inode))
2791                 return false;
2792
2793         return pnfs_wait_on_layoutreturn(inode, task);
2794 }
2795
2796 struct nfs4_closedata {
2797         struct inode *inode;
2798         struct nfs4_state *state;
2799         struct nfs_closeargs arg;
2800         struct nfs_closeres res;
2801         struct nfs_fattr fattr;
2802         unsigned long timestamp;
2803         bool roc;
2804         u32 roc_barrier;
2805 };
2806
2807 static void nfs4_free_closedata(void *data)
2808 {
2809         struct nfs4_closedata *calldata = data;
2810         struct nfs4_state_owner *sp = calldata->state->owner;
2811         struct super_block *sb = calldata->state->inode->i_sb;
2812
2813         if (calldata->roc)
2814                 pnfs_roc_release(calldata->state->inode);
2815         nfs4_put_open_state(calldata->state);
2816         nfs_free_seqid(calldata->arg.seqid);
2817         nfs4_put_state_owner(sp);
2818         nfs_sb_deactive(sb);
2819         kfree(calldata);
2820 }
2821
2822 static void nfs4_close_done(struct rpc_task *task, void *data)
2823 {
2824         struct nfs4_closedata *calldata = data;
2825         struct nfs4_state *state = calldata->state;
2826         struct nfs_server *server = NFS_SERVER(calldata->inode);
2827         nfs4_stateid *res_stateid = NULL;
2828
2829         dprintk("%s: begin!\n", __func__);
2830         if (!nfs4_sequence_done(task, &calldata->res.seq_res))
2831                 return;
2832         trace_nfs4_close(state, &calldata->arg, &calldata->res, task->tk_status);
2833         /* hmm. we are done with the inode, and in the process of freeing
2834          * the state_owner. we keep this around to process errors
2835          */
2836         switch (task->tk_status) {
2837                 case 0:
2838                         res_stateid = &calldata->res.stateid;
2839                         if (calldata->roc)
2840                                 pnfs_roc_set_barrier(state->inode,
2841                                                      calldata->roc_barrier);
2842                         renew_lease(server, calldata->timestamp);
2843                         break;
2844                 case -NFS4ERR_ADMIN_REVOKED:
2845                 case -NFS4ERR_STALE_STATEID:
2846                 case -NFS4ERR_OLD_STATEID:
2847                 case -NFS4ERR_BAD_STATEID:
2848                 case -NFS4ERR_EXPIRED:
2849                         if (!nfs4_stateid_match(&calldata->arg.stateid,
2850                                                 &state->open_stateid)) {
2851                                 rpc_restart_call_prepare(task);
2852                                 goto out_release;
2853                         }
2854                         if (calldata->arg.fmode == 0)
2855                                 break;
2856                 default:
2857                         if (nfs4_async_handle_error(task, server, state, NULL) == -EAGAIN) {
2858                                 rpc_restart_call_prepare(task);
2859                                 goto out_release;
2860                         }
2861         }
2862         nfs_clear_open_stateid(state, &calldata->arg.stateid,
2863                         res_stateid, calldata->arg.fmode);
2864 out_release:
2865         nfs_release_seqid(calldata->arg.seqid);
2866         nfs_refresh_inode(calldata->inode, calldata->res.fattr);
2867         dprintk("%s: done, ret = %d!\n", __func__, task->tk_status);
2868 }
2869
2870 static void nfs4_close_prepare(struct rpc_task *task, void *data)
2871 {
2872         struct nfs4_closedata *calldata = data;
2873         struct nfs4_state *state = calldata->state;
2874         struct inode *inode = calldata->inode;
2875         bool is_rdonly, is_wronly, is_rdwr;
2876         int call_close = 0;
2877
2878         dprintk("%s: begin!\n", __func__);
2879         if (nfs_wait_on_sequence(calldata->arg.seqid, task) != 0)
2880                 goto out_wait;
2881
2882         task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_DOWNGRADE];
2883         spin_lock(&state->owner->so_lock);
2884         is_rdwr = test_bit(NFS_O_RDWR_STATE, &state->flags);
2885         is_rdonly = test_bit(NFS_O_RDONLY_STATE, &state->flags);
2886         is_wronly = test_bit(NFS_O_WRONLY_STATE, &state->flags);
2887         nfs4_stateid_copy(&calldata->arg.stateid, &state->open_stateid);
2888         /* Calculate the change in open mode */
2889         calldata->arg.fmode = 0;
2890         if (state->n_rdwr == 0) {
2891                 if (state->n_rdonly == 0)
2892                         call_close |= is_rdonly;
2893                 else if (is_rdonly)
2894                         calldata->arg.fmode |= FMODE_READ;
2895                 if (state->n_wronly == 0)
2896                         call_close |= is_wronly;
2897                 else if (is_wronly)
2898                         calldata->arg.fmode |= FMODE_WRITE;
2899                 if (calldata->arg.fmode != (FMODE_READ|FMODE_WRITE))
2900                         call_close |= is_rdwr;
2901         } else if (is_rdwr)
2902                 calldata->arg.fmode |= FMODE_READ|FMODE_WRITE;
2903
2904         if (!nfs4_valid_open_stateid(state))
2905                 call_close = 0;
2906         spin_unlock(&state->owner->so_lock);
2907
2908         if (!call_close) {
2909                 /* Note: exit _without_ calling nfs4_close_done */
2910                 goto out_no_action;
2911         }
2912
2913         if (nfs4_wait_on_layoutreturn(inode, task)) {
2914                 nfs_release_seqid(calldata->arg.seqid);
2915                 goto out_wait;
2916         }
2917
2918         if (calldata->arg.fmode == 0)
2919                 task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_CLOSE];
2920         if (calldata->roc)
2921                 pnfs_roc_get_barrier(inode, &calldata->roc_barrier);
2922
2923         calldata->arg.share_access =
2924                 nfs4_map_atomic_open_share(NFS_SERVER(inode),
2925                                 calldata->arg.fmode, 0);
2926
2927         nfs_fattr_init(calldata->res.fattr);
2928         calldata->timestamp = jiffies;
2929         if (nfs4_setup_sequence(NFS_SERVER(inode),
2930                                 &calldata->arg.seq_args,
2931                                 &calldata->res.seq_res,
2932                                 task) != 0)
2933                 nfs_release_seqid(calldata->arg.seqid);
2934         dprintk("%s: done!\n", __func__);
2935         return;
2936 out_no_action:
2937         task->tk_action = NULL;
2938 out_wait:
2939         nfs4_sequence_done(task, &calldata->res.seq_res);
2940 }
2941
2942 static const struct rpc_call_ops nfs4_close_ops = {
2943         .rpc_call_prepare = nfs4_close_prepare,
2944         .rpc_call_done = nfs4_close_done,
2945         .rpc_release = nfs4_free_closedata,
2946 };
2947
2948 static bool nfs4_roc(struct inode *inode)
2949 {
2950         if (!nfs_have_layout(inode))
2951                 return false;
2952         return pnfs_roc(inode);
2953 }
2954
2955 /* 
2956  * It is possible for data to be read/written from a mem-mapped file 
2957  * after the sys_close call (which hits the vfs layer as a flush).
2958  * This means that we can't safely call nfsv4 close on a file until 
2959  * the inode is cleared. This in turn means that we are not good
2960  * NFSv4 citizens - we do not indicate to the server to update the file's 
2961  * share state even when we are done with one of the three share 
2962  * stateid's in the inode.
2963  *
2964  * NOTE: Caller must be holding the sp->so_owner semaphore!
2965  */
2966 int nfs4_do_close(struct nfs4_state *state, gfp_t gfp_mask, int wait)
2967 {
2968         struct nfs_server *server = NFS_SERVER(state->inode);
2969         struct nfs_seqid *(*alloc_seqid)(struct nfs_seqid_counter *, gfp_t);
2970         struct nfs4_closedata *calldata;
2971         struct nfs4_state_owner *sp = state->owner;
2972         struct rpc_task *task;
2973         struct rpc_message msg = {
2974                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_CLOSE],
2975                 .rpc_cred = state->owner->so_cred,
2976         };
2977         struct rpc_task_setup task_setup_data = {
2978                 .rpc_client = server->client,
2979                 .rpc_message = &msg,
2980                 .callback_ops = &nfs4_close_ops,
2981                 .workqueue = nfsiod_workqueue,
2982                 .flags = RPC_TASK_ASYNC,
2983         };
2984         int status = -ENOMEM;
2985
2986         nfs4_state_protect(server->nfs_client, NFS_SP4_MACH_CRED_CLEANUP,
2987                 &task_setup_data.rpc_client, &msg);
2988
2989         calldata = kzalloc(sizeof(*calldata), gfp_mask);
2990         if (calldata == NULL)
2991                 goto out;
2992         nfs4_init_sequence(&calldata->arg.seq_args, &calldata->res.seq_res, 1);
2993         calldata->inode = state->inode;
2994         calldata->state = state;
2995         calldata->arg.fh = NFS_FH(state->inode);
2996         /* Serialization for the sequence id */
2997         alloc_seqid = server->nfs_client->cl_mvops->alloc_seqid;
2998         calldata->arg.seqid = alloc_seqid(&state->owner->so_seqid, gfp_mask);
2999         if (IS_ERR(calldata->arg.seqid))
3000                 goto out_free_calldata;
3001         calldata->arg.fmode = 0;
3002         calldata->arg.bitmask = server->cache_consistency_bitmask;
3003         calldata->res.fattr = &calldata->fattr;
3004         calldata->res.seqid = calldata->arg.seqid;
3005         calldata->res.server = server;
3006         calldata->roc = nfs4_roc(state->inode);
3007         nfs_sb_active(calldata->inode->i_sb);
3008
3009         msg.rpc_argp = &calldata->arg;
3010         msg.rpc_resp = &calldata->res;
3011         task_setup_data.callback_data = calldata;
3012         task = rpc_run_task(&task_setup_data);
3013         if (IS_ERR(task))
3014                 return PTR_ERR(task);
3015         status = 0;
3016         if (wait)
3017                 status = rpc_wait_for_completion_task(task);
3018         rpc_put_task(task);
3019         return status;
3020 out_free_calldata:
3021         kfree(calldata);
3022 out:
3023         nfs4_put_open_state(state);
3024         nfs4_put_state_owner(sp);
3025         return status;
3026 }
3027
3028 static struct inode *
3029 nfs4_atomic_open(struct inode *dir, struct nfs_open_context *ctx,
3030                 int open_flags, struct iattr *attr, int *opened)
3031 {
3032         struct nfs4_state *state;
3033         struct nfs4_label l = {0, 0, 0, NULL}, *label = NULL;
3034
3035         label = nfs4_label_init_security(dir, ctx->dentry, attr, &l);
3036
3037         /* Protect against concurrent sillydeletes */
3038         state = nfs4_do_open(dir, ctx, open_flags, attr, label, opened);
3039
3040         nfs4_label_release_security(label);
3041
3042         if (IS_ERR(state))
3043                 return ERR_CAST(state);
3044         return state->inode;
3045 }
3046
3047 static void nfs4_close_context(struct nfs_open_context *ctx, int is_sync)
3048 {
3049         if (ctx->state == NULL)
3050                 return;
3051         if (is_sync)
3052                 nfs4_close_sync(ctx->state, ctx->mode);
3053         else
3054                 nfs4_close_state(ctx->state, ctx->mode);
3055 }
3056
3057 #define FATTR4_WORD1_NFS40_MASK (2*FATTR4_WORD1_MOUNTED_ON_FILEID - 1UL)
3058 #define FATTR4_WORD2_NFS41_MASK (2*FATTR4_WORD2_SUPPATTR_EXCLCREAT - 1UL)
3059 #define FATTR4_WORD2_NFS42_MASK (2*FATTR4_WORD2_SECURITY_LABEL - 1UL)
3060
3061 static int _nfs4_server_capabilities(struct nfs_server *server, struct nfs_fh *fhandle)
3062 {
3063         u32 bitmask[3] = {}, minorversion = server->nfs_client->cl_minorversion;
3064         struct nfs4_server_caps_arg args = {
3065                 .fhandle = fhandle,
3066                 .bitmask = bitmask,
3067         };
3068         struct nfs4_server_caps_res res = {};
3069         struct rpc_message msg = {
3070                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_SERVER_CAPS],
3071                 .rpc_argp = &args,
3072                 .rpc_resp = &res,
3073         };
3074         int status;
3075
3076         bitmask[0] = FATTR4_WORD0_SUPPORTED_ATTRS |
3077                      FATTR4_WORD0_FH_EXPIRE_TYPE |
3078                      FATTR4_WORD0_LINK_SUPPORT |
3079                      FATTR4_WORD0_SYMLINK_SUPPORT |
3080                      FATTR4_WORD0_ACLSUPPORT;
3081         if (minorversion)
3082                 bitmask[2] = FATTR4_WORD2_SUPPATTR_EXCLCREAT;
3083
3084         status = nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 0);
3085         if (status == 0) {
3086                 /* Sanity check the server answers */
3087                 switch (minorversion) {
3088                 case 0:
3089                         res.attr_bitmask[1] &= FATTR4_WORD1_NFS40_MASK;
3090                         res.attr_bitmask[2] = 0;
3091                         break;
3092                 case 1:
3093                         res.attr_bitmask[2] &= FATTR4_WORD2_NFS41_MASK;
3094                         break;
3095                 case 2:
3096                         res.attr_bitmask[2] &= FATTR4_WORD2_NFS42_MASK;
3097                 }
3098                 memcpy(server->attr_bitmask, res.attr_bitmask, sizeof(server->attr_bitmask));
3099                 server->caps &= ~(NFS_CAP_ACLS|NFS_CAP_HARDLINKS|
3100                                 NFS_CAP_SYMLINKS|NFS_CAP_FILEID|
3101                                 NFS_CAP_MODE|NFS_CAP_NLINK|NFS_CAP_OWNER|
3102                                 NFS_CAP_OWNER_GROUP|NFS_CAP_ATIME|
3103                                 NFS_CAP_CTIME|NFS_CAP_MTIME|
3104                                 NFS_CAP_SECURITY_LABEL);
3105                 if (res.attr_bitmask[0] & FATTR4_WORD0_ACL &&
3106                                 res.acl_bitmask & ACL4_SUPPORT_ALLOW_ACL)
3107                         server->caps |= NFS_CAP_ACLS;
3108                 if (res.has_links != 0)
3109                         server->caps |= NFS_CAP_HARDLINKS;
3110                 if (res.has_symlinks != 0)
3111                         server->caps |= NFS_CAP_SYMLINKS;
3112                 if (res.attr_bitmask[0] & FATTR4_WORD0_FILEID)
3113                         server->caps |= NFS_CAP_FILEID;
3114                 if (res.attr_bitmask[1] & FATTR4_WORD1_MODE)
3115                         server->caps |= NFS_CAP_MODE;
3116                 if (res.attr_bitmask[1] & FATTR4_WORD1_NUMLINKS)
3117                         server->caps |= NFS_CAP_NLINK;
3118                 if (res.attr_bitmask[1] & FATTR4_WORD1_OWNER)
3119                         server->caps |= NFS_CAP_OWNER;
3120                 if (res.attr_bitmask[1] & FATTR4_WORD1_OWNER_GROUP)
3121                         server->caps |= NFS_CAP_OWNER_GROUP;
3122                 if (res.attr_bitmask[1] & FATTR4_WORD1_TIME_ACCESS)
3123                         server->caps |= NFS_CAP_ATIME;
3124                 if (res.attr_bitmask[1] & FATTR4_WORD1_TIME_METADATA)
3125                         server->caps |= NFS_CAP_CTIME;
3126                 if (res.attr_bitmask[1] & FATTR4_WORD1_TIME_MODIFY)
3127                         server->caps |= NFS_CAP_MTIME;
3128 #ifdef CONFIG_NFS_V4_SECURITY_LABEL
3129                 if (res.attr_bitmask[2] & FATTR4_WORD2_SECURITY_LABEL)
3130                         server->caps |= NFS_CAP_SECURITY_LABEL;
3131 #endif
3132                 memcpy(server->attr_bitmask_nl, res.attr_bitmask,
3133                                 sizeof(server->attr_bitmask));
3134                 server->attr_bitmask_nl[2] &= ~FATTR4_WORD2_SECURITY_LABEL;
3135
3136                 memcpy(server->cache_consistency_bitmask, res.attr_bitmask, sizeof(server->cache_consistency_bitmask));
3137                 server->cache_consistency_bitmask[0] &= FATTR4_WORD0_CHANGE|FATTR4_WORD0_SIZE;
3138                 server->cache_consistency_bitmask[1] &= FATTR4_WORD1_TIME_METADATA|FATTR4_WORD1_TIME_MODIFY;
3139                 server->cache_consistency_bitmask[2] = 0;
3140                 memcpy(server->exclcreat_bitmask, res.exclcreat_bitmask,
3141                         sizeof(server->exclcreat_bitmask));
3142                 server->acl_bitmask = res.acl_bitmask;
3143                 server->fh_expire_type = res.fh_expire_type;
3144         }
3145
3146         return status;
3147 }
3148
3149 int nfs4_server_capabilities(struct nfs_server *server, struct nfs_fh *fhandle)
3150 {
3151         struct nfs4_exception exception = { };
3152         int err;
3153         do {
3154                 err = nfs4_handle_exception(server,
3155                                 _nfs4_server_capabilities(server, fhandle),
3156                                 &exception);
3157         } while (exception.retry);
3158         return err;
3159 }
3160
3161 static int _nfs4_lookup_root(struct nfs_server *server, struct nfs_fh *fhandle,
3162                 struct nfs_fsinfo *info)
3163 {
3164         u32 bitmask[3];
3165         struct nfs4_lookup_root_arg args = {
3166                 .bitmask = bitmask,
3167         };
3168         struct nfs4_lookup_res res = {
3169                 .server = server,
3170                 .fattr = info->fattr,
3171                 .fh = fhandle,
3172         };
3173         struct rpc_message msg = {
3174                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_LOOKUP_ROOT],
3175                 .rpc_argp = &args,
3176                 .rpc_resp = &res,
3177         };
3178
3179         bitmask[0] = nfs4_fattr_bitmap[0];
3180         bitmask[1] = nfs4_fattr_bitmap[1];
3181         /*
3182          * Process the label in the upcoming getfattr
3183          */
3184         bitmask[2] = nfs4_fattr_bitmap[2] & ~FATTR4_WORD2_SECURITY_LABEL;
3185
3186         nfs_fattr_init(info->fattr);
3187         return nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 0);
3188 }
3189
3190 static int nfs4_lookup_root(struct nfs_server *server, struct nfs_fh *fhandle,
3191                 struct nfs_fsinfo *info)
3192 {
3193         struct nfs4_exception exception = { };
3194         int err;
3195         do {
3196                 err = _nfs4_lookup_root(server, fhandle, info);
3197                 trace_nfs4_lookup_root(server, fhandle, info->fattr, err);
3198                 switch (err) {
3199                 case 0:
3200                 case -NFS4ERR_WRONGSEC:
3201                         goto out;
3202                 default:
3203                         err = nfs4_handle_exception(server, err, &exception);
3204                 }
3205         } while (exception.retry);
3206 out:
3207         return err;
3208 }
3209
3210 static int nfs4_lookup_root_sec(struct nfs_server *server, struct nfs_fh *fhandle,
3211                                 struct nfs_fsinfo *info, rpc_authflavor_t flavor)
3212 {
3213         struct rpc_auth_create_args auth_args = {
3214                 .pseudoflavor = flavor,
3215         };
3216         struct rpc_auth *auth;
3217         int ret;
3218
3219         auth = rpcauth_create(&auth_args, server->client);
3220         if (IS_ERR(auth)) {
3221                 ret = -EACCES;
3222                 goto out;
3223         }
3224         ret = nfs4_lookup_root(server, fhandle, info);
3225 out:
3226         return ret;
3227 }
3228
3229 /*
3230  * Retry pseudoroot lookup with various security flavors.  We do this when:
3231  *
3232  *   NFSv4.0: the PUTROOTFH operation returns NFS4ERR_WRONGSEC
3233  *   NFSv4.1: the server does not support the SECINFO_NO_NAME operation
3234  *
3235  * Returns zero on success, or a negative NFS4ERR value, or a
3236  * negative errno value.
3237  */
3238 static int nfs4_find_root_sec(struct nfs_server *server, struct nfs_fh *fhandle,
3239                               struct nfs_fsinfo *info)
3240 {
3241         /* Per 3530bis 15.33.5 */
3242         static const rpc_authflavor_t flav_array[] = {
3243                 RPC_AUTH_GSS_KRB5P,
3244                 RPC_AUTH_GSS_KRB5I,
3245                 RPC_AUTH_GSS_KRB5,
3246                 RPC_AUTH_UNIX,                  /* courtesy */
3247                 RPC_AUTH_NULL,
3248         };
3249         int status = -EPERM;
3250         size_t i;
3251
3252         if (server->auth_info.flavor_len > 0) {
3253                 /* try each flavor specified by user */
3254                 for (i = 0; i < server->auth_info.flavor_len; i++) {
3255                         status = nfs4_lookup_root_sec(server, fhandle, info,
3256                                                 server->auth_info.flavors[i]);
3257                         if (status == -NFS4ERR_WRONGSEC || status == -EACCES)
3258                                 continue;
3259                         break;
3260                 }
3261         } else {
3262                 /* no flavors specified by user, try default list */
3263                 for (i = 0; i < ARRAY_SIZE(flav_array); i++) {
3264                         status = nfs4_lookup_root_sec(server, fhandle, info,
3265                                                       flav_array[i]);
3266                         if (status == -NFS4ERR_WRONGSEC || status == -EACCES)
3267                                 continue;
3268                         break;
3269                 }
3270  &nb