pNFS: Layoutreturn must invalidate all existing layout segments.
[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                 case -NFS4ERR_DELEG_REVOKED:
360                 case -NFS4ERR_ADMIN_REVOKED:
361                 case -NFS4ERR_BAD_STATEID:
362                         if (inode && nfs4_have_delegation(inode, FMODE_READ)) {
363                                 nfs4_inode_return_delegation(inode);
364                                 exception->retry = 1;
365                                 return 0;
366                         }
367                         if (state == NULL)
368                                 break;
369                         ret = nfs4_schedule_stateid_recovery(server, state);
370                         if (ret < 0)
371                                 break;
372                         goto wait_on_recovery;
373                 case -NFS4ERR_EXPIRED:
374                         if (state != NULL) {
375                                 ret = nfs4_schedule_stateid_recovery(server, state);
376                                 if (ret < 0)
377                                         break;
378                         }
379                 case -NFS4ERR_STALE_STATEID:
380                 case -NFS4ERR_STALE_CLIENTID:
381                         nfs4_schedule_lease_recovery(clp);
382                         goto wait_on_recovery;
383                 case -NFS4ERR_MOVED:
384                         ret = nfs4_schedule_migration_recovery(server);
385                         if (ret < 0)
386                                 break;
387                         goto wait_on_recovery;
388                 case -NFS4ERR_LEASE_MOVED:
389                         nfs4_schedule_lease_moved_recovery(clp);
390                         goto wait_on_recovery;
391 #if defined(CONFIG_NFS_V4_1)
392                 case -NFS4ERR_BADSESSION:
393                 case -NFS4ERR_BADSLOT:
394                 case -NFS4ERR_BAD_HIGH_SLOT:
395                 case -NFS4ERR_CONN_NOT_BOUND_TO_SESSION:
396                 case -NFS4ERR_DEADSESSION:
397                 case -NFS4ERR_SEQ_FALSE_RETRY:
398                 case -NFS4ERR_SEQ_MISORDERED:
399                         dprintk("%s ERROR: %d Reset session\n", __func__,
400                                 errorcode);
401                         nfs4_schedule_session_recovery(clp->cl_session, errorcode);
402                         goto wait_on_recovery;
403 #endif /* defined(CONFIG_NFS_V4_1) */
404                 case -NFS4ERR_FILE_OPEN:
405                         if (exception->timeout > HZ) {
406                                 /* We have retried a decent amount, time to
407                                  * fail
408                                  */
409                                 ret = -EBUSY;
410                                 break;
411                         }
412                 case -NFS4ERR_GRACE:
413                 case -NFS4ERR_DELAY:
414                         ret = nfs4_delay(server->client, &exception->timeout);
415                         if (ret != 0)
416                                 break;
417                 case -NFS4ERR_RETRY_UNCACHED_REP:
418                 case -NFS4ERR_OLD_STATEID:
419                         exception->retry = 1;
420                         break;
421                 case -NFS4ERR_BADOWNER:
422                         /* The following works around a Linux server bug! */
423                 case -NFS4ERR_BADNAME:
424                         if (server->caps & NFS_CAP_UIDGID_NOMAP) {
425                                 server->caps &= ~NFS_CAP_UIDGID_NOMAP;
426                                 exception->retry = 1;
427                                 printk(KERN_WARNING "NFS: v4 server %s "
428                                                 "does not accept raw "
429                                                 "uid/gids. "
430                                                 "Reenabling the idmapper.\n",
431                                                 server->nfs_client->cl_hostname);
432                         }
433         }
434         /* We failed to handle the error */
435         return nfs4_map_errors(ret);
436 wait_on_recovery:
437         ret = nfs4_wait_clnt_recover(clp);
438         if (test_bit(NFS_MIG_FAILED, &server->mig_status))
439                 return -EIO;
440         if (ret == 0)
441                 exception->retry = 1;
442         return ret;
443 }
444
445 /*
446  * Return 'true' if 'clp' is using an rpc_client that is integrity protected
447  * or 'false' otherwise.
448  */
449 static bool _nfs4_is_integrity_protected(struct nfs_client *clp)
450 {
451         rpc_authflavor_t flavor = clp->cl_rpcclient->cl_auth->au_flavor;
452
453         if (flavor == RPC_AUTH_GSS_KRB5I ||
454             flavor == RPC_AUTH_GSS_KRB5P)
455                 return true;
456
457         return false;
458 }
459
460 static void do_renew_lease(struct nfs_client *clp, unsigned long timestamp)
461 {
462         spin_lock(&clp->cl_lock);
463         if (time_before(clp->cl_last_renewal,timestamp))
464                 clp->cl_last_renewal = timestamp;
465         spin_unlock(&clp->cl_lock);
466 }
467
468 static void renew_lease(const struct nfs_server *server, unsigned long timestamp)
469 {
470         struct nfs_client *clp = server->nfs_client;
471
472         if (!nfs4_has_session(clp))
473                 do_renew_lease(clp, timestamp);
474 }
475
476 struct nfs4_call_sync_data {
477         const struct nfs_server *seq_server;
478         struct nfs4_sequence_args *seq_args;
479         struct nfs4_sequence_res *seq_res;
480 };
481
482 void nfs4_init_sequence(struct nfs4_sequence_args *args,
483                         struct nfs4_sequence_res *res, int cache_reply)
484 {
485         args->sa_slot = NULL;
486         args->sa_cache_this = cache_reply;
487         args->sa_privileged = 0;
488
489         res->sr_slot = NULL;
490 }
491
492 static void nfs4_set_sequence_privileged(struct nfs4_sequence_args *args)
493 {
494         args->sa_privileged = 1;
495 }
496
497 int nfs40_setup_sequence(struct nfs4_slot_table *tbl,
498                          struct nfs4_sequence_args *args,
499                          struct nfs4_sequence_res *res,
500                          struct rpc_task *task)
501 {
502         struct nfs4_slot *slot;
503
504         /* slot already allocated? */
505         if (res->sr_slot != NULL)
506                 goto out_start;
507
508         spin_lock(&tbl->slot_tbl_lock);
509         if (nfs4_slot_tbl_draining(tbl) && !args->sa_privileged)
510                 goto out_sleep;
511
512         slot = nfs4_alloc_slot(tbl);
513         if (IS_ERR(slot)) {
514                 if (slot == ERR_PTR(-ENOMEM))
515                         task->tk_timeout = HZ >> 2;
516                 goto out_sleep;
517         }
518         spin_unlock(&tbl->slot_tbl_lock);
519
520         args->sa_slot = slot;
521         res->sr_slot = slot;
522
523 out_start:
524         rpc_call_start(task);
525         return 0;
526
527 out_sleep:
528         if (args->sa_privileged)
529                 rpc_sleep_on_priority(&tbl->slot_tbl_waitq, task,
530                                 NULL, RPC_PRIORITY_PRIVILEGED);
531         else
532                 rpc_sleep_on(&tbl->slot_tbl_waitq, task, NULL);
533         spin_unlock(&tbl->slot_tbl_lock);
534         return -EAGAIN;
535 }
536 EXPORT_SYMBOL_GPL(nfs40_setup_sequence);
537
538 static int nfs40_sequence_done(struct rpc_task *task,
539                                struct nfs4_sequence_res *res)
540 {
541         struct nfs4_slot *slot = res->sr_slot;
542         struct nfs4_slot_table *tbl;
543
544         if (slot == NULL)
545                 goto out;
546
547         tbl = slot->table;
548         spin_lock(&tbl->slot_tbl_lock);
549         if (!nfs41_wake_and_assign_slot(tbl, slot))
550                 nfs4_free_slot(tbl, slot);
551         spin_unlock(&tbl->slot_tbl_lock);
552
553         res->sr_slot = NULL;
554 out:
555         return 1;
556 }
557
558 #if defined(CONFIG_NFS_V4_1)
559
560 static void nfs41_sequence_free_slot(struct nfs4_sequence_res *res)
561 {
562         struct nfs4_session *session;
563         struct nfs4_slot_table *tbl;
564         struct nfs4_slot *slot = res->sr_slot;
565         bool send_new_highest_used_slotid = false;
566
567         tbl = slot->table;
568         session = tbl->session;
569
570         spin_lock(&tbl->slot_tbl_lock);
571         /* Be nice to the server: try to ensure that the last transmitted
572          * value for highest_user_slotid <= target_highest_slotid
573          */
574         if (tbl->highest_used_slotid > tbl->target_highest_slotid)
575                 send_new_highest_used_slotid = true;
576
577         if (nfs41_wake_and_assign_slot(tbl, slot)) {
578                 send_new_highest_used_slotid = false;
579                 goto out_unlock;
580         }
581         nfs4_free_slot(tbl, slot);
582
583         if (tbl->highest_used_slotid != NFS4_NO_SLOT)
584                 send_new_highest_used_slotid = false;
585 out_unlock:
586         spin_unlock(&tbl->slot_tbl_lock);
587         res->sr_slot = NULL;
588         if (send_new_highest_used_slotid)
589                 nfs41_server_notify_highest_slotid_update(session->clp);
590 }
591
592 int nfs41_sequence_done(struct rpc_task *task, struct nfs4_sequence_res *res)
593 {
594         struct nfs4_session *session;
595         struct nfs4_slot *slot = res->sr_slot;
596         struct nfs_client *clp;
597         bool interrupted = false;
598         int ret = 1;
599
600         if (slot == NULL)
601                 goto out_noaction;
602         /* don't increment the sequence number if the task wasn't sent */
603         if (!RPC_WAS_SENT(task))
604                 goto out;
605
606         session = slot->table->session;
607
608         if (slot->interrupted) {
609                 slot->interrupted = 0;
610                 interrupted = true;
611         }
612
613         trace_nfs4_sequence_done(session, res);
614         /* Check the SEQUENCE operation status */
615         switch (res->sr_status) {
616         case 0:
617                 /* Update the slot's sequence and clientid lease timer */
618                 ++slot->seq_nr;
619                 clp = session->clp;
620                 do_renew_lease(clp, res->sr_timestamp);
621                 /* Check sequence flags */
622                 nfs41_handle_sequence_flag_errors(clp, res->sr_status_flags);
623                 nfs41_update_target_slotid(slot->table, slot, res);
624                 break;
625         case 1:
626                 /*
627                  * sr_status remains 1 if an RPC level error occurred.
628                  * The server may or may not have processed the sequence
629                  * operation..
630                  * Mark the slot as having hosted an interrupted RPC call.
631                  */
632                 slot->interrupted = 1;
633                 goto out;
634         case -NFS4ERR_DELAY:
635                 /* The server detected a resend of the RPC call and
636                  * returned NFS4ERR_DELAY as per Section 2.10.6.2
637                  * of RFC5661.
638                  */
639                 dprintk("%s: slot=%u seq=%u: Operation in progress\n",
640                         __func__,
641                         slot->slot_nr,
642                         slot->seq_nr);
643                 goto out_retry;
644         case -NFS4ERR_BADSLOT:
645                 /*
646                  * The slot id we used was probably retired. Try again
647                  * using a different slot id.
648                  */
649                 goto retry_nowait;
650         case -NFS4ERR_SEQ_MISORDERED:
651                 /*
652                  * Was the last operation on this sequence interrupted?
653                  * If so, retry after bumping the sequence number.
654                  */
655                 if (interrupted) {
656                         ++slot->seq_nr;
657                         goto retry_nowait;
658                 }
659                 /*
660                  * Could this slot have been previously retired?
661                  * If so, then the server may be expecting seq_nr = 1!
662                  */
663                 if (slot->seq_nr != 1) {
664                         slot->seq_nr = 1;
665                         goto retry_nowait;
666                 }
667                 break;
668         case -NFS4ERR_SEQ_FALSE_RETRY:
669                 ++slot->seq_nr;
670                 goto retry_nowait;
671         default:
672                 /* Just update the slot sequence no. */
673                 ++slot->seq_nr;
674         }
675 out:
676         /* The session may be reset by one of the error handlers. */
677         dprintk("%s: Error %d free the slot \n", __func__, res->sr_status);
678         nfs41_sequence_free_slot(res);
679 out_noaction:
680         return ret;
681 retry_nowait:
682         if (rpc_restart_call_prepare(task)) {
683                 task->tk_status = 0;
684                 ret = 0;
685         }
686         goto out;
687 out_retry:
688         if (!rpc_restart_call(task))
689                 goto out;
690         rpc_delay(task, NFS4_POLL_RETRY_MAX);
691         return 0;
692 }
693 EXPORT_SYMBOL_GPL(nfs41_sequence_done);
694
695 int nfs4_sequence_done(struct rpc_task *task, struct nfs4_sequence_res *res)
696 {
697         if (res->sr_slot == NULL)
698                 return 1;
699         if (!res->sr_slot->table->session)
700                 return nfs40_sequence_done(task, res);
701         return nfs41_sequence_done(task, res);
702 }
703 EXPORT_SYMBOL_GPL(nfs4_sequence_done);
704
705 int nfs41_setup_sequence(struct nfs4_session *session,
706                                 struct nfs4_sequence_args *args,
707                                 struct nfs4_sequence_res *res,
708                                 struct rpc_task *task)
709 {
710         struct nfs4_slot *slot;
711         struct nfs4_slot_table *tbl;
712
713         dprintk("--> %s\n", __func__);
714         /* slot already allocated? */
715         if (res->sr_slot != NULL)
716                 goto out_success;
717
718         tbl = &session->fc_slot_table;
719
720         task->tk_timeout = 0;
721
722         spin_lock(&tbl->slot_tbl_lock);
723         if (test_bit(NFS4_SLOT_TBL_DRAINING, &tbl->slot_tbl_state) &&
724             !args->sa_privileged) {
725                 /* The state manager will wait until the slot table is empty */
726                 dprintk("%s session is draining\n", __func__);
727                 goto out_sleep;
728         }
729
730         slot = nfs4_alloc_slot(tbl);
731         if (IS_ERR(slot)) {
732                 /* If out of memory, try again in 1/4 second */
733                 if (slot == ERR_PTR(-ENOMEM))
734                         task->tk_timeout = HZ >> 2;
735                 dprintk("<-- %s: no free slots\n", __func__);
736                 goto out_sleep;
737         }
738         spin_unlock(&tbl->slot_tbl_lock);
739
740         args->sa_slot = slot;
741
742         dprintk("<-- %s slotid=%u seqid=%u\n", __func__,
743                         slot->slot_nr, slot->seq_nr);
744
745         res->sr_slot = slot;
746         res->sr_timestamp = jiffies;
747         res->sr_status_flags = 0;
748         /*
749          * sr_status is only set in decode_sequence, and so will remain
750          * set to 1 if an rpc level failure occurs.
751          */
752         res->sr_status = 1;
753         trace_nfs4_setup_sequence(session, args);
754 out_success:
755         rpc_call_start(task);
756         return 0;
757 out_sleep:
758         /* Privileged tasks are queued with top priority */
759         if (args->sa_privileged)
760                 rpc_sleep_on_priority(&tbl->slot_tbl_waitq, task,
761                                 NULL, RPC_PRIORITY_PRIVILEGED);
762         else
763                 rpc_sleep_on(&tbl->slot_tbl_waitq, task, NULL);
764         spin_unlock(&tbl->slot_tbl_lock);
765         return -EAGAIN;
766 }
767 EXPORT_SYMBOL_GPL(nfs41_setup_sequence);
768
769 static int nfs4_setup_sequence(const struct nfs_server *server,
770                                struct nfs4_sequence_args *args,
771                                struct nfs4_sequence_res *res,
772                                struct rpc_task *task)
773 {
774         struct nfs4_session *session = nfs4_get_session(server);
775         int ret = 0;
776
777         if (!session)
778                 return nfs40_setup_sequence(server->nfs_client->cl_slot_tbl,
779                                             args, res, task);
780
781         dprintk("--> %s clp %p session %p sr_slot %u\n",
782                 __func__, session->clp, session, res->sr_slot ?
783                         res->sr_slot->slot_nr : NFS4_NO_SLOT);
784
785         ret = nfs41_setup_sequence(session, args, res, task);
786
787         dprintk("<-- %s status=%d\n", __func__, ret);
788         return ret;
789 }
790
791 static void nfs41_call_sync_prepare(struct rpc_task *task, void *calldata)
792 {
793         struct nfs4_call_sync_data *data = calldata;
794         struct nfs4_session *session = nfs4_get_session(data->seq_server);
795
796         dprintk("--> %s data->seq_server %p\n", __func__, data->seq_server);
797
798         nfs41_setup_sequence(session, data->seq_args, data->seq_res, task);
799 }
800
801 static void nfs41_call_sync_done(struct rpc_task *task, void *calldata)
802 {
803         struct nfs4_call_sync_data *data = calldata;
804
805         nfs41_sequence_done(task, data->seq_res);
806 }
807
808 static const struct rpc_call_ops nfs41_call_sync_ops = {
809         .rpc_call_prepare = nfs41_call_sync_prepare,
810         .rpc_call_done = nfs41_call_sync_done,
811 };
812
813 #else   /* !CONFIG_NFS_V4_1 */
814
815 static int nfs4_setup_sequence(const struct nfs_server *server,
816                                struct nfs4_sequence_args *args,
817                                struct nfs4_sequence_res *res,
818                                struct rpc_task *task)
819 {
820         return nfs40_setup_sequence(server->nfs_client->cl_slot_tbl,
821                                     args, res, task);
822 }
823
824 int nfs4_sequence_done(struct rpc_task *task,
825                        struct nfs4_sequence_res *res)
826 {
827         return nfs40_sequence_done(task, res);
828 }
829 EXPORT_SYMBOL_GPL(nfs4_sequence_done);
830
831 #endif  /* !CONFIG_NFS_V4_1 */
832
833 static void nfs40_call_sync_prepare(struct rpc_task *task, void *calldata)
834 {
835         struct nfs4_call_sync_data *data = calldata;
836         nfs4_setup_sequence(data->seq_server,
837                                 data->seq_args, data->seq_res, task);
838 }
839
840 static void nfs40_call_sync_done(struct rpc_task *task, void *calldata)
841 {
842         struct nfs4_call_sync_data *data = calldata;
843         nfs4_sequence_done(task, data->seq_res);
844 }
845
846 static const struct rpc_call_ops nfs40_call_sync_ops = {
847         .rpc_call_prepare = nfs40_call_sync_prepare,
848         .rpc_call_done = nfs40_call_sync_done,
849 };
850
851 static int nfs4_call_sync_sequence(struct rpc_clnt *clnt,
852                                    struct nfs_server *server,
853                                    struct rpc_message *msg,
854                                    struct nfs4_sequence_args *args,
855                                    struct nfs4_sequence_res *res)
856 {
857         int ret;
858         struct rpc_task *task;
859         struct nfs_client *clp = server->nfs_client;
860         struct nfs4_call_sync_data data = {
861                 .seq_server = server,
862                 .seq_args = args,
863                 .seq_res = res,
864         };
865         struct rpc_task_setup task_setup = {
866                 .rpc_client = clnt,
867                 .rpc_message = msg,
868                 .callback_ops = clp->cl_mvops->call_sync_ops,
869                 .callback_data = &data
870         };
871
872         task = rpc_run_task(&task_setup);
873         if (IS_ERR(task))
874                 ret = PTR_ERR(task);
875         else {
876                 ret = task->tk_status;
877                 rpc_put_task(task);
878         }
879         return ret;
880 }
881
882 int nfs4_call_sync(struct rpc_clnt *clnt,
883                    struct nfs_server *server,
884                    struct rpc_message *msg,
885                    struct nfs4_sequence_args *args,
886                    struct nfs4_sequence_res *res,
887                    int cache_reply)
888 {
889         nfs4_init_sequence(args, res, cache_reply);
890         return nfs4_call_sync_sequence(clnt, server, msg, args, res);
891 }
892
893 static void update_changeattr(struct inode *dir, struct nfs4_change_info *cinfo)
894 {
895         struct nfs_inode *nfsi = NFS_I(dir);
896
897         spin_lock(&dir->i_lock);
898         nfsi->cache_validity |= NFS_INO_INVALID_ATTR|NFS_INO_INVALID_DATA;
899         if (!cinfo->atomic || cinfo->before != dir->i_version)
900                 nfs_force_lookup_revalidate(dir);
901         dir->i_version = cinfo->after;
902         nfsi->attr_gencount = nfs_inc_attr_generation_counter();
903         nfs_fscache_invalidate(dir);
904         spin_unlock(&dir->i_lock);
905 }
906
907 struct nfs4_opendata {
908         struct kref kref;
909         struct nfs_openargs o_arg;
910         struct nfs_openres o_res;
911         struct nfs_open_confirmargs c_arg;
912         struct nfs_open_confirmres c_res;
913         struct nfs4_string owner_name;
914         struct nfs4_string group_name;
915         struct nfs_fattr f_attr;
916         struct nfs4_label *f_label;
917         struct dentry *dir;
918         struct dentry *dentry;
919         struct nfs4_state_owner *owner;
920         struct nfs4_state *state;
921         struct iattr attrs;
922         unsigned long timestamp;
923         unsigned int rpc_done : 1;
924         unsigned int file_created : 1;
925         unsigned int is_recover : 1;
926         int rpc_status;
927         int cancelled;
928 };
929
930 static bool nfs4_clear_cap_atomic_open_v1(struct nfs_server *server,
931                 int err, struct nfs4_exception *exception)
932 {
933         if (err != -EINVAL)
934                 return false;
935         if (!(server->caps & NFS_CAP_ATOMIC_OPEN_V1))
936                 return false;
937         server->caps &= ~NFS_CAP_ATOMIC_OPEN_V1;
938         exception->retry = 1;
939         return true;
940 }
941
942 static u32
943 nfs4_map_atomic_open_share(struct nfs_server *server,
944                 fmode_t fmode, int openflags)
945 {
946         u32 res = 0;
947
948         switch (fmode & (FMODE_READ | FMODE_WRITE)) {
949         case FMODE_READ:
950                 res = NFS4_SHARE_ACCESS_READ;
951                 break;
952         case FMODE_WRITE:
953                 res = NFS4_SHARE_ACCESS_WRITE;
954                 break;
955         case FMODE_READ|FMODE_WRITE:
956                 res = NFS4_SHARE_ACCESS_BOTH;
957         }
958         if (!(server->caps & NFS_CAP_ATOMIC_OPEN_V1))
959                 goto out;
960         /* Want no delegation if we're using O_DIRECT */
961         if (openflags & O_DIRECT)
962                 res |= NFS4_SHARE_WANT_NO_DELEG;
963 out:
964         return res;
965 }
966
967 static enum open_claim_type4
968 nfs4_map_atomic_open_claim(struct nfs_server *server,
969                 enum open_claim_type4 claim)
970 {
971         if (server->caps & NFS_CAP_ATOMIC_OPEN_V1)
972                 return claim;
973         switch (claim) {
974         default:
975                 return claim;
976         case NFS4_OPEN_CLAIM_FH:
977                 return NFS4_OPEN_CLAIM_NULL;
978         case NFS4_OPEN_CLAIM_DELEG_CUR_FH:
979                 return NFS4_OPEN_CLAIM_DELEGATE_CUR;
980         case NFS4_OPEN_CLAIM_DELEG_PREV_FH:
981                 return NFS4_OPEN_CLAIM_DELEGATE_PREV;
982         }
983 }
984
985 static void nfs4_init_opendata_res(struct nfs4_opendata *p)
986 {
987         p->o_res.f_attr = &p->f_attr;
988         p->o_res.f_label = p->f_label;
989         p->o_res.seqid = p->o_arg.seqid;
990         p->c_res.seqid = p->c_arg.seqid;
991         p->o_res.server = p->o_arg.server;
992         p->o_res.access_request = p->o_arg.access;
993         nfs_fattr_init(&p->f_attr);
994         nfs_fattr_init_names(&p->f_attr, &p->owner_name, &p->group_name);
995 }
996
997 static struct nfs4_opendata *nfs4_opendata_alloc(struct dentry *dentry,
998                 struct nfs4_state_owner *sp, fmode_t fmode, int flags,
999                 const struct iattr *attrs,
1000                 struct nfs4_label *label,
1001                 enum open_claim_type4 claim,
1002                 gfp_t gfp_mask)
1003 {
1004         struct dentry *parent = dget_parent(dentry);
1005         struct inode *dir = d_inode(parent);
1006         struct nfs_server *server = NFS_SERVER(dir);
1007         struct nfs_seqid *(*alloc_seqid)(struct nfs_seqid_counter *, gfp_t);
1008         struct nfs4_opendata *p;
1009
1010         p = kzalloc(sizeof(*p), gfp_mask);
1011         if (p == NULL)
1012                 goto err;
1013
1014         p->f_label = nfs4_label_alloc(server, gfp_mask);
1015         if (IS_ERR(p->f_label))
1016                 goto err_free_p;
1017
1018         alloc_seqid = server->nfs_client->cl_mvops->alloc_seqid;
1019         p->o_arg.seqid = alloc_seqid(&sp->so_seqid, gfp_mask);
1020         if (IS_ERR(p->o_arg.seqid))
1021                 goto err_free_label;
1022         nfs_sb_active(dentry->d_sb);
1023         p->dentry = dget(dentry);
1024         p->dir = parent;
1025         p->owner = sp;
1026         atomic_inc(&sp->so_count);
1027         p->o_arg.open_flags = flags;
1028         p->o_arg.fmode = fmode & (FMODE_READ|FMODE_WRITE);
1029         p->o_arg.share_access = nfs4_map_atomic_open_share(server,
1030                         fmode, flags);
1031         /* don't put an ACCESS op in OPEN compound if O_EXCL, because ACCESS
1032          * will return permission denied for all bits until close */
1033         if (!(flags & O_EXCL)) {
1034                 /* ask server to check for all possible rights as results
1035                  * are cached */
1036                 p->o_arg.access = NFS4_ACCESS_READ | NFS4_ACCESS_MODIFY |
1037                                   NFS4_ACCESS_EXTEND | NFS4_ACCESS_EXECUTE;
1038         }
1039         p->o_arg.clientid = server->nfs_client->cl_clientid;
1040         p->o_arg.id.create_time = ktime_to_ns(sp->so_seqid.create_time);
1041         p->o_arg.id.uniquifier = sp->so_seqid.owner_id;
1042         p->o_arg.name = &dentry->d_name;
1043         p->o_arg.server = server;
1044         p->o_arg.bitmask = nfs4_bitmask(server, label);
1045         p->o_arg.open_bitmap = &nfs4_fattr_bitmap[0];
1046         p->o_arg.label = label;
1047         p->o_arg.claim = nfs4_map_atomic_open_claim(server, claim);
1048         switch (p->o_arg.claim) {
1049         case NFS4_OPEN_CLAIM_NULL:
1050         case NFS4_OPEN_CLAIM_DELEGATE_CUR:
1051         case NFS4_OPEN_CLAIM_DELEGATE_PREV:
1052                 p->o_arg.fh = NFS_FH(dir);
1053                 break;
1054         case NFS4_OPEN_CLAIM_PREVIOUS:
1055         case NFS4_OPEN_CLAIM_FH:
1056         case NFS4_OPEN_CLAIM_DELEG_CUR_FH:
1057         case NFS4_OPEN_CLAIM_DELEG_PREV_FH:
1058                 p->o_arg.fh = NFS_FH(d_inode(dentry));
1059         }
1060         if (attrs != NULL && attrs->ia_valid != 0) {
1061                 __u32 verf[2];
1062
1063                 p->o_arg.u.attrs = &p->attrs;
1064                 memcpy(&p->attrs, attrs, sizeof(p->attrs));
1065
1066                 verf[0] = jiffies;
1067                 verf[1] = current->pid;
1068                 memcpy(p->o_arg.u.verifier.data, verf,
1069                                 sizeof(p->o_arg.u.verifier.data));
1070         }
1071         p->c_arg.fh = &p->o_res.fh;
1072         p->c_arg.stateid = &p->o_res.stateid;
1073         p->c_arg.seqid = p->o_arg.seqid;
1074         nfs4_init_opendata_res(p);
1075         kref_init(&p->kref);
1076         return p;
1077
1078 err_free_label:
1079         nfs4_label_free(p->f_label);
1080 err_free_p:
1081         kfree(p);
1082 err:
1083         dput(parent);
1084         return NULL;
1085 }
1086
1087 static void nfs4_opendata_free(struct kref *kref)
1088 {
1089         struct nfs4_opendata *p = container_of(kref,
1090                         struct nfs4_opendata, kref);
1091         struct super_block *sb = p->dentry->d_sb;
1092
1093         nfs_free_seqid(p->o_arg.seqid);
1094         if (p->state != NULL)
1095                 nfs4_put_open_state(p->state);
1096         nfs4_put_state_owner(p->owner);
1097
1098         nfs4_label_free(p->f_label);
1099
1100         dput(p->dir);
1101         dput(p->dentry);
1102         nfs_sb_deactive(sb);
1103         nfs_fattr_free_names(&p->f_attr);
1104         kfree(p->f_attr.mdsthreshold);
1105         kfree(p);
1106 }
1107
1108 static void nfs4_opendata_put(struct nfs4_opendata *p)
1109 {
1110         if (p != NULL)
1111                 kref_put(&p->kref, nfs4_opendata_free);
1112 }
1113
1114 static int nfs4_wait_for_completion_rpc_task(struct rpc_task *task)
1115 {
1116         int ret;
1117
1118         ret = rpc_wait_for_completion_task(task);
1119         return ret;
1120 }
1121
1122 static int can_open_cached(struct nfs4_state *state, fmode_t mode, int open_mode)
1123 {
1124         int ret = 0;
1125
1126         if (open_mode & (O_EXCL|O_TRUNC))
1127                 goto out;
1128         switch (mode & (FMODE_READ|FMODE_WRITE)) {
1129                 case FMODE_READ:
1130                         ret |= test_bit(NFS_O_RDONLY_STATE, &state->flags) != 0
1131                                 && state->n_rdonly != 0;
1132                         break;
1133                 case FMODE_WRITE:
1134                         ret |= test_bit(NFS_O_WRONLY_STATE, &state->flags) != 0
1135                                 && state->n_wronly != 0;
1136                         break;
1137                 case FMODE_READ|FMODE_WRITE:
1138                         ret |= test_bit(NFS_O_RDWR_STATE, &state->flags) != 0
1139                                 && state->n_rdwr != 0;
1140         }
1141 out:
1142         return ret;
1143 }
1144
1145 static int can_open_delegated(struct nfs_delegation *delegation, fmode_t fmode)
1146 {
1147         if (delegation == NULL)
1148                 return 0;
1149         if ((delegation->type & fmode) != fmode)
1150                 return 0;
1151         if (test_bit(NFS_DELEGATION_RETURNING, &delegation->flags))
1152                 return 0;
1153         nfs_mark_delegation_referenced(delegation);
1154         return 1;
1155 }
1156
1157 static void update_open_stateflags(struct nfs4_state *state, fmode_t fmode)
1158 {
1159         switch (fmode) {
1160                 case FMODE_WRITE:
1161                         state->n_wronly++;
1162                         break;
1163                 case FMODE_READ:
1164                         state->n_rdonly++;
1165                         break;
1166                 case FMODE_READ|FMODE_WRITE:
1167                         state->n_rdwr++;
1168         }
1169         nfs4_state_set_mode_locked(state, state->state | fmode);
1170 }
1171
1172 static void nfs_test_and_clear_all_open_stateid(struct nfs4_state *state)
1173 {
1174         struct nfs_client *clp = state->owner->so_server->nfs_client;
1175         bool need_recover = false;
1176
1177         if (test_and_clear_bit(NFS_O_RDONLY_STATE, &state->flags) && state->n_rdonly)
1178                 need_recover = true;
1179         if (test_and_clear_bit(NFS_O_WRONLY_STATE, &state->flags) && state->n_wronly)
1180                 need_recover = true;
1181         if (test_and_clear_bit(NFS_O_RDWR_STATE, &state->flags) && state->n_rdwr)
1182                 need_recover = true;
1183         if (need_recover)
1184                 nfs4_state_mark_reclaim_nograce(clp, state);
1185 }
1186
1187 static bool nfs_need_update_open_stateid(struct nfs4_state *state,
1188                 nfs4_stateid *stateid)
1189 {
1190         if (test_and_set_bit(NFS_OPEN_STATE, &state->flags) == 0)
1191                 return true;
1192         if (!nfs4_stateid_match_other(stateid, &state->open_stateid)) {
1193                 nfs_test_and_clear_all_open_stateid(state);
1194                 return true;
1195         }
1196         if (nfs4_stateid_is_newer(stateid, &state->open_stateid))
1197                 return true;
1198         return false;
1199 }
1200
1201 static void nfs_resync_open_stateid_locked(struct nfs4_state *state)
1202 {
1203         if (state->n_wronly)
1204                 set_bit(NFS_O_WRONLY_STATE, &state->flags);
1205         if (state->n_rdonly)
1206                 set_bit(NFS_O_RDONLY_STATE, &state->flags);
1207         if (state->n_rdwr)
1208                 set_bit(NFS_O_RDWR_STATE, &state->flags);
1209 }
1210
1211 static void nfs_clear_open_stateid_locked(struct nfs4_state *state,
1212                 nfs4_stateid *stateid, fmode_t fmode)
1213 {
1214         clear_bit(NFS_O_RDWR_STATE, &state->flags);
1215         switch (fmode & (FMODE_READ|FMODE_WRITE)) {
1216         case FMODE_WRITE:
1217                 clear_bit(NFS_O_RDONLY_STATE, &state->flags);
1218                 break;
1219         case FMODE_READ:
1220                 clear_bit(NFS_O_WRONLY_STATE, &state->flags);
1221                 break;
1222         case 0:
1223                 clear_bit(NFS_O_RDONLY_STATE, &state->flags);
1224                 clear_bit(NFS_O_WRONLY_STATE, &state->flags);
1225                 clear_bit(NFS_OPEN_STATE, &state->flags);
1226         }
1227         if (stateid == NULL)
1228                 return;
1229         /* Handle races with OPEN */
1230         if (!nfs4_stateid_match_other(stateid, &state->open_stateid) ||
1231             !nfs4_stateid_is_newer(stateid, &state->open_stateid)) {
1232                 nfs_resync_open_stateid_locked(state);
1233                 return;
1234         }
1235         if (test_bit(NFS_DELEGATED_STATE, &state->flags) == 0)
1236                 nfs4_stateid_copy(&state->stateid, stateid);
1237         nfs4_stateid_copy(&state->open_stateid, stateid);
1238 }
1239
1240 static void nfs_clear_open_stateid(struct nfs4_state *state, nfs4_stateid *stateid, fmode_t fmode)
1241 {
1242         write_seqlock(&state->seqlock);
1243         nfs_clear_open_stateid_locked(state, stateid, fmode);
1244         write_sequnlock(&state->seqlock);
1245         if (test_bit(NFS_STATE_RECLAIM_NOGRACE, &state->flags))
1246                 nfs4_schedule_state_manager(state->owner->so_server->nfs_client);
1247 }
1248
1249 static void nfs_set_open_stateid_locked(struct nfs4_state *state, nfs4_stateid *stateid, fmode_t fmode)
1250 {
1251         switch (fmode) {
1252                 case FMODE_READ:
1253                         set_bit(NFS_O_RDONLY_STATE, &state->flags);
1254                         break;
1255                 case FMODE_WRITE:
1256                         set_bit(NFS_O_WRONLY_STATE, &state->flags);
1257                         break;
1258                 case FMODE_READ|FMODE_WRITE:
1259                         set_bit(NFS_O_RDWR_STATE, &state->flags);
1260         }
1261         if (!nfs_need_update_open_stateid(state, stateid))
1262                 return;
1263         if (test_bit(NFS_DELEGATED_STATE, &state->flags) == 0)
1264                 nfs4_stateid_copy(&state->stateid, stateid);
1265         nfs4_stateid_copy(&state->open_stateid, stateid);
1266 }
1267
1268 static void __update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, const nfs4_stateid *deleg_stateid, fmode_t fmode)
1269 {
1270         /*
1271          * Protect the call to nfs4_state_set_mode_locked and
1272          * serialise the stateid update
1273          */
1274         write_seqlock(&state->seqlock);
1275         if (deleg_stateid != NULL) {
1276                 nfs4_stateid_copy(&state->stateid, deleg_stateid);
1277                 set_bit(NFS_DELEGATED_STATE, &state->flags);
1278         }
1279         if (open_stateid != NULL)
1280                 nfs_set_open_stateid_locked(state, open_stateid, fmode);
1281         write_sequnlock(&state->seqlock);
1282         spin_lock(&state->owner->so_lock);
1283         update_open_stateflags(state, fmode);
1284         spin_unlock(&state->owner->so_lock);
1285 }
1286
1287 static int update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, nfs4_stateid *delegation, fmode_t fmode)
1288 {
1289         struct nfs_inode *nfsi = NFS_I(state->inode);
1290         struct nfs_delegation *deleg_cur;
1291         int ret = 0;
1292
1293         fmode &= (FMODE_READ|FMODE_WRITE);
1294
1295         rcu_read_lock();
1296         deleg_cur = rcu_dereference(nfsi->delegation);
1297         if (deleg_cur == NULL)
1298                 goto no_delegation;
1299
1300         spin_lock(&deleg_cur->lock);
1301         if (rcu_dereference(nfsi->delegation) != deleg_cur ||
1302            test_bit(NFS_DELEGATION_RETURNING, &deleg_cur->flags) ||
1303             (deleg_cur->type & fmode) != fmode)
1304                 goto no_delegation_unlock;
1305
1306         if (delegation == NULL)
1307                 delegation = &deleg_cur->stateid;
1308         else if (!nfs4_stateid_match(&deleg_cur->stateid, delegation))
1309                 goto no_delegation_unlock;
1310
1311         nfs_mark_delegation_referenced(deleg_cur);
1312         __update_open_stateid(state, open_stateid, &deleg_cur->stateid, fmode);
1313         ret = 1;
1314 no_delegation_unlock:
1315         spin_unlock(&deleg_cur->lock);
1316 no_delegation:
1317         rcu_read_unlock();
1318
1319         if (!ret && open_stateid != NULL) {
1320                 __update_open_stateid(state, open_stateid, NULL, fmode);
1321                 ret = 1;
1322         }
1323         if (test_bit(NFS_STATE_RECLAIM_NOGRACE, &state->flags))
1324                 nfs4_schedule_state_manager(state->owner->so_server->nfs_client);
1325
1326         return ret;
1327 }
1328
1329 static bool nfs4_update_lock_stateid(struct nfs4_lock_state *lsp,
1330                 const nfs4_stateid *stateid)
1331 {
1332         struct nfs4_state *state = lsp->ls_state;
1333         bool ret = false;
1334
1335         spin_lock(&state->state_lock);
1336         if (!nfs4_stateid_match_other(stateid, &lsp->ls_stateid))
1337                 goto out_noupdate;
1338         if (!nfs4_stateid_is_newer(stateid, &lsp->ls_stateid))
1339                 goto out_noupdate;
1340         nfs4_stateid_copy(&lsp->ls_stateid, stateid);
1341         ret = true;
1342 out_noupdate:
1343         spin_unlock(&state->state_lock);
1344         return ret;
1345 }
1346
1347 static void nfs4_return_incompatible_delegation(struct inode *inode, fmode_t fmode)
1348 {
1349         struct nfs_delegation *delegation;
1350
1351         rcu_read_lock();
1352         delegation = rcu_dereference(NFS_I(inode)->delegation);
1353         if (delegation == NULL || (delegation->type & fmode) == fmode) {
1354                 rcu_read_unlock();
1355                 return;
1356         }
1357         rcu_read_unlock();
1358         nfs4_inode_return_delegation(inode);
1359 }
1360
1361 static struct nfs4_state *nfs4_try_open_cached(struct nfs4_opendata *opendata)
1362 {
1363         struct nfs4_state *state = opendata->state;
1364         struct nfs_inode *nfsi = NFS_I(state->inode);
1365         struct nfs_delegation *delegation;
1366         int open_mode = opendata->o_arg.open_flags;
1367         fmode_t fmode = opendata->o_arg.fmode;
1368         nfs4_stateid stateid;
1369         int ret = -EAGAIN;
1370
1371         for (;;) {
1372                 spin_lock(&state->owner->so_lock);
1373                 if (can_open_cached(state, fmode, open_mode)) {
1374                         update_open_stateflags(state, fmode);
1375                         spin_unlock(&state->owner->so_lock);
1376                         goto out_return_state;
1377                 }
1378                 spin_unlock(&state->owner->so_lock);
1379                 rcu_read_lock();
1380                 delegation = rcu_dereference(nfsi->delegation);
1381                 if (!can_open_delegated(delegation, fmode)) {
1382                         rcu_read_unlock();
1383                         break;
1384                 }
1385                 /* Save the delegation */
1386                 nfs4_stateid_copy(&stateid, &delegation->stateid);
1387                 rcu_read_unlock();
1388                 nfs_release_seqid(opendata->o_arg.seqid);
1389                 if (!opendata->is_recover) {
1390                         ret = nfs_may_open(state->inode, state->owner->so_cred, open_mode);
1391                         if (ret != 0)
1392                                 goto out;
1393                 }
1394                 ret = -EAGAIN;
1395
1396                 /* Try to update the stateid using the delegation */
1397                 if (update_open_stateid(state, NULL, &stateid, fmode))
1398                         goto out_return_state;
1399         }
1400 out:
1401         return ERR_PTR(ret);
1402 out_return_state:
1403         atomic_inc(&state->count);
1404         return state;
1405 }
1406
1407 static void
1408 nfs4_opendata_check_deleg(struct nfs4_opendata *data, struct nfs4_state *state)
1409 {
1410         struct nfs_client *clp = NFS_SERVER(state->inode)->nfs_client;
1411         struct nfs_delegation *delegation;
1412         int delegation_flags = 0;
1413
1414         rcu_read_lock();
1415         delegation = rcu_dereference(NFS_I(state->inode)->delegation);
1416         if (delegation)
1417                 delegation_flags = delegation->flags;
1418         rcu_read_unlock();
1419         if (data->o_arg.claim == NFS4_OPEN_CLAIM_DELEGATE_CUR) {
1420                 pr_err_ratelimited("NFS: Broken NFSv4 server %s is "
1421                                    "returning a delegation for "
1422                                    "OPEN(CLAIM_DELEGATE_CUR)\n",
1423                                    clp->cl_hostname);
1424         } else if ((delegation_flags & 1UL<<NFS_DELEGATION_NEED_RECLAIM) == 0)
1425                 nfs_inode_set_delegation(state->inode,
1426                                          data->owner->so_cred,
1427                                          &data->o_res);
1428         else
1429                 nfs_inode_reclaim_delegation(state->inode,
1430                                              data->owner->so_cred,
1431                                              &data->o_res);
1432 }
1433
1434 /*
1435  * Check the inode attributes against the CLAIM_PREVIOUS returned attributes
1436  * and update the nfs4_state.
1437  */
1438 static struct nfs4_state *
1439 _nfs4_opendata_reclaim_to_nfs4_state(struct nfs4_opendata *data)
1440 {
1441         struct inode *inode = data->state->inode;
1442         struct nfs4_state *state = data->state;
1443         int ret;
1444
1445         if (!data->rpc_done) {
1446                 if (data->rpc_status) {
1447                         ret = data->rpc_status;
1448                         goto err;
1449                 }
1450                 /* cached opens have already been processed */
1451                 goto update;
1452         }
1453
1454         ret = nfs_refresh_inode(inode, &data->f_attr);
1455         if (ret)
1456                 goto err;
1457
1458         if (data->o_res.delegation_type != 0)
1459                 nfs4_opendata_check_deleg(data, state);
1460 update:
1461         update_open_stateid(state, &data->o_res.stateid, NULL,
1462                             data->o_arg.fmode);
1463         atomic_inc(&state->count);
1464
1465         return state;
1466 err:
1467         return ERR_PTR(ret);
1468
1469 }
1470
1471 static struct nfs4_state *
1472 _nfs4_opendata_to_nfs4_state(struct nfs4_opendata *data)
1473 {
1474         struct inode *inode;
1475         struct nfs4_state *state = NULL;
1476         int ret;
1477
1478         if (!data->rpc_done) {
1479                 state = nfs4_try_open_cached(data);
1480                 goto out;
1481         }
1482
1483         ret = -EAGAIN;
1484         if (!(data->f_attr.valid & NFS_ATTR_FATTR))
1485                 goto err;
1486         inode = nfs_fhget(data->dir->d_sb, &data->o_res.fh, &data->f_attr, data->f_label);
1487         ret = PTR_ERR(inode);
1488         if (IS_ERR(inode))
1489                 goto err;
1490         ret = -ENOMEM;
1491         state = nfs4_get_open_state(inode, data->owner);
1492         if (state == NULL)
1493                 goto err_put_inode;
1494         if (data->o_res.delegation_type != 0)
1495                 nfs4_opendata_check_deleg(data, state);
1496         update_open_stateid(state, &data->o_res.stateid, NULL,
1497                         data->o_arg.fmode);
1498         iput(inode);
1499 out:
1500         nfs_release_seqid(data->o_arg.seqid);
1501         return state;
1502 err_put_inode:
1503         iput(inode);
1504 err:
1505         return ERR_PTR(ret);
1506 }
1507
1508 static struct nfs4_state *
1509 nfs4_opendata_to_nfs4_state(struct nfs4_opendata *data)
1510 {
1511         if (data->o_arg.claim == NFS4_OPEN_CLAIM_PREVIOUS)
1512                 return _nfs4_opendata_reclaim_to_nfs4_state(data);
1513         return _nfs4_opendata_to_nfs4_state(data);
1514 }
1515
1516 static struct nfs_open_context *nfs4_state_find_open_context(struct nfs4_state *state)
1517 {
1518         struct nfs_inode *nfsi = NFS_I(state->inode);
1519         struct nfs_open_context *ctx;
1520
1521         spin_lock(&state->inode->i_lock);
1522         list_for_each_entry(ctx, &nfsi->open_files, list) {
1523                 if (ctx->state != state)
1524                         continue;
1525                 get_nfs_open_context(ctx);
1526                 spin_unlock(&state->inode->i_lock);
1527                 return ctx;
1528         }
1529         spin_unlock(&state->inode->i_lock);
1530         return ERR_PTR(-ENOENT);
1531 }
1532
1533 static struct nfs4_opendata *nfs4_open_recoverdata_alloc(struct nfs_open_context *ctx,
1534                 struct nfs4_state *state, enum open_claim_type4 claim)
1535 {
1536         struct nfs4_opendata *opendata;
1537
1538         opendata = nfs4_opendata_alloc(ctx->dentry, state->owner, 0, 0,
1539                         NULL, NULL, claim, GFP_NOFS);
1540         if (opendata == NULL)
1541                 return ERR_PTR(-ENOMEM);
1542         opendata->state = state;
1543         atomic_inc(&state->count);
1544         return opendata;
1545 }
1546
1547 static int nfs4_open_recover_helper(struct nfs4_opendata *opendata, fmode_t fmode, struct nfs4_state **res)
1548 {
1549         struct nfs4_state *newstate;
1550         int ret;
1551
1552         if ((opendata->o_arg.claim == NFS4_OPEN_CLAIM_DELEGATE_CUR ||
1553              opendata->o_arg.claim == NFS4_OPEN_CLAIM_DELEG_CUR_FH) &&
1554             (opendata->o_arg.u.delegation_type & fmode) != fmode)
1555                 /* This mode can't have been delegated, so we must have
1556                  * a valid open_stateid to cover it - not need to reclaim.
1557                  */
1558                 return 0;
1559         opendata->o_arg.open_flags = 0;
1560         opendata->o_arg.fmode = fmode;
1561         opendata->o_arg.share_access = nfs4_map_atomic_open_share(
1562                         NFS_SB(opendata->dentry->d_sb),
1563                         fmode, 0);
1564         memset(&opendata->o_res, 0, sizeof(opendata->o_res));
1565         memset(&opendata->c_res, 0, sizeof(opendata->c_res));
1566         nfs4_init_opendata_res(opendata);
1567         ret = _nfs4_recover_proc_open(opendata);
1568         if (ret != 0)
1569                 return ret; 
1570         newstate = nfs4_opendata_to_nfs4_state(opendata);
1571         if (IS_ERR(newstate))
1572                 return PTR_ERR(newstate);
1573         nfs4_close_state(newstate, fmode);
1574         *res = newstate;
1575         return 0;
1576 }
1577
1578 static int nfs4_open_recover(struct nfs4_opendata *opendata, struct nfs4_state *state)
1579 {
1580         struct nfs4_state *newstate;
1581         int ret;
1582
1583         /* Don't trigger recovery in nfs_test_and_clear_all_open_stateid */
1584         clear_bit(NFS_O_RDWR_STATE, &state->flags);
1585         clear_bit(NFS_O_WRONLY_STATE, &state->flags);
1586         clear_bit(NFS_O_RDONLY_STATE, &state->flags);
1587         /* memory barrier prior to reading state->n_* */
1588         clear_bit(NFS_DELEGATED_STATE, &state->flags);
1589         clear_bit(NFS_OPEN_STATE, &state->flags);
1590         smp_rmb();
1591         if (state->n_rdwr != 0) {
1592                 ret = nfs4_open_recover_helper(opendata, FMODE_READ|FMODE_WRITE, &newstate);
1593                 if (ret != 0)
1594                         return ret;
1595                 if (newstate != state)
1596                         return -ESTALE;
1597         }
1598         if (state->n_wronly != 0) {
1599                 ret = nfs4_open_recover_helper(opendata, FMODE_WRITE, &newstate);
1600                 if (ret != 0)
1601                         return ret;
1602                 if (newstate != state)
1603                         return -ESTALE;
1604         }
1605         if (state->n_rdonly != 0) {
1606                 ret = nfs4_open_recover_helper(opendata, FMODE_READ, &newstate);
1607                 if (ret != 0)
1608                         return ret;
1609                 if (newstate != state)
1610                         return -ESTALE;
1611         }
1612         /*
1613          * We may have performed cached opens for all three recoveries.
1614          * Check if we need to update the current stateid.
1615          */
1616         if (test_bit(NFS_DELEGATED_STATE, &state->flags) == 0 &&
1617             !nfs4_stateid_match(&state->stateid, &state->open_stateid)) {
1618                 write_seqlock(&state->seqlock);
1619                 if (test_bit(NFS_DELEGATED_STATE, &state->flags) == 0)
1620                         nfs4_stateid_copy(&state->stateid, &state->open_stateid);
1621                 write_sequnlock(&state->seqlock);
1622         }
1623         return 0;
1624 }
1625
1626 /*
1627  * OPEN_RECLAIM:
1628  *      reclaim state on the server after a reboot.
1629  */
1630 static int _nfs4_do_open_reclaim(struct nfs_open_context *ctx, struct nfs4_state *state)
1631 {
1632         struct nfs_delegation *delegation;
1633         struct nfs4_opendata *opendata;
1634         fmode_t delegation_type = 0;
1635         int status;
1636
1637         opendata = nfs4_open_recoverdata_alloc(ctx, state,
1638                         NFS4_OPEN_CLAIM_PREVIOUS);
1639         if (IS_ERR(opendata))
1640                 return PTR_ERR(opendata);
1641         rcu_read_lock();
1642         delegation = rcu_dereference(NFS_I(state->inode)->delegation);
1643         if (delegation != NULL && test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags) != 0)
1644                 delegation_type = delegation->type;
1645         rcu_read_unlock();
1646         opendata->o_arg.u.delegation_type = delegation_type;
1647         status = nfs4_open_recover(opendata, state);
1648         nfs4_opendata_put(opendata);
1649         return status;
1650 }
1651
1652 static int nfs4_do_open_reclaim(struct nfs_open_context *ctx, struct nfs4_state *state)
1653 {
1654         struct nfs_server *server = NFS_SERVER(state->inode);
1655         struct nfs4_exception exception = { };
1656         int err;
1657         do {
1658                 err = _nfs4_do_open_reclaim(ctx, state);
1659                 trace_nfs4_open_reclaim(ctx, 0, err);
1660                 if (nfs4_clear_cap_atomic_open_v1(server, err, &exception))
1661                         continue;
1662                 if (err != -NFS4ERR_DELAY)
1663                         break;
1664                 nfs4_handle_exception(server, err, &exception);
1665         } while (exception.retry);
1666         return err;
1667 }
1668
1669 static int nfs4_open_reclaim(struct nfs4_state_owner *sp, struct nfs4_state *state)
1670 {
1671         struct nfs_open_context *ctx;
1672         int ret;
1673
1674         ctx = nfs4_state_find_open_context(state);
1675         if (IS_ERR(ctx))
1676                 return -EAGAIN;
1677         ret = nfs4_do_open_reclaim(ctx, state);
1678         put_nfs_open_context(ctx);
1679         return ret;
1680 }
1681
1682 static int nfs4_handle_delegation_recall_error(struct nfs_server *server, struct nfs4_state *state, const nfs4_stateid *stateid, int err)
1683 {
1684         switch (err) {
1685                 default:
1686                         printk(KERN_ERR "NFS: %s: unhandled error "
1687                                         "%d.\n", __func__, err);
1688                 case 0:
1689                 case -ENOENT:
1690                 case -EAGAIN:
1691                 case -ESTALE:
1692                         break;
1693                 case -NFS4ERR_BADSESSION:
1694                 case -NFS4ERR_BADSLOT:
1695                 case -NFS4ERR_BAD_HIGH_SLOT:
1696                 case -NFS4ERR_CONN_NOT_BOUND_TO_SESSION:
1697                 case -NFS4ERR_DEADSESSION:
1698                         set_bit(NFS_DELEGATED_STATE, &state->flags);
1699                         nfs4_schedule_session_recovery(server->nfs_client->cl_session, err);
1700                         return -EAGAIN;
1701                 case -NFS4ERR_STALE_CLIENTID:
1702                 case -NFS4ERR_STALE_STATEID:
1703                         set_bit(NFS_DELEGATED_STATE, &state->flags);
1704                 case -NFS4ERR_EXPIRED:
1705                         /* Don't recall a delegation if it was lost */
1706                         nfs4_schedule_lease_recovery(server->nfs_client);
1707                         return -EAGAIN;
1708                 case -NFS4ERR_MOVED:
1709                         nfs4_schedule_migration_recovery(server);
1710                         return -EAGAIN;
1711                 case -NFS4ERR_LEASE_MOVED:
1712                         nfs4_schedule_lease_moved_recovery(server->nfs_client);
1713                         return -EAGAIN;
1714                 case -NFS4ERR_DELEG_REVOKED:
1715                 case -NFS4ERR_ADMIN_REVOKED:
1716                 case -NFS4ERR_BAD_STATEID:
1717                 case -NFS4ERR_OPENMODE:
1718                         nfs_inode_find_state_and_recover(state->inode,
1719                                         stateid);
1720                         nfs4_schedule_stateid_recovery(server, state);
1721                         return -EAGAIN;
1722                 case -NFS4ERR_DELAY:
1723                 case -NFS4ERR_GRACE:
1724                         set_bit(NFS_DELEGATED_STATE, &state->flags);
1725                         ssleep(1);
1726                         return -EAGAIN;
1727                 case -ENOMEM:
1728                 case -NFS4ERR_DENIED:
1729                         /* kill_proc(fl->fl_pid, SIGLOST, 1); */
1730                         return 0;
1731         }
1732         return err;
1733 }
1734
1735 int nfs4_open_delegation_recall(struct nfs_open_context *ctx, struct nfs4_state *state, const nfs4_stateid *stateid)
1736 {
1737         struct nfs_server *server = NFS_SERVER(state->inode);
1738         struct nfs4_opendata *opendata;
1739         int err;
1740
1741         opendata = nfs4_open_recoverdata_alloc(ctx, state,
1742                         NFS4_OPEN_CLAIM_DELEG_CUR_FH);
1743         if (IS_ERR(opendata))
1744                 return PTR_ERR(opendata);
1745         nfs4_stateid_copy(&opendata->o_arg.u.delegation, stateid);
1746         err = nfs4_open_recover(opendata, state);
1747         nfs4_opendata_put(opendata);
1748         return nfs4_handle_delegation_recall_error(server, state, stateid, err);
1749 }
1750
1751 static void nfs4_open_confirm_prepare(struct rpc_task *task, void *calldata)
1752 {
1753         struct nfs4_opendata *data = calldata;
1754
1755         nfs40_setup_sequence(data->o_arg.server->nfs_client->cl_slot_tbl,
1756                              &data->c_arg.seq_args, &data->c_res.seq_res, task);
1757 }
1758
1759 static void nfs4_open_confirm_done(struct rpc_task *task, void *calldata)
1760 {
1761         struct nfs4_opendata *data = calldata;
1762
1763         nfs40_sequence_done(task, &data->c_res.seq_res);
1764
1765         data->rpc_status = task->tk_status;
1766         if (data->rpc_status == 0) {
1767                 nfs4_stateid_copy(&data->o_res.stateid, &data->c_res.stateid);
1768                 nfs_confirm_seqid(&data->owner->so_seqid, 0);
1769                 renew_lease(data->o_res.server, data->timestamp);
1770                 data->rpc_done = 1;
1771         }
1772 }
1773
1774 static void nfs4_open_confirm_release(void *calldata)
1775 {
1776         struct nfs4_opendata *data = calldata;
1777         struct nfs4_state *state = NULL;
1778
1779         /* If this request hasn't been cancelled, do nothing */
1780         if (data->cancelled == 0)
1781                 goto out_free;
1782         /* In case of error, no cleanup! */
1783         if (!data->rpc_done)
1784                 goto out_free;
1785         state = nfs4_opendata_to_nfs4_state(data);
1786         if (!IS_ERR(state))
1787                 nfs4_close_state(state, data->o_arg.fmode);
1788 out_free:
1789         nfs4_opendata_put(data);
1790 }
1791
1792 static const struct rpc_call_ops nfs4_open_confirm_ops = {
1793         .rpc_call_prepare = nfs4_open_confirm_prepare,
1794         .rpc_call_done = nfs4_open_confirm_done,
1795         .rpc_release = nfs4_open_confirm_release,
1796 };
1797
1798 /*
1799  * Note: On error, nfs4_proc_open_confirm will free the struct nfs4_opendata
1800  */
1801 static int _nfs4_proc_open_confirm(struct nfs4_opendata *data)
1802 {
1803         struct nfs_server *server = NFS_SERVER(d_inode(data->dir));
1804         struct rpc_task *task;
1805         struct  rpc_message msg = {
1806                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_CONFIRM],
1807                 .rpc_argp = &data->c_arg,
1808                 .rpc_resp = &data->c_res,
1809                 .rpc_cred = data->owner->so_cred,
1810         };
1811         struct rpc_task_setup task_setup_data = {
1812                 .rpc_client = server->client,
1813                 .rpc_message = &msg,
1814                 .callback_ops = &nfs4_open_confirm_ops,
1815                 .callback_data = data,
1816                 .workqueue = nfsiod_workqueue,
1817                 .flags = RPC_TASK_ASYNC,
1818         };
1819         int status;
1820
1821         nfs4_init_sequence(&data->c_arg.seq_args, &data->c_res.seq_res, 1);
1822         kref_get(&data->kref);
1823         data->rpc_done = 0;
1824         data->rpc_status = 0;
1825         data->timestamp = jiffies;
1826         task = rpc_run_task(&task_setup_data);
1827         if (IS_ERR(task))
1828                 return PTR_ERR(task);
1829         status = nfs4_wait_for_completion_rpc_task(task);
1830         if (status != 0) {
1831                 data->cancelled = 1;
1832                 smp_wmb();
1833         } else
1834                 status = data->rpc_status;
1835         rpc_put_task(task);
1836         return status;
1837 }
1838
1839 static void nfs4_open_prepare(struct rpc_task *task, void *calldata)
1840 {
1841         struct nfs4_opendata *data = calldata;
1842         struct nfs4_state_owner *sp = data->owner;
1843         struct nfs_client *clp = sp->so_server->nfs_client;
1844
1845         if (nfs_wait_on_sequence(data->o_arg.seqid, task) != 0)
1846                 goto out_wait;
1847         /*
1848          * Check if we still need to send an OPEN call, or if we can use
1849          * a delegation instead.
1850          */
1851         if (data->state != NULL) {
1852                 struct nfs_delegation *delegation;
1853
1854                 if (can_open_cached(data->state, data->o_arg.fmode, data->o_arg.open_flags))
1855                         goto out_no_action;
1856                 rcu_read_lock();
1857                 delegation = rcu_dereference(NFS_I(data->state->inode)->delegation);
1858                 if (data->o_arg.claim != NFS4_OPEN_CLAIM_DELEGATE_CUR &&
1859                     data->o_arg.claim != NFS4_OPEN_CLAIM_DELEG_CUR_FH &&
1860                     can_open_delegated(delegation, data->o_arg.fmode))
1861                         goto unlock_no_action;
1862                 rcu_read_unlock();
1863         }
1864         /* Update client id. */
1865         data->o_arg.clientid = clp->cl_clientid;
1866         switch (data->o_arg.claim) {
1867         case NFS4_OPEN_CLAIM_PREVIOUS:
1868         case NFS4_OPEN_CLAIM_DELEG_CUR_FH:
1869         case NFS4_OPEN_CLAIM_DELEG_PREV_FH:
1870                 data->o_arg.open_bitmap = &nfs4_open_noattr_bitmap[0];
1871         case NFS4_OPEN_CLAIM_FH:
1872                 task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_NOATTR];
1873                 nfs_copy_fh(&data->o_res.fh, data->o_arg.fh);
1874         }
1875         data->timestamp = jiffies;
1876         if (nfs4_setup_sequence(data->o_arg.server,
1877                                 &data->o_arg.seq_args,
1878                                 &data->o_res.seq_res,
1879                                 task) != 0)
1880                 nfs_release_seqid(data->o_arg.seqid);
1881
1882         /* Set the create mode (note dependency on the session type) */
1883         data->o_arg.createmode = NFS4_CREATE_UNCHECKED;
1884         if (data->o_arg.open_flags & O_EXCL) {
1885                 data->o_arg.createmode = NFS4_CREATE_EXCLUSIVE;
1886                 if (nfs4_has_persistent_session(clp))
1887                         data->o_arg.createmode = NFS4_CREATE_GUARDED;
1888                 else if (clp->cl_mvops->minor_version > 0)
1889                         data->o_arg.createmode = NFS4_CREATE_EXCLUSIVE4_1;
1890         }
1891         return;
1892 unlock_no_action:
1893         rcu_read_unlock();
1894 out_no_action:
1895         task->tk_action = NULL;
1896 out_wait:
1897         nfs4_sequence_done(task, &data->o_res.seq_res);
1898 }
1899
1900 static void nfs4_open_done(struct rpc_task *task, void *calldata)
1901 {
1902         struct nfs4_opendata *data = calldata;
1903
1904         data->rpc_status = task->tk_status;
1905
1906         if (!nfs4_sequence_done(task, &data->o_res.seq_res))
1907                 return;
1908
1909         if (task->tk_status == 0) {
1910                 if (data->o_res.f_attr->valid & NFS_ATTR_FATTR_TYPE) {
1911                         switch (data->o_res.f_attr->mode & S_IFMT) {
1912                         case S_IFREG:
1913                                 break;
1914                         case S_IFLNK:
1915                                 data->rpc_status = -ELOOP;
1916                                 break;
1917                         case S_IFDIR:
1918                                 data->rpc_status = -EISDIR;
1919                                 break;
1920                         default:
1921                                 data->rpc_status = -ENOTDIR;
1922                         }
1923                 }
1924                 renew_lease(data->o_res.server, data->timestamp);
1925                 if (!(data->o_res.rflags & NFS4_OPEN_RESULT_CONFIRM))
1926                         nfs_confirm_seqid(&data->owner->so_seqid, 0);
1927         }
1928         data->rpc_done = 1;
1929 }
1930
1931 static void nfs4_open_release(void *calldata)
1932 {
1933         struct nfs4_opendata *data = calldata;
1934         struct nfs4_state *state = NULL;
1935
1936         /* If this request hasn't been cancelled, do nothing */
1937         if (data->cancelled == 0)
1938                 goto out_free;
1939         /* In case of error, no cleanup! */
1940         if (data->rpc_status != 0 || !data->rpc_done)
1941                 goto out_free;
1942         /* In case we need an open_confirm, no cleanup! */
1943         if (data->o_res.rflags & NFS4_OPEN_RESULT_CONFIRM)
1944                 goto out_free;
1945         state = nfs4_opendata_to_nfs4_state(data);
1946         if (!IS_ERR(state))
1947                 nfs4_close_state(state, data->o_arg.fmode);
1948 out_free:
1949         nfs4_opendata_put(data);
1950 }
1951
1952 static const struct rpc_call_ops nfs4_open_ops = {
1953         .rpc_call_prepare = nfs4_open_prepare,
1954         .rpc_call_done = nfs4_open_done,
1955         .rpc_release = nfs4_open_release,
1956 };
1957
1958 static int nfs4_run_open_task(struct nfs4_opendata *data, int isrecover)
1959 {
1960         struct inode *dir = d_inode(data->dir);
1961         struct nfs_server *server = NFS_SERVER(dir);
1962         struct nfs_openargs *o_arg = &data->o_arg;
1963         struct nfs_openres *o_res = &data->o_res;
1964         struct rpc_task *task;
1965         struct rpc_message msg = {
1966                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN],
1967                 .rpc_argp = o_arg,
1968                 .rpc_resp = o_res,
1969                 .rpc_cred = data->owner->so_cred,
1970         };
1971         struct rpc_task_setup task_setup_data = {
1972                 .rpc_client = server->client,
1973                 .rpc_message = &msg,
1974                 .callback_ops = &nfs4_open_ops,
1975                 .callback_data = data,
1976                 .workqueue = nfsiod_workqueue,
1977                 .flags = RPC_TASK_ASYNC,
1978         };
1979         int status;
1980
1981         nfs4_init_sequence(&o_arg->seq_args, &o_res->seq_res, 1);
1982         kref_get(&data->kref);
1983         data->rpc_done = 0;
1984         data->rpc_status = 0;
1985         data->cancelled = 0;
1986         data->is_recover = 0;
1987         if (isrecover) {
1988                 nfs4_set_sequence_privileged(&o_arg->seq_args);
1989                 data->is_recover = 1;
1990         }
1991         task = rpc_run_task(&task_setup_data);
1992         if (IS_ERR(task))
1993                 return PTR_ERR(task);
1994         status = nfs4_wait_for_completion_rpc_task(task);
1995         if (status != 0) {
1996                 data->cancelled = 1;
1997                 smp_wmb();
1998         } else
1999                 status = data->rpc_status;
2000         rpc_put_task(task);
2001
2002         return status;
2003 }
2004
2005 static int _nfs4_recover_proc_open(struct nfs4_opendata *data)
2006 {
2007         struct inode *dir = d_inode(data->dir);
2008         struct nfs_openres *o_res = &data->o_res;
2009         int status;
2010
2011         status = nfs4_run_open_task(data, 1);
2012         if (status != 0 || !data->rpc_done)
2013                 return status;
2014
2015         nfs_fattr_map_and_free_names(NFS_SERVER(dir), &data->f_attr);
2016
2017         if (o_res->rflags & NFS4_OPEN_RESULT_CONFIRM) {
2018                 status = _nfs4_proc_open_confirm(data);
2019                 if (status != 0)
2020                         return status;
2021         }
2022
2023         return status;
2024 }
2025
2026 /*
2027  * Additional permission checks in order to distinguish between an
2028  * open for read, and an open for execute. This works around the
2029  * fact that NFSv4 OPEN treats read and execute permissions as being
2030  * the same.
2031  * Note that in the non-execute case, we want to turn off permission
2032  * checking if we just created a new file (POSIX open() semantics).
2033  */
2034 static int nfs4_opendata_access(struct rpc_cred *cred,
2035                                 struct nfs4_opendata *opendata,
2036                                 struct nfs4_state *state, fmode_t fmode,
2037                                 int openflags)
2038 {
2039         struct nfs_access_entry cache;
2040         u32 mask;
2041
2042         /* access call failed or for some reason the server doesn't
2043          * support any access modes -- defer access call until later */
2044         if (opendata->o_res.access_supported == 0)
2045                 return 0;
2046
2047         mask = 0;
2048         /*
2049          * Use openflags to check for exec, because fmode won't
2050          * always have FMODE_EXEC set when file open for exec.
2051          */
2052         if (openflags & __FMODE_EXEC) {
2053                 /* ONLY check for exec rights */
2054                 mask = MAY_EXEC;
2055         } else if ((fmode & FMODE_READ) && !opendata->file_created)
2056                 mask = MAY_READ;
2057
2058         cache.cred = cred;
2059         cache.jiffies = jiffies;
2060         nfs_access_set_mask(&cache, opendata->o_res.access_result);
2061         nfs_access_add_cache(state->inode, &cache);
2062
2063         if ((mask & ~cache.mask & (MAY_READ | MAY_EXEC)) == 0)
2064                 return 0;
2065
2066         /* even though OPEN succeeded, access is denied. Close the file */
2067         nfs4_close_state(state, fmode);
2068         return -EACCES;
2069 }
2070
2071 /*
2072  * Note: On error, nfs4_proc_open will free the struct nfs4_opendata
2073  */
2074 static int _nfs4_proc_open(struct nfs4_opendata *data)
2075 {
2076         struct inode *dir = d_inode(data->dir);
2077         struct nfs_server *server = NFS_SERVER(dir);
2078         struct nfs_openargs *o_arg = &data->o_arg;
2079         struct nfs_openres *o_res = &data->o_res;
2080         int status;
2081
2082         status = nfs4_run_open_task(data, 0);
2083         if (!data->rpc_done)
2084                 return status;
2085         if (status != 0) {
2086                 if (status == -NFS4ERR_BADNAME &&
2087                                 !(o_arg->open_flags & O_CREAT))
2088                         return -ENOENT;
2089                 return status;
2090         }
2091
2092         nfs_fattr_map_and_free_names(server, &data->f_attr);
2093
2094         if (o_arg->open_flags & O_CREAT) {
2095                 update_changeattr(dir, &o_res->cinfo);
2096                 if (o_arg->open_flags & O_EXCL)
2097                         data->file_created = 1;
2098                 else if (o_res->cinfo.before != o_res->cinfo.after)
2099                         data->file_created = 1;
2100         }
2101         if ((o_res->rflags & NFS4_OPEN_RESULT_LOCKTYPE_POSIX) == 0)
2102                 server->caps &= ~NFS_CAP_POSIX_LOCK;
2103         if(o_res->rflags & NFS4_OPEN_RESULT_CONFIRM) {
2104                 status = _nfs4_proc_open_confirm(data);
2105                 if (status != 0)
2106                         return status;
2107         }
2108         if (!(o_res->f_attr->valid & NFS_ATTR_FATTR))
2109                 nfs4_proc_getattr(server, &o_res->fh, o_res->f_attr, o_res->f_label);
2110         return 0;
2111 }
2112
2113 static int nfs4_recover_expired_lease(struct nfs_server *server)
2114 {
2115         return nfs4_client_recover_expired_lease(server->nfs_client);
2116 }
2117
2118 /*
2119  * OPEN_EXPIRED:
2120  *      reclaim state on the server after a network partition.
2121  *      Assumes caller holds the appropriate lock
2122  */
2123 static int _nfs4_open_expired(struct nfs_open_context *ctx, struct nfs4_state *state)
2124 {
2125         struct nfs4_opendata *opendata;
2126         int ret;
2127
2128         opendata = nfs4_open_recoverdata_alloc(ctx, state,
2129                         NFS4_OPEN_CLAIM_FH);
2130         if (IS_ERR(opendata))
2131                 return PTR_ERR(opendata);
2132         ret = nfs4_open_recover(opendata, state);
2133         if (ret == -ESTALE)
2134                 d_drop(ctx->dentry);
2135         nfs4_opendata_put(opendata);
2136         return ret;
2137 }
2138
2139 static int nfs4_do_open_expired(struct nfs_open_context *ctx, struct nfs4_state *state)
2140 {
2141         struct nfs_server *server = NFS_SERVER(state->inode);
2142         struct nfs4_exception exception = { };
2143         int err;
2144
2145         do {
2146                 err = _nfs4_open_expired(ctx, state);
2147                 trace_nfs4_open_expired(ctx, 0, err);
2148                 if (nfs4_clear_cap_atomic_open_v1(server, err, &exception))
2149                         continue;
2150                 switch (err) {
2151                 default:
2152                         goto out;
2153                 case -NFS4ERR_GRACE:
2154                 case -NFS4ERR_DELAY:
2155                         nfs4_handle_exception(server, err, &exception);
2156                         err = 0;
2157                 }
2158         } while (exception.retry);
2159 out:
2160         return err;
2161 }
2162
2163 static int nfs4_open_expired(struct nfs4_state_owner *sp, struct nfs4_state *state)
2164 {
2165         struct nfs_open_context *ctx;
2166         int ret;
2167
2168         ctx = nfs4_state_find_open_context(state);
2169         if (IS_ERR(ctx))
2170                 return -EAGAIN;
2171         ret = nfs4_do_open_expired(ctx, state);
2172         put_nfs_open_context(ctx);
2173         return ret;
2174 }
2175
2176 static void nfs_finish_clear_delegation_stateid(struct nfs4_state *state)
2177 {
2178         nfs_remove_bad_delegation(state->inode);
2179         write_seqlock(&state->seqlock);
2180         nfs4_stateid_copy(&state->stateid, &state->open_stateid);
2181         write_sequnlock(&state->seqlock);
2182         clear_bit(NFS_DELEGATED_STATE, &state->flags);
2183 }
2184
2185 static void nfs40_clear_delegation_stateid(struct nfs4_state *state)
2186 {
2187         if (rcu_access_pointer(NFS_I(state->inode)->delegation) != NULL)
2188                 nfs_finish_clear_delegation_stateid(state);
2189 }
2190
2191 static int nfs40_open_expired(struct nfs4_state_owner *sp, struct nfs4_state *state)
2192 {
2193         /* NFSv4.0 doesn't allow for delegation recovery on open expire */
2194         nfs40_clear_delegation_stateid(state);
2195         return nfs4_open_expired(sp, state);
2196 }
2197
2198 #if defined(CONFIG_NFS_V4_1)
2199 static void nfs41_check_delegation_stateid(struct nfs4_state *state)
2200 {
2201         struct nfs_server *server = NFS_SERVER(state->inode);
2202         nfs4_stateid stateid;
2203         struct nfs_delegation *delegation;
2204         struct rpc_cred *cred;
2205         int status;
2206
2207         /* Get the delegation credential for use by test/free_stateid */
2208         rcu_read_lock();
2209         delegation = rcu_dereference(NFS_I(state->inode)->delegation);
2210         if (delegation == NULL) {
2211                 rcu_read_unlock();
2212                 return;
2213         }
2214
2215         nfs4_stateid_copy(&stateid, &delegation->stateid);
2216         cred = get_rpccred(delegation->cred);
2217         rcu_read_unlock();
2218         status = nfs41_test_stateid(server, &stateid, cred);
2219         trace_nfs4_test_delegation_stateid(state, NULL, status);
2220
2221         if (status != NFS_OK) {
2222                 /* Free the stateid unless the server explicitly
2223                  * informs us the stateid is unrecognized. */
2224                 if (status != -NFS4ERR_BAD_STATEID)
2225                         nfs41_free_stateid(server, &stateid, cred);
2226                 nfs_finish_clear_delegation_stateid(state);
2227         }
2228
2229         put_rpccred(cred);
2230 }
2231
2232 /**
2233  * nfs41_check_open_stateid - possibly free an open stateid
2234  *
2235  * @state: NFSv4 state for an inode
2236  *
2237  * Returns NFS_OK if recovery for this stateid is now finished.
2238  * Otherwise a negative NFS4ERR value is returned.
2239  */
2240 static int nfs41_check_open_stateid(struct nfs4_state *state)
2241 {
2242         struct nfs_server *server = NFS_SERVER(state->inode);
2243         nfs4_stateid *stateid = &state->open_stateid;
2244         struct rpc_cred *cred = state->owner->so_cred;
2245         int status;
2246
2247         /* If a state reset has been done, test_stateid is unneeded */
2248         if ((test_bit(NFS_O_RDONLY_STATE, &state->flags) == 0) &&
2249             (test_bit(NFS_O_WRONLY_STATE, &state->flags) == 0) &&
2250             (test_bit(NFS_O_RDWR_STATE, &state->flags) == 0))
2251                 return -NFS4ERR_BAD_STATEID;
2252
2253         status = nfs41_test_stateid(server, stateid, cred);
2254         trace_nfs4_test_open_stateid(state, NULL, status);
2255         if (status != NFS_OK) {
2256                 /* Free the stateid unless the server explicitly
2257                  * informs us the stateid is unrecognized. */
2258                 if (status != -NFS4ERR_BAD_STATEID)
2259                         nfs41_free_stateid(server, stateid, cred);
2260
2261                 clear_bit(NFS_O_RDONLY_STATE, &state->flags);
2262                 clear_bit(NFS_O_WRONLY_STATE, &state->flags);
2263                 clear_bit(NFS_O_RDWR_STATE, &state->flags);
2264                 clear_bit(NFS_OPEN_STATE, &state->flags);
2265         }
2266         return status;
2267 }
2268
2269 static int nfs41_open_expired(struct nfs4_state_owner *sp, struct nfs4_state *state)
2270 {
2271         int status;
2272
2273         nfs41_check_delegation_stateid(state);
2274         status = nfs41_check_open_stateid(state);
2275         if (status != NFS_OK)
2276                 status = nfs4_open_expired(sp, state);
2277         return status;
2278 }
2279 #endif
2280
2281 /*
2282  * on an EXCLUSIVE create, the server should send back a bitmask with FATTR4-*
2283  * fields corresponding to attributes that were used to store the verifier.
2284  * Make sure we clobber those fields in the later setattr call
2285  */
2286 static inline void nfs4_exclusive_attrset(struct nfs4_opendata *opendata, struct iattr *sattr)
2287 {
2288         if ((opendata->o_res.attrset[1] & FATTR4_WORD1_TIME_ACCESS) &&
2289             !(sattr->ia_valid & ATTR_ATIME_SET))
2290                 sattr->ia_valid |= ATTR_ATIME;
2291
2292         if ((opendata->o_res.attrset[1] & FATTR4_WORD1_TIME_MODIFY) &&
2293             !(sattr->ia_valid & ATTR_MTIME_SET))
2294                 sattr->ia_valid |= ATTR_MTIME;
2295 }
2296
2297 static int _nfs4_open_and_get_state(struct nfs4_opendata *opendata,
2298                 fmode_t fmode,
2299                 int flags,
2300                 struct nfs_open_context *ctx)
2301 {
2302         struct nfs4_state_owner *sp = opendata->owner;
2303         struct nfs_server *server = sp->so_server;
2304         struct dentry *dentry;
2305         struct nfs4_state *state;
2306         unsigned int seq;
2307         int ret;
2308
2309         seq = raw_seqcount_begin(&sp->so_reclaim_seqcount);
2310
2311         ret = _nfs4_proc_open(opendata);
2312         if (ret != 0)
2313                 goto out;
2314
2315         state = nfs4_opendata_to_nfs4_state(opendata);
2316         ret = PTR_ERR(state);
2317         if (IS_ERR(state))
2318                 goto out;
2319         if (server->caps & NFS_CAP_POSIX_LOCK)
2320                 set_bit(NFS_STATE_POSIX_LOCKS, &state->flags);
2321
2322         dentry = opendata->dentry;
2323         if (d_really_is_negative(dentry)) {
2324                 /* FIXME: Is this d_drop() ever needed? */
2325                 d_drop(dentry);
2326                 dentry = d_add_unique(dentry, igrab(state->inode));
2327                 if (dentry == NULL) {
2328                         dentry = opendata->dentry;
2329                 } else if (dentry != ctx->dentry) {
2330                         dput(ctx->dentry);
2331                         ctx->dentry = dget(dentry);
2332                 }
2333                 nfs_set_verifier(dentry,
2334                                 nfs_save_change_attribute(d_inode(opendata->dir)));
2335         }
2336
2337         ret = nfs4_opendata_access(sp->so_cred, opendata, state, fmode, flags);
2338         if (ret != 0)
2339                 goto out;
2340
2341         ctx->state = state;
2342         if (d_inode(dentry) == state->inode) {
2343                 nfs_inode_attach_open_context(ctx);
2344                 if (read_seqcount_retry(&sp->so_reclaim_seqcount, seq))
2345                         nfs4_schedule_stateid_recovery(server, state);
2346         }
2347 out:
2348         return ret;
2349 }
2350
2351 /*
2352  * Returns a referenced nfs4_state
2353  */
2354 static int _nfs4_do_open(struct inode *dir,
2355                         struct nfs_open_context *ctx,
2356                         int flags,
2357                         struct iattr *sattr,
2358                         struct nfs4_label *label,
2359                         int *opened)
2360 {
2361         struct nfs4_state_owner  *sp;
2362         struct nfs4_state     *state = NULL;
2363         struct nfs_server       *server = NFS_SERVER(dir);
2364         struct nfs4_opendata *opendata;
2365         struct dentry *dentry = ctx->dentry;
2366         struct rpc_cred *cred = ctx->cred;
2367         struct nfs4_threshold **ctx_th = &ctx->mdsthreshold;
2368         fmode_t fmode = ctx->mode & (FMODE_READ|FMODE_WRITE|FMODE_EXEC);
2369         enum open_claim_type4 claim = NFS4_OPEN_CLAIM_NULL;
2370         struct nfs4_label *olabel = NULL;
2371         int status;
2372
2373         /* Protect against reboot recovery conflicts */
2374         status = -ENOMEM;
2375         sp = nfs4_get_state_owner(server, cred, GFP_KERNEL);
2376         if (sp == NULL) {
2377                 dprintk("nfs4_do_open: nfs4_get_state_owner failed!\n");
2378                 goto out_err;
2379         }
2380         status = nfs4_recover_expired_lease(server);
2381         if (status != 0)
2382                 goto err_put_state_owner;
2383         if (d_really_is_positive(dentry))
2384                 nfs4_return_incompatible_delegation(d_inode(dentry), fmode);
2385         status = -ENOMEM;
2386         if (d_really_is_positive(dentry))
2387                 claim = NFS4_OPEN_CLAIM_FH;
2388         opendata = nfs4_opendata_alloc(dentry, sp, fmode, flags, sattr,
2389                         label, claim, GFP_KERNEL);
2390         if (opendata == NULL)
2391                 goto err_put_state_owner;
2392
2393         if (label) {
2394                 olabel = nfs4_label_alloc(server, GFP_KERNEL);
2395                 if (IS_ERR(olabel)) {
2396                         status = PTR_ERR(olabel);
2397                         goto err_opendata_put;
2398                 }
2399         }
2400
2401         if (server->attr_bitmask[2] & FATTR4_WORD2_MDSTHRESHOLD) {
2402                 if (!opendata->f_attr.mdsthreshold) {
2403                         opendata->f_attr.mdsthreshold = pnfs_mdsthreshold_alloc();
2404                         if (!opendata->f_attr.mdsthreshold)
2405                                 goto err_free_label;
2406                 }
2407                 opendata->o_arg.open_bitmap = &nfs4_pnfs_open_bitmap[0];
2408         }
2409         if (d_really_is_positive(dentry))
2410                 opendata->state = nfs4_get_open_state(d_inode(dentry), sp);
2411
2412         status = _nfs4_open_and_get_state(opendata, fmode, flags, ctx);
2413         if (status != 0)
2414                 goto err_free_label;
2415         state = ctx->state;
2416
2417         if ((opendata->o_arg.open_flags & O_EXCL) &&
2418             (opendata->o_arg.createmode != NFS4_CREATE_GUARDED)) {
2419                 nfs4_exclusive_attrset(opendata, sattr);
2420
2421                 nfs_fattr_init(opendata->o_res.f_attr);
2422                 status = nfs4_do_setattr(state->inode, cred,
2423                                 opendata->o_res.f_attr, sattr,
2424                                 state, label, olabel);
2425                 if (status == 0) {
2426                         nfs_setattr_update_inode(state->inode, sattr,
2427                                         opendata->o_res.f_attr);
2428                         nfs_setsecurity(state->inode, opendata->o_res.f_attr, olabel);
2429                 }
2430         }
2431         if (opendata->file_created)
2432                 *opened |= FILE_CREATED;
2433
2434         if (pnfs_use_threshold(ctx_th, opendata->f_attr.mdsthreshold, server)) {
2435                 *ctx_th = opendata->f_attr.mdsthreshold;
2436                 opendata->f_attr.mdsthreshold = NULL;
2437         }
2438
2439         nfs4_label_free(olabel);
2440
2441         nfs4_opendata_put(opendata);
2442         nfs4_put_state_owner(sp);
2443         return 0;
2444 err_free_label:
2445         nfs4_label_free(olabel);
2446 err_opendata_put:
2447         nfs4_opendata_put(opendata);
2448 err_put_state_owner:
2449         nfs4_put_state_owner(sp);
2450 out_err:
2451         return status;
2452 }
2453
2454
2455 static struct nfs4_state *nfs4_do_open(struct inode *dir,
2456                                         struct nfs_open_context *ctx,
2457                                         int flags,
2458                                         struct iattr *sattr,
2459                                         struct nfs4_label *label,
2460                                         int *opened)
2461 {
2462         struct nfs_server *server = NFS_SERVER(dir);
2463         struct nfs4_exception exception = { };
2464         struct nfs4_state *res;
2465         int status;
2466
2467         do {
2468                 status = _nfs4_do_open(dir, ctx, flags, sattr, label, opened);
2469                 res = ctx->state;
2470                 trace_nfs4_open_file(ctx, flags, status);
2471                 if (status == 0)
2472                         break;
2473                 /* NOTE: BAD_SEQID means the server and client disagree about the
2474                  * book-keeping w.r.t. state-changing operations
2475                  * (OPEN/CLOSE/LOCK/LOCKU...)
2476                  * It is actually a sign of a bug on the client or on the server.
2477                  *
2478                  * If we receive a BAD_SEQID error in the particular case of
2479                  * doing an OPEN, we assume that nfs_increment_open_seqid() will
2480                  * have unhashed the old state_owner for us, and that we can
2481                  * therefore safely retry using a new one. We should still warn
2482                  * the user though...
2483                  */
2484                 if (status == -NFS4ERR_BAD_SEQID) {
2485                         pr_warn_ratelimited("NFS: v4 server %s "
2486                                         " returned a bad sequence-id error!\n",
2487                                         NFS_SERVER(dir)->nfs_client->cl_hostname);
2488                         exception.retry = 1;
2489                         continue;
2490                 }
2491                 /*
2492                  * BAD_STATEID on OPEN means that the server cancelled our
2493                  * state before it received the OPEN_CONFIRM.
2494                  * Recover by retrying the request as per the discussion
2495                  * on Page 181 of RFC3530.
2496                  */
2497                 if (status == -NFS4ERR_BAD_STATEID) {
2498                         exception.retry = 1;
2499                         continue;
2500                 }
2501                 if (status == -EAGAIN) {
2502                         /* We must have found a delegation */
2503                         exception.retry = 1;
2504                         continue;
2505                 }
2506                 if (nfs4_clear_cap_atomic_open_v1(server, status, &exception))
2507                         continue;
2508                 res = ERR_PTR(nfs4_handle_exception(server,
2509                                         status, &exception));
2510         } while (exception.retry);
2511         return res;
2512 }
2513
2514 static int _nfs4_do_setattr(struct inode *inode, struct rpc_cred *cred,
2515                             struct nfs_fattr *fattr, struct iattr *sattr,
2516                             struct nfs4_state *state, struct nfs4_label *ilabel,
2517                             struct nfs4_label *olabel)
2518 {
2519         struct nfs_server *server = NFS_SERVER(inode);
2520         struct nfs_setattrargs  arg = {
2521                 .fh             = NFS_FH(inode),
2522                 .iap            = sattr,
2523                 .server         = server,
2524                 .bitmask = server->attr_bitmask,
2525                 .label          = ilabel,
2526         };
2527         struct nfs_setattrres  res = {
2528                 .fattr          = fattr,
2529                 .label          = olabel,
2530                 .server         = server,
2531         };
2532         struct rpc_message msg = {
2533                 .rpc_proc       = &nfs4_procedures[NFSPROC4_CLNT_SETATTR],
2534                 .rpc_argp       = &arg,
2535                 .rpc_resp       = &res,
2536                 .rpc_cred       = cred,
2537         };
2538         unsigned long timestamp = jiffies;
2539         fmode_t fmode;
2540         bool truncate;
2541         int status;
2542
2543         arg.bitmask = nfs4_bitmask(server, ilabel);
2544         if (ilabel)
2545                 arg.bitmask = nfs4_bitmask(server, olabel);
2546
2547         nfs_fattr_init(fattr);
2548
2549         /* Servers should only apply open mode checks for file size changes */
2550         truncate = (sattr->ia_valid & ATTR_SIZE) ? true : false;
2551         fmode = truncate ? FMODE_WRITE : FMODE_READ;
2552
2553         if (nfs4_copy_delegation_stateid(&arg.stateid, inode, fmode)) {
2554                 /* Use that stateid */
2555         } else if (truncate && state != NULL) {
2556                 struct nfs_lockowner lockowner = {
2557                         .l_owner = current->files,
2558                         .l_pid = current->tgid,
2559                 };
2560                 if (!nfs4_valid_open_stateid(state))
2561                         return -EBADF;
2562                 if (nfs4_select_rw_stateid(&arg.stateid, state, FMODE_WRITE,
2563                                 &lockowner) == -EIO)
2564                         return -EBADF;
2565         } else
2566                 nfs4_stateid_copy(&arg.stateid, &zero_stateid);
2567
2568         status = nfs4_call_sync(server->client, server, &msg, &arg.seq_args, &res.seq_res, 1);
2569         if (status == 0 && state != NULL)
2570                 renew_lease(server, timestamp);
2571         return status;
2572 }
2573
2574 static int nfs4_do_setattr(struct inode *inode, struct rpc_cred *cred,
2575                            struct nfs_fattr *fattr, struct iattr *sattr,
2576                            struct nfs4_state *state, struct nfs4_label *ilabel,
2577                            struct nfs4_label *olabel)
2578 {
2579         struct nfs_server *server = NFS_SERVER(inode);
2580         struct nfs4_exception exception = {
2581                 .state = state,
2582                 .inode = inode,
2583         };
2584         int err;
2585         do {
2586                 err = _nfs4_do_setattr(inode, cred, fattr, sattr, state, ilabel, olabel);
2587                 trace_nfs4_setattr(inode, err);
2588                 switch (err) {
2589                 case -NFS4ERR_OPENMODE:
2590                         if (!(sattr->ia_valid & ATTR_SIZE)) {
2591                                 pr_warn_once("NFSv4: server %s is incorrectly "
2592                                                 "applying open mode checks to "
2593                                                 "a SETATTR that is not "
2594                                                 "changing file size.\n",
2595                                                 server->nfs_client->cl_hostname);
2596                         }
2597                         if (state && !(state->state & FMODE_WRITE)) {
2598                                 err = -EBADF;
2599                                 if (sattr->ia_valid & ATTR_OPEN)
2600                                         err = -EACCES;
2601                                 goto out;
2602                         }
2603                 }
2604                 err = nfs4_handle_exception(server, err, &exception);
2605         } while (exception.retry);
2606 out:
2607         return err;
2608 }
2609
2610 struct nfs4_closedata {
2611         struct inode *inode;
2612         struct nfs4_state *state;
2613         struct nfs_closeargs arg;
2614         struct nfs_closeres res;
2615         struct nfs_fattr fattr;
2616         unsigned long timestamp;
2617         bool roc;
2618         u32 roc_barrier;
2619 };
2620
2621 static void nfs4_free_closedata(void *data)
2622 {
2623         struct nfs4_closedata *calldata = data;
2624         struct nfs4_state_owner *sp = calldata->state->owner;
2625         struct super_block *sb = calldata->state->inode->i_sb;
2626
2627         if (calldata->roc)
2628                 pnfs_roc_release(calldata->state->inode);
2629         nfs4_put_open_state(calldata->state);
2630         nfs_free_seqid(calldata->arg.seqid);
2631         nfs4_put_state_owner(sp);
2632         nfs_sb_deactive(sb);
2633         kfree(calldata);
2634 }
2635
2636 static void nfs4_close_done(struct rpc_task *task, void *data)
2637 {
2638         struct nfs4_closedata *calldata = data;
2639         struct nfs4_state *state = calldata->state;
2640         struct nfs_server *server = NFS_SERVER(calldata->inode);
2641         nfs4_stateid *res_stateid = NULL;
2642
2643         dprintk("%s: begin!\n", __func__);
2644         if (!nfs4_sequence_done(task, &calldata->res.seq_res))
2645                 return;
2646         trace_nfs4_close(state, &calldata->arg, &calldata->res, task->tk_status);
2647         /* hmm. we are done with the inode, and in the process of freeing
2648          * the state_owner. we keep this around to process errors
2649          */
2650         switch (task->tk_status) {
2651                 case 0:
2652                         res_stateid = &calldata->res.stateid;
2653                         if (calldata->arg.fmode == 0 && calldata->roc)
2654                                 pnfs_roc_set_barrier(state->inode,
2655                                                      calldata->roc_barrier);
2656                         renew_lease(server, calldata->timestamp);
2657                         break;
2658                 case -NFS4ERR_ADMIN_REVOKED:
2659                 case -NFS4ERR_STALE_STATEID:
2660                 case -NFS4ERR_OLD_STATEID:
2661                 case -NFS4ERR_BAD_STATEID:
2662                 case -NFS4ERR_EXPIRED:
2663                         if (!nfs4_stateid_match(&calldata->arg.stateid,
2664                                                 &state->open_stateid)) {
2665                                 rpc_restart_call_prepare(task);
2666                                 goto out_release;
2667                         }
2668                         if (calldata->arg.fmode == 0)
2669                                 break;
2670                 default:
2671                         if (nfs4_async_handle_error(task, server, state, NULL) == -EAGAIN) {
2672                                 rpc_restart_call_prepare(task);
2673                                 goto out_release;
2674                         }
2675         }
2676         nfs_clear_open_stateid(state, res_stateid, calldata->arg.fmode);
2677 out_release:
2678         nfs_release_seqid(calldata->arg.seqid);
2679         nfs_refresh_inode(calldata->inode, calldata->res.fattr);
2680         dprintk("%s: done, ret = %d!\n", __func__, task->tk_status);
2681 }
2682
2683 static void nfs4_close_prepare(struct rpc_task *task, void *data)
2684 {
2685         struct nfs4_closedata *calldata = data;
2686         struct nfs4_state *state = calldata->state;
2687         struct inode *inode = calldata->inode;
2688         bool is_rdonly, is_wronly, is_rdwr;
2689         int call_close = 0;
2690
2691         dprintk("%s: begin!\n", __func__);
2692         if (nfs_wait_on_sequence(calldata->arg.seqid, task) != 0)
2693                 goto out_wait;
2694
2695         task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_DOWNGRADE];
2696         spin_lock(&state->owner->so_lock);
2697         is_rdwr = test_bit(NFS_O_RDWR_STATE, &state->flags);
2698         is_rdonly = test_bit(NFS_O_RDONLY_STATE, &state->flags);
2699         is_wronly = test_bit(NFS_O_WRONLY_STATE, &state->flags);
2700         nfs4_stateid_copy(&calldata->arg.stateid, &state->open_stateid);
2701         /* Calculate the change in open mode */
2702         calldata->arg.fmode = 0;
2703         if (state->n_rdwr == 0) {
2704                 if (state->n_rdonly == 0)
2705                         call_close |= is_rdonly;
2706                 else if (is_rdonly)
2707                         calldata->arg.fmode |= FMODE_READ;
2708                 if (state->n_wronly == 0)
2709                         call_close |= is_wronly;
2710                 else if (is_wronly)
2711                         calldata->arg.fmode |= FMODE_WRITE;
2712         } else if (is_rdwr)
2713                 calldata->arg.fmode |= FMODE_READ|FMODE_WRITE;
2714
2715         if (calldata->arg.fmode == 0)
2716                 call_close |= is_rdwr;
2717
2718         if (!nfs4_valid_open_stateid(state))
2719                 call_close = 0;
2720         spin_unlock(&state->owner->so_lock);
2721
2722         if (!call_close) {
2723                 /* Note: exit _without_ calling nfs4_close_done */
2724                 goto out_no_action;
2725         }
2726
2727         if (calldata->arg.fmode == 0) {
2728                 task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_CLOSE];
2729                 if (calldata->roc &&
2730                     pnfs_roc_drain(inode, &calldata->roc_barrier, task)) {
2731                         nfs_release_seqid(calldata->arg.seqid);
2732                         goto out_wait;
2733                     }
2734         }
2735         calldata->arg.share_access =
2736                 nfs4_map_atomic_open_share(NFS_SERVER(inode),
2737                                 calldata->arg.fmode, 0);
2738
2739         nfs_fattr_init(calldata->res.fattr);
2740         calldata->timestamp = jiffies;
2741         if (nfs4_setup_sequence(NFS_SERVER(inode),
2742                                 &calldata->arg.seq_args,
2743                                 &calldata->res.seq_res,
2744                                 task) != 0)
2745                 nfs_release_seqid(calldata->arg.seqid);
2746         dprintk("%s: done!\n", __func__);
2747         return;
2748 out_no_action:
2749         task->tk_action = NULL;
2750 out_wait:
2751         nfs4_sequence_done(task, &calldata->res.seq_res);
2752 }
2753
2754 static const struct rpc_call_ops nfs4_close_ops = {
2755         .rpc_call_prepare = nfs4_close_prepare,
2756         .rpc_call_done = nfs4_close_done,
2757         .rpc_release = nfs4_free_closedata,
2758 };
2759
2760 static bool nfs4_roc(struct inode *inode)
2761 {
2762         if (!nfs_have_layout(inode))
2763                 return false;
2764         return pnfs_roc(inode);
2765 }
2766
2767 /* 
2768  * It is possible for data to be read/written from a mem-mapped file 
2769  * after the sys_close call (which hits the vfs layer as a flush).
2770  * This means that we can't safely call nfsv4 close on a file until 
2771  * the inode is cleared. This in turn means that we are not good
2772  * NFSv4 citizens - we do not indicate to the server to update the file's 
2773  * share state even when we are done with one of the three share 
2774  * stateid's in the inode.
2775  *
2776  * NOTE: Caller must be holding the sp->so_owner semaphore!
2777  */
2778 int nfs4_do_close(struct nfs4_state *state, gfp_t gfp_mask, int wait)
2779 {
2780         struct nfs_server *server = NFS_SERVER(state->inode);
2781         struct nfs_seqid *(*alloc_seqid)(struct nfs_seqid_counter *, gfp_t);
2782         struct nfs4_closedata *calldata;
2783         struct nfs4_state_owner *sp = state->owner;
2784         struct rpc_task *task;
2785         struct rpc_message msg = {
2786                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_CLOSE],
2787                 .rpc_cred = state->owner->so_cred,
2788         };
2789         struct rpc_task_setup task_setup_data = {
2790                 .rpc_client = server->client,
2791                 .rpc_message = &msg,
2792                 .callback_ops = &nfs4_close_ops,
2793                 .workqueue = nfsiod_workqueue,
2794                 .flags = RPC_TASK_ASYNC,
2795         };
2796         int status = -ENOMEM;
2797
2798         nfs4_state_protect(server->nfs_client, NFS_SP4_MACH_CRED_CLEANUP,
2799                 &task_setup_data.rpc_client, &msg);
2800
2801         calldata = kzalloc(sizeof(*calldata), gfp_mask);
2802         if (calldata == NULL)
2803                 goto out;
2804         nfs4_init_sequence(&calldata->arg.seq_args, &calldata->res.seq_res, 1);
2805         calldata->inode = state->inode;
2806         calldata->state = state;
2807         calldata->arg.fh = NFS_FH(state->inode);
2808         /* Serialization for the sequence id */
2809         alloc_seqid = server->nfs_client->cl_mvops->alloc_seqid;
2810         calldata->arg.seqid = alloc_seqid(&state->owner->so_seqid, gfp_mask);
2811         if (IS_ERR(calldata->arg.seqid))
2812                 goto out_free_calldata;
2813         calldata->arg.fmode = 0;
2814         calldata->arg.bitmask = server->cache_consistency_bitmask;
2815         calldata->res.fattr = &calldata->fattr;
2816         calldata->res.seqid = calldata->arg.seqid;
2817         calldata->res.server = server;
2818         calldata->roc = nfs4_roc(state->inode);
2819         nfs_sb_active(calldata->inode->i_sb);
2820
2821         msg.rpc_argp = &calldata->arg;
2822         msg.rpc_resp = &calldata->res;
2823         task_setup_data.callback_data = calldata;
2824         task = rpc_run_task(&task_setup_data);
2825         if (IS_ERR(task))
2826                 return PTR_ERR(task);
2827         status = 0;
2828         if (wait)
2829                 status = rpc_wait_for_completion_task(task);
2830         rpc_put_task(task);
2831         return status;
2832 out_free_calldata:
2833         kfree(calldata);
2834 out:
2835         nfs4_put_open_state(state);
2836         nfs4_put_state_owner(sp);
2837         return status;
2838 }
2839
2840 static struct inode *
2841 nfs4_atomic_open(struct inode *dir, struct nfs_open_context *ctx,
2842                 int open_flags, struct iattr *attr, int *opened)
2843 {
2844         struct nfs4_state *state;
2845         struct nfs4_label l = {0, 0, 0, NULL}, *label = NULL;
2846
2847         label = nfs4_label_init_security(dir, ctx->dentry, attr, &l);
2848
2849         /* Protect against concurrent sillydeletes */
2850         state = nfs4_do_open(dir, ctx, open_flags, attr, label, opened);
2851
2852         nfs4_label_release_security(label);
2853
2854         if (IS_ERR(state))
2855                 return ERR_CAST(state);
2856         return state->inode;
2857 }
2858
2859 static void nfs4_close_context(struct nfs_open_context *ctx, int is_sync)
2860 {
2861         if (ctx->state == NULL)
2862                 return;
2863         if (is_sync)
2864                 nfs4_close_sync(ctx->state, ctx->mode);
2865         else
2866                 nfs4_close_state(ctx->state, ctx->mode);
2867 }
2868
2869 #define FATTR4_WORD1_NFS40_MASK (2*FATTR4_WORD1_MOUNTED_ON_FILEID - 1UL)
2870 #define FATTR4_WORD2_NFS41_MASK (2*FATTR4_WORD2_SUPPATTR_EXCLCREAT - 1UL)
2871 #define FATTR4_WORD2_NFS42_MASK (2*FATTR4_WORD2_SECURITY_LABEL - 1UL)
2872
2873 static int _nfs4_server_capabilities(struct nfs_server *server, struct nfs_fh *fhandle)
2874 {
2875         struct nfs4_server_caps_arg args = {
2876                 .fhandle = fhandle,
2877         };
2878         struct nfs4_server_caps_res res = {};
2879         struct rpc_message msg = {
2880                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_SERVER_CAPS],
2881                 .rpc_argp = &args,
2882                 .rpc_resp = &res,
2883         };
2884         int status;
2885
2886         status = nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 0);
2887         if (status == 0) {
2888                 /* Sanity check the server answers */
2889                 switch (server->nfs_client->cl_minorversion) {
2890                 case 0:
2891                         res.attr_bitmask[1] &= FATTR4_WORD1_NFS40_MASK;
2892                         res.attr_bitmask[2] = 0;
2893                         break;
2894                 case 1:
2895                         res.attr_bitmask[2] &= FATTR4_WORD2_NFS41_MASK;
2896                         break;
2897                 case 2:
2898                         res.attr_bitmask[2] &= FATTR4_WORD2_NFS42_MASK;
2899                 }
2900                 memcpy(server->attr_bitmask, res.attr_bitmask, sizeof(server->attr_bitmask));
2901                 server->caps &= ~(NFS_CAP_ACLS|NFS_CAP_HARDLINKS|
2902                                 NFS_CAP_SYMLINKS|NFS_CAP_FILEID|
2903                                 NFS_CAP_MODE|NFS_CAP_NLINK|NFS_CAP_OWNER|
2904                                 NFS_CAP_OWNER_GROUP|NFS_CAP_ATIME|
2905                                 NFS_CAP_CTIME|NFS_CAP_MTIME|
2906                                 NFS_CAP_SECURITY_LABEL);
2907                 if (res.attr_bitmask[0] & FATTR4_WORD0_ACL &&
2908                                 res.acl_bitmask & ACL4_SUPPORT_ALLOW_ACL)
2909                         server->caps |= NFS_CAP_ACLS;
2910                 if (res.has_links != 0)
2911                         server->caps |= NFS_CAP_HARDLINKS;
2912                 if (res.has_symlinks != 0)
2913                         server->caps |= NFS_CAP_SYMLINKS;
2914                 if (res.attr_bitmask[0] & FATTR4_WORD0_FILEID)
2915                         server->caps |= NFS_CAP_FILEID;
2916                 if (res.attr_bitmask[1] & FATTR4_WORD1_MODE)
2917                         server->caps |= NFS_CAP_MODE;
2918                 if (res.attr_bitmask[1] & FATTR4_WORD1_NUMLINKS)
2919                         server->caps |= NFS_CAP_NLINK;
2920                 if (res.attr_bitmask[1] & FATTR4_WORD1_OWNER)
2921                         server->caps |= NFS_CAP_OWNER;
2922                 if (res.attr_bitmask[1] & FATTR4_WORD1_OWNER_GROUP)
2923                         server->caps |= NFS_CAP_OWNER_GROUP;
2924                 if (res.attr_bitmask[1] & FATTR4_WORD1_TIME_ACCESS)
2925                         server->caps |= NFS_CAP_ATIME;
2926                 if (res.attr_bitmask[1] & FATTR4_WORD1_TIME_METADATA)
2927                         server->caps |= NFS_CAP_CTIME;
2928                 if (res.attr_bitmask[1] & FATTR4_WORD1_TIME_MODIFY)
2929                         server->caps |= NFS_CAP_MTIME;
2930 #ifdef CONFIG_NFS_V4_SECURITY_LABEL
2931                 if (res.attr_bitmask[2] & FATTR4_WORD2_SECURITY_LABEL)
2932                         server->caps |= NFS_CAP_SECURITY_LABEL;
2933 #endif
2934                 memcpy(server->attr_bitmask_nl, res.attr_bitmask,
2935                                 sizeof(server->attr_bitmask));
2936                 server->attr_bitmask_nl[2] &= ~FATTR4_WORD2_SECURITY_LABEL;
2937
2938                 memcpy(server->cache_consistency_bitmask, res.attr_bitmask, sizeof(server->cache_consistency_bitmask));
2939                 server->cache_consistency_bitmask[0] &= FATTR4_WORD0_CHANGE|FATTR4_WORD0_SIZE;
2940                 server->cache_consistency_bitmask[1] &= FATTR4_WORD1_TIME_METADATA|FATTR4_WORD1_TIME_MODIFY;
2941                 server->cache_consistency_bitmask[2] = 0;
2942                 server->acl_bitmask = res.acl_bitmask;
2943                 server->fh_expire_type = res.fh_expire_type;
2944         }
2945
2946         return status;
2947 }
2948
2949 int nfs4_server_capabilities(struct nfs_server *server, struct nfs_fh *fhandle)
2950 {
2951         struct nfs4_exception exception = { };
2952         int err;
2953         do {
2954                 err = nfs4_handle_exception(server,
2955                                 _nfs4_server_capabilities(server, fhandle),
2956                                 &exception);
2957         } while (exception.retry);
2958         return err;
2959 }
2960
2961 static int _nfs4_lookup_root(struct nfs_server *server, struct nfs_fh *fhandle,
2962                 struct nfs_fsinfo *info)
2963 {
2964         u32 bitmask[3];
2965         struct nfs4_lookup_root_arg args = {
2966                 .bitmask = bitmask,
2967         };
2968         struct nfs4_lookup_res res = {
2969                 .server = server,
2970                 .fattr = info->fattr,
2971                 .fh = fhandle,
2972         };
2973         struct rpc_message msg = {
2974                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_LOOKUP_ROOT],
2975                 .rpc_argp = &args,
2976                 .rpc_resp = &res,
2977         };
2978
2979         bitmask[0] = nfs4_fattr_bitmap[0];
2980         bitmask[1] = nfs4_fattr_bitmap[1];
2981         /*
2982          * Process the label in the upcoming getfattr
2983          */
2984         bitmask[2] = nfs4_fattr_bitmap[2] & ~FATTR4_WORD2_SECURITY_LABEL;
2985
2986         nfs_fattr_init(info->fattr);
2987         return nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 0);
2988 }
2989
2990 static int nfs4_lookup_root(struct nfs_server *server, struct nfs_fh *fhandle,
2991                 struct nfs_fsinfo *info)
2992 {
2993         struct nfs4_exception exception = { };
2994         int err;
2995         do {
2996                 err = _nfs4_lookup_root(server, fhandle, info);
2997                 trace_nfs4_lookup_root(server, fhandle, info->fattr, err);
2998                 switch (err) {
2999                 case 0:
3000                 case -NFS4ERR_WRONGSEC:
3001                         goto out;
3002                 default:
3003                         err = nfs4_handle_exception(server, err, &exception);
3004                 }
3005         } while (exception.retry);
3006 out:
3007         return err;
3008 }
3009
3010 static int nfs4_lookup_root_sec(struct nfs_server *server, struct nfs_fh *fhandle,
3011                                 struct nfs_fsinfo *info, rpc_authflavor_t flavor)
3012 {
3013         struct rpc_auth_create_args auth_args = {
3014                 .pseudoflavor = flavor,
3015         };
3016         struct rpc_auth *auth;
3017         int ret;
3018
3019         auth = rpcauth_create(&auth_args, server->client);
3020         if (IS_ERR(auth)) {
3021                 ret = -EACCES;
3022                 goto out;
3023         }
3024         ret = nfs4_lookup_root(server, fhandle, info);
3025 out:
3026         return ret;
3027 }
3028
3029 /*
3030  * Retry pseudoroot lookup with various security flavors.  We do this when:
3031  *
3032  *   NFSv4.0: the PUTROOTFH operation returns NFS4ERR_WRONGSEC
3033  *   NFSv4.1: the server does not support the SECINFO_NO_NAME operation
3034  *
3035  * Returns zero on success, or a negative NFS4ERR value, or a
3036  * negative errno value.
3037  */
3038 static int nfs4_find_root_sec(struct nfs_server *server, struct nfs_fh *fhandle,
3039                               struct nfs_fsinfo *info)
3040 {
3041         /* Per 3530bis 15.33.5 */
3042         static const rpc_authflavor_t flav_array[] = {
3043                 RPC_AUTH_GSS_KRB5P,
3044                 RPC_AUTH_GSS_KRB5I,
3045                 RPC_AUTH_GSS_KRB5,
3046                 RPC_AUTH_UNIX,                  /* courtesy */
3047                 RPC_AUTH_NULL,
3048         };
3049         int status = -EPERM;
3050         size_t i;
3051
3052         if (server->auth_info.flavor_len > 0) {
3053                 /* try each flavor specified by user */
3054                 for (i = 0; i < server->auth_info.flavor_len; i++) {
3055                         status = nfs4_lookup_root_sec(server, fhandle, info,
3056                                                 server->auth_info.flavors[i]);
3057                         if (status == -NFS4ERR_WRONGSEC || status == -EACCES)
3058                                 continue;
3059                         break;
3060                 }
3061         } else {
3062                 /* no flavors specified by user, try default list */
3063                 for (i = 0; i < ARRAY_SIZE(flav_array); i++) {
3064                         status = nfs4_lookup_root_sec(server, fhandle, info,
3065                                                       flav_array[i]);
3066                         if (status == -NFS4ERR_WRONGSEC || status == -EACCES)
3067                                 continue;
3068                         break;
3069                 }
3070         }
3071
3072         /*
3073          * -EACCESS could mean that the user doesn't have correct permissions
3074          * to access the mount.  It could also mean that we tried to mount
3075          * with a gss auth flavor, but rpc.gssd isn't running.  Either way,
3076          * existing mount programs don't handle -EACCES very well so it should
3077          * be mapped to -EPERM instead.
3078          */
3079         if (status == -EACCES)
3080                 status = -EPERM;
3081         return status;
3082 }
3083
3084 static int nfs4_do_find_root_sec(struct nfs_server *server,
3085                 struct nfs_fh *fhandle, struct nfs_fsinfo *info)
3086 {
3087         int mv = server->nfs_client->cl_minorversion;
3088         return nfs_v4_minor_ops[mv]->find_root_sec(server, fhandle, info);
3089 }
3090
3091 /**
3092  * nfs4_proc_get_rootfh - get file handle for server's pseudoroot
3093  * @server: initialized nfs_server handle
3094  * @fhandle: we fill in the pseudo-fs root file handle
3095  * @info: we fill in an FSINFO struct
3096  * @auth_probe: probe the auth flavours
3097  *
3098  * Returns zero on success, or a negative errno.
3099  */
3100 int nfs4_proc_get_rootfh(struct nfs_server *server, struct nfs_fh *fhandle,
3101                          struct nfs_fsinfo *info,
3102                          bool auth_probe)
3103 {
3104         int status = 0;
3105
3106         if (!auth_probe)
3107                 status = nfs4_lookup_root(server, fhandle, info);
3108
3109         if (auth_probe || status == NFS4ERR_WRONGSEC)
3110                 status = nfs4_do_find_root_sec(server, fhandle, info);
3111
3112         if (status == 0)
3113                 status = nfs4_server_capabilities(server, fhandle);
3114         if (status == 0)
3115                 status = nfs4_do_fsinfo(server, fhandle, info);
3116
3117         return nfs4_map_errors(status);
3118 }
3119
3120 static int nfs4_proc_get_root(struct nfs_server *server, struct nfs_fh *mntfh,
3121                               struct nfs_fsinfo *info)
3122 {
3123         int error;
3124         struct nfs_fattr *fattr = info->fattr;
3125         struct nfs4_label *label = NULL;
3126
3127         error = nfs4_server_capabilities(server, mntfh);
3128         if (error < 0) {
3129                 dprintk("nfs4_get_root: getcaps error = %d\n", -error);
3130                 return error;
3131         }
3132
3133         label = nfs4_label_alloc(server, GFP_KERNEL);
3134         if (IS_ERR(label))
3135                 return PTR_ERR(label);
3136
3137         error = nfs4_proc_getattr(server, mntfh, fattr, label);
3138         if (error < 0) {
3139                 dprintk("nfs4_get_root: getattr error = %d\n", -error);
3140                 goto err_free_label;
3141         }
3142
3143         if (fattr->valid & NFS_ATTR_FATTR_FSID &&
3144             !nfs_fsid_equal(&server->fsid, &fattr->fsid))
3145                 memcpy(&server->fsid, &fattr->fsid, sizeof(server->fsid));
3146
3147 err_free_label:
3148         nfs4_label_free(label);
3149
3150         return error;
3151 }
3152
3153 /*
3154  * Get locations and (maybe) other attributes of a referral.
3155  * Note that we'll actually follow the referral later when
3156  * we detect fsid mismatch in inode revalidation
3157  */
3158 static int nfs4_get_referral(struct rpc_clnt *client, struct inode *dir,
3159                              const struct qstr *name, struct nfs_fattr *fattr,
3160                              struct nfs_fh *fhandle)
3161 {
3162         int status = -ENOMEM;
3163         struct page *page = NULL;
3164         struct nfs4_fs_locations *locations = NULL;
3165
3166         page = alloc_page(GFP_KERNEL);
3167         if (page == NULL)
3168                 goto out;
3169         locations = kmalloc(sizeof(struct nfs4_fs_locations), GFP_KERNEL);
3170         if (locations == NULL)
3171                 goto out;
3172
3173         status = nfs4_proc_fs_locations(client, dir, name, locations, page);
3174         if (status != 0)
3175                 goto out;
3176
3177         /*
3178          * If the fsid didn't change, this is a migration event, not a
3179          * referral.  Cause us to drop into the exception handler, which
3180          * will kick off migration recovery.
3181          */
3182         if (nfs_fsid_equal(&NFS_SERVER(dir)->fsid, &locations->fattr.fsid)) {
3183                 dprintk("%s: server did not return a different fsid for"
3184                         " a referral at %s\n", __func__, name->name);
3185                 status = -NFS4ERR_MOVED;
3186                 goto out;
3187         }
3188         /* Fixup attributes for the nfs_lookup() call to nfs_fhget() */
3189         nfs_fixup_referral_attributes(&locations->fattr);
3190
3191         /* replace the lookup nfs_fattr with the locations nfs_fattr */
3192         memcpy(fattr, &locations->fattr, sizeof(struct nfs_fattr));
3193         memset(fhandle, 0, sizeof(struct nfs_fh));
3194 out:
3195         if (page)
3196                 __free_page(page);
3197         kfree(locations);
3198         return status;
3199 }
3200
3201 static int _nfs4_proc_getattr(struct nfs_server *server, struct nfs_fh *fhandle,
3202                                 struct nfs_fattr *fattr, struct nfs4_label *label)
3203 {
3204         struct nfs4_getattr_arg args = {
3205                 .fh = fhandle,
3206                 .bitmask = server->attr_bitmask,
3207         };
3208         struct nfs4_getattr_res res = {
3209                 .fattr = fattr,
3210                 .label = label,
3211                 .server = server,
3212         };
3213         struct rpc_message msg = {
3214                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETATTR],
3215                 .rpc_argp = &args,
3216                 .rpc_resp = &res,
3217         };
3218
3219         args.bitmask = nfs4_bitmask(server, label);
3220
3221         nfs_fattr_init(fattr);
3222         return nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 0);
3223 }
3224
3225 static int nfs4_proc_getattr(struct nfs_server *server, struct nfs_fh *fhandle,
3226                                 struct nfs_fattr *fattr, struct nfs4_label *label)
3227 {
3228         struct nfs4_exception exception = { };
3229         int err;
3230         do {
3231                 err = _nfs4_proc_getattr(server, fhandle, fattr, label);
3232                 trace_nfs4_getattr(server, fhandle, fattr, err);
3233                 err = nfs4_handle_exception(server, err,
3234                                 &exception);
3235         } while (exception.retry);
3236         return err;
3237 }
3238
3239 /* 
3240  * The file is not closed if it is opened due to the a request to change
3241  * the size of the file. The open call will not be needed once the
3242  * VFS layer lookup-intents are implemented.
3243  *
3244  * Close is called when the inode is destroyed.
3245  * If we haven't opened the file for O_WRONLY, we
3246  * need to in the size_change case to obtain a stateid.
3247  *
3248  * Got race?
3249  * Because OPEN is always done by name in nfsv4, it is
3250  * possible that we opened a different file by the same
3251  * name.  We can recognize this race condition, but we
3252  * can't do anything about it besides returning an error.
3253  *
3254  * This will be fixed with VFS changes (lookup-intent).
3255  */
3256 static int
3257 nfs4_proc_setattr(struct dentry *dentry, struct nfs_fattr *fattr,
3258                   struct iattr *sattr)
3259 {
3260         struct inode *inode = d_inode(dentry);
3261         struct rpc_cred *cred = NULL;
3262         struct nfs4_state *state = NULL;
3263         struct nfs4_label *label = NULL;
3264         int status;
3265
3266         if (pnfs_ld_layoutret_on_setattr(inode) &&
3267             sattr->ia_valid & ATTR_SIZE &&
3268             sattr->ia_size < i_size_read(inode))
3269                 pnfs_commit_and_return_layout(inode);
3270
3271         nfs_fattr_init(fattr);
3272         
3273         /* Deal with open(O_TRUNC) */
3274         if (sattr->ia_valid & ATTR_OPEN)
3275                 sattr->ia_valid &= ~(ATTR_MTIME|ATTR_CTIME);
3276
3277         /* Optimization: if the end result is no change, don't RPC */
3278         if ((sattr->ia_valid & ~(ATTR_FILE|ATTR_OPEN)) == 0)
3279                 return 0;
3280
3281         /* Search for an existing open(O_WRITE) file */
3282         if (sattr->ia_valid & ATTR_FILE) {
3283                 struct nfs_open_context *ctx;
3284
3285                 ctx = nfs_file_open_context(sattr->ia_file);
3286                 if (ctx) {
3287                         cred = ctx->cred;
3288                         state = ctx->state;
3289                 }
3290         }
3291
3292         label = nfs4_label_alloc(NFS_SERVER(inode), GFP_KERNEL);
3293         if (IS_ERR(label))
3294                 return PTR_ERR(label);
3295
3296         status = nfs4_do_setattr(inode, cred, fattr, sattr, state, NULL, label);
3297         if (status == 0) {
3298                 nfs_setattr_update_inode(inode, sattr, fattr);
3299                 nfs_setsecurity(inode, fattr, label);
3300         }
3301         nfs4_label_free(label);
3302         return status;
3303 }
3304
3305 static int _nfs4_proc_lookup(struct rpc_clnt *clnt, struct inode *dir,
3306                 const struct qstr *name, struct nfs_fh *fhandle,
3307                 struct nfs_fattr *fattr, struct nfs4_label *label)
3308 {
3309         struct nfs_server *server = NFS_SERVER(dir);
3310         int                    status;
3311         struct nfs4_lookup_arg args = {
3312                 .bitmask = server->attr_bitmask,
3313                 .dir_fh = NFS_FH(dir),
3314                 .name = name,
3315         };
3316         struct nfs4_lookup_res res = {
3317                 .server = server,
3318                 .fattr = fattr,
3319                 .label = label,
3320                 .fh = fhandle,
3321         };
3322         struct rpc_message msg = {
3323                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_LOOKUP],
3324                 .rpc_argp = &args,
3325                 .rpc_resp = &res,
3326         };
3327
3328         args.bitmask = nfs4_bitmask(server, label);
3329
3330         nfs_fattr_init(fattr);
3331
3332         dprintk("NFS call  lookup %s\n", name->name);
3333         status = nfs4_call_sync(clnt, server, &msg, &args.seq_args, &res.seq_res, 0);
3334         dprintk("NFS reply lookup: %d\n", status);
3335         return status;
3336 }
3337
3338 static void nfs_fixup_secinfo_attributes(struct nfs_fattr *fattr)
3339 {
3340         fattr->valid |= NFS_ATTR_FATTR_TYPE | NFS_ATTR_FATTR_MODE |
3341                 NFS_ATTR_FATTR_NLINK | NFS_ATTR_FATTR_MOUNTPOINT;
3342         fattr->mode = S_IFDIR | S_IRUGO | S_IXUGO;
3343         fattr->nlink = 2;
3344 }
3345
3346 static int nfs4_proc_lookup_common(struct rpc_clnt **clnt, struct inode *dir,
3347                                    struct qstr *name, struct nfs_fh *fhandle,
3348                                    struct nfs_fattr *fattr, struct nfs4_label *label)
3349 {
3350         struct nfs4_exception exception = { };
3351         struct rpc_clnt *client = *clnt;
3352         int err;
3353         do {
3354                 err = _nfs4_proc_lookup(client, dir, name, fhandle, fattr, label);
3355                 trace_nfs4_lookup(dir, name, err);
3356                 switch (err) {
3357                 case -NFS4ERR_BADNAME:
3358                         err = -ENOENT;
3359                         goto out;
3360                 case -NFS4ERR_MOVED:
3361                         err = nfs4_get_referral(client, dir, name, fattr, fhandle);
3362                         if (err == -NFS4ERR_MOVED)
3363                                 err = nfs4_handle_exception(NFS_SERVER(dir), err, &exception);
3364                         goto out;
3365                 case -NFS4ERR_WRONGSEC:
3366                         err = -EPERM;
3367                         if (client != *clnt)
3368                                 goto out;
3369                         client = nfs4_negotiate_security(client, dir, name);
3370                         if (IS_ERR(client))
3371                                 return PTR_ERR(client);
3372
3373                         exception.retry = 1;
3374                         break;
3375                 default:
3376                         err = nfs4_handle_exception(NFS_SERVER(dir), err, &exception);
3377                 }
3378         } while (exception.retry);
3379
3380 out:
3381         if (err == 0)
3382                 *clnt = client;
3383         else if (client != *clnt)
3384                 rpc_shutdown_client(client);
3385
3386         return err;
3387 }
3388
3389 static int nfs4_proc_lookup(struct inode *dir, struct qstr *name,
3390                             struct nfs_fh *fhandle, struct nfs_fattr *fattr,
3391                             struct nfs4_label *label)
3392 {
3393         int status;
3394         struct rpc_clnt *client = NFS_CLIENT(dir);
3395
3396         status = nfs4_proc_lookup_common(&client, dir, name, fhandle, fattr, label);
3397         if (client != NFS_CLIENT(dir)) {
3398                 rpc_shutdown_client(client);
3399                 nfs_fixup_secinfo_attributes(fattr);
3400         }
3401         return status;
3402 }
3403
3404 struct rpc_clnt *
3405 nfs4_proc_lookup_mountpoint(struct inode *dir, struct qstr *name,
3406                             struct nfs_fh *fhandle, struct nfs_fattr *fattr)
3407 {
3408         struct rpc_clnt *client = NFS_CLIENT(dir);
3409         int status;
3410
3411         status = nfs4_proc_lookup_common(&client, dir, name, fhandle, fattr, NULL);
3412         if (status < 0)
3413                 return ERR_PTR(status);
3414         return (client == NFS_CLIENT(dir)) ? rpc_clone_client(client) : client;
3415 }
3416
3417 static int _nfs4_proc_access(struct inode *inode, struct nfs_access_entry *entry)
3418 {
3419         struct nfs_server *server = NFS_SERVER(inode);
3420         struct nfs4_accessargs args = {
3421                 .fh = NFS_FH(inode),
3422                 .bitmask = server->cache_consistency_bitmask,
3423         };
3424         struct nfs4_accessres res = {
3425                 .server = server,
3426         };
3427         struct rpc_message msg = {
3428                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_ACCESS],
3429                 .rpc_argp = &args,
3430                 .rpc_resp = &res,
3431                 .rpc_cred = entry->cred,
3432         };
3433         int mode = entry->mask;
3434         int status = 0;
3435
3436         /*
3437          * Determine which access bits we want to ask for...
3438          */
3439         if (mode & MAY_READ)
3440                 args.access |= NFS4_ACCESS_READ;
3441         if (S_ISDIR(inode->i_mode)) {
3442                 if (mode & MAY_WRITE)
3443                         args.access |= NFS4_ACCESS_MODIFY | NFS4_ACCESS_EXTEND | NFS4_ACCESS_DELETE;
3444                 if (mode & MAY_EXEC)
3445                         args.access |= NFS4_ACCESS_LOOKUP;
3446         } else {
3447                 if (mode & MAY_WRITE)
3448                         args.access |= NFS4_ACCESS_MODIFY | NFS4_ACCESS_EXTEND;
3449                 if (mode & MAY_EXEC)
3450                         args.access |= NFS4_ACCESS_EXECUTE;
3451         }
3452
3453         res.fattr = nfs_alloc_fattr();
3454         if (res.fattr == NULL)
3455                 return -ENOMEM;
3456
3457         status = nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 0);
3458         if (!status) {
3459                 nfs_access_set_mask(entry, res.access);
3460                 nfs_refresh_inode(inode, res.fattr);
3461         }
3462         nfs_free_fattr(res.fattr);
3463         return status;
3464 }
3465
3466 static int nfs4_proc_access(struct inode *inode, struct nfs_access_entry *entry)
3467 {
3468         struct nfs4_exception exception = { };
3469         int err;
3470         do {
3471                 err = _nfs4_proc_access(inode, entry);
3472                 trace_nfs4_access(inode, err);
3473                 err = nfs4_handle_exception(NFS_SERVER(inode), err,
3474                                 &exception);
3475         } while (exception.retry);
3476         return err;
3477 }
3478
3479 /*
3480  * TODO: For the time being, we don't try to get any attributes
3481  * along with any of the zero-copy operations READ, READDIR,
3482  * READLINK, WRITE.
3483  *
3484  * In the case of the first three, we want to put the GETATTR
3485  * after the read-type operation -- this is because it is hard
3486  * to predict the length of a GETATTR response in v4, and thus
3487  * align the READ data correctly.  This means that the GETATTR
3488  * may end up partially falling into the page cache, and we should
3489  * shift it into the 'tail' of the xdr_buf before processing.
3490  * To do this efficiently, we need to know the total length
3491  * of data received, which doesn't seem to be available outside
3492  * of the RPC layer.
3493  *
3494  * In the case of WRITE, we also want to put the GETATTR after
3495  * the operation -- in this case because we want to make sure
3496  * we get the post-operation mtime and size.
3497  *
3498  * Both of these changes to the XDR layer would in fact be quite
3499  * minor, but I decided to leave them for a subsequent patch.
3500  */
3501 static int _nfs4_proc_readlink(struct inode *inode, struct page *page,
3502                 unsigned int pgbase, unsigned int pglen)
3503 {
3504         struct nfs4_readlink args = {
3505                 .fh       = NFS_FH(inode),
3506                 .pgbase   = pgbase,
3507                 .pglen    = pglen,
3508                 .pages    = &page,
3509         };
3510         struct nfs4_readlink_res res;
3511         struct rpc_message msg = {
3512                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_READLINK],
3513                 .rpc_argp = &args,
3514                 .rpc_resp = &res,
3515         };
3516
3517         return nfs4_call_sync(NFS_SERVER(inode)->client, NFS_SERVER(inode), &msg, &args.seq_args, &res.seq_res, 0);
3518 }
3519
3520 static int nfs4_proc_readlink(struct inode *inode, struct page *page,
3521                 unsigned int pgbase, unsigned int pglen)
3522 {
3523         struct nfs4_exception exception = { };
3524         int err;
3525         do {
3526                 err = _nfs4_proc_readlink(inode, page, pgbase, pglen);
3527                 trace_nfs4_readlink(inode, err);
3528                 err = nfs4_handle_exception(NFS_SERVER(inode), err,
3529                                 &exception);
3530         } while (exception.retry);
3531         return err;
3532 }
3533
3534 /*
3535  * This is just for mknod.  open(O_CREAT) will always do ->open_context().
3536  */
3537 static int
3538 nfs4_proc_create(struct inode *dir, struct dentry *dentry, struct iattr *sattr,
3539                  int flags)
3540 {
3541         struct nfs4_label l, *ilabel = NULL;
3542         struct nfs_open_context *ctx;
3543         struct nfs4_state *state;
3544         int opened = 0;
3545         int status = 0;
3546
3547         ctx = alloc_nfs_open_context(dentry, FMODE_READ);
3548         if (IS_ERR(ctx))
3549                 return PTR_ERR(ctx);
3550
3551         ilabel = nfs4_label_init_security(dir, dentry, sattr, &l);
3552
3553         sattr->ia_mode &= ~current_umask();
3554         state = nfs4_do_open(dir, ctx, flags, sattr, ilabel, &opened);
3555         if (IS_ERR(state)) {
3556                 status = PTR_ERR(state);
3557                 goto out;
3558         }
3559 out:
3560         nfs4_label_release_security(ilabel);
3561         put_nfs_open_context(ctx);
3562         return status;
3563 }
3564
3565 static int _nfs4_proc_remove(struct inode *dir, struct qstr *name)
3566 {
3567         struct nfs_server *server = NFS_SERVER(dir);
3568         struct nfs_removeargs args = {
3569                 .fh = NFS_FH(dir),
3570                 .name = *name,
3571         };
3572         struct nfs_removeres res = {
3573                 .server = server,
3574         };
3575         struct rpc_message msg = {
3576                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_REMOVE],
3577                 .rpc_argp = &args,
3578                 .rpc_resp = &res,
3579         };
3580         int status;
3581
3582         status = nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 1);
3583         if (status == 0)
3584                 update_changeattr(dir, &res.cinfo);
3585         return status;
3586 }
3587
3588 static int nfs4_proc_remove(struct inode *dir, struct qstr *name)
3589 {
3590         struct nfs4_exception exception = { };
3591         int err;
3592         do {
3593                 err = _nfs4_proc_remove(dir, name);
3594                 trace_nfs4_remove(dir, name, err);
3595                 err = nfs4_handle_exception(NFS_SERVER(dir), err,
3596                                 &exception);
3597         } while (exception.retry);
3598         return err;
3599 }
3600
3601 static void nfs4_proc_unlink_setup(struct rpc_message *msg, struct inode *dir)
3602 {
3603         struct nfs_server *server = NFS_SERVER(dir);
3604         struct nfs_removeargs *args = msg->rpc_argp;
3605         struct nfs_removeres *res = msg->rpc_resp;
3606
3607         res->server = server;
3608         msg->rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_REMOVE];
3609         nfs4_init_sequence(&args->seq_args, &res->seq_res, 1);
3610
3611         nfs_fattr_init(res->dir_attr);
3612 }
3613
3614 static void nfs4_proc_unlink_rpc_prepare(struct rpc_task *task, struct nfs_unlinkdata *data)
3615 {
3616         nfs4_setup_sequence(NFS_SERVER(data->dir),
3617                         &data->args.seq_args,
3618                         &data->res.seq_res,
3619                         task);
3620 }
3621
3622 static int nfs4_proc_unlink_done(struct rpc_task *task, struct inode *dir)
3623 {
3624         struct nfs_unlinkdata *data = task->tk_calldata;
3625         struct nfs_removeres *res = &data->res;
3626
3627         if (!nfs4_sequence_done(task, &res->seq_res))
3628                 return 0;
3629         if (nfs4_async_handle_error(task, res->server, NULL,
3630                                     &data->timeout) == -EAGAIN)
3631                 return 0;
3632         update_changeattr(dir, &res->cinfo);
3633         return 1;
3634 }
3635
3636 static void nfs4_proc_rename_setup(struct rpc_message *msg, struct inode *dir)
3637 {
3638         struct nfs_server *server = NFS_SERVER(dir);
3639         struct nfs_renameargs *arg = msg->rpc_argp;
3640         struct nfs_renameres *res = msg->rpc_resp;
3641
3642         msg->rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_RENAME];
3643         res->server = server;
3644         nfs4_init_sequence(&arg->seq_args, &res->seq_res, 1);
3645 }
3646
3647 static void nfs4_proc_rename_rpc_prepare(struct rpc_task *task, struct nfs_renamedata *data)
3648 {
3649         nfs4_setup_sequence(NFS_SERVER(data->old_dir),
3650                         &data->args.seq_args,
3651                         &data->res.seq_res,
3652                         task);
3653 }
3654
3655 static int nfs4_proc_rename_done(struct rpc_task *task, struct inode *old_dir,
3656                                  struct inode *new_dir)
3657 {
3658         struct nfs_renamedata *data = task->tk_calldata;
3659         struct nfs_renameres *res = &data->res;
3660
3661         if (!nfs4_sequence_done(task, &res->seq_res))
3662                 return 0;
3663         if (nfs4_async_handle_error(task, res->server, NULL, &data->timeout) == -EAGAIN)
3664                 return 0;
3665
3666         update_changeattr(old_dir, &res->old_cinfo);
3667         update_changeattr(new_dir, &res->new_cinfo);
3668         return 1;
3669 }
3670
3671 static int _nfs4_proc_link(struct inode *inode, struct inode *dir, struct qstr *name)
3672 {
3673         struct nfs_server *server = NFS_SERVER(inode);
3674         struct nfs4_link_arg arg = {
3675                 .fh     = NFS_FH(inode),
3676                 .dir_fh = NFS_FH(dir),
3677                 .name   = name,
3678                 .bitmask = server->attr_bitmask,
3679         };
3680         struct nfs4_link_res res = {
3681                 .server = server,
3682                 .label = NULL,
3683         };
3684         struct rpc_message msg = {
3685                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_LINK],
3686                 .rpc_argp = &arg,
3687                 .rpc_resp = &res,
3688         };
3689         int status = -ENOMEM;
3690
3691         res.fattr = nfs_alloc_fattr();
3692         if (res.fattr == NULL)
3693                 goto out;
3694
3695         res.label = nfs4_label_alloc(server, GFP_KERNEL);
3696         if (IS_ERR(res.label)) {
3697                 status = PTR_ERR(res.label);
3698                 goto out;
3699         }
3700         arg.bitmask = nfs4_bitmask(server, res.label);
3701
3702         status = nfs4_call_sync(server->client, server, &msg, &arg.seq_args, &res.seq_res, 1);
3703         if (!status) {
3704                 update_changeattr(dir, &res.cinfo);
3705                 status = nfs_post_op_update_inode(inode, res.fattr);
3706                 if (!status)
3707                         nfs_setsecurity(inode, res.fattr, res.label);
3708         }
3709
3710
3711         nfs4_label_free(res.label);
3712
3713 out:
3714         nfs_free_fattr(res.fattr);
3715         return status;
3716 }
3717
3718 static int nfs4_proc_link(struct inode *inode, struct inode *dir, struct qstr *name)
3719 {
3720         struct nfs4_exception exception = { };
3721         int err;
3722         do {
3723                 err = nfs4_handle_exception(NFS_SERVER(inode),
3724                                 _nfs4_proc_link(inode, dir, name),
3725                                 &exception);
3726         } while (exception.retry);
3727         return err;
3728 }
3729
3730 struct nfs4_createdata {
3731         struct rpc_message msg;
3732         struct nfs4_create_arg arg;
3733         struct nfs4_create_res res;
3734         struct nfs_fh fh;
3735         struct nfs_fattr fattr;
3736         struct nfs4_label *label;
3737 };
3738
3739 static struct nfs4_createdata *nfs4_alloc_createdata(struct inode *dir,
3740                 struct qstr *name, struct iattr *sattr, u32 ftype)
3741 {
3742         struct nfs4_createdata *data;
3743
3744         data = kzalloc(sizeof(*data), GFP_KERNEL);
3745         if (data != NULL) {
3746                 struct nfs_server *server = NFS_SERVER(dir);
3747
3748                 data->label = nfs4_label_alloc(server, GFP_KERNEL);
3749                 if (IS_ERR(data->label))
3750                         goto out_free;
3751
3752                 data->msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_CREATE];
3753                 data->msg.rpc_argp = &data->arg;
3754                 data->msg.rpc_resp = &data->res;
3755                 data->arg.dir_fh = NFS_FH(dir);
3756                 data->arg.server = server;
3757                 data->arg.name = name;
3758                 data->arg.attrs = sattr;
3759                 data->arg.ftype = ftype;
3760                 data->arg.bitmask = nfs4_bitmask(server, data->label);
3761                 data->res.server = server;
3762                 data->res.fh = &data->fh;
3763                 data->res.fattr = &data->fattr;
3764                 data->res.label = data->label;
3765                 nfs_fattr_init(data->res.fattr);
3766         }
3767         return data;
3768 out_free:
3769         kfree(data);
3770         return NULL;
3771 }
3772
3773 static int nfs4_do_create(struct inode *dir, struct dentry *dentry, struct nfs4_createdata *data)
3774 {
3775         int status = nfs4_call_sync(NFS_SERVER(dir)->client, NFS_SERVER(dir), &data->msg,
3776                                     &data->arg.seq_args, &data->res.seq_res, 1);
3777         if (status == 0) {
3778                 update_changeattr(dir, &data->res.dir_cinfo);
3779                 status = nfs_instantiate(dentry, data->res.fh, data->res.fattr, data->res.label);
3780         }
3781         return status;
3782 }
3783
3784 static void nfs4_free_createdata(struct nfs4_createdata *data)
3785 {
3786         nfs4_label_free(data->label);
3787         kfree(data);
3788 }
3789
3790 static int _nfs4_proc_symlink(struct inode *dir, struct dentry *dentry,
3791                 struct page *page, unsigned int len, struct iattr *sattr,
3792                 struct nfs4_label *label)
3793 {
3794         struct nfs4_createdata *data;
3795         int status = -ENAMETOOLONG;
3796
3797         if (len > NFS4_MAXPATHLEN)
3798                 goto out;
3799
3800         status = -ENOMEM;
3801         data = nfs4_alloc_createdata(dir, &dentry->d_name, sattr, NF4LNK);
3802         if (data == NULL)
3803                 goto out;
3804
3805         data->msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_SYMLINK];
3806         data->arg.u.symlink.pages = &page;
3807         data->arg.u.symlink.len = len;
3808         data->arg.label = label;
3809         
3810         status = nfs4_do_create(dir, dentry, data);
3811
3812         nfs4_free_createdata(data);
3813 out:
3814         return status;
3815 }
3816
3817 static int nfs4_proc_symlink(struct inode *dir, struct dentry *dentry,
3818                 struct page *page, unsigned int len, struct iattr *sattr)
3819 {
3820         struct nfs4_exception exception = { };
3821         struct nfs4_label l, *label = NULL;
3822         int err;
3823
3824         label = nfs4_label_init_security(dir, dentry, sattr, &l);
3825
3826         do {
3827                 err = _nfs4_proc_symlink(dir, dentry, page, len, sattr, label);
3828                 trace_nfs4_symlink(dir, &dentry->d_name, err);
3829                 err = nfs4_handle_exception(NFS_SERVER(dir), err,
3830                                 &exception);
3831         } while (exception.retry);
3832
3833         nfs4_label_release_security(label);
3834         return err;
3835 }
3836
3837 static int _nfs4_proc_mkdir(struct inode *dir, struct dentry *dentry,
3838                 struct iattr *sattr, struct nfs4_label *label)
3839 {
3840         struct nfs4_createdata *data;
3841         int status = -ENOMEM;
3842
3843         data = nfs4_alloc_createdata(dir, &dentry->d_name, sattr, NF4DIR);
3844         if (data == NULL)
3845                 goto out;
3846
3847         data->arg.label = label;
3848         status = nfs4_do_create(dir, dentry, data);
3849
3850         nfs4_free_createdata(data);
3851 out:
3852         return status;
3853 }
3854
3855 static int nfs4_proc_mkdir(struct inode *dir, struct dentry *dentry,
3856                 struct iattr *sattr)
3857 {
3858         struct nfs4_exception exception = { };
3859         struct nfs4_label l, *label = NULL;
3860         int err;
3861
3862         label = nfs4_label_init_security(dir, dentry, sattr, &l);
3863
3864         sattr->ia_mode &= ~current_umask();
3865         do {
3866                 err = _nfs4_proc_mkdir(dir, dentry, sattr, label);
3867                 trace_nfs4_mkdir(dir, &dentry->d_name, err);
3868                 err = nfs4_handle_exception(NFS_SERVER(dir), err,
3869                                 &exception);
3870         } while (exception.retry);
3871         nfs4_label_release_security(label);
3872
3873         return err;
3874 }
3875
3876 static int _nfs4_proc_readdir(struct dentry *dentry, struct rpc_cred *cred,
3877                 u64 cookie, struct page **pages, unsigned int count, int plus)
3878 {
3879         struct inode            *dir = d_inode(dentry);
3880         struct nfs4_readdir_arg args = {
3881                 .fh = NFS_FH(dir),
3882                 .pages = pages,
3883                 .pgbase = 0,
3884                 .count = count,
3885                 .bitmask = NFS_SERVER(d_inode(dentry))->attr_bitmask,
3886                 .plus = plus,
3887         };
3888         struct nfs4_readdir_res res;
3889         struct rpc_message msg = {
3890                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_READDIR],
3891                 .rpc_argp = &args,
3892                 .rpc_resp = &res,
3893                 .rpc_cred = cred,
3894         };
3895         int                     status;
3896
3897         dprintk("%s: dentry = %pd2, cookie = %Lu\n", __func__,
3898                         dentry,
3899                         (unsigned long long)cookie);
3900         nfs4_setup_readdir(cookie, NFS_I(dir)->cookieverf, dentry, &args);
3901         res.pgbase = args.pgbase;
3902         status = nfs4_call_sync(NFS_SERVER(dir)->client, NFS_SERVER(dir), &msg, &args.seq_args, &res.seq_res, 0);
3903         if (status >= 0) {
3904                 memcpy(NFS_I(dir)->cookieverf, res.verifier.data, NFS4_VERIFIER_SIZE);
3905                 status += args.pgbase;
3906         }
3907
3908         nfs_invalidate_atime(dir);
3909
3910         dprintk("%s: returns %d\n", __func__, status);
3911         return status;
3912 }
3913
3914 static int nfs4_proc_readdir(struct dentry *dentry, struct rpc_cred *cred,
3915                 u64 cookie, struct page **pages, unsigned int count, int plus)
3916 {
3917         struct nfs4_exception exception = { };
3918         int err;
3919         do {
3920                 err = _nfs4_proc_readdir(dentry, cred, cookie,
3921                                 pages, count, plus);
3922                 trace_nfs4_readdir(d_inode(dentry), err);
3923                 err = nfs4_handle_exception(NFS_SERVER(d_inode(dentry)), err,
3924                                 &exception);
3925         } while (exception.retry);
3926         return err;
3927 }
3928
3929 static int _nfs4_proc_mknod(struct inode *dir, struct dentry *dentry,
3930                 struct iattr *sattr, struct nfs4_label *label, dev_t rdev)
3931 {
3932         struct nfs4_createdata *data;
3933         int mode = sattr->ia_mode;
3934         int status = -ENOMEM;
3935
3936         data = nfs4_alloc_createdata(dir, &dentry->d_name, sattr, NF4SOCK);
3937         if (data == NULL)
3938                 goto out;
3939
3940         if (S_ISFIFO(mode))
3941                 data->arg.ftype = NF4FIFO;
3942         else if (S_ISBLK(mode)) {
3943                 data->arg.ftype = NF4BLK;
3944                 data->arg.u.device.specdata1 = MAJOR(rdev);
3945                 data->arg.u.device.specdata2 = MINOR(rdev);
3946         }
3947         else if (S_ISCHR(mode)) {
3948                 data->arg.ftype = NF4CHR;
3949                 data->arg.u.device.specdata1 = MAJOR(rdev);
3950                 data->arg.u.device.specdata2 = MINOR(rdev);
3951         } else if (!S_ISSOCK(mode)) {
3952                 status = -EINVAL;
3953                 goto out_free;
3954         }
3955
3956         data->arg.label = label;
3957         status = nfs4_do_create(dir, dentry, data);
3958 out_free:
3959         nfs4_free_createdata(data);
3960 out:
3961         return status;
3962 }
3963
3964 static int nfs4_proc_mknod(struct inode *dir, struct dentry *dentry,
3965                 struct iattr *sattr, dev_t rdev)
3966 {
3967         struct nfs4_exception exception = { };
3968         struct nfs4_label l, *label = NULL;
3969         int err;
3970
3971         label = nfs4_label_init_security(dir, dentry, sattr, &l);
3972
3973         sattr->ia_mode &= ~current_umask();
3974         do {
3975                 err = _nfs4_proc_mknod(dir, dentry, sattr, label, rdev);
3976                 trace_nfs4_mknod(dir, &dentry->d_name, err);
3977                 err = nfs4_handle_exception(NFS_SERVER(dir), err,
3978                                 &exception);
3979         } while (exception.retry);
3980
3981         nfs4_label_release_security(label);
3982
3983         return err;
3984 }
3985
3986 static int _nfs4_proc_statfs(struct nfs_server *server, struct nfs_fh *fhandle,
3987                  struct nfs_fsstat *fsstat)
3988 {
3989         struct nfs4_statfs_arg args = {
3990                 .fh = fhandle,
3991                 .bitmask = server->attr_bitmask,
3992         };
3993         struct nfs4_statfs_res res = {
3994                 .fsstat = fsstat,
3995         };
3996         struct rpc_message msg = {
3997                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_STATFS],
3998                 .rpc_argp = &args,
3999                 .rpc_resp = &res,
4000         };
4001
4002         nfs_fattr_init(fsstat->fattr);
4003         return  nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 0);
4004 }
4005
4006 static int nfs4_proc_statfs(struct nfs_server *server, struct nfs_fh *fhandle, struct nfs_fsstat *fsstat)
4007 {
4008         struct nfs4_exception exception = { };
4009         int err;
4010         do {
4011                 err = nfs4_handle_exception(server,
4012                                 _nfs4_proc_statfs(server, fhandle, fsstat),
4013                                 &exception);
4014         } while (exception.retry);
4015         return err;
4016 }
4017
4018 static int _nfs4_do_fsinfo(struct nfs_server *server, struct nfs_fh *fhandle,
4019                 struct nfs_fsinfo *fsinfo)
4020 {
4021         struct nfs4_fsinfo_arg args = {
4022                 .fh = fhandle,
4023                 .bitmask = server->attr_bitmask,
4024         };
4025         struct nfs4_fsinfo_res res = {
4026                 .fsinfo = fsinfo,
4027         };
4028         struct rpc_message msg = {
4029                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_FSINFO],
4030                 .rpc_argp = &args,
4031                 .rpc_resp = &res,
4032         };
4033
4034         return nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 0);
4035 }
4036
4037 static int nfs4_do_fsinfo(struct nfs_server *server, struct nfs_fh *fhandle, struct nfs_fsinfo *fsinfo)
4038 {
4039         struct nfs4_exception exception = { };
4040         unsigned long now = jiffies;
4041         int err;
4042
4043         do {
4044                 err = _nfs4_do_fsinfo(server, fhandle, fsinfo);
4045                 trace_nfs4_fsinfo(server, fhandle, fsinfo->fattr, err);
4046                 if (err == 0) {
4047                         struct nfs_client *clp = server->nfs_client;
4048
4049                         spin_lock(&clp->cl_lock);
4050                         clp->cl_lease_time = fsinfo->lease_time * HZ;
4051                         clp->cl_last_renewal = now;
4052                         spin_unlock(&clp->cl_lock);
4053                         break;
4054                 }
4055                 err = nfs4_handle_exception(server, err, &exception);
4056         } while (exception.retry);
4057         return err;
4058 }
4059
4060 static int nfs4_proc_fsinfo(struct nfs_server *server, struct nfs_fh *fhandle, struct nfs_fsinfo *fsinfo)
4061 {
4062         int error;
4063
4064         nfs_fattr_init(fsinfo->fattr);
4065         error = nfs4_do_fsinfo(server, fhandle, fsinfo);
4066         if (error == 0) {
4067                 /* block layout checks this! */
4068                 server->pnfs_blksize = fsinfo->blksize;
4069                 set_pnfs_layoutdriver(server, fhandle, fsinfo->layouttype);
4070         }
4071
4072         return error;
4073 }
4074
4075 static int _nfs4_proc_pathconf(struct nfs_server *server, struct nfs_fh *fhandle,
4076                 struct nfs_pathconf *pathconf)
4077 {
4078         struct nfs4_pathconf_arg args = {
4079                 .fh = fhandle,
4080                 .bitmask = server->attr_bitmask,
4081         };
4082         struct nfs4_pathconf_res res = {
4083                 .pathconf = pathconf,
4084         };
4085         struct rpc_message msg = {
4086                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_PATHCONF],
4087                 .rpc_argp = &args,
4088                 .rpc_resp = &res,
4089         };
4090
4091         /* None of the pathconf attributes are mandatory to implement */
4092         if ((args.bitmask[0] & nfs4_pathconf_bitmap[0]) == 0) {
4093                 memset(pathconf, 0, sizeof(*pathconf));
4094                 return 0;
4095         }
4096
4097         nfs_fattr_init(pathconf->fattr);
4098         return nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 0);
4099 }
4100
4101 static int nfs4_proc_pathconf(struct nfs_server *server, struct nfs_fh *fhandle,
4102                 struct nfs_pathconf *pathconf)
4103 {
4104         struct nfs4_exception exception = { };
4105         int err;
4106
4107         do {
4108                 err = nfs4_handle_exception(server,
4109                                 _nfs4_proc_pathconf(server, fhandle, pathconf),
4110                                 &exception);
4111         } while (exception.retry);
4112         return err;
4113 }
4114
4115 int nfs4_set_rw_stateid(nfs4_stateid *stateid,
4116                 const struct nfs_open_context *ctx,
4117                 const struct nfs_lock_context *l_ctx,
4118                 fmode_t fmode)
4119 {
4120         const struct nfs_lockowner *lockowner = NULL;
4121
4122         if (l_ctx != NULL)
4123                 lockowner = &l_ctx->lockowner;
4124         return nfs4_select_rw_stateid(stateid, ctx->state, fmode, lockowner);
4125 }
4126 EXPORT_SYMBOL_GPL(nfs4_set_rw_stateid);
4127
4128 static bool nfs4_stateid_is_current(nfs4_stateid *stateid,
4129                 const struct nfs_open_context *ctx,
4130                 const struct nfs_lock_context *l_ctx,
4131                 fmode_t fmode)
4132 {
4133         nfs4_stateid current_stateid;
4134
4135         /* If the current stateid represents a lost lock, then exit */
4136         if (nfs4_set_rw_stateid(&current_stateid, ctx, l_ctx, fmode) == -EIO)
4137                 return true;
4138         return nfs4_stateid_match(stateid, &current_stateid);
4139 }
4140
4141 static bool nfs4_error_stateid_expired(int err)
4142 {
4143         switch (err) {
4144         case -NFS4ERR_DELEG_REVOKED:
4145         case -NFS4ERR_ADMIN_REVOKED:
4146         case -NFS4ERR_BAD_STATEID:
4147         case -NFS4ERR_STALE_STATEID:
4148         case -NFS4ERR_OLD_STATEID:
4149         case -NFS4ERR_OPENMODE:
4150         case -NFS4ERR_EXPIRED:
4151                 return true;
4152         }
4153         return false;
4154 }
4155
4156 void __nfs4_read_done_cb(struct nfs_pgio_header *hdr)
4157 {
4158         nfs_invalidate_atime(hdr->inode);
4159 }
4160
4161 static int nfs4_read_done_cb(struct rpc_task *task, struct nfs_pgio_header *hdr)
4162 {
4163         struct nfs_server *server = NFS_SERVER(hdr->inode);
4164
4165         trace_nfs4_read(hdr, task->tk_status);
4166         if (nfs4_async_handle_error(task, server,
4167                                     hdr->args.context->state,
4168                                     NULL) == -EAGAIN) {
4169                 rpc_restart_call_prepare(task);
4170                 return -EAGAIN;
4171         }
4172
4173         __nfs4_read_done_cb(hdr);
4174         if (task->tk_status > 0)
4175                 renew_lease(server, hdr->timestamp);
4176         return 0;
4177 }
4178
4179 static bool nfs4_read_stateid_changed(struct rpc_task *task,
4180                 struct nfs_pgio_args *args)
4181 {
4182
4183         if (!nfs4_error_stateid_expired(task->tk_status) ||
4184                 nfs4_stateid_is_current(&args->stateid,
4185                                 args->context,
4186                                 args->lock_context,
4187                                 FMODE_READ))
4188                 return false;
4189         rpc_restart_call_prepare(task);
4190         return true;
4191 }
4192
4193 static int nfs4_read_done(struct rpc_task *task, struct nfs_pgio_header *hdr)
4194 {
4195
4196         dprintk("--> %s\n", __func__);
4197
4198         if (!nfs4_sequence_done(task, &hdr->res.seq_res))
4199                 return -EAGAIN;
4200         if (nfs4_read_stateid_changed(task, &hdr->args))
4201                 return -EAGAIN;
4202         return hdr->pgio_done_cb ? hdr->pgio_done_cb(task, hdr) :
4203                                     nfs4_read_done_cb(task, hdr);
4204 }
4205
4206 static void nfs4_proc_read_setup(struct nfs_pgio_header *hdr,
4207                                  struct rpc_message *msg)
4208 {
4209         hdr->timestamp   = jiffies;
4210         hdr->pgio_done_cb = nfs4_read_done_cb;
4211         msg->rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_READ];
4212         nfs4_init_sequence(&hdr->args.seq_args, &hdr->res.seq_res, 0);
4213 }
4214
4215 static int nfs4_proc_pgio_rpc_prepare(struct rpc_task *task,
4216                                       struct nfs_pgio_header *hdr)
4217 {
4218         if (nfs4_setup_sequence(NFS_SERVER(hdr->inode),
4219                         &hdr->args.seq_args,
4220                         &hdr->res.seq_res,
4221                         task))
4222                 return 0;
4223         if (nfs4_set_rw_stateid(&hdr->args.stateid, hdr->args.context,
4224                                 hdr->args.lock_context,
4225                                 hdr->rw_ops->rw_mode) == -EIO)
4226                 return -EIO;
4227         if (unlikely(test_bit(NFS_CONTEXT_BAD, &hdr->args.context->flags)))
4228                 return -EIO;
4229         return 0;
4230 }
4231
4232 static int nfs4_write_done_cb(struct rpc_task *task,
4233                               struct nfs_pgio_header *hdr)
4234 {
4235         struct inode *inode = hdr->inode;
4236
4237         trace_nfs4_write(hdr, task->tk_status);
4238         if (nfs4_async_handle_error(task, NFS_SERVER(inode),
4239                                     hdr->args.context->state,
4240                                     NULL) == -EAGAIN) {
4241                 rpc_restart_call_prepare(task);
4242                 return -EAGAIN;
4243         }
4244         if (task->tk_status >= 0) {
4245                 renew_lease(NFS_SERVER(inode), hdr->timestamp);
4246                 nfs_writeback_update_inode(hdr);
4247         }
4248         return 0;
4249 }
4250
4251 static bool nfs4_write_stateid_changed(struct rpc_task *task,
4252                 struct nfs_pgio_args *args)
4253 {
4254
4255         if (!nfs4_error_stateid_expired(task->tk_status) ||
4256                 nfs4_stateid_is_current(&args->stateid,
4257                                 args->context,
4258                                 args->lock_context,
4259                                 FMODE_WRITE))
4260                 return false;
4261         rpc_restart_call_prepare(task);
4262         return true;
4263 }
4264
4265 static int nfs4_write_done(struct rpc_task *task, struct nfs_pgio_header *hdr)
4266 {
4267         if (!nfs4_sequence_done(task, &hdr->res.seq_res))
4268                 return -EAGAIN;
4269         if (nfs4_write_stateid_changed(task, &hdr->args))
4270                 return -EAGAIN;
4271         return hdr->pgio_done_cb ? hdr->pgio_done_cb(task, hdr) :
4272                 nfs4_write_done_cb(task, hdr);
4273 }
4274
4275 static
4276 bool nfs4_write_need_cache_consistency_data(struct nfs_pgio_header *hdr)
4277 {
4278         /* Don't request attributes for pNFS or O_DIRECT writes */
4279         if (hdr->ds_clp != NULL || hdr->dreq != NULL)
4280                 return false;
4281         /* Otherwise, request attributes if and only if we don't hold
4282          * a delegation
4283          */
4284         return nfs4_have_delegation(hdr->inode, FMODE_READ) == 0;
4285 }
4286
4287 static void nfs4_proc_write_setup(struct nfs_pgio_header *hdr,
4288                                   struct rpc_message *msg)
4289 {
4290         struct nfs_server *server = NFS_SERVER(hdr->inode);
4291
4292         if (!nfs4_write_need_cache_consistency_data(hdr)) {
4293                 hdr->args.bitmask = NULL;
4294                 hdr->res.fattr = NULL;
4295         } else
4296                 hdr->args.bitmask = server->cache_consistency_bitmask;
4297
4298         if (!hdr->pgio_done_cb)
4299                 hdr->pgio_done_cb = nfs4_write_done_cb;
4300         hdr->res.server = server;
4301         hdr->timestamp   = jiffies;
4302
4303         msg->rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_WRITE];
4304         nfs4_init_sequence(&hdr->args.seq_args, &hdr->res.seq_res, 1);
4305 }
4306
4307 static void nfs4_proc_commit_rpc_prepare(struct rpc_task *task, struct nfs_commit_data *data)
4308 {
4309         nfs4_setup_sequence(NFS_SERVER(data->inode),
4310                         &data->args.seq_args,
4311                         &data->res.seq_res,
4312                         task);
4313 }
4314
4315 static int nfs4_commit_done_cb(struct rpc_task *task, struct nfs_commit_data *data)
4316 {
4317         struct inode *inode = data->inode;
4318
4319         trace_nfs4_commit(data, task->tk_status);
4320         if (nfs4_async_handle_error(task, NFS_SERVER(inode),
4321                                     NULL, NULL) == -EAGAIN) {
4322                 rpc_restart_call_prepare(task);
4323                 return -EAGAIN;
4324         }
4325         return 0;
4326 }
4327
4328 static int nfs4_commit_done(struct rpc_task *task, struct nfs_commit_data *data)
4329 {
4330         if (!nfs4_sequence_done(task, &data->res.seq_res))
4331                 return -EAGAIN;
4332         return data->commit_done_cb(task, data);
4333 }
4334
4335 static void nfs4_proc_commit_setup(struct nfs_commit_data *data, struct rpc_message *msg)
4336 {
4337         struct nfs_server *server = NFS_SERVER(data->inode);
4338
4339         if (data->commit_done_cb == NULL)
4340                 data->commit_done_cb = nfs4_commit_done_cb;
4341         data->res.server = server;
4342         msg->rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_COMMIT];
4343         nfs4_init_sequence(&data->args.seq_args, &data->res.seq_res, 1);
4344 }
4345
4346 struct nfs4_renewdata {
4347         struct nfs_client       *client;
4348         unsigned long           timestamp;
4349 };
4350
4351 /*
4352  * nfs4_proc_async_renew(): This is not one of the nfs_rpc_ops; it is a special
4353  * standalone procedure for queueing an asynchronous RENEW.
4354  */
4355 static void nfs4_renew_release(void *calldata)
4356 {
4357         struct nfs4_renewdata *data = calldata;
4358         struct nfs_client *clp = data->client;
4359
4360         if (atomic_read(&clp->cl_count) > 1)
4361                 nfs4_schedule_state_renewal(clp);
4362         nfs_put_client(clp);
4363         kfree(data);
4364 }
4365
4366 static void nfs4_renew_done(struct rpc_task *task, void *calldata)
4367 {
4368         struct nfs4_renewdata *data = calldata;
4369         struct nfs_client *clp = data->client;
4370         unsigned long timestamp = data->timestamp;
4371
4372         trace_nfs4_renew_async(clp, task->tk_status);
4373         switch (task->tk_status) {
4374         case 0:
4375                 break;
4376         case -NFS4ERR_LEASE_MOVED:
4377                 nfs4_schedule_lease_moved_recovery(clp);
4378                 break;
4379         default:
4380                 /* Unless we're shutting down, schedule state recovery! */
4381                 if (test_bit(NFS_CS_RENEWD, &clp->cl_res_state) == 0)
4382                         return;
4383                 if (task->tk_status != NFS4ERR_CB_PATH_DOWN) {
4384                         nfs4_schedule_lease_recovery(clp);
4385                         return;
4386                 }
4387                 nfs4_schedule_path_down_recovery(clp);
4388         }
4389         do_renew_lease(clp, timestamp);
4390 }
4391
4392 static const struct rpc_call_ops nfs4_renew_ops = {
4393         .rpc_call_done = nfs4_renew_done,
4394         .rpc_release = nfs4_renew_release,
4395 };
4396
4397 static int nfs4_proc_async_renew(struct nfs_client *clp, struct rpc_cred *cred, unsigned renew_flags)
4398 {
4399         struct rpc_message msg = {
4400                 .rpc_proc       = &nfs4_procedures[NFSPROC4_CLNT_RENEW],
4401                 .rpc_argp       = clp,
4402                 .rpc_cred       = cred,
4403         };
4404         struct nfs4_renewdata *data;
4405
4406         if (renew_flags == 0)
4407                 return 0;
4408         if (!atomic_inc_not_zero(&clp->cl_count))
4409                 return -EIO;
4410         data = kmalloc(sizeof(*data), GFP_NOFS);
4411         if (data == NULL)
4412                 return -ENOMEM;
4413         data->client = clp;
4414         data->timestamp = jiffies;
4415         return rpc_call_async(clp->cl_rpcclient, &msg, RPC_TASK_TIMEOUT,
4416                         &nfs4_renew_ops, data);
4417 }
4418
4419 static int nfs4_proc_renew(struct nfs_client *clp, struct rpc_cred *cred)
4420 {
4421         struct rpc_message msg = {
4422                 .rpc_proc       = &nfs4_procedures[NFSPROC4_CLNT_RENEW],
4423                 .rpc_argp       = clp,
4424                 .rpc_cred       = cred,
4425         };
4426         unsigned long now = jiffies;
4427         int status;
4428
4429         status = rpc_call_sync(clp->cl_rpcclient, &msg, RPC_TASK_TIMEOUT);
4430         if (status < 0)
4431                 return status;
4432         do_renew_lease(clp, now);
4433         return 0;
4434 }
4435
4436 static inline int nfs4_server_supports_acls(struct nfs_server *server)
4437 {
4438         return server->caps & NFS_CAP_ACLS;
4439 }
4440
4441 /* Assuming that XATTR_SIZE_MAX is a multiple of PAGE_SIZE, and that
4442  * it's OK to put sizeof(void) * (XATTR_SIZE_MAX/PAGE_SIZE) bytes on
4443  * the stack.
4444  */
4445 #define NFS4ACL_MAXPAGES DIV_ROUND_UP(XATTR_SIZE_MAX, PAGE_SIZE)
4446
4447 static int buf_to_pages_noslab(const void *buf, size_t buflen,
4448                 struct page **pages, unsigned int *pgbase)
4449 {
4450         struct page *newpage, **spages;
4451         int rc = 0;
4452         size_t len;
4453         spages = pages;
4454
4455         do {
4456                 len = min_t(size_t, PAGE_SIZE, buflen);
4457                 newpage = alloc_page(GFP_KERNEL);
4458
4459                 if (newpage == NULL)
4460                         goto unwind;
4461                 memcpy(page_address(newpage), buf, len);
4462                 buf += len;
4463                 buflen -= len;
4464                 *pages++ = newpage;
4465                 rc++;
4466         } while (buflen != 0);
4467
4468         return rc;
4469
4470 unwind:
4471         for(; rc > 0; rc--)
4472                 __free_page(spages[rc-1]);
4473         return -ENOMEM;
4474 }
4475
4476 struct nfs4_cached_acl {
4477         int cached;
4478         size_t len;
4479         char data[0];
4480 };
4481
4482 static void nfs4_set_cached_acl(struct inode *inode, struct nfs4_cached_acl *acl)
4483 {
4484         struct nfs_inode *nfsi = NFS_I(inode);
4485
4486         spin_lock(&inode->i_lock);
4487         kfree(nfsi->nfs4_acl);
4488         nfsi->nfs4_acl = acl;
4489         spin_unlock(&inode->i_lock);
4490 }
4491
4492 static void nfs4_zap_acl_attr(struct inode *inode)
4493 {
4494         nfs4_set_cached_acl(inode, NULL);
4495 }
4496
4497 static inline ssize_t nfs4_read_cached_acl(struct inode *inode, char *buf, size_t buflen)
4498 {
4499         struct nfs_inode *nfsi = NFS_I(inode);
4500         struct nfs4_cached_acl *acl;
4501         int ret = -ENOENT;
4502
4503         spin_lock(&inode->i_lock);
4504         acl = nfsi->nfs4_acl;
4505         if (acl == NULL)
4506                 goto out;
4507         if (buf == NULL) /* user is just asking for length */
4508                 goto out_len;
4509         if (acl->cached == 0)
4510                 goto out;
4511         ret = -ERANGE; /* see getxattr(2) man page */
4512         if (acl->len > buflen)
4513                 goto out;
4514         memcpy(buf, acl->data, acl->len);
4515 out_len:
4516         ret = acl->len;
4517 out:
4518         spin_unlock(&inode->i_lock);
4519         return ret;
4520 }
4521
4522 static void nfs4_write_cached_acl(struct inode *inode, struct page **pages, size_t pgbase, size_t acl_len)
4523 {
4524         struct nfs4_cached_acl *acl;
4525         size_t buflen = sizeof(*acl) + acl_len;
4526
4527         if (buflen <= PAGE_SIZE) {
4528                 acl = kmalloc(buflen, GFP_KERNEL);
4529                 if (acl == NULL)
4530                         goto out;
4531                 acl->cached = 1;
4532                 _copy_from_pages(acl->data, pages, pgbase, acl_len);
4533         } else {
4534                 acl = kmalloc(sizeof(*acl), GFP_KERNEL);
4535                 if (acl == NULL)
4536                         goto out;
4537                 acl->cached = 0;
4538         }
4539         acl->len = acl_len;
4540 out:
4541         nfs4_set_cached_acl(inode, acl);
4542 }
4543
4544 /*
4545  * The getxattr API returns the required buffer length when called with a
4546  * NULL buf. The NFSv4 acl tool then calls getxattr again after allocating
4547  * the required buf.  On a NULL buf, we send a page of data to the server
4548  * guessing that the ACL request can be serviced by a page. If so, we cache
4549  * up to the page of ACL data, and the 2nd call to getxattr is serviced by
4550  * the cache. If not so, we throw away the page, and cache the required
4551  * length. The next getxattr call will then produce another round trip to
4552  * the server, this time with the input buf of the required size.
4553  */
4554 static ssize_t __nfs4_get_acl_uncached(struct inode *inode, void *buf, size_t buflen)
4555 {
4556         struct page *pages[NFS4ACL_MAXPAGES] = {NULL, };
4557         struct nfs_getaclargs args = {
4558                 .fh = NFS_FH(inode),
4559                 .acl_pages = pages,
4560                 .acl_len = buflen,
4561         };
4562         struct nfs_getaclres res = {
4563                 .acl_len = buflen,
4564         };
4565         struct rpc_message msg = {
4566                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETACL],
4567                 .rpc_argp = &args,
4568                 .rpc_resp = &res,
4569         };
4570         unsigned int npages = DIV_ROUND_UP(buflen, PAGE_SIZE);
4571         int ret = -ENOMEM, i;
4572
4573         /* As long as we're doing a round trip to the server anyway,
4574          * let's be prepared for a page of acl data. */
4575         if (npages == 0)
4576                 npages = 1;
4577         if (npages > ARRAY_SIZE(pages))
4578                 return -ERANGE;
4579
4580         for (i = 0; i < npages; i++) {
4581                 pages[i] = alloc_page(GFP_KERNEL);
4582                 if (!pages[i])
4583                         goto out_free;
4584         }
4585
4586         /* for decoding across pages */
4587         res.acl_scratch = alloc_page(GFP_KERNEL);
4588         if (!res.acl_scratch)
4589                 goto out_free;
4590
4591         args.acl_len = npages * PAGE_SIZE;
4592         args.acl_pgbase = 0;
4593
4594         dprintk("%s  buf %p buflen %zu npages %d args.acl_len %zu\n",
4595                 __func__, buf, buflen, npages, args.acl_len);
4596         ret = nfs4_call_sync(NFS_SERVER(inode)->client, NFS_SERVER(inode),
4597                              &msg, &args.seq_args, &res.seq_res, 0);
4598         if (ret)
4599                 goto out_free;
4600
4601         /* Handle the case where the passed-in buffer is too short */
4602         if (res.acl_flags & NFS4_ACL_TRUNC) {
4603                 /* Did the user only issue a request for the acl length? */
4604                 if (buf == NULL)
4605                         goto out_ok;
4606                 ret = -ERANGE;
4607                 goto out_free;
4608         }
4609         nfs4_write_cached_acl(inode, pages, res.acl_data_offset, res.acl_len);
4610         if (buf) {
4611                 if (res.acl_len > buflen) {
4612                         ret = -ERANGE;
4613                         goto out_free;
4614                 }
4615                 _copy_from_pages(buf, pages, res.acl_data_offset, res.acl_len);
4616         }
4617 out_ok:
4618         ret = res.acl_len;
4619 out_free:
4620         for (i = 0; i < npages; i++)
4621                 if (pages[i])
4622                         __free_page(pages[i]);
4623         if (res.acl_scratch)
4624                 __free_page(res.acl_scratch);
4625         return ret;
4626 }
4627
4628 static ssize_t nfs4_get_acl_uncached(struct inode *inode, void *buf, size_t buflen)
4629 {
4630         struct nfs4_exception exception = { };
4631         ssize_t ret;
4632         do {
4633                 ret = __nfs4_get_acl_uncached(inode, buf, buflen);
4634                 trace_nfs4_get_acl(inode, ret);
4635                 if (ret >= 0)
4636                         break;
4637                 ret = nfs4_handle_exception(NFS_SERVER(inode), ret, &exception);
4638         } while (exception.retry);
4639         return ret;
4640 }
4641
4642 static ssize_t nfs4_proc_get_acl(struct inode *inode, void *buf, size_t buflen)
4643 {
4644         struct nfs_server *server = NFS_SERVER(inode);
4645         int ret;
4646
4647         if (!nfs4_server_supports_acls(server))
4648                 return -EOPNOTSUPP;
4649         ret = nfs_revalidate_inode(server, inode);
4650         if (ret < 0)
4651                 return ret;
4652         if (NFS_I(inode)->cache_validity & NFS_INO_INVALID_ACL)
4653                 nfs_zap_acl_cache(inode);
4654         ret = nfs4_read_cached_acl(inode, buf, buflen);
4655         if (ret != -ENOENT)
4656                 /* -ENOENT is returned if there is no ACL or if there is an ACL
4657                  * but no cached acl data, just the acl length */
4658                 return ret;
4659         return nfs4_get_acl_uncached(inode, buf, buflen);
4660 }
4661
4662 static int __nfs4_proc_set_acl(struct inode *inode, const void *buf, size_t buflen)
4663 {
4664         struct nfs_server *server = NFS_SERVER(inode);
4665         struct page *pages[NFS4ACL_MAXPAGES];
4666         struct nfs_setaclargs arg = {
4667                 .fh             = NFS_FH(inode),
4668                 .acl_pages      = pages,
4669                 .acl_len        = buflen,
4670         };
4671         struct nfs_setaclres res;
4672         struct rpc_message msg = {
4673                 .rpc_proc       = &nfs4_procedures[NFSPROC4_CLNT_SETACL],
4674                 .rpc_argp       = &arg,
4675                 .rpc_resp       = &res,
4676         };
4677         unsigned int npages = DIV_ROUND_UP(buflen, PAGE_SIZE);
4678         int ret, i;
4679
4680         if (!nfs4_server_supports_acls(server))
4681                 return -EOPNOTSUPP;
4682         if (npages > ARRAY_SIZE(pages))
4683                 return -ERANGE;
4684         i = buf_to_pages_noslab(buf, buflen, arg.acl_pages, &arg.acl_pgbase);
4685         if (i < 0)
4686                 return i;
4687         nfs4_inode_return_delegation(inode);
4688         ret = nfs4_call_sync(server->client, server, &msg, &arg.seq_args, &res.seq_res, 1);
4689
4690         /*
4691          * Free each page after tx, so the only ref left is
4692          * held by the network stack
4693          */
4694         for (; i > 0; i--)
4695                 put_page(pages[i-1]);
4696
4697         /*
4698          * Acl update can result in inode attribute update.
4699          * so mark the attribute cache invalid.
4700          */
4701         spin_lock(&inode->i_lock);
4702         NFS_I(inode)->cache_validity |= NFS_INO_INVALID_ATTR;
4703         spin_unlock(&inode->i_lock);
4704         nfs_access_zap_cache(inode);
4705         nfs_zap_acl_cache(inode);
4706         return ret;
4707 }
4708
4709 static int nfs4_proc_set_acl(struct inode *inode, const void *buf, size_t buflen)
4710 {
4711         struct nfs4_exception exception = { };
4712         int err;
4713         do {
4714                 err = __nfs4_proc_set_acl(inode, buf, buflen);
4715                 trace_nfs4_set_acl(inode, err);
4716                 err = nfs4_handle_exception(NFS_SERVER(inode), err,
4717                                 &exception);
4718         } while (exception.retry);
4719         return err;
4720 }
4721
4722 #ifdef CONFIG_NFS_V4_SECURITY_LABEL
4723 static int _nfs4_get_security_label(struct inode *inode, void *buf,
4724                                         size_t buflen)
4725 {
4726         struct nfs_server *server = NFS_SERVER(inode);
4727         struct nfs_fattr fattr;
4728         struct nfs4_label label = {0, 0, buflen, buf};
4729
4730         u32 bitmask[3] = { 0, 0, FATTR4_WORD2_SECURITY_LABEL };
4731         struct nfs4_getattr_arg arg = {
4732                 .fh             = NFS_FH(inode),
4733                 .bitmask        = bitmask,
4734         };
4735         struct nfs4_getattr_res res = {
4736                 .fattr          = &fattr,
4737                 .label          = &label,
4738                 .server         = server,
4739         };
4740         struct rpc_message msg = {
4741                 .rpc_proc       = &nfs4_procedures[NFSPROC4_CLNT_GETATTR],
4742                 .rpc_argp       = &arg,
4743                 .rpc_resp       = &res,
4744         };
4745         int ret;
4746
4747         nfs_fattr_init(&fattr);
4748
4749         ret = nfs4_call_sync(server->client, server, &msg, &arg.seq_args, &res.seq_res, 0);
4750         if (ret)
4751                 return ret;
4752         if (!(fattr.valid & NFS_ATTR_FATTR_V4_SECURITY_LABEL))
4753                 return -ENOENT;
4754         if (buflen < label.len)
4755                 return -ERANGE;
4756         return 0;
4757 }
4758
4759 static int nfs4_get_security_label(struct inode *inode, void *buf,
4760                                         size_t buflen)
4761 {
4762         struct nfs4_exception exception = { };
4763         int err;
4764
4765         if (!nfs_server_capable(inode, NFS_CAP_SECURITY_LABEL))
4766                 return -EOPNOTSUPP;
4767
4768         do {
4769                 err = _nfs4_get_security_label(inode, buf, buflen);
4770                 trace_nfs4_get_security_label(inode, err);
4771                 err = nfs4_handle_exception(NFS_SERVER(inode), err,
4772                                 &exception);
4773         } while (exception.retry);
4774         return err;
4775 }
4776
4777 static int _nfs4_do_set_security_label(struct inode *inode,
4778                 struct nfs4_label *ilabel,
4779                 struct nfs_fattr *fattr,
4780                 struct nfs4_label *olabel)
4781 {
4782
4783         struct iattr sattr = {0};
4784         struct nfs_server *server = NFS_SERVER(inode);
4785         const u32 bitmask[3] = { 0, 0, FATTR4_WORD2_SECURITY_LABEL };
4786         struct nfs_setattrargs arg = {
4787                 .fh             = NFS_FH(inode),
4788                 .iap            = &sattr,
4789                 .server         = server,
4790                 .bitmask        = bitmask,
4791                 .label          = ilabel,
4792         };
4793         struct nfs_setattrres res = {
4794                 .fattr          = fattr,
4795                 .label          = olabel,
4796                 .server         = server,
4797         };
4798         struct rpc_message msg = {
4799                 .rpc_proc       = &nfs4_procedures[NFSPROC4_CLNT_SETATTR],
4800                 .rpc_argp       = &arg,
4801                 .rpc_resp       = &res,
4802         };
4803         int status;
4804
4805         nfs4_stateid_copy(&arg.stateid, &zero_stateid);
4806
4807         status = nfs4_call_sync(server->client, server, &msg, &arg.seq_args, &res.seq_res, 1);
4808         if (status)
4809                 dprintk("%s failed: %d\n", __func__, status);
4810
4811         return status;
4812 }
4813
4814 static int nfs4_do_set_security_label(struct inode *inode,
4815                 struct nfs4_label *ilabel,
4816                 struct nfs_fattr *fattr,
4817                 struct nfs4_label *olabel)
4818 {
4819         struct nfs4_exception exception = { };
4820         int err;
4821
4822         do {
4823                 err = _nfs4_do_set_security_label(inode, ilabel,
4824                                 fattr, olabel);
4825                 trace_nfs4_set_security_label(inode, err);
4826                 err = nfs4_handle_exception(NFS_SERVER(inode), err,
4827                                 &exception);
4828         } while (exception.retry);
4829         return err;
4830 }
4831
4832 static int
4833 nfs4_set_security_label(struct dentry *dentry, const void *buf, size_t buflen)
4834 {
4835         struct nfs4_label ilabel, *olabel = NULL;
4836         struct nfs_fattr fattr;
4837         struct rpc_cred *cred;
4838         struct inode *inode = d_inode(dentry);
4839         int status;
4840
4841         if (!nfs_server_capable(inode, NFS_CAP_SECURITY_LABEL))
4842                 return -EOPNOTSUPP;
4843
4844         nfs_fattr_init(&fattr);
4845
4846         ilabel.pi = 0;
4847         ilabel.lfs = 0;
4848         ilabel.label = (char *)buf;
4849         ilabel.len = buflen;
4850
4851         cred = rpc_lookup_cred();
4852         if (IS_ERR(cred))
4853                 return PTR_ERR(cred);
4854
4855         olabel = nfs4_label_alloc(NFS_SERVER(inode), GFP_KERNEL);
4856         if (IS_ERR(olabel)) {
4857                 status = -PTR_ERR(olabel);
4858                 goto out;
4859         }
4860
4861         status = nfs4_do_set_security_label(inode, &ilabel, &fattr, olabel);
4862         if (status == 0)
4863                 nfs_setsecurity(inode, &fattr, olabel);
4864
4865         nfs4_label_free(olabel);
4866 out:
4867         put_rpccred(cred);
4868         return status;
4869 }
4870 #endif  /* CONFIG_NFS_V4_SECURITY_LABEL */
4871
4872
4873 static int
4874 nfs4_async_handle_error(struct rpc_task *task, const struct nfs_server *server,
4875                         struct nfs4_state *state, long *timeout)
4876 {
4877         struct nfs_client *clp = server->nfs_client;
4878
4879         if (task->tk_status >= 0)
4880                 return 0;
4881         switch(task->tk_status) {
4882                 case -NFS4ERR_DELEG_REVOKED:
4883                 case -NFS4ERR_ADMIN_REVOKED:
4884                 case -NFS4ERR_BAD_STATEID:
4885                 case -NFS4ERR_OPENMODE:
4886                         if (state == NULL)
4887                                 break;
4888                         if (nfs4_schedule_stateid_recovery(server, state) < 0)
4889                                 goto recovery_failed;
4890                         goto wait_on_recovery;
4891                 case -NFS4ERR_EXPIRED:
4892                         if (state != NULL) {
4893                                 if (nfs4_schedule_stateid_recovery(server, state) < 0)
4894                                         goto recovery_failed;
4895                         }
4896                 case -NFS4ERR_STALE_STATEID:
4897                 case -NFS4ERR_STALE_CLIENTID:
4898                         nfs4_schedule_lease_recovery(clp);
4899                         goto wait_on_recovery;
4900                 case -NFS4ERR_MOVED:
4901                         if (nfs4_schedule_migration_recovery(server) < 0)
4902                                 goto recovery_failed;
4903                         goto wait_on_recovery;
4904                 case -NFS4ERR_LEASE_MOVED:
4905                         nfs4_schedule_lease_moved_recovery(clp);
4906                         goto wait_on_recovery;
4907 #if defined(CONFIG_NFS_V4_1)
4908                 case -NFS4ERR_BADSESSION:
4909                 case -NFS4ERR_BADSLOT:
4910                 case -NFS4ERR_BAD_HIGH_SLOT:
4911                 case -NFS4ERR_DEADSESSION:
4912                 case -NFS4ERR_CONN_NOT_BOUND_TO_SESSION:
4913                 case -NFS4ERR_SEQ_FALSE_RETRY:
4914                 case -NFS4ERR_SEQ_MISORDERED:
4915                         dprintk("%s ERROR %d, Reset session\n", __func__,
4916                                 task->tk_status);
4917                         nfs4_schedule_session_recovery(clp->cl_session, task->tk_status);
4918                         goto wait_on_recovery;
4919 #endif /* CONFIG_NFS_V4_1 */
4920                 case -NFS4ERR_DELAY:
4921                         nfs_inc_server_stats(server, NFSIOS_DELAY);
4922                         rpc_delay(task, nfs4_update_delay(timeout));
4923                         goto restart_call;
4924                 case -NFS4ERR_GRACE:
4925                         rpc_delay(task, NFS4_POLL_RETRY_MAX);
4926                 case -NFS4ERR_RETRY_UNCACHED_REP:
4927                 case -NFS4ERR_OLD_STATEID:
4928                         goto restart_call;
4929         }
4930         task->tk_status = nfs4_map_errors(task->tk_status);
4931         return 0;
4932 recovery_failed:
4933         task->tk_status = -EIO;
4934         return 0;
4935 wait_on_recovery:
4936         rpc_sleep_on(&clp->cl_rpcwaitq, task, NULL);
4937         if (test_bit(NFS4CLNT_MANAGER_RUNNING, &clp->cl_state) == 0)
4938                 rpc_wake_up_queued_task(&clp->cl_rpcwaitq, task);
4939         if (test_bit(NFS_MIG_FAILED, &server->mig_status))
4940                 goto recovery_failed;
4941 restart_call:
4942         task->tk_status = 0;
4943         return -EAGAIN;
4944 }
4945
4946 static void nfs4_init_boot_verifier(const struct nfs_client *clp,
4947                                     nfs4_verifier *bootverf)
4948 {
4949         __be32 verf[2];
4950
4951         if (test_bit(NFS4CLNT_PURGE_STATE, &clp->cl_state)) {
4952                 /* An impossible timestamp guarantees this value
4953                  * will never match a generated boot time. */
4954                 verf[0] = 0;
4955                 verf[1] = cpu_to_be32(NSEC_PER_SEC + 1);
4956         } else {
4957                 struct nfs_net *nn = net_generic(clp->cl_net, nfs_net_id);
4958                 verf[0] = cpu_to_be32(nn->boot_time.tv_sec);
4959                 verf[1] = cpu_to_be32(nn->boot_time.tv_nsec);
4960         }
4961         memcpy(bootverf->data, verf, sizeof(bootverf->data));
4962 }
4963
4964 static int
4965 nfs4_init_nonuniform_client_string(struct nfs_client *clp)
4966 {
4967         int result;
4968         size_t len;
4969         char *str;
4970         bool retried = false;
4971
4972         if (clp->cl_owner_id != NULL)
4973                 return 0;
4974 retry:
4975         rcu_read_lock();
4976         len = 10 + strlen(clp->cl_ipaddr) + 1 +
4977                 strlen(rpc_peeraddr2str(clp->cl_rpcclient, RPC_DISPLAY_ADDR)) +
4978                 1 +
4979                 strlen(rpc_peeraddr2str(clp->cl_rpcclient, RPC_DISPLAY_PROTO)) +
4980                 1;
4981         rcu_read_unlock();
4982
4983         if (len > NFS4_OPAQUE_LIMIT + 1)
4984                 return -EINVAL;
4985
4986         /*
4987          * Since this string is allocated at mount time, and held until the
4988          * nfs_client is destroyed, we can use GFP_KERNEL here w/o worrying
4989          * about a memory-reclaim deadlock.
4990          */
4991         str = kmalloc(len, GFP_KERNEL);
4992         if (!str)
4993                 return -ENOMEM;
4994
4995         rcu_read_lock();
4996         result = scnprintf(str, len, "Linux NFSv4.0 %s/%s %s",
4997                         clp->cl_ipaddr,
4998                         rpc_peeraddr2str(clp->cl_rpcclient, RPC_DISPLAY_ADDR),
4999                         rpc_peeraddr2str(clp->cl_rpcclient, RPC_DISPLAY_PROTO));
5000         rcu_read_unlock();
5001
5002         /* Did something change? */
5003         if (result >= len) {
5004                 kfree(str);
5005                 if (retried)
5006                         return -EINVAL;
5007                 retried = true;
5008                 goto retry;
5009         }
5010         clp->cl_owner_id = str;
5011         return 0;
5012 }
5013
5014 static int
5015 nfs4_init_uniquifier_client_string(struct nfs_client *clp)
5016 {
5017         int result;
5018         size_t len;
5019         char *str;
5020
5021         len = 10 + 10 + 1 + 10 + 1 +
5022                 strlen(nfs4_client_id_uniquifier) + 1 +
5023                 strlen(clp->cl_rpcclient->cl_nodename) + 1;
5024
5025         if (len > NFS4_OPAQUE_LIMIT + 1)
5026                 return -EINVAL;
5027
5028         /*
5029          * Since this string is allocated at mount time, and held until the
5030          * nfs_client is destroyed, we can use GFP_KERNEL here w/o worrying
5031          * about a memory-reclaim deadlock.
5032          */
5033         str = kmalloc(len, GFP_KERNEL);
5034         if (!str)
5035                 return -ENOMEM;
5036
5037         result = scnprintf(str, len, "Linux NFSv%u.%u %s/%s",
5038                         clp->rpc_ops->version, clp->cl_minorversion,
5039                         nfs4_client_id_uniquifier,
5040                         clp->cl_rpcclient->cl_nodename);
5041         if (result >= len) {
5042                 kfree(str);
5043                 return -EINVAL;
5044         }
5045         clp->cl_owner_id = str;
5046         return 0;
5047 }
5048
5049 static int
5050 nfs4_init_uniform_client_string(struct nfs_client *clp)
5051 {
5052         int result;
5053         size_t len;
5054         char *str;
5055
5056         if (clp->cl_owner_id != NULL)
5057                 return 0;
5058
5059         if (nfs4_client_id_uniquifier[0] != '\0')
5060                 return nfs4_init_uniquifier_client_string(clp);
5061
5062         len = 10 + 10 + 1 + 10 + 1 +
5063                 strlen(clp->cl_rpcclient->cl_nodename) + 1;
5064
5065         if (len > NFS4_OPAQUE_LIMIT + 1)
5066                 return -EINVAL;
5067
5068         /*
5069          * Since this string is allocated at mount time, and held until the
5070          * nfs_client is destroyed, we can use GFP_KERNEL here w/o worrying
5071          * about a memory-reclaim deadlock.
5072          */
5073         str = kmalloc(len, GFP_KERNEL);
5074         if (!str)
5075                 return -ENOMEM;
5076
5077         result = scnprintf(str, len, "Linux NFSv%u.%u %s",
5078                         clp->rpc_ops->version, clp->cl_minorversion,
5079                         clp->cl_rpcclient->cl_nodename);
5080         if (result >= len) {
5081                 kfree(str);
5082                 return -EINVAL;
5083         }
5084         clp->cl_owner_id = str;
5085         return 0;
5086 }
5087
5088 /*
5089  * nfs4_callback_up_net() starts only "tcp" and "tcp6" callback
5090  * services.  Advertise one based on the address family of the
5091  * clientaddr.
5092  */
5093 static unsigned int
5094 nfs4_init_callback_netid(const struct nfs_client *clp, char *buf, size_t len)
5095 {
5096         if (strchr(clp->cl_ipaddr, ':') != NULL)
5097                 return scnprintf(buf, len, "tcp6");
5098         else
5099                 return scnprintf(buf, len, "tcp");
5100 }
5101
5102 static void nfs4_setclientid_done(struct rpc_task *task, void *calldata)
5103 {
5104         struct nfs4_setclientid *sc = calldata;
5105
5106         if (task->tk_status == 0)
5107                 sc->sc_cred = get_rpccred(task->tk_rqstp->rq_cred);
5108 }
5109
5110 static const struct rpc_call_ops nfs4_setclientid_ops = {
5111         .rpc_call_done = nfs4_setclientid_done,
5112 };
5113
5114 /**
5115  * nfs4_proc_setclientid - Negotiate client ID
5116  * @clp: state data structure
5117  * @program: RPC program for NFSv4 callback service
5118  * @port: IP port number for NFS4 callback service
5119  * @cred: RPC credential to use for this call
5120  * @res: where to place the result
5121  *
5122  * Returns zero, a negative errno, or a negative NFS4ERR status code.
5123  */
5124 int nfs4_proc_setclientid(struct nfs_client *clp, u32 program,
5125                 unsigned short port, struct rpc_cred *cred,
5126                 struct nfs4_setclientid_res *res)
5127 {
5128         nfs4_verifier sc_verifier;
5129         struct nfs4_setclientid setclientid = {
5130                 .sc_verifier = &sc_verifier,
5131                 .sc_prog = program,
5132                 .sc_clnt = clp,
5133         };
5134         struct rpc_message msg = {
5135                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_SETCLIENTID],
5136                 .rpc_argp = &setclientid,
5137                 .rpc_resp = res,
5138                 .rpc_cred = cred,
5139         };
5140         struct rpc_task *task;
5141         struct rpc_task_setup task_setup_data = {
5142                 .rpc_client = clp->cl_rpcclient,
5143                 .rpc_message = &msg,
5144                 .callback_ops = &nfs4_setclientid_ops,
5145                 .callback_data = &setclientid,
5146                 .flags = RPC_TASK_TIMEOUT,
5147         };
5148         int status;
5149
5150         /* nfs_client_id4 */
5151         nfs4_init_boot_verifier(clp, &sc_verifier);
5152
5153         if (test_bit(NFS_CS_MIGRATION, &clp->cl_flags))
5154                 status = nfs4_init_uniform_client_string(clp);
5155         else
5156                 status = nfs4_init_nonuniform_client_string(clp);
5157
5158         if (status)
5159                 goto out;
5160
5161         /* cb_client4 */
5162         setclientid.sc_netid_len =
5163                                 nfs4_init_callback_netid(clp,
5164                                                 setclientid.sc_netid,
5165                                                 sizeof(setclientid.sc_netid));
5166         setclientid.sc_uaddr_len = scnprintf(setclientid.sc_uaddr,
5167                                 sizeof(setclientid.sc_uaddr), "%s.%u.%u",
5168                                 clp->cl_ipaddr, port >> 8, port & 255);
5169
5170         dprintk("NFS call  setclientid auth=%s, '%s'\n",
5171                 clp->cl_rpcclient->cl_auth->au_ops->au_name,
5172                 clp->cl_owner_id);
5173         task = rpc_run_task(&task_setup_data);
5174         if (IS_ERR(task)) {
5175                 status = PTR_ERR(task);
5176                 goto out;
5177         }
5178         status = task->tk_status;
5179         if (setclientid.sc_cred) {
5180                 clp->cl_acceptor = rpcauth_stringify_acceptor(setclientid.sc_cred);
5181                 put_rpccred(setclientid.sc_cred);
5182         }
5183         rpc_put_task(task);
5184 out:
5185         trace_nfs4_setclientid(clp, status);
5186         dprintk("NFS reply setclientid: %d\n", status);
5187         return status;
5188 }
5189
5190 /**
5191  * nfs4_proc_setclientid_confirm - Confirm client ID
5192  * @clp: state data structure
5193  * @res: result of a previous SETCLIENTID
5194  * @cred: RPC credential to use for this call
5195  *
5196  * Returns zero, a negative errno, or a negative NFS4ERR status code.
5197  */
5198 int nfs4_proc_setclientid_confirm(struct nfs_client *clp,
5199                 struct nfs4_setclientid_res *arg,
5200                 struct rpc_cred *cred)
5201 {
5202         struct rpc_message msg = {
5203                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_SETCLIENTID_CONFIRM],
5204                 .rpc_argp = arg,
5205                 .rpc_cred = cred,
5206         };
5207         int status;
5208
5209         dprintk("NFS call  setclientid_confirm auth=%s, (client ID %llx)\n",
5210                 clp->cl_rpcclient->cl_auth->au_ops->au_name,
5211                 clp->cl_clientid);
5212         status = rpc_call_sync(clp->cl_rpcclient, &msg, RPC_TASK_TIMEOUT);
5213         trace_nfs4_setclientid_confirm(clp, status);
5214         dprintk("NFS reply setclientid_confirm: %d\n", status);
5215         return status;
5216 }
5217
5218 struct nfs4_delegreturndata {
5219         struct nfs4_delegreturnargs args;
5220         struct nfs4_delegreturnres res;
5221         struct nfs_fh fh;
5222         nfs4_stateid stateid;
5223         unsigned long timestamp;
5224         struct nfs_fattr fattr;
5225         int rpc_status;
5226         struct inode *inode;
5227         bool roc;
5228         u32 roc_barrier;
5229 };
5230
5231 static void nfs4_delegreturn_done(struct rpc_task *task, void *calldata)
5232 {
5233         struct nfs4_delegreturndata *data = calldata;
5234
5235         if (!nfs4_sequence_done(task, &data->res.seq_res))
5236                 return;
5237
5238         trace_nfs4_delegreturn_exit(&data->args, &data->res, task->tk_status);
5239         switch (task->tk_status) {
5240         case 0:
5241                 renew_lease(data->res.server, data->timestamp);
5242         case -NFS4ERR_ADMIN_REVOKED:
5243         case -NFS4ERR_DELEG_REVOKED:
5244         case -NFS4ERR_BAD_STATEID:
5245         case -NFS4ERR_OLD_STATEID:
5246         case -NFS4ERR_STALE_STATEID:
5247         case -NFS4ERR_EXPIRED:
5248                 task->tk_status = 0;
5249                 if (data->roc)
5250                         pnfs_roc_set_barrier(data->inode, data->roc_barrier);
5251                 break;
5252         default:
5253                 if (nfs4_async_handle_error(task, data->res.server,
5254                                             NULL, NULL) == -EAGAIN) {
5255                         rpc_restart_call_prepare(task);
5256                         return;
5257                 }
5258         }
5259         data->rpc_status = task->tk_status;
5260 }
5261
5262 static void nfs4_delegreturn_release(void *calldata)
5263 {
5264         struct nfs4_delegreturndata *data = calldata;
5265         struct inode *inode = data->inode;
5266
5267         if (inode) {
5268                 if (data->roc)
5269                         pnfs_roc_release(inode);
5270                 nfs_iput_and_deactive(inode);
5271         }
5272         kfree(calldata);
5273 }
5274
5275 static void nfs4_delegreturn_prepare(struct rpc_task *task, void *data)
5276 {
5277         struct nfs4_delegreturndata *d_data;
5278
5279         d_data = (struct nfs4_delegreturndata *)data;
5280
5281         if (d_data->roc &&
5282             pnfs_roc_drain(d_data->inode, &d_data->roc_barrier, task))
5283                 return;
5284
5285         nfs4_setup_sequence(d_data->res.server,
5286                         &d_data->args.seq_args,
5287                         &d_data->res.seq_res,
5288                         task);
5289 }
5290
5291 static const struct rpc_call_ops nfs4_delegreturn_ops = {
5292         .rpc_call_prepare = nfs4_delegreturn_prepare,
5293         .rpc_call_done = nfs4_delegreturn_done,
5294         .rpc_release = nfs4_delegreturn_release,
5295 };
5296
5297 static int _nfs4_proc_delegreturn(struct inode *inode, struct rpc_cred *cred, const nfs4_stateid *stateid, int issync)
5298 {
5299         struct nfs4_delegreturndata *data;
5300         struct nfs_server *server = NFS_SERVER(inode);
5301         struct rpc_task *task;
5302         struct rpc_message msg = {
5303                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_DELEGRETURN],
5304                 .rpc_cred = cred,
5305         };
5306         struct rpc_task_setup task_setup_data = {
5307                 .rpc_client = server->client,
5308                 .rpc_message = &msg,
5309                 .callback_ops = &nfs4_delegreturn_ops,
5310                 .flags = RPC_TASK_ASYNC,
5311         };
5312         int status = 0;
5313
5314         data = kzalloc(sizeof(*data), GFP_NOFS);
5315         if (data == NULL)
5316                 return -ENOMEM;
5317         nfs4_init_sequence(&data->args.seq_args, &data->res.seq_res, 1);
5318         data->args.fhandle = &data->fh;
5319         data->args.stateid = &data->stateid;
5320         data->args.bitmask = server->cache_consistency_bitmask;
5321         nfs_copy_fh(&data->fh, NFS_FH(inode));
5322         nfs4_stateid_copy(&data->stateid, stateid);
5323         data->res.fattr = &data->fattr;
5324         data->res.server = server;
5325         nfs_fattr_init(data->res.fattr);
5326         data->timestamp = jiffies;
5327         data->rpc_status = 0;
5328         data->inode = nfs_igrab_and_active(inode);
5329         if (data->inode)
5330                 data->roc = nfs4_roc(inode);
5331
5332         task_setup_data.callback_data = data;
5333         msg.rpc_argp = &data->args;
5334         msg.rpc_resp = &data->res;
5335         task = rpc_run_task(&task_setup_data);
5336         if (IS_ERR(task))
5337                 return PTR_ERR(task);
5338         if (!issync)
5339                 goto out;
5340         status = nfs4_wait_for_completion_rpc_task(task);
5341         if (status != 0)
5342                 goto out;
5343         status = data->rpc_status;
5344         if (status == 0)
5345                 nfs_post_op_update_inode_force_wcc(inode, &data->fattr);
5346         else
5347                 nfs_refresh_inode(inode, &data->fattr);
5348 out:
5349         rpc_put_task(task);
5350         return status;
5351 }
5352
5353 int nfs4_proc_delegreturn(struct inode *inode, struct rpc_cred *cred, const nfs4_stateid *stateid, int issync)
5354 {
5355         struct nfs_server *server = NFS_SERVER(inode);
5356         struct nfs4_exception exception = { };
5357         int err;
5358         do {
5359                 err = _nfs4_proc_delegreturn(inode, cred, stateid, issync);
5360                 trace_nfs4_delegreturn(inode, err);
5361                 switch (err) {
5362                         case -NFS4ERR_STALE_STATEID:
5363                         case -NFS4ERR_EXPIRED:
5364                         case 0:
5365                                 return 0;
5366                 }
5367                 err = nfs4_handle_exception(server, err, &exception);
5368         } while (exception.retry);
5369         return err;
5370 }
5371
5372 #define NFS4_LOCK_MINTIMEOUT (1 * HZ)
5373 #define NFS4_LOCK_MAXTIMEOUT (30 * HZ)
5374
5375 /* 
5376  * sleep, with exponential backoff, and retry the LOCK operation. 
5377  */
5378 static unsigned long
5379 nfs4_set_lock_task_retry(unsigned long timeout)
5380 {
5381         freezable_schedule_timeout_killable_unsafe(timeout);
5382         timeout <<= 1;
5383         if (timeout > NFS4_LOCK_MAXTIMEOUT)
5384                 return NFS4_LOCK_MAXTIMEOUT;
5385         return timeout;
5386 }
5387
5388 static int _nfs4_proc_getlk(struct nfs4_state *state, int cmd, struct file_lock *request)
5389 {
5390         struct inode *inode = state->inode;
5391         struct nfs_server *server = NFS_SERVER(inode);
5392         struct nfs_client *clp = server->nfs_client;
5393         struct nfs_lockt_args arg = {
5394                 .fh = NFS_FH(inode),
5395                 .fl = request,
5396         };
5397         struct nfs_lockt_res res = {
5398                 .denied = request,
5399         };
5400         struct rpc_message msg = {
5401                 .rpc_proc       = &nfs4_procedures[NFSPROC4_CLNT_LOCKT],
5402                 .rpc_argp       = &arg,
5403                 .rpc_resp       = &res,
5404                 .rpc_cred       = state->owner->so_cred,
5405         };
5406         struct nfs4_lock_state *lsp;
5407         int status;
5408
5409         arg.lock_owner.clientid = clp->cl_clientid;
5410         status = nfs4_set_lock_state(state, request);
5411         if (status != 0)
5412                 goto out;
5413         lsp = request->fl_u.nfs4_fl.owner;
5414         arg.lock_owner.id = lsp->ls_seqid.owner_id;
5415         arg.lock_owner.s_dev = server->s_dev;
5416         status = nfs4_call_sync(server->client, server, &msg, &arg.seq_args, &res.seq_res, 1);
5417         switch (status) {
5418                 case 0:
5419                         request->fl_type = F_UNLCK;
5420                         break;
5421                 case -NFS4ERR_DENIED:
5422                         status = 0;
5423         }
5424         request->fl_ops->fl_release_private(request);
5425         request->fl_ops = NULL;
5426 out:
5427         return status;
5428 }
5429
5430 static int nfs4_proc_getlk(struct nfs4_state *state, int cmd, struct file_lock *request)
5431 {
5432         struct nfs4_exception exception = { };
5433         int err;
5434
5435         do {
5436                 err = _nfs4_proc_getlk(state, cmd, request);
5437                 trace_nfs4_get_lock(request, state, cmd, err);
5438                 err = nfs4_handle_exception(NFS_SERVER(state->inode), err,
5439                                 &exception);
5440         } while (exception.retry);
5441         return err;
5442 }
5443
5444 static int do_vfs_lock(struct file *file, struct file_lock *fl)
5445 {
5446         int res = 0;
5447         switch (fl->fl_flags & (FL_POSIX|FL_FLOCK)) {
5448                 case FL_POSIX:
5449                         res = posix_lock_file_wait(file, fl);
5450                         break;
5451                 case FL_FLOCK:
5452                         res = flock_lock_file_wait(file, fl);
5453                         break;
5454                 default:
5455                         BUG();
5456         }
5457         return res;
5458 }
5459
5460 struct nfs4_unlockdata {
5461         struct nfs_locku_args arg;
5462         struct nfs_locku_res res;
5463         struct nfs4_lock_state *lsp;
5464         struct nfs_open_context *ctx;
5465         struct file_lock fl;
5466         const struct nfs_server *server;
5467         unsigned long timestamp;
5468 };
5469
5470 static struct nfs4_unlockdata *nfs4_alloc_unlockdata(struct file_lock *fl,
5471                 struct nfs_open_context *ctx,
5472                 struct nfs4_lock_state *lsp,
5473                 struct nfs_seqid *seqid)
5474 {
5475         struct nfs4_unlockdata *p;
5476         struct inode *inode = lsp->ls_state->inode;
5477
5478         p = kzalloc(sizeof(*p), GFP_NOFS);
5479         if (p == NULL)
5480                 return NULL;
5481         p->arg.fh = NFS_FH(inode);
5482         p->arg.fl = &p->fl;
5483         p->arg.seqid = seqid;
5484         p->res.seqid = seqid;
5485         p->lsp = lsp;
5486         atomic_inc(&lsp->ls_count);
5487         /* Ensure we don't close file until we're done freeing locks! */
5488         p->ctx = get_nfs_open_context(ctx);
5489         get_file(fl->fl_file);
5490         memcpy(&p->fl, fl, sizeof(p->fl));
5491         p->server = NFS_SERVER(inode);
5492         return p;
5493 }
5494
5495 static void nfs4_locku_release_calldata(void *data)
5496 {
5497         struct nfs4_unlockdata *calldata = data;
5498         nfs_free_seqid(calldata->arg.seqid);
5499         nfs4_put_lock_state(calldata->lsp);
5500         put_nfs_open_context(calldata->ctx);
5501         fput(calldata->fl.fl_file);
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_impl_id;
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                 res.impl_id = NULL;
7006
7007                 if (clp->cl_serverscope != NULL &&
7008                     !nfs41_same_server_scope(clp->cl_serverscope,
7009                                              res.server_scope)) {
7010                         dprintk("%s: server_scope mismatch detected\n",
7011                                 __func__);
7012                         set_bit(NFS4CLNT_SERVER_SCOPE_MISMATCH, &clp->cl_state);
7013                         kfree(clp->cl_serverscope);
7014                         clp->cl_serverscope = NULL;
7015                 }
7016
7017                 if (clp->cl_serverscope == NULL) {
7018                         clp->cl_serverscope = res.server_scope;
7019                         res.server_scope = NULL;
7020                 }
7021         }
7022
7023 out_impl_id:
7024         kfree(res.impl_id);
7025 out_server_scope:
7026         kfree(res.server_scope);
7027 out_server_owner:
7028         kfree(res.server_owner);
7029 out:
7030         if (clp->cl_implid != NULL)
7031                 dprintk("NFS reply exchange_id: Server Implementation ID: "
7032                         "domain: %s, name: %s, date: %llu,%u\n",
7033                         clp->cl_implid->domain, clp->cl_implid->name,
7034                         clp->cl_implid->date.seconds,
7035                         clp->cl_implid->date.nseconds);
7036         dprintk("NFS reply exchange_id: %d\n", status);
7037         return status;
7038 }
7039
7040 /*
7041  * nfs4_proc_exchange_id()
7042  *
7043  * Returns zero, a negative errno, or a negative NFS4ERR status code.
7044  *
7045  * Since the clientid has expired, all compounds using sessions
7046  * associated with the stale clientid will be returning
7047  * NFS4ERR_BADSESSION in the sequence operation, and will therefore
7048  * be in some phase of session reset.
7049  *
7050  * Will attempt to negotiate SP4_MACH_CRED if krb5i / krb5p auth is used.
7051  */
7052 int nfs4_proc_exchange_id(struct nfs_client *clp, struct rpc_cred *cred)
7053 {
7054         rpc_authflavor_t authflavor = clp->cl_rpcclient->cl_auth->au_flavor;
7055         int status;
7056
7057         /* try SP4_MACH_CRED if krb5i/p */
7058         if (authflavor == RPC_AUTH_GSS_KRB5I ||
7059             authflavor == RPC_AUTH_GSS_KRB5P) {
7060                 status = _nfs4_proc_exchange_id(clp, cred, SP4_MACH_CRED);
7061                 if (!status)
7062                         return 0;
7063         }
7064
7065         /* try SP4_NONE */
7066         return _nfs4_proc_exchange_id(clp, cred, SP4_NONE);
7067 }
7068
7069 static int _nfs4_proc_destroy_clientid(struct nfs_client *clp,
7070                 struct rpc_cred *cred)
7071 {
7072         struct rpc_message msg = {
7073                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_DESTROY_CLIENTID],
7074                 .rpc_argp = clp,
7075                 .rpc_cred = cred,
7076         };
7077         int status;
7078
7079         status = rpc_call_sync(clp->cl_rpcclient, &msg, RPC_TASK_TIMEOUT);
7080         trace_nfs4_destroy_clientid(clp, status);
7081         if (status)
7082                 dprintk("NFS: Got error %d from the server %s on "
7083                         "DESTROY_CLIENTID.", status, clp->cl_hostname);
7084         return status;
7085 }
7086
7087 static int nfs4_proc_destroy_clientid(struct nfs_client *clp,
7088                 struct rpc_cred *cred)
7089 {
7090         unsigned int loop;
7091         int ret;
7092
7093         for (loop = NFS4_MAX_LOOP_ON_RECOVER; loop != 0; loop--) {
7094                 ret = _nfs4_proc_destroy_clientid(clp, cred);
7095                 switch (ret) {
7096                 case -NFS4ERR_DELAY:
7097                 case -NFS4ERR_CLIENTID_BUSY:
7098                         ssleep(1);
7099                         break;
7100                 default:
7101                         return ret;
7102                 }
7103         }
7104         return 0;
7105 }
7106
7107 int nfs4_destroy_clientid(struct nfs_client *clp)
7108 {
7109         struct rpc_cred *cred;
7110         int ret = 0;
7111
7112         if (clp->cl_mvops->minor_version < 1)
7113                 goto out;
7114         if (clp->cl_exchange_flags == 0)
7115                 goto out;
7116         if (clp->cl_preserve_clid)
7117                 goto out;
7118         cred = nfs4_get_clid_cred(clp);
7119         ret = nfs4_proc_destroy_clientid(clp, cred);
7120         if (cred)
7121                 put_rpccred(cred);
7122         switch (ret) {
7123         case 0:
7124         case -NFS4ERR_STALE_CLIENTID:
7125                 clp->cl_exchange_flags = 0;
7126         }
7127 out:
7128         return ret;
7129 }
7130
7131 struct nfs4_get_lease_time_data {
7132         struct nfs4_get_lease_time_args *args;
7133         struct nfs4_get_lease_time_res *res;
7134         struct nfs_client *clp;
7135 };
7136
7137 static void nfs4_get_lease_time_prepare(struct rpc_task *task,
7138                                         void *calldata)
7139 {
7140         struct nfs4_get_lease_time_data *data =
7141                         (struct nfs4_get_lease_time_data *)calldata;
7142
7143         dprintk("--> %s\n", __func__);
7144         /* just setup sequence, do not trigger session recovery
7145            since we're invoked within one */
7146         nfs41_setup_sequence(data->clp->cl_session,
7147                         &data->args->la_seq_args,
7148                         &data->res->lr_seq_res,
7149                         task);
7150         dprintk("<-- %s\n", __func__);
7151 }
7152
7153 /*
7154  * Called from nfs4_state_manager thread for session setup, so don't recover
7155  * from sequence operation or clientid errors.
7156  */
7157 static void nfs4_get_lease_time_done(struct rpc_task *task, void *calldata)
7158 {
7159         struct nfs4_get_lease_time_data *data =
7160                         (struct nfs4_get_lease_time_data *)calldata;
7161
7162         dprintk("--> %s\n", __func__);
7163         if (!nfs41_sequence_done(task, &data->res->lr_seq_res))
7164                 return;
7165         switch (task->tk_status) {
7166         case -NFS4ERR_DELAY:
7167         case -NFS4ERR_GRACE:
7168                 dprintk("%s Retry: tk_status %d\n", __func__, task->tk_status);
7169                 rpc_delay(task, NFS4_POLL_RETRY_MIN);
7170                 task->tk_status = 0;
7171                 /* fall through */
7172         case -NFS4ERR_RETRY_UNCACHED_REP:
7173                 rpc_restart_call_prepare(task);
7174                 return;
7175         }
7176         dprintk("<-- %s\n", __func__);
7177 }
7178
7179 static const struct rpc_call_ops nfs4_get_lease_time_ops = {
7180         .rpc_call_prepare = nfs4_get_lease_time_prepare,
7181         .rpc_call_done = nfs4_get_lease_time_done,
7182 };
7183
7184 int nfs4_proc_get_lease_time(struct nfs_client *clp, struct nfs_fsinfo *fsinfo)
7185 {
7186         struct rpc_task *task;
7187         struct nfs4_get_lease_time_args args;
7188         struct nfs4_get_lease_time_res res = {
7189                 .lr_fsinfo = fsinfo,
7190         };
7191         struct nfs4_get_lease_time_data data = {
7192                 .args = &args,
7193                 .res = &res,
7194                 .clp = clp,
7195         };
7196         struct rpc_message msg = {
7197                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GET_LEASE_TIME],
7198                 .rpc_argp = &args,
7199                 .rpc_resp = &res,
7200         };
7201         struct rpc_task_setup task_setup = {
7202                 .rpc_client = clp->cl_rpcclient,
7203                 .rpc_message = &msg,
7204                 .callback_ops = &nfs4_get_lease_time_ops,
7205                 .callback_data = &data,
7206                 .flags = RPC_TASK_TIMEOUT,
7207         };
7208         int status;
7209
7210         nfs4_init_sequence(&args.la_seq_args, &res.lr_seq_res, 0);
7211         nfs4_set_sequence_privileged(&args.la_seq_args);
7212         dprintk("--> %s\n", __func__);
7213         task = rpc_run_task(&task_setup);
7214
7215         if (IS_ERR(task))
7216                 status = PTR_ERR(task);
7217         else {
7218                 status = task->tk_status;
7219                 rpc_put_task(task);
7220         }
7221         dprintk("<-- %s return %d\n", __func__, status);
7222
7223         return status;
7224 }
7225
7226 /*
7227  * Initialize the values to be used by the client in CREATE_SESSION
7228  * If nfs4_init_session set the fore channel request and response sizes,
7229  * use them.
7230  *
7231  * Set the back channel max_resp_sz_cached to zero to force the client to
7232  * always set csa_cachethis to FALSE because the current implementation
7233  * of the back channel DRC only supports caching the CB_SEQUENCE operation.
7234  */
7235 static void nfs4_init_channel_attrs(struct nfs41_create_session_args *args)
7236 {
7237         unsigned int max_rqst_sz, max_resp_sz;
7238
7239         max_rqst_sz = NFS_MAX_FILE_IO_SIZE + nfs41_maxwrite_overhead;
7240         max_resp_sz = NFS_MAX_FILE_IO_SIZE + nfs41_maxread_overhead;
7241
7242         /* Fore channel attributes */
7243         args->fc_attrs.max_rqst_sz = max_rqst_sz;
7244         args->fc_attrs.max_resp_sz = max_resp_sz;
7245         args->fc_attrs.max_ops = NFS4_MAX_OPS;
7246         args->fc_attrs.max_reqs = max_session_slots;
7247
7248         dprintk("%s: Fore Channel : max_rqst_sz=%u max_resp_sz=%u "
7249                 "max_ops=%u max_reqs=%u\n",
7250                 __func__,
7251                 args->fc_attrs.max_rqst_sz, args->fc_attrs.max_resp_sz,
7252                 args->fc_attrs.max_ops, args->fc_attrs.max_reqs);
7253
7254         /* Back channel attributes */
7255         args->bc_attrs.max_rqst_sz = PAGE_SIZE;
7256         args->bc_attrs.max_resp_sz = PAGE_SIZE;
7257         args->bc_attrs.max_resp_sz_cached = 0;
7258         args->bc_attrs.max_ops = NFS4_MAX_BACK_CHANNEL_OPS;
7259         args->bc_attrs.max_reqs = 1;
7260
7261         dprintk("%s: Back Channel : max_rqst_sz=%u max_resp_sz=%u "
7262                 "max_resp_sz_cached=%u max_ops=%u max_reqs=%u\n",
7263                 __func__,
7264                 args->bc_attrs.max_rqst_sz, args->bc_attrs.max_resp_sz,
7265                 args->bc_attrs.max_resp_sz_cached, args->bc_attrs.max_ops,
7266                 args->bc_attrs.max_reqs);
7267 }
7268
7269 static int nfs4_verify_fore_channel_attrs(struct nfs41_create_session_args *args,
7270                 struct nfs41_create_session_res *res)
7271 {
7272         struct nfs4_channel_attrs *sent = &args->fc_attrs;
7273         struct nfs4_channel_attrs *rcvd = &res->fc_attrs;
7274
7275         if (rcvd->max_resp_sz > sent->max_resp_sz)
7276                 return -EINVAL;
7277         /*
7278          * Our requested max_ops is the minimum we need; we're not
7279          * prepared to break up compounds into smaller pieces than that.
7280          * So, no point even trying to continue if the server won't
7281          * cooperate:
7282          */
7283         if (rcvd->max_ops < sent->max_ops)
7284                 return -EINVAL;
7285         if (rcvd->max_reqs == 0)
7286                 return -EINVAL;
7287         if (rcvd->max_reqs > NFS4_MAX_SLOT_TABLE)
7288                 rcvd->max_reqs = NFS4_MAX_SLOT_TABLE;
7289         return 0;
7290 }
7291
7292 static int nfs4_verify_back_channel_attrs(struct nfs41_create_session_args *args,
7293                 struct nfs41_create_session_res *res)
7294 {
7295         struct nfs4_channel_attrs *sent = &args->bc_attrs;
7296         struct nfs4_channel_attrs *rcvd = &res->bc_attrs;
7297
7298         if (!(res->flags & SESSION4_BACK_CHAN))
7299                 goto out;
7300         if (rcvd->max_rqst_sz > sent->max_rqst_sz)
7301                 return -EINVAL;
7302         if (rcvd->max_resp_sz < sent->max_resp_sz)
7303                 return -EINVAL;
7304         if (rcvd->max_resp_sz_cached > sent->max_resp_sz_cached)
7305                 return -EINVAL;
7306         /* These would render the backchannel useless: */
7307         if (rcvd->max_ops != sent->max_ops)
7308                 return -EINVAL;
7309         if (rcvd->max_reqs != sent->max_reqs)
7310                 return -EINVAL;
7311 out:
7312         return 0;
7313 }
7314
7315 static int nfs4_verify_channel_attrs(struct nfs41_create_session_args *args,
7316                                      struct nfs41_create_session_res *res)
7317 {
7318         int ret;
7319
7320         ret = nfs4_verify_fore_channel_attrs(args, res);
7321         if (ret)
7322                 return ret;
7323         return nfs4_verify_back_channel_attrs(args, res);
7324 }
7325
7326 static void nfs4_update_session(struct nfs4_session *session,
7327                 struct nfs41_create_session_res *res)
7328 {
7329         nfs4_copy_sessionid(&session->sess_id, &res->sessionid);
7330         /* Mark client id and session as being confirmed */
7331         session->clp->cl_exchange_flags |= EXCHGID4_FLAG_CONFIRMED_R;
7332         set_bit(NFS4_SESSION_ESTABLISHED, &session->session_state);
7333         session->flags = res->flags;
7334         memcpy(&session->fc_attrs, &res->fc_attrs, sizeof(session->fc_attrs));
7335         if (res->flags & SESSION4_BACK_CHAN)
7336                 memcpy(&session->bc_attrs, &res->bc_attrs,
7337                                 sizeof(session->bc_attrs));
7338 }
7339
7340 static int _nfs4_proc_create_session(struct nfs_client *clp,
7341                 struct rpc_cred *cred)
7342 {
7343         struct nfs4_session *session = clp->cl_session;
7344         struct nfs41_create_session_args args = {
7345                 .client = clp,
7346                 .clientid = clp->cl_clientid,
7347                 .seqid = clp->cl_seqid,
7348                 .cb_program = NFS4_CALLBACK,
7349         };
7350         struct nfs41_create_session_res res;
7351
7352         struct rpc_message msg = {
7353                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_CREATE_SESSION],
7354                 .rpc_argp = &args,
7355                 .rpc_resp = &res,
7356                 .rpc_cred = cred,
7357         };
7358         int status;
7359
7360         nfs4_init_channel_attrs(&args);
7361         args.flags = (SESSION4_PERSIST | SESSION4_BACK_CHAN);
7362
7363         status = rpc_call_sync(session->clp->cl_rpcclient, &msg, RPC_TASK_TIMEOUT);
7364         trace_nfs4_create_session(clp, status);
7365
7366         if (!status) {
7367                 /* Verify the session's negotiated channel_attrs values */
7368                 status = nfs4_verify_channel_attrs(&args, &res);
7369                 /* Increment the clientid slot sequence id */
7370                 if (clp->cl_seqid == res.seqid)
7371                         clp->cl_seqid++;
7372                 if (status)
7373                         goto out;
7374                 nfs4_update_session(session, &res);
7375         }
7376 out:
7377         return status;
7378 }
7379
7380 /*
7381  * Issues a CREATE_SESSION operation to the server.
7382  * It is the responsibility of the caller to verify the session is
7383  * expired before calling this routine.
7384  */
7385 int nfs4_proc_create_session(struct nfs_client *clp, struct rpc_cred *cred)
7386 {
7387         int status;
7388         unsigned *ptr;
7389         struct nfs4_session *session = clp->cl_session;
7390
7391         dprintk("--> %s clp=%p session=%p\n", __func__, clp, session);
7392
7393         status = _nfs4_proc_create_session(clp, cred);
7394         if (status)
7395                 goto out;
7396
7397         /* Init or reset the session slot tables */
7398         status = nfs4_setup_session_slot_tables(session);
7399         dprintk("slot table setup returned %d\n", status);
7400         if (status)
7401                 goto out;
7402
7403         ptr = (unsigned *)&session->sess_id.data[0];
7404         dprintk("%s client>seqid %d sessionid %u:%u:%u:%u\n", __func__,
7405                 clp->cl_seqid, ptr[0], ptr[1], ptr[2], ptr[3]);
7406 out:
7407         dprintk("<-- %s\n", __func__);
7408         return status;
7409 }
7410
7411 /*
7412  * Issue the over-the-wire RPC DESTROY_SESSION.
7413  * The caller must serialize access to this routine.
7414  */
7415 int nfs4_proc_destroy_session(struct nfs4_session *session,
7416                 struct rpc_cred *cred)
7417 {
7418         struct rpc_message msg = {
7419                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_DESTROY_SESSION],
7420                 .rpc_argp = session,
7421                 .rpc_cred = cred,
7422         };
7423         int status = 0;
7424
7425         dprintk("--> nfs4_proc_destroy_session\n");
7426
7427         /* session is still being setup */
7428         if (!test_and_clear_bit(NFS4_SESSION_ESTABLISHED, &session->session_state))
7429                 return 0;
7430
7431         status = rpc_call_sync(session->clp->cl_rpcclient, &msg, RPC_TASK_TIMEOUT);
7432         trace_nfs4_destroy_session(session->clp, status);
7433
7434         if (status)
7435                 dprintk("NFS: Got error %d from the server on DESTROY_SESSION. "
7436                         "Session has been destroyed regardless...\n", status);
7437
7438         dprintk("<-- nfs4_proc_destroy_session\n");
7439         return status;
7440 }
7441
7442 /*
7443  * Renew the cl_session lease.
7444  */
7445 struct nfs4_sequence_data {
7446         struct nfs_client *clp;
7447         struct nfs4_sequence_args args;
7448         struct nfs4_sequence_res res;
7449 };
7450
7451 static void nfs41_sequence_release(void *data)
7452 {
7453         struct nfs4_sequence_data *calldata = data;
7454         struct nfs_client *clp = calldata->clp;
7455
7456         if (atomic_read(&clp->cl_count) > 1)
7457                 nfs4_schedule_state_renewal(clp);
7458         nfs_put_client(clp);
7459         kfree(calldata);
7460 }
7461
7462 static int nfs41_sequence_handle_errors(struct rpc_task *task, struct nfs_client *clp)
7463 {
7464         switch(task->tk_status) {
7465         case -NFS4ERR_DELAY:
7466                 rpc_delay(task, NFS4_POLL_RETRY_MAX);
7467                 return -EAGAIN;
7468         default:
7469                 nfs4_schedule_lease_recovery(clp);
7470         }
7471         return 0;
7472 }
7473
7474 static void nfs41_sequence_call_done(struct rpc_task *task, void *data)
7475 {
7476         struct nfs4_sequence_data *calldata = data;
7477         struct nfs_client *clp = calldata->clp;
7478
7479         if (!nfs41_sequence_done(task, task->tk_msg.rpc_resp))
7480                 return;
7481
7482         trace_nfs4_sequence(clp, task->tk_status);
7483         if (task->tk_status < 0) {
7484                 dprintk("%s ERROR %d\n", __func__, task->tk_status);
7485                 if (atomic_read(&clp->cl_count) == 1)
7486                         goto out;
7487
7488                 if (nfs41_sequence_handle_errors(task, clp) == -EAGAIN) {
7489                         rpc_restart_call_prepare(task);
7490                         return;
7491                 }
7492         }
7493         dprintk("%s rpc_cred %p\n", __func__, task->tk_msg.rpc_cred);
7494 out:
7495         dprintk("<-- %s\n", __func__);
7496 }
7497
7498 static void nfs41_sequence_prepare(struct rpc_task *task, void *data)
7499 {
7500         struct nfs4_sequence_data *calldata = data;
7501         struct nfs_client *clp = calldata->clp;
7502         struct nfs4_sequence_args *args;
7503         struct nfs4_sequence_res *res;
7504
7505         args = task->tk_msg.rpc_argp;
7506         res = task->tk_msg.rpc_resp;
7507
7508         nfs41_setup_sequence(clp->cl_session, args, res, task);
7509 }
7510
7511 static const struct rpc_call_ops nfs41_sequence_ops = {
7512         .rpc_call_done = nfs41_sequence_call_done,
7513         .rpc_call_prepare = nfs41_sequence_prepare,
7514         .rpc_release = nfs41_sequence_release,
7515 };
7516
7517 static struct rpc_task *_nfs41_proc_sequence(struct nfs_client *clp,
7518                 struct rpc_cred *cred,
7519                 bool is_privileged)
7520 {
7521         struct nfs4_sequence_data *calldata;
7522         struct rpc_message msg = {
7523                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_SEQUENCE],
7524                 .rpc_cred = cred,
7525         };
7526         struct rpc_task_setup task_setup_data = {
7527                 .rpc_client = clp->cl_rpcclient,
7528                 .rpc_message = &msg,
7529                 .callback_ops = &nfs41_sequence_ops,
7530                 .flags = RPC_TASK_ASYNC | RPC_TASK_TIMEOUT,
7531         };
7532
7533         if (!atomic_inc_not_zero(&clp->cl_count))
7534                 return ERR_PTR(-EIO);
7535         calldata = kzalloc(sizeof(*calldata), GFP_NOFS);
7536         if (calldata == NULL) {
7537                 nfs_put_client(clp);
7538                 return ERR_PTR(-ENOMEM);
7539         }
7540         nfs4_init_sequence(&calldata->args, &calldata->res, 0);
7541         if (is_privileged)
7542                 nfs4_set_sequence_privileged(&calldata->args);
7543         msg.rpc_argp = &calldata->args;
7544         msg.rpc_resp = &calldata->res;
7545         calldata->clp = clp;
7546         task_setup_data.callback_data = calldata;
7547
7548         return rpc_run_task(&task_setup_data);
7549 }
7550
7551 static int nfs41_proc_async_sequence(struct nfs_client *clp, struct rpc_cred *cred, unsigned renew_flags)
7552 {
7553         struct rpc_task *task;
7554         int ret = 0;
7555
7556         if ((renew_flags & NFS4_RENEW_TIMEOUT) == 0)
7557                 return -EAGAIN;
7558         task = _nfs41_proc_sequence(clp, cred, false);
7559         if (IS_ERR(task))
7560                 ret = PTR_ERR(task);
7561         else
7562                 rpc_put_task_async(task);
7563         dprintk("<-- %s status=%d\n", __func__, ret);
7564         return ret;
7565 }
7566
7567 static int nfs4_proc_sequence(struct nfs_client *clp, struct rpc_cred *cred)
7568 {
7569         struct rpc_task *task;
7570         int ret;
7571
7572         task = _nfs41_proc_sequence(clp, cred, true);
7573         if (IS_ERR(task)) {
7574                 ret = PTR_ERR(task);
7575                 goto out;
7576         }
7577         ret = rpc_wait_for_completion_task(task);
7578         if (!ret)
7579                 ret = task->tk_status;
7580         rpc_put_task(task);
7581 out:
7582         dprintk("<-- %s status=%d\n", __func__, ret);
7583         return ret;
7584 }
7585
7586 struct nfs4_reclaim_complete_data {
7587         struct nfs_client *clp;
7588         struct nfs41_reclaim_complete_args arg;
7589         struct nfs41_reclaim_complete_res res;
7590 };
7591
7592 static void nfs4_reclaim_complete_prepare(struct rpc_task *task, void *data)
7593 {
7594         struct nfs4_reclaim_complete_data *calldata = data;
7595
7596         nfs41_setup_sequence(calldata->clp->cl_session,
7597                         &calldata->arg.seq_args,
7598                         &calldata->res.seq_res,
7599                         task);
7600 }
7601
7602 static int nfs41_reclaim_complete_handle_errors(struct rpc_task *task, struct nfs_client *clp)
7603 {
7604         switch(task->tk_status) {
7605         case 0:
7606         case -NFS4ERR_COMPLETE_ALREADY:
7607         case -NFS4ERR_WRONG_CRED: /* What to do here? */
7608                 break;
7609         case -NFS4ERR_DELAY:
7610                 rpc_delay(task, NFS4_POLL_RETRY_MAX);
7611                 /* fall through */
7612         case -NFS4ERR_RETRY_UNCACHED_REP:
7613                 return -EAGAIN;
7614         default:
7615                 nfs4_schedule_lease_recovery(clp);
7616         }
7617         return 0;
7618 }
7619
7620 static void nfs4_reclaim_complete_done(struct rpc_task *task, void *data)
7621 {
7622         struct nfs4_reclaim_complete_data *calldata = data;
7623         struct nfs_client *clp = calldata->clp;
7624         struct nfs4_sequence_res *res = &calldata->res.seq_res;
7625
7626         dprintk("--> %s\n", __func__);
7627         if (!nfs41_sequence_done(task, res))
7628                 return;
7629
7630         trace_nfs4_reclaim_complete(clp, task->tk_status);
7631         if (nfs41_reclaim_complete_handle_errors(task, clp) == -EAGAIN) {
7632                 rpc_restart_call_prepare(task);
7633                 return;
7634         }
7635         dprintk("<-- %s\n", __func__);
7636 }
7637
7638 static void nfs4_free_reclaim_complete_data(void *data)
7639 {
7640         struct nfs4_reclaim_complete_data *calldata = data;
7641
7642         kfree(calldata);
7643 }
7644
7645 static const struct rpc_call_ops nfs4_reclaim_complete_call_ops = {
7646         .rpc_call_prepare = nfs4_reclaim_complete_prepare,
7647         .rpc_call_done = nfs4_reclaim_complete_done,
7648         .rpc_release = nfs4_free_reclaim_complete_data,
7649 };
7650
7651 /*
7652  * Issue a global reclaim complete.
7653  */
7654 static int nfs41_proc_reclaim_complete(struct nfs_client *clp,
7655                 struct rpc_cred *cred)
7656 {
7657         struct nfs4_reclaim_complete_data *calldata;
7658         struct rpc_task *task;
7659         struct rpc_message msg = {
7660                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_RECLAIM_COMPLETE],
7661                 .rpc_cred = cred,
7662         };
7663         struct rpc_task_setup task_setup_data = {
7664                 .rpc_client = clp->cl_rpcclient,
7665                 .rpc_message = &msg,
7666                 .callback_ops = &nfs4_reclaim_complete_call_ops,
7667                 .flags = RPC_TASK_ASYNC,
7668         };
7669         int status = -ENOMEM;
7670
7671         dprintk("--> %s\n", __func__);
7672         calldata = kzalloc(sizeof(*calldata), GFP_NOFS);
7673         if (calldata == NULL)
7674                 goto out;
7675         calldata->clp = clp;
7676         calldata->arg.one_fs = 0;
7677
7678         nfs4_init_sequence(&calldata->arg.seq_args, &calldata->res.seq_res, 0);
7679         nfs4_set_sequence_privileged(&calldata->arg.seq_args);
7680         msg.rpc_argp = &calldata->arg;
7681         msg.rpc_resp = &calldata->res;
7682         task_setup_data.callback_data = calldata;
7683         task = rpc_run_task(&task_setup_data);
7684         if (IS_ERR(task)) {
7685                 status = PTR_ERR(task);
7686                 goto out;
7687         }
7688         status = nfs4_wait_for_completion_rpc_task(task);
7689         if (status == 0)
7690                 status = task->tk_status;
7691         rpc_put_task(task);
7692         return 0;
7693 out:
7694         dprintk("<-- %s status=%d\n", __func__, status);
7695         return status;
7696 }
7697
7698 static void
7699 nfs4_layoutget_prepare(struct rpc_task *task, void *calldata)
7700 {
7701         struct nfs4_layoutget *lgp = calldata;
7702         struct nfs_server *server = NFS_SERVER(lgp->args.inode);
7703         struct nfs4_session *session = nfs4_get_session(server);
7704
7705         dprintk("--> %s\n", __func__);
7706         /* Note the is a race here, where a CB_LAYOUTRECALL can come in
7707          * right now covering the LAYOUTGET we are about to send.
7708          * However, that is not so catastrophic, and there seems
7709          * to be no way to prevent it completely.
7710          */
7711         if (nfs41_setup_sequence(session, &lgp->args.seq_args,
7712                                 &lgp->res.seq_res, task))
7713                 return;
7714         if (pnfs_choose_layoutget_stateid(&lgp->args.stateid,
7715                                           NFS_I(lgp->args.inode)->layout,
7716                                           &lgp->args.range,
7717                                           lgp->args.ctx->state)) {
7718                 rpc_exit(task, NFS4_OK);
7719         }
7720 }
7721
7722 static void nfs4_layoutget_done(struct rpc_task *task, void *calldata)
7723 {
7724         struct nfs4_layoutget *lgp = calldata;
7725         struct inode *inode = lgp->args.inode;
7726         struct nfs_server *server = NFS_SERVER(inode);
7727         struct pnfs_layout_hdr *lo;
7728         struct nfs4_state *state = NULL;
7729         unsigned long timeo, now, giveup;
7730
7731         dprintk("--> %s tk_status => %d\n", __func__, -task->tk_status);
7732
7733         if (!nfs41_sequence_done(task, &lgp->res.seq_res))
7734                 goto out;
7735
7736         switch (task->tk_status) {
7737         case 0:
7738                 goto out;
7739         /*
7740          * NFS4ERR_LAYOUTTRYLATER is a conflict with another client
7741          * (or clients) writing to the same RAID stripe
7742          */
7743         case -NFS4ERR_LAYOUTTRYLATER:
7744         /*
7745          * NFS4ERR_RECALLCONFLICT is when conflict with self (must recall
7746          * existing layout before getting a new one).
7747          */
7748         case -NFS4ERR_RECALLCONFLICT:
7749                 timeo = rpc_get_timeout(task->tk_client);
7750                 giveup = lgp->args.timestamp + timeo;
7751                 now = jiffies;
7752                 if (time_after(giveup, now)) {
7753                         unsigned long delay;
7754
7755                         /* Delay for:
7756                          * - Not less then NFS4_POLL_RETRY_MIN.
7757                          * - One last time a jiffie before we give up
7758                          * - exponential backoff (time_now minus start_attempt)
7759                          */
7760                         delay = max_t(unsigned long, NFS4_POLL_RETRY_MIN,
7761                                     min((giveup - now - 1),
7762                                         now - lgp->args.timestamp));
7763
7764                         dprintk("%s: NFS4ERR_RECALLCONFLICT waiting %lu\n",
7765                                 __func__, delay);
7766                         rpc_delay(task, delay);
7767                         task->tk_status = 0;
7768                         rpc_restart_call_prepare(task);
7769                         goto out; /* Do not call nfs4_async_handle_error() */
7770                 }
7771                 break;
7772         case -NFS4ERR_EXPIRED:
7773         case -NFS4ERR_BAD_STATEID:
7774                 spin_lock(&inode->i_lock);
7775                 lo = NFS_I(inode)->layout;
7776                 if (!lo || list_empty(&lo->plh_segs)) {
7777                         spin_unlock(&inode->i_lock);
7778                         /* If the open stateid was bad, then recover it. */
7779                         state = lgp->args.ctx->state;
7780                 } else {
7781                         LIST_HEAD(head);
7782
7783                         /*
7784                          * Mark the bad layout state as invalid, then retry
7785                          * with the current stateid.
7786                          */
7787                         pnfs_mark_matching_lsegs_invalid(lo, &head, NULL);
7788                         spin_unlock(&inode->i_lock);
7789                         pnfs_free_lseg_list(&head);
7790         
7791                         task->tk_status = 0;
7792                         rpc_restart_call_prepare(task);
7793                 }
7794         }
7795         if (nfs4_async_handle_error(task, server, state, NULL) == -EAGAIN)
7796                 rpc_restart_call_prepare(task);
7797 out:
7798         dprintk("<-- %s\n", __func__);
7799 }
7800
7801 static size_t max_response_pages(struct nfs_server *server)
7802 {
7803         u32 max_resp_sz = server->nfs_client->cl_session->fc_attrs.max_resp_sz;
7804         return nfs_page_array_len(0, max_resp_sz);
7805 }
7806
7807 static void nfs4_free_pages(struct page **pages, size_t size)
7808 {
7809         int i;
7810
7811         if (!pages)
7812                 return;
7813
7814         for (i = 0; i < size; i++) {
7815                 if (!pages[i])
7816                         break;
7817                 __free_page(pages[i]);
7818         }
7819         kfree(pages);
7820 }
7821
7822 static struct page **nfs4_alloc_pages(size_t size, gfp_t gfp_flags)
7823 {
7824         struct page **pages;
7825         int i;
7826
7827         pages = kcalloc(size, sizeof(struct page *), gfp_flags);
7828         if (!pages) {
7829                 dprintk("%s: can't alloc array of %zu pages\n", __func__, size);
7830                 return NULL;
7831         }
7832
7833         for (i = 0; i < size; i++) {
7834                 pages[i] = alloc_page(gfp_flags);
7835                 if (!pages[i]) {
7836                         dprintk("%s: failed to allocate page\n", __func__);
7837                         nfs4_free_pages(pages, size);
7838                         return NULL;
7839                 }
7840         }
7841
7842         return pages;
7843 }
7844
7845 static void nfs4_layoutget_release(void *calldata)
7846 {
7847         struct nfs4_layoutget *lgp = calldata;
7848         struct inode *inode = lgp->args.inode;
7849         struct nfs_server *server = NFS_SERVER(inode);
7850         size_t max_pages = max_response_pages(server);
7851
7852         dprintk("--> %s\n", __func__);
7853         nfs4_free_pages(lgp->args.layout.pages, max_pages);
7854         pnfs_put_layout_hdr(NFS_I(inode)->layout);
7855         put_nfs_open_context(lgp->args.ctx);
7856         kfree(calldata);
7857         dprintk("<-- %s\n", __func__);
7858 }
7859
7860 static const struct rpc_call_ops nfs4_layoutget_call_ops = {
7861         .rpc_call_prepare = nfs4_layoutget_prepare,
7862         .rpc_call_done = nfs4_layoutget_done,
7863         .rpc_release = nfs4_layoutget_release,
7864 };
7865
7866 struct pnfs_layout_segment *
7867 nfs4_proc_layoutget(struct nfs4_layoutget *lgp, gfp_t gfp_flags)
7868 {
7869         struct inode *inode = lgp->args.inode;
7870         struct nfs_server *server = NFS_SERVER(inode);
7871         size_t max_pages = max_response_pages(server);
7872         struct rpc_task *task;
7873         struct rpc_message msg = {
7874                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_LAYOUTGET],
7875                 .rpc_argp = &lgp->args,
7876                 .rpc_resp = &lgp->res,
7877                 .rpc_cred = lgp->cred,
7878         };
7879         struct rpc_task_setup task_setup_data = {
7880                 .rpc_client = server->client,
7881                 .rpc_message = &msg,
7882                 .callback_ops = &nfs4_layoutget_call_ops,
7883                 .callback_data = lgp,
7884                 .flags = RPC_TASK_ASYNC,
7885         };
7886         struct pnfs_layout_segment *lseg = NULL;
7887         int status = 0;
7888
7889         dprintk("--> %s\n", __func__);
7890
7891         /* nfs4_layoutget_release calls pnfs_put_layout_hdr */
7892         pnfs_get_layout_hdr(NFS_I(inode)->layout);
7893
7894         lgp->args.layout.pages = nfs4_alloc_pages(max_pages, gfp_flags);
7895         if (!lgp->args.layout.pages) {
7896                 nfs4_layoutget_release(lgp);
7897                 return ERR_PTR(-ENOMEM);
7898         }
7899         lgp->args.layout.pglen = max_pages * PAGE_SIZE;
7900         lgp->args.timestamp = jiffies;
7901
7902         lgp->res.layoutp = &lgp->args.layout;
7903         lgp->res.seq_res.sr_slot = NULL;
7904         nfs4_init_sequence(&lgp->args.seq_args, &lgp->res.seq_res, 0);
7905
7906         task = rpc_run_task(&task_setup_data);
7907         if (IS_ERR(task))
7908                 return ERR_CAST(task);
7909         status = nfs4_wait_for_completion_rpc_task(task);
7910         if (status == 0)
7911                 status = task->tk_status;
7912         trace_nfs4_layoutget(lgp->args.ctx,
7913                         &lgp->args.range,
7914                         &lgp->res.range,
7915                         status);
7916         /* if layoutp->len is 0, nfs4_layoutget_prepare called rpc_exit */
7917         if (status == 0 && lgp->res.layoutp->len)
7918                 lseg = pnfs_layout_process(lgp);
7919         rpc_put_task(task);
7920         dprintk("<-- %s status=%d\n", __func__, status);
7921         if (status)
7922                 return ERR_PTR(status);
7923         return lseg;
7924 }
7925
7926 static void
7927 nfs4_layoutreturn_prepare(struct rpc_task *task, void *calldata)
7928 {
7929         struct nfs4_layoutreturn *lrp = calldata;
7930
7931         dprintk("--> %s\n", __func__);
7932         nfs41_setup_sequence(lrp->clp->cl_session,
7933                         &lrp->args.seq_args,
7934                         &lrp->res.seq_res,
7935                         task);
7936 }
7937
7938 static void nfs4_layoutreturn_done(struct rpc_task *task, void *calldata)
7939 {
7940         struct nfs4_layoutreturn *lrp = calldata;
7941         struct nfs_server *server;
7942
7943         dprintk("--> %s\n", __func__);
7944
7945         if (!nfs41_sequence_done(task, &lrp->res.seq_res))
7946                 return;
7947
7948         server = NFS_SERVER(lrp->args.inode);
7949         switch (task->tk_status) {
7950         default:
7951                 task->tk_status = 0;
7952         case 0:
7953                 break;
7954         case -NFS4ERR_DELAY:
7955                 if (nfs4_async_handle_error(task, server, NULL, NULL) != -EAGAIN)
7956                         break;
7957                 rpc_restart_call_prepare(task);
7958                 return;
7959         }
7960         dprintk("<-- %s\n", __func__);
7961 }
7962
7963 static void nfs4_layoutreturn_release(void *calldata)
7964 {
7965         struct nfs4_layoutreturn *lrp = calldata;
7966         struct pnfs_layout_hdr *lo = lrp->args.layout;
7967         LIST_HEAD(freeme);
7968
7969         dprintk("--> %s\n", __func__);
7970         spin_lock(&lo->plh_inode->i_lock);
7971         if (lrp->res.lrs_present)
7972                 pnfs_set_layout_stateid(lo, &lrp->res.stateid, true);
7973         pnfs_mark_matching_lsegs_invalid(lo, &freeme, &lrp->args.range);
7974         pnfs_clear_layoutreturn_waitbit(lo);
7975         clear_bit(NFS_LAYOUT_RETURN_BEFORE_CLOSE, &lo->plh_flags);
7976         rpc_wake_up(&NFS_SERVER(lo->plh_inode)->roc_rpcwaitq);
7977         lo->plh_block_lgets--;
7978         spin_unlock(&lo->plh_inode->i_lock);
7979         pnfs_free_lseg_list(&freeme);
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: initiating layoutcommit call. sync %d "
8154                 "lbw: %llu inode %lu\n", sync,
8155                 data->args.lastbytewritten,
8156                 data->args.inode->i_ino);
8157
8158         if (!sync) {
8159                 data->inode = nfs_igrab_and_active(data->args.inode);
8160                 if (data->inode == NULL) {
8161                         nfs4_layoutcommit_release(data);
8162                         return -EAGAIN;
8163                 }
8164                 task_setup_data.flags = RPC_TASK_ASYNC;
8165         }
8166         nfs4_init_sequence(&data->args.seq_args, &data->res.seq_res, 1);
8167         task = rpc_run_task(&task_setup_data);
8168         if (IS_ERR(task))
8169                 return PTR_ERR(task);
8170         if (sync)
8171                 status = task->tk_status;
8172         trace_nfs4_layoutcommit(data->args.inode, status);
8173         dprintk("%s: status %d\n", __func__, status);
8174         rpc_put_task(task);
8175         return status;
8176 }
8177
8178 /**
8179  * Use the state managment nfs_client cl_rpcclient, which uses krb5i (if
8180  * possible) as per RFC3530bis and RFC5661 Security Considerations sections
8181  */
8182 static int
8183 _nfs41_proc_secinfo_no_name(struct nfs_server *server, struct nfs_fh *fhandle,
8184                     struct nfs_fsinfo *info,
8185                     struct nfs4_secinfo_flavors *flavors, bool use_integrity)
8186 {
8187         struct nfs41_secinfo_no_name_args args = {
8188                 .style = SECINFO_STYLE_CURRENT_FH,
8189         };
8190         struct nfs4_secinfo_res res = {
8191                 .flavors = flavors,
8192         };
8193         struct rpc_message msg = {
8194                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_SECINFO_NO_NAME],
8195                 .rpc_argp = &args,
8196                 .rpc_resp = &res,
8197         };
8198         struct rpc_clnt *clnt = server->client;
8199         struct rpc_cred *cred = NULL;
8200         int status;
8201
8202         if (use_integrity) {
8203                 clnt = server->nfs_client->cl_rpcclient;
8204                 cred = nfs4_get_clid_cred(server->nfs_client);
8205                 msg.rpc_cred = cred;
8206         }
8207
8208         dprintk("--> %s\n", __func__);
8209         status = nfs4_call_sync(clnt, server, &msg, &args.seq_args,
8210                                 &res.seq_res, 0);
8211         dprintk("<-- %s status=%d\n", __func__, status);
8212
8213         if (cred)
8214                 put_rpccred(cred);
8215
8216         return status;
8217 }
8218
8219 static int
8220 nfs41_proc_secinfo_no_name(struct nfs_server *server, struct nfs_fh *fhandle,
8221                            struct nfs_fsinfo *info, struct nfs4_secinfo_flavors *flavors)
8222 {
8223         struct nfs4_exception exception = { };
8224         int err;
8225         do {
8226                 /* first try using integrity protection */
8227                 err = -NFS4ERR_WRONGSEC;
8228
8229                 /* try to use integrity protection with machine cred */
8230                 if (_nfs4_is_integrity_protected(server->nfs_client))
8231                         err = _nfs41_proc_secinfo_no_name(server, fhandle, info,
8232                                                           flavors, true);
8233
8234                 /*
8235                  * if unable to use integrity protection, or SECINFO with
8236                  * integrity protection returns NFS4ERR_WRONGSEC (which is
8237                  * disallowed by spec, but exists in deployed servers) use
8238                  * the current filesystem's rpc_client and the user cred.
8239                  */
8240                 if (err == -NFS4ERR_WRONGSEC)
8241                         err = _nfs41_proc_secinfo_no_name(server, fhandle, info,
8242                                                           flavors, false);
8243
8244                 switch (err) {
8245                 case 0:
8246                 case -NFS4ERR_WRONGSEC:
8247                 case -ENOTSUPP:
8248                         goto out;
8249                 default:
8250                         err = nfs4_handle_exception(server, err, &exception);
8251                 }
8252         } while (exception.retry);
8253 out:
8254         return err;
8255 }
8256
8257 static int
8258 nfs41_find_root_sec(struct nfs_server *server, struct nfs_fh *fhandle,
8259                     struct nfs_fsinfo *info)
8260 {
8261         int err;
8262         struct page *page;
8263         rpc_authflavor_t flavor = RPC_AUTH_MAXFLAVOR;
8264         struct nfs4_secinfo_flavors *flavors;
8265         struct nfs4_secinfo4 *secinfo;
8266         int i;
8267
8268         page = alloc_page(GFP_KERNEL);
8269         if (!page) {
8270                 err = -ENOMEM;
8271                 goto out;
8272         }
8273
8274         flavors = page_address(page);
8275         err = nfs41_proc_secinfo_no_name(server, fhandle, info, flavors);
8276
8277         /*
8278          * Fall back on "guess and check" method if
8279          * the server doesn't support SECINFO_NO_NAME
8280          */
8281         if (err == -NFS4ERR_WRONGSEC || err == -ENOTSUPP) {
8282                 err = nfs4_find_root_sec(server, fhandle, info);
8283                 goto out_freepage;
8284         }
8285         if (err)
8286                 goto out_freepage;
8287
8288         for (i = 0; i < flavors->num_flavors; i++) {
8289                 secinfo = &flavors->flavors[i];
8290
8291                 switch (secinfo->flavor) {
8292                 case RPC_AUTH_NULL:
8293                 case RPC_AUTH_UNIX:
8294                 case RPC_AUTH_GSS:
8295                         flavor = rpcauth_get_pseudoflavor(secinfo->flavor,
8296                                         &secinfo->flavor_info);
8297                         break;
8298                 default:
8299                         flavor = RPC_AUTH_MAXFLAVOR;
8300                         break;
8301                 }
8302
8303                 if (!nfs_auth_info_match(&server->auth_info, flavor))
8304                         flavor = RPC_AUTH_MAXFLAVOR;
8305
8306                 if (flavor != RPC_AUTH_MAXFLAVOR) {
8307                         err = nfs4_lookup_root_sec(server, fhandle,
8308                                                    info, flavor);
8309                         if (!err)
8310                                 break;
8311                 }
8312         }
8313
8314         if (flavor == RPC_AUTH_MAXFLAVOR)
8315                 err = -EPERM;
8316
8317 out_freepage:
8318         put_page(page);
8319         if (err == -EACCES)
8320                 return -EPERM;
8321 out:
8322         return err;
8323 }
8324
8325 static int _nfs41_test_stateid(struct nfs_server *server,
8326                 nfs4_stateid *stateid,
8327                 struct rpc_cred *cred)
8328 {
8329         int status;
8330         struct nfs41_test_stateid_args args = {
8331                 .stateid = stateid,
8332         };
8333         struct nfs41_test_stateid_res res;
8334         struct rpc_message msg = {
8335                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_TEST_STATEID],
8336                 .rpc_argp = &args,
8337                 .rpc_resp = &res,
8338                 .rpc_cred = cred,
8339         };
8340         struct rpc_clnt *rpc_client = server->client;
8341
8342         nfs4_state_protect(server->nfs_client, NFS_SP4_MACH_CRED_STATEID,
8343                 &rpc_client, &msg);
8344
8345         dprintk("NFS call  test_stateid %p\n", stateid);
8346         nfs4_init_sequence(&args.seq_args, &res.seq_res, 0);
8347         nfs4_set_sequence_privileged(&args.seq_args);
8348         status = nfs4_call_sync_sequence(rpc_client, server, &msg,
8349                         &args.seq_args, &res.seq_res);
8350         if (status != NFS_OK) {
8351                 dprintk("NFS reply test_stateid: failed, %d\n", status);
8352                 return status;
8353         }
8354         dprintk("NFS reply test_stateid: succeeded, %d\n", -res.status);
8355         return -res.status;
8356 }
8357
8358 /**
8359  * nfs41_test_stateid - perform a TEST_STATEID operation
8360  *
8361  * @server: server / transport on which to perform the operation
8362  * @stateid: state ID to test
8363  * @cred: credential
8364  *
8365  * Returns NFS_OK if the server recognizes that "stateid" is valid.
8366  * Otherwise a negative NFS4ERR value is returned if the operation
8367  * failed or the state ID is not currently valid.
8368  */
8369 static int nfs41_test_stateid(struct nfs_server *server,
8370                 nfs4_stateid *stateid,
8371                 struct rpc_cred *cred)
8372 {
8373         struct nfs4_exception exception = { };
8374         int err;
8375         do {
8376                 err = _nfs41_test_stateid(server, stateid, cred);
8377                 if (err != -NFS4ERR_DELAY)
8378                         break;
8379                 nfs4_handle_exception(server, err, &exception);
8380         } while (exception.retry);
8381         return err;
8382 }
8383
8384 struct nfs_free_stateid_data {
8385         struct nfs_server *server;
8386         struct nfs41_free_stateid_args args;
8387         struct nfs41_free_stateid_res res;
8388 };
8389
8390 static void nfs41_free_stateid_prepare(struct rpc_task *task, void *calldata)
8391 {
8392         struct nfs_free_stateid_data *data = calldata;
8393         nfs41_setup_sequence(nfs4_get_session(data->server),
8394                         &data->args.seq_args,
8395                         &data->res.seq_res,
8396                         task);
8397 }
8398
8399 static void nfs41_free_stateid_done(struct rpc_task *task, void *calldata)
8400 {
8401         struct nfs_free_stateid_data *data = calldata;
8402
8403         nfs41_sequence_done(task, &data->res.seq_res);
8404
8405         switch (task->tk_status) {
8406         case -NFS4ERR_DELAY:
8407                 if (nfs4_async_handle_error(task, data->server, NULL, NULL) == -EAGAIN)
8408                         rpc_restart_call_prepare(task);
8409         }
8410 }
8411
8412 static void nfs41_free_stateid_release(void *calldata)
8413 {
8414         kfree(calldata);
8415 }
8416
8417 static const struct rpc_call_ops nfs41_free_stateid_ops = {
8418         .rpc_call_prepare = nfs41_free_stateid_prepare,
8419         .rpc_call_done = nfs41_free_stateid_done,
8420         .rpc_release = nfs41_free_stateid_release,
8421 };
8422
8423 static struct rpc_task *_nfs41_free_stateid(struct nfs_server *server,
8424                 nfs4_stateid *stateid,
8425                 struct rpc_cred *cred,
8426                 bool privileged)
8427 {
8428         struct rpc_message msg = {
8429                 .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_FREE_STATEID],
8430                 .rpc_cred = cred,
8431         };
8432         struct rpc_task_setup task_setup = {
8433                 .rpc_client = server->client,
8434                 .rpc_message = &msg,
8435                 .callback_ops = &nfs41_free_stateid_ops,
8436                 .flags = RPC_TASK_ASYNC,
8437         };
8438         struct nfs_free_stateid_data *data;
8439
8440         nfs4_state_protect(server->nfs_client, NFS_SP4_MACH_CRED_STATEID,
8441                 &task_setup.rpc_client, &msg);
8442
8443         dprintk("NFS call  free_stateid %p\n", stateid);
8444         data = kmalloc(sizeof(*data), GFP_NOFS);
8445         if (!data)
8446                 return ERR_PTR(-ENOMEM);
8447         data->server = server;
8448         nfs4_stateid_copy(&data->args.stateid, stateid);
8449
8450         task_setup.callback_data = data;
8451
8452         msg.rpc_argp = &data->args;
8453         msg.rpc_resp = &data->res;
8454         nfs4_init_sequence(&data->args.seq_args, &data->res.seq_res, 0);
8455         if (privileged)
8456                 nfs4_set_sequence_privileged(&data->args.seq_args);
8457
8458         return rpc_run_task(&task_setup);
8459 }
8460
8461 /**
8462  * nfs41_free_stateid - perform a FREE_STATEID operation
8463  *
8464  * @server: server / transport on which to perform the operation
8465  * @stateid: state ID to release
8466  * @cred: credential
8467  *
8468  * Returns NFS_OK if the server freed "stateid".  Otherwise a
8469  * negative NFS4ERR value is returned.
8470  */
8471 static int nfs41_free_stateid(struct nfs_server *server,
8472                 nfs4_stateid *stateid,
8473                 struct rpc_cred *cred)
8474 {
8475         struct rpc_task *task;
8476         int ret;
8477
8478         task = _nfs41_free_stateid(server, stateid, cred, true);
8479         if (IS_ERR(task))
8480                 return PTR_ERR(task);
8481         ret = rpc_wait_for_completion_task(task);
8482         if (!ret)
8483                 ret = task->tk_status;
8484         rpc_put_task(task);
8485         return ret;
8486 }
8487
8488 static void
8489 nfs41_free_lock_state(struct nfs_server *server, struct nfs4_lock_state *lsp)
8490 {
8491         struct rpc_task *task;
8492         struct rpc_cred *cred = lsp->ls_state->owner->so_cred;
8493
8494         task = _nfs41_free_stateid(server, &lsp->ls_stateid, cred, false);
8495         nfs4_free_lock_state(server, lsp);
8496         if (IS_ERR(task))
8497                 return;
8498         rpc_put_task(task);
8499 }
8500
8501 static bool nfs41_match_stateid(const nfs4_stateid *s1,
8502                 const nfs4_stateid *s2)
8503 {
8504         if (memcmp(s1->other, s2->other, sizeof(s1->other)) != 0)
8505                 return false;
8506
8507         if (s1->seqid == s2->seqid)
8508                 return true;
8509         if (s1->seqid == 0 || s2->seqid == 0)
8510                 return true;
8511
8512         return false;
8513 }
8514
8515 #endif /* CONFIG_NFS_V4_1 */
8516
8517 static bool nfs4_match_stateid(const nfs4_stateid *s1,
8518                 const nfs4_stateid *s2)
8519 {
8520         return nfs4_stateid_match(s1, s2);
8521 }
8522
8523
8524 static const struct nfs4_state_recovery_ops nfs40_reboot_recovery_ops = {
8525         .owner_flag_bit = NFS_OWNER_RECLAIM_REBOOT,
8526         .state_flag_bit = NFS_STATE_RECLAIM_REBOOT,
8527         .recover_open   = nfs4_open_reclaim,
8528         .recover_lock   = nfs4_lock_reclaim,
8529         .establish_clid = nfs4_init_clientid,
8530         .detect_trunking = nfs40_discover_server_trunking,
8531 };
8532
8533 #if defined(CONFIG_NFS_V4_1)
8534 static const struct nfs4_state_recovery_ops nfs41_reboot_recovery_ops = {
8535         .owner_flag_bit = NFS_OWNER_RECLAIM_REBOOT,
8536         .state_flag_bit = NFS_STATE_RECLAIM_REBOOT,
8537         .recover_open   = nfs4_open_reclaim,
8538         .recover_lock   = nfs4_lock_reclaim,
8539         .establish_clid = nfs41_init_clientid,
8540         .reclaim_complete = nfs41_proc_reclaim_complete,
8541         .detect_trunking = nfs41_discover_server_trunking,
8542 };
8543 #endif /* CONFIG_NFS_V4_1 */
8544
8545 static const struct nfs4_state_recovery_ops nfs40_nograce_recovery_ops = {
8546         .owner_flag_bit = NFS_OWNER_RECLAIM_NOGRACE,
8547         .state_flag_bit = NFS_STATE_RECLAIM_NOGRACE,
8548         .recover_open   = nfs40_open_expired,
8549         .recover_lock   = nfs4_lock_expired,
8550         .establish_clid = nfs4_init_clientid,
8551 };
8552
8553 #if defined(CONFIG_NFS_V4_1)
8554 static const struct nfs4_state_recovery_ops nfs41_nograce_recovery_ops = {
8555         .owner_flag_bit = NFS_OWNER_RECLAIM_NOGRACE,
8556         .state_flag_bit = NFS_STATE_RECLAIM_NOGRACE,
8557         .recover_open   = nfs41_open_expired,
8558         .recover_lock   = nfs41_lock_expired,
8559         .establish_clid = nfs41_init_clientid,
8560 };
8561 #endif /* CONFIG_NFS_V4_1 */
8562
8563 static const struct nfs4_state_maintenance_ops nfs40_state_renewal_ops = {
8564         .sched_state_renewal = nfs4_proc_async_renew,
8565         .get_state_renewal_cred_locked = nfs4_get_renew_cred_locked,
8566         .renew_lease = nfs4_proc_renew,
8567 };
8568
8569 #if defined(CONFIG_NFS_V4_1)
8570 static const struct nfs4_state_maintenance_ops nfs41_state_renewal_ops = {
8571         .sched_state_renewal = nfs41_proc_async_sequence,
8572         .get_state_renewal_cred_locked = nfs4_get_machine_cred_locked,
8573         .renew_lease = nfs4_proc_sequence,
8574 };
8575 #endif
8576
8577 static const struct nfs4_mig_recovery_ops nfs40_mig_recovery_ops = {
8578         .get_locations = _nfs40_proc_get_locations,
8579         .fsid_present = _nfs40_proc_fsid_present,
8580 };
8581
8582 #if defined(CONFIG_NFS_V4_1)
8583 static const struct nfs4_mig_recovery_ops nfs41_mig_recovery_ops = {
8584         .get_locations = _nfs41_proc_get_locations,
8585         .fsid_present = _nfs41_proc_fsid_present,
8586 };
8587 #endif  /* CONFIG_NFS_V4_1 */
8588
8589 static const struct nfs4_minor_version_ops nfs_v4_0_minor_ops = {
8590         .minor_version = 0,
8591         .init_caps = NFS_CAP_READDIRPLUS
8592                 | NFS_CAP_ATOMIC_OPEN
8593                 | NFS_CAP_CHANGE_ATTR
8594                 | NFS_CAP_POSIX_LOCK,
8595         .init_client = nfs40_init_client,
8596         .shutdown_client = nfs40_shutdown_client,
8597         .match_stateid = nfs4_match_stateid,
8598         .find_root_sec = nfs4_find_root_sec,
8599         .free_lock_state = nfs4_release_lockowner,
8600         .alloc_seqid = nfs_alloc_seqid,
8601         .call_sync_ops = &nfs40_call_sync_ops,
8602         .reboot_recovery_ops = &nfs40_reboot_recovery_ops,
8603         .nograce_recovery_ops = &nfs40_nograce_recovery_ops,
8604         .state_renewal_ops = &nfs40_state_renewal_ops,
8605         .mig_recovery_ops = &nfs40_mig_recovery_ops,
8606 };
8607
8608 #if defined(CONFIG_NFS_V4_1)
8609 static struct nfs_seqid *
8610 nfs_alloc_no_seqid(struct nfs_seqid_counter *arg1, gfp_t arg2)
8611 {
8612         return NULL;
8613 }
8614
8615 static const struct nfs4_minor_version_ops nfs_v4_1_minor_ops = {
8616         .minor_version = 1,
8617         .init_caps = NFS_CAP_READDIRPLUS
8618                 | NFS_CAP_ATOMIC_OPEN
8619                 | NFS_CAP_CHANGE_ATTR
8620                 | NFS_CAP_POSIX_LOCK
8621                 | NFS_CAP_STATEID_NFSV41
8622                 | NFS_CAP_ATOMIC_OPEN_V1,
8623         .init_client = nfs41_init_client,
8624         .shutdown_client = nfs41_shutdown_client,
8625         .match_stateid = nfs41_match_stateid,
8626         .find_root_sec = nfs41_find_root_sec,
8627         .free_lock_state = nfs41_free_lock_state,
8628         .alloc_seqid = nfs_alloc_no_seqid,
8629         .call_sync_ops = &nfs41_call_sync_ops,
8630         .reboot_recovery_ops = &nfs41_reboot_recovery_ops,
8631         .nograce_recovery_ops = &nfs41_nograce_recovery_ops,
8632         .state_renewal_ops = &nfs41_state_renewal_ops,
8633         .mig_recovery_ops = &nfs41_mig_recovery_ops,
8634 };
8635 #endif
8636
8637 #if defined(CONFIG_NFS_V4_2)
8638 static const struct nfs4_minor_version_ops nfs_v4_2_minor_ops = {
8639         .minor_version = 2,
8640         .init_caps = NFS_CAP_READDIRPLUS
8641                 | NFS_CAP_ATOMIC_OPEN
8642                 | NFS_CAP_CHANGE_ATTR
8643                 | NFS_CAP_POSIX_LOCK
8644                 | NFS_CAP_STATEID_NFSV41
8645                 | NFS_CAP_ATOMIC_OPEN_V1
8646                 | NFS_CAP_ALLOCATE
8647                 | NFS_CAP_DEALLOCATE
8648                 | NFS_CAP_SEEK
8649                 | NFS_CAP_LAYOUTSTATS,
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  */