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