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