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