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