make get_file() return its argument
[pandora-kernel.git] / fs / nfsd / nfs4state.c
1 /*
2 *  Copyright (c) 2001 The Regents of the University of Michigan.
3 *  All rights reserved.
4 *
5 *  Kendrick Smith <kmsmith@umich.edu>
6 *  Andy Adamson <kandros@umich.edu>
7 *
8 *  Redistribution and use in source and binary forms, with or without
9 *  modification, are permitted provided that the following conditions
10 *  are met:
11 *
12 *  1. Redistributions of source code must retain the above copyright
13 *     notice, this list of conditions and the following disclaimer.
14 *  2. Redistributions in binary form must reproduce the above copyright
15 *     notice, this list of conditions and the following disclaimer in the
16 *     documentation and/or other materials provided with the distribution.
17 *  3. Neither the name of the University nor the names of its
18 *     contributors may be used to endorse or promote products derived
19 *     from this software without specific prior written permission.
20 *
21 *  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
22 *  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
23 *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
24 *  DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 *  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
28 *  BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 *  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 *  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 *
33 */
34
35 #include <linux/file.h>
36 #include <linux/fs.h>
37 #include <linux/slab.h>
38 #include <linux/namei.h>
39 #include <linux/swap.h>
40 #include <linux/pagemap.h>
41 #include <linux/sunrpc/svcauth_gss.h>
42 #include <linux/sunrpc/clnt.h>
43 #include "xdr4.h"
44 #include "vfs.h"
45
46 #define NFSDDBG_FACILITY                NFSDDBG_PROC
47
48 /* Globals */
49 time_t nfsd4_lease = 90;     /* default lease time */
50 time_t nfsd4_grace = 90;
51 static time_t boot_time;
52 static stateid_t zerostateid;             /* bits all 0 */
53 static stateid_t onestateid;              /* bits all 1 */
54 static u64 current_sessionid = 1;
55
56 #define ZERO_STATEID(stateid) (!memcmp((stateid), &zerostateid, sizeof(stateid_t)))
57 #define ONE_STATEID(stateid)  (!memcmp((stateid), &onestateid, sizeof(stateid_t)))
58
59 /* forward declarations */
60 static int check_for_locks(struct nfs4_file *filp, struct nfs4_lockowner *lowner);
61
62 /* Locking: */
63
64 /* Currently used for almost all code touching nfsv4 state: */
65 static DEFINE_MUTEX(client_mutex);
66
67 /*
68  * Currently used for the del_recall_lru and file hash table.  In an
69  * effort to decrease the scope of the client_mutex, this spinlock may
70  * eventually cover more:
71  */
72 static DEFINE_SPINLOCK(recall_lock);
73
74 static struct kmem_cache *openowner_slab = NULL;
75 static struct kmem_cache *lockowner_slab = NULL;
76 static struct kmem_cache *file_slab = NULL;
77 static struct kmem_cache *stateid_slab = NULL;
78 static struct kmem_cache *deleg_slab = NULL;
79
80 void
81 nfs4_lock_state(void)
82 {
83         mutex_lock(&client_mutex);
84 }
85
86 void
87 nfs4_unlock_state(void)
88 {
89         mutex_unlock(&client_mutex);
90 }
91
92 static inline u32
93 opaque_hashval(const void *ptr, int nbytes)
94 {
95         unsigned char *cptr = (unsigned char *) ptr;
96
97         u32 x = 0;
98         while (nbytes--) {
99                 x *= 37;
100                 x += *cptr++;
101         }
102         return x;
103 }
104
105 static struct list_head del_recall_lru;
106
107 static void nfsd4_free_file(struct nfs4_file *f)
108 {
109         kmem_cache_free(file_slab, f);
110 }
111
112 static inline void
113 put_nfs4_file(struct nfs4_file *fi)
114 {
115         if (atomic_dec_and_lock(&fi->fi_ref, &recall_lock)) {
116                 list_del(&fi->fi_hash);
117                 spin_unlock(&recall_lock);
118                 iput(fi->fi_inode);
119                 nfsd4_free_file(fi);
120         }
121 }
122
123 static inline void
124 get_nfs4_file(struct nfs4_file *fi)
125 {
126         atomic_inc(&fi->fi_ref);
127 }
128
129 static int num_delegations;
130 unsigned int max_delegations;
131
132 /*
133  * Open owner state (share locks)
134  */
135
136 /* hash tables for open owners */
137 #define OPEN_OWNER_HASH_BITS              8
138 #define OPEN_OWNER_HASH_SIZE             (1 << OPEN_OWNER_HASH_BITS)
139 #define OPEN_OWNER_HASH_MASK             (OPEN_OWNER_HASH_SIZE - 1)
140
141 static unsigned int open_ownerstr_hashval(u32 clientid, struct xdr_netobj *ownername)
142 {
143         unsigned int ret;
144
145         ret = opaque_hashval(ownername->data, ownername->len);
146         ret += clientid;
147         return ret & OPEN_OWNER_HASH_MASK;
148 }
149
150 static struct list_head open_ownerstr_hashtbl[OPEN_OWNER_HASH_SIZE];
151
152 /* hash table for nfs4_file */
153 #define FILE_HASH_BITS                   8
154 #define FILE_HASH_SIZE                  (1 << FILE_HASH_BITS)
155
156 static unsigned int file_hashval(struct inode *ino)
157 {
158         /* XXX: why are we hashing on inode pointer, anyway? */
159         return hash_ptr(ino, FILE_HASH_BITS);
160 }
161
162 static struct list_head file_hashtbl[FILE_HASH_SIZE];
163
164 static void __nfs4_file_get_access(struct nfs4_file *fp, int oflag)
165 {
166         BUG_ON(!(fp->fi_fds[oflag] || fp->fi_fds[O_RDWR]));
167         atomic_inc(&fp->fi_access[oflag]);
168 }
169
170 static void nfs4_file_get_access(struct nfs4_file *fp, int oflag)
171 {
172         if (oflag == O_RDWR) {
173                 __nfs4_file_get_access(fp, O_RDONLY);
174                 __nfs4_file_get_access(fp, O_WRONLY);
175         } else
176                 __nfs4_file_get_access(fp, oflag);
177 }
178
179 static void nfs4_file_put_fd(struct nfs4_file *fp, int oflag)
180 {
181         if (fp->fi_fds[oflag]) {
182                 fput(fp->fi_fds[oflag]);
183                 fp->fi_fds[oflag] = NULL;
184         }
185 }
186
187 static void __nfs4_file_put_access(struct nfs4_file *fp, int oflag)
188 {
189         if (atomic_dec_and_test(&fp->fi_access[oflag])) {
190                 nfs4_file_put_fd(fp, oflag);
191                 if (atomic_read(&fp->fi_access[1 - oflag]) == 0)
192                         nfs4_file_put_fd(fp, O_RDWR);
193         }
194 }
195
196 static void nfs4_file_put_access(struct nfs4_file *fp, int oflag)
197 {
198         if (oflag == O_RDWR) {
199                 __nfs4_file_put_access(fp, O_RDONLY);
200                 __nfs4_file_put_access(fp, O_WRONLY);
201         } else
202                 __nfs4_file_put_access(fp, oflag);
203 }
204
205 static inline int get_new_stid(struct nfs4_stid *stid)
206 {
207         static int min_stateid = 0;
208         struct idr *stateids = &stid->sc_client->cl_stateids;
209         int new_stid;
210         int error;
211
212         error = idr_get_new_above(stateids, stid, min_stateid, &new_stid);
213         /*
214          * Note: the necessary preallocation was done in
215          * nfs4_alloc_stateid().  The idr code caps the number of
216          * preallocations that can exist at a time, but the state lock
217          * prevents anyone from using ours before we get here:
218          */
219         BUG_ON(error);
220         /*
221          * It shouldn't be a problem to reuse an opaque stateid value.
222          * I don't think it is for 4.1.  But with 4.0 I worry that, for
223          * example, a stray write retransmission could be accepted by
224          * the server when it should have been rejected.  Therefore,
225          * adopt a trick from the sctp code to attempt to maximize the
226          * amount of time until an id is reused, by ensuring they always
227          * "increase" (mod INT_MAX):
228          */
229
230         min_stateid = new_stid+1;
231         if (min_stateid == INT_MAX)
232                 min_stateid = 0;
233         return new_stid;
234 }
235
236 static void init_stid(struct nfs4_stid *stid, struct nfs4_client *cl, unsigned char type)
237 {
238         stateid_t *s = &stid->sc_stateid;
239         int new_id;
240
241         stid->sc_type = type;
242         stid->sc_client = cl;
243         s->si_opaque.so_clid = cl->cl_clientid;
244         new_id = get_new_stid(stid);
245         s->si_opaque.so_id = (u32)new_id;
246         /* Will be incremented before return to client: */
247         s->si_generation = 0;
248 }
249
250 static struct nfs4_stid *nfs4_alloc_stid(struct nfs4_client *cl, struct kmem_cache *slab)
251 {
252         struct idr *stateids = &cl->cl_stateids;
253
254         if (!idr_pre_get(stateids, GFP_KERNEL))
255                 return NULL;
256         /*
257          * Note: if we fail here (or any time between now and the time
258          * we actually get the new idr), we won't need to undo the idr
259          * preallocation, since the idr code caps the number of
260          * preallocated entries.
261          */
262         return kmem_cache_alloc(slab, GFP_KERNEL);
263 }
264
265 static struct nfs4_ol_stateid * nfs4_alloc_stateid(struct nfs4_client *clp)
266 {
267         return openlockstateid(nfs4_alloc_stid(clp, stateid_slab));
268 }
269
270 static struct nfs4_delegation *
271 alloc_init_deleg(struct nfs4_client *clp, struct nfs4_ol_stateid *stp, struct svc_fh *current_fh, u32 type)
272 {
273         struct nfs4_delegation *dp;
274         struct nfs4_file *fp = stp->st_file;
275
276         dprintk("NFSD alloc_init_deleg\n");
277         /*
278          * Major work on the lease subsystem (for example, to support
279          * calbacks on stat) will be required before we can support
280          * write delegations properly.
281          */
282         if (type != NFS4_OPEN_DELEGATE_READ)
283                 return NULL;
284         if (fp->fi_had_conflict)
285                 return NULL;
286         if (num_delegations > max_delegations)
287                 return NULL;
288         dp = delegstateid(nfs4_alloc_stid(clp, deleg_slab));
289         if (dp == NULL)
290                 return dp;
291         init_stid(&dp->dl_stid, clp, NFS4_DELEG_STID);
292         /*
293          * delegation seqid's are never incremented.  The 4.1 special
294          * meaning of seqid 0 isn't meaningful, really, but let's avoid
295          * 0 anyway just for consistency and use 1:
296          */
297         dp->dl_stid.sc_stateid.si_generation = 1;
298         num_delegations++;
299         INIT_LIST_HEAD(&dp->dl_perfile);
300         INIT_LIST_HEAD(&dp->dl_perclnt);
301         INIT_LIST_HEAD(&dp->dl_recall_lru);
302         get_nfs4_file(fp);
303         dp->dl_file = fp;
304         dp->dl_type = type;
305         fh_copy_shallow(&dp->dl_fh, &current_fh->fh_handle);
306         dp->dl_time = 0;
307         atomic_set(&dp->dl_count, 1);
308         INIT_WORK(&dp->dl_recall.cb_work, nfsd4_do_callback_rpc);
309         return dp;
310 }
311
312 void
313 nfs4_put_delegation(struct nfs4_delegation *dp)
314 {
315         if (atomic_dec_and_test(&dp->dl_count)) {
316                 dprintk("NFSD: freeing dp %p\n",dp);
317                 put_nfs4_file(dp->dl_file);
318                 kmem_cache_free(deleg_slab, dp);
319                 num_delegations--;
320         }
321 }
322
323 static void nfs4_put_deleg_lease(struct nfs4_file *fp)
324 {
325         if (atomic_dec_and_test(&fp->fi_delegees)) {
326                 vfs_setlease(fp->fi_deleg_file, F_UNLCK, &fp->fi_lease);
327                 fp->fi_lease = NULL;
328                 fput(fp->fi_deleg_file);
329                 fp->fi_deleg_file = NULL;
330         }
331 }
332
333 static void unhash_stid(struct nfs4_stid *s)
334 {
335         struct idr *stateids = &s->sc_client->cl_stateids;
336
337         idr_remove(stateids, s->sc_stateid.si_opaque.so_id);
338 }
339
340 static void
341 hash_delegation_locked(struct nfs4_delegation *dp, struct nfs4_file *fp)
342 {
343         lockdep_assert_held(&recall_lock);
344
345         list_add(&dp->dl_perfile, &fp->fi_delegations);
346         list_add(&dp->dl_perclnt, &dp->dl_stid.sc_client->cl_delegations);
347 }
348
349 /* Called under the state lock. */
350 static void
351 unhash_delegation(struct nfs4_delegation *dp)
352 {
353         unhash_stid(&dp->dl_stid);
354         spin_lock(&recall_lock);
355         list_del_init(&dp->dl_perclnt);
356         list_del_init(&dp->dl_perfile);
357         list_del_init(&dp->dl_recall_lru);
358         spin_unlock(&recall_lock);
359         nfs4_put_deleg_lease(dp->dl_file);
360         nfs4_put_delegation(dp);
361 }
362
363 /* 
364  * SETCLIENTID state 
365  */
366
367 /* client_lock protects the client lru list and session hash table */
368 static DEFINE_SPINLOCK(client_lock);
369
370 /* Hash tables for nfs4_clientid state */
371 #define CLIENT_HASH_BITS                 4
372 #define CLIENT_HASH_SIZE                (1 << CLIENT_HASH_BITS)
373 #define CLIENT_HASH_MASK                (CLIENT_HASH_SIZE - 1)
374
375 static unsigned int clientid_hashval(u32 id)
376 {
377         return id & CLIENT_HASH_MASK;
378 }
379
380 static unsigned int clientstr_hashval(const char *name)
381 {
382         return opaque_hashval(name, 8) & CLIENT_HASH_MASK;
383 }
384
385 /*
386  * reclaim_str_hashtbl[] holds known client info from previous reset/reboot
387  * used in reboot/reset lease grace period processing
388  *
389  * conf_id_hashtbl[], and conf_str_hashtbl[] hold confirmed
390  * setclientid_confirmed info. 
391  *
392  * unconf_str_hastbl[] and unconf_id_hashtbl[] hold unconfirmed 
393  * setclientid info.
394  *
395  * client_lru holds client queue ordered by nfs4_client.cl_time
396  * for lease renewal.
397  *
398  * close_lru holds (open) stateowner queue ordered by nfs4_stateowner.so_time
399  * for last close replay.
400  */
401 static struct list_head reclaim_str_hashtbl[CLIENT_HASH_SIZE];
402 static int reclaim_str_hashtbl_size = 0;
403 static struct list_head conf_id_hashtbl[CLIENT_HASH_SIZE];
404 static struct list_head conf_str_hashtbl[CLIENT_HASH_SIZE];
405 static struct list_head unconf_str_hashtbl[CLIENT_HASH_SIZE];
406 static struct list_head unconf_id_hashtbl[CLIENT_HASH_SIZE];
407 static struct list_head client_lru;
408 static struct list_head close_lru;
409
410 /*
411  * We store the NONE, READ, WRITE, and BOTH bits separately in the
412  * st_{access,deny}_bmap field of the stateid, in order to track not
413  * only what share bits are currently in force, but also what
414  * combinations of share bits previous opens have used.  This allows us
415  * to enforce the recommendation of rfc 3530 14.2.19 that the server
416  * return an error if the client attempt to downgrade to a combination
417  * of share bits not explicable by closing some of its previous opens.
418  *
419  * XXX: This enforcement is actually incomplete, since we don't keep
420  * track of access/deny bit combinations; so, e.g., we allow:
421  *
422  *      OPEN allow read, deny write
423  *      OPEN allow both, deny none
424  *      DOWNGRADE allow read, deny none
425  *
426  * which we should reject.
427  */
428 static void
429 set_access(unsigned int *access, unsigned long bmap) {
430         int i;
431
432         *access = 0;
433         for (i = 1; i < 4; i++) {
434                 if (test_bit(i, &bmap))
435                         *access |= i;
436         }
437 }
438
439 static void
440 set_deny(unsigned int *deny, unsigned long bmap) {
441         int i;
442
443         *deny = 0;
444         for (i = 0; i < 4; i++) {
445                 if (test_bit(i, &bmap))
446                         *deny |= i ;
447         }
448 }
449
450 static int
451 test_share(struct nfs4_ol_stateid *stp, struct nfsd4_open *open) {
452         unsigned int access, deny;
453
454         set_access(&access, stp->st_access_bmap);
455         set_deny(&deny, stp->st_deny_bmap);
456         if ((access & open->op_share_deny) || (deny & open->op_share_access))
457                 return 0;
458         return 1;
459 }
460
461 static int nfs4_access_to_omode(u32 access)
462 {
463         switch (access & NFS4_SHARE_ACCESS_BOTH) {
464         case NFS4_SHARE_ACCESS_READ:
465                 return O_RDONLY;
466         case NFS4_SHARE_ACCESS_WRITE:
467                 return O_WRONLY;
468         case NFS4_SHARE_ACCESS_BOTH:
469                 return O_RDWR;
470         }
471         BUG();
472 }
473
474 static void unhash_generic_stateid(struct nfs4_ol_stateid *stp)
475 {
476         list_del(&stp->st_perfile);
477         list_del(&stp->st_perstateowner);
478 }
479
480 static void close_generic_stateid(struct nfs4_ol_stateid *stp)
481 {
482         int i;
483
484         if (stp->st_access_bmap) {
485                 for (i = 1; i < 4; i++) {
486                         if (test_bit(i, &stp->st_access_bmap))
487                                 nfs4_file_put_access(stp->st_file,
488                                                 nfs4_access_to_omode(i));
489                         __clear_bit(i, &stp->st_access_bmap);
490                 }
491         }
492         put_nfs4_file(stp->st_file);
493         stp->st_file = NULL;
494 }
495
496 static void free_generic_stateid(struct nfs4_ol_stateid *stp)
497 {
498         kmem_cache_free(stateid_slab, stp);
499 }
500
501 static void release_lock_stateid(struct nfs4_ol_stateid *stp)
502 {
503         struct file *file;
504
505         unhash_generic_stateid(stp);
506         unhash_stid(&stp->st_stid);
507         file = find_any_file(stp->st_file);
508         if (file)
509                 locks_remove_posix(file, (fl_owner_t)lockowner(stp->st_stateowner));
510         close_generic_stateid(stp);
511         free_generic_stateid(stp);
512 }
513
514 static void unhash_lockowner(struct nfs4_lockowner *lo)
515 {
516         struct nfs4_ol_stateid *stp;
517
518         list_del(&lo->lo_owner.so_strhash);
519         list_del(&lo->lo_perstateid);
520         while (!list_empty(&lo->lo_owner.so_stateids)) {
521                 stp = list_first_entry(&lo->lo_owner.so_stateids,
522                                 struct nfs4_ol_stateid, st_perstateowner);
523                 release_lock_stateid(stp);
524         }
525 }
526
527 static void release_lockowner(struct nfs4_lockowner *lo)
528 {
529         unhash_lockowner(lo);
530         nfs4_free_lockowner(lo);
531 }
532
533 static void
534 release_stateid_lockowners(struct nfs4_ol_stateid *open_stp)
535 {
536         struct nfs4_lockowner *lo;
537
538         while (!list_empty(&open_stp->st_lockowners)) {
539                 lo = list_entry(open_stp->st_lockowners.next,
540                                 struct nfs4_lockowner, lo_perstateid);
541                 release_lockowner(lo);
542         }
543 }
544
545 static void unhash_open_stateid(struct nfs4_ol_stateid *stp)
546 {
547         unhash_generic_stateid(stp);
548         release_stateid_lockowners(stp);
549         close_generic_stateid(stp);
550 }
551
552 static void release_open_stateid(struct nfs4_ol_stateid *stp)
553 {
554         unhash_open_stateid(stp);
555         unhash_stid(&stp->st_stid);
556         free_generic_stateid(stp);
557 }
558
559 static void unhash_openowner(struct nfs4_openowner *oo)
560 {
561         struct nfs4_ol_stateid *stp;
562
563         list_del(&oo->oo_owner.so_strhash);
564         list_del(&oo->oo_perclient);
565         while (!list_empty(&oo->oo_owner.so_stateids)) {
566                 stp = list_first_entry(&oo->oo_owner.so_stateids,
567                                 struct nfs4_ol_stateid, st_perstateowner);
568                 release_open_stateid(stp);
569         }
570 }
571
572 static void release_last_closed_stateid(struct nfs4_openowner *oo)
573 {
574         struct nfs4_ol_stateid *s = oo->oo_last_closed_stid;
575
576         if (s) {
577                 unhash_stid(&s->st_stid);
578                 free_generic_stateid(s);
579                 oo->oo_last_closed_stid = NULL;
580         }
581 }
582
583 static void release_openowner(struct nfs4_openowner *oo)
584 {
585         unhash_openowner(oo);
586         list_del(&oo->oo_close_lru);
587         release_last_closed_stateid(oo);
588         nfs4_free_openowner(oo);
589 }
590
591 #define SESSION_HASH_SIZE       512
592 static struct list_head sessionid_hashtbl[SESSION_HASH_SIZE];
593
594 static inline int
595 hash_sessionid(struct nfs4_sessionid *sessionid)
596 {
597         struct nfsd4_sessionid *sid = (struct nfsd4_sessionid *)sessionid;
598
599         return sid->sequence % SESSION_HASH_SIZE;
600 }
601
602 static inline void
603 dump_sessionid(const char *fn, struct nfs4_sessionid *sessionid)
604 {
605         u32 *ptr = (u32 *)(&sessionid->data[0]);
606         dprintk("%s: %u:%u:%u:%u\n", fn, ptr[0], ptr[1], ptr[2], ptr[3]);
607 }
608
609 static void
610 gen_sessionid(struct nfsd4_session *ses)
611 {
612         struct nfs4_client *clp = ses->se_client;
613         struct nfsd4_sessionid *sid;
614
615         sid = (struct nfsd4_sessionid *)ses->se_sessionid.data;
616         sid->clientid = clp->cl_clientid;
617         sid->sequence = current_sessionid++;
618         sid->reserved = 0;
619 }
620
621 /*
622  * The protocol defines ca_maxresponssize_cached to include the size of
623  * the rpc header, but all we need to cache is the data starting after
624  * the end of the initial SEQUENCE operation--the rest we regenerate
625  * each time.  Therefore we can advertise a ca_maxresponssize_cached
626  * value that is the number of bytes in our cache plus a few additional
627  * bytes.  In order to stay on the safe side, and not promise more than
628  * we can cache, those additional bytes must be the minimum possible: 24
629  * bytes of rpc header (xid through accept state, with AUTH_NULL
630  * verifier), 12 for the compound header (with zero-length tag), and 44
631  * for the SEQUENCE op response:
632  */
633 #define NFSD_MIN_HDR_SEQ_SZ  (24 + 12 + 44)
634
635 static void
636 free_session_slots(struct nfsd4_session *ses)
637 {
638         int i;
639
640         for (i = 0; i < ses->se_fchannel.maxreqs; i++)
641                 kfree(ses->se_slots[i]);
642 }
643
644 /*
645  * We don't actually need to cache the rpc and session headers, so we
646  * can allocate a little less for each slot:
647  */
648 static inline int slot_bytes(struct nfsd4_channel_attrs *ca)
649 {
650         return ca->maxresp_cached - NFSD_MIN_HDR_SEQ_SZ;
651 }
652
653 static int nfsd4_sanitize_slot_size(u32 size)
654 {
655         size -= NFSD_MIN_HDR_SEQ_SZ; /* We don't cache the rpc header */
656         size = min_t(u32, size, NFSD_SLOT_CACHE_SIZE);
657
658         return size;
659 }
660
661 /*
662  * XXX: If we run out of reserved DRC memory we could (up to a point)
663  * re-negotiate active sessions and reduce their slot usage to make
664  * rooom for new connections. For now we just fail the create session.
665  */
666 static int nfsd4_get_drc_mem(int slotsize, u32 num)
667 {
668         int avail;
669
670         num = min_t(u32, num, NFSD_MAX_SLOTS_PER_SESSION);
671
672         spin_lock(&nfsd_drc_lock);
673         avail = min_t(int, NFSD_MAX_MEM_PER_SESSION,
674                         nfsd_drc_max_mem - nfsd_drc_mem_used);
675         num = min_t(int, num, avail / slotsize);
676         nfsd_drc_mem_used += num * slotsize;
677         spin_unlock(&nfsd_drc_lock);
678
679         return num;
680 }
681
682 static void nfsd4_put_drc_mem(int slotsize, int num)
683 {
684         spin_lock(&nfsd_drc_lock);
685         nfsd_drc_mem_used -= slotsize * num;
686         spin_unlock(&nfsd_drc_lock);
687 }
688
689 static struct nfsd4_session *alloc_session(int slotsize, int numslots)
690 {
691         struct nfsd4_session *new;
692         int mem, i;
693
694         BUILD_BUG_ON(NFSD_MAX_SLOTS_PER_SESSION * sizeof(struct nfsd4_slot *)
695                         + sizeof(struct nfsd4_session) > PAGE_SIZE);
696         mem = numslots * sizeof(struct nfsd4_slot *);
697
698         new = kzalloc(sizeof(*new) + mem, GFP_KERNEL);
699         if (!new)
700                 return NULL;
701         /* allocate each struct nfsd4_slot and data cache in one piece */
702         for (i = 0; i < numslots; i++) {
703                 mem = sizeof(struct nfsd4_slot) + slotsize;
704                 new->se_slots[i] = kzalloc(mem, GFP_KERNEL);
705                 if (!new->se_slots[i])
706                         goto out_free;
707         }
708         return new;
709 out_free:
710         while (i--)
711                 kfree(new->se_slots[i]);
712         kfree(new);
713         return NULL;
714 }
715
716 static void init_forechannel_attrs(struct nfsd4_channel_attrs *new, struct nfsd4_channel_attrs *req, int numslots, int slotsize)
717 {
718         u32 maxrpc = nfsd_serv->sv_max_mesg;
719
720         new->maxreqs = numslots;
721         new->maxresp_cached = min_t(u32, req->maxresp_cached,
722                                         slotsize + NFSD_MIN_HDR_SEQ_SZ);
723         new->maxreq_sz = min_t(u32, req->maxreq_sz, maxrpc);
724         new->maxresp_sz = min_t(u32, req->maxresp_sz, maxrpc);
725         new->maxops = min_t(u32, req->maxops, NFSD_MAX_OPS_PER_COMPOUND);
726 }
727
728 static void free_conn(struct nfsd4_conn *c)
729 {
730         svc_xprt_put(c->cn_xprt);
731         kfree(c);
732 }
733
734 static void nfsd4_conn_lost(struct svc_xpt_user *u)
735 {
736         struct nfsd4_conn *c = container_of(u, struct nfsd4_conn, cn_xpt_user);
737         struct nfs4_client *clp = c->cn_session->se_client;
738
739         spin_lock(&clp->cl_lock);
740         if (!list_empty(&c->cn_persession)) {
741                 list_del(&c->cn_persession);
742                 free_conn(c);
743         }
744         spin_unlock(&clp->cl_lock);
745         nfsd4_probe_callback(clp);
746 }
747
748 static struct nfsd4_conn *alloc_conn(struct svc_rqst *rqstp, u32 flags)
749 {
750         struct nfsd4_conn *conn;
751
752         conn = kmalloc(sizeof(struct nfsd4_conn), GFP_KERNEL);
753         if (!conn)
754                 return NULL;
755         svc_xprt_get(rqstp->rq_xprt);
756         conn->cn_xprt = rqstp->rq_xprt;
757         conn->cn_flags = flags;
758         INIT_LIST_HEAD(&conn->cn_xpt_user.list);
759         return conn;
760 }
761
762 static void __nfsd4_hash_conn(struct nfsd4_conn *conn, struct nfsd4_session *ses)
763 {
764         conn->cn_session = ses;
765         list_add(&conn->cn_persession, &ses->se_conns);
766 }
767
768 static void nfsd4_hash_conn(struct nfsd4_conn *conn, struct nfsd4_session *ses)
769 {
770         struct nfs4_client *clp = ses->se_client;
771
772         spin_lock(&clp->cl_lock);
773         __nfsd4_hash_conn(conn, ses);
774         spin_unlock(&clp->cl_lock);
775 }
776
777 static int nfsd4_register_conn(struct nfsd4_conn *conn)
778 {
779         conn->cn_xpt_user.callback = nfsd4_conn_lost;
780         return register_xpt_user(conn->cn_xprt, &conn->cn_xpt_user);
781 }
782
783 static __be32 nfsd4_new_conn(struct svc_rqst *rqstp, struct nfsd4_session *ses, u32 dir)
784 {
785         struct nfsd4_conn *conn;
786         int ret;
787
788         conn = alloc_conn(rqstp, dir);
789         if (!conn)
790                 return nfserr_jukebox;
791         nfsd4_hash_conn(conn, ses);
792         ret = nfsd4_register_conn(conn);
793         if (ret)
794                 /* oops; xprt is already down: */
795                 nfsd4_conn_lost(&conn->cn_xpt_user);
796         return nfs_ok;
797 }
798
799 static __be32 nfsd4_new_conn_from_crses(struct svc_rqst *rqstp, struct nfsd4_session *ses)
800 {
801         u32 dir = NFS4_CDFC4_FORE;
802
803         if (ses->se_flags & SESSION4_BACK_CHAN)
804                 dir |= NFS4_CDFC4_BACK;
805
806         return nfsd4_new_conn(rqstp, ses, dir);
807 }
808
809 /* must be called under client_lock */
810 static void nfsd4_del_conns(struct nfsd4_session *s)
811 {
812         struct nfs4_client *clp = s->se_client;
813         struct nfsd4_conn *c;
814
815         spin_lock(&clp->cl_lock);
816         while (!list_empty(&s->se_conns)) {
817                 c = list_first_entry(&s->se_conns, struct nfsd4_conn, cn_persession);
818                 list_del_init(&c->cn_persession);
819                 spin_unlock(&clp->cl_lock);
820
821                 unregister_xpt_user(c->cn_xprt, &c->cn_xpt_user);
822                 free_conn(c);
823
824                 spin_lock(&clp->cl_lock);
825         }
826         spin_unlock(&clp->cl_lock);
827 }
828
829 void free_session(struct kref *kref)
830 {
831         struct nfsd4_session *ses;
832         int mem;
833
834         ses = container_of(kref, struct nfsd4_session, se_ref);
835         nfsd4_del_conns(ses);
836         spin_lock(&nfsd_drc_lock);
837         mem = ses->se_fchannel.maxreqs * slot_bytes(&ses->se_fchannel);
838         nfsd_drc_mem_used -= mem;
839         spin_unlock(&nfsd_drc_lock);
840         free_session_slots(ses);
841         kfree(ses);
842 }
843
844 static struct nfsd4_session *alloc_init_session(struct svc_rqst *rqstp, struct nfs4_client *clp, struct nfsd4_create_session *cses)
845 {
846         struct nfsd4_session *new;
847         struct nfsd4_channel_attrs *fchan = &cses->fore_channel;
848         int numslots, slotsize;
849         int status;
850         int idx;
851
852         /*
853          * Note decreasing slot size below client's request may
854          * make it difficult for client to function correctly, whereas
855          * decreasing the number of slots will (just?) affect
856          * performance.  When short on memory we therefore prefer to
857          * decrease number of slots instead of their size.
858          */
859         slotsize = nfsd4_sanitize_slot_size(fchan->maxresp_cached);
860         numslots = nfsd4_get_drc_mem(slotsize, fchan->maxreqs);
861         if (numslots < 1)
862                 return NULL;
863
864         new = alloc_session(slotsize, numslots);
865         if (!new) {
866                 nfsd4_put_drc_mem(slotsize, fchan->maxreqs);
867                 return NULL;
868         }
869         init_forechannel_attrs(&new->se_fchannel, fchan, numslots, slotsize);
870
871         new->se_client = clp;
872         gen_sessionid(new);
873
874         INIT_LIST_HEAD(&new->se_conns);
875
876         new->se_cb_seq_nr = 1;
877         new->se_flags = cses->flags;
878         new->se_cb_prog = cses->callback_prog;
879         kref_init(&new->se_ref);
880         idx = hash_sessionid(&new->se_sessionid);
881         spin_lock(&client_lock);
882         list_add(&new->se_hash, &sessionid_hashtbl[idx]);
883         spin_lock(&clp->cl_lock);
884         list_add(&new->se_perclnt, &clp->cl_sessions);
885         spin_unlock(&clp->cl_lock);
886         spin_unlock(&client_lock);
887
888         status = nfsd4_new_conn_from_crses(rqstp, new);
889         /* whoops: benny points out, status is ignored! (err, or bogus) */
890         if (status) {
891                 free_session(&new->se_ref);
892                 return NULL;
893         }
894         if (cses->flags & SESSION4_BACK_CHAN) {
895                 struct sockaddr *sa = svc_addr(rqstp);
896                 /*
897                  * This is a little silly; with sessions there's no real
898                  * use for the callback address.  Use the peer address
899                  * as a reasonable default for now, but consider fixing
900                  * the rpc client not to require an address in the
901                  * future:
902                  */
903                 rpc_copy_addr((struct sockaddr *)&clp->cl_cb_conn.cb_addr, sa);
904                 clp->cl_cb_conn.cb_addrlen = svc_addr_len(sa);
905         }
906         nfsd4_probe_callback(clp);
907         return new;
908 }
909
910 /* caller must hold client_lock */
911 static struct nfsd4_session *
912 find_in_sessionid_hashtbl(struct nfs4_sessionid *sessionid)
913 {
914         struct nfsd4_session *elem;
915         int idx;
916
917         dump_sessionid(__func__, sessionid);
918         idx = hash_sessionid(sessionid);
919         /* Search in the appropriate list */
920         list_for_each_entry(elem, &sessionid_hashtbl[idx], se_hash) {
921                 if (!memcmp(elem->se_sessionid.data, sessionid->data,
922                             NFS4_MAX_SESSIONID_LEN)) {
923                         return elem;
924                 }
925         }
926
927         dprintk("%s: session not found\n", __func__);
928         return NULL;
929 }
930
931 /* caller must hold client_lock */
932 static void
933 unhash_session(struct nfsd4_session *ses)
934 {
935         list_del(&ses->se_hash);
936         spin_lock(&ses->se_client->cl_lock);
937         list_del(&ses->se_perclnt);
938         spin_unlock(&ses->se_client->cl_lock);
939 }
940
941 /* must be called under the client_lock */
942 static inline void
943 renew_client_locked(struct nfs4_client *clp)
944 {
945         if (is_client_expired(clp)) {
946                 dprintk("%s: client (clientid %08x/%08x) already expired\n",
947                         __func__,
948                         clp->cl_clientid.cl_boot,
949                         clp->cl_clientid.cl_id);
950                 return;
951         }
952
953         dprintk("renewing client (clientid %08x/%08x)\n", 
954                         clp->cl_clientid.cl_boot, 
955                         clp->cl_clientid.cl_id);
956         list_move_tail(&clp->cl_lru, &client_lru);
957         clp->cl_time = get_seconds();
958 }
959
960 static inline void
961 renew_client(struct nfs4_client *clp)
962 {
963         spin_lock(&client_lock);
964         renew_client_locked(clp);
965         spin_unlock(&client_lock);
966 }
967
968 /* SETCLIENTID and SETCLIENTID_CONFIRM Helper functions */
969 static int
970 STALE_CLIENTID(clientid_t *clid)
971 {
972         if (clid->cl_boot == boot_time)
973                 return 0;
974         dprintk("NFSD stale clientid (%08x/%08x) boot_time %08lx\n",
975                 clid->cl_boot, clid->cl_id, boot_time);
976         return 1;
977 }
978
979 /* 
980  * XXX Should we use a slab cache ?
981  * This type of memory management is somewhat inefficient, but we use it
982  * anyway since SETCLIENTID is not a common operation.
983  */
984 static struct nfs4_client *alloc_client(struct xdr_netobj name)
985 {
986         struct nfs4_client *clp;
987
988         clp = kzalloc(sizeof(struct nfs4_client), GFP_KERNEL);
989         if (clp == NULL)
990                 return NULL;
991         clp->cl_name.data = kmalloc(name.len, GFP_KERNEL);
992         if (clp->cl_name.data == NULL) {
993                 kfree(clp);
994                 return NULL;
995         }
996         memcpy(clp->cl_name.data, name.data, name.len);
997         clp->cl_name.len = name.len;
998         INIT_LIST_HEAD(&clp->cl_sessions);
999         idr_init(&clp->cl_stateids);
1000         atomic_set(&clp->cl_refcount, 0);
1001         clp->cl_cb_state = NFSD4_CB_UNKNOWN;
1002         INIT_LIST_HEAD(&clp->cl_idhash);
1003         INIT_LIST_HEAD(&clp->cl_strhash);
1004         INIT_LIST_HEAD(&clp->cl_openowners);
1005         INIT_LIST_HEAD(&clp->cl_delegations);
1006         INIT_LIST_HEAD(&clp->cl_lru);
1007         INIT_LIST_HEAD(&clp->cl_callbacks);
1008         spin_lock_init(&clp->cl_lock);
1009         rpc_init_wait_queue(&clp->cl_cb_waitq, "Backchannel slot table");
1010         return clp;
1011 }
1012
1013 static inline void
1014 free_client(struct nfs4_client *clp)
1015 {
1016         while (!list_empty(&clp->cl_sessions)) {
1017                 struct nfsd4_session *ses;
1018                 ses = list_entry(clp->cl_sessions.next, struct nfsd4_session,
1019                                 se_perclnt);
1020                 list_del(&ses->se_perclnt);
1021                 nfsd4_put_session(ses);
1022         }
1023         rpc_destroy_wait_queue(&clp->cl_cb_waitq);
1024         if (clp->cl_cred.cr_group_info)
1025                 put_group_info(clp->cl_cred.cr_group_info);
1026         kfree(clp->cl_principal);
1027         kfree(clp->cl_name.data);
1028         idr_remove_all(&clp->cl_stateids);
1029         idr_destroy(&clp->cl_stateids);
1030         kfree(clp);
1031 }
1032
1033 void
1034 release_session_client(struct nfsd4_session *session)
1035 {
1036         struct nfs4_client *clp = session->se_client;
1037
1038         if (!atomic_dec_and_lock(&clp->cl_refcount, &client_lock))
1039                 return;
1040         if (is_client_expired(clp)) {
1041                 free_client(clp);
1042                 session->se_client = NULL;
1043         } else
1044                 renew_client_locked(clp);
1045         spin_unlock(&client_lock);
1046 }
1047
1048 /* must be called under the client_lock */
1049 static inline void
1050 unhash_client_locked(struct nfs4_client *clp)
1051 {
1052         struct nfsd4_session *ses;
1053
1054         mark_client_expired(clp);
1055         list_del(&clp->cl_lru);
1056         spin_lock(&clp->cl_lock);
1057         list_for_each_entry(ses, &clp->cl_sessions, se_perclnt)
1058                 list_del_init(&ses->se_hash);
1059         spin_unlock(&clp->cl_lock);
1060 }
1061
1062 static void
1063 expire_client(struct nfs4_client *clp)
1064 {
1065         struct nfs4_openowner *oo;
1066         struct nfs4_delegation *dp;
1067         struct list_head reaplist;
1068
1069         INIT_LIST_HEAD(&reaplist);
1070         spin_lock(&recall_lock);
1071         while (!list_empty(&clp->cl_delegations)) {
1072                 dp = list_entry(clp->cl_delegations.next, struct nfs4_delegation, dl_perclnt);
1073                 list_del_init(&dp->dl_perclnt);
1074                 list_move(&dp->dl_recall_lru, &reaplist);
1075         }
1076         spin_unlock(&recall_lock);
1077         while (!list_empty(&reaplist)) {
1078                 dp = list_entry(reaplist.next, struct nfs4_delegation, dl_recall_lru);
1079                 list_del_init(&dp->dl_recall_lru);
1080                 unhash_delegation(dp);
1081         }
1082         while (!list_empty(&clp->cl_openowners)) {
1083                 oo = list_entry(clp->cl_openowners.next, struct nfs4_openowner, oo_perclient);
1084                 release_openowner(oo);
1085         }
1086         nfsd4_shutdown_callback(clp);
1087         if (clp->cl_cb_conn.cb_xprt)
1088                 svc_xprt_put(clp->cl_cb_conn.cb_xprt);
1089         list_del(&clp->cl_idhash);
1090         list_del(&clp->cl_strhash);
1091         spin_lock(&client_lock);
1092         unhash_client_locked(clp);
1093         if (atomic_read(&clp->cl_refcount) == 0)
1094                 free_client(clp);
1095         spin_unlock(&client_lock);
1096 }
1097
1098 static void copy_verf(struct nfs4_client *target, nfs4_verifier *source)
1099 {
1100         memcpy(target->cl_verifier.data, source->data,
1101                         sizeof(target->cl_verifier.data));
1102 }
1103
1104 static void copy_clid(struct nfs4_client *target, struct nfs4_client *source)
1105 {
1106         target->cl_clientid.cl_boot = source->cl_clientid.cl_boot; 
1107         target->cl_clientid.cl_id = source->cl_clientid.cl_id; 
1108 }
1109
1110 static void copy_cred(struct svc_cred *target, struct svc_cred *source)
1111 {
1112         target->cr_uid = source->cr_uid;
1113         target->cr_gid = source->cr_gid;
1114         target->cr_group_info = source->cr_group_info;
1115         get_group_info(target->cr_group_info);
1116 }
1117
1118 static int same_name(const char *n1, const char *n2)
1119 {
1120         return 0 == memcmp(n1, n2, HEXDIR_LEN);
1121 }
1122
1123 static int
1124 same_verf(nfs4_verifier *v1, nfs4_verifier *v2)
1125 {
1126         return 0 == memcmp(v1->data, v2->data, sizeof(v1->data));
1127 }
1128
1129 static int
1130 same_clid(clientid_t *cl1, clientid_t *cl2)
1131 {
1132         return (cl1->cl_boot == cl2->cl_boot) && (cl1->cl_id == cl2->cl_id);
1133 }
1134
1135 /* XXX what about NGROUP */
1136 static int
1137 same_creds(struct svc_cred *cr1, struct svc_cred *cr2)
1138 {
1139         return cr1->cr_uid == cr2->cr_uid;
1140 }
1141
1142 static void gen_clid(struct nfs4_client *clp)
1143 {
1144         static u32 current_clientid = 1;
1145
1146         clp->cl_clientid.cl_boot = boot_time;
1147         clp->cl_clientid.cl_id = current_clientid++; 
1148 }
1149
1150 static void gen_confirm(struct nfs4_client *clp)
1151 {
1152         static u32 i;
1153         u32 *p;
1154
1155         p = (u32 *)clp->cl_confirm.data;
1156         *p++ = get_seconds();
1157         *p++ = i++;
1158 }
1159
1160 static struct nfs4_stid *find_stateid(struct nfs4_client *cl, stateid_t *t)
1161 {
1162         return idr_find(&cl->cl_stateids, t->si_opaque.so_id);
1163 }
1164
1165 static struct nfs4_stid *find_stateid_by_type(struct nfs4_client *cl, stateid_t *t, char typemask)
1166 {
1167         struct nfs4_stid *s;
1168
1169         s = find_stateid(cl, t);
1170         if (!s)
1171                 return NULL;
1172         if (typemask & s->sc_type)
1173                 return s;
1174         return NULL;
1175 }
1176
1177 static struct nfs4_client *create_client(struct xdr_netobj name, char *recdir,
1178                 struct svc_rqst *rqstp, nfs4_verifier *verf)
1179 {
1180         struct nfs4_client *clp;
1181         struct sockaddr *sa = svc_addr(rqstp);
1182         char *princ;
1183
1184         clp = alloc_client(name);
1185         if (clp == NULL)
1186                 return NULL;
1187
1188
1189         princ = svc_gss_principal(rqstp);
1190         if (princ) {
1191                 clp->cl_principal = kstrdup(princ, GFP_KERNEL);
1192                 if (clp->cl_principal == NULL) {
1193                         free_client(clp);
1194                         return NULL;
1195                 }
1196         }
1197
1198         memcpy(clp->cl_recdir, recdir, HEXDIR_LEN);
1199         INIT_WORK(&clp->cl_cb_null.cb_work, nfsd4_do_callback_rpc);
1200         clp->cl_time = get_seconds();
1201         clear_bit(0, &clp->cl_cb_slot_busy);
1202         copy_verf(clp, verf);
1203         rpc_copy_addr((struct sockaddr *) &clp->cl_addr, sa);
1204         clp->cl_flavor = rqstp->rq_flavor;
1205         copy_cred(&clp->cl_cred, &rqstp->rq_cred);
1206         gen_confirm(clp);
1207         clp->cl_cb_session = NULL;
1208         return clp;
1209 }
1210
1211 static void
1212 add_to_unconfirmed(struct nfs4_client *clp, unsigned int strhashval)
1213 {
1214         unsigned int idhashval;
1215
1216         list_add(&clp->cl_strhash, &unconf_str_hashtbl[strhashval]);
1217         idhashval = clientid_hashval(clp->cl_clientid.cl_id);
1218         list_add(&clp->cl_idhash, &unconf_id_hashtbl[idhashval]);
1219         renew_client(clp);
1220 }
1221
1222 static void
1223 move_to_confirmed(struct nfs4_client *clp)
1224 {
1225         unsigned int idhashval = clientid_hashval(clp->cl_clientid.cl_id);
1226         unsigned int strhashval;
1227
1228         dprintk("NFSD: move_to_confirm nfs4_client %p\n", clp);
1229         list_move(&clp->cl_idhash, &conf_id_hashtbl[idhashval]);
1230         strhashval = clientstr_hashval(clp->cl_recdir);
1231         list_move(&clp->cl_strhash, &conf_str_hashtbl[strhashval]);
1232         renew_client(clp);
1233 }
1234
1235 static struct nfs4_client *
1236 find_confirmed_client(clientid_t *clid)
1237 {
1238         struct nfs4_client *clp;
1239         unsigned int idhashval = clientid_hashval(clid->cl_id);
1240
1241         list_for_each_entry(clp, &conf_id_hashtbl[idhashval], cl_idhash) {
1242                 if (same_clid(&clp->cl_clientid, clid)) {
1243                         renew_client(clp);
1244                         return clp;
1245                 }
1246         }
1247         return NULL;
1248 }
1249
1250 static struct nfs4_client *
1251 find_unconfirmed_client(clientid_t *clid)
1252 {
1253         struct nfs4_client *clp;
1254         unsigned int idhashval = clientid_hashval(clid->cl_id);
1255
1256         list_for_each_entry(clp, &unconf_id_hashtbl[idhashval], cl_idhash) {
1257                 if (same_clid(&clp->cl_clientid, clid))
1258                         return clp;
1259         }
1260         return NULL;
1261 }
1262
1263 static bool clp_used_exchangeid(struct nfs4_client *clp)
1264 {
1265         return clp->cl_exchange_flags != 0;
1266
1267
1268 static struct nfs4_client *
1269 find_confirmed_client_by_str(const char *dname, unsigned int hashval)
1270 {
1271         struct nfs4_client *clp;
1272
1273         list_for_each_entry(clp, &conf_str_hashtbl[hashval], cl_strhash) {
1274                 if (same_name(clp->cl_recdir, dname))
1275                         return clp;
1276         }
1277         return NULL;
1278 }
1279
1280 static struct nfs4_client *
1281 find_unconfirmed_client_by_str(const char *dname, unsigned int hashval)
1282 {
1283         struct nfs4_client *clp;
1284
1285         list_for_each_entry(clp, &unconf_str_hashtbl[hashval], cl_strhash) {
1286                 if (same_name(clp->cl_recdir, dname))
1287                         return clp;
1288         }
1289         return NULL;
1290 }
1291
1292 static void
1293 gen_callback(struct nfs4_client *clp, struct nfsd4_setclientid *se, struct svc_rqst *rqstp)
1294 {
1295         struct nfs4_cb_conn *conn = &clp->cl_cb_conn;
1296         struct sockaddr *sa = svc_addr(rqstp);
1297         u32 scopeid = rpc_get_scope_id(sa);
1298         unsigned short expected_family;
1299
1300         /* Currently, we only support tcp and tcp6 for the callback channel */
1301         if (se->se_callback_netid_len == 3 &&
1302             !memcmp(se->se_callback_netid_val, "tcp", 3))
1303                 expected_family = AF_INET;
1304         else if (se->se_callback_netid_len == 4 &&
1305                  !memcmp(se->se_callback_netid_val, "tcp6", 4))
1306                 expected_family = AF_INET6;
1307         else
1308                 goto out_err;
1309
1310         conn->cb_addrlen = rpc_uaddr2sockaddr(se->se_callback_addr_val,
1311                                             se->se_callback_addr_len,
1312                                             (struct sockaddr *)&conn->cb_addr,
1313                                             sizeof(conn->cb_addr));
1314
1315         if (!conn->cb_addrlen || conn->cb_addr.ss_family != expected_family)
1316                 goto out_err;
1317
1318         if (conn->cb_addr.ss_family == AF_INET6)
1319                 ((struct sockaddr_in6 *)&conn->cb_addr)->sin6_scope_id = scopeid;
1320
1321         conn->cb_prog = se->se_callback_prog;
1322         conn->cb_ident = se->se_callback_ident;
1323         memcpy(&conn->cb_saddr, &rqstp->rq_daddr, rqstp->rq_daddrlen);
1324         return;
1325 out_err:
1326         conn->cb_addr.ss_family = AF_UNSPEC;
1327         conn->cb_addrlen = 0;
1328         dprintk(KERN_INFO "NFSD: this client (clientid %08x/%08x) "
1329                 "will not receive delegations\n",
1330                 clp->cl_clientid.cl_boot, clp->cl_clientid.cl_id);
1331
1332         return;
1333 }
1334
1335 /*
1336  * Cache a reply. nfsd4_check_drc_limit() has bounded the cache size.
1337  */
1338 void
1339 nfsd4_store_cache_entry(struct nfsd4_compoundres *resp)
1340 {
1341         struct nfsd4_slot *slot = resp->cstate.slot;
1342         unsigned int base;
1343
1344         dprintk("--> %s slot %p\n", __func__, slot);
1345
1346         slot->sl_opcnt = resp->opcnt;
1347         slot->sl_status = resp->cstate.status;
1348
1349         if (nfsd4_not_cached(resp)) {
1350                 slot->sl_datalen = 0;
1351                 return;
1352         }
1353         slot->sl_datalen = (char *)resp->p - (char *)resp->cstate.datap;
1354         base = (char *)resp->cstate.datap -
1355                                         (char *)resp->xbuf->head[0].iov_base;
1356         if (read_bytes_from_xdr_buf(resp->xbuf, base, slot->sl_data,
1357                                     slot->sl_datalen))
1358                 WARN("%s: sessions DRC could not cache compound\n", __func__);
1359         return;
1360 }
1361
1362 /*
1363  * Encode the replay sequence operation from the slot values.
1364  * If cachethis is FALSE encode the uncached rep error on the next
1365  * operation which sets resp->p and increments resp->opcnt for
1366  * nfs4svc_encode_compoundres.
1367  *
1368  */
1369 static __be32
1370 nfsd4_enc_sequence_replay(struct nfsd4_compoundargs *args,
1371                           struct nfsd4_compoundres *resp)
1372 {
1373         struct nfsd4_op *op;
1374         struct nfsd4_slot *slot = resp->cstate.slot;
1375
1376         dprintk("--> %s resp->opcnt %d cachethis %u \n", __func__,
1377                 resp->opcnt, resp->cstate.slot->sl_cachethis);
1378
1379         /* Encode the replayed sequence operation */
1380         op = &args->ops[resp->opcnt - 1];
1381         nfsd4_encode_operation(resp, op);
1382
1383         /* Return nfserr_retry_uncached_rep in next operation. */
1384         if (args->opcnt > 1 && slot->sl_cachethis == 0) {
1385                 op = &args->ops[resp->opcnt++];
1386                 op->status = nfserr_retry_uncached_rep;
1387                 nfsd4_encode_operation(resp, op);
1388         }
1389         return op->status;
1390 }
1391
1392 /*
1393  * The sequence operation is not cached because we can use the slot and
1394  * session values.
1395  */
1396 __be32
1397 nfsd4_replay_cache_entry(struct nfsd4_compoundres *resp,
1398                          struct nfsd4_sequence *seq)
1399 {
1400         struct nfsd4_slot *slot = resp->cstate.slot;
1401         __be32 status;
1402
1403         dprintk("--> %s slot %p\n", __func__, slot);
1404
1405         /* Either returns 0 or nfserr_retry_uncached */
1406         status = nfsd4_enc_sequence_replay(resp->rqstp->rq_argp, resp);
1407         if (status == nfserr_retry_uncached_rep)
1408                 return status;
1409
1410         /* The sequence operation has been encoded, cstate->datap set. */
1411         memcpy(resp->cstate.datap, slot->sl_data, slot->sl_datalen);
1412
1413         resp->opcnt = slot->sl_opcnt;
1414         resp->p = resp->cstate.datap + XDR_QUADLEN(slot->sl_datalen);
1415         status = slot->sl_status;
1416
1417         return status;
1418 }
1419
1420 /*
1421  * Set the exchange_id flags returned by the server.
1422  */
1423 static void
1424 nfsd4_set_ex_flags(struct nfs4_client *new, struct nfsd4_exchange_id *clid)
1425 {
1426         /* pNFS is not supported */
1427         new->cl_exchange_flags |= EXCHGID4_FLAG_USE_NON_PNFS;
1428
1429         /* Referrals are supported, Migration is not. */
1430         new->cl_exchange_flags |= EXCHGID4_FLAG_SUPP_MOVED_REFER;
1431
1432         /* set the wire flags to return to client. */
1433         clid->flags = new->cl_exchange_flags;
1434 }
1435
1436 __be32
1437 nfsd4_exchange_id(struct svc_rqst *rqstp,
1438                   struct nfsd4_compound_state *cstate,
1439                   struct nfsd4_exchange_id *exid)
1440 {
1441         struct nfs4_client *unconf, *conf, *new;
1442         int status;
1443         unsigned int            strhashval;
1444         char                    dname[HEXDIR_LEN];
1445         char                    addr_str[INET6_ADDRSTRLEN];
1446         nfs4_verifier           verf = exid->verifier;
1447         struct sockaddr         *sa = svc_addr(rqstp);
1448
1449         rpc_ntop(sa, addr_str, sizeof(addr_str));
1450         dprintk("%s rqstp=%p exid=%p clname.len=%u clname.data=%p "
1451                 "ip_addr=%s flags %x, spa_how %d\n",
1452                 __func__, rqstp, exid, exid->clname.len, exid->clname.data,
1453                 addr_str, exid->flags, exid->spa_how);
1454
1455         if (exid->flags & ~EXCHGID4_FLAG_MASK_A)
1456                 return nfserr_inval;
1457
1458         /* Currently only support SP4_NONE */
1459         switch (exid->spa_how) {
1460         case SP4_NONE:
1461                 break;
1462         case SP4_SSV:
1463                 return nfserr_serverfault;
1464         default:
1465                 BUG();                          /* checked by xdr code */
1466         case SP4_MACH_CRED:
1467                 return nfserr_serverfault;      /* no excuse :-/ */
1468         }
1469
1470         status = nfs4_make_rec_clidname(dname, &exid->clname);
1471
1472         if (status)
1473                 goto error;
1474
1475         strhashval = clientstr_hashval(dname);
1476
1477         nfs4_lock_state();
1478         status = nfs_ok;
1479
1480         conf = find_confirmed_client_by_str(dname, strhashval);
1481         if (conf) {
1482                 if (!clp_used_exchangeid(conf)) {
1483                         status = nfserr_clid_inuse; /* XXX: ? */
1484                         goto out;
1485                 }
1486                 if (!same_verf(&verf, &conf->cl_verifier)) {
1487                         /* 18.35.4 case 8 */
1488                         if (exid->flags & EXCHGID4_FLAG_UPD_CONFIRMED_REC_A) {
1489                                 status = nfserr_not_same;
1490                                 goto out;
1491                         }
1492                         /* Client reboot: destroy old state */
1493                         expire_client(conf);
1494                         goto out_new;
1495                 }
1496                 if (!same_creds(&conf->cl_cred, &rqstp->rq_cred)) {
1497                         /* 18.35.4 case 9 */
1498                         if (exid->flags & EXCHGID4_FLAG_UPD_CONFIRMED_REC_A) {
1499                                 status = nfserr_perm;
1500                                 goto out;
1501                         }
1502                         expire_client(conf);
1503                         goto out_new;
1504                 }
1505                 /*
1506                  * Set bit when the owner id and verifier map to an already
1507                  * confirmed client id (18.35.3).
1508                  */
1509                 exid->flags |= EXCHGID4_FLAG_CONFIRMED_R;
1510
1511                 /*
1512                  * Falling into 18.35.4 case 2, possible router replay.
1513                  * Leave confirmed record intact and return same result.
1514                  */
1515                 copy_verf(conf, &verf);
1516                 new = conf;
1517                 goto out_copy;
1518         }
1519
1520         /* 18.35.4 case 7 */
1521         if (exid->flags & EXCHGID4_FLAG_UPD_CONFIRMED_REC_A) {
1522                 status = nfserr_noent;
1523                 goto out;
1524         }
1525
1526         unconf  = find_unconfirmed_client_by_str(dname, strhashval);
1527         if (unconf) {
1528                 /*
1529                  * Possible retry or client restart.  Per 18.35.4 case 4,
1530                  * a new unconfirmed record should be generated regardless
1531                  * of whether any properties have changed.
1532                  */
1533                 expire_client(unconf);
1534         }
1535
1536 out_new:
1537         /* Normal case */
1538         new = create_client(exid->clname, dname, rqstp, &verf);
1539         if (new == NULL) {
1540                 status = nfserr_jukebox;
1541                 goto out;
1542         }
1543
1544         gen_clid(new);
1545         add_to_unconfirmed(new, strhashval);
1546 out_copy:
1547         exid->clientid.cl_boot = new->cl_clientid.cl_boot;
1548         exid->clientid.cl_id = new->cl_clientid.cl_id;
1549
1550         exid->seqid = 1;
1551         nfsd4_set_ex_flags(new, exid);
1552
1553         dprintk("nfsd4_exchange_id seqid %d flags %x\n",
1554                 new->cl_cs_slot.sl_seqid, new->cl_exchange_flags);
1555         status = nfs_ok;
1556
1557 out:
1558         nfs4_unlock_state();
1559 error:
1560         dprintk("nfsd4_exchange_id returns %d\n", ntohl(status));
1561         return status;
1562 }
1563
1564 static int
1565 check_slot_seqid(u32 seqid, u32 slot_seqid, int slot_inuse)
1566 {
1567         dprintk("%s enter. seqid %d slot_seqid %d\n", __func__, seqid,
1568                 slot_seqid);
1569
1570         /* The slot is in use, and no response has been sent. */
1571         if (slot_inuse) {
1572                 if (seqid == slot_seqid)
1573                         return nfserr_jukebox;
1574                 else
1575                         return nfserr_seq_misordered;
1576         }
1577         /* Normal */
1578         if (likely(seqid == slot_seqid + 1))
1579                 return nfs_ok;
1580         /* Replay */
1581         if (seqid == slot_seqid)
1582                 return nfserr_replay_cache;
1583         /* Wraparound */
1584         if (seqid == 1 && (slot_seqid + 1) == 0)
1585                 return nfs_ok;
1586         /* Misordered replay or misordered new request */
1587         return nfserr_seq_misordered;
1588 }
1589
1590 /*
1591  * Cache the create session result into the create session single DRC
1592  * slot cache by saving the xdr structure. sl_seqid has been set.
1593  * Do this for solo or embedded create session operations.
1594  */
1595 static void
1596 nfsd4_cache_create_session(struct nfsd4_create_session *cr_ses,
1597                            struct nfsd4_clid_slot *slot, int nfserr)
1598 {
1599         slot->sl_status = nfserr;
1600         memcpy(&slot->sl_cr_ses, cr_ses, sizeof(*cr_ses));
1601 }
1602
1603 static __be32
1604 nfsd4_replay_create_session(struct nfsd4_create_session *cr_ses,
1605                             struct nfsd4_clid_slot *slot)
1606 {
1607         memcpy(cr_ses, &slot->sl_cr_ses, sizeof(*cr_ses));
1608         return slot->sl_status;
1609 }
1610
1611 #define NFSD_MIN_REQ_HDR_SEQ_SZ ((\
1612                         2 * 2 + /* credential,verifier: AUTH_NULL, length 0 */ \
1613                         1 +     /* MIN tag is length with zero, only length */ \
1614                         3 +     /* version, opcount, opcode */ \
1615                         XDR_QUADLEN(NFS4_MAX_SESSIONID_LEN) + \
1616                                 /* seqid, slotID, slotID, cache */ \
1617                         4 ) * sizeof(__be32))
1618
1619 #define NFSD_MIN_RESP_HDR_SEQ_SZ ((\
1620                         2 +     /* verifier: AUTH_NULL, length 0 */\
1621                         1 +     /* status */ \
1622                         1 +     /* MIN tag is length with zero, only length */ \
1623                         3 +     /* opcount, opcode, opstatus*/ \
1624                         XDR_QUADLEN(NFS4_MAX_SESSIONID_LEN) + \
1625                                 /* seqid, slotID, slotID, slotID, status */ \
1626                         5 ) * sizeof(__be32))
1627
1628 static __be32 check_forechannel_attrs(struct nfsd4_channel_attrs fchannel)
1629 {
1630         return fchannel.maxreq_sz < NFSD_MIN_REQ_HDR_SEQ_SZ
1631                 || fchannel.maxresp_sz < NFSD_MIN_RESP_HDR_SEQ_SZ;
1632 }
1633
1634 __be32
1635 nfsd4_create_session(struct svc_rqst *rqstp,
1636                      struct nfsd4_compound_state *cstate,
1637                      struct nfsd4_create_session *cr_ses)
1638 {
1639         struct sockaddr *sa = svc_addr(rqstp);
1640         struct nfs4_client *conf, *unconf;
1641         struct nfsd4_session *new;
1642         struct nfsd4_clid_slot *cs_slot = NULL;
1643         bool confirm_me = false;
1644         int status = 0;
1645
1646         if (cr_ses->flags & ~SESSION4_FLAG_MASK_A)
1647                 return nfserr_inval;
1648
1649         nfs4_lock_state();
1650         unconf = find_unconfirmed_client(&cr_ses->clientid);
1651         conf = find_confirmed_client(&cr_ses->clientid);
1652
1653         if (conf) {
1654                 cs_slot = &conf->cl_cs_slot;
1655                 status = check_slot_seqid(cr_ses->seqid, cs_slot->sl_seqid, 0);
1656                 if (status == nfserr_replay_cache) {
1657                         dprintk("Got a create_session replay! seqid= %d\n",
1658                                 cs_slot->sl_seqid);
1659                         /* Return the cached reply status */
1660                         status = nfsd4_replay_create_session(cr_ses, cs_slot);
1661                         goto out;
1662                 } else if (cr_ses->seqid != cs_slot->sl_seqid + 1) {
1663                         status = nfserr_seq_misordered;
1664                         dprintk("Sequence misordered!\n");
1665                         dprintk("Expected seqid= %d but got seqid= %d\n",
1666                                 cs_slot->sl_seqid, cr_ses->seqid);
1667                         goto out;
1668                 }
1669         } else if (unconf) {
1670                 if (!same_creds(&unconf->cl_cred, &rqstp->rq_cred) ||
1671                     !rpc_cmp_addr(sa, (struct sockaddr *) &unconf->cl_addr)) {
1672                         status = nfserr_clid_inuse;
1673                         goto out;
1674                 }
1675
1676                 cs_slot = &unconf->cl_cs_slot;
1677                 status = check_slot_seqid(cr_ses->seqid, cs_slot->sl_seqid, 0);
1678                 if (status) {
1679                         /* an unconfirmed replay returns misordered */
1680                         status = nfserr_seq_misordered;
1681                         goto out;
1682                 }
1683
1684                 confirm_me = true;
1685                 conf = unconf;
1686         } else {
1687                 status = nfserr_stale_clientid;
1688                 goto out;
1689         }
1690
1691         /*
1692          * XXX: we should probably set this at creation time, and check
1693          * for consistent minorversion use throughout:
1694          */
1695         conf->cl_minorversion = 1;
1696         /*
1697          * We do not support RDMA or persistent sessions
1698          */
1699         cr_ses->flags &= ~SESSION4_PERSIST;
1700         cr_ses->flags &= ~SESSION4_RDMA;
1701
1702         status = nfserr_toosmall;
1703         if (check_forechannel_attrs(cr_ses->fore_channel))
1704                 goto out;
1705
1706         status = nfserr_jukebox;
1707         new = alloc_init_session(rqstp, conf, cr_ses);
1708         if (!new)
1709                 goto out;
1710         status = nfs_ok;
1711         memcpy(cr_ses->sessionid.data, new->se_sessionid.data,
1712                NFS4_MAX_SESSIONID_LEN);
1713         memcpy(&cr_ses->fore_channel, &new->se_fchannel,
1714                 sizeof(struct nfsd4_channel_attrs));
1715         cs_slot->sl_seqid++;
1716         cr_ses->seqid = cs_slot->sl_seqid;
1717
1718         /* cache solo and embedded create sessions under the state lock */
1719         nfsd4_cache_create_session(cr_ses, cs_slot, status);
1720         if (confirm_me)
1721                 move_to_confirmed(conf);
1722 out:
1723         nfs4_unlock_state();
1724         dprintk("%s returns %d\n", __func__, ntohl(status));
1725         return status;
1726 }
1727
1728 static bool nfsd4_last_compound_op(struct svc_rqst *rqstp)
1729 {
1730         struct nfsd4_compoundres *resp = rqstp->rq_resp;
1731         struct nfsd4_compoundargs *argp = rqstp->rq_argp;
1732
1733         return argp->opcnt == resp->opcnt;
1734 }
1735
1736 static __be32 nfsd4_map_bcts_dir(u32 *dir)
1737 {
1738         switch (*dir) {
1739         case NFS4_CDFC4_FORE:
1740         case NFS4_CDFC4_BACK:
1741                 return nfs_ok;
1742         case NFS4_CDFC4_FORE_OR_BOTH:
1743         case NFS4_CDFC4_BACK_OR_BOTH:
1744                 *dir = NFS4_CDFC4_BOTH;
1745                 return nfs_ok;
1746         };
1747         return nfserr_inval;
1748 }
1749
1750 __be32 nfsd4_bind_conn_to_session(struct svc_rqst *rqstp,
1751                      struct nfsd4_compound_state *cstate,
1752                      struct nfsd4_bind_conn_to_session *bcts)
1753 {
1754         __be32 status;
1755
1756         if (!nfsd4_last_compound_op(rqstp))
1757                 return nfserr_not_only_op;
1758         spin_lock(&client_lock);
1759         cstate->session = find_in_sessionid_hashtbl(&bcts->sessionid);
1760         /* Sorta weird: we only need the refcnt'ing because new_conn acquires
1761          * client_lock iself: */
1762         if (cstate->session) {
1763                 nfsd4_get_session(cstate->session);
1764                 atomic_inc(&cstate->session->se_client->cl_refcount);
1765         }
1766         spin_unlock(&client_lock);
1767         if (!cstate->session)
1768                 return nfserr_badsession;
1769
1770         status = nfsd4_map_bcts_dir(&bcts->dir);
1771         if (!status)
1772                 nfsd4_new_conn(rqstp, cstate->session, bcts->dir);
1773         return status;
1774 }
1775
1776 static bool nfsd4_compound_in_session(struct nfsd4_session *session, struct nfs4_sessionid *sid)
1777 {
1778         if (!session)
1779                 return 0;
1780         return !memcmp(sid, &session->se_sessionid, sizeof(*sid));
1781 }
1782
1783 __be32
1784 nfsd4_destroy_session(struct svc_rqst *r,
1785                       struct nfsd4_compound_state *cstate,
1786                       struct nfsd4_destroy_session *sessionid)
1787 {
1788         struct nfsd4_session *ses;
1789         u32 status = nfserr_badsession;
1790
1791         /* Notes:
1792          * - The confirmed nfs4_client->cl_sessionid holds destroyed sessinid
1793          * - Should we return nfserr_back_chan_busy if waiting for
1794          *   callbacks on to-be-destroyed session?
1795          * - Do we need to clear any callback info from previous session?
1796          */
1797
1798         if (nfsd4_compound_in_session(cstate->session, &sessionid->sessionid)) {
1799                 if (!nfsd4_last_compound_op(r))
1800                         return nfserr_not_only_op;
1801         }
1802         dump_sessionid(__func__, &sessionid->sessionid);
1803         spin_lock(&client_lock);
1804         ses = find_in_sessionid_hashtbl(&sessionid->sessionid);
1805         if (!ses) {
1806                 spin_unlock(&client_lock);
1807                 goto out;
1808         }
1809
1810         unhash_session(ses);
1811         spin_unlock(&client_lock);
1812
1813         nfs4_lock_state();
1814         nfsd4_probe_callback_sync(ses->se_client);
1815         nfs4_unlock_state();
1816
1817         nfsd4_del_conns(ses);
1818
1819         nfsd4_put_session(ses);
1820         status = nfs_ok;
1821 out:
1822         dprintk("%s returns %d\n", __func__, ntohl(status));
1823         return status;
1824 }
1825
1826 static struct nfsd4_conn *__nfsd4_find_conn(struct svc_xprt *xpt, struct nfsd4_session *s)
1827 {
1828         struct nfsd4_conn *c;
1829
1830         list_for_each_entry(c, &s->se_conns, cn_persession) {
1831                 if (c->cn_xprt == xpt) {
1832                         return c;
1833                 }
1834         }
1835         return NULL;
1836 }
1837
1838 static void nfsd4_sequence_check_conn(struct nfsd4_conn *new, struct nfsd4_session *ses)
1839 {
1840         struct nfs4_client *clp = ses->se_client;
1841         struct nfsd4_conn *c;
1842         int ret;
1843
1844         spin_lock(&clp->cl_lock);
1845         c = __nfsd4_find_conn(new->cn_xprt, ses);
1846         if (c) {
1847                 spin_unlock(&clp->cl_lock);
1848                 free_conn(new);
1849                 return;
1850         }
1851         __nfsd4_hash_conn(new, ses);
1852         spin_unlock(&clp->cl_lock);
1853         ret = nfsd4_register_conn(new);
1854         if (ret)
1855                 /* oops; xprt is already down: */
1856                 nfsd4_conn_lost(&new->cn_xpt_user);
1857         return;
1858 }
1859
1860 static bool nfsd4_session_too_many_ops(struct svc_rqst *rqstp, struct nfsd4_session *session)
1861 {
1862         struct nfsd4_compoundargs *args = rqstp->rq_argp;
1863
1864         return args->opcnt > session->se_fchannel.maxops;
1865 }
1866
1867 static bool nfsd4_request_too_big(struct svc_rqst *rqstp,
1868                                   struct nfsd4_session *session)
1869 {
1870         struct xdr_buf *xb = &rqstp->rq_arg;
1871
1872         return xb->len > session->se_fchannel.maxreq_sz;
1873 }
1874
1875 __be32
1876 nfsd4_sequence(struct svc_rqst *rqstp,
1877                struct nfsd4_compound_state *cstate,
1878                struct nfsd4_sequence *seq)
1879 {
1880         struct nfsd4_compoundres *resp = rqstp->rq_resp;
1881         struct nfsd4_session *session;
1882         struct nfsd4_slot *slot;
1883         struct nfsd4_conn *conn;
1884         int status;
1885
1886         if (resp->opcnt != 1)
1887                 return nfserr_sequence_pos;
1888
1889         /*
1890          * Will be either used or freed by nfsd4_sequence_check_conn
1891          * below.
1892          */
1893         conn = alloc_conn(rqstp, NFS4_CDFC4_FORE);
1894         if (!conn)
1895                 return nfserr_jukebox;
1896
1897         spin_lock(&client_lock);
1898         status = nfserr_badsession;
1899         session = find_in_sessionid_hashtbl(&seq->sessionid);
1900         if (!session)
1901                 goto out;
1902
1903         status = nfserr_too_many_ops;
1904         if (nfsd4_session_too_many_ops(rqstp, session))
1905                 goto out;
1906
1907         status = nfserr_req_too_big;
1908         if (nfsd4_request_too_big(rqstp, session))
1909                 goto out;
1910
1911         status = nfserr_badslot;
1912         if (seq->slotid >= session->se_fchannel.maxreqs)
1913                 goto out;
1914
1915         slot = session->se_slots[seq->slotid];
1916         dprintk("%s: slotid %d\n", __func__, seq->slotid);
1917
1918         /* We do not negotiate the number of slots yet, so set the
1919          * maxslots to the session maxreqs which is used to encode
1920          * sr_highest_slotid and the sr_target_slot id to maxslots */
1921         seq->maxslots = session->se_fchannel.maxreqs;
1922
1923         status = check_slot_seqid(seq->seqid, slot->sl_seqid, slot->sl_inuse);
1924         if (status == nfserr_replay_cache) {
1925                 cstate->slot = slot;
1926                 cstate->session = session;
1927                 /* Return the cached reply status and set cstate->status
1928                  * for nfsd4_proc_compound processing */
1929                 status = nfsd4_replay_cache_entry(resp, seq);
1930                 cstate->status = nfserr_replay_cache;
1931                 goto out;
1932         }
1933         if (status)
1934                 goto out;
1935
1936         nfsd4_sequence_check_conn(conn, session);
1937         conn = NULL;
1938
1939         /* Success! bump slot seqid */
1940         slot->sl_inuse = true;
1941         slot->sl_seqid = seq->seqid;
1942         slot->sl_cachethis = seq->cachethis;
1943
1944         cstate->slot = slot;
1945         cstate->session = session;
1946
1947 out:
1948         /* Hold a session reference until done processing the compound. */
1949         if (cstate->session) {
1950                 struct nfs4_client *clp = session->se_client;
1951
1952                 nfsd4_get_session(cstate->session);
1953                 atomic_inc(&clp->cl_refcount);
1954                 switch (clp->cl_cb_state) {
1955                 case NFSD4_CB_DOWN:
1956                         seq->status_flags = SEQ4_STATUS_CB_PATH_DOWN;
1957                         break;
1958                 case NFSD4_CB_FAULT:
1959                         seq->status_flags = SEQ4_STATUS_BACKCHANNEL_FAULT;
1960                         break;
1961                 default:
1962                         seq->status_flags = 0;
1963                 }
1964         }
1965         kfree(conn);
1966         spin_unlock(&client_lock);
1967         dprintk("%s: return %d\n", __func__, ntohl(status));
1968         return status;
1969 }
1970
1971 static inline bool has_resources(struct nfs4_client *clp)
1972 {
1973         return !list_empty(&clp->cl_openowners)
1974                 || !list_empty(&clp->cl_delegations)
1975                 || !list_empty(&clp->cl_sessions);
1976 }
1977
1978 __be32
1979 nfsd4_destroy_clientid(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_destroy_clientid *dc)
1980 {
1981         struct nfs4_client *conf, *unconf, *clp;
1982         int status = 0;
1983
1984         nfs4_lock_state();
1985         unconf = find_unconfirmed_client(&dc->clientid);
1986         conf = find_confirmed_client(&dc->clientid);
1987
1988         if (conf) {
1989                 clp = conf;
1990
1991                 if (!is_client_expired(conf) && has_resources(conf)) {
1992                         status = nfserr_clientid_busy;
1993                         goto out;
1994                 }
1995
1996                 /* rfc5661 18.50.3 */
1997                 if (cstate->session && conf == cstate->session->se_client) {
1998                         status = nfserr_clientid_busy;
1999                         goto out;
2000                 }
2001         } else if (unconf)
2002                 clp = unconf;
2003         else {
2004                 status = nfserr_stale_clientid;
2005                 goto out;
2006         }
2007
2008         expire_client(clp);
2009 out:
2010         nfs4_unlock_state();
2011         dprintk("%s return %d\n", __func__, ntohl(status));
2012         return status;
2013 }
2014
2015 __be32
2016 nfsd4_reclaim_complete(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_reclaim_complete *rc)
2017 {
2018         int status = 0;
2019
2020         if (rc->rca_one_fs) {
2021                 if (!cstate->current_fh.fh_dentry)
2022                         return nfserr_nofilehandle;
2023                 /*
2024                  * We don't take advantage of the rca_one_fs case.
2025                  * That's OK, it's optional, we can safely ignore it.
2026                  */
2027                  return nfs_ok;
2028         }
2029
2030         nfs4_lock_state();
2031         status = nfserr_complete_already;
2032         if (cstate->session->se_client->cl_firststate)
2033                 goto out;
2034
2035         status = nfserr_stale_clientid;
2036         if (is_client_expired(cstate->session->se_client))
2037                 /*
2038                  * The following error isn't really legal.
2039                  * But we only get here if the client just explicitly
2040                  * destroyed the client.  Surely it no longer cares what
2041                  * error it gets back on an operation for the dead
2042                  * client.
2043                  */
2044                 goto out;
2045
2046         status = nfs_ok;
2047         nfsd4_create_clid_dir(cstate->session->se_client);
2048 out:
2049         nfs4_unlock_state();
2050         return status;
2051 }
2052
2053 __be32
2054 nfsd4_setclientid(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
2055                   struct nfsd4_setclientid *setclid)
2056 {
2057         struct xdr_netobj       clname = setclid->se_name;
2058         nfs4_verifier           clverifier = setclid->se_verf;
2059         unsigned int            strhashval;
2060         struct nfs4_client      *conf, *unconf, *new;
2061         __be32                  status;
2062         char                    dname[HEXDIR_LEN];
2063         
2064         status = nfs4_make_rec_clidname(dname, &clname);
2065         if (status)
2066                 return status;
2067
2068         /* 
2069          * XXX The Duplicate Request Cache (DRC) has been checked (??)
2070          * We get here on a DRC miss.
2071          */
2072
2073         strhashval = clientstr_hashval(dname);
2074
2075         nfs4_lock_state();
2076         conf = find_confirmed_client_by_str(dname, strhashval);
2077         if (conf) {
2078                 /* RFC 3530 14.2.33 CASE 0: */
2079                 status = nfserr_clid_inuse;
2080                 if (clp_used_exchangeid(conf))
2081                         goto out;
2082                 if (!same_creds(&conf->cl_cred, &rqstp->rq_cred)) {
2083                         char addr_str[INET6_ADDRSTRLEN];
2084                         rpc_ntop((struct sockaddr *) &conf->cl_addr, addr_str,
2085                                  sizeof(addr_str));
2086                         dprintk("NFSD: setclientid: string in use by client "
2087                                 "at %s\n", addr_str);
2088                         goto out;
2089                 }
2090         }
2091         /*
2092          * section 14.2.33 of RFC 3530 (under the heading "IMPLEMENTATION")
2093          * has a description of SETCLIENTID request processing consisting
2094          * of 5 bullet points, labeled as CASE0 - CASE4 below.
2095          */
2096         unconf = find_unconfirmed_client_by_str(dname, strhashval);
2097         status = nfserr_jukebox;
2098         if (!conf) {
2099                 /*
2100                  * RFC 3530 14.2.33 CASE 4:
2101                  * placed first, because it is the normal case
2102                  */
2103                 if (unconf)
2104                         expire_client(unconf);
2105                 new = create_client(clname, dname, rqstp, &clverifier);
2106                 if (new == NULL)
2107                         goto out;
2108                 gen_clid(new);
2109         } else if (same_verf(&conf->cl_verifier, &clverifier)) {
2110                 /*
2111                  * RFC 3530 14.2.33 CASE 1:
2112                  * probable callback update
2113                  */
2114                 if (unconf) {
2115                         /* Note this is removing unconfirmed {*x***},
2116                          * which is stronger than RFC recommended {vxc**}.
2117                          * This has the advantage that there is at most
2118                          * one {*x***} in either list at any time.
2119                          */
2120                         expire_client(unconf);
2121                 }
2122                 new = create_client(clname, dname, rqstp, &clverifier);
2123                 if (new == NULL)
2124                         goto out;
2125                 copy_clid(new, conf);
2126         } else if (!unconf) {
2127                 /*
2128                  * RFC 3530 14.2.33 CASE 2:
2129                  * probable client reboot; state will be removed if
2130                  * confirmed.
2131                  */
2132                 new = create_client(clname, dname, rqstp, &clverifier);
2133                 if (new == NULL)
2134                         goto out;
2135                 gen_clid(new);
2136         } else {
2137                 /*
2138                  * RFC 3530 14.2.33 CASE 3:
2139                  * probable client reboot; state will be removed if
2140                  * confirmed.
2141                  */
2142                 expire_client(unconf);
2143                 new = create_client(clname, dname, rqstp, &clverifier);
2144                 if (new == NULL)
2145                         goto out;
2146                 gen_clid(new);
2147         }
2148         /*
2149          * XXX: we should probably set this at creation time, and check
2150          * for consistent minorversion use throughout:
2151          */
2152         new->cl_minorversion = 0;
2153         gen_callback(new, setclid, rqstp);
2154         add_to_unconfirmed(new, strhashval);
2155         setclid->se_clientid.cl_boot = new->cl_clientid.cl_boot;
2156         setclid->se_clientid.cl_id = new->cl_clientid.cl_id;
2157         memcpy(setclid->se_confirm.data, new->cl_confirm.data, sizeof(setclid->se_confirm.data));
2158         status = nfs_ok;
2159 out:
2160         nfs4_unlock_state();
2161         return status;
2162 }
2163
2164
2165 /*
2166  * Section 14.2.34 of RFC 3530 (under the heading "IMPLEMENTATION") has
2167  * a description of SETCLIENTID_CONFIRM request processing consisting of 4
2168  * bullets, labeled as CASE1 - CASE4 below.
2169  */
2170 __be32
2171 nfsd4_setclientid_confirm(struct svc_rqst *rqstp,
2172                          struct nfsd4_compound_state *cstate,
2173                          struct nfsd4_setclientid_confirm *setclientid_confirm)
2174 {
2175         struct sockaddr *sa = svc_addr(rqstp);
2176         struct nfs4_client *conf, *unconf;
2177         nfs4_verifier confirm = setclientid_confirm->sc_confirm; 
2178         clientid_t * clid = &setclientid_confirm->sc_clientid;
2179         __be32 status;
2180
2181         if (STALE_CLIENTID(clid))
2182                 return nfserr_stale_clientid;
2183         /* 
2184          * XXX The Duplicate Request Cache (DRC) has been checked (??)
2185          * We get here on a DRC miss.
2186          */
2187
2188         nfs4_lock_state();
2189
2190         conf = find_confirmed_client(clid);
2191         unconf = find_unconfirmed_client(clid);
2192
2193         status = nfserr_clid_inuse;
2194         if (conf && !rpc_cmp_addr((struct sockaddr *) &conf->cl_addr, sa))
2195                 goto out;
2196         if (unconf && !rpc_cmp_addr((struct sockaddr *) &unconf->cl_addr, sa))
2197                 goto out;
2198
2199         /*
2200          * section 14.2.34 of RFC 3530 has a description of
2201          * SETCLIENTID_CONFIRM request processing consisting
2202          * of 4 bullet points, labeled as CASE1 - CASE4 below.
2203          */
2204         if (conf && unconf && same_verf(&confirm, &unconf->cl_confirm)) {
2205                 /*
2206                  * RFC 3530 14.2.34 CASE 1:
2207                  * callback update
2208                  */
2209                 if (!same_creds(&conf->cl_cred, &unconf->cl_cred))
2210                         status = nfserr_clid_inuse;
2211                 else {
2212                         nfsd4_change_callback(conf, &unconf->cl_cb_conn);
2213                         nfsd4_probe_callback(conf);
2214                         expire_client(unconf);
2215                         status = nfs_ok;
2216
2217                 }
2218         } else if (conf && !unconf) {
2219                 /*
2220                  * RFC 3530 14.2.34 CASE 2:
2221                  * probable retransmitted request; play it safe and
2222                  * do nothing.
2223                  */
2224                 if (!same_creds(&conf->cl_cred, &rqstp->rq_cred))
2225                         status = nfserr_clid_inuse;
2226                 else
2227                         status = nfs_ok;
2228         } else if (!conf && unconf
2229                         && same_verf(&unconf->cl_confirm, &confirm)) {
2230                 /*
2231                  * RFC 3530 14.2.34 CASE 3:
2232                  * Normal case; new or rebooted client:
2233                  */
2234                 if (!same_creds(&unconf->cl_cred, &rqstp->rq_cred)) {
2235                         status = nfserr_clid_inuse;
2236                 } else {
2237                         unsigned int hash =
2238                                 clientstr_hashval(unconf->cl_recdir);
2239                         conf = find_confirmed_client_by_str(unconf->cl_recdir,
2240                                                             hash);
2241                         if (conf) {
2242                                 nfsd4_remove_clid_dir(conf);
2243                                 expire_client(conf);
2244                         }
2245                         move_to_confirmed(unconf);
2246                         conf = unconf;
2247                         nfsd4_probe_callback(conf);
2248                         status = nfs_ok;
2249                 }
2250         } else if ((!conf || (conf && !same_verf(&conf->cl_confirm, &confirm)))
2251             && (!unconf || (unconf && !same_verf(&unconf->cl_confirm,
2252                                                                 &confirm)))) {
2253                 /*
2254                  * RFC 3530 14.2.34 CASE 4:
2255                  * Client probably hasn't noticed that we rebooted yet.
2256                  */
2257                 status = nfserr_stale_clientid;
2258         } else {
2259                 /* check that we have hit one of the cases...*/
2260                 status = nfserr_clid_inuse;
2261         }
2262 out:
2263         nfs4_unlock_state();
2264         return status;
2265 }
2266
2267 static struct nfs4_file *nfsd4_alloc_file(void)
2268 {
2269         return kmem_cache_alloc(file_slab, GFP_KERNEL);
2270 }
2271
2272 /* OPEN Share state helper functions */
2273 static void nfsd4_init_file(struct nfs4_file *fp, struct inode *ino)
2274 {
2275         unsigned int hashval = file_hashval(ino);
2276
2277         atomic_set(&fp->fi_ref, 1);
2278         INIT_LIST_HEAD(&fp->fi_hash);
2279         INIT_LIST_HEAD(&fp->fi_stateids);
2280         INIT_LIST_HEAD(&fp->fi_delegations);
2281         fp->fi_inode = igrab(ino);
2282         fp->fi_had_conflict = false;
2283         fp->fi_lease = NULL;
2284         memset(fp->fi_fds, 0, sizeof(fp->fi_fds));
2285         memset(fp->fi_access, 0, sizeof(fp->fi_access));
2286         spin_lock(&recall_lock);
2287         list_add(&fp->fi_hash, &file_hashtbl[hashval]);
2288         spin_unlock(&recall_lock);
2289 }
2290
2291 static void
2292 nfsd4_free_slab(struct kmem_cache **slab)
2293 {
2294         if (*slab == NULL)
2295                 return;
2296         kmem_cache_destroy(*slab);
2297         *slab = NULL;
2298 }
2299
2300 void
2301 nfsd4_free_slabs(void)
2302 {
2303         nfsd4_free_slab(&openowner_slab);
2304         nfsd4_free_slab(&lockowner_slab);
2305         nfsd4_free_slab(&file_slab);
2306         nfsd4_free_slab(&stateid_slab);
2307         nfsd4_free_slab(&deleg_slab);
2308 }
2309
2310 static int
2311 nfsd4_init_slabs(void)
2312 {
2313         openowner_slab = kmem_cache_create("nfsd4_openowners",
2314                         sizeof(struct nfs4_openowner), 0, 0, NULL);
2315         if (openowner_slab == NULL)
2316                 goto out_nomem;
2317         lockowner_slab = kmem_cache_create("nfsd4_lockowners",
2318                         sizeof(struct nfs4_lockowner), 0, 0, NULL);
2319         if (lockowner_slab == NULL)
2320                 goto out_nomem;
2321         file_slab = kmem_cache_create("nfsd4_files",
2322                         sizeof(struct nfs4_file), 0, 0, NULL);
2323         if (file_slab == NULL)
2324                 goto out_nomem;
2325         stateid_slab = kmem_cache_create("nfsd4_stateids",
2326                         sizeof(struct nfs4_ol_stateid), 0, 0, NULL);
2327         if (stateid_slab == NULL)
2328                 goto out_nomem;
2329         deleg_slab = kmem_cache_create("nfsd4_delegations",
2330                         sizeof(struct nfs4_delegation), 0, 0, NULL);
2331         if (deleg_slab == NULL)
2332                 goto out_nomem;
2333         return 0;
2334 out_nomem:
2335         nfsd4_free_slabs();
2336         dprintk("nfsd4: out of memory while initializing nfsv4\n");
2337         return -ENOMEM;
2338 }
2339
2340 void nfs4_free_openowner(struct nfs4_openowner *oo)
2341 {
2342         kfree(oo->oo_owner.so_owner.data);
2343         kmem_cache_free(openowner_slab, oo);
2344 }
2345
2346 void nfs4_free_lockowner(struct nfs4_lockowner *lo)
2347 {
2348         kfree(lo->lo_owner.so_owner.data);
2349         kmem_cache_free(lockowner_slab, lo);
2350 }
2351
2352 static void init_nfs4_replay(struct nfs4_replay *rp)
2353 {
2354         rp->rp_status = nfserr_serverfault;
2355         rp->rp_buflen = 0;
2356         rp->rp_buf = rp->rp_ibuf;
2357 }
2358
2359 static inline void *alloc_stateowner(struct kmem_cache *slab, struct xdr_netobj *owner, struct nfs4_client *clp)
2360 {
2361         struct nfs4_stateowner *sop;
2362
2363         sop = kmem_cache_alloc(slab, GFP_KERNEL);
2364         if (!sop)
2365                 return NULL;
2366
2367         sop->so_owner.data = kmemdup(owner->data, owner->len, GFP_KERNEL);
2368         if (!sop->so_owner.data) {
2369                 kmem_cache_free(slab, sop);
2370                 return NULL;
2371         }
2372         sop->so_owner.len = owner->len;
2373
2374         INIT_LIST_HEAD(&sop->so_stateids);
2375         sop->so_client = clp;
2376         init_nfs4_replay(&sop->so_replay);
2377         return sop;
2378 }
2379
2380 static void hash_openowner(struct nfs4_openowner *oo, struct nfs4_client *clp, unsigned int strhashval)
2381 {
2382         list_add(&oo->oo_owner.so_strhash, &open_ownerstr_hashtbl[strhashval]);
2383         list_add(&oo->oo_perclient, &clp->cl_openowners);
2384 }
2385
2386 static struct nfs4_openowner *
2387 alloc_init_open_stateowner(unsigned int strhashval, struct nfs4_client *clp, struct nfsd4_open *open) {
2388         struct nfs4_openowner *oo;
2389
2390         oo = alloc_stateowner(openowner_slab, &open->op_owner, clp);
2391         if (!oo)
2392                 return NULL;
2393         oo->oo_owner.so_is_open_owner = 1;
2394         oo->oo_owner.so_seqid = open->op_seqid;
2395         oo->oo_flags = NFS4_OO_NEW;
2396         oo->oo_time = 0;
2397         oo->oo_last_closed_stid = NULL;
2398         INIT_LIST_HEAD(&oo->oo_close_lru);
2399         hash_openowner(oo, clp, strhashval);
2400         return oo;
2401 }
2402
2403 static void init_open_stateid(struct nfs4_ol_stateid *stp, struct nfs4_file *fp, struct nfsd4_open *open) {
2404         struct nfs4_openowner *oo = open->op_openowner;
2405         struct nfs4_client *clp = oo->oo_owner.so_client;
2406
2407         init_stid(&stp->st_stid, clp, NFS4_OPEN_STID);
2408         INIT_LIST_HEAD(&stp->st_lockowners);
2409         list_add(&stp->st_perstateowner, &oo->oo_owner.so_stateids);
2410         list_add(&stp->st_perfile, &fp->fi_stateids);
2411         stp->st_stateowner = &oo->oo_owner;
2412         get_nfs4_file(fp);
2413         stp->st_file = fp;
2414         stp->st_access_bmap = 0;
2415         stp->st_deny_bmap = 0;
2416         __set_bit(open->op_share_access, &stp->st_access_bmap);
2417         __set_bit(open->op_share_deny, &stp->st_deny_bmap);
2418         stp->st_openstp = NULL;
2419 }
2420
2421 static void
2422 move_to_close_lru(struct nfs4_openowner *oo)
2423 {
2424         dprintk("NFSD: move_to_close_lru nfs4_openowner %p\n", oo);
2425
2426         list_move_tail(&oo->oo_close_lru, &close_lru);
2427         oo->oo_time = get_seconds();
2428 }
2429
2430 static int
2431 same_owner_str(struct nfs4_stateowner *sop, struct xdr_netobj *owner,
2432                                                         clientid_t *clid)
2433 {
2434         return (sop->so_owner.len == owner->len) &&
2435                 0 == memcmp(sop->so_owner.data, owner->data, owner->len) &&
2436                 (sop->so_client->cl_clientid.cl_id == clid->cl_id);
2437 }
2438
2439 static struct nfs4_openowner *
2440 find_openstateowner_str(unsigned int hashval, struct nfsd4_open *open)
2441 {
2442         struct nfs4_stateowner *so;
2443         struct nfs4_openowner *oo;
2444
2445         list_for_each_entry(so, &open_ownerstr_hashtbl[hashval], so_strhash) {
2446                 if (same_owner_str(so, &open->op_owner, &open->op_clientid)) {
2447                         oo = openowner(so);
2448                         renew_client(oo->oo_owner.so_client);
2449                         return oo;
2450                 }
2451         }
2452         return NULL;
2453 }
2454
2455 /* search file_hashtbl[] for file */
2456 static struct nfs4_file *
2457 find_file(struct inode *ino)
2458 {
2459         unsigned int hashval = file_hashval(ino);
2460         struct nfs4_file *fp;
2461
2462         spin_lock(&recall_lock);
2463         list_for_each_entry(fp, &file_hashtbl[hashval], fi_hash) {
2464                 if (fp->fi_inode == ino) {
2465                         get_nfs4_file(fp);
2466                         spin_unlock(&recall_lock);
2467                         return fp;
2468                 }
2469         }
2470         spin_unlock(&recall_lock);
2471         return NULL;
2472 }
2473
2474 /*
2475  * Called to check deny when READ with all zero stateid or
2476  * WRITE with all zero or all one stateid
2477  */
2478 static __be32
2479 nfs4_share_conflict(struct svc_fh *current_fh, unsigned int deny_type)
2480 {
2481         struct inode *ino = current_fh->fh_dentry->d_inode;
2482         struct nfs4_file *fp;
2483         struct nfs4_ol_stateid *stp;
2484         __be32 ret;
2485
2486         dprintk("NFSD: nfs4_share_conflict\n");
2487
2488         fp = find_file(ino);
2489         if (!fp)
2490                 return nfs_ok;
2491         ret = nfserr_locked;
2492         /* Search for conflicting share reservations */
2493         list_for_each_entry(stp, &fp->fi_stateids, st_perfile) {
2494                 if (test_bit(deny_type, &stp->st_deny_bmap) ||
2495                     test_bit(NFS4_SHARE_DENY_BOTH, &stp->st_deny_bmap))
2496                         goto out;
2497         }
2498         ret = nfs_ok;
2499 out:
2500         put_nfs4_file(fp);
2501         return ret;
2502 }
2503
2504 static void nfsd_break_one_deleg(struct nfs4_delegation *dp)
2505 {
2506         /* We're assuming the state code never drops its reference
2507          * without first removing the lease.  Since we're in this lease
2508          * callback (and since the lease code is serialized by the kernel
2509          * lock) we know the server hasn't removed the lease yet, we know
2510          * it's safe to take a reference: */
2511         atomic_inc(&dp->dl_count);
2512
2513         list_add_tail(&dp->dl_recall_lru, &del_recall_lru);
2514
2515         /* only place dl_time is set. protected by lock_flocks*/
2516         dp->dl_time = get_seconds();
2517
2518         nfsd4_cb_recall(dp);
2519 }
2520
2521 /* Called from break_lease() with lock_flocks() held. */
2522 static void nfsd_break_deleg_cb(struct file_lock *fl)
2523 {
2524         struct nfs4_file *fp = (struct nfs4_file *)fl->fl_owner;
2525         struct nfs4_delegation *dp;
2526
2527         BUG_ON(!fp);
2528         /* We assume break_lease is only called once per lease: */
2529         BUG_ON(fp->fi_had_conflict);
2530         /*
2531          * We don't want the locks code to timeout the lease for us;
2532          * we'll remove it ourself if a delegation isn't returned
2533          * in time:
2534          */
2535         fl->fl_break_time = 0;
2536
2537         spin_lock(&recall_lock);
2538         fp->fi_had_conflict = true;
2539         list_for_each_entry(dp, &fp->fi_delegations, dl_perfile)
2540                 nfsd_break_one_deleg(dp);
2541         spin_unlock(&recall_lock);
2542 }
2543
2544 static
2545 int nfsd_change_deleg_cb(struct file_lock **onlist, int arg)
2546 {
2547         if (arg & F_UNLCK)
2548                 return lease_modify(onlist, arg);
2549         else
2550                 return -EAGAIN;
2551 }
2552
2553 static const struct lock_manager_operations nfsd_lease_mng_ops = {
2554         .lm_break = nfsd_break_deleg_cb,
2555         .lm_change = nfsd_change_deleg_cb,
2556 };
2557
2558 static __be32 nfsd4_check_seqid(struct nfsd4_compound_state *cstate, struct nfs4_stateowner *so, u32 seqid)
2559 {
2560         if (nfsd4_has_session(cstate))
2561                 return nfs_ok;
2562         if (seqid == so->so_seqid - 1)
2563                 return nfserr_replay_me;
2564         if (seqid == so->so_seqid)
2565                 return nfs_ok;
2566         return nfserr_bad_seqid;
2567 }
2568
2569 __be32
2570 nfsd4_process_open1(struct nfsd4_compound_state *cstate,
2571                     struct nfsd4_open *open)
2572 {
2573         clientid_t *clientid = &open->op_clientid;
2574         struct nfs4_client *clp = NULL;
2575         unsigned int strhashval;
2576         struct nfs4_openowner *oo = NULL;
2577         __be32 status;
2578
2579         if (STALE_CLIENTID(&open->op_clientid))
2580                 return nfserr_stale_clientid;
2581         /*
2582          * In case we need it later, after we've already created the
2583          * file and don't want to risk a further failure:
2584          */
2585         open->op_file = nfsd4_alloc_file();
2586         if (open->op_file == NULL)
2587                 return nfserr_jukebox;
2588
2589         strhashval = open_ownerstr_hashval(clientid->cl_id, &open->op_owner);
2590         oo = find_openstateowner_str(strhashval, open);
2591         open->op_openowner = oo;
2592         if (!oo) {
2593                 clp = find_confirmed_client(clientid);
2594                 if (clp == NULL)
2595                         return nfserr_expired;
2596                 goto new_owner;
2597         }
2598         if (!(oo->oo_flags & NFS4_OO_CONFIRMED)) {
2599                 /* Replace unconfirmed owners without checking for replay. */
2600                 clp = oo->oo_owner.so_client;
2601                 release_openowner(oo);
2602                 open->op_openowner = NULL;
2603                 goto new_owner;
2604         }
2605         status = nfsd4_check_seqid(cstate, &oo->oo_owner, open->op_seqid);
2606         if (status)
2607                 return status;
2608         clp = oo->oo_owner.so_client;
2609         goto alloc_stateid;
2610 new_owner:
2611         oo = alloc_init_open_stateowner(strhashval, clp, open);
2612         if (oo == NULL)
2613                 return nfserr_jukebox;
2614         open->op_openowner = oo;
2615 alloc_stateid:
2616         open->op_stp = nfs4_alloc_stateid(clp);
2617         if (!open->op_stp)
2618                 return nfserr_jukebox;
2619         return nfs_ok;
2620 }
2621
2622 static inline __be32
2623 nfs4_check_delegmode(struct nfs4_delegation *dp, int flags)
2624 {
2625         if ((flags & WR_STATE) && (dp->dl_type == NFS4_OPEN_DELEGATE_READ))
2626                 return nfserr_openmode;
2627         else
2628                 return nfs_ok;
2629 }
2630
2631 static int share_access_to_flags(u32 share_access)
2632 {
2633         share_access &= ~NFS4_SHARE_WANT_MASK;
2634
2635         return share_access == NFS4_SHARE_ACCESS_READ ? RD_STATE : WR_STATE;
2636 }
2637
2638 static struct nfs4_delegation *find_deleg_stateid(struct nfs4_client *cl, stateid_t *s)
2639 {
2640         struct nfs4_stid *ret;
2641
2642         ret = find_stateid_by_type(cl, s, NFS4_DELEG_STID);
2643         if (!ret)
2644                 return NULL;
2645         return delegstateid(ret);
2646 }
2647
2648 static bool nfsd4_is_deleg_cur(struct nfsd4_open *open)
2649 {
2650         return open->op_claim_type == NFS4_OPEN_CLAIM_DELEGATE_CUR ||
2651                open->op_claim_type == NFS4_OPEN_CLAIM_DELEG_CUR_FH;
2652 }
2653
2654 static __be32
2655 nfs4_check_deleg(struct nfs4_client *cl, struct nfs4_file *fp, struct nfsd4_open *open,
2656                 struct nfs4_delegation **dp)
2657 {
2658         int flags;
2659         __be32 status = nfserr_bad_stateid;
2660
2661         *dp = find_deleg_stateid(cl, &open->op_delegate_stateid);
2662         if (*dp == NULL)
2663                 goto out;
2664         flags = share_access_to_flags(open->op_share_access);
2665         status = nfs4_check_delegmode(*dp, flags);
2666         if (status)
2667                 *dp = NULL;
2668 out:
2669         if (!nfsd4_is_deleg_cur(open))
2670                 return nfs_ok;
2671         if (status)
2672                 return status;
2673         open->op_openowner->oo_flags |= NFS4_OO_CONFIRMED;
2674         return nfs_ok;
2675 }
2676
2677 static __be32
2678 nfs4_check_open(struct nfs4_file *fp, struct nfsd4_open *open, struct nfs4_ol_stateid **stpp)
2679 {
2680         struct nfs4_ol_stateid *local;
2681         struct nfs4_openowner *oo = open->op_openowner;
2682
2683         list_for_each_entry(local, &fp->fi_stateids, st_perfile) {
2684                 /* ignore lock owners */
2685                 if (local->st_stateowner->so_is_open_owner == 0)
2686                         continue;
2687                 /* remember if we have seen this open owner */
2688                 if (local->st_stateowner == &oo->oo_owner)
2689                         *stpp = local;
2690                 /* check for conflicting share reservations */
2691                 if (!test_share(local, open))
2692                         return nfserr_share_denied;
2693         }
2694         return nfs_ok;
2695 }
2696
2697 static void nfs4_free_stateid(struct nfs4_ol_stateid *s)
2698 {
2699         kmem_cache_free(stateid_slab, s);
2700 }
2701
2702 static inline int nfs4_access_to_access(u32 nfs4_access)
2703 {
2704         int flags = 0;
2705
2706         if (nfs4_access & NFS4_SHARE_ACCESS_READ)
2707                 flags |= NFSD_MAY_READ;
2708         if (nfs4_access & NFS4_SHARE_ACCESS_WRITE)
2709                 flags |= NFSD_MAY_WRITE;
2710         return flags;
2711 }
2712
2713 static __be32 nfs4_get_vfs_file(struct svc_rqst *rqstp, struct nfs4_file *fp,
2714                 struct svc_fh *cur_fh, struct nfsd4_open *open)
2715 {
2716         __be32 status;
2717         int oflag = nfs4_access_to_omode(open->op_share_access);
2718         int access = nfs4_access_to_access(open->op_share_access);
2719
2720         if (!fp->fi_fds[oflag]) {
2721                 status = nfsd_open(rqstp, cur_fh, S_IFREG, access,
2722                         &fp->fi_fds[oflag]);
2723                 if (status)
2724                         return status;
2725         }
2726         nfs4_file_get_access(fp, oflag);
2727
2728         return nfs_ok;
2729 }
2730
2731 static inline __be32
2732 nfsd4_truncate(struct svc_rqst *rqstp, struct svc_fh *fh,
2733                 struct nfsd4_open *open)
2734 {
2735         struct iattr iattr = {
2736                 .ia_valid = ATTR_SIZE,
2737                 .ia_size = 0,
2738         };
2739         if (!open->op_truncate)
2740                 return 0;
2741         if (!(open->op_share_access & NFS4_SHARE_ACCESS_WRITE))
2742                 return nfserr_inval;
2743         return nfsd_setattr(rqstp, fh, &iattr, 0, (time_t)0);
2744 }
2745
2746 static __be32
2747 nfs4_upgrade_open(struct svc_rqst *rqstp, struct nfs4_file *fp, struct svc_fh *cur_fh, struct nfs4_ol_stateid *stp, struct nfsd4_open *open)
2748 {
2749         u32 op_share_access = open->op_share_access;
2750         bool new_access;
2751         __be32 status;
2752
2753         new_access = !test_bit(op_share_access, &stp->st_access_bmap);
2754         if (new_access) {
2755                 status = nfs4_get_vfs_file(rqstp, fp, cur_fh, open);
2756                 if (status)
2757                         return status;
2758         }
2759         status = nfsd4_truncate(rqstp, cur_fh, open);
2760         if (status) {
2761                 if (new_access) {
2762                         int oflag = nfs4_access_to_omode(op_share_access);
2763                         nfs4_file_put_access(fp, oflag);
2764                 }
2765                 return status;
2766         }
2767         /* remember the open */
2768         __set_bit(op_share_access, &stp->st_access_bmap);
2769         __set_bit(open->op_share_deny, &stp->st_deny_bmap);
2770
2771         return nfs_ok;
2772 }
2773
2774
2775 static void
2776 nfs4_set_claim_prev(struct nfsd4_open *open)
2777 {
2778         open->op_openowner->oo_flags |= NFS4_OO_CONFIRMED;
2779         open->op_openowner->oo_owner.so_client->cl_firststate = 1;
2780 }
2781
2782 /* Should we give out recallable state?: */
2783 static bool nfsd4_cb_channel_good(struct nfs4_client *clp)
2784 {
2785         if (clp->cl_cb_state == NFSD4_CB_UP)
2786                 return true;
2787         /*
2788          * In the sessions case, since we don't have to establish a
2789          * separate connection for callbacks, we assume it's OK
2790          * until we hear otherwise:
2791          */
2792         return clp->cl_minorversion && clp->cl_cb_state == NFSD4_CB_UNKNOWN;
2793 }
2794
2795 static struct file_lock *nfs4_alloc_init_lease(struct nfs4_delegation *dp, int flag)
2796 {
2797         struct file_lock *fl;
2798
2799         fl = locks_alloc_lock();
2800         if (!fl)
2801                 return NULL;
2802         locks_init_lock(fl);
2803         fl->fl_lmops = &nfsd_lease_mng_ops;
2804         fl->fl_flags = FL_LEASE;
2805         fl->fl_type = flag == NFS4_OPEN_DELEGATE_READ? F_RDLCK: F_WRLCK;
2806         fl->fl_end = OFFSET_MAX;
2807         fl->fl_owner = (fl_owner_t)(dp->dl_file);
2808         fl->fl_pid = current->tgid;
2809         return fl;
2810 }
2811
2812 static int nfs4_setlease(struct nfs4_delegation *dp, int flag)
2813 {
2814         struct nfs4_file *fp = dp->dl_file;
2815         struct file_lock *fl;
2816         int status;
2817
2818         fl = nfs4_alloc_init_lease(dp, flag);
2819         if (!fl)
2820                 return -ENOMEM;
2821         fl->fl_file = find_readable_file(fp);
2822         status = vfs_setlease(fl->fl_file, fl->fl_type, &fl);
2823         if (status) {
2824                 locks_free_lock(fl);
2825                 return -ENOMEM;
2826         }
2827         fp->fi_lease = fl;
2828         fp->fi_deleg_file = get_file(fl->fl_file);
2829         atomic_set(&fp->fi_delegees, 1);
2830         spin_lock(&recall_lock);
2831         hash_delegation_locked(dp, fp);
2832         spin_unlock(&recall_lock);
2833         return 0;
2834 }
2835
2836 static int nfs4_set_delegation(struct nfs4_delegation *dp, int flag)
2837 {
2838         struct nfs4_file *fp = dp->dl_file;
2839
2840         if (!fp->fi_lease)
2841                 return nfs4_setlease(dp, flag);
2842         spin_lock(&recall_lock);
2843         if (fp->fi_had_conflict) {
2844                 spin_unlock(&recall_lock);
2845                 return -EAGAIN;
2846         }
2847         atomic_inc(&fp->fi_delegees);
2848         hash_delegation_locked(dp, fp);
2849         spin_unlock(&recall_lock);
2850         return 0;
2851 }
2852
2853 /*
2854  * Attempt to hand out a delegation.
2855  */
2856 static void
2857 nfs4_open_delegation(struct svc_fh *fh, struct nfsd4_open *open, struct nfs4_ol_stateid *stp)
2858 {
2859         struct nfs4_delegation *dp;
2860         struct nfs4_openowner *oo = container_of(stp->st_stateowner, struct nfs4_openowner, oo_owner);
2861         int cb_up;
2862         int status, flag = 0;
2863
2864         cb_up = nfsd4_cb_channel_good(oo->oo_owner.so_client);
2865         flag = NFS4_OPEN_DELEGATE_NONE;
2866         open->op_recall = 0;
2867         switch (open->op_claim_type) {
2868                 case NFS4_OPEN_CLAIM_PREVIOUS:
2869                         if (!cb_up)
2870                                 open->op_recall = 1;
2871                         flag = open->op_delegate_type;
2872                         if (flag == NFS4_OPEN_DELEGATE_NONE)
2873                                 goto out;
2874                         break;
2875                 case NFS4_OPEN_CLAIM_NULL:
2876                         /* Let's not give out any delegations till everyone's
2877                          * had the chance to reclaim theirs.... */
2878                         if (locks_in_grace())
2879                                 goto out;
2880                         if (!cb_up || !(oo->oo_flags & NFS4_OO_CONFIRMED))
2881                                 goto out;
2882                         if (open->op_share_access & NFS4_SHARE_ACCESS_WRITE)
2883                                 flag = NFS4_OPEN_DELEGATE_WRITE;
2884                         else
2885                                 flag = NFS4_OPEN_DELEGATE_READ;
2886                         break;
2887                 default:
2888                         goto out;
2889         }
2890
2891         dp = alloc_init_deleg(oo->oo_owner.so_client, stp, fh, flag);
2892         if (dp == NULL)
2893                 goto out_no_deleg;
2894         status = nfs4_set_delegation(dp, flag);
2895         if (status)
2896                 goto out_free;
2897
2898         memcpy(&open->op_delegate_stateid, &dp->dl_stid.sc_stateid, sizeof(dp->dl_stid.sc_stateid));
2899
2900         dprintk("NFSD: delegation stateid=" STATEID_FMT "\n",
2901                 STATEID_VAL(&dp->dl_stid.sc_stateid));
2902 out:
2903         if (open->op_claim_type == NFS4_OPEN_CLAIM_PREVIOUS
2904                         && flag == NFS4_OPEN_DELEGATE_NONE
2905                         && open->op_delegate_type != NFS4_OPEN_DELEGATE_NONE)
2906                 dprintk("NFSD: WARNING: refusing delegation reclaim\n");
2907         open->op_delegate_type = flag;
2908         return;
2909 out_free:
2910         nfs4_put_delegation(dp);
2911 out_no_deleg:
2912         flag = NFS4_OPEN_DELEGATE_NONE;
2913         goto out;
2914 }
2915
2916 /*
2917  * called with nfs4_lock_state() held.
2918  */
2919 __be32
2920 nfsd4_process_open2(struct svc_rqst *rqstp, struct svc_fh *current_fh, struct nfsd4_open *open)
2921 {
2922         struct nfsd4_compoundres *resp = rqstp->rq_resp;
2923         struct nfs4_client *cl = open->op_openowner->oo_owner.so_client;
2924         struct nfs4_file *fp = NULL;
2925         struct inode *ino = current_fh->fh_dentry->d_inode;
2926         struct nfs4_ol_stateid *stp = NULL;
2927         struct nfs4_delegation *dp = NULL;
2928         __be32 status;
2929
2930         /*
2931          * Lookup file; if found, lookup stateid and check open request,
2932          * and check for delegations in the process of being recalled.
2933          * If not found, create the nfs4_file struct
2934          */
2935         fp = find_file(ino);
2936         if (fp) {
2937                 if ((status = nfs4_check_open(fp, open, &stp)))
2938                         goto out;
2939                 status = nfs4_check_deleg(cl, fp, open, &dp);
2940                 if (status)
2941                         goto out;
2942         } else {
2943                 status = nfserr_bad_stateid;
2944                 if (nfsd4_is_deleg_cur(open))
2945                         goto out;
2946                 status = nfserr_jukebox;
2947                 fp = open->op_file;
2948                 open->op_file = NULL;
2949                 nfsd4_init_file(fp, ino);
2950         }
2951
2952         /*
2953          * OPEN the file, or upgrade an existing OPEN.
2954          * If truncate fails, the OPEN fails.
2955          */
2956         if (stp) {
2957                 /* Stateid was found, this is an OPEN upgrade */
2958                 status = nfs4_upgrade_open(rqstp, fp, current_fh, stp, open);
2959                 if (status)
2960                         goto out;
2961         } else {
2962                 status = nfs4_get_vfs_file(rqstp, fp, current_fh, open);
2963                 if (status)
2964                         goto out;
2965                 stp = open->op_stp;
2966                 open->op_stp = NULL;
2967                 init_open_stateid(stp, fp, open);
2968                 status = nfsd4_truncate(rqstp, current_fh, open);
2969                 if (status) {
2970                         release_open_stateid(stp);
2971                         goto out;
2972                 }
2973         }
2974         update_stateid(&stp->st_stid.sc_stateid);
2975         memcpy(&open->op_stateid, &stp->st_stid.sc_stateid, sizeof(stateid_t));
2976
2977         if (nfsd4_has_session(&resp->cstate))
2978                 open->op_openowner->oo_flags |= NFS4_OO_CONFIRMED;
2979
2980         /*
2981         * Attempt to hand out a delegation. No error return, because the
2982         * OPEN succeeds even if we fail.
2983         */
2984         nfs4_open_delegation(current_fh, open, stp);
2985
2986         status = nfs_ok;
2987
2988         dprintk("%s: stateid=" STATEID_FMT "\n", __func__,
2989                 STATEID_VAL(&stp->st_stid.sc_stateid));
2990 out:
2991         if (fp)
2992                 put_nfs4_file(fp);
2993         if (status == 0 && open->op_claim_type == NFS4_OPEN_CLAIM_PREVIOUS)
2994                 nfs4_set_claim_prev(open);
2995         /*
2996         * To finish the open response, we just need to set the rflags.
2997         */
2998         open->op_rflags = NFS4_OPEN_RESULT_LOCKTYPE_POSIX;
2999         if (!(open->op_openowner->oo_flags & NFS4_OO_CONFIRMED) &&
3000             !nfsd4_has_session(&resp->cstate))
3001                 open->op_rflags |= NFS4_OPEN_RESULT_CONFIRM;
3002
3003         return status;
3004 }
3005
3006 void nfsd4_cleanup_open_state(struct nfsd4_open *open, __be32 status)
3007 {
3008         if (open->op_openowner) {
3009                 struct nfs4_openowner *oo = open->op_openowner;
3010
3011                 if (!list_empty(&oo->oo_owner.so_stateids))
3012                         list_del_init(&oo->oo_close_lru);
3013                 if (oo->oo_flags & NFS4_OO_NEW) {
3014                         if (status) {
3015                                 release_openowner(oo);
3016                                 open->op_openowner = NULL;
3017                         } else
3018                                 oo->oo_flags &= ~NFS4_OO_NEW;
3019                 }
3020         }
3021         if (open->op_file)
3022                 nfsd4_free_file(open->op_file);
3023         if (open->op_stp)
3024                 nfs4_free_stateid(open->op_stp);
3025 }
3026
3027 __be32
3028 nfsd4_renew(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3029             clientid_t *clid)
3030 {
3031         struct nfs4_client *clp;
3032         __be32 status;
3033
3034         nfs4_lock_state();
3035         dprintk("process_renew(%08x/%08x): starting\n", 
3036                         clid->cl_boot, clid->cl_id);
3037         status = nfserr_stale_clientid;
3038         if (STALE_CLIENTID(clid))
3039                 goto out;
3040         clp = find_confirmed_client(clid);
3041         status = nfserr_expired;
3042         if (clp == NULL) {
3043                 /* We assume the client took too long to RENEW. */
3044                 dprintk("nfsd4_renew: clientid not found!\n");
3045                 goto out;
3046         }
3047         status = nfserr_cb_path_down;
3048         if (!list_empty(&clp->cl_delegations)
3049                         && clp->cl_cb_state != NFSD4_CB_UP)
3050                 goto out;
3051         status = nfs_ok;
3052 out:
3053         nfs4_unlock_state();
3054         return status;
3055 }
3056
3057 static struct lock_manager nfsd4_manager = {
3058 };
3059
3060 static void
3061 nfsd4_end_grace(void)
3062 {
3063         dprintk("NFSD: end of grace period\n");
3064         nfsd4_recdir_purge_old();
3065         locks_end_grace(&nfsd4_manager);
3066         /*
3067          * Now that every NFSv4 client has had the chance to recover and
3068          * to see the (possibly new, possibly shorter) lease time, we
3069          * can safely set the next grace time to the current lease time:
3070          */
3071         nfsd4_grace = nfsd4_lease;
3072 }
3073
3074 static time_t
3075 nfs4_laundromat(void)
3076 {
3077         struct nfs4_client *clp;
3078         struct nfs4_openowner *oo;
3079         struct nfs4_delegation *dp;
3080         struct list_head *pos, *next, reaplist;
3081         time_t cutoff = get_seconds() - nfsd4_lease;
3082         time_t t, clientid_val = nfsd4_lease;
3083         time_t u, test_val = nfsd4_lease;
3084
3085         nfs4_lock_state();
3086
3087         dprintk("NFSD: laundromat service - starting\n");
3088         if (locks_in_grace())
3089                 nfsd4_end_grace();
3090         INIT_LIST_HEAD(&reaplist);
3091         spin_lock(&client_lock);
3092         list_for_each_safe(pos, next, &client_lru) {
3093                 clp = list_entry(pos, struct nfs4_client, cl_lru);
3094                 if (time_after((unsigned long)clp->cl_time, (unsigned long)cutoff)) {
3095                         t = clp->cl_time - cutoff;
3096                         if (clientid_val > t)
3097                                 clientid_val = t;
3098                         break;
3099                 }
3100                 if (atomic_read(&clp->cl_refcount)) {
3101                         dprintk("NFSD: client in use (clientid %08x)\n",
3102                                 clp->cl_clientid.cl_id);
3103                         continue;
3104                 }
3105                 unhash_client_locked(clp);
3106                 list_add(&clp->cl_lru, &reaplist);
3107         }
3108         spin_unlock(&client_lock);
3109         list_for_each_safe(pos, next, &reaplist) {
3110                 clp = list_entry(pos, struct nfs4_client, cl_lru);
3111                 dprintk("NFSD: purging unused client (clientid %08x)\n",
3112                         clp->cl_clientid.cl_id);
3113                 nfsd4_remove_clid_dir(clp);
3114                 expire_client(clp);
3115         }
3116         spin_lock(&recall_lock);
3117         list_for_each_safe(pos, next, &del_recall_lru) {
3118                 dp = list_entry (pos, struct nfs4_delegation, dl_recall_lru);
3119                 if (time_after((unsigned long)dp->dl_time, (unsigned long)cutoff)) {
3120                         u = dp->dl_time - cutoff;
3121                         if (test_val > u)
3122                                 test_val = u;
3123                         break;
3124                 }
3125                 list_move(&dp->dl_recall_lru, &reaplist);
3126         }
3127         spin_unlock(&recall_lock);
3128         list_for_each_safe(pos, next, &reaplist) {
3129                 dp = list_entry (pos, struct nfs4_delegation, dl_recall_lru);
3130                 list_del_init(&dp->dl_recall_lru);
3131                 unhash_delegation(dp);
3132         }
3133         test_val = nfsd4_lease;
3134         list_for_each_safe(pos, next, &close_lru) {
3135                 oo = container_of(pos, struct nfs4_openowner, oo_close_lru);
3136                 if (time_after((unsigned long)oo->oo_time, (unsigned long)cutoff)) {
3137                         u = oo->oo_time - cutoff;
3138                         if (test_val > u)
3139                                 test_val = u;
3140                         break;
3141                 }
3142                 release_openowner(oo);
3143         }
3144         if (clientid_val < NFSD_LAUNDROMAT_MINTIMEOUT)
3145                 clientid_val = NFSD_LAUNDROMAT_MINTIMEOUT;
3146         nfs4_unlock_state();
3147         return clientid_val;
3148 }
3149
3150 static struct workqueue_struct *laundry_wq;
3151 static void laundromat_main(struct work_struct *);
3152 static DECLARE_DELAYED_WORK(laundromat_work, laundromat_main);
3153
3154 static void
3155 laundromat_main(struct work_struct *not_used)
3156 {
3157         time_t t;
3158
3159         t = nfs4_laundromat();
3160         dprintk("NFSD: laundromat_main - sleeping for %ld seconds\n", t);
3161         queue_delayed_work(laundry_wq, &laundromat_work, t*HZ);
3162 }
3163
3164 static inline __be32 nfs4_check_fh(struct svc_fh *fhp, struct nfs4_ol_stateid *stp)
3165 {
3166         if (fhp->fh_dentry->d_inode != stp->st_file->fi_inode)
3167                 return nfserr_bad_stateid;
3168         return nfs_ok;
3169 }
3170
3171 static int
3172 STALE_STATEID(stateid_t *stateid)
3173 {
3174         if (stateid->si_opaque.so_clid.cl_boot == boot_time)
3175                 return 0;
3176         dprintk("NFSD: stale stateid " STATEID_FMT "!\n",
3177                 STATEID_VAL(stateid));
3178         return 1;
3179 }
3180
3181 static inline int
3182 access_permit_read(unsigned long access_bmap)
3183 {
3184         return test_bit(NFS4_SHARE_ACCESS_READ, &access_bmap) ||
3185                 test_bit(NFS4_SHARE_ACCESS_BOTH, &access_bmap) ||
3186                 test_bit(NFS4_SHARE_ACCESS_WRITE, &access_bmap);
3187 }
3188
3189 static inline int
3190 access_permit_write(unsigned long access_bmap)
3191 {
3192         return test_bit(NFS4_SHARE_ACCESS_WRITE, &access_bmap) ||
3193                 test_bit(NFS4_SHARE_ACCESS_BOTH, &access_bmap);
3194 }
3195
3196 static
3197 __be32 nfs4_check_openmode(struct nfs4_ol_stateid *stp, int flags)
3198 {
3199         __be32 status = nfserr_openmode;
3200
3201         /* For lock stateid's, we test the parent open, not the lock: */
3202         if (stp->st_openstp)
3203                 stp = stp->st_openstp;
3204         if ((flags & WR_STATE) && (!access_permit_write(stp->st_access_bmap)))
3205                 goto out;
3206         if ((flags & RD_STATE) && (!access_permit_read(stp->st_access_bmap)))
3207                 goto out;
3208         status = nfs_ok;
3209 out:
3210         return status;
3211 }
3212
3213 static inline __be32
3214 check_special_stateids(svc_fh *current_fh, stateid_t *stateid, int flags)
3215 {
3216         if (ONE_STATEID(stateid) && (flags & RD_STATE))
3217                 return nfs_ok;
3218         else if (locks_in_grace()) {
3219                 /* Answer in remaining cases depends on existence of
3220                  * conflicting state; so we must wait out the grace period. */
3221                 return nfserr_grace;
3222         } else if (flags & WR_STATE)
3223                 return nfs4_share_conflict(current_fh,
3224                                 NFS4_SHARE_DENY_WRITE);
3225         else /* (flags & RD_STATE) && ZERO_STATEID(stateid) */
3226                 return nfs4_share_conflict(current_fh,
3227                                 NFS4_SHARE_DENY_READ);
3228 }
3229
3230 /*
3231  * Allow READ/WRITE during grace period on recovered state only for files
3232  * that are not able to provide mandatory locking.
3233  */
3234 static inline int
3235 grace_disallows_io(struct inode *inode)
3236 {
3237         return locks_in_grace() && mandatory_lock(inode);
3238 }
3239
3240 /* Returns true iff a is later than b: */
3241 static bool stateid_generation_after(stateid_t *a, stateid_t *b)
3242 {
3243         return (s32)a->si_generation - (s32)b->si_generation > 0;
3244 }
3245
3246 static int check_stateid_generation(stateid_t *in, stateid_t *ref, bool has_session)
3247 {
3248         /*
3249          * When sessions are used the stateid generation number is ignored
3250          * when it is zero.
3251          */
3252         if (has_session && in->si_generation == 0)
3253                 return nfs_ok;
3254
3255         if (in->si_generation == ref->si_generation)
3256                 return nfs_ok;
3257
3258         /* If the client sends us a stateid from the future, it's buggy: */
3259         if (stateid_generation_after(in, ref))
3260                 return nfserr_bad_stateid;
3261         /*
3262          * However, we could see a stateid from the past, even from a
3263          * non-buggy client.  For example, if the client sends a lock
3264          * while some IO is outstanding, the lock may bump si_generation
3265          * while the IO is still in flight.  The client could avoid that
3266          * situation by waiting for responses on all the IO requests,
3267          * but better performance may result in retrying IO that
3268          * receives an old_stateid error if requests are rarely
3269          * reordered in flight:
3270          */
3271         return nfserr_old_stateid;
3272 }
3273
3274 static __be32 nfsd4_check_openowner_confirmed(struct nfs4_ol_stateid *ols)
3275 {
3276         if (ols->st_stateowner->so_is_open_owner &&
3277             !(openowner(ols->st_stateowner)->oo_flags & NFS4_OO_CONFIRMED))
3278                 return nfserr_bad_stateid;
3279         return nfs_ok;
3280 }
3281
3282 __be32 nfs4_validate_stateid(struct nfs4_client *cl, stateid_t *stateid)
3283 {
3284         struct nfs4_stid *s;
3285         __be32 status;
3286
3287         if (STALE_STATEID(stateid))
3288                 return nfserr_stale_stateid;
3289
3290         s = find_stateid(cl, stateid);
3291         if (!s)
3292                  return nfserr_stale_stateid;
3293         status = check_stateid_generation(stateid, &s->sc_stateid, 1);
3294         if (status)
3295                 return status;
3296         if (!(s->sc_type & (NFS4_OPEN_STID | NFS4_LOCK_STID)))
3297                 return nfs_ok;
3298         return nfsd4_check_openowner_confirmed(openlockstateid(s));
3299 }
3300
3301 static __be32 nfsd4_lookup_stateid(stateid_t *stateid, unsigned char typemask, struct nfs4_stid **s)
3302 {
3303         struct nfs4_client *cl;
3304
3305         if (ZERO_STATEID(stateid) || ONE_STATEID(stateid))
3306                 return nfserr_bad_stateid;
3307         if (STALE_STATEID(stateid))
3308                 return nfserr_stale_stateid;
3309         cl = find_confirmed_client(&stateid->si_opaque.so_clid);
3310         if (!cl)
3311                 return nfserr_expired;
3312         *s = find_stateid_by_type(cl, stateid, typemask);
3313         if (!*s)
3314                 return nfserr_bad_stateid;
3315         return nfs_ok;
3316
3317 }
3318
3319 /*
3320 * Checks for stateid operations
3321 */
3322 __be32
3323 nfs4_preprocess_stateid_op(struct nfsd4_compound_state *cstate,
3324                            stateid_t *stateid, int flags, struct file **filpp)
3325 {
3326         struct nfs4_stid *s;
3327         struct nfs4_ol_stateid *stp = NULL;
3328         struct nfs4_delegation *dp = NULL;
3329         struct svc_fh *current_fh = &cstate->current_fh;
3330         struct inode *ino = current_fh->fh_dentry->d_inode;
3331         __be32 status;
3332
3333         if (filpp)
3334                 *filpp = NULL;