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