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