nfsd: Add a struct nfs4_file field to struct nfs4_stid
[firefly-linux-kernel-4.4.55.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/ratelimit.h>
42 #include <linux/sunrpc/svcauth_gss.h>
43 #include <linux/sunrpc/addr.h>
44 #include <linux/hash.h>
45 #include "xdr4.h"
46 #include "xdr4cb.h"
47 #include "vfs.h"
48 #include "current_stateid.h"
49
50 #include "netns.h"
51
52 #define NFSDDBG_FACILITY                NFSDDBG_PROC
53
54 #define all_ones {{~0,~0},~0}
55 static const stateid_t one_stateid = {
56         .si_generation = ~0,
57         .si_opaque = all_ones,
58 };
59 static const stateid_t zero_stateid = {
60         /* all fields zero */
61 };
62 static const stateid_t currentstateid = {
63         .si_generation = 1,
64 };
65
66 static u64 current_sessionid = 1;
67
68 #define ZERO_STATEID(stateid) (!memcmp((stateid), &zero_stateid, sizeof(stateid_t)))
69 #define ONE_STATEID(stateid)  (!memcmp((stateid), &one_stateid, sizeof(stateid_t)))
70 #define CURRENT_STATEID(stateid) (!memcmp((stateid), &currentstateid, sizeof(stateid_t)))
71
72 /* forward declarations */
73 static bool check_for_locks(struct nfs4_file *fp, struct nfs4_lockowner *lowner);
74 static void nfs4_free_ol_stateid(struct nfs4_stid *stid);
75
76 /* Locking: */
77
78 /* Currently used for almost all code touching nfsv4 state: */
79 static DEFINE_MUTEX(client_mutex);
80
81 /*
82  * Currently used for the del_recall_lru and file hash table.  In an
83  * effort to decrease the scope of the client_mutex, this spinlock may
84  * eventually cover more:
85  */
86 static DEFINE_SPINLOCK(state_lock);
87
88 static struct kmem_cache *openowner_slab;
89 static struct kmem_cache *lockowner_slab;
90 static struct kmem_cache *file_slab;
91 static struct kmem_cache *stateid_slab;
92 static struct kmem_cache *deleg_slab;
93
94 void
95 nfs4_lock_state(void)
96 {
97         mutex_lock(&client_mutex);
98 }
99
100 static void free_session(struct nfsd4_session *);
101
102 static bool is_session_dead(struct nfsd4_session *ses)
103 {
104         return ses->se_flags & NFS4_SESSION_DEAD;
105 }
106
107 static __be32 mark_session_dead_locked(struct nfsd4_session *ses, int ref_held_by_me)
108 {
109         if (atomic_read(&ses->se_ref) > ref_held_by_me)
110                 return nfserr_jukebox;
111         ses->se_flags |= NFS4_SESSION_DEAD;
112         return nfs_ok;
113 }
114
115 void
116 nfs4_unlock_state(void)
117 {
118         mutex_unlock(&client_mutex);
119 }
120
121 static bool is_client_expired(struct nfs4_client *clp)
122 {
123         return clp->cl_time == 0;
124 }
125
126 static __be32 mark_client_expired_locked(struct nfs4_client *clp)
127 {
128         if (atomic_read(&clp->cl_refcount))
129                 return nfserr_jukebox;
130         clp->cl_time = 0;
131         return nfs_ok;
132 }
133
134 static __be32 mark_client_expired(struct nfs4_client *clp)
135 {
136         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
137         __be32 ret;
138
139         spin_lock(&nn->client_lock);
140         ret = mark_client_expired_locked(clp);
141         spin_unlock(&nn->client_lock);
142         return ret;
143 }
144
145 static __be32 get_client_locked(struct nfs4_client *clp)
146 {
147         if (is_client_expired(clp))
148                 return nfserr_expired;
149         atomic_inc(&clp->cl_refcount);
150         return nfs_ok;
151 }
152
153 /* must be called under the client_lock */
154 static inline void
155 renew_client_locked(struct nfs4_client *clp)
156 {
157         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
158
159         if (is_client_expired(clp)) {
160                 WARN_ON(1);
161                 printk("%s: client (clientid %08x/%08x) already expired\n",
162                         __func__,
163                         clp->cl_clientid.cl_boot,
164                         clp->cl_clientid.cl_id);
165                 return;
166         }
167
168         dprintk("renewing client (clientid %08x/%08x)\n",
169                         clp->cl_clientid.cl_boot,
170                         clp->cl_clientid.cl_id);
171         list_move_tail(&clp->cl_lru, &nn->client_lru);
172         clp->cl_time = get_seconds();
173 }
174
175 static inline void
176 renew_client(struct nfs4_client *clp)
177 {
178         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
179
180         spin_lock(&nn->client_lock);
181         renew_client_locked(clp);
182         spin_unlock(&nn->client_lock);
183 }
184
185 static void put_client_renew_locked(struct nfs4_client *clp)
186 {
187         if (!atomic_dec_and_test(&clp->cl_refcount))
188                 return;
189         if (!is_client_expired(clp))
190                 renew_client_locked(clp);
191 }
192
193 static void put_client_renew(struct nfs4_client *clp)
194 {
195         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
196
197         if (!atomic_dec_and_lock(&clp->cl_refcount, &nn->client_lock))
198                 return;
199         if (!is_client_expired(clp))
200                 renew_client_locked(clp);
201         spin_unlock(&nn->client_lock);
202 }
203
204 static __be32 nfsd4_get_session_locked(struct nfsd4_session *ses)
205 {
206         __be32 status;
207
208         if (is_session_dead(ses))
209                 return nfserr_badsession;
210         status = get_client_locked(ses->se_client);
211         if (status)
212                 return status;
213         atomic_inc(&ses->se_ref);
214         return nfs_ok;
215 }
216
217 static void nfsd4_put_session_locked(struct nfsd4_session *ses)
218 {
219         struct nfs4_client *clp = ses->se_client;
220
221         if (atomic_dec_and_test(&ses->se_ref) && is_session_dead(ses))
222                 free_session(ses);
223         put_client_renew_locked(clp);
224 }
225
226 static void nfsd4_put_session(struct nfsd4_session *ses)
227 {
228         struct nfs4_client *clp = ses->se_client;
229         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
230
231         spin_lock(&nn->client_lock);
232         nfsd4_put_session_locked(ses);
233         spin_unlock(&nn->client_lock);
234 }
235
236
237 static inline u32
238 opaque_hashval(const void *ptr, int nbytes)
239 {
240         unsigned char *cptr = (unsigned char *) ptr;
241
242         u32 x = 0;
243         while (nbytes--) {
244                 x *= 37;
245                 x += *cptr++;
246         }
247         return x;
248 }
249
250 static void nfsd4_free_file(struct nfs4_file *f)
251 {
252         kmem_cache_free(file_slab, f);
253 }
254
255 static inline void
256 put_nfs4_file(struct nfs4_file *fi)
257 {
258         might_lock(&state_lock);
259
260         if (atomic_dec_and_lock(&fi->fi_ref, &state_lock)) {
261                 hlist_del(&fi->fi_hash);
262                 spin_unlock(&state_lock);
263                 nfsd4_free_file(fi);
264         }
265 }
266
267 static inline void
268 get_nfs4_file(struct nfs4_file *fi)
269 {
270         atomic_inc(&fi->fi_ref);
271 }
272
273 static struct file *
274 __nfs4_get_fd(struct nfs4_file *f, int oflag)
275 {
276         if (f->fi_fds[oflag])
277                 return get_file(f->fi_fds[oflag]);
278         return NULL;
279 }
280
281 static struct file *
282 find_writeable_file_locked(struct nfs4_file *f)
283 {
284         struct file *ret;
285
286         lockdep_assert_held(&f->fi_lock);
287
288         ret = __nfs4_get_fd(f, O_WRONLY);
289         if (!ret)
290                 ret = __nfs4_get_fd(f, O_RDWR);
291         return ret;
292 }
293
294 static struct file *
295 find_writeable_file(struct nfs4_file *f)
296 {
297         struct file *ret;
298
299         spin_lock(&f->fi_lock);
300         ret = find_writeable_file_locked(f);
301         spin_unlock(&f->fi_lock);
302
303         return ret;
304 }
305
306 static struct file *find_readable_file_locked(struct nfs4_file *f)
307 {
308         struct file *ret;
309
310         lockdep_assert_held(&f->fi_lock);
311
312         ret = __nfs4_get_fd(f, O_RDONLY);
313         if (!ret)
314                 ret = __nfs4_get_fd(f, O_RDWR);
315         return ret;
316 }
317
318 static struct file *
319 find_readable_file(struct nfs4_file *f)
320 {
321         struct file *ret;
322
323         spin_lock(&f->fi_lock);
324         ret = find_readable_file_locked(f);
325         spin_unlock(&f->fi_lock);
326
327         return ret;
328 }
329
330 static struct file *
331 find_any_file(struct nfs4_file *f)
332 {
333         struct file *ret;
334
335         spin_lock(&f->fi_lock);
336         ret = __nfs4_get_fd(f, O_RDWR);
337         if (!ret) {
338                 ret = __nfs4_get_fd(f, O_WRONLY);
339                 if (!ret)
340                         ret = __nfs4_get_fd(f, O_RDONLY);
341         }
342         spin_unlock(&f->fi_lock);
343         return ret;
344 }
345
346 static atomic_long_t num_delegations;
347 unsigned long max_delegations;
348
349 /*
350  * Open owner state (share locks)
351  */
352
353 /* hash tables for lock and open owners */
354 #define OWNER_HASH_BITS              8
355 #define OWNER_HASH_SIZE             (1 << OWNER_HASH_BITS)
356 #define OWNER_HASH_MASK             (OWNER_HASH_SIZE - 1)
357
358 static unsigned int ownerstr_hashval(u32 clientid, struct xdr_netobj *ownername)
359 {
360         unsigned int ret;
361
362         ret = opaque_hashval(ownername->data, ownername->len);
363         ret += clientid;
364         return ret & OWNER_HASH_MASK;
365 }
366
367 /* hash table for nfs4_file */
368 #define FILE_HASH_BITS                   8
369 #define FILE_HASH_SIZE                  (1 << FILE_HASH_BITS)
370
371 static unsigned int nfsd_fh_hashval(struct knfsd_fh *fh)
372 {
373         return jhash2(fh->fh_base.fh_pad, XDR_QUADLEN(fh->fh_size), 0);
374 }
375
376 static unsigned int file_hashval(struct knfsd_fh *fh)
377 {
378         return nfsd_fh_hashval(fh) & (FILE_HASH_SIZE - 1);
379 }
380
381 static bool nfsd_fh_match(struct knfsd_fh *fh1, struct knfsd_fh *fh2)
382 {
383         return fh1->fh_size == fh2->fh_size &&
384                 !memcmp(fh1->fh_base.fh_pad,
385                                 fh2->fh_base.fh_pad,
386                                 fh1->fh_size);
387 }
388
389 static struct hlist_head file_hashtbl[FILE_HASH_SIZE];
390
391 static void
392 __nfs4_file_get_access(struct nfs4_file *fp, u32 access)
393 {
394         lockdep_assert_held(&fp->fi_lock);
395
396         if (access & NFS4_SHARE_ACCESS_WRITE)
397                 atomic_inc(&fp->fi_access[O_WRONLY]);
398         if (access & NFS4_SHARE_ACCESS_READ)
399                 atomic_inc(&fp->fi_access[O_RDONLY]);
400 }
401
402 static __be32
403 nfs4_file_get_access(struct nfs4_file *fp, u32 access)
404 {
405         lockdep_assert_held(&fp->fi_lock);
406
407         /* Does this access mode make sense? */
408         if (access & ~NFS4_SHARE_ACCESS_BOTH)
409                 return nfserr_inval;
410
411         /* Does it conflict with a deny mode already set? */
412         if ((access & fp->fi_share_deny) != 0)
413                 return nfserr_share_denied;
414
415         __nfs4_file_get_access(fp, access);
416         return nfs_ok;
417 }
418
419 static __be32 nfs4_file_check_deny(struct nfs4_file *fp, u32 deny)
420 {
421         /* Common case is that there is no deny mode. */
422         if (deny) {
423                 /* Does this deny mode make sense? */
424                 if (deny & ~NFS4_SHARE_DENY_BOTH)
425                         return nfserr_inval;
426
427                 if ((deny & NFS4_SHARE_DENY_READ) &&
428                     atomic_read(&fp->fi_access[O_RDONLY]))
429                         return nfserr_share_denied;
430
431                 if ((deny & NFS4_SHARE_DENY_WRITE) &&
432                     atomic_read(&fp->fi_access[O_WRONLY]))
433                         return nfserr_share_denied;
434         }
435         return nfs_ok;
436 }
437
438 static void __nfs4_file_put_access(struct nfs4_file *fp, int oflag)
439 {
440         might_lock(&fp->fi_lock);
441
442         if (atomic_dec_and_lock(&fp->fi_access[oflag], &fp->fi_lock)) {
443                 struct file *f1 = NULL;
444                 struct file *f2 = NULL;
445
446                 swap(f1, fp->fi_fds[oflag]);
447                 if (atomic_read(&fp->fi_access[1 - oflag]) == 0)
448                         swap(f2, fp->fi_fds[O_RDWR]);
449                 spin_unlock(&fp->fi_lock);
450                 if (f1)
451                         fput(f1);
452                 if (f2)
453                         fput(f2);
454         }
455 }
456
457 static void nfs4_file_put_access(struct nfs4_file *fp, u32 access)
458 {
459         WARN_ON_ONCE(access & ~NFS4_SHARE_ACCESS_BOTH);
460
461         if (access & NFS4_SHARE_ACCESS_WRITE)
462                 __nfs4_file_put_access(fp, O_WRONLY);
463         if (access & NFS4_SHARE_ACCESS_READ)
464                 __nfs4_file_put_access(fp, O_RDONLY);
465 }
466
467 static struct nfs4_stid *nfs4_alloc_stid(struct nfs4_client *cl,
468                                          struct kmem_cache *slab)
469 {
470         struct idr *stateids = &cl->cl_stateids;
471         struct nfs4_stid *stid;
472         int new_id;
473
474         stid = kmem_cache_zalloc(slab, GFP_KERNEL);
475         if (!stid)
476                 return NULL;
477
478         new_id = idr_alloc_cyclic(stateids, stid, 0, 0, GFP_KERNEL);
479         if (new_id < 0)
480                 goto out_free;
481         stid->sc_client = cl;
482         stid->sc_stateid.si_opaque.so_id = new_id;
483         stid->sc_stateid.si_opaque.so_clid = cl->cl_clientid;
484         /* Will be incremented before return to client: */
485         atomic_set(&stid->sc_count, 1);
486
487         /*
488          * It shouldn't be a problem to reuse an opaque stateid value.
489          * I don't think it is for 4.1.  But with 4.0 I worry that, for
490          * example, a stray write retransmission could be accepted by
491          * the server when it should have been rejected.  Therefore,
492          * adopt a trick from the sctp code to attempt to maximize the
493          * amount of time until an id is reused, by ensuring they always
494          * "increase" (mod INT_MAX):
495          */
496         return stid;
497 out_free:
498         kmem_cache_free(slab, stid);
499         return NULL;
500 }
501
502 static struct nfs4_ol_stateid * nfs4_alloc_stateid(struct nfs4_client *clp)
503 {
504         struct nfs4_stid *stid;
505         struct nfs4_ol_stateid *stp;
506
507         stid = nfs4_alloc_stid(clp, stateid_slab);
508         if (!stid)
509                 return NULL;
510
511         stp = openlockstateid(stid);
512         stp->st_stid.sc_free = nfs4_free_ol_stateid;
513         return stp;
514 }
515
516 static void nfs4_free_deleg(struct nfs4_stid *stid)
517 {
518         kmem_cache_free(deleg_slab, stid);
519         atomic_long_dec(&num_delegations);
520 }
521
522 /*
523  * When we recall a delegation, we should be careful not to hand it
524  * out again straight away.
525  * To ensure this we keep a pair of bloom filters ('new' and 'old')
526  * in which the filehandles of recalled delegations are "stored".
527  * If a filehandle appear in either filter, a delegation is blocked.
528  * When a delegation is recalled, the filehandle is stored in the "new"
529  * filter.
530  * Every 30 seconds we swap the filters and clear the "new" one,
531  * unless both are empty of course.
532  *
533  * Each filter is 256 bits.  We hash the filehandle to 32bit and use the
534  * low 3 bytes as hash-table indices.
535  *
536  * 'blocked_delegations_lock', which is always taken in block_delegations(),
537  * is used to manage concurrent access.  Testing does not need the lock
538  * except when swapping the two filters.
539  */
540 static DEFINE_SPINLOCK(blocked_delegations_lock);
541 static struct bloom_pair {
542         int     entries, old_entries;
543         time_t  swap_time;
544         int     new; /* index into 'set' */
545         DECLARE_BITMAP(set[2], 256);
546 } blocked_delegations;
547
548 static int delegation_blocked(struct knfsd_fh *fh)
549 {
550         u32 hash;
551         struct bloom_pair *bd = &blocked_delegations;
552
553         if (bd->entries == 0)
554                 return 0;
555         if (seconds_since_boot() - bd->swap_time > 30) {
556                 spin_lock(&blocked_delegations_lock);
557                 if (seconds_since_boot() - bd->swap_time > 30) {
558                         bd->entries -= bd->old_entries;
559                         bd->old_entries = bd->entries;
560                         memset(bd->set[bd->new], 0,
561                                sizeof(bd->set[0]));
562                         bd->new = 1-bd->new;
563                         bd->swap_time = seconds_since_boot();
564                 }
565                 spin_unlock(&blocked_delegations_lock);
566         }
567         hash = arch_fast_hash(&fh->fh_base, fh->fh_size, 0);
568         if (test_bit(hash&255, bd->set[0]) &&
569             test_bit((hash>>8)&255, bd->set[0]) &&
570             test_bit((hash>>16)&255, bd->set[0]))
571                 return 1;
572
573         if (test_bit(hash&255, bd->set[1]) &&
574             test_bit((hash>>8)&255, bd->set[1]) &&
575             test_bit((hash>>16)&255, bd->set[1]))
576                 return 1;
577
578         return 0;
579 }
580
581 static void block_delegations(struct knfsd_fh *fh)
582 {
583         u32 hash;
584         struct bloom_pair *bd = &blocked_delegations;
585
586         hash = arch_fast_hash(&fh->fh_base, fh->fh_size, 0);
587
588         spin_lock(&blocked_delegations_lock);
589         __set_bit(hash&255, bd->set[bd->new]);
590         __set_bit((hash>>8)&255, bd->set[bd->new]);
591         __set_bit((hash>>16)&255, bd->set[bd->new]);
592         if (bd->entries == 0)
593                 bd->swap_time = seconds_since_boot();
594         bd->entries += 1;
595         spin_unlock(&blocked_delegations_lock);
596 }
597
598 static struct nfs4_delegation *
599 alloc_init_deleg(struct nfs4_client *clp, struct svc_fh *current_fh)
600 {
601         struct nfs4_delegation *dp;
602         long n;
603
604         dprintk("NFSD alloc_init_deleg\n");
605         n = atomic_long_inc_return(&num_delegations);
606         if (n < 0 || n > max_delegations)
607                 goto out_dec;
608         if (delegation_blocked(&current_fh->fh_handle))
609                 goto out_dec;
610         dp = delegstateid(nfs4_alloc_stid(clp, deleg_slab));
611         if (dp == NULL)
612                 goto out_dec;
613
614         dp->dl_stid.sc_free = nfs4_free_deleg;
615         /*
616          * delegation seqid's are never incremented.  The 4.1 special
617          * meaning of seqid 0 isn't meaningful, really, but let's avoid
618          * 0 anyway just for consistency and use 1:
619          */
620         dp->dl_stid.sc_stateid.si_generation = 1;
621         INIT_LIST_HEAD(&dp->dl_perfile);
622         INIT_LIST_HEAD(&dp->dl_perclnt);
623         INIT_LIST_HEAD(&dp->dl_recall_lru);
624         dp->dl_type = NFS4_OPEN_DELEGATE_READ;
625         INIT_WORK(&dp->dl_recall.cb_work, nfsd4_run_cb_recall);
626         return dp;
627 out_dec:
628         atomic_long_dec(&num_delegations);
629         return NULL;
630 }
631
632 void
633 nfs4_put_stid(struct nfs4_stid *s)
634 {
635         struct nfs4_file *fp = s->sc_file;
636         struct nfs4_client *clp = s->sc_client;
637
638         if (!atomic_dec_and_test(&s->sc_count))
639                 return;
640         idr_remove(&clp->cl_stateids, s->sc_stateid.si_opaque.so_id);
641         s->sc_free(s);
642         if (fp)
643                 put_nfs4_file(fp);
644 }
645
646 static void nfs4_put_deleg_lease(struct nfs4_file *fp)
647 {
648         lockdep_assert_held(&state_lock);
649
650         if (!fp->fi_lease)
651                 return;
652         if (atomic_dec_and_test(&fp->fi_delegees)) {
653                 vfs_setlease(fp->fi_deleg_file, F_UNLCK, &fp->fi_lease);
654                 fp->fi_lease = NULL;
655                 fput(fp->fi_deleg_file);
656                 fp->fi_deleg_file = NULL;
657         }
658 }
659
660 static void unhash_stid(struct nfs4_stid *s)
661 {
662         s->sc_type = 0;
663 }
664
665 static void
666 hash_delegation_locked(struct nfs4_delegation *dp, struct nfs4_file *fp)
667 {
668         lockdep_assert_held(&state_lock);
669         lockdep_assert_held(&fp->fi_lock);
670
671         dp->dl_stid.sc_type = NFS4_DELEG_STID;
672         list_add(&dp->dl_perfile, &fp->fi_delegations);
673         list_add(&dp->dl_perclnt, &dp->dl_stid.sc_client->cl_delegations);
674 }
675
676 static void
677 unhash_delegation_locked(struct nfs4_delegation *dp)
678 {
679         struct nfs4_file *fp = dp->dl_stid.sc_file;
680
681         lockdep_assert_held(&state_lock);
682
683         dp->dl_stid.sc_type = NFS4_CLOSED_DELEG_STID;
684         /* Ensure that deleg break won't try to requeue it */
685         ++dp->dl_time;
686         spin_lock(&fp->fi_lock);
687         list_del_init(&dp->dl_perclnt);
688         list_del_init(&dp->dl_recall_lru);
689         list_del_init(&dp->dl_perfile);
690         spin_unlock(&fp->fi_lock);
691         if (fp)
692                 nfs4_put_deleg_lease(fp);
693 }
694
695 static void destroy_delegation(struct nfs4_delegation *dp)
696 {
697         spin_lock(&state_lock);
698         unhash_delegation_locked(dp);
699         spin_unlock(&state_lock);
700         nfs4_put_stid(&dp->dl_stid);
701 }
702
703 static void revoke_delegation(struct nfs4_delegation *dp)
704 {
705         struct nfs4_client *clp = dp->dl_stid.sc_client;
706
707         WARN_ON(!list_empty(&dp->dl_recall_lru));
708
709         if (clp->cl_minorversion == 0)
710                 nfs4_put_stid(&dp->dl_stid);
711         else {
712                 dp->dl_stid.sc_type = NFS4_REVOKED_DELEG_STID;
713                 spin_lock(&clp->cl_lock);
714                 list_add(&dp->dl_recall_lru, &clp->cl_revoked);
715                 spin_unlock(&clp->cl_lock);
716         }
717 }
718
719 /* 
720  * SETCLIENTID state 
721  */
722
723 static unsigned int clientid_hashval(u32 id)
724 {
725         return id & CLIENT_HASH_MASK;
726 }
727
728 static unsigned int clientstr_hashval(const char *name)
729 {
730         return opaque_hashval(name, 8) & CLIENT_HASH_MASK;
731 }
732
733 /*
734  * We store the NONE, READ, WRITE, and BOTH bits separately in the
735  * st_{access,deny}_bmap field of the stateid, in order to track not
736  * only what share bits are currently in force, but also what
737  * combinations of share bits previous opens have used.  This allows us
738  * to enforce the recommendation of rfc 3530 14.2.19 that the server
739  * return an error if the client attempt to downgrade to a combination
740  * of share bits not explicable by closing some of its previous opens.
741  *
742  * XXX: This enforcement is actually incomplete, since we don't keep
743  * track of access/deny bit combinations; so, e.g., we allow:
744  *
745  *      OPEN allow read, deny write
746  *      OPEN allow both, deny none
747  *      DOWNGRADE allow read, deny none
748  *
749  * which we should reject.
750  */
751 static unsigned int
752 bmap_to_share_mode(unsigned long bmap) {
753         int i;
754         unsigned int access = 0;
755
756         for (i = 1; i < 4; i++) {
757                 if (test_bit(i, &bmap))
758                         access |= i;
759         }
760         return access;
761 }
762
763 /* set share access for a given stateid */
764 static inline void
765 set_access(u32 access, struct nfs4_ol_stateid *stp)
766 {
767         unsigned char mask = 1 << access;
768
769         WARN_ON_ONCE(access > NFS4_SHARE_ACCESS_BOTH);
770         stp->st_access_bmap |= mask;
771 }
772
773 /* clear share access for a given stateid */
774 static inline void
775 clear_access(u32 access, struct nfs4_ol_stateid *stp)
776 {
777         unsigned char mask = 1 << access;
778
779         WARN_ON_ONCE(access > NFS4_SHARE_ACCESS_BOTH);
780         stp->st_access_bmap &= ~mask;
781 }
782
783 /* test whether a given stateid has access */
784 static inline bool
785 test_access(u32 access, struct nfs4_ol_stateid *stp)
786 {
787         unsigned char mask = 1 << access;
788
789         return (bool)(stp->st_access_bmap & mask);
790 }
791
792 /* set share deny for a given stateid */
793 static inline void
794 set_deny(u32 deny, struct nfs4_ol_stateid *stp)
795 {
796         unsigned char mask = 1 << deny;
797
798         WARN_ON_ONCE(deny > NFS4_SHARE_DENY_BOTH);
799         stp->st_deny_bmap |= mask;
800 }
801
802 /* clear share deny for a given stateid */
803 static inline void
804 clear_deny(u32 deny, struct nfs4_ol_stateid *stp)
805 {
806         unsigned char mask = 1 << deny;
807
808         WARN_ON_ONCE(deny > NFS4_SHARE_DENY_BOTH);
809         stp->st_deny_bmap &= ~mask;
810 }
811
812 /* test whether a given stateid is denying specific access */
813 static inline bool
814 test_deny(u32 deny, struct nfs4_ol_stateid *stp)
815 {
816         unsigned char mask = 1 << deny;
817
818         return (bool)(stp->st_deny_bmap & mask);
819 }
820
821 static int nfs4_access_to_omode(u32 access)
822 {
823         switch (access & NFS4_SHARE_ACCESS_BOTH) {
824         case NFS4_SHARE_ACCESS_READ:
825                 return O_RDONLY;
826         case NFS4_SHARE_ACCESS_WRITE:
827                 return O_WRONLY;
828         case NFS4_SHARE_ACCESS_BOTH:
829                 return O_RDWR;
830         }
831         WARN_ON_ONCE(1);
832         return O_RDONLY;
833 }
834
835 /*
836  * A stateid that had a deny mode associated with it is being released
837  * or downgraded. Recalculate the deny mode on the file.
838  */
839 static void
840 recalculate_deny_mode(struct nfs4_file *fp)
841 {
842         struct nfs4_ol_stateid *stp;
843
844         spin_lock(&fp->fi_lock);
845         fp->fi_share_deny = 0;
846         list_for_each_entry(stp, &fp->fi_stateids, st_perfile)
847                 fp->fi_share_deny |= bmap_to_share_mode(stp->st_deny_bmap);
848         spin_unlock(&fp->fi_lock);
849 }
850
851 static void
852 reset_union_bmap_deny(u32 deny, struct nfs4_ol_stateid *stp)
853 {
854         int i;
855         bool change = false;
856
857         for (i = 1; i < 4; i++) {
858                 if ((i & deny) != i) {
859                         change = true;
860                         clear_deny(i, stp);
861                 }
862         }
863
864         /* Recalculate per-file deny mode if there was a change */
865         if (change)
866                 recalculate_deny_mode(stp->st_stid.sc_file);
867 }
868
869 /* release all access and file references for a given stateid */
870 static void
871 release_all_access(struct nfs4_ol_stateid *stp)
872 {
873         int i;
874         struct nfs4_file *fp = stp->st_stid.sc_file;
875
876         if (fp && stp->st_deny_bmap != 0)
877                 recalculate_deny_mode(fp);
878
879         for (i = 1; i < 4; i++) {
880                 if (test_access(i, stp))
881                         nfs4_file_put_access(stp->st_stid.sc_file, i);
882                 clear_access(i, stp);
883         }
884 }
885
886 static void unhash_generic_stateid(struct nfs4_ol_stateid *stp)
887 {
888         struct nfs4_file *fp = stp->st_stid.sc_file;
889
890         spin_lock(&fp->fi_lock);
891         list_del(&stp->st_perfile);
892         spin_unlock(&fp->fi_lock);
893         list_del(&stp->st_perstateowner);
894 }
895
896 static void nfs4_free_ol_stateid(struct nfs4_stid *stid)
897 {
898         struct nfs4_ol_stateid *stp = openlockstateid(stid);
899
900         release_all_access(stp);
901         kmem_cache_free(stateid_slab, stid);
902 }
903
904 static void __release_lock_stateid(struct nfs4_ol_stateid *stp)
905 {
906         struct file *file;
907
908         list_del(&stp->st_locks);
909         unhash_generic_stateid(stp);
910         unhash_stid(&stp->st_stid);
911         file = find_any_file(stp->st_stid.sc_file);
912         if (file)
913                 filp_close(file, (fl_owner_t)lockowner(stp->st_stateowner));
914         nfs4_put_stid(&stp->st_stid);
915 }
916
917 static void unhash_lockowner(struct nfs4_lockowner *lo)
918 {
919         struct nfs4_ol_stateid *stp;
920
921         list_del(&lo->lo_owner.so_strhash);
922         while (!list_empty(&lo->lo_owner.so_stateids)) {
923                 stp = list_first_entry(&lo->lo_owner.so_stateids,
924                                 struct nfs4_ol_stateid, st_perstateowner);
925                 __release_lock_stateid(stp);
926         }
927 }
928
929 static void nfs4_free_lockowner(struct nfs4_lockowner *lo)
930 {
931         kfree(lo->lo_owner.so_owner.data);
932         kmem_cache_free(lockowner_slab, lo);
933 }
934
935 static void release_lockowner(struct nfs4_lockowner *lo)
936 {
937         unhash_lockowner(lo);
938         nfs4_free_lockowner(lo);
939 }
940
941 static void release_lockowner_if_empty(struct nfs4_lockowner *lo)
942 {
943         if (list_empty(&lo->lo_owner.so_stateids))
944                 release_lockowner(lo);
945 }
946
947 static void release_lock_stateid(struct nfs4_ol_stateid *stp)
948 {
949         struct nfs4_lockowner *lo;
950
951         lo = lockowner(stp->st_stateowner);
952         __release_lock_stateid(stp);
953         release_lockowner_if_empty(lo);
954 }
955
956 static void release_open_stateid_locks(struct nfs4_ol_stateid *open_stp)
957 {
958         struct nfs4_ol_stateid *stp;
959
960         while (!list_empty(&open_stp->st_locks)) {
961                 stp = list_entry(open_stp->st_locks.next,
962                                 struct nfs4_ol_stateid, st_locks);
963                 release_lock_stateid(stp);
964         }
965 }
966
967 static void unhash_open_stateid(struct nfs4_ol_stateid *stp)
968 {
969         unhash_generic_stateid(stp);
970         release_open_stateid_locks(stp);
971 }
972
973 static void release_open_stateid(struct nfs4_ol_stateid *stp)
974 {
975         unhash_open_stateid(stp);
976         nfs4_put_stid(&stp->st_stid);
977 }
978
979 static void unhash_openowner(struct nfs4_openowner *oo)
980 {
981         struct nfs4_ol_stateid *stp;
982
983         list_del(&oo->oo_owner.so_strhash);
984         list_del(&oo->oo_perclient);
985         while (!list_empty(&oo->oo_owner.so_stateids)) {
986                 stp = list_first_entry(&oo->oo_owner.so_stateids,
987                                 struct nfs4_ol_stateid, st_perstateowner);
988                 release_open_stateid(stp);
989         }
990 }
991
992 static void release_last_closed_stateid(struct nfs4_openowner *oo)
993 {
994         struct nfs4_ol_stateid *s = oo->oo_last_closed_stid;
995
996         if (s) {
997                 nfs4_put_stid(&s->st_stid);
998                 oo->oo_last_closed_stid = NULL;
999         }
1000 }
1001
1002 static void nfs4_free_openowner(struct nfs4_openowner *oo)
1003 {
1004         kfree(oo->oo_owner.so_owner.data);
1005         kmem_cache_free(openowner_slab, oo);
1006 }
1007
1008 static void release_openowner(struct nfs4_openowner *oo)
1009 {
1010         unhash_openowner(oo);
1011         list_del(&oo->oo_close_lru);
1012         release_last_closed_stateid(oo);
1013         nfs4_free_openowner(oo);
1014 }
1015
1016 static inline int
1017 hash_sessionid(struct nfs4_sessionid *sessionid)
1018 {
1019         struct nfsd4_sessionid *sid = (struct nfsd4_sessionid *)sessionid;
1020
1021         return sid->sequence % SESSION_HASH_SIZE;
1022 }
1023
1024 #ifdef NFSD_DEBUG
1025 static inline void
1026 dump_sessionid(const char *fn, struct nfs4_sessionid *sessionid)
1027 {
1028         u32 *ptr = (u32 *)(&sessionid->data[0]);
1029         dprintk("%s: %u:%u:%u:%u\n", fn, ptr[0], ptr[1], ptr[2], ptr[3]);
1030 }
1031 #else
1032 static inline void
1033 dump_sessionid(const char *fn, struct nfs4_sessionid *sessionid)
1034 {
1035 }
1036 #endif
1037
1038 /*
1039  * Bump the seqid on cstate->replay_owner, and clear replay_owner if it
1040  * won't be used for replay.
1041  */
1042 void nfsd4_bump_seqid(struct nfsd4_compound_state *cstate, __be32 nfserr)
1043 {
1044         struct nfs4_stateowner *so = cstate->replay_owner;
1045
1046         if (nfserr == nfserr_replay_me)
1047                 return;
1048
1049         if (!seqid_mutating_err(ntohl(nfserr))) {
1050                 cstate->replay_owner = NULL;
1051                 return;
1052         }
1053         if (!so)
1054                 return;
1055         if (so->so_is_open_owner)
1056                 release_last_closed_stateid(openowner(so));
1057         so->so_seqid++;
1058         return;
1059 }
1060
1061 static void
1062 gen_sessionid(struct nfsd4_session *ses)
1063 {
1064         struct nfs4_client *clp = ses->se_client;
1065         struct nfsd4_sessionid *sid;
1066
1067         sid = (struct nfsd4_sessionid *)ses->se_sessionid.data;
1068         sid->clientid = clp->cl_clientid;
1069         sid->sequence = current_sessionid++;
1070         sid->reserved = 0;
1071 }
1072
1073 /*
1074  * The protocol defines ca_maxresponssize_cached to include the size of
1075  * the rpc header, but all we need to cache is the data starting after
1076  * the end of the initial SEQUENCE operation--the rest we regenerate
1077  * each time.  Therefore we can advertise a ca_maxresponssize_cached
1078  * value that is the number of bytes in our cache plus a few additional
1079  * bytes.  In order to stay on the safe side, and not promise more than
1080  * we can cache, those additional bytes must be the minimum possible: 24
1081  * bytes of rpc header (xid through accept state, with AUTH_NULL
1082  * verifier), 12 for the compound header (with zero-length tag), and 44
1083  * for the SEQUENCE op response:
1084  */
1085 #define NFSD_MIN_HDR_SEQ_SZ  (24 + 12 + 44)
1086
1087 static void
1088 free_session_slots(struct nfsd4_session *ses)
1089 {
1090         int i;
1091
1092         for (i = 0; i < ses->se_fchannel.maxreqs; i++)
1093                 kfree(ses->se_slots[i]);
1094 }
1095
1096 /*
1097  * We don't actually need to cache the rpc and session headers, so we
1098  * can allocate a little less for each slot:
1099  */
1100 static inline u32 slot_bytes(struct nfsd4_channel_attrs *ca)
1101 {
1102         u32 size;
1103
1104         if (ca->maxresp_cached < NFSD_MIN_HDR_SEQ_SZ)
1105                 size = 0;
1106         else
1107                 size = ca->maxresp_cached - NFSD_MIN_HDR_SEQ_SZ;
1108         return size + sizeof(struct nfsd4_slot);
1109 }
1110
1111 /*
1112  * XXX: If we run out of reserved DRC memory we could (up to a point)
1113  * re-negotiate active sessions and reduce their slot usage to make
1114  * room for new connections. For now we just fail the create session.
1115  */
1116 static u32 nfsd4_get_drc_mem(struct nfsd4_channel_attrs *ca)
1117 {
1118         u32 slotsize = slot_bytes(ca);
1119         u32 num = ca->maxreqs;
1120         int avail;
1121
1122         spin_lock(&nfsd_drc_lock);
1123         avail = min((unsigned long)NFSD_MAX_MEM_PER_SESSION,
1124                     nfsd_drc_max_mem - nfsd_drc_mem_used);
1125         num = min_t(int, num, avail / slotsize);
1126         nfsd_drc_mem_used += num * slotsize;
1127         spin_unlock(&nfsd_drc_lock);
1128
1129         return num;
1130 }
1131
1132 static void nfsd4_put_drc_mem(struct nfsd4_channel_attrs *ca)
1133 {
1134         int slotsize = slot_bytes(ca);
1135
1136         spin_lock(&nfsd_drc_lock);
1137         nfsd_drc_mem_used -= slotsize * ca->maxreqs;
1138         spin_unlock(&nfsd_drc_lock);
1139 }
1140
1141 static struct nfsd4_session *alloc_session(struct nfsd4_channel_attrs *fattrs,
1142                                            struct nfsd4_channel_attrs *battrs)
1143 {
1144         int numslots = fattrs->maxreqs;
1145         int slotsize = slot_bytes(fattrs);
1146         struct nfsd4_session *new;
1147         int mem, i;
1148
1149         BUILD_BUG_ON(NFSD_MAX_SLOTS_PER_SESSION * sizeof(struct nfsd4_slot *)
1150                         + sizeof(struct nfsd4_session) > PAGE_SIZE);
1151         mem = numslots * sizeof(struct nfsd4_slot *);
1152
1153         new = kzalloc(sizeof(*new) + mem, GFP_KERNEL);
1154         if (!new)
1155                 return NULL;
1156         /* allocate each struct nfsd4_slot and data cache in one piece */
1157         for (i = 0; i < numslots; i++) {
1158                 new->se_slots[i] = kzalloc(slotsize, GFP_KERNEL);
1159                 if (!new->se_slots[i])
1160                         goto out_free;
1161         }
1162
1163         memcpy(&new->se_fchannel, fattrs, sizeof(struct nfsd4_channel_attrs));
1164         memcpy(&new->se_bchannel, battrs, sizeof(struct nfsd4_channel_attrs));
1165
1166         return new;
1167 out_free:
1168         while (i--)
1169                 kfree(new->se_slots[i]);
1170         kfree(new);
1171         return NULL;
1172 }
1173
1174 static void free_conn(struct nfsd4_conn *c)
1175 {
1176         svc_xprt_put(c->cn_xprt);
1177         kfree(c);
1178 }
1179
1180 static void nfsd4_conn_lost(struct svc_xpt_user *u)
1181 {
1182         struct nfsd4_conn *c = container_of(u, struct nfsd4_conn, cn_xpt_user);
1183         struct nfs4_client *clp = c->cn_session->se_client;
1184
1185         spin_lock(&clp->cl_lock);
1186         if (!list_empty(&c->cn_persession)) {
1187                 list_del(&c->cn_persession);
1188                 free_conn(c);
1189         }
1190         nfsd4_probe_callback(clp);
1191         spin_unlock(&clp->cl_lock);
1192 }
1193
1194 static struct nfsd4_conn *alloc_conn(struct svc_rqst *rqstp, u32 flags)
1195 {
1196         struct nfsd4_conn *conn;
1197
1198         conn = kmalloc(sizeof(struct nfsd4_conn), GFP_KERNEL);
1199         if (!conn)
1200                 return NULL;
1201         svc_xprt_get(rqstp->rq_xprt);
1202         conn->cn_xprt = rqstp->rq_xprt;
1203         conn->cn_flags = flags;
1204         INIT_LIST_HEAD(&conn->cn_xpt_user.list);
1205         return conn;
1206 }
1207
1208 static void __nfsd4_hash_conn(struct nfsd4_conn *conn, struct nfsd4_session *ses)
1209 {
1210         conn->cn_session = ses;
1211         list_add(&conn->cn_persession, &ses->se_conns);
1212 }
1213
1214 static void nfsd4_hash_conn(struct nfsd4_conn *conn, struct nfsd4_session *ses)
1215 {
1216         struct nfs4_client *clp = ses->se_client;
1217
1218         spin_lock(&clp->cl_lock);
1219         __nfsd4_hash_conn(conn, ses);
1220         spin_unlock(&clp->cl_lock);
1221 }
1222
1223 static int nfsd4_register_conn(struct nfsd4_conn *conn)
1224 {
1225         conn->cn_xpt_user.callback = nfsd4_conn_lost;
1226         return register_xpt_user(conn->cn_xprt, &conn->cn_xpt_user);
1227 }
1228
1229 static void nfsd4_init_conn(struct svc_rqst *rqstp, struct nfsd4_conn *conn, struct nfsd4_session *ses)
1230 {
1231         int ret;
1232
1233         nfsd4_hash_conn(conn, ses);
1234         ret = nfsd4_register_conn(conn);
1235         if (ret)
1236                 /* oops; xprt is already down: */
1237                 nfsd4_conn_lost(&conn->cn_xpt_user);
1238         /* We may have gained or lost a callback channel: */
1239         nfsd4_probe_callback_sync(ses->se_client);
1240 }
1241
1242 static struct nfsd4_conn *alloc_conn_from_crses(struct svc_rqst *rqstp, struct nfsd4_create_session *cses)
1243 {
1244         u32 dir = NFS4_CDFC4_FORE;
1245
1246         if (cses->flags & SESSION4_BACK_CHAN)
1247                 dir |= NFS4_CDFC4_BACK;
1248         return alloc_conn(rqstp, dir);
1249 }
1250
1251 /* must be called under client_lock */
1252 static void nfsd4_del_conns(struct nfsd4_session *s)
1253 {
1254         struct nfs4_client *clp = s->se_client;
1255         struct nfsd4_conn *c;
1256
1257         spin_lock(&clp->cl_lock);
1258         while (!list_empty(&s->se_conns)) {
1259                 c = list_first_entry(&s->se_conns, struct nfsd4_conn, cn_persession);
1260                 list_del_init(&c->cn_persession);
1261                 spin_unlock(&clp->cl_lock);
1262
1263                 unregister_xpt_user(c->cn_xprt, &c->cn_xpt_user);
1264                 free_conn(c);
1265
1266                 spin_lock(&clp->cl_lock);
1267         }
1268         spin_unlock(&clp->cl_lock);
1269 }
1270
1271 static void __free_session(struct nfsd4_session *ses)
1272 {
1273         free_session_slots(ses);
1274         kfree(ses);
1275 }
1276
1277 static void free_session(struct nfsd4_session *ses)
1278 {
1279         struct nfsd_net *nn = net_generic(ses->se_client->net, nfsd_net_id);
1280
1281         lockdep_assert_held(&nn->client_lock);
1282         nfsd4_del_conns(ses);
1283         nfsd4_put_drc_mem(&ses->se_fchannel);
1284         __free_session(ses);
1285 }
1286
1287 static void init_session(struct svc_rqst *rqstp, struct nfsd4_session *new, struct nfs4_client *clp, struct nfsd4_create_session *cses)
1288 {
1289         int idx;
1290         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
1291
1292         new->se_client = clp;
1293         gen_sessionid(new);
1294
1295         INIT_LIST_HEAD(&new->se_conns);
1296
1297         new->se_cb_seq_nr = 1;
1298         new->se_flags = cses->flags;
1299         new->se_cb_prog = cses->callback_prog;
1300         new->se_cb_sec = cses->cb_sec;
1301         atomic_set(&new->se_ref, 0);
1302         idx = hash_sessionid(&new->se_sessionid);
1303         spin_lock(&nn->client_lock);
1304         list_add(&new->se_hash, &nn->sessionid_hashtbl[idx]);
1305         spin_lock(&clp->cl_lock);
1306         list_add(&new->se_perclnt, &clp->cl_sessions);
1307         spin_unlock(&clp->cl_lock);
1308         spin_unlock(&nn->client_lock);
1309
1310         if (cses->flags & SESSION4_BACK_CHAN) {
1311                 struct sockaddr *sa = svc_addr(rqstp);
1312                 /*
1313                  * This is a little silly; with sessions there's no real
1314                  * use for the callback address.  Use the peer address
1315                  * as a reasonable default for now, but consider fixing
1316                  * the rpc client not to require an address in the
1317                  * future:
1318                  */
1319                 rpc_copy_addr((struct sockaddr *)&clp->cl_cb_conn.cb_addr, sa);
1320                 clp->cl_cb_conn.cb_addrlen = svc_addr_len(sa);
1321         }
1322 }
1323
1324 /* caller must hold client_lock */
1325 static struct nfsd4_session *
1326 __find_in_sessionid_hashtbl(struct nfs4_sessionid *sessionid, struct net *net)
1327 {
1328         struct nfsd4_session *elem;
1329         int idx;
1330         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
1331
1332         dump_sessionid(__func__, sessionid);
1333         idx = hash_sessionid(sessionid);
1334         /* Search in the appropriate list */
1335         list_for_each_entry(elem, &nn->sessionid_hashtbl[idx], se_hash) {
1336                 if (!memcmp(elem->se_sessionid.data, sessionid->data,
1337                             NFS4_MAX_SESSIONID_LEN)) {
1338                         return elem;
1339                 }
1340         }
1341
1342         dprintk("%s: session not found\n", __func__);
1343         return NULL;
1344 }
1345
1346 static struct nfsd4_session *
1347 find_in_sessionid_hashtbl(struct nfs4_sessionid *sessionid, struct net *net,
1348                 __be32 *ret)
1349 {
1350         struct nfsd4_session *session;
1351         __be32 status = nfserr_badsession;
1352
1353         session = __find_in_sessionid_hashtbl(sessionid, net);
1354         if (!session)
1355                 goto out;
1356         status = nfsd4_get_session_locked(session);
1357         if (status)
1358                 session = NULL;
1359 out:
1360         *ret = status;
1361         return session;
1362 }
1363
1364 /* caller must hold client_lock */
1365 static void
1366 unhash_session(struct nfsd4_session *ses)
1367 {
1368         list_del(&ses->se_hash);
1369         spin_lock(&ses->se_client->cl_lock);
1370         list_del(&ses->se_perclnt);
1371         spin_unlock(&ses->se_client->cl_lock);
1372 }
1373
1374 /* SETCLIENTID and SETCLIENTID_CONFIRM Helper functions */
1375 static int
1376 STALE_CLIENTID(clientid_t *clid, struct nfsd_net *nn)
1377 {
1378         if (clid->cl_boot == nn->boot_time)
1379                 return 0;
1380         dprintk("NFSD stale clientid (%08x/%08x) boot_time %08lx\n",
1381                 clid->cl_boot, clid->cl_id, nn->boot_time);
1382         return 1;
1383 }
1384
1385 /* 
1386  * XXX Should we use a slab cache ?
1387  * This type of memory management is somewhat inefficient, but we use it
1388  * anyway since SETCLIENTID is not a common operation.
1389  */
1390 static struct nfs4_client *alloc_client(struct xdr_netobj name)
1391 {
1392         struct nfs4_client *clp;
1393
1394         clp = kzalloc(sizeof(struct nfs4_client), GFP_KERNEL);
1395         if (clp == NULL)
1396                 return NULL;
1397         clp->cl_name.data = kmemdup(name.data, name.len, GFP_KERNEL);
1398         if (clp->cl_name.data == NULL) {
1399                 kfree(clp);
1400                 return NULL;
1401         }
1402         clp->cl_name.len = name.len;
1403         INIT_LIST_HEAD(&clp->cl_sessions);
1404         idr_init(&clp->cl_stateids);
1405         atomic_set(&clp->cl_refcount, 0);
1406         clp->cl_cb_state = NFSD4_CB_UNKNOWN;
1407         INIT_LIST_HEAD(&clp->cl_idhash);
1408         INIT_LIST_HEAD(&clp->cl_openowners);
1409         INIT_LIST_HEAD(&clp->cl_delegations);
1410         INIT_LIST_HEAD(&clp->cl_lru);
1411         INIT_LIST_HEAD(&clp->cl_callbacks);
1412         INIT_LIST_HEAD(&clp->cl_revoked);
1413         spin_lock_init(&clp->cl_lock);
1414         rpc_init_wait_queue(&clp->cl_cb_waitq, "Backchannel slot table");
1415         return clp;
1416 }
1417
1418 static void
1419 free_client(struct nfs4_client *clp)
1420 {
1421         struct nfsd_net __maybe_unused *nn = net_generic(clp->net, nfsd_net_id);
1422
1423         lockdep_assert_held(&nn->client_lock);
1424         while (!list_empty(&clp->cl_sessions)) {
1425                 struct nfsd4_session *ses;
1426                 ses = list_entry(clp->cl_sessions.next, struct nfsd4_session,
1427                                 se_perclnt);
1428                 list_del(&ses->se_perclnt);
1429                 WARN_ON_ONCE(atomic_read(&ses->se_ref));
1430                 free_session(ses);
1431         }
1432         rpc_destroy_wait_queue(&clp->cl_cb_waitq);
1433         free_svc_cred(&clp->cl_cred);
1434         kfree(clp->cl_name.data);
1435         idr_destroy(&clp->cl_stateids);
1436         kfree(clp);
1437 }
1438
1439 /* must be called under the client_lock */
1440 static inline void
1441 unhash_client_locked(struct nfs4_client *clp)
1442 {
1443         struct nfsd4_session *ses;
1444
1445         list_del(&clp->cl_lru);
1446         spin_lock(&clp->cl_lock);
1447         list_for_each_entry(ses, &clp->cl_sessions, se_perclnt)
1448                 list_del_init(&ses->se_hash);
1449         spin_unlock(&clp->cl_lock);
1450 }
1451
1452 static void
1453 destroy_client(struct nfs4_client *clp)
1454 {
1455         struct nfs4_openowner *oo;
1456         struct nfs4_delegation *dp;
1457         struct list_head reaplist;
1458         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
1459
1460         INIT_LIST_HEAD(&reaplist);
1461         spin_lock(&state_lock);
1462         while (!list_empty(&clp->cl_delegations)) {
1463                 dp = list_entry(clp->cl_delegations.next, struct nfs4_delegation, dl_perclnt);
1464                 unhash_delegation_locked(dp);
1465                 list_add(&dp->dl_recall_lru, &reaplist);
1466         }
1467         spin_unlock(&state_lock);
1468         while (!list_empty(&reaplist)) {
1469                 dp = list_entry(reaplist.next, struct nfs4_delegation, dl_recall_lru);
1470                 list_del_init(&dp->dl_recall_lru);
1471                 nfs4_put_stid(&dp->dl_stid);
1472         }
1473         while (!list_empty(&clp->cl_revoked)) {
1474                 dp = list_entry(reaplist.next, struct nfs4_delegation, dl_recall_lru);
1475                 list_del_init(&dp->dl_recall_lru);
1476                 nfs4_put_stid(&dp->dl_stid);
1477         }
1478         while (!list_empty(&clp->cl_openowners)) {
1479                 oo = list_entry(clp->cl_openowners.next, struct nfs4_openowner, oo_perclient);
1480                 release_openowner(oo);
1481         }
1482         nfsd4_shutdown_callback(clp);
1483         if (clp->cl_cb_conn.cb_xprt)
1484                 svc_xprt_put(clp->cl_cb_conn.cb_xprt);
1485         list_del(&clp->cl_idhash);
1486         if (test_bit(NFSD4_CLIENT_CONFIRMED, &clp->cl_flags))
1487                 rb_erase(&clp->cl_namenode, &nn->conf_name_tree);
1488         else
1489                 rb_erase(&clp->cl_namenode, &nn->unconf_name_tree);
1490         spin_lock(&nn->client_lock);
1491         unhash_client_locked(clp);
1492         WARN_ON_ONCE(atomic_read(&clp->cl_refcount));
1493         free_client(clp);
1494         spin_unlock(&nn->client_lock);
1495 }
1496
1497 static void expire_client(struct nfs4_client *clp)
1498 {
1499         nfsd4_client_record_remove(clp);
1500         destroy_client(clp);
1501 }
1502
1503 static void copy_verf(struct nfs4_client *target, nfs4_verifier *source)
1504 {
1505         memcpy(target->cl_verifier.data, source->data,
1506                         sizeof(target->cl_verifier.data));
1507 }
1508
1509 static void copy_clid(struct nfs4_client *target, struct nfs4_client *source)
1510 {
1511         target->cl_clientid.cl_boot = source->cl_clientid.cl_boot; 
1512         target->cl_clientid.cl_id = source->cl_clientid.cl_id; 
1513 }
1514
1515 static int copy_cred(struct svc_cred *target, struct svc_cred *source)
1516 {
1517         if (source->cr_principal) {
1518                 target->cr_principal =
1519                                 kstrdup(source->cr_principal, GFP_KERNEL);
1520                 if (target->cr_principal == NULL)
1521                         return -ENOMEM;
1522         } else
1523                 target->cr_principal = NULL;
1524         target->cr_flavor = source->cr_flavor;
1525         target->cr_uid = source->cr_uid;
1526         target->cr_gid = source->cr_gid;
1527         target->cr_group_info = source->cr_group_info;
1528         get_group_info(target->cr_group_info);
1529         target->cr_gss_mech = source->cr_gss_mech;
1530         if (source->cr_gss_mech)
1531                 gss_mech_get(source->cr_gss_mech);
1532         return 0;
1533 }
1534
1535 static long long
1536 compare_blob(const struct xdr_netobj *o1, const struct xdr_netobj *o2)
1537 {
1538         long long res;
1539
1540         res = o1->len - o2->len;
1541         if (res)
1542                 return res;
1543         return (long long)memcmp(o1->data, o2->data, o1->len);
1544 }
1545
1546 static int same_name(const char *n1, const char *n2)
1547 {
1548         return 0 == memcmp(n1, n2, HEXDIR_LEN);
1549 }
1550
1551 static int
1552 same_verf(nfs4_verifier *v1, nfs4_verifier *v2)
1553 {
1554         return 0 == memcmp(v1->data, v2->data, sizeof(v1->data));
1555 }
1556
1557 static int
1558 same_clid(clientid_t *cl1, clientid_t *cl2)
1559 {
1560         return (cl1->cl_boot == cl2->cl_boot) && (cl1->cl_id == cl2->cl_id);
1561 }
1562
1563 static bool groups_equal(struct group_info *g1, struct group_info *g2)
1564 {
1565         int i;
1566
1567         if (g1->ngroups != g2->ngroups)
1568                 return false;
1569         for (i=0; i<g1->ngroups; i++)
1570                 if (!gid_eq(GROUP_AT(g1, i), GROUP_AT(g2, i)))
1571                         return false;
1572         return true;
1573 }
1574
1575 /*
1576  * RFC 3530 language requires clid_inuse be returned when the
1577  * "principal" associated with a requests differs from that previously
1578  * used.  We use uid, gid's, and gss principal string as our best
1579  * approximation.  We also don't want to allow non-gss use of a client
1580  * established using gss: in theory cr_principal should catch that
1581  * change, but in practice cr_principal can be null even in the gss case
1582  * since gssd doesn't always pass down a principal string.
1583  */
1584 static bool is_gss_cred(struct svc_cred *cr)
1585 {
1586         /* Is cr_flavor one of the gss "pseudoflavors"?: */
1587         return (cr->cr_flavor > RPC_AUTH_MAXFLAVOR);
1588 }
1589
1590
1591 static bool
1592 same_creds(struct svc_cred *cr1, struct svc_cred *cr2)
1593 {
1594         if ((is_gss_cred(cr1) != is_gss_cred(cr2))
1595                 || (!uid_eq(cr1->cr_uid, cr2->cr_uid))
1596                 || (!gid_eq(cr1->cr_gid, cr2->cr_gid))
1597                 || !groups_equal(cr1->cr_group_info, cr2->cr_group_info))
1598                 return false;
1599         if (cr1->cr_principal == cr2->cr_principal)
1600                 return true;
1601         if (!cr1->cr_principal || !cr2->cr_principal)
1602                 return false;
1603         return 0 == strcmp(cr1->cr_principal, cr2->cr_principal);
1604 }
1605
1606 static bool svc_rqst_integrity_protected(struct svc_rqst *rqstp)
1607 {
1608         struct svc_cred *cr = &rqstp->rq_cred;
1609         u32 service;
1610
1611         if (!cr->cr_gss_mech)
1612                 return false;
1613         service = gss_pseudoflavor_to_service(cr->cr_gss_mech, cr->cr_flavor);
1614         return service == RPC_GSS_SVC_INTEGRITY ||
1615                service == RPC_GSS_SVC_PRIVACY;
1616 }
1617
1618 static bool mach_creds_match(struct nfs4_client *cl, struct svc_rqst *rqstp)
1619 {
1620         struct svc_cred *cr = &rqstp->rq_cred;
1621
1622         if (!cl->cl_mach_cred)
1623                 return true;
1624         if (cl->cl_cred.cr_gss_mech != cr->cr_gss_mech)
1625                 return false;
1626         if (!svc_rqst_integrity_protected(rqstp))
1627                 return false;
1628         if (!cr->cr_principal)
1629                 return false;
1630         return 0 == strcmp(cl->cl_cred.cr_principal, cr->cr_principal);
1631 }
1632
1633 static void gen_clid(struct nfs4_client *clp, struct nfsd_net *nn)
1634 {
1635         static u32 current_clientid = 1;
1636
1637         clp->cl_clientid.cl_boot = nn->boot_time;
1638         clp->cl_clientid.cl_id = current_clientid++; 
1639 }
1640
1641 static void gen_confirm(struct nfs4_client *clp)
1642 {
1643         __be32 verf[2];
1644         static u32 i;
1645
1646         /*
1647          * This is opaque to client, so no need to byte-swap. Use
1648          * __force to keep sparse happy
1649          */
1650         verf[0] = (__force __be32)get_seconds();
1651         verf[1] = (__force __be32)i++;
1652         memcpy(clp->cl_confirm.data, verf, sizeof(clp->cl_confirm.data));
1653 }
1654
1655 static struct nfs4_stid *find_stateid(struct nfs4_client *cl, stateid_t *t)
1656 {
1657         struct nfs4_stid *ret;
1658
1659         ret = idr_find(&cl->cl_stateids, t->si_opaque.so_id);
1660         if (!ret || !ret->sc_type)
1661                 return NULL;
1662         return ret;
1663 }
1664
1665 static struct nfs4_stid *find_stateid_by_type(struct nfs4_client *cl, stateid_t *t, char typemask)
1666 {
1667         struct nfs4_stid *s;
1668
1669         s = find_stateid(cl, t);
1670         if (!s)
1671                 return NULL;
1672         if (typemask & s->sc_type)
1673                 return s;
1674         return NULL;
1675 }
1676
1677 static struct nfs4_client *create_client(struct xdr_netobj name,
1678                 struct svc_rqst *rqstp, nfs4_verifier *verf)
1679 {
1680         struct nfs4_client *clp;
1681         struct sockaddr *sa = svc_addr(rqstp);
1682         int ret;
1683         struct net *net = SVC_NET(rqstp);
1684         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
1685
1686         clp = alloc_client(name);
1687         if (clp == NULL)
1688                 return NULL;
1689
1690         ret = copy_cred(&clp->cl_cred, &rqstp->rq_cred);
1691         if (ret) {
1692                 spin_lock(&nn->client_lock);
1693                 free_client(clp);
1694                 spin_unlock(&nn->client_lock);
1695                 return NULL;
1696         }
1697         INIT_WORK(&clp->cl_cb_null.cb_work, nfsd4_run_cb_null);
1698         clp->cl_time = get_seconds();
1699         clear_bit(0, &clp->cl_cb_slot_busy);
1700         copy_verf(clp, verf);
1701         rpc_copy_addr((struct sockaddr *) &clp->cl_addr, sa);
1702         gen_confirm(clp);
1703         clp->cl_cb_session = NULL;
1704         clp->net = net;
1705         return clp;
1706 }
1707
1708 static void
1709 add_clp_to_name_tree(struct nfs4_client *new_clp, struct rb_root *root)
1710 {
1711         struct rb_node **new = &(root->rb_node), *parent = NULL;
1712         struct nfs4_client *clp;
1713
1714         while (*new) {
1715                 clp = rb_entry(*new, struct nfs4_client, cl_namenode);
1716                 parent = *new;
1717
1718                 if (compare_blob(&clp->cl_name, &new_clp->cl_name) > 0)
1719                         new = &((*new)->rb_left);
1720                 else
1721                         new = &((*new)->rb_right);
1722         }
1723
1724         rb_link_node(&new_clp->cl_namenode, parent, new);
1725         rb_insert_color(&new_clp->cl_namenode, root);
1726 }
1727
1728 static struct nfs4_client *
1729 find_clp_in_name_tree(struct xdr_netobj *name, struct rb_root *root)
1730 {
1731         long long cmp;
1732         struct rb_node *node = root->rb_node;
1733         struct nfs4_client *clp;
1734
1735         while (node) {
1736                 clp = rb_entry(node, struct nfs4_client, cl_namenode);
1737                 cmp = compare_blob(&clp->cl_name, name);
1738                 if (cmp > 0)
1739                         node = node->rb_left;
1740                 else if (cmp < 0)
1741                         node = node->rb_right;
1742                 else
1743                         return clp;
1744         }
1745         return NULL;
1746 }
1747
1748 static void
1749 add_to_unconfirmed(struct nfs4_client *clp)
1750 {
1751         unsigned int idhashval;
1752         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
1753
1754         clear_bit(NFSD4_CLIENT_CONFIRMED, &clp->cl_flags);
1755         add_clp_to_name_tree(clp, &nn->unconf_name_tree);
1756         idhashval = clientid_hashval(clp->cl_clientid.cl_id);
1757         list_add(&clp->cl_idhash, &nn->unconf_id_hashtbl[idhashval]);
1758         renew_client(clp);
1759 }
1760
1761 static void
1762 move_to_confirmed(struct nfs4_client *clp)
1763 {
1764         unsigned int idhashval = clientid_hashval(clp->cl_clientid.cl_id);
1765         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
1766
1767         dprintk("NFSD: move_to_confirm nfs4_client %p\n", clp);
1768         list_move(&clp->cl_idhash, &nn->conf_id_hashtbl[idhashval]);
1769         rb_erase(&clp->cl_namenode, &nn->unconf_name_tree);
1770         add_clp_to_name_tree(clp, &nn->conf_name_tree);
1771         set_bit(NFSD4_CLIENT_CONFIRMED, &clp->cl_flags);
1772         renew_client(clp);
1773 }
1774
1775 static struct nfs4_client *
1776 find_client_in_id_table(struct list_head *tbl, clientid_t *clid, bool sessions)
1777 {
1778         struct nfs4_client *clp;
1779         unsigned int idhashval = clientid_hashval(clid->cl_id);
1780
1781         list_for_each_entry(clp, &tbl[idhashval], cl_idhash) {
1782                 if (same_clid(&clp->cl_clientid, clid)) {
1783                         if ((bool)clp->cl_minorversion != sessions)
1784                                 return NULL;
1785                         renew_client(clp);
1786                         return clp;
1787                 }
1788         }
1789         return NULL;
1790 }
1791
1792 static struct nfs4_client *
1793 find_confirmed_client(clientid_t *clid, bool sessions, struct nfsd_net *nn)
1794 {
1795         struct list_head *tbl = nn->conf_id_hashtbl;
1796
1797         return find_client_in_id_table(tbl, clid, sessions);
1798 }
1799
1800 static struct nfs4_client *
1801 find_unconfirmed_client(clientid_t *clid, bool sessions, struct nfsd_net *nn)
1802 {
1803         struct list_head *tbl = nn->unconf_id_hashtbl;
1804
1805         return find_client_in_id_table(tbl, clid, sessions);
1806 }
1807
1808 static bool clp_used_exchangeid(struct nfs4_client *clp)
1809 {
1810         return clp->cl_exchange_flags != 0;
1811
1812
1813 static struct nfs4_client *
1814 find_confirmed_client_by_name(struct xdr_netobj *name, struct nfsd_net *nn)
1815 {
1816         return find_clp_in_name_tree(name, &nn->conf_name_tree);
1817 }
1818
1819 static struct nfs4_client *
1820 find_unconfirmed_client_by_name(struct xdr_netobj *name, struct nfsd_net *nn)
1821 {
1822         return find_clp_in_name_tree(name, &nn->unconf_name_tree);
1823 }
1824
1825 static void
1826 gen_callback(struct nfs4_client *clp, struct nfsd4_setclientid *se, struct svc_rqst *rqstp)
1827 {
1828         struct nfs4_cb_conn *conn = &clp->cl_cb_conn;
1829         struct sockaddr *sa = svc_addr(rqstp);
1830         u32 scopeid = rpc_get_scope_id(sa);
1831         unsigned short expected_family;
1832
1833         /* Currently, we only support tcp and tcp6 for the callback channel */
1834         if (se->se_callback_netid_len == 3 &&
1835             !memcmp(se->se_callback_netid_val, "tcp", 3))
1836                 expected_family = AF_INET;
1837         else if (se->se_callback_netid_len == 4 &&
1838                  !memcmp(se->se_callback_netid_val, "tcp6", 4))
1839                 expected_family = AF_INET6;
1840         else
1841                 goto out_err;
1842
1843         conn->cb_addrlen = rpc_uaddr2sockaddr(clp->net, se->se_callback_addr_val,
1844                                             se->se_callback_addr_len,
1845                                             (struct sockaddr *)&conn->cb_addr,
1846                                             sizeof(conn->cb_addr));
1847
1848         if (!conn->cb_addrlen || conn->cb_addr.ss_family != expected_family)
1849                 goto out_err;
1850
1851         if (conn->cb_addr.ss_family == AF_INET6)
1852                 ((struct sockaddr_in6 *)&conn->cb_addr)->sin6_scope_id = scopeid;
1853
1854         conn->cb_prog = se->se_callback_prog;
1855         conn->cb_ident = se->se_callback_ident;
1856         memcpy(&conn->cb_saddr, &rqstp->rq_daddr, rqstp->rq_daddrlen);
1857         return;
1858 out_err:
1859         conn->cb_addr.ss_family = AF_UNSPEC;
1860         conn->cb_addrlen = 0;
1861         dprintk(KERN_INFO "NFSD: this client (clientid %08x/%08x) "
1862                 "will not receive delegations\n",
1863                 clp->cl_clientid.cl_boot, clp->cl_clientid.cl_id);
1864
1865         return;
1866 }
1867
1868 /*
1869  * Cache a reply. nfsd4_check_resp_size() has bounded the cache size.
1870  */
1871 static void
1872 nfsd4_store_cache_entry(struct nfsd4_compoundres *resp)
1873 {
1874         struct xdr_buf *buf = resp->xdr.buf;
1875         struct nfsd4_slot *slot = resp->cstate.slot;
1876         unsigned int base;
1877
1878         dprintk("--> %s slot %p\n", __func__, slot);
1879
1880         slot->sl_opcnt = resp->opcnt;
1881         slot->sl_status = resp->cstate.status;
1882
1883         slot->sl_flags |= NFSD4_SLOT_INITIALIZED;
1884         if (nfsd4_not_cached(resp)) {
1885                 slot->sl_datalen = 0;
1886                 return;
1887         }
1888         base = resp->cstate.data_offset;
1889         slot->sl_datalen = buf->len - base;
1890         if (read_bytes_from_xdr_buf(buf, base, slot->sl_data, slot->sl_datalen))
1891                 WARN("%s: sessions DRC could not cache compound\n", __func__);
1892         return;
1893 }
1894
1895 /*
1896  * Encode the replay sequence operation from the slot values.
1897  * If cachethis is FALSE encode the uncached rep error on the next
1898  * operation which sets resp->p and increments resp->opcnt for
1899  * nfs4svc_encode_compoundres.
1900  *
1901  */
1902 static __be32
1903 nfsd4_enc_sequence_replay(struct nfsd4_compoundargs *args,
1904                           struct nfsd4_compoundres *resp)
1905 {
1906         struct nfsd4_op *op;
1907         struct nfsd4_slot *slot = resp->cstate.slot;
1908
1909         /* Encode the replayed sequence operation */
1910         op = &args->ops[resp->opcnt - 1];
1911         nfsd4_encode_operation(resp, op);
1912
1913         /* Return nfserr_retry_uncached_rep in next operation. */
1914         if (args->opcnt > 1 && !(slot->sl_flags & NFSD4_SLOT_CACHETHIS)) {
1915                 op = &args->ops[resp->opcnt++];
1916                 op->status = nfserr_retry_uncached_rep;
1917                 nfsd4_encode_operation(resp, op);
1918         }
1919         return op->status;
1920 }
1921
1922 /*
1923  * The sequence operation is not cached because we can use the slot and
1924  * session values.
1925  */
1926 static __be32
1927 nfsd4_replay_cache_entry(struct nfsd4_compoundres *resp,
1928                          struct nfsd4_sequence *seq)
1929 {
1930         struct nfsd4_slot *slot = resp->cstate.slot;
1931         struct xdr_stream *xdr = &resp->xdr;
1932         __be32 *p;
1933         __be32 status;
1934
1935         dprintk("--> %s slot %p\n", __func__, slot);
1936
1937         status = nfsd4_enc_sequence_replay(resp->rqstp->rq_argp, resp);
1938         if (status)
1939                 return status;
1940
1941         p = xdr_reserve_space(xdr, slot->sl_datalen);
1942         if (!p) {
1943                 WARN_ON_ONCE(1);
1944                 return nfserr_serverfault;
1945         }
1946         xdr_encode_opaque_fixed(p, slot->sl_data, slot->sl_datalen);
1947         xdr_commit_encode(xdr);
1948
1949         resp->opcnt = slot->sl_opcnt;
1950         return slot->sl_status;
1951 }
1952
1953 /*
1954  * Set the exchange_id flags returned by the server.
1955  */
1956 static void
1957 nfsd4_set_ex_flags(struct nfs4_client *new, struct nfsd4_exchange_id *clid)
1958 {
1959         /* pNFS is not supported */
1960         new->cl_exchange_flags |= EXCHGID4_FLAG_USE_NON_PNFS;
1961
1962         /* Referrals are supported, Migration is not. */
1963         new->cl_exchange_flags |= EXCHGID4_FLAG_SUPP_MOVED_REFER;
1964
1965         /* set the wire flags to return to client. */
1966         clid->flags = new->cl_exchange_flags;
1967 }
1968
1969 static bool client_has_state(struct nfs4_client *clp)
1970 {
1971         /*
1972          * Note clp->cl_openowners check isn't quite right: there's no
1973          * need to count owners without stateid's.
1974          *
1975          * Also note we should probably be using this in 4.0 case too.
1976          */
1977         return !list_empty(&clp->cl_openowners)
1978                 || !list_empty(&clp->cl_delegations)
1979                 || !list_empty(&clp->cl_sessions);
1980 }
1981
1982 __be32
1983 nfsd4_exchange_id(struct svc_rqst *rqstp,
1984                   struct nfsd4_compound_state *cstate,
1985                   struct nfsd4_exchange_id *exid)
1986 {
1987         struct nfs4_client *unconf, *conf, *new;
1988         __be32 status;
1989         char                    addr_str[INET6_ADDRSTRLEN];
1990         nfs4_verifier           verf = exid->verifier;
1991         struct sockaddr         *sa = svc_addr(rqstp);
1992         bool    update = exid->flags & EXCHGID4_FLAG_UPD_CONFIRMED_REC_A;
1993         struct nfsd_net         *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
1994
1995         rpc_ntop(sa, addr_str, sizeof(addr_str));
1996         dprintk("%s rqstp=%p exid=%p clname.len=%u clname.data=%p "
1997                 "ip_addr=%s flags %x, spa_how %d\n",
1998                 __func__, rqstp, exid, exid->clname.len, exid->clname.data,
1999                 addr_str, exid->flags, exid->spa_how);
2000
2001         if (exid->flags & ~EXCHGID4_FLAG_MASK_A)
2002                 return nfserr_inval;
2003
2004         switch (exid->spa_how) {
2005         case SP4_MACH_CRED:
2006                 if (!svc_rqst_integrity_protected(rqstp))
2007                         return nfserr_inval;
2008         case SP4_NONE:
2009                 break;
2010         default:                                /* checked by xdr code */
2011                 WARN_ON_ONCE(1);
2012         case SP4_SSV:
2013                 return nfserr_encr_alg_unsupp;
2014         }
2015
2016         /* Cases below refer to rfc 5661 section 18.35.4: */
2017         nfs4_lock_state();
2018         conf = find_confirmed_client_by_name(&exid->clname, nn);
2019         if (conf) {
2020                 bool creds_match = same_creds(&conf->cl_cred, &rqstp->rq_cred);
2021                 bool verfs_match = same_verf(&verf, &conf->cl_verifier);
2022
2023                 if (update) {
2024                         if (!clp_used_exchangeid(conf)) { /* buggy client */
2025                                 status = nfserr_inval;
2026                                 goto out;
2027                         }
2028                         if (!mach_creds_match(conf, rqstp)) {
2029                                 status = nfserr_wrong_cred;
2030                                 goto out;
2031                         }
2032                         if (!creds_match) { /* case 9 */
2033                                 status = nfserr_perm;
2034                                 goto out;
2035                         }
2036                         if (!verfs_match) { /* case 8 */
2037                                 status = nfserr_not_same;
2038                                 goto out;
2039                         }
2040                         /* case 6 */
2041                         exid->flags |= EXCHGID4_FLAG_CONFIRMED_R;
2042                         new = conf;
2043                         goto out_copy;
2044                 }
2045                 if (!creds_match) { /* case 3 */
2046                         if (client_has_state(conf)) {
2047                                 status = nfserr_clid_inuse;
2048                                 goto out;
2049                         }
2050                         expire_client(conf);
2051                         goto out_new;
2052                 }
2053                 if (verfs_match) { /* case 2 */
2054                         conf->cl_exchange_flags |= EXCHGID4_FLAG_CONFIRMED_R;
2055                         new = conf;
2056                         goto out_copy;
2057                 }
2058                 /* case 5, client reboot */
2059                 goto out_new;
2060         }
2061
2062         if (update) { /* case 7 */
2063                 status = nfserr_noent;
2064                 goto out;
2065         }
2066
2067         unconf  = find_unconfirmed_client_by_name(&exid->clname, nn);
2068         if (unconf) /* case 4, possible retry or client restart */
2069                 expire_client(unconf);
2070
2071         /* case 1 (normal case) */
2072 out_new:
2073         new = create_client(exid->clname, rqstp, &verf);
2074         if (new == NULL) {
2075                 status = nfserr_jukebox;
2076                 goto out;
2077         }
2078         new->cl_minorversion = cstate->minorversion;
2079         new->cl_mach_cred = (exid->spa_how == SP4_MACH_CRED);
2080
2081         gen_clid(new, nn);
2082         add_to_unconfirmed(new);
2083 out_copy:
2084         exid->clientid.cl_boot = new->cl_clientid.cl_boot;
2085         exid->clientid.cl_id = new->cl_clientid.cl_id;
2086
2087         exid->seqid = new->cl_cs_slot.sl_seqid + 1;
2088         nfsd4_set_ex_flags(new, exid);
2089
2090         dprintk("nfsd4_exchange_id seqid %d flags %x\n",
2091                 new->cl_cs_slot.sl_seqid, new->cl_exchange_flags);
2092         status = nfs_ok;
2093
2094 out:
2095         nfs4_unlock_state();
2096         return status;
2097 }
2098
2099 static __be32
2100 check_slot_seqid(u32 seqid, u32 slot_seqid, int slot_inuse)
2101 {
2102         dprintk("%s enter. seqid %d slot_seqid %d\n", __func__, seqid,
2103                 slot_seqid);
2104
2105         /* The slot is in use, and no response has been sent. */
2106         if (slot_inuse) {
2107                 if (seqid == slot_seqid)
2108                         return nfserr_jukebox;
2109                 else
2110                         return nfserr_seq_misordered;
2111         }
2112         /* Note unsigned 32-bit arithmetic handles wraparound: */
2113         if (likely(seqid == slot_seqid + 1))
2114                 return nfs_ok;
2115         if (seqid == slot_seqid)
2116                 return nfserr_replay_cache;
2117         return nfserr_seq_misordered;
2118 }
2119
2120 /*
2121  * Cache the create session result into the create session single DRC
2122  * slot cache by saving the xdr structure. sl_seqid has been set.
2123  * Do this for solo or embedded create session operations.
2124  */
2125 static void
2126 nfsd4_cache_create_session(struct nfsd4_create_session *cr_ses,
2127                            struct nfsd4_clid_slot *slot, __be32 nfserr)
2128 {
2129         slot->sl_status = nfserr;
2130         memcpy(&slot->sl_cr_ses, cr_ses, sizeof(*cr_ses));
2131 }
2132
2133 static __be32
2134 nfsd4_replay_create_session(struct nfsd4_create_session *cr_ses,
2135                             struct nfsd4_clid_slot *slot)
2136 {
2137         memcpy(cr_ses, &slot->sl_cr_ses, sizeof(*cr_ses));
2138         return slot->sl_status;
2139 }
2140
2141 #define NFSD_MIN_REQ_HDR_SEQ_SZ ((\
2142                         2 * 2 + /* credential,verifier: AUTH_NULL, length 0 */ \
2143                         1 +     /* MIN tag is length with zero, only length */ \
2144                         3 +     /* version, opcount, opcode */ \
2145                         XDR_QUADLEN(NFS4_MAX_SESSIONID_LEN) + \
2146                                 /* seqid, slotID, slotID, cache */ \
2147                         4 ) * sizeof(__be32))
2148
2149 #define NFSD_MIN_RESP_HDR_SEQ_SZ ((\
2150                         2 +     /* verifier: AUTH_NULL, length 0 */\
2151                         1 +     /* status */ \
2152                         1 +     /* MIN tag is length with zero, only length */ \
2153                         3 +     /* opcount, opcode, opstatus*/ \
2154                         XDR_QUADLEN(NFS4_MAX_SESSIONID_LEN) + \
2155                                 /* seqid, slotID, slotID, slotID, status */ \
2156                         5 ) * sizeof(__be32))
2157
2158 static __be32 check_forechannel_attrs(struct nfsd4_channel_attrs *ca, struct nfsd_net *nn)
2159 {
2160         u32 maxrpc = nn->nfsd_serv->sv_max_mesg;
2161
2162         if (ca->maxreq_sz < NFSD_MIN_REQ_HDR_SEQ_SZ)
2163                 return nfserr_toosmall;
2164         if (ca->maxresp_sz < NFSD_MIN_RESP_HDR_SEQ_SZ)
2165                 return nfserr_toosmall;
2166         ca->headerpadsz = 0;
2167         ca->maxreq_sz = min_t(u32, ca->maxreq_sz, maxrpc);
2168         ca->maxresp_sz = min_t(u32, ca->maxresp_sz, maxrpc);
2169         ca->maxops = min_t(u32, ca->maxops, NFSD_MAX_OPS_PER_COMPOUND);
2170         ca->maxresp_cached = min_t(u32, ca->maxresp_cached,
2171                         NFSD_SLOT_CACHE_SIZE + NFSD_MIN_HDR_SEQ_SZ);
2172         ca->maxreqs = min_t(u32, ca->maxreqs, NFSD_MAX_SLOTS_PER_SESSION);
2173         /*
2174          * Note decreasing slot size below client's request may make it
2175          * difficult for client to function correctly, whereas
2176          * decreasing the number of slots will (just?) affect
2177          * performance.  When short on memory we therefore prefer to
2178          * decrease number of slots instead of their size.  Clients that
2179          * request larger slots than they need will get poor results:
2180          */
2181         ca->maxreqs = nfsd4_get_drc_mem(ca);
2182         if (!ca->maxreqs)
2183                 return nfserr_jukebox;
2184
2185         return nfs_ok;
2186 }
2187
2188 #define NFSD_CB_MAX_REQ_SZ      ((NFS4_enc_cb_recall_sz + \
2189                                  RPC_MAX_HEADER_WITH_AUTH) * sizeof(__be32))
2190 #define NFSD_CB_MAX_RESP_SZ     ((NFS4_dec_cb_recall_sz + \
2191                                  RPC_MAX_REPHEADER_WITH_AUTH) * sizeof(__be32))
2192
2193 static __be32 check_backchannel_attrs(struct nfsd4_channel_attrs *ca)
2194 {
2195         ca->headerpadsz = 0;
2196
2197         /*
2198          * These RPC_MAX_HEADER macros are overkill, especially since we
2199          * don't even do gss on the backchannel yet.  But this is still
2200          * less than 1k.  Tighten up this estimate in the unlikely event
2201          * it turns out to be a problem for some client:
2202          */
2203         if (ca->maxreq_sz < NFSD_CB_MAX_REQ_SZ)
2204                 return nfserr_toosmall;
2205         if (ca->maxresp_sz < NFSD_CB_MAX_RESP_SZ)
2206                 return nfserr_toosmall;
2207         ca->maxresp_cached = 0;
2208         if (ca->maxops < 2)
2209                 return nfserr_toosmall;
2210
2211         return nfs_ok;
2212 }
2213
2214 static __be32 nfsd4_check_cb_sec(struct nfsd4_cb_sec *cbs)
2215 {
2216         switch (cbs->flavor) {
2217         case RPC_AUTH_NULL:
2218         case RPC_AUTH_UNIX:
2219                 return nfs_ok;
2220         default:
2221                 /*
2222                  * GSS case: the spec doesn't allow us to return this
2223                  * error.  But it also doesn't allow us not to support
2224                  * GSS.
2225                  * I'd rather this fail hard than return some error the
2226                  * client might think it can already handle:
2227                  */
2228                 return nfserr_encr_alg_unsupp;
2229         }
2230 }
2231
2232 __be32
2233 nfsd4_create_session(struct svc_rqst *rqstp,
2234                      struct nfsd4_compound_state *cstate,
2235                      struct nfsd4_create_session *cr_ses)
2236 {
2237         struct sockaddr *sa = svc_addr(rqstp);
2238         struct nfs4_client *conf, *unconf;
2239         struct nfsd4_session *new;
2240         struct nfsd4_conn *conn;
2241         struct nfsd4_clid_slot *cs_slot = NULL;
2242         __be32 status = 0;
2243         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
2244
2245         if (cr_ses->flags & ~SESSION4_FLAG_MASK_A)
2246                 return nfserr_inval;
2247         status = nfsd4_check_cb_sec(&cr_ses->cb_sec);
2248         if (status)
2249                 return status;
2250         status = check_forechannel_attrs(&cr_ses->fore_channel, nn);
2251         if (status)
2252                 return status;
2253         status = check_backchannel_attrs(&cr_ses->back_channel);
2254         if (status)
2255                 goto out_release_drc_mem;
2256         status = nfserr_jukebox;
2257         new = alloc_session(&cr_ses->fore_channel, &cr_ses->back_channel);
2258         if (!new)
2259                 goto out_release_drc_mem;
2260         conn = alloc_conn_from_crses(rqstp, cr_ses);
2261         if (!conn)
2262                 goto out_free_session;
2263
2264         nfs4_lock_state();
2265         unconf = find_unconfirmed_client(&cr_ses->clientid, true, nn);
2266         conf = find_confirmed_client(&cr_ses->clientid, true, nn);
2267         WARN_ON_ONCE(conf && unconf);
2268
2269         if (conf) {
2270                 status = nfserr_wrong_cred;
2271                 if (!mach_creds_match(conf, rqstp))
2272                         goto out_free_conn;
2273                 cs_slot = &conf->cl_cs_slot;
2274                 status = check_slot_seqid(cr_ses->seqid, cs_slot->sl_seqid, 0);
2275                 if (status == nfserr_replay_cache) {
2276                         status = nfsd4_replay_create_session(cr_ses, cs_slot);
2277                         goto out_free_conn;
2278                 } else if (cr_ses->seqid != cs_slot->sl_seqid + 1) {
2279                         status = nfserr_seq_misordered;
2280                         goto out_free_conn;
2281                 }
2282         } else if (unconf) {
2283                 struct nfs4_client *old;
2284                 if (!same_creds(&unconf->cl_cred, &rqstp->rq_cred) ||
2285                     !rpc_cmp_addr(sa, (struct sockaddr *) &unconf->cl_addr)) {
2286                         status = nfserr_clid_inuse;
2287                         goto out_free_conn;
2288                 }
2289                 status = nfserr_wrong_cred;
2290                 if (!mach_creds_match(unconf, rqstp))
2291                         goto out_free_conn;
2292                 cs_slot = &unconf->cl_cs_slot;
2293                 status = check_slot_seqid(cr_ses->seqid, cs_slot->sl_seqid, 0);
2294                 if (status) {
2295                         /* an unconfirmed replay returns misordered */
2296                         status = nfserr_seq_misordered;
2297                         goto out_free_conn;
2298                 }
2299                 old = find_confirmed_client_by_name(&unconf->cl_name, nn);
2300                 if (old) {
2301                         status = mark_client_expired(old);
2302                         if (status)
2303                                 goto out_free_conn;
2304                         expire_client(old);
2305                 }
2306                 move_to_confirmed(unconf);
2307                 conf = unconf;
2308         } else {
2309                 status = nfserr_stale_clientid;
2310                 goto out_free_conn;
2311         }
2312         status = nfs_ok;
2313         /*
2314          * We do not support RDMA or persistent sessions
2315          */
2316         cr_ses->flags &= ~SESSION4_PERSIST;
2317         cr_ses->flags &= ~SESSION4_RDMA;
2318
2319         init_session(rqstp, new, conf, cr_ses);
2320         nfsd4_init_conn(rqstp, conn, new);
2321
2322         memcpy(cr_ses->sessionid.data, new->se_sessionid.data,
2323                NFS4_MAX_SESSIONID_LEN);
2324         cs_slot->sl_seqid++;
2325         cr_ses->seqid = cs_slot->sl_seqid;
2326
2327         /* cache solo and embedded create sessions under the state lock */
2328         nfsd4_cache_create_session(cr_ses, cs_slot, status);
2329         nfs4_unlock_state();
2330         return status;
2331 out_free_conn:
2332         nfs4_unlock_state();
2333         free_conn(conn);
2334 out_free_session:
2335         __free_session(new);
2336 out_release_drc_mem:
2337         nfsd4_put_drc_mem(&cr_ses->fore_channel);
2338         return status;
2339 }
2340
2341 static __be32 nfsd4_map_bcts_dir(u32 *dir)
2342 {
2343         switch (*dir) {
2344         case NFS4_CDFC4_FORE:
2345         case NFS4_CDFC4_BACK:
2346                 return nfs_ok;
2347         case NFS4_CDFC4_FORE_OR_BOTH:
2348         case NFS4_CDFC4_BACK_OR_BOTH:
2349                 *dir = NFS4_CDFC4_BOTH;
2350                 return nfs_ok;
2351         };
2352         return nfserr_inval;
2353 }
2354
2355 __be32 nfsd4_backchannel_ctl(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_backchannel_ctl *bc)
2356 {
2357         struct nfsd4_session *session = cstate->session;
2358         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
2359         __be32 status;
2360
2361         status = nfsd4_check_cb_sec(&bc->bc_cb_sec);
2362         if (status)
2363                 return status;
2364         spin_lock(&nn->client_lock);
2365         session->se_cb_prog = bc->bc_cb_program;
2366         session->se_cb_sec = bc->bc_cb_sec;
2367         spin_unlock(&nn->client_lock);
2368
2369         nfsd4_probe_callback(session->se_client);
2370
2371         return nfs_ok;
2372 }
2373
2374 __be32 nfsd4_bind_conn_to_session(struct svc_rqst *rqstp,
2375                      struct nfsd4_compound_state *cstate,
2376                      struct nfsd4_bind_conn_to_session *bcts)
2377 {
2378         __be32 status;
2379         struct nfsd4_conn *conn;
2380         struct nfsd4_session *session;
2381         struct net *net = SVC_NET(rqstp);
2382         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
2383
2384         if (!nfsd4_last_compound_op(rqstp))
2385                 return nfserr_not_only_op;
2386         nfs4_lock_state();
2387         spin_lock(&nn->client_lock);
2388         session = find_in_sessionid_hashtbl(&bcts->sessionid, net, &status);
2389         spin_unlock(&nn->client_lock);
2390         if (!session)
2391                 goto out_no_session;
2392         status = nfserr_wrong_cred;
2393         if (!mach_creds_match(session->se_client, rqstp))
2394                 goto out;
2395         status = nfsd4_map_bcts_dir(&bcts->dir);
2396         if (status)
2397                 goto out;
2398         conn = alloc_conn(rqstp, bcts->dir);
2399         status = nfserr_jukebox;
2400         if (!conn)
2401                 goto out;
2402         nfsd4_init_conn(rqstp, conn, session);
2403         status = nfs_ok;
2404 out:
2405         nfsd4_put_session(session);
2406 out_no_session:
2407         nfs4_unlock_state();
2408         return status;
2409 }
2410
2411 static bool nfsd4_compound_in_session(struct nfsd4_session *session, struct nfs4_sessionid *sid)
2412 {
2413         if (!session)
2414                 return 0;
2415         return !memcmp(sid, &session->se_sessionid, sizeof(*sid));
2416 }
2417
2418 __be32
2419 nfsd4_destroy_session(struct svc_rqst *r,
2420                       struct nfsd4_compound_state *cstate,
2421                       struct nfsd4_destroy_session *sessionid)
2422 {
2423         struct nfsd4_session *ses;
2424         __be32 status;
2425         int ref_held_by_me = 0;
2426         struct net *net = SVC_NET(r);
2427         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
2428
2429         nfs4_lock_state();
2430         status = nfserr_not_only_op;
2431         if (nfsd4_compound_in_session(cstate->session, &sessionid->sessionid)) {
2432                 if (!nfsd4_last_compound_op(r))
2433                         goto out;
2434                 ref_held_by_me++;
2435         }
2436         dump_sessionid(__func__, &sessionid->sessionid);
2437         spin_lock(&nn->client_lock);
2438         ses = find_in_sessionid_hashtbl(&sessionid->sessionid, net, &status);
2439         if (!ses)
2440                 goto out_client_lock;
2441         status = nfserr_wrong_cred;
2442         if (!mach_creds_match(ses->se_client, r))
2443                 goto out_put_session;
2444         status = mark_session_dead_locked(ses, 1 + ref_held_by_me);
2445         if (status)
2446                 goto out_put_session;
2447         unhash_session(ses);
2448         spin_unlock(&nn->client_lock);
2449
2450         nfsd4_probe_callback_sync(ses->se_client);
2451
2452         spin_lock(&nn->client_lock);
2453         status = nfs_ok;
2454 out_put_session:
2455         nfsd4_put_session_locked(ses);
2456 out_client_lock:
2457         spin_unlock(&nn->client_lock);
2458 out:
2459         nfs4_unlock_state();
2460         return status;
2461 }
2462
2463 static struct nfsd4_conn *__nfsd4_find_conn(struct svc_xprt *xpt, struct nfsd4_session *s)
2464 {
2465         struct nfsd4_conn *c;
2466
2467         list_for_each_entry(c, &s->se_conns, cn_persession) {
2468                 if (c->cn_xprt == xpt) {
2469                         return c;
2470                 }
2471         }
2472         return NULL;
2473 }
2474
2475 static __be32 nfsd4_sequence_check_conn(struct nfsd4_conn *new, struct nfsd4_session *ses)
2476 {
2477         struct nfs4_client *clp = ses->se_client;
2478         struct nfsd4_conn *c;
2479         __be32 status = nfs_ok;
2480         int ret;
2481
2482         spin_lock(&clp->cl_lock);
2483         c = __nfsd4_find_conn(new->cn_xprt, ses);
2484         if (c)
2485                 goto out_free;
2486         status = nfserr_conn_not_bound_to_session;
2487         if (clp->cl_mach_cred)
2488                 goto out_free;
2489         __nfsd4_hash_conn(new, ses);
2490         spin_unlock(&clp->cl_lock);
2491         ret = nfsd4_register_conn(new);
2492         if (ret)
2493                 /* oops; xprt is already down: */
2494                 nfsd4_conn_lost(&new->cn_xpt_user);
2495         return nfs_ok;
2496 out_free:
2497         spin_unlock(&clp->cl_lock);
2498         free_conn(new);
2499         return status;
2500 }
2501
2502 static bool nfsd4_session_too_many_ops(struct svc_rqst *rqstp, struct nfsd4_session *session)
2503 {
2504         struct nfsd4_compoundargs *args = rqstp->rq_argp;
2505
2506         return args->opcnt > session->se_fchannel.maxops;
2507 }
2508
2509 static bool nfsd4_request_too_big(struct svc_rqst *rqstp,
2510                                   struct nfsd4_session *session)
2511 {
2512         struct xdr_buf *xb = &rqstp->rq_arg;
2513
2514         return xb->len > session->se_fchannel.maxreq_sz;
2515 }
2516
2517 __be32
2518 nfsd4_sequence(struct svc_rqst *rqstp,
2519                struct nfsd4_compound_state *cstate,
2520                struct nfsd4_sequence *seq)
2521 {
2522         struct nfsd4_compoundres *resp = rqstp->rq_resp;
2523         struct xdr_stream *xdr = &resp->xdr;
2524         struct nfsd4_session *session;
2525         struct nfs4_client *clp;
2526         struct nfsd4_slot *slot;
2527         struct nfsd4_conn *conn;
2528         __be32 status;
2529         int buflen;
2530         struct net *net = SVC_NET(rqstp);
2531         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
2532
2533         if (resp->opcnt != 1)
2534                 return nfserr_sequence_pos;
2535
2536         /*
2537          * Will be either used or freed by nfsd4_sequence_check_conn
2538          * below.
2539          */
2540         conn = alloc_conn(rqstp, NFS4_CDFC4_FORE);
2541         if (!conn)
2542                 return nfserr_jukebox;
2543
2544         spin_lock(&nn->client_lock);
2545         session = find_in_sessionid_hashtbl(&seq->sessionid, net, &status);
2546         if (!session)
2547                 goto out_no_session;
2548         clp = session->se_client;
2549
2550         status = nfserr_too_many_ops;
2551         if (nfsd4_session_too_many_ops(rqstp, session))
2552                 goto out_put_session;
2553
2554         status = nfserr_req_too_big;
2555         if (nfsd4_request_too_big(rqstp, session))
2556                 goto out_put_session;
2557
2558         status = nfserr_badslot;
2559         if (seq->slotid >= session->se_fchannel.maxreqs)
2560                 goto out_put_session;
2561
2562         slot = session->se_slots[seq->slotid];
2563         dprintk("%s: slotid %d\n", __func__, seq->slotid);
2564
2565         /* We do not negotiate the number of slots yet, so set the
2566          * maxslots to the session maxreqs which is used to encode
2567          * sr_highest_slotid and the sr_target_slot id to maxslots */
2568         seq->maxslots = session->se_fchannel.maxreqs;
2569
2570         status = check_slot_seqid(seq->seqid, slot->sl_seqid,
2571                                         slot->sl_flags & NFSD4_SLOT_INUSE);
2572         if (status == nfserr_replay_cache) {
2573                 status = nfserr_seq_misordered;
2574                 if (!(slot->sl_flags & NFSD4_SLOT_INITIALIZED))
2575                         goto out_put_session;
2576                 cstate->slot = slot;
2577                 cstate->session = session;
2578                 cstate->clp = clp;
2579                 /* Return the cached reply status and set cstate->status
2580                  * for nfsd4_proc_compound processing */
2581                 status = nfsd4_replay_cache_entry(resp, seq);
2582                 cstate->status = nfserr_replay_cache;
2583                 goto out;
2584         }
2585         if (status)
2586                 goto out_put_session;
2587
2588         status = nfsd4_sequence_check_conn(conn, session);
2589         conn = NULL;
2590         if (status)
2591                 goto out_put_session;
2592
2593         buflen = (seq->cachethis) ?
2594                         session->se_fchannel.maxresp_cached :
2595                         session->se_fchannel.maxresp_sz;
2596         status = (seq->cachethis) ? nfserr_rep_too_big_to_cache :
2597                                     nfserr_rep_too_big;
2598         if (xdr_restrict_buflen(xdr, buflen - rqstp->rq_auth_slack))
2599                 goto out_put_session;
2600         svc_reserve(rqstp, buflen);
2601
2602         status = nfs_ok;
2603         /* Success! bump slot seqid */
2604         slot->sl_seqid = seq->seqid;
2605         slot->sl_flags |= NFSD4_SLOT_INUSE;
2606         if (seq->cachethis)
2607                 slot->sl_flags |= NFSD4_SLOT_CACHETHIS;
2608         else
2609                 slot->sl_flags &= ~NFSD4_SLOT_CACHETHIS;
2610
2611         cstate->slot = slot;
2612         cstate->session = session;
2613         cstate->clp = clp;
2614
2615 out:
2616         switch (clp->cl_cb_state) {
2617         case NFSD4_CB_DOWN:
2618                 seq->status_flags = SEQ4_STATUS_CB_PATH_DOWN;
2619                 break;
2620         case NFSD4_CB_FAULT:
2621                 seq->status_flags = SEQ4_STATUS_BACKCHANNEL_FAULT;
2622                 break;
2623         default:
2624                 seq->status_flags = 0;
2625         }
2626         if (!list_empty(&clp->cl_revoked))
2627                 seq->status_flags |= SEQ4_STATUS_RECALLABLE_STATE_REVOKED;
2628 out_no_session:
2629         if (conn)
2630                 free_conn(conn);
2631         spin_unlock(&nn->client_lock);
2632         return status;
2633 out_put_session:
2634         nfsd4_put_session_locked(session);
2635         goto out_no_session;
2636 }
2637
2638 void
2639 nfsd4_sequence_done(struct nfsd4_compoundres *resp)
2640 {
2641         struct nfsd4_compound_state *cs = &resp->cstate;
2642
2643         if (nfsd4_has_session(cs)) {
2644                 if (cs->status != nfserr_replay_cache) {
2645                         nfsd4_store_cache_entry(resp);
2646                         cs->slot->sl_flags &= ~NFSD4_SLOT_INUSE;
2647                 }
2648                 /* Drop session reference that was taken in nfsd4_sequence() */
2649                 nfsd4_put_session(cs->session);
2650         } else if (cs->clp)
2651                 put_client_renew(cs->clp);
2652 }
2653
2654 __be32
2655 nfsd4_destroy_clientid(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_destroy_clientid *dc)
2656 {
2657         struct nfs4_client *conf, *unconf, *clp;
2658         __be32 status = 0;
2659         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
2660
2661         nfs4_lock_state();
2662         unconf = find_unconfirmed_client(&dc->clientid, true, nn);
2663         conf = find_confirmed_client(&dc->clientid, true, nn);
2664         WARN_ON_ONCE(conf && unconf);
2665
2666         if (conf) {
2667                 clp = conf;
2668
2669                 if (client_has_state(conf)) {
2670                         status = nfserr_clientid_busy;
2671                         goto out;
2672                 }
2673         } else if (unconf)
2674                 clp = unconf;
2675         else {
2676                 status = nfserr_stale_clientid;
2677                 goto out;
2678         }
2679         if (!mach_creds_match(clp, rqstp)) {
2680                 status = nfserr_wrong_cred;
2681                 goto out;
2682         }
2683         expire_client(clp);
2684 out:
2685         nfs4_unlock_state();
2686         return status;
2687 }
2688
2689 __be32
2690 nfsd4_reclaim_complete(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_reclaim_complete *rc)
2691 {
2692         __be32 status = 0;
2693
2694         if (rc->rca_one_fs) {
2695                 if (!cstate->current_fh.fh_dentry)
2696                         return nfserr_nofilehandle;
2697                 /*
2698                  * We don't take advantage of the rca_one_fs case.
2699                  * That's OK, it's optional, we can safely ignore it.
2700                  */
2701                  return nfs_ok;
2702         }
2703
2704         nfs4_lock_state();
2705         status = nfserr_complete_already;
2706         if (test_and_set_bit(NFSD4_CLIENT_RECLAIM_COMPLETE,
2707                              &cstate->session->se_client->cl_flags))
2708                 goto out;
2709
2710         status = nfserr_stale_clientid;
2711         if (is_client_expired(cstate->session->se_client))
2712                 /*
2713                  * The following error isn't really legal.
2714                  * But we only get here if the client just explicitly
2715                  * destroyed the client.  Surely it no longer cares what
2716                  * error it gets back on an operation for the dead
2717                  * client.
2718                  */
2719                 goto out;
2720
2721         status = nfs_ok;
2722         nfsd4_client_record_create(cstate->session->se_client);
2723 out:
2724         nfs4_unlock_state();
2725         return status;
2726 }
2727
2728 __be32
2729 nfsd4_setclientid(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
2730                   struct nfsd4_setclientid *setclid)
2731 {
2732         struct xdr_netobj       clname = setclid->se_name;
2733         nfs4_verifier           clverifier = setclid->se_verf;
2734         struct nfs4_client      *conf, *unconf, *new;
2735         __be32                  status;
2736         struct nfsd_net         *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
2737
2738         /* Cases below refer to rfc 3530 section 14.2.33: */
2739         nfs4_lock_state();
2740         conf = find_confirmed_client_by_name(&clname, nn);
2741         if (conf) {
2742                 /* case 0: */
2743                 status = nfserr_clid_inuse;
2744                 if (clp_used_exchangeid(conf))
2745                         goto out;
2746                 if (!same_creds(&conf->cl_cred, &rqstp->rq_cred)) {
2747                         char addr_str[INET6_ADDRSTRLEN];
2748                         rpc_ntop((struct sockaddr *) &conf->cl_addr, addr_str,
2749                                  sizeof(addr_str));
2750                         dprintk("NFSD: setclientid: string in use by client "
2751                                 "at %s\n", addr_str);
2752                         goto out;
2753                 }
2754         }
2755         unconf = find_unconfirmed_client_by_name(&clname, nn);
2756         if (unconf)
2757                 expire_client(unconf);
2758         status = nfserr_jukebox;
2759         new = create_client(clname, rqstp, &clverifier);
2760         if (new == NULL)
2761                 goto out;
2762         if (conf && same_verf(&conf->cl_verifier, &clverifier))
2763                 /* case 1: probable callback update */
2764                 copy_clid(new, conf);
2765         else /* case 4 (new client) or cases 2, 3 (client reboot): */
2766                 gen_clid(new, nn);
2767         new->cl_minorversion = 0;
2768         gen_callback(new, setclid, rqstp);
2769         add_to_unconfirmed(new);
2770         setclid->se_clientid.cl_boot = new->cl_clientid.cl_boot;
2771         setclid->se_clientid.cl_id = new->cl_clientid.cl_id;
2772         memcpy(setclid->se_confirm.data, new->cl_confirm.data, sizeof(setclid->se_confirm.data));
2773         status = nfs_ok;
2774 out:
2775         nfs4_unlock_state();
2776         return status;
2777 }
2778
2779
2780 __be32
2781 nfsd4_setclientid_confirm(struct svc_rqst *rqstp,
2782                          struct nfsd4_compound_state *cstate,
2783                          struct nfsd4_setclientid_confirm *setclientid_confirm)
2784 {
2785         struct nfs4_client *conf, *unconf;
2786         nfs4_verifier confirm = setclientid_confirm->sc_confirm; 
2787         clientid_t * clid = &setclientid_confirm->sc_clientid;
2788         __be32 status;
2789         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
2790
2791         if (STALE_CLIENTID(clid, nn))
2792                 return nfserr_stale_clientid;
2793         nfs4_lock_state();
2794
2795         conf = find_confirmed_client(clid, false, nn);
2796         unconf = find_unconfirmed_client(clid, false, nn);
2797         /*
2798          * We try hard to give out unique clientid's, so if we get an
2799          * attempt to confirm the same clientid with a different cred,
2800          * there's a bug somewhere.  Let's charitably assume it's our
2801          * bug.
2802          */
2803         status = nfserr_serverfault;
2804         if (unconf && !same_creds(&unconf->cl_cred, &rqstp->rq_cred))
2805                 goto out;
2806         if (conf && !same_creds(&conf->cl_cred, &rqstp->rq_cred))
2807                 goto out;
2808         /* cases below refer to rfc 3530 section 14.2.34: */
2809         if (!unconf || !same_verf(&confirm, &unconf->cl_confirm)) {
2810                 if (conf && !unconf) /* case 2: probable retransmit */
2811                         status = nfs_ok;
2812                 else /* case 4: client hasn't noticed we rebooted yet? */
2813                         status = nfserr_stale_clientid;
2814                 goto out;
2815         }
2816         status = nfs_ok;
2817         if (conf) { /* case 1: callback update */
2818                 nfsd4_change_callback(conf, &unconf->cl_cb_conn);
2819                 nfsd4_probe_callback(conf);
2820                 expire_client(unconf);
2821         } else { /* case 3: normal case; new or rebooted client */
2822                 conf = find_confirmed_client_by_name(&unconf->cl_name, nn);
2823                 if (conf) {
2824                         status = mark_client_expired(conf);
2825                         if (status)
2826                                 goto out;
2827                         expire_client(conf);
2828                 }
2829                 move_to_confirmed(unconf);
2830                 nfsd4_probe_callback(unconf);
2831         }
2832 out:
2833         nfs4_unlock_state();
2834         return status;
2835 }
2836
2837 static struct nfs4_file *nfsd4_alloc_file(void)
2838 {
2839         return kmem_cache_alloc(file_slab, GFP_KERNEL);
2840 }
2841
2842 /* OPEN Share state helper functions */
2843 static void nfsd4_init_file(struct nfs4_file *fp, struct knfsd_fh *fh)
2844 {
2845         unsigned int hashval = file_hashval(fh);
2846
2847         lockdep_assert_held(&state_lock);
2848
2849         atomic_set(&fp->fi_ref, 1);
2850         spin_lock_init(&fp->fi_lock);
2851         INIT_LIST_HEAD(&fp->fi_stateids);
2852         INIT_LIST_HEAD(&fp->fi_delegations);
2853         fh_copy_shallow(&fp->fi_fhandle, fh);
2854         fp->fi_had_conflict = false;
2855         fp->fi_lease = NULL;
2856         fp->fi_share_deny = 0;
2857         memset(fp->fi_fds, 0, sizeof(fp->fi_fds));
2858         memset(fp->fi_access, 0, sizeof(fp->fi_access));
2859         hlist_add_head(&fp->fi_hash, &file_hashtbl[hashval]);
2860 }
2861
2862 void
2863 nfsd4_free_slabs(void)
2864 {
2865         kmem_cache_destroy(openowner_slab);
2866         kmem_cache_destroy(lockowner_slab);
2867         kmem_cache_destroy(file_slab);
2868         kmem_cache_destroy(stateid_slab);
2869         kmem_cache_destroy(deleg_slab);
2870 }
2871
2872 int
2873 nfsd4_init_slabs(void)
2874 {
2875         openowner_slab = kmem_cache_create("nfsd4_openowners",
2876                         sizeof(struct nfs4_openowner), 0, 0, NULL);
2877         if (openowner_slab == NULL)
2878                 goto out;
2879         lockowner_slab = kmem_cache_create("nfsd4_lockowners",
2880                         sizeof(struct nfs4_lockowner), 0, 0, NULL);
2881         if (lockowner_slab == NULL)
2882                 goto out_free_openowner_slab;
2883         file_slab = kmem_cache_create("nfsd4_files",
2884                         sizeof(struct nfs4_file), 0, 0, NULL);
2885         if (file_slab == NULL)
2886                 goto out_free_lockowner_slab;
2887         stateid_slab = kmem_cache_create("nfsd4_stateids",
2888                         sizeof(struct nfs4_ol_stateid), 0, 0, NULL);
2889         if (stateid_slab == NULL)
2890                 goto out_free_file_slab;
2891         deleg_slab = kmem_cache_create("nfsd4_delegations",
2892                         sizeof(struct nfs4_delegation), 0, 0, NULL);
2893         if (deleg_slab == NULL)
2894                 goto out_free_stateid_slab;
2895         return 0;
2896
2897 out_free_stateid_slab:
2898         kmem_cache_destroy(stateid_slab);
2899 out_free_file_slab:
2900         kmem_cache_destroy(file_slab);
2901 out_free_lockowner_slab:
2902         kmem_cache_destroy(lockowner_slab);
2903 out_free_openowner_slab:
2904         kmem_cache_destroy(openowner_slab);
2905 out:
2906         dprintk("nfsd4: out of memory while initializing nfsv4\n");
2907         return -ENOMEM;
2908 }
2909
2910 static void init_nfs4_replay(struct nfs4_replay *rp)
2911 {
2912         rp->rp_status = nfserr_serverfault;
2913         rp->rp_buflen = 0;
2914         rp->rp_buf = rp->rp_ibuf;
2915 }
2916
2917 static inline void *alloc_stateowner(struct kmem_cache *slab, struct xdr_netobj *owner, struct nfs4_client *clp)
2918 {
2919         struct nfs4_stateowner *sop;
2920
2921         sop = kmem_cache_alloc(slab, GFP_KERNEL);
2922         if (!sop)
2923                 return NULL;
2924
2925         sop->so_owner.data = kmemdup(owner->data, owner->len, GFP_KERNEL);
2926         if (!sop->so_owner.data) {
2927                 kmem_cache_free(slab, sop);
2928                 return NULL;
2929         }
2930         sop->so_owner.len = owner->len;
2931
2932         INIT_LIST_HEAD(&sop->so_stateids);
2933         sop->so_client = clp;
2934         init_nfs4_replay(&sop->so_replay);
2935         return sop;
2936 }
2937
2938 static void hash_openowner(struct nfs4_openowner *oo, struct nfs4_client *clp, unsigned int strhashval)
2939 {
2940         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
2941
2942         list_add(&oo->oo_owner.so_strhash, &nn->ownerstr_hashtbl[strhashval]);
2943         list_add(&oo->oo_perclient, &clp->cl_openowners);
2944 }
2945
2946 static struct nfs4_openowner *
2947 alloc_init_open_stateowner(unsigned int strhashval, struct nfsd4_open *open,
2948                            struct nfsd4_compound_state *cstate)
2949 {
2950         struct nfs4_client *clp = cstate->clp;
2951         struct nfs4_openowner *oo;
2952
2953         oo = alloc_stateowner(openowner_slab, &open->op_owner, clp);
2954         if (!oo)
2955                 return NULL;
2956         oo->oo_owner.so_is_open_owner = 1;
2957         oo->oo_owner.so_seqid = open->op_seqid;
2958         oo->oo_flags = NFS4_OO_NEW;
2959         if (nfsd4_has_session(cstate))
2960                 oo->oo_flags |= NFS4_OO_CONFIRMED;
2961         oo->oo_time = 0;
2962         oo->oo_last_closed_stid = NULL;
2963         INIT_LIST_HEAD(&oo->oo_close_lru);
2964         hash_openowner(oo, clp, strhashval);
2965         return oo;
2966 }
2967
2968 static void init_open_stateid(struct nfs4_ol_stateid *stp, struct nfs4_file *fp, struct nfsd4_open *open) {
2969         struct nfs4_openowner *oo = open->op_openowner;
2970
2971         stp->st_stid.sc_type = NFS4_OPEN_STID;
2972         INIT_LIST_HEAD(&stp->st_locks);
2973         list_add(&stp->st_perstateowner, &oo->oo_owner.so_stateids);
2974         stp->st_stateowner = &oo->oo_owner;
2975         get_nfs4_file(fp);
2976         stp->st_stid.sc_file = fp;
2977         stp->st_access_bmap = 0;
2978         stp->st_deny_bmap = 0;
2979         stp->st_openstp = NULL;
2980         spin_lock(&fp->fi_lock);
2981         list_add(&stp->st_perfile, &fp->fi_stateids);
2982         spin_unlock(&fp->fi_lock);
2983 }
2984
2985 static void
2986 move_to_close_lru(struct nfs4_openowner *oo, struct net *net)
2987 {
2988         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
2989
2990         dprintk("NFSD: move_to_close_lru nfs4_openowner %p\n", oo);
2991
2992         list_move_tail(&oo->oo_close_lru, &nn->close_lru);
2993         oo->oo_time = get_seconds();
2994 }
2995
2996 static int
2997 same_owner_str(struct nfs4_stateowner *sop, struct xdr_netobj *owner,
2998                                                         clientid_t *clid)
2999 {
3000         return (sop->so_owner.len == owner->len) &&
3001                 0 == memcmp(sop->so_owner.data, owner->data, owner->len) &&
3002                 (sop->so_client->cl_clientid.cl_id == clid->cl_id);
3003 }
3004
3005 static struct nfs4_openowner *
3006 find_openstateowner_str(unsigned int hashval, struct nfsd4_open *open,
3007                         bool sessions, struct nfsd_net *nn)
3008 {
3009         struct nfs4_stateowner *so;
3010         struct nfs4_openowner *oo;
3011         struct nfs4_client *clp;
3012
3013         list_for_each_entry(so, &nn->ownerstr_hashtbl[hashval], so_strhash) {
3014                 if (!so->so_is_open_owner)
3015                         continue;
3016                 if (same_owner_str(so, &open->op_owner, &open->op_clientid)) {
3017                         oo = openowner(so);
3018                         clp = oo->oo_owner.so_client;
3019                         if ((bool)clp->cl_minorversion != sessions)
3020                                 return NULL;
3021                         renew_client(oo->oo_owner.so_client);
3022                         return oo;
3023                 }
3024         }
3025         return NULL;
3026 }
3027
3028 /* search file_hashtbl[] for file */
3029 static struct nfs4_file *
3030 find_file_locked(struct knfsd_fh *fh)
3031 {
3032         unsigned int hashval = file_hashval(fh);
3033         struct nfs4_file *fp;
3034
3035         lockdep_assert_held(&state_lock);
3036
3037         hlist_for_each_entry(fp, &file_hashtbl[hashval], fi_hash) {
3038                 if (nfsd_fh_match(&fp->fi_fhandle, fh)) {
3039                         get_nfs4_file(fp);
3040                         return fp;
3041                 }
3042         }
3043         return NULL;
3044 }
3045
3046 static struct nfs4_file *
3047 find_file(struct knfsd_fh *fh)
3048 {
3049         struct nfs4_file *fp;
3050
3051         spin_lock(&state_lock);
3052         fp = find_file_locked(fh);
3053         spin_unlock(&state_lock);
3054         return fp;
3055 }
3056
3057 static struct nfs4_file *
3058 find_or_add_file(struct nfs4_file *new, struct knfsd_fh *fh)
3059 {
3060         struct nfs4_file *fp;
3061
3062         spin_lock(&state_lock);
3063         fp = find_file_locked(fh);
3064         if (fp == NULL) {
3065                 nfsd4_init_file(new, fh);
3066                 fp = new;
3067         }
3068         spin_unlock(&state_lock);
3069
3070         return fp;
3071 }
3072
3073 /*
3074  * Called to check deny when READ with all zero stateid or
3075  * WRITE with all zero or all one stateid
3076  */
3077 static __be32
3078 nfs4_share_conflict(struct svc_fh *current_fh, unsigned int deny_type)
3079 {
3080         struct nfs4_file *fp;
3081         __be32 ret = nfs_ok;
3082
3083         fp = find_file(&current_fh->fh_handle);
3084         if (!fp)
3085                 return ret;
3086         /* Check for conflicting share reservations */
3087         spin_lock(&fp->fi_lock);
3088         if (fp->fi_share_deny & deny_type)
3089                 ret = nfserr_locked;
3090         spin_unlock(&fp->fi_lock);
3091         put_nfs4_file(fp);
3092         return ret;
3093 }
3094
3095 void nfsd4_prepare_cb_recall(struct nfs4_delegation *dp)
3096 {
3097         struct nfsd_net *nn = net_generic(dp->dl_stid.sc_client->net,
3098                                           nfsd_net_id);
3099
3100         block_delegations(&dp->dl_stid.sc_file->fi_fhandle);
3101
3102         /*
3103          * We can't do this in nfsd_break_deleg_cb because it is
3104          * already holding inode->i_lock.
3105          *
3106          * If the dl_time != 0, then we know that it has already been
3107          * queued for a lease break. Don't queue it again.
3108          */
3109         spin_lock(&state_lock);
3110         if (dp->dl_time == 0) {
3111                 dp->dl_time = get_seconds();
3112                 list_add_tail(&dp->dl_recall_lru, &nn->del_recall_lru);
3113         }
3114         spin_unlock(&state_lock);
3115 }
3116
3117 static void nfsd_break_one_deleg(struct nfs4_delegation *dp)
3118 {
3119         /*
3120          * We're assuming the state code never drops its reference
3121          * without first removing the lease.  Since we're in this lease
3122          * callback (and since the lease code is serialized by the kernel
3123          * lock) we know the server hasn't removed the lease yet, we know
3124          * it's safe to take a reference.
3125          */
3126         atomic_inc(&dp->dl_stid.sc_count);
3127         nfsd4_cb_recall(dp);
3128 }
3129
3130 /* Called from break_lease() with i_lock held. */
3131 static void nfsd_break_deleg_cb(struct file_lock *fl)
3132 {
3133         struct nfs4_file *fp = (struct nfs4_file *)fl->fl_owner;
3134         struct nfs4_delegation *dp;
3135
3136         if (!fp) {
3137                 WARN(1, "(%p)->fl_owner NULL\n", fl);
3138                 return;
3139         }
3140         if (fp->fi_had_conflict) {
3141                 WARN(1, "duplicate break on %p\n", fp);
3142                 return;
3143         }
3144         /*
3145          * We don't want the locks code to timeout the lease for us;
3146          * we'll remove it ourself if a delegation isn't returned
3147          * in time:
3148          */
3149         fl->fl_break_time = 0;
3150
3151         spin_lock(&fp->fi_lock);
3152         fp->fi_had_conflict = true;
3153         /*
3154          * If there are no delegations on the list, then we can't count on this
3155          * lease ever being cleaned up. Set the fl_break_time to jiffies so that
3156          * time_out_leases will do it ASAP. The fact that fi_had_conflict is now
3157          * true should keep any new delegations from being hashed.
3158          */
3159         if (list_empty(&fp->fi_delegations))
3160                 fl->fl_break_time = jiffies;
3161         else
3162                 list_for_each_entry(dp, &fp->fi_delegations, dl_perfile)
3163                         nfsd_break_one_deleg(dp);
3164         spin_unlock(&fp->fi_lock);
3165 }
3166
3167 static
3168 int nfsd_change_deleg_cb(struct file_lock **onlist, int arg)
3169 {
3170         if (arg & F_UNLCK)
3171                 return lease_modify(onlist, arg);
3172         else
3173                 return -EAGAIN;
3174 }
3175
3176 static const struct lock_manager_operations nfsd_lease_mng_ops = {
3177         .lm_break = nfsd_break_deleg_cb,
3178         .lm_change = nfsd_change_deleg_cb,
3179 };
3180
3181 static __be32 nfsd4_check_seqid(struct nfsd4_compound_state *cstate, struct nfs4_stateowner *so, u32 seqid)
3182 {
3183         if (nfsd4_has_session(cstate))
3184                 return nfs_ok;
3185         if (seqid == so->so_seqid - 1)
3186                 return nfserr_replay_me;
3187         if (seqid == so->so_seqid)
3188                 return nfs_ok;
3189         return nfserr_bad_seqid;
3190 }
3191
3192 static __be32 lookup_clientid(clientid_t *clid,
3193                 struct nfsd4_compound_state *cstate,
3194                 struct nfsd_net *nn)
3195 {
3196         struct nfs4_client *found;
3197
3198         if (cstate->clp) {
3199                 found = cstate->clp;
3200                 if (!same_clid(&found->cl_clientid, clid))
3201                         return nfserr_stale_clientid;
3202                 return nfs_ok;
3203         }
3204
3205         if (STALE_CLIENTID(clid, nn))
3206                 return nfserr_stale_clientid;
3207
3208         /*
3209          * For v4.1+ we get the client in the SEQUENCE op. If we don't have one
3210          * cached already then we know this is for is for v4.0 and "sessions"
3211          * will be false.
3212          */
3213         WARN_ON_ONCE(cstate->session);
3214         found = find_confirmed_client(clid, false, nn);
3215         if (!found)
3216                 return nfserr_expired;
3217
3218         /* Cache the nfs4_client in cstate! */
3219         cstate->clp = found;
3220         atomic_inc(&found->cl_refcount);
3221         return nfs_ok;
3222 }
3223
3224 __be32
3225 nfsd4_process_open1(struct nfsd4_compound_state *cstate,
3226                     struct nfsd4_open *open, struct nfsd_net *nn)
3227 {
3228         clientid_t *clientid = &open->op_clientid;
3229         struct nfs4_client *clp = NULL;
3230         unsigned int strhashval;
3231         struct nfs4_openowner *oo = NULL;
3232         __be32 status;
3233
3234         if (STALE_CLIENTID(&open->op_clientid, nn))
3235                 return nfserr_stale_clientid;
3236         /*
3237          * In case we need it later, after we've already created the
3238          * file and don't want to risk a further failure:
3239          */
3240         open->op_file = nfsd4_alloc_file();
3241         if (open->op_file == NULL)
3242                 return nfserr_jukebox;
3243
3244         status = lookup_clientid(clientid, cstate, nn);
3245         if (status)
3246                 return status;
3247         clp = cstate->clp;
3248
3249         strhashval = ownerstr_hashval(clientid->cl_id, &open->op_owner);
3250         oo = find_openstateowner_str(strhashval, open, cstate->minorversion, nn);
3251         open->op_openowner = oo;
3252         if (!oo) {
3253                 goto new_owner;
3254         }
3255         if (!(oo->oo_flags & NFS4_OO_CONFIRMED)) {
3256                 /* Replace unconfirmed owners without checking for replay. */
3257                 release_openowner(oo);
3258                 open->op_openowner = NULL;
3259                 goto new_owner;
3260         }
3261         status = nfsd4_check_seqid(cstate, &oo->oo_owner, open->op_seqid);
3262         if (status)
3263                 return status;
3264         goto alloc_stateid;
3265 new_owner:
3266         oo = alloc_init_open_stateowner(strhashval, open, cstate);
3267         if (oo == NULL)
3268                 return nfserr_jukebox;
3269         open->op_openowner = oo;
3270 alloc_stateid:
3271         open->op_stp = nfs4_alloc_stateid(clp);
3272         if (!open->op_stp)
3273                 return nfserr_jukebox;
3274         return nfs_ok;
3275 }
3276
3277 static inline __be32
3278 nfs4_check_delegmode(struct nfs4_delegation *dp, int flags)
3279 {
3280         if ((flags & WR_STATE) && (dp->dl_type == NFS4_OPEN_DELEGATE_READ))
3281                 return nfserr_openmode;
3282         else
3283                 return nfs_ok;
3284 }
3285
3286 static int share_access_to_flags(u32 share_access)
3287 {
3288         return share_access == NFS4_SHARE_ACCESS_READ ? RD_STATE : WR_STATE;
3289 }
3290
3291 static struct nfs4_delegation *find_deleg_stateid(struct nfs4_client *cl, stateid_t *s)
3292 {
3293         struct nfs4_stid *ret;
3294
3295         ret = find_stateid_by_type(cl, s, NFS4_DELEG_STID);
3296         if (!ret)
3297                 return NULL;
3298         return delegstateid(ret);
3299 }
3300
3301 static bool nfsd4_is_deleg_cur(struct nfsd4_open *open)
3302 {
3303         return open->op_claim_type == NFS4_OPEN_CLAIM_DELEGATE_CUR ||
3304                open->op_claim_type == NFS4_OPEN_CLAIM_DELEG_CUR_FH;
3305 }
3306
3307 static __be32
3308 nfs4_check_deleg(struct nfs4_client *cl, struct nfsd4_open *open,
3309                 struct nfs4_delegation **dp)
3310 {
3311         int flags;
3312         __be32 status = nfserr_bad_stateid;
3313
3314         *dp = find_deleg_stateid(cl, &open->op_delegate_stateid);
3315         if (*dp == NULL)
3316                 goto out;
3317         flags = share_access_to_flags(open->op_share_access);
3318         status = nfs4_check_delegmode(*dp, flags);
3319         if (status)
3320                 *dp = NULL;
3321 out:
3322         if (!nfsd4_is_deleg_cur(open))
3323                 return nfs_ok;
3324         if (status)
3325                 return status;
3326         open->op_openowner->oo_flags |= NFS4_OO_CONFIRMED;
3327         return nfs_ok;
3328 }
3329
3330 static struct nfs4_ol_stateid *
3331 nfsd4_find_existing_open(struct nfs4_file *fp, struct nfsd4_open *open)
3332 {
3333         struct nfs4_ol_stateid *local, *ret = NULL;
3334         struct nfs4_openowner *oo = open->op_openowner;
3335
3336         spin_lock(&fp->fi_lock);
3337         list_for_each_entry(local, &fp->fi_stateids, st_perfile) {
3338                 /* ignore lock owners */
3339                 if (local->st_stateowner->so_is_open_owner == 0)
3340                         continue;
3341                 if (local->st_stateowner == &oo->oo_owner) {
3342                         ret = local;
3343                         break;
3344                 }
3345         }
3346         spin_unlock(&fp->fi_lock);
3347         return ret;
3348 }
3349
3350 static inline int nfs4_access_to_access(u32 nfs4_access)
3351 {
3352         int flags = 0;
3353
3354         if (nfs4_access & NFS4_SHARE_ACCESS_READ)
3355                 flags |= NFSD_MAY_READ;
3356         if (nfs4_access & NFS4_SHARE_ACCESS_WRITE)
3357                 flags |= NFSD_MAY_WRITE;
3358         return flags;
3359 }
3360
3361 static inline __be32
3362 nfsd4_truncate(struct svc_rqst *rqstp, struct svc_fh *fh,
3363                 struct nfsd4_open *open)
3364 {
3365         struct iattr iattr = {
3366                 .ia_valid = ATTR_SIZE,
3367                 .ia_size = 0,
3368         };
3369         if (!open->op_truncate)
3370                 return 0;
3371         if (!(open->op_share_access & NFS4_SHARE_ACCESS_WRITE))
3372                 return nfserr_inval;
3373         return nfsd_setattr(rqstp, fh, &iattr, 0, (time_t)0);
3374 }
3375
3376 static __be32 nfs4_get_vfs_file(struct svc_rqst *rqstp, struct nfs4_file *fp,
3377                 struct svc_fh *cur_fh, struct nfs4_ol_stateid *stp,
3378                 struct nfsd4_open *open)
3379 {
3380         struct file *filp = NULL;
3381         __be32 status;
3382         int oflag = nfs4_access_to_omode(open->op_share_access);
3383         int access = nfs4_access_to_access(open->op_share_access);
3384         unsigned char old_access_bmap, old_deny_bmap;
3385
3386         spin_lock(&fp->fi_lock);
3387
3388         /*
3389          * Are we trying to set a deny mode that would conflict with
3390          * current access?
3391          */
3392         status = nfs4_file_check_deny(fp, open->op_share_deny);
3393         if (status != nfs_ok) {
3394                 spin_unlock(&fp->fi_lock);
3395                 goto out;
3396         }
3397
3398         /* set access to the file */
3399         status = nfs4_file_get_access(fp, open->op_share_access);
3400         if (status != nfs_ok) {
3401                 spin_unlock(&fp->fi_lock);
3402                 goto out;
3403         }
3404
3405         /* Set access bits in stateid */
3406         old_access_bmap = stp->st_access_bmap;
3407         set_access(open->op_share_access, stp);
3408
3409         /* Set new deny mask */
3410         old_deny_bmap = stp->st_deny_bmap;
3411         set_deny(open->op_share_deny, stp);
3412         fp->fi_share_deny |= (open->op_share_deny & NFS4_SHARE_DENY_BOTH);
3413
3414         if (!fp->fi_fds[oflag]) {
3415                 spin_unlock(&fp->fi_lock);
3416                 status = nfsd_open(rqstp, cur_fh, S_IFREG, access, &filp);
3417                 if (status)
3418                         goto out_put_access;
3419                 spin_lock(&fp->fi_lock);
3420                 if (!fp->fi_fds[oflag]) {
3421                         fp->fi_fds[oflag] = filp;
3422                         filp = NULL;
3423                 }
3424         }
3425         spin_unlock(&fp->fi_lock);
3426         if (filp)
3427                 fput(filp);
3428
3429         status = nfsd4_truncate(rqstp, cur_fh, open);
3430         if (status)
3431                 goto out_put_access;
3432 out:
3433         return status;
3434 out_put_access:
3435         stp->st_access_bmap = old_access_bmap;
3436         nfs4_file_put_access(fp, open->op_share_access);
3437         reset_union_bmap_deny(bmap_to_share_mode(old_deny_bmap), stp);
3438         goto out;
3439 }
3440
3441 static __be32
3442 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)
3443 {
3444         __be32 status;
3445         unsigned char old_deny_bmap;
3446
3447         if (!test_access(open->op_share_access, stp))
3448                 return nfs4_get_vfs_file(rqstp, fp, cur_fh, stp, open);
3449
3450         /* test and set deny mode */
3451         spin_lock(&fp->fi_lock);
3452         status = nfs4_file_check_deny(fp, open->op_share_deny);
3453         if (status == nfs_ok) {
3454                 old_deny_bmap = stp->st_deny_bmap;
3455                 set_deny(open->op_share_deny, stp);
3456                 fp->fi_share_deny |=
3457                                 (open->op_share_deny & NFS4_SHARE_DENY_BOTH);
3458         }
3459         spin_unlock(&fp->fi_lock);
3460
3461         if (status != nfs_ok)
3462                 return status;
3463
3464         status = nfsd4_truncate(rqstp, cur_fh, open);
3465         if (status != nfs_ok)
3466                 reset_union_bmap_deny(old_deny_bmap, stp);
3467         return status;
3468 }
3469
3470 static void
3471 nfs4_set_claim_prev(struct nfsd4_open *open, bool has_session)
3472 {
3473         open->op_openowner->oo_flags |= NFS4_OO_CONFIRMED;
3474 }
3475
3476 /* Should we give out recallable state?: */
3477 static bool nfsd4_cb_channel_good(struct nfs4_client *clp)
3478 {
3479         if (clp->cl_cb_state == NFSD4_CB_UP)
3480                 return true;
3481         /*
3482          * In the sessions case, since we don't have to establish a
3483          * separate connection for callbacks, we assume it's OK
3484          * until we hear otherwise:
3485          */
3486         return clp->cl_minorversion && clp->cl_cb_state == NFSD4_CB_UNKNOWN;
3487 }
3488
3489 static struct file_lock *nfs4_alloc_init_lease(struct nfs4_file *fp, int flag)
3490 {
3491         struct file_lock *fl;
3492
3493         fl = locks_alloc_lock();
3494         if (!fl)
3495                 return NULL;
3496         locks_init_lock(fl);
3497         fl->fl_lmops = &nfsd_lease_mng_ops;
3498         fl->fl_flags = FL_DELEG;
3499         fl->fl_type = flag == NFS4_OPEN_DELEGATE_READ? F_RDLCK: F_WRLCK;
3500         fl->fl_end = OFFSET_MAX;
3501         fl->fl_owner = (fl_owner_t)fp;
3502         fl->fl_pid = current->tgid;
3503         return fl;
3504 }
3505
3506 static int nfs4_setlease(struct nfs4_delegation *dp)
3507 {
3508         struct nfs4_file *fp = dp->dl_stid.sc_file;
3509         struct file_lock *fl;
3510         struct file *filp;
3511         int status = 0;
3512
3513         fl = nfs4_alloc_init_lease(fp, NFS4_OPEN_DELEGATE_READ);
3514         if (!fl)
3515                 return -ENOMEM;
3516         filp = find_readable_file(fp);
3517         if (!filp) {
3518                 /* We should always have a readable file here */
3519                 WARN_ON_ONCE(1);
3520                 return -EBADF;
3521         }
3522         fl->fl_file = filp;
3523         status = vfs_setlease(filp, fl->fl_type, &fl);
3524         if (status) {
3525                 locks_free_lock(fl);
3526                 goto out_fput;
3527         }
3528         spin_lock(&state_lock);
3529         spin_lock(&fp->fi_lock);
3530         /* Did the lease get broken before we took the lock? */
3531         status = -EAGAIN;
3532         if (fp->fi_had_conflict)
3533                 goto out_unlock;
3534         /* Race breaker */
3535         if (fp->fi_lease) {
3536                 status = 0;
3537                 atomic_inc(&fp->fi_delegees);
3538                 hash_delegation_locked(dp, fp);
3539                 goto out_unlock;
3540         }
3541         fp->fi_lease = fl;
3542         fp->fi_deleg_file = filp;
3543         atomic_set(&fp->fi_delegees, 1);
3544         hash_delegation_locked(dp, fp);
3545         spin_unlock(&fp->fi_lock);
3546         spin_unlock(&state_lock);
3547         return 0;
3548 out_unlock:
3549         spin_unlock(&fp->fi_lock);
3550         spin_unlock(&state_lock);
3551 out_fput:
3552         fput(filp);
3553         return status;
3554 }
3555
3556 static struct nfs4_delegation *
3557 nfs4_set_delegation(struct nfs4_client *clp, struct svc_fh *fh,
3558                     struct nfs4_file *fp)
3559 {
3560         int status;
3561         struct nfs4_delegation *dp;
3562
3563         if (fp->fi_had_conflict)
3564                 return ERR_PTR(-EAGAIN);
3565
3566         dp = alloc_init_deleg(clp, fh);
3567         if (!dp)
3568                 return ERR_PTR(-ENOMEM);
3569
3570         get_nfs4_file(fp);
3571         spin_lock(&state_lock);
3572         spin_lock(&fp->fi_lock);
3573         dp->dl_stid.sc_file = fp;
3574         if (!fp->fi_lease) {
3575                 spin_unlock(&fp->fi_lock);
3576                 spin_unlock(&state_lock);
3577                 status = nfs4_setlease(dp);
3578                 goto out;
3579         }
3580         atomic_inc(&fp->fi_delegees);
3581         if (fp->fi_had_conflict) {
3582                 status = -EAGAIN;
3583                 goto out_unlock;
3584         }
3585         hash_delegation_locked(dp, fp);
3586         status = 0;
3587 out_unlock:
3588         spin_unlock(&fp->fi_lock);
3589         spin_unlock(&state_lock);
3590 out:
3591         if (status) {
3592                 nfs4_put_stid(&dp->dl_stid);
3593                 return ERR_PTR(status);
3594         }
3595         return dp;
3596 }
3597
3598 static void nfsd4_open_deleg_none_ext(struct nfsd4_open *open, int status)
3599 {
3600         open->op_delegate_type = NFS4_OPEN_DELEGATE_NONE_EXT;
3601         if (status == -EAGAIN)
3602                 open->op_why_no_deleg = WND4_CONTENTION;
3603         else {
3604                 open->op_why_no_deleg = WND4_RESOURCE;
3605                 switch (open->op_deleg_want) {
3606                 case NFS4_SHARE_WANT_READ_DELEG:
3607                 case NFS4_SHARE_WANT_WRITE_DELEG:
3608                 case NFS4_SHARE_WANT_ANY_DELEG:
3609                         break;
3610                 case NFS4_SHARE_WANT_CANCEL:
3611                         open->op_why_no_deleg = WND4_CANCELLED;
3612                         break;
3613                 case NFS4_SHARE_WANT_NO_DELEG:
3614                         WARN_ON_ONCE(1);
3615                 }
3616         }
3617 }
3618
3619 /*
3620  * Attempt to hand out a delegation.
3621  *
3622  * Note we don't support write delegations, and won't until the vfs has
3623  * proper support for them.
3624  */
3625 static void
3626 nfs4_open_delegation(struct svc_fh *fh, struct nfsd4_open *open,
3627                         struct nfs4_ol_stateid *stp)
3628 {
3629         struct nfs4_delegation *dp;
3630         struct nfs4_openowner *oo = openowner(stp->st_stateowner);
3631         struct nfs4_client *clp = stp->st_stid.sc_client;
3632         int cb_up;
3633         int status = 0;
3634
3635         cb_up = nfsd4_cb_channel_good(oo->oo_owner.so_client);
3636         open->op_recall = 0;
3637         switch (open->op_claim_type) {
3638                 case NFS4_OPEN_CLAIM_PREVIOUS:
3639                         if (!cb_up)
3640                                 open->op_recall = 1;
3641                         if (open->op_delegate_type != NFS4_OPEN_DELEGATE_READ)
3642                                 goto out_no_deleg;
3643                         break;
3644                 case NFS4_OPEN_CLAIM_NULL:
3645                 case NFS4_OPEN_CLAIM_FH:
3646                         /*
3647                          * Let's not give out any delegations till everyone's
3648                          * had the chance to reclaim theirs....
3649                          */
3650                         if (locks_in_grace(clp->net))
3651                                 goto out_no_deleg;
3652                         if (!cb_up || !(oo->oo_flags & NFS4_OO_CONFIRMED))
3653                                 goto out_no_deleg;
3654                         /*
3655                          * Also, if the file was opened for write or
3656                          * create, there's a good chance the client's
3657                          * about to write to it, resulting in an
3658                          * immediate recall (since we don't support
3659                          * write delegations):
3660                          */
3661                         if (open->op_share_access & NFS4_SHARE_ACCESS_WRITE)
3662                                 goto out_no_deleg;
3663                         if (open->op_create == NFS4_OPEN_CREATE)
3664                                 goto out_no_deleg;
3665                         break;
3666                 default:
3667                         goto out_no_deleg;
3668         }
3669         dp = nfs4_set_delegation(clp, fh, stp->st_stid.sc_file);
3670         if (IS_ERR(dp))
3671                 goto out_no_deleg;
3672
3673         memcpy(&open->op_delegate_stateid, &dp->dl_stid.sc_stateid, sizeof(dp->dl_stid.sc_stateid));
3674
3675         dprintk("NFSD: delegation stateid=" STATEID_FMT "\n",
3676                 STATEID_VAL(&dp->dl_stid.sc_stateid));
3677         open->op_delegate_type = NFS4_OPEN_DELEGATE_READ;
3678         return;
3679 out_no_deleg:
3680         open->op_delegate_type = NFS4_OPEN_DELEGATE_NONE;
3681         if (open->op_claim_type == NFS4_OPEN_CLAIM_PREVIOUS &&
3682             open->op_delegate_type != NFS4_OPEN_DELEGATE_NONE) {
3683                 dprintk("NFSD: WARNING: refusing delegation reclaim\n");
3684                 open->op_recall = 1;
3685         }
3686
3687         /* 4.1 client asking for a delegation? */
3688         if (open->op_deleg_want)
3689                 nfsd4_open_deleg_none_ext(open, status);
3690         return;
3691 }
3692
3693 static void nfsd4_deleg_xgrade_none_ext(struct nfsd4_open *open,
3694                                         struct nfs4_delegation *dp)
3695 {
3696         if (open->op_deleg_want == NFS4_SHARE_WANT_READ_DELEG &&
3697             dp->dl_type == NFS4_OPEN_DELEGATE_WRITE) {
3698                 open->op_delegate_type = NFS4_OPEN_DELEGATE_NONE_EXT;
3699                 open->op_why_no_deleg = WND4_NOT_SUPP_DOWNGRADE;
3700         } else if (open->op_deleg_want == NFS4_SHARE_WANT_WRITE_DELEG &&
3701                    dp->dl_type == NFS4_OPEN_DELEGATE_WRITE) {
3702                 open->op_delegate_type = NFS4_OPEN_DELEGATE_NONE_EXT;
3703                 open->op_why_no_deleg = WND4_NOT_SUPP_UPGRADE;
3704         }
3705         /* Otherwise the client must be confused wanting a delegation
3706          * it already has, therefore we don't return
3707          * NFS4_OPEN_DELEGATE_NONE_EXT and reason.
3708          */
3709 }
3710
3711 /*
3712  * called with nfs4_lock_state() held.
3713  */
3714 __be32
3715 nfsd4_process_open2(struct svc_rqst *rqstp, struct svc_fh *current_fh, struct nfsd4_open *open)
3716 {
3717         struct nfsd4_compoundres *resp = rqstp->rq_resp;
3718         struct nfs4_client *cl = open->op_openowner->oo_owner.so_client;
3719         struct nfs4_file *fp = NULL;
3720         struct nfs4_ol_stateid *stp = NULL;
3721         struct nfs4_delegation *dp = NULL;
3722         __be32 status;
3723
3724         /*
3725          * Lookup file; if found, lookup stateid and check open request,
3726          * and check for delegations in the process of being recalled.
3727          * If not found, create the nfs4_file struct
3728          */
3729         fp = find_or_add_file(open->op_file, &current_fh->fh_handle);
3730         if (fp != open->op_file) {
3731                 status = nfs4_check_deleg(cl, open, &dp);
3732                 if (status)
3733                         goto out;
3734                 stp = nfsd4_find_existing_open(fp, open);
3735         } else {
3736                 open->op_file = NULL;
3737                 status = nfserr_bad_stateid;
3738                 if (nfsd4_is_deleg_cur(open))
3739                         goto out;
3740                 status = nfserr_jukebox;
3741         }
3742
3743         /*
3744          * OPEN the file, or upgrade an existing OPEN.
3745          * If truncate fails, the OPEN fails.
3746          */
3747         if (stp) {
3748                 /* Stateid was found, this is an OPEN upgrade */
3749                 status = nfs4_upgrade_open(rqstp, fp, current_fh, stp, open);
3750                 if (status)
3751                         goto out;
3752         } else {
3753                 stp = open->op_stp;
3754                 open->op_stp = NULL;
3755                 init_open_stateid(stp, fp, open);
3756                 status = nfs4_get_vfs_file(rqstp, fp, current_fh, stp, open);
3757                 if (status) {
3758                         release_open_stateid(stp);
3759                         goto out;
3760                 }
3761         }
3762         update_stateid(&stp->st_stid.sc_stateid);
3763         memcpy(&open->op_stateid, &stp->st_stid.sc_stateid, sizeof(stateid_t));
3764
3765         if (nfsd4_has_session(&resp->cstate)) {
3766                 if (open->op_deleg_want & NFS4_SHARE_WANT_NO_DELEG) {
3767                         open->op_delegate_type = NFS4_OPEN_DELEGATE_NONE_EXT;
3768                         open->op_why_no_deleg = WND4_NOT_WANTED;
3769                         goto nodeleg;
3770                 }
3771         }
3772
3773         /*
3774         * Attempt to hand out a delegation. No error return, because the
3775         * OPEN succeeds even if we fail.
3776         */
3777         nfs4_open_delegation(current_fh, open, stp);
3778 nodeleg:
3779         status = nfs_ok;
3780
3781         dprintk("%s: stateid=" STATEID_FMT "\n", __func__,
3782                 STATEID_VAL(&stp->st_stid.sc_stateid));
3783 out:
3784         /* 4.1 client trying to upgrade/downgrade delegation? */
3785         if (open->op_delegate_type == NFS4_OPEN_DELEGATE_NONE && dp &&
3786             open->op_deleg_want)
3787                 nfsd4_deleg_xgrade_none_ext(open, dp);
3788
3789         if (fp)
3790                 put_nfs4_file(fp);
3791         if (status == 0 && open->op_claim_type == NFS4_OPEN_CLAIM_PREVIOUS)
3792                 nfs4_set_claim_prev(open, nfsd4_has_session(&resp->cstate));
3793         /*
3794         * To finish the open response, we just need to set the rflags.
3795         */
3796         open->op_rflags = NFS4_OPEN_RESULT_LOCKTYPE_POSIX;
3797         if (!(open->op_openowner->oo_flags & NFS4_OO_CONFIRMED) &&
3798             !nfsd4_has_session(&resp->cstate))
3799                 open->op_rflags |= NFS4_OPEN_RESULT_CONFIRM;
3800
3801         return status;
3802 }
3803
3804 void nfsd4_cleanup_open_state(struct nfsd4_open *open, __be32 status)
3805 {
3806         if (open->op_openowner) {
3807                 struct nfs4_openowner *oo = open->op_openowner;
3808
3809                 if (!list_empty(&oo->oo_owner.so_stateids))
3810                         list_del_init(&oo->oo_close_lru);
3811                 if (oo->oo_flags & NFS4_OO_NEW) {
3812                         if (status) {
3813                                 release_openowner(oo);
3814                                 open->op_openowner = NULL;
3815                         } else
3816                                 oo->oo_flags &= ~NFS4_OO_NEW;
3817                 }
3818         }
3819         if (open->op_file)
3820                 nfsd4_free_file(open->op_file);
3821         if (open->op_stp)
3822                 nfs4_put_stid(&open->op_stp->st_stid);
3823 }
3824
3825 __be32
3826 nfsd4_renew(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3827             clientid_t *clid)
3828 {
3829         struct nfs4_client *clp;
3830         __be32 status;
3831         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
3832
3833         nfs4_lock_state();
3834         dprintk("process_renew(%08x/%08x): starting\n", 
3835                         clid->cl_boot, clid->cl_id);
3836         status = lookup_clientid(clid, cstate, nn);
3837         if (status)
3838                 goto out;
3839         clp = cstate->clp;
3840         status = nfserr_cb_path_down;
3841         if (!list_empty(&clp->cl_delegations)
3842                         && clp->cl_cb_state != NFSD4_CB_UP)
3843                 goto out;
3844         status = nfs_ok;
3845 out:
3846         nfs4_unlock_state();
3847         return status;
3848 }
3849
3850 static void
3851 nfsd4_end_grace(struct nfsd_net *nn)
3852 {
3853         /* do nothing if grace period already ended */
3854         if (nn->grace_ended)
3855                 return;
3856
3857         dprintk("NFSD: end of grace period\n");
3858         nn->grace_ended = true;
3859         nfsd4_record_grace_done(nn, nn->boot_time);
3860         locks_end_grace(&nn->nfsd4_manager);
3861         /*
3862          * Now that every NFSv4 client has had the chance to recover and
3863          * to see the (possibly new, possibly shorter) lease time, we
3864          * can safely set the next grace time to the current lease time:
3865          */
3866         nn->nfsd4_grace = nn->nfsd4_lease;
3867 }
3868
3869 static time_t
3870 nfs4_laundromat(struct nfsd_net *nn)
3871 {
3872         struct nfs4_client *clp;
3873         struct nfs4_openowner *oo;
3874         struct nfs4_delegation *dp;
3875         struct list_head *pos, *next, reaplist;
3876         time_t cutoff = get_seconds() - nn->nfsd4_lease;
3877         time_t t, new_timeo = nn->nfsd4_lease;
3878
3879         nfs4_lock_state();
3880
3881         dprintk("NFSD: laundromat service - starting\n");
3882         nfsd4_end_grace(nn);
3883         INIT_LIST_HEAD(&reaplist);
3884         spin_lock(&nn->client_lock);
3885         list_for_each_safe(pos, next, &nn->client_lru) {
3886                 clp = list_entry(pos, struct nfs4_client, cl_lru);
3887                 if (time_after((unsigned long)clp->cl_time, (unsigned long)cutoff)) {
3888                         t = clp->cl_time - cutoff;
3889                         new_timeo = min(new_timeo, t);
3890                         break;
3891                 }
3892                 if (mark_client_expired_locked(clp)) {
3893                         dprintk("NFSD: client in use (clientid %08x)\n",
3894                                 clp->cl_clientid.cl_id);
3895                         continue;
3896                 }
3897                 list_move(&clp->cl_lru, &reaplist);
3898         }
3899         spin_unlock(&nn->client_lock);
3900         list_for_each_safe(pos, next, &reaplist) {
3901                 clp = list_entry(pos, struct nfs4_client, cl_lru);
3902                 dprintk("NFSD: purging unused client (clientid %08x)\n",
3903                         clp->cl_clientid.cl_id);
3904                 expire_client(clp);
3905         }
3906         spin_lock(&state_lock);
3907         list_for_each_safe(pos, next, &nn->del_recall_lru) {
3908                 dp = list_entry (pos, struct nfs4_delegation, dl_recall_lru);
3909                 if (net_generic(dp->dl_stid.sc_client->net, nfsd_net_id) != nn)
3910                         continue;
3911                 if (time_after((unsigned long)dp->dl_time, (unsigned long)cutoff)) {
3912                         t = dp->dl_time - cutoff;
3913                         new_timeo = min(new_timeo, t);
3914                         break;
3915                 }
3916                 unhash_delegation_locked(dp);
3917                 list_add(&dp->dl_recall_lru, &reaplist);
3918         }
3919         spin_unlock(&state_lock);
3920         while (!list_empty(&reaplist)) {
3921                 dp = list_first_entry(&reaplist, struct nfs4_delegation,
3922                                         dl_recall_lru);
3923                 list_del_init(&dp->dl_recall_lru);
3924                 revoke_delegation(dp);
3925         }
3926         list_for_each_safe(pos, next, &nn->close_lru) {
3927                 oo = container_of(pos, struct nfs4_openowner, oo_close_lru);
3928                 if (time_after((unsigned long)oo->oo_time, (unsigned long)cutoff)) {
3929                         t = oo->oo_time - cutoff;
3930                         new_timeo = min(new_timeo, t);
3931                         break;
3932                 }
3933                 release_openowner(oo);
3934         }
3935         new_timeo = max_t(time_t, new_timeo, NFSD_LAUNDROMAT_MINTIMEOUT);
3936         nfs4_unlock_state();
3937         return new_timeo;
3938 }
3939
3940 static struct workqueue_struct *laundry_wq;
3941 static void laundromat_main(struct work_struct *);
3942
3943 static void
3944 laundromat_main(struct work_struct *laundry)
3945 {
3946         time_t t;
3947         struct delayed_work *dwork = container_of(laundry, struct delayed_work,
3948                                                   work);
3949         struct nfsd_net *nn = container_of(dwork, struct nfsd_net,
3950                                            laundromat_work);
3951
3952         t = nfs4_laundromat(nn);
3953         dprintk("NFSD: laundromat_main - sleeping for %ld seconds\n", t);
3954         queue_delayed_work(laundry_wq, &nn->laundromat_work, t*HZ);
3955 }
3956
3957 static inline __be32 nfs4_check_fh(struct svc_fh *fhp, struct nfs4_ol_stateid *stp)
3958 {
3959         if (!nfsd_fh_match(&fhp->fh_handle, &stp->st_stid.sc_file->fi_fhandle))
3960                 return nfserr_bad_stateid;
3961         return nfs_ok;
3962 }
3963
3964 static inline int
3965 access_permit_read(struct nfs4_ol_stateid *stp)
3966 {
3967         return test_access(NFS4_SHARE_ACCESS_READ, stp) ||
3968                 test_access(NFS4_SHARE_ACCESS_BOTH, stp) ||
3969                 test_access(NFS4_SHARE_ACCESS_WRITE, stp);
3970 }
3971
3972 static inline int
3973 access_permit_write(struct nfs4_ol_stateid *stp)
3974 {
3975         return test_access(NFS4_SHARE_ACCESS_WRITE, stp) ||
3976                 test_access(NFS4_SHARE_ACCESS_BOTH, stp);
3977 }
3978
3979 static
3980 __be32 nfs4_check_openmode(struct nfs4_ol_stateid *stp, int flags)
3981 {
3982         __be32 status = nfserr_openmode;
3983
3984         /* For lock stateid's, we test the parent open, not the lock: */
3985         if (stp->st_openstp)
3986                 stp = stp->st_openstp;
3987         if ((flags & WR_STATE) && !access_permit_write(stp))
3988                 goto out;
3989         if ((flags & RD_STATE) && !access_permit_read(stp))
3990                 goto out;
3991         status = nfs_ok;
3992 out:
3993         return status;
3994 }
3995
3996 static inline __be32
3997 check_special_stateids(struct net *net, svc_fh *current_fh, stateid_t *stateid, int flags)
3998 {
3999         if (ONE_STATEID(stateid) && (flags & RD_STATE))
4000                 return nfs_ok;
4001         else if (locks_in_grace(net)) {
4002                 /* Answer in remaining cases depends on existence of
4003                  * conflicting state; so we must wait out the grace period. */
4004                 return nfserr_grace;
4005         } else if (flags & WR_STATE)
4006                 return nfs4_share_conflict(current_fh,
4007                                 NFS4_SHARE_DENY_WRITE);
4008         else /* (flags & RD_STATE) && ZERO_STATEID(stateid) */
4009                 return nfs4_share_conflict(current_fh,
4010                                 NFS4_SHARE_DENY_READ);
4011 }
4012
4013 /*
4014  * Allow READ/WRITE during grace period on recovered state only for files
4015  * that are not able to provide mandatory locking.
4016  */
4017 static inline int
4018 grace_disallows_io(struct net *net, struct inode *inode)
4019 {
4020         return locks_in_grace(net) && mandatory_lock(inode);
4021 }
4022
4023 /* Returns true iff a is later than b: */
4024 static bool stateid_generation_after(stateid_t *a, stateid_t *b)
4025 {
4026         return (s32)(a->si_generation - b->si_generation) > 0;
4027 }
4028
4029 static __be32 check_stateid_generation(stateid_t *in, stateid_t *ref, bool has_session)
4030 {
4031         /*
4032          * When sessions are used the stateid generation number is ignored
4033          * when it is zero.
4034          */
4035         if (has_session && in->si_generation == 0)
4036                 return nfs_ok;
4037
4038         if (in->si_generation == ref->si_generation)
4039                 return nfs_ok;
4040
4041         /* If the client sends us a stateid from the future, it's buggy: */
4042         if (stateid_generation_after(in, ref))
4043                 return nfserr_bad_stateid;
4044         /*
4045          * However, we could see a stateid from the past, even from a
4046          * non-buggy client.  For example, if the client sends a lock
4047          * while some IO is outstanding, the lock may bump si_generation
4048          * while the IO is still in flight.  The client could avoid that
4049          * situation by waiting for responses on all the IO requests,
4050          * but better performance may result in retrying IO that
4051          * receives an old_stateid error if requests are rarely
4052          * reordered in flight:
4053          */
4054         return nfserr_old_stateid;
4055 }
4056
4057 static __be32 nfsd4_validate_stateid(struct nfs4_client *cl, stateid_t *stateid)
4058 {
4059         struct nfs4_stid *s;
4060         struct nfs4_ol_stateid *ols;
4061         __be32 status;
4062
4063         if (ZERO_STATEID(stateid) || ONE_STATEID(stateid))
4064                 return nfserr_bad_stateid;
4065         /* Client debugging aid. */
4066         if (!same_clid(&stateid->si_opaque.so_clid, &cl->cl_clientid)) {
4067                 char addr_str[INET6_ADDRSTRLEN];
4068                 rpc_ntop((struct sockaddr *)&cl->cl_addr, addr_str,
4069                                  sizeof(addr_str));
4070                 pr_warn_ratelimited("NFSD: client %s testing state ID "
4071                                         "with incorrect client ID\n", addr_str);
4072                 return nfserr_bad_stateid;
4073         }
4074         s = find_stateid(cl, stateid);
4075         if (!s)
4076                 return nfserr_bad_stateid;
4077         status = check_stateid_generation(stateid, &s->sc_stateid, 1);
4078         if (status)
4079                 return status;
4080         switch (s->sc_type) {
4081         case NFS4_DELEG_STID:
4082                 return nfs_ok;
4083         case NFS4_REVOKED_DELEG_STID:
4084                 return nfserr_deleg_revoked;
4085         case NFS4_OPEN_STID:
4086         case NFS4_LOCK_STID:
4087                 ols = openlockstateid(s);
4088                 if (ols->st_stateowner->so_is_open_owner
4089                                 && !(openowner(ols->st_stateowner)->oo_flags
4090                                                 & NFS4_OO_CONFIRMED))
4091                         return nfserr_bad_stateid;
4092                 return nfs_ok;
4093         default:
4094                 printk("unknown stateid type %x\n", s->sc_type);
4095                 /* Fallthrough */
4096         case NFS4_CLOSED_STID:
4097         case NFS4_CLOSED_DELEG_STID:
4098                 return nfserr_bad_stateid;
4099         }
4100 }
4101
4102 static __be32
4103 nfsd4_lookup_stateid(struct nfsd4_compound_state *cstate,
4104                      stateid_t *stateid, unsigned char typemask,
4105                      struct nfs4_stid **s, struct nfsd_net *nn)
4106 {
4107         __be32 status;
4108
4109         if (ZERO_STATEID(stateid) || ONE_STATEID(stateid))
4110                 return nfserr_bad_stateid;
4111         status = lookup_clientid(&stateid->si_opaque.so_clid, cstate, nn);
4112         if (status == nfserr_stale_clientid) {
4113                 if (cstate->session)
4114                         return nfserr_bad_stateid;
4115                 return nfserr_stale_stateid;
4116         }
4117         if (status)
4118                 return status;
4119         *s = find_stateid_by_type(cstate->clp, stateid, typemask);
4120         if (!*s)
4121                 return nfserr_bad_stateid;
4122         return nfs_ok;
4123 }
4124
4125 /*
4126 * Checks for stateid operations
4127 */
4128 __be32
4129 nfs4_preprocess_stateid_op(struct net *net, struct nfsd4_compound_state *cstate,
4130                            stateid_t *stateid, int flags, struct file **filpp)
4131 {
4132         struct nfs4_stid *s;
4133         struct nfs4_ol_stateid *stp = NULL;
4134         struct nfs4_delegation *dp = NULL;
4135         struct svc_fh *current_fh = &cstate->current_fh;
4136         struct inode *ino = current_fh->fh_dentry->d_inode;
4137         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
4138         struct file *file = NULL;
4139         __be32 status;
4140
4141         if (filpp)
4142                 *filpp = NULL;
4143
4144         if (grace_disallows_io(net, ino))
4145                 return nfserr_grace;
4146
4147         if (ZERO_STATEID(stateid) || ONE_STATEID(stateid))
4148                 return check_special_stateids(net, current_fh, stateid, flags);
4149
4150         nfs4_lock_state();
4151
4152         status = nfsd4_lookup_stateid(cstate, stateid,
4153                                 NFS4_DELEG_STID|NFS4_OPEN_STID|NFS4_LOCK_STID,
4154                                 &s, nn);
4155         if (status)
4156                 goto out;
4157         status = check_stateid_generation(stateid, &s->sc_stateid, nfsd4_has_session(cstate));
4158         if (status)
4159                 goto out;
4160         switch (s->sc_type) {
4161         case NFS4_DELEG_STID:
4162                 dp = delegstateid(s);
4163                 status = nfs4_check_delegmode(dp, flags);
4164                 if (status)
4165                         goto out;
4166                 if (filpp) {
4167                         file = dp->dl_stid.sc_file->fi_deleg_file;
4168                         if (!file) {
4169                                 WARN_ON_ONCE(1);
4170                                 status = nfserr_serverfault;
4171                                 goto out;
4172                         }
4173                         get_file(file);
4174                 }
4175                 break;
4176         case NFS4_OPEN_STID:
4177         case NFS4_LOCK_STID:
4178                 stp = openlockstateid(s);
4179                 status = nfs4_check_fh(current_fh, stp);
4180                 if (status)
4181                         goto out;
4182                 if (stp->st_stateowner->so_is_open_owner
4183                     && !(openowner(stp->st_stateowner)->oo_flags & NFS4_OO_CONFIRMED))
4184                         goto out;
4185                 status = nfs4_check_openmode(stp, flags);
4186                 if (status)
4187                         goto out;
4188                 if (filpp) {
4189                         struct nfs4_file *fp = stp->st_stid.sc_file;
4190
4191                         if (flags & RD_STATE)
4192                                 file = find_readable_file(fp);
4193                         else
4194                                 file = find_writeable_file(fp);
4195                 }
4196                 break;
4197         default:
4198                 status = nfserr_bad_stateid;
4199                 goto out;
4200         }
4201         status = nfs_ok;
4202         if (file)
4203                 *filpp = file;
4204 out:
4205         nfs4_unlock_state();
4206         return status;
4207 }
4208
4209 static __be32
4210 nfsd4_free_lock_stateid(struct nfs4_ol_stateid *stp)
4211 {
4212         struct nfs4_lockowner *lo = lockowner(stp->st_stateowner);
4213
4214         if (check_for_locks(stp->st_stid.sc_file, lo))
4215                 return nfserr_locks_held;
4216         release_lockowner_if_empty(lo);
4217         return nfs_ok;
4218 }
4219
4220 /*
4221  * Test if the stateid is valid
4222  */
4223 __be32
4224 nfsd4_test_stateid(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
4225                    struct nfsd4_test_stateid *test_stateid)
4226 {
4227         struct nfsd4_test_stateid_id *stateid;
4228         struct nfs4_client *cl = cstate->session->se_client;
4229
4230         nfs4_lock_state();
4231         list_for_each_entry(stateid, &test_stateid->ts_stateid_list, ts_id_list)
4232                 stateid->ts_id_status =
4233                         nfsd4_validate_stateid(cl, &stateid->ts_id_stateid);
4234         nfs4_unlock_state();
4235
4236         return nfs_ok;
4237 }
4238
4239 __be32
4240 nfsd4_free_stateid(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
4241                    struct nfsd4_free_stateid *free_stateid)
4242 {
4243         stateid_t *stateid = &free_stateid->fr_stateid;
4244         struct nfs4_stid *s;
4245         struct nfs4_delegation *dp;
4246         struct nfs4_client *cl = cstate->session->se_client;
4247         __be32 ret = nfserr_bad_stateid;
4248
4249         nfs4_lock_state();
4250         s = find_stateid(cl, stateid);
4251         if (!s)
4252                 goto out;
4253         switch (s->sc_type) {
4254         case NFS4_DELEG_STID:
4255                 ret = nfserr_locks_held;
4256                 goto out;
4257         case NFS4_OPEN_STID:
4258         case NFS4_LOCK_STID:
4259                 ret = check_stateid_generation(stateid, &s->sc_stateid, 1);
4260                 if (ret)
4261                         goto out;
4262                 if (s->sc_type == NFS4_LOCK_STID)
4263                         ret = nfsd4_free_lock_stateid(openlockstateid(s));
4264                 else
4265                         ret = nfserr_locks_held;
4266                 break;
4267         case NFS4_REVOKED_DELEG_STID:
4268                 dp = delegstateid(s);
4269                 spin_lock(&cl->cl_lock);
4270                 list_del_init(&dp->dl_recall_lru);
4271                 spin_unlock(&cl->cl_lock);
4272                 nfs4_put_stid(s);
4273                 ret = nfs_ok;
4274                 break;
4275         default:
4276                 ret = nfserr_bad_stateid;
4277         }
4278 out:
4279         nfs4_unlock_state();
4280         return ret;
4281 }
4282
4283 static inline int
4284 setlkflg (int type)
4285 {
4286         return (type == NFS4_READW_LT || type == NFS4_READ_LT) ?
4287                 RD_STATE : WR_STATE;
4288 }
4289
4290 static __be32 nfs4_seqid_op_checks(struct nfsd4_compound_state *cstate, stateid_t *stateid, u32 seqid, struct nfs4_ol_stateid *stp)
4291 {
4292         struct svc_fh *current_fh = &cstate->current_fh;
4293         struct nfs4_stateowner *sop = stp->st_stateowner;
4294         __be32 status;
4295
4296         status = nfsd4_check_seqid(cstate, sop, seqid);
4297         if (status)
4298                 return status;
4299         if (stp->st_stid.sc_type == NFS4_CLOSED_STID
4300                 || stp->st_stid.sc_type == NFS4_REVOKED_DELEG_STID)
4301                 /*
4302                  * "Closed" stateid's exist *only* to return
4303                  * nfserr_replay_me from the previous step, and
4304                  * revoked delegations are kept only for free_stateid.
4305                  */
4306                 return nfserr_bad_stateid;
4307         status = check_stateid_generation(stateid, &stp->st_stid.sc_stateid, nfsd4_has_session(cstate));
4308         if (status)
4309                 return status;
4310         return nfs4_check_fh(current_fh, stp);
4311 }
4312
4313 /* 
4314  * Checks for sequence id mutating operations. 
4315  */
4316 static __be32
4317 nfs4_preprocess_seqid_op(struct nfsd4_compound_state *cstate, u32 seqid,
4318                          stateid_t *stateid, char typemask,
4319                          struct nfs4_ol_stateid **stpp,
4320                          struct nfsd_net *nn)
4321 {
4322         __be32 status;
4323         struct nfs4_stid *s;
4324         struct nfs4_ol_stateid *stp = NULL;
4325
4326         dprintk("NFSD: %s: seqid=%d stateid = " STATEID_FMT "\n", __func__,
4327                 seqid, STATEID_VAL(stateid));
4328
4329         *stpp = NULL;
4330         status = nfsd4_lookup_stateid(cstate, stateid, typemask, &s, nn);
4331         if (status)
4332                 return status;
4333         stp = openlockstateid(s);
4334         if (!nfsd4_has_session(cstate))
4335                 cstate->replay_owner = stp->st_stateowner;
4336
4337         status = nfs4_seqid_op_checks(cstate, stateid, seqid, stp);
4338         if (!status)
4339                 *stpp = stp;
4340         return status;
4341 }
4342
4343 static __be32 nfs4_preprocess_confirmed_seqid_op(struct nfsd4_compound_state *cstate, u32 seqid,
4344                                                  stateid_t *stateid, struct nfs4_ol_stateid **stpp, struct nfsd_net *nn)
4345 {
4346         __be32 status;
4347         struct nfs4_openowner *oo;
4348
4349         status = nfs4_preprocess_seqid_op(cstate, seqid, stateid,
4350                                                 NFS4_OPEN_STID, stpp, nn);
4351         if (status)
4352                 return status;
4353         oo = openowner((*stpp)->st_stateowner);
4354         if (!(oo->oo_flags & NFS4_OO_CONFIRMED))
4355                 return nfserr_bad_stateid;
4356         return nfs_ok;
4357 }
4358
4359 __be32
4360 nfsd4_open_confirm(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
4361                    struct nfsd4_open_confirm *oc)
4362 {
4363         __be32 status;
4364         struct nfs4_openowner *oo;
4365         struct nfs4_ol_stateid *stp;
4366         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
4367
4368         dprintk("NFSD: nfsd4_open_confirm on file %pd\n",
4369                         cstate->current_fh.fh_dentry);
4370
4371         status = fh_verify(rqstp, &cstate->current_fh, S_IFREG, 0);
4372         if (status)
4373                 return status;
4374
4375         nfs4_lock_state();
4376
4377         status = nfs4_preprocess_seqid_op(cstate,
4378                                         oc->oc_seqid, &oc->oc_req_stateid,
4379                                         NFS4_OPEN_STID, &stp, nn);
4380         if (status)
4381                 goto out;
4382         oo = openowner(stp->st_stateowner);
4383         status = nfserr_bad_stateid;
4384         if (oo->oo_flags & NFS4_OO_CONFIRMED)
4385                 goto out;
4386         oo->oo_flags |= NFS4_OO_CONFIRMED;
4387         update_stateid(&stp->st_stid.sc_stateid);
4388         memcpy(&oc->oc_resp_stateid, &stp->st_stid.sc_stateid, sizeof(stateid_t));
4389         dprintk("NFSD: %s: success, seqid=%d stateid=" STATEID_FMT "\n",
4390                 __func__, oc->oc_seqid, STATEID_VAL(&stp->st_stid.sc_stateid));
4391
4392         nfsd4_client_record_create(oo->oo_owner.so_client);
4393         status = nfs_ok;
4394 out:
4395         nfsd4_bump_seqid(cstate, status);
4396         if (!cstate->replay_owner)
4397                 nfs4_unlock_state();
4398         return status;
4399 }
4400
4401 static inline void nfs4_stateid_downgrade_bit(struct nfs4_ol_stateid *stp, u32 access)
4402 {
4403         if (!test_access(access, stp))
4404                 return;
4405         nfs4_file_put_access(stp->st_stid.sc_file, access);
4406         clear_access(access, stp);
4407 }
4408
4409 static inline void nfs4_stateid_downgrade(struct nfs4_ol_stateid *stp, u32 to_access)
4410 {
4411         switch (to_access) {
4412         case NFS4_SHARE_ACCESS_READ:
4413                 nfs4_stateid_downgrade_bit(stp, NFS4_SHARE_ACCESS_WRITE);
4414                 nfs4_stateid_downgrade_bit(stp, NFS4_SHARE_ACCESS_BOTH);
4415                 break;
4416         case NFS4_SHARE_ACCESS_WRITE:
4417                 nfs4_stateid_downgrade_bit(stp, NFS4_SHARE_ACCESS_READ);
4418                 nfs4_stateid_downgrade_bit(stp, NFS4_SHARE_ACCESS_BOTH);
4419                 break;
4420         case NFS4_SHARE_ACCESS_BOTH:
4421                 break;
4422         default:
4423                 WARN_ON_ONCE(1);
4424         }
4425 }
4426
4427 __be32
4428 nfsd4_open_downgrade(struct svc_rqst *rqstp,
4429                      struct nfsd4_compound_state *cstate,
4430                      struct nfsd4_open_downgrade *od)
4431 {
4432         __be32 status;
4433         struct nfs4_ol_stateid *stp;
4434         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
4435
4436         dprintk("NFSD: nfsd4_open_downgrade on file %pd\n", 
4437                         cstate->current_fh.fh_dentry);
4438
4439         /* We don't yet support WANT bits: */
4440         if (od->od_deleg_want)
4441                 dprintk("NFSD: %s: od_deleg_want=0x%x ignored\n", __func__,
4442                         od->od_deleg_want);
4443
4444         nfs4_lock_state();
4445         status = nfs4_preprocess_confirmed_seqid_op(cstate, od->od_seqid,
4446                                         &od->od_stateid, &stp, nn);
4447         if (status)
4448                 goto out; 
4449         status = nfserr_inval;
4450         if (!test_access(od->od_share_access, stp)) {
4451                 dprintk("NFSD: access not a subset of current bitmap: 0x%hhx, input access=%08x\n",
4452                         stp->st_access_bmap, od->od_share_access);
4453                 goto out;
4454         }
4455         if (!test_deny(od->od_share_deny, stp)) {
4456                 dprintk("NFSD: deny not a subset of current bitmap: 0x%hhx, input deny=%08x\n",
4457                         stp->st_deny_bmap, od->od_share_deny);
4458                 goto out;
4459         }
4460         nfs4_stateid_downgrade(stp, od->od_share_access);
4461
4462         reset_union_bmap_deny(od->od_share_deny, stp);
4463
4464         update_stateid(&stp->st_stid.sc_stateid);
4465         memcpy(&od->od_stateid, &stp->st_stid.sc_stateid, sizeof(stateid_t));
4466         status = nfs_ok;
4467 out:
4468         nfsd4_bump_seqid(cstate, status);
4469         if (!cstate->replay_owner)
4470                 nfs4_unlock_state();
4471         return status;
4472 }
4473
4474 static void nfsd4_close_open_stateid(struct nfs4_ol_stateid *s)
4475 {
4476         struct nfs4_client *clp = s->st_stid.sc_client;
4477         struct nfs4_openowner *oo = openowner(s->st_stateowner);
4478
4479         s->st_stid.sc_type = NFS4_CLOSED_STID;
4480         unhash_open_stateid(s);
4481
4482         if (clp->cl_minorversion) {
4483                 if (list_empty(&oo->oo_owner.so_stateids))
4484                         release_openowner(oo);
4485                 nfs4_put_stid(&s->st_stid);
4486         } else {
4487                 /*
4488                  * In the 4.0 case we need to keep the owners around a
4489                  * little while to handle CLOSE replay. We still do need
4490                  * to release any file access that is held by them
4491                  * before returning however.
4492                  */
4493                 release_all_access(s);
4494                 if (s->st_stid.sc_file) {
4495                         put_nfs4_file(s->st_stid.sc_file);
4496                         s->st_stid.sc_file = NULL;
4497                 }
4498                 oo->oo_last_closed_stid = s;
4499                 if (list_empty(&oo->oo_owner.so_stateids))
4500                         move_to_close_lru(oo, clp->net);
4501         }
4502 }
4503
4504 /*
4505  * nfs4_unlock_state() called after encode
4506  */
4507 __be32
4508 nfsd4_close(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
4509             struct nfsd4_close *close)
4510 {
4511         __be32 status;
4512         struct nfs4_ol_stateid *stp;
4513         struct net *net = SVC_NET(rqstp);
4514         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
4515
4516         dprintk("NFSD: nfsd4_close on file %pd\n", 
4517                         cstate->current_fh.fh_dentry);
4518
4519         nfs4_lock_state();
4520         status = nfs4_preprocess_seqid_op(cstate, close->cl_seqid,
4521                                         &close->cl_stateid,
4522                                         NFS4_OPEN_STID|NFS4_CLOSED_STID,
4523                                         &stp, nn);
4524         nfsd4_bump_seqid(cstate, status);
4525         if (status)
4526                 goto out; 
4527         update_stateid(&stp->st_stid.sc_stateid);
4528         memcpy(&close->cl_stateid, &stp->st_stid.sc_stateid, sizeof(stateid_t));
4529
4530         nfsd4_close_open_stateid(stp);
4531 out:
4532         if (!cstate->replay_owner)
4533                 nfs4_unlock_state();
4534         return status;
4535 }
4536
4537 __be32
4538 nfsd4_delegreturn(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
4539                   struct nfsd4_delegreturn *dr)
4540 {
4541         struct nfs4_delegation *dp;
4542         stateid_t *stateid = &dr->dr_stateid;
4543         struct nfs4_stid *s;
4544         __be32 status;
4545         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
4546
4547         if ((status = fh_verify(rqstp, &cstate->current_fh, S_IFREG, 0)))
4548                 return status;
4549
4550         nfs4_lock_state();
4551         status = nfsd4_lookup_stateid(cstate, stateid, NFS4_DELEG_STID, &s, nn);
4552         if (status)
4553                 goto out;
4554         dp = delegstateid(s);
4555         status = check_stateid_generation(stateid, &dp->dl_stid.sc_stateid, nfsd4_has_session(cstate));
4556         if (status)
4557                 goto out;
4558
4559         destroy_delegation(dp);
4560 out:
4561         nfs4_unlock_state();
4562
4563         return status;
4564 }
4565
4566
4567 #define LOFF_OVERFLOW(start, len)      ((u64)(len) > ~(u64)(start))
4568
4569 static inline u64
4570 end_offset(u64 start, u64 len)
4571 {
4572         u64 end;
4573
4574         end = start + len;
4575         return end >= start ? end: NFS4_MAX_UINT64;
4576 }
4577
4578 /* last octet in a range */
4579 static inline u64
4580 last_byte_offset(u64 start, u64 len)
4581 {
4582         u64 end;
4583
4584         WARN_ON_ONCE(!len);
4585         end = start + len;
4586         return end > start ? end - 1: NFS4_MAX_UINT64;
4587 }
4588
4589 /*
4590  * TODO: Linux file offsets are _signed_ 64-bit quantities, which means that
4591  * we can't properly handle lock requests that go beyond the (2^63 - 1)-th
4592  * byte, because of sign extension problems.  Since NFSv4 calls for 64-bit
4593  * locking, this prevents us from being completely protocol-compliant.  The
4594  * real solution to this problem is to start using unsigned file offsets in
4595  * the VFS, but this is a very deep change!
4596  */
4597 static inline void
4598 nfs4_transform_lock_offset(struct file_lock *lock)
4599 {
4600         if (lock->fl_start < 0)
4601                 lock->fl_start = OFFSET_MAX;
4602         if (lock->fl_end < 0)
4603                 lock->fl_end = OFFSET_MAX;
4604 }
4605
4606 /* Hack!: For now, we're defining this just so we can use a pointer to it
4607  * as a unique cookie to identify our (NFSv4's) posix locks. */
4608 static const struct lock_manager_operations nfsd_posix_mng_ops  = {
4609 };
4610
4611 static inline void
4612 nfs4_set_lock_denied(struct file_lock *fl, struct nfsd4_lock_denied *deny)
4613 {
4614         struct nfs4_lockowner *lo;
4615
4616         if (fl->fl_lmops == &nfsd_posix_mng_ops) {
4617                 lo = (struct nfs4_lockowner *) fl->fl_owner;
4618                 deny->ld_owner.data = kmemdup(lo->lo_owner.so_owner.data,
4619                                         lo->lo_owner.so_owner.len, GFP_KERNEL);
4620                 if (!deny->ld_owner.data)
4621                         /* We just don't care that much */
4622                         goto nevermind;
4623                 deny->ld_owner.len = lo->lo_owner.so_owner.len;
4624                 deny->ld_clientid = lo->lo_owner.so_client->cl_clientid;
4625         } else {
4626 nevermind:
4627                 deny->ld_owner.len = 0;
4628                 deny->ld_owner.data = NULL;
4629                 deny->ld_clientid.cl_boot = 0;
4630                 deny->ld_clientid.cl_id = 0;
4631         }
4632         deny->ld_start = fl->fl_start;
4633         deny->ld_length = NFS4_MAX_UINT64;
4634         if (fl->fl_end != NFS4_MAX_UINT64)
4635                 deny->ld_length = fl->fl_end - fl->fl_start + 1;        
4636         deny->ld_type = NFS4_READ_LT;
4637         if (fl->fl_type != F_RDLCK)
4638                 deny->ld_type = NFS4_WRITE_LT;
4639 }
4640
4641 static struct nfs4_lockowner *
4642 find_lockowner_str(clientid_t *clid, struct xdr_netobj *owner,
4643                 struct nfsd_net *nn)
4644 {
4645         unsigned int strhashval = ownerstr_hashval(clid->cl_id, owner);
4646         struct nfs4_stateowner *so;
4647
4648         list_for_each_entry(so, &nn->ownerstr_hashtbl[strhashval], so_strhash) {
4649                 if (so->so_is_open_owner)
4650                         continue;
4651                 if (!same_owner_str(so, owner, clid))
4652                         continue;
4653                 return lockowner(so);
4654         }
4655         return NULL;
4656 }
4657
4658 /*
4659  * Alloc a lock owner structure.
4660  * Called in nfsd4_lock - therefore, OPEN and OPEN_CONFIRM (if needed) has 
4661  * occurred. 
4662  *
4663  * strhashval = ownerstr_hashval
4664  */
4665 static struct nfs4_lockowner *
4666 alloc_init_lock_stateowner(unsigned int strhashval, struct nfs4_client *clp, struct nfs4_ol_stateid *open_stp, struct nfsd4_lock *lock) {
4667         struct nfs4_lockowner *lo;
4668         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
4669
4670         lo = alloc_stateowner(lockowner_slab, &lock->lk_new_owner, clp);
4671         if (!lo)
4672                 return NULL;
4673         INIT_LIST_HEAD(&lo->lo_owner.so_stateids);
4674         lo->lo_owner.so_is_open_owner = 0;
4675         /* It is the openowner seqid that will be incremented in encode in the
4676          * case of new lockowners; so increment the lock seqid manually: */
4677         lo->lo_owner.so_seqid = lock->lk_new_lock_seqid + 1;
4678         list_add(&lo->lo_owner.so_strhash, &nn->ownerstr_hashtbl[strhashval]);
4679         return lo;
4680 }
4681
4682 static struct nfs4_ol_stateid *
4683 alloc_init_lock_stateid(struct nfs4_lockowner *lo, struct nfs4_file *fp,
4684                 struct inode *inode,
4685                 struct nfs4_ol_stateid *open_stp)
4686 {
4687         struct nfs4_ol_stateid *stp;
4688         struct nfs4_client *clp = lo->lo_owner.so_client;
4689
4690         stp = nfs4_alloc_stateid(clp);
4691         if (stp == NULL)
4692                 return NULL;
4693         stp->st_stid.sc_type = NFS4_LOCK_STID;
4694         list_add(&stp->st_perstateowner, &lo->lo_owner.so_stateids);
4695         stp->st_stateowner = &lo->lo_owner;
4696         get_nfs4_file(fp);
4697         stp->st_stid.sc_file = fp;
4698         stp->st_access_bmap = 0;
4699         stp->st_deny_bmap = open_stp->st_deny_bmap;
4700         stp->st_openstp = open_stp;
4701         list_add(&stp->st_locks, &open_stp->st_locks);
4702         spin_lock(&fp->fi_lock);
4703         list_add(&stp->st_perfile, &fp->fi_stateids);
4704         spin_unlock(&fp->fi_lock);
4705         return stp;
4706 }
4707
4708 static struct nfs4_ol_stateid *
4709 find_lock_stateid(struct nfs4_lockowner *lo, struct nfs4_file *fp)
4710 {
4711         struct nfs4_ol_stateid *lst;
4712
4713         list_for_each_entry(lst, &lo->lo_owner.so_stateids, st_perstateowner) {
4714                 if (lst->st_stid.sc_file == fp)
4715                         return lst;
4716         }
4717         return NULL;
4718 }
4719
4720
4721 static int
4722 check_lock_length(u64 offset, u64 length)
4723 {
4724         return ((length == 0)  || ((length != NFS4_MAX_UINT64) &&
4725              LOFF_OVERFLOW(offset, length)));
4726 }
4727
4728 static void get_lock_access(struct nfs4_ol_stateid *lock_stp, u32 access)
4729 {
4730         struct nfs4_file *fp = lock_stp->st_stid.sc_file;
4731
4732         lockdep_assert_held(&fp->fi_lock);
4733
4734         if (test_access(access, lock_stp))
4735                 return;
4736         __nfs4_file_get_access(fp, access);
4737         set_access(access, lock_stp);
4738 }
4739
4740 static __be32 lookup_or_create_lock_state(struct nfsd4_compound_state *cstate, struct nfs4_ol_stateid *ost, struct nfsd4_lock *lock, struct nfs4_ol_stateid **lst, bool *new)
4741 {
4742         struct nfs4_file *fi = ost->st_stid.sc_file;
4743         struct nfs4_openowner *oo = openowner(ost->st_stateowner);
4744         struct nfs4_client *cl = oo->oo_owner.so_client;
4745         struct inode *inode = cstate->current_fh.fh_dentry->d_inode;
4746         struct nfs4_lockowner *lo;
4747         unsigned int strhashval;
4748         struct nfsd_net *nn = net_generic(cl->net, nfsd_net_id);
4749
4750         lo = find_lockowner_str(&cl->cl_clientid, &lock->v.new.owner, nn);
4751         if (!lo) {
4752                 strhashval = ownerstr_hashval(cl->cl_clientid.cl_id,
4753                                 &lock->v.new.owner);
4754                 lo = alloc_init_lock_stateowner(strhashval, cl, ost, lock);
4755                 if (lo == NULL)
4756                         return nfserr_jukebox;
4757         } else {
4758                 /* with an existing lockowner, seqids must be the same */
4759                 if (!cstate->minorversion &&
4760                     lock->lk_new_lock_seqid != lo->lo_owner.so_seqid)
4761                         return nfserr_bad_seqid;
4762         }
4763
4764         *lst = find_lock_stateid(lo, fi);
4765         if (*lst == NULL) {
4766                 *lst = alloc_init_lock_stateid(lo, fi, inode, ost);
4767                 if (*lst == NULL) {
4768                         release_lockowner_if_empty(lo);
4769                         return nfserr_jukebox;
4770                 }
4771                 *new = true;
4772         }
4773         return nfs_ok;
4774 }
4775
4776 /*
4777  *  LOCK operation 
4778  */
4779 __be32
4780 nfsd4_lock(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
4781            struct nfsd4_lock *lock)
4782 {
4783         struct nfs4_openowner *open_sop = NULL;
4784         struct nfs4_lockowner *lock_sop = NULL;
4785         struct nfs4_ol_stateid *lock_stp;
4786         struct nfs4_file *fp;
4787         struct file *filp = NULL;
4788         struct file_lock *file_lock = NULL;
4789         struct file_lock *conflock = NULL;
4790         __be32 status = 0;
4791         bool new_state = false;
4792         int lkflg;
4793         int err;
4794         struct net *net = SVC_NET(rqstp);
4795         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
4796
4797         dprintk("NFSD: nfsd4_lock: start=%Ld length=%Ld\n",
4798                 (long long) lock->lk_offset,
4799                 (long long) lock->lk_length);
4800
4801         if (check_lock_length(lock->lk_offset, lock->lk_length))
4802                  return nfserr_inval;
4803
4804         if ((status = fh_verify(rqstp, &cstate->current_fh,
4805                                 S_IFREG, NFSD_MAY_LOCK))) {
4806                 dprintk("NFSD: nfsd4_lock: permission denied!\n");
4807                 return status;
4808         }
4809
4810         nfs4_lock_state();
4811
4812         if (lock->lk_is_new) {
4813                 struct nfs4_ol_stateid *open_stp = NULL;
4814
4815                 if (nfsd4_has_session(cstate))
4816                         /* See rfc 5661 18.10.3: given clientid is ignored: */
4817                         memcpy(&lock->v.new.clientid,
4818                                 &cstate->session->se_client->cl_clientid,
4819                                 sizeof(clientid_t));
4820
4821                 status = nfserr_stale_clientid;
4822                 if (STALE_CLIENTID(&lock->lk_new_clientid, nn))
4823                         goto out;
4824
4825                 /* validate and update open stateid and open seqid */
4826                 status = nfs4_preprocess_confirmed_seqid_op(cstate,
4827                                         lock->lk_new_open_seqid,
4828                                         &lock->lk_new_open_stateid,
4829                                         &open_stp, nn);
4830                 if (status)
4831                         goto out;
4832                 open_sop = openowner(open_stp->st_stateowner);
4833                 status = nfserr_bad_stateid;
4834                 if (!same_clid(&open_sop->oo_owner.so_client->cl_clientid,
4835                                                 &lock->v.new.clientid))
4836                         goto out;
4837                 status = lookup_or_create_lock_state(cstate, open_stp, lock,
4838                                                         &lock_stp, &new_state);
4839         } else
4840                 status = nfs4_preprocess_seqid_op(cstate,
4841                                        lock->lk_old_lock_seqid,
4842                                        &lock->lk_old_lock_stateid,
4843                                        NFS4_LOCK_STID, &lock_stp, nn);
4844         if (status)
4845                 goto out;
4846         lock_sop = lockowner(lock_stp->st_stateowner);
4847
4848         lkflg = setlkflg(lock->lk_type);
4849         status = nfs4_check_openmode(lock_stp, lkflg);
4850         if (status)
4851                 goto out;
4852
4853         status = nfserr_grace;
4854         if (locks_in_grace(net) && !lock->lk_reclaim)
4855                 goto out;
4856         status = nfserr_no_grace;
4857         if (!locks_in_grace(net) && lock->lk_reclaim)
4858                 goto out;
4859
4860         file_lock = locks_alloc_lock();
4861         if (!file_lock) {
4862                 dprintk("NFSD: %s: unable to allocate lock!\n", __func__);
4863                 status = nfserr_jukebox;
4864                 goto out;
4865         }
4866
4867         fp = lock_stp->st_stid.sc_file;
4868         locks_init_lock(file_lock);
4869         switch (lock->lk_type) {
4870                 case NFS4_READ_LT:
4871                 case NFS4_READW_LT:
4872                         spin_lock(&fp->fi_lock);
4873                         filp = find_readable_file_locked(fp);
4874                         if (filp)
4875                                 get_lock_access(lock_stp, NFS4_SHARE_ACCESS_READ);
4876                         spin_unlock(&fp->fi_lock);
4877                         file_lock->fl_type = F_RDLCK;
4878                         break;
4879                 case NFS4_WRITE_LT:
4880                 case NFS4_WRITEW_LT:
4881                         spin_lock(&fp->fi_lock);
4882                         filp = find_writeable_file_locked(fp);
4883                         if (filp)
4884                                 get_lock_access(lock_stp, NFS4_SHARE_ACCESS_WRITE);
4885                         spin_unlock(&fp->fi_lock);
4886                         file_lock->fl_type = F_WRLCK;
4887                         break;
4888                 default:
4889                         status = nfserr_inval;
4890                 goto out;
4891         }
4892         if (!filp) {
4893                 status = nfserr_openmode;
4894                 goto out;
4895         }
4896         file_lock->fl_owner = (fl_owner_t)lock_sop;
4897         file_lock->fl_pid = current->tgid;
4898         file_lock->fl_file = filp;
4899         file_lock->fl_flags = FL_POSIX;
4900         file_lock->fl_lmops = &nfsd_posix_mng_ops;
4901         file_lock->fl_start = lock->lk_offset;
4902         file_lock->fl_end = last_byte_offset(lock->lk_offset, lock->lk_length);
4903         nfs4_transform_lock_offset(file_lock);
4904
4905         conflock = locks_alloc_lock();
4906         if (!conflock) {
4907                 dprintk("NFSD: %s: unable to allocate lock!\n", __func__);
4908                 status = nfserr_jukebox;
4909                 goto out;
4910         }
4911
4912         err = vfs_lock_file(filp, F_SETLK, file_lock, conflock);
4913         switch (-err) {
4914         case 0: /* success! */
4915                 update_stateid(&lock_stp->st_stid.sc_stateid);
4916                 memcpy(&lock->lk_resp_stateid, &lock_stp->st_stid.sc_stateid, 
4917                                 sizeof(stateid_t));
4918                 status = 0;
4919                 break;
4920         case (EAGAIN):          /* conflock holds conflicting lock */
4921                 status = nfserr_denied;
4922                 dprintk("NFSD: nfsd4_lock: conflicting lock found!\n");
4923                 nfs4_set_lock_denied(conflock, &lock->lk_denied);
4924                 break;
4925         case (EDEADLK):
4926                 status = nfserr_deadlock;
4927                 break;
4928         default:
4929                 dprintk("NFSD: nfsd4_lock: vfs_lock_file() failed! status %d\n",err);
4930                 status = nfserrno(err);
4931                 break;
4932         }
4933 out:
4934         if (filp)
4935                 fput(filp);
4936         if (status && new_state)
4937                 release_lock_stateid(lock_stp);
4938         nfsd4_bump_seqid(cstate, status);
4939         if (!cstate->replay_owner)
4940                 nfs4_unlock_state();
4941         if (file_lock)
4942                 locks_free_lock(file_lock);
4943         if (conflock)
4944                 locks_free_lock(conflock);
4945         return status;
4946 }
4947
4948 /*
4949  * The NFSv4 spec allows a client to do a LOCKT without holding an OPEN,
4950  * so we do a temporary open here just to get an open file to pass to
4951  * vfs_test_lock.  (Arguably perhaps test_lock should be done with an
4952  * inode operation.)
4953  */
4954 static __be32 nfsd_test_lock(struct svc_rqst *rqstp, struct svc_fh *fhp, struct file_lock *lock)
4955 {
4956         struct file *file;
4957         __be32 err = nfsd_open(rqstp, fhp, S_IFREG, NFSD_MAY_READ, &file);
4958         if (!err) {
4959                 err = nfserrno(vfs_test_lock(file, lock));
4960                 nfsd_close(file);
4961         }
4962         return err;
4963 }
4964
4965 /*
4966  * LOCKT operation
4967  */
4968 __be32
4969 nfsd4_lockt(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
4970             struct nfsd4_lockt *lockt)
4971 {
4972         struct file_lock *file_lock = NULL;
4973         struct nfs4_lockowner *lo;
4974         __be32 status;
4975         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
4976
4977         if (locks_in_grace(SVC_NET(rqstp)))
4978                 return nfserr_grace;
4979
4980         if (check_lock_length(lockt->lt_offset, lockt->lt_length))
4981                  return nfserr_inval;
4982
4983         nfs4_lock_state();
4984
4985         if (!nfsd4_has_session(cstate)) {
4986                 status = lookup_clientid(&lockt->lt_clientid, cstate, nn);
4987                 if (status)
4988                         goto out;
4989         }
4990
4991         if ((status = fh_verify(rqstp, &cstate->current_fh, S_IFREG, 0)))
4992                 goto out;
4993
4994         file_lock = locks_alloc_lock();
4995         if (!file_lock) {
4996                 dprintk("NFSD: %s: unable to allocate lock!\n", __func__);
4997                 status = nfserr_jukebox;
4998                 goto out;
4999         }
5000         locks_init_lock(file_lock);
5001         switch (lockt->lt_type) {
5002                 case NFS4_READ_LT:
5003                 case NFS4_READW_LT:
5004                         file_lock->fl_type = F_RDLCK;
5005                 break;
5006                 case NFS4_WRITE_LT:
5007                 case NFS4_WRITEW_LT:
5008                         file_lock->fl_type = F_WRLCK;
5009                 break;
5010                 default:
5011                         dprintk("NFSD: nfs4_lockt: bad lock type!\n");
5012                         status = nfserr_inval;
5013                 goto out;
5014         }
5015
5016         lo = find_lockowner_str(&lockt->lt_clientid, &lockt->lt_owner, nn);
5017         if (lo)
5018                 file_lock->fl_owner = (fl_owner_t)lo;
5019         file_lock->fl_pid = current->tgid;
5020         file_lock->fl_flags = FL_POSIX;
5021
5022         file_lock->fl_start = lockt->lt_offset;
5023         file_lock->fl_end = last_byte_offset(lockt->lt_offset, lockt->lt_length);
5024
5025         nfs4_transform_lock_offset(file_lock);
5026
5027         status = nfsd_test_lock(rqstp, &cstate->current_fh, file_lock);
5028         if (status)
5029                 goto out;
5030
5031         if (file_lock->fl_type != F_UNLCK) {
5032                 status = nfserr_denied;
5033                 nfs4_set_lock_denied(file_lock, &lockt->lt_denied);
5034         }
5035 out:
5036         nfs4_unlock_state();
5037         if (file_lock)
5038                 locks_free_lock(file_lock);
5039         return status;
5040 }
5041
5042 __be32
5043 nfsd4_locku(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
5044             struct nfsd4_locku *locku)
5045 {
5046         struct nfs4_ol_stateid *stp;
5047         struct file *filp = NULL;
5048         struct file_lock *file_lock = NULL;
5049         __be32 status;
5050         int err;
5051         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
5052
5053         dprintk("NFSD: nfsd4_locku: start=%Ld length=%Ld\n",
5054                 (long long) locku->lu_offset,
5055                 (long long) locku->lu_length);
5056
5057         if (check_lock_length(locku->lu_offset, locku->lu_length))
5058                  return nfserr_inval;
5059
5060         nfs4_lock_state();
5061                                                                                 
5062         status = nfs4_preprocess_seqid_op(cstate, locku->lu_seqid,
5063                                         &locku->lu_stateid, NFS4_LOCK_STID,
5064                                         &stp, nn);
5065         if (status)
5066                 goto out;
5067         filp = find_any_file(stp->st_stid.sc_file);
5068         if (!filp) {
5069                 status = nfserr_lock_range;
5070                 goto out;
5071         }
5072         file_lock = locks_alloc_lock();
5073         if (!file_lock) {
5074                 dprintk("NFSD: %s: unable to allocate lock!\n", __func__);
5075                 status = nfserr_jukebox;
5076                 goto fput;
5077         }
5078         locks_init_lock(file_lock);
5079         file_lock->fl_type = F_UNLCK;
5080         file_lock->fl_owner = (fl_owner_t)lockowner(stp->st_stateowner);
5081         file_lock->fl_pid = current->tgid;
5082         file_lock->fl_file = filp;
5083         file_lock->fl_flags = FL_POSIX;
5084         file_lock->fl_lmops = &nfsd_posix_mng_ops;
5085         file_lock->fl_start = locku->lu_offset;
5086
5087         file_lock->fl_end = last_byte_offset(locku->lu_offset,
5088                                                 locku->lu_length);
5089         nfs4_transform_lock_offset(file_lock);
5090
5091         err = vfs_lock_file(filp, F_SETLK, file_lock, NULL);
5092         if (err) {
5093                 dprintk("NFSD: nfs4_locku: vfs_lock_file failed!\n");
5094                 goto out_nfserr;
5095         }
5096         update_stateid(&stp->st_stid.sc_stateid);
5097         memcpy(&locku->lu_stateid, &stp->st_stid.sc_stateid, sizeof(stateid_t));
5098 fput:
5099         fput(filp);
5100 out:
5101         nfsd4_bump_seqid(cstate, status);
5102         if (!cstate->replay_owner)
5103                 nfs4_unlock_state();
5104         if (file_lock)
5105                 locks_free_lock(file_lock);
5106         return status;
5107
5108 out_nfserr:
5109         status = nfserrno(err);
5110         goto fput;
5111 }
5112
5113 /*
5114  * returns
5115  *      true:  locks held by lockowner
5116  *      false: no locks held by lockowner
5117  */
5118 static bool
5119 check_for_locks(struct nfs4_file *fp, struct nfs4_lockowner *lowner)
5120 {
5121         struct file_lock **flpp;
5122         int status = false;
5123         struct file *filp = find_any_file(fp);
5124         struct inode *inode;
5125
5126         if (!filp) {
5127                 /* Any valid lock stateid should have some sort of access */
5128                 WARN_ON_ONCE(1);
5129                 return status;
5130         }
5131
5132         inode = file_inode(filp);
5133
5134         spin_lock(&inode->i_lock);
5135         for (flpp = &inode->i_flock; *flpp != NULL; flpp = &(*flpp)->fl_next) {
5136                 if ((*flpp)->fl_owner == (fl_owner_t)lowner) {
5137                         status = true;
5138                         break;
5139                 }
5140         }
5141         spin_unlock(&inode->i_lock);
5142         fput(filp);
5143         return status;
5144 }
5145
5146 __be32
5147 nfsd4_release_lockowner(struct svc_rqst *rqstp,
5148                         struct nfsd4_compound_state *cstate,
5149                         struct nfsd4_release_lockowner *rlockowner)
5150 {
5151         clientid_t *clid = &rlockowner->rl_clientid;
5152         struct nfs4_stateowner *sop = NULL, *tmp;
5153         struct nfs4_lockowner *lo;
5154         struct nfs4_ol_stateid *stp;
5155         struct xdr_netobj *owner = &rlockowner->rl_owner;
5156         unsigned int hashval = ownerstr_hashval(clid->cl_id, owner);
5157         __be32 status;
5158         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
5159
5160         dprintk("nfsd4_release_lockowner clientid: (%08x/%08x):\n",
5161                 clid->cl_boot, clid->cl_id);
5162
5163         nfs4_lock_state();
5164
5165         status = lookup_clientid(clid, cstate, nn);
5166         if (status)
5167                 goto out;
5168
5169         status = nfserr_locks_held;
5170
5171         /* Find the matching lock stateowner */
5172         list_for_each_entry(tmp, &nn->ownerstr_hashtbl[hashval], so_strhash) {
5173                 if (tmp->so_is_open_owner)
5174                         continue;
5175                 if (same_owner_str(tmp, owner, clid)) {
5176                         sop = tmp;
5177                         break;
5178                 }
5179         }
5180
5181         /* No matching owner found, maybe a replay? Just declare victory... */
5182         if (!sop) {
5183                 status = nfs_ok;
5184                 goto out;
5185         }
5186
5187         lo = lockowner(sop);
5188         /* see if there are still any locks associated with it */
5189         list_for_each_entry(stp, &sop->so_stateids, st_perstateowner) {
5190                 if (check_for_locks(stp->st_stid.sc_file, lo))
5191                         goto out;
5192         }
5193
5194         status = nfs_ok;
5195         release_lockowner(lo);
5196 out:
5197         nfs4_unlock_state();
5198         return status;
5199 }
5200
5201 static inline struct nfs4_client_reclaim *
5202 alloc_reclaim(void)
5203 {
5204         return kmalloc(sizeof(struct nfs4_client_reclaim), GFP_KERNEL);
5205 }
5206
5207 bool
5208 nfs4_has_reclaimed_state(const char *name, struct nfsd_net *nn)
5209 {
5210         struct nfs4_client_reclaim *crp;
5211
5212         crp = nfsd4_find_reclaim_client(name, nn);
5213         return (crp && crp->cr_clp);
5214 }
5215
5216 /*
5217  * failure => all reset bets are off, nfserr_no_grace...
5218  */
5219 struct nfs4_client_reclaim *
5220 nfs4_client_to_reclaim(const char *name, struct nfsd_net *nn)
5221 {
5222         unsigned int strhashval;
5223         struct nfs4_client_reclaim *crp;
5224
5225         dprintk("NFSD nfs4_client_to_reclaim NAME: %.*s\n", HEXDIR_LEN, name);
5226         crp = alloc_reclaim();
5227         if (crp) {
5228                 strhashval = clientstr_hashval(name);
5229                 INIT_LIST_HEAD(&crp->cr_strhash);
5230                 list_add(&crp->cr_strhash, &nn->reclaim_str_hashtbl[strhashval]);
5231                 memcpy(crp->cr_recdir, name, HEXDIR_LEN);
5232                 crp->cr_clp = NULL;
5233                 nn->reclaim_str_hashtbl_size++;
5234         }
5235         return crp;
5236 }
5237
5238 void
5239 nfs4_remove_reclaim_record(struct nfs4_client_reclaim *crp, struct nfsd_net *nn)
5240 {
5241         list_del(&crp->cr_strhash);
5242         kfree(crp);
5243         nn->reclaim_str_hashtbl_size--;
5244 }
5245
5246 void
5247 nfs4_release_reclaim(struct nfsd_net *nn)
5248 {
5249         struct nfs4_client_reclaim *crp = NULL;
5250         int i;
5251
5252         for (i = 0; i < CLIENT_HASH_SIZE; i++) {
5253                 while (!list_empty(&nn->reclaim_str_hashtbl[i])) {
5254                         crp = list_entry(nn->reclaim_str_hashtbl[i].next,
5255                                         struct nfs4_client_reclaim, cr_strhash);
5256                         nfs4_remove_reclaim_record(crp, nn);
5257                 }
5258         }
5259         WARN_ON_ONCE(nn->reclaim_str_hashtbl_size);
5260 }
5261
5262 /*
5263  * called from OPEN, CLAIM_PREVIOUS with a new clientid. */
5264 struct nfs4_client_reclaim *
5265 nfsd4_find_reclaim_client(const char *recdir, struct nfsd_net *nn)
5266 {
5267         unsigned int strhashval;
5268         struct nfs4_client_reclaim *crp = NULL;
5269
5270         dprintk("NFSD: nfs4_find_reclaim_client for recdir %s\n", recdir);
5271
5272         strhashval = clientstr_hashval(recdir);
5273         list_for_each_entry(crp, &nn->reclaim_str_hashtbl[strhashval], cr_strhash) {
5274                 if (same_name(crp->cr_recdir, recdir)) {
5275                         return crp;
5276                 }
5277         }
5278         return NULL;
5279 }
5280
5281 /*
5282 * Called from OPEN. Look for clientid in reclaim list.
5283 */
5284 __be32
5285 nfs4_check_open_reclaim(clientid_t *clid,
5286                 struct nfsd4_compound_state *cstate,
5287                 struct nfsd_net *nn)
5288 {
5289         __be32 status;
5290
5291         /* find clientid in conf_id_hashtbl */
5292         status = lookup_clientid(clid, cstate, nn);
5293         if (status)
5294                 return nfserr_reclaim_bad;
5295
5296         if (nfsd4_client_record_check(cstate->clp))
5297                 return nfserr_reclaim_bad;
5298
5299         return nfs_ok;
5300 }
5301
5302 #ifdef CONFIG_NFSD_FAULT_INJECTION
5303
5304 u64 nfsd_forget_client(struct nfs4_client *clp, u64 max)
5305 {
5306         if (mark_client_expired(clp))
5307                 return 0;
5308         expire_client(clp);
5309         return 1;
5310 }
5311
5312 u64 nfsd_print_client(struct nfs4_client *clp, u64 num)
5313 {
5314         char buf[INET6_ADDRSTRLEN];
5315         rpc_ntop((struct sockaddr *)&clp->cl_addr, buf, sizeof(buf));
5316         printk(KERN_INFO "NFS Client: %s\n", buf);
5317         return 1;
5318 }
5319
5320 static void nfsd_print_count(struct nfs4_client *clp, unsigned int count,
5321                              const char *type)
5322 {
5323         char buf[INET6_ADDRSTRLEN];
5324         rpc_ntop((struct sockaddr *)&clp->cl_addr, buf, sizeof(buf));
5325         printk(KERN_INFO "NFS Client: %s has %u %s\n", buf, count, type);
5326 }
5327
5328 static u64 nfsd_foreach_client_lock(struct nfs4_client *clp, u64 max,
5329                                     void (*func)(struct nfs4_ol_stateid *))
5330 {
5331         struct nfs4_openowner *oop;
5332         struct nfs4_ol_stateid *stp, *st_next;
5333         struct nfs4_ol_stateid *lst, *lst_next;
5334         u64 count = 0;
5335
5336         list_for_each_entry(oop, &clp->cl_openowners, oo_perclient) {
5337                 list_for_each_entry_safe(stp, st_next,
5338                                 &oop->oo_owner.so_stateids, st_perstateowner) {
5339                         list_for_each_entry_safe(lst, lst_next,
5340                                         &stp->st_locks, st_locks) {
5341                                 if (func)
5342                                         func(lst);
5343                                 if (++count == max)
5344                                         return count;
5345                         }
5346                 }
5347         }
5348
5349         return count;
5350 }
5351
5352 u64 nfsd_forget_client_locks(struct nfs4_client *clp, u64 max)
5353 {
5354         return nfsd_foreach_client_lock(clp, max, release_lock_stateid);
5355 }
5356
5357 u64 nfsd_print_client_locks(struct nfs4_client *clp, u64 max)
5358 {
5359         u64 count = nfsd_foreach_client_lock(clp, max, NULL);
5360         nfsd_print_count(clp, count, "locked files");
5361         return count;
5362 }
5363
5364 static u64 nfsd_foreach_client_open(struct nfs4_client *clp, u64 max, void (*func)(struct nfs4_openowner *))
5365 {
5366         struct nfs4_openowner *oop, *next;
5367         u64 count = 0;
5368
5369         list_for_each_entry_safe(oop, next, &clp->cl_openowners, oo_perclient) {
5370                 if (func)
5371                         func(oop);
5372                 if (++count == max)
5373                         break;
5374         }
5375
5376         return count;
5377 }
5378
5379 u64 nfsd_forget_client_openowners(struct nfs4_client *clp, u64 max)
5380 {
5381         return nfsd_foreach_client_open(clp, max, release_openowner);
5382 }
5383
5384 u64 nfsd_print_client_openowners(struct nfs4_client *clp, u64 max)
5385 {
5386         u64 count = nfsd_foreach_client_open(clp, max, NULL);
5387         nfsd_print_count(clp, count, "open files");
5388         return count;
5389 }
5390
5391 static u64 nfsd_find_all_delegations(struct nfs4_client *clp, u64 max,
5392                                      struct list_head *victims)
5393 {
5394         struct nfs4_delegation *dp, *next;
5395         u64 count = 0;
5396
5397         lockdep_assert_held(&state_lock);
5398         list_for_each_entry_safe(dp, next, &clp->cl_delegations, dl_perclnt) {
5399                 if (victims) {
5400                         /*
5401                          * It's not safe to mess with delegations that have a
5402                          * non-zero dl_time. They might have already been broken
5403                          * and could be processed by the laundromat outside of
5404                          * the state_lock. Just leave them be.
5405                          */
5406                         if (dp->dl_time != 0)
5407                                 continue;
5408
5409                         unhash_delegation_locked(dp);
5410                         list_add(&dp->dl_recall_lru, victims);
5411                 }
5412                 if (++count == max)
5413                         break;
5414         }
5415         return count;
5416 }
5417
5418 u64 nfsd_forget_client_delegations(struct nfs4_client *clp, u64 max)
5419 {
5420         struct nfs4_delegation *dp, *next;
5421         LIST_HEAD(victims);
5422         u64 count;
5423
5424         spin_lock(&state_lock);
5425         count = nfsd_find_all_delegations(clp, max, &victims);
5426         spin_unlock(&state_lock);
5427
5428         list_for_each_entry_safe(dp, next, &victims, dl_recall_lru) {
5429                 list_del_init(&dp->dl_recall_lru);
5430                 revoke_delegation(dp);
5431         }
5432
5433         return count;
5434 }
5435
5436 u64 nfsd_recall_client_delegations(struct nfs4_client *clp, u64 max)
5437 {
5438         struct nfs4_delegation *dp;
5439         LIST_HEAD(victims);
5440         u64 count;
5441
5442         spin_lock(&state_lock);
5443         count = nfsd_find_all_delegations(clp, max, &victims);
5444         while (!list_empty(&victims)) {
5445                 dp = list_first_entry(&victims, struct nfs4_delegation,
5446                                         dl_recall_lru);
5447                 list_del_init(&dp->dl_recall_lru);
5448                 dp->dl_time = 0;
5449                 nfsd_break_one_deleg(dp);
5450         }
5451         spin_unlock(&state_lock);
5452
5453         return count;
5454 }
5455
5456 u64 nfsd_print_client_delegations(struct nfs4_client *clp, u64 max)
5457 {
5458         u64 count = 0;
5459
5460         spin_lock(&state_lock);
5461         count = nfsd_find_all_delegations(clp, max, NULL);
5462         spin_unlock(&state_lock);
5463
5464         nfsd_print_count(clp, count, "delegations");
5465         return count;
5466 }
5467
5468 u64 nfsd_for_n_state(u64 max, u64 (*func)(struct nfs4_client *, u64))
5469 {
5470         struct nfs4_client *clp, *next;
5471         u64 count = 0;
5472         struct nfsd_net *nn = net_generic(current->nsproxy->net_ns, nfsd_net_id);
5473
5474         if (!nfsd_netns_ready(nn))
5475                 return 0;
5476
5477         list_for_each_entry_safe(clp, next, &nn->client_lru, cl_lru) {
5478                 count += func(clp, max - count);
5479                 if ((max != 0) && (count >= max))
5480                         break;
5481         }
5482
5483         return count;
5484 }
5485
5486 struct nfs4_client *nfsd_find_client(struct sockaddr_storage *addr, size_t addr_size)
5487 {
5488         struct nfs4_client *clp;
5489         struct nfsd_net *nn = net_generic(current->nsproxy->net_ns, nfsd_net_id);
5490
5491         if (!nfsd_netns_ready(nn))
5492                 return NULL;
5493
5494         list_for_each_entry(clp, &nn->client_lru, cl_lru) {
5495                 if (memcmp(&clp->cl_addr, addr, addr_size) == 0)
5496                         return clp;
5497         }
5498         return NULL;
5499 }
5500
5501 #endif /* CONFIG_NFSD_FAULT_INJECTION */
5502
5503 /*
5504  * Since the lifetime of a delegation isn't limited to that of an open, a
5505  * client may quite reasonably hang on to a delegation as long as it has
5506  * the inode cached.  This becomes an obvious problem the first time a
5507  * client's inode cache approaches the size of the server's total memory.
5508  *
5509  * For now we avoid this problem by imposing a hard limit on the number
5510  * of delegations, which varies according to the server's memory size.
5511  */
5512 static void
5513 set_max_delegations(void)
5514 {
5515         /*
5516          * Allow at most 4 delegations per megabyte of RAM.  Quick
5517          * estimates suggest that in the worst case (where every delegation
5518          * is for a different inode), a delegation could take about 1.5K,
5519          * giving a worst case usage of about 6% of memory.
5520          */
5521         max_delegations = nr_free_buffer_pages() >> (20 - 2 - PAGE_SHIFT);
5522 }
5523
5524 static int nfs4_state_create_net(struct net *net)
5525 {
5526         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
5527         int i;
5528
5529         nn->conf_id_hashtbl = kmalloc(sizeof(struct list_head) *
5530                         CLIENT_HASH_SIZE, GFP_KERNEL);
5531         if (!nn->conf_id_hashtbl)
5532                 goto err;
5533         nn->unconf_id_hashtbl = kmalloc(sizeof(struct list_head) *
5534                         CLIENT_HASH_SIZE, GFP_KERNEL);
5535         if (!nn->unconf_id_hashtbl)
5536                 goto err_unconf_id;
5537         nn->ownerstr_hashtbl = kmalloc(sizeof(struct list_head) *
5538                         OWNER_HASH_SIZE, GFP_KERNEL);
5539         if (!nn->ownerstr_hashtbl)
5540                 goto err_ownerstr;
5541         nn->sessionid_hashtbl = kmalloc(sizeof(struct list_head) *
5542                         SESSION_HASH_SIZE, GFP_KERNEL);
5543         if (!nn->sessionid_hashtbl)
5544                 goto err_sessionid;
5545
5546         for (i = 0; i < CLIENT_HASH_SIZE; i++) {
5547                 INIT_LIST_HEAD(&nn->conf_id_hashtbl[i]);
5548                 INIT_LIST_HEAD(&nn->unconf_id_hashtbl[i]);
5549         }
5550         for (i = 0; i < OWNER_HASH_SIZE; i++)
5551                 INIT_LIST_HEAD(&nn->ownerstr_hashtbl[i]);
5552         for (i = 0; i < SESSION_HASH_SIZE; i++)
5553                 INIT_LIST_HEAD(&nn->sessionid_hashtbl[i]);
5554         nn->conf_name_tree = RB_ROOT;
5555         nn->unconf_name_tree = RB_ROOT;
5556         INIT_LIST_HEAD(&nn->client_lru);
5557         INIT_LIST_HEAD(&nn->close_lru);
5558         INIT_LIST_HEAD(&nn->del_recall_lru);
5559         spin_lock_init(&nn->client_lock);
5560
5561         INIT_DELAYED_WORK(&nn->laundromat_work, laundromat_main);
5562         get_net(net);
5563
5564         return 0;
5565
5566 err_sessionid:
5567         kfree(nn->ownerstr_hashtbl);
5568 err_ownerstr:
5569         kfree(nn->unconf_id_hashtbl);
5570 err_unconf_id:
5571         kfree(nn->conf_id_hashtbl);
5572 err:
5573         return -ENOMEM;
5574 }
5575
5576 static void
5577 nfs4_state_destroy_net(struct net *net)
5578 {
5579         int i;
5580         struct nfs4_client *clp = NULL;
5581         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
5582
5583         for (i = 0; i < CLIENT_HASH_SIZE; i++) {
5584                 while (!list_empty(&nn->conf_id_hashtbl[i])) {
5585                         clp = list_entry(nn->conf_id_hashtbl[i].next, struct nfs4_client, cl_idhash);
5586                         destroy_client(clp);
5587                 }
5588         }
5589
5590         for (i = 0; i < CLIENT_HASH_SIZE; i++) {
5591                 while (!list_empty(&nn->unconf_id_hashtbl[i])) {
5592                         clp = list_entry(nn->unconf_id_hashtbl[i].next, struct nfs4_client, cl_idhash);
5593                         destroy_client(clp);
5594                 }
5595         }
5596
5597         kfree(nn->sessionid_hashtbl);
5598         kfree(nn->ownerstr_hashtbl);
5599         kfree(nn->unconf_id_hashtbl);
5600         kfree(nn->conf_id_hashtbl);
5601         put_net(net);
5602 }
5603
5604 int
5605 nfs4_state_start_net(struct net *net)
5606 {
5607         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
5608         int ret;
5609
5610         ret = nfs4_state_create_net(net);
5611         if (ret)
5612                 return ret;
5613         nfsd4_client_tracking_init(net);
5614         nn->boot_time = get_seconds();
5615         locks_start_grace(net, &nn->nfsd4_manager);
5616         nn->grace_ended = false;
5617         printk(KERN_INFO "NFSD: starting %ld-second grace period (net %p)\n",
5618                nn->nfsd4_grace, net);
5619         queue_delayed_work(laundry_wq, &nn->laundromat_work, nn->nfsd4_grace * HZ);
5620         return 0;
5621 }
5622
5623 /* initialization to perform when the nfsd service is started: */
5624
5625 int
5626 nfs4_state_start(void)
5627 {
5628         int ret;
5629
5630         ret = set_callback_cred();
5631         if (ret)
5632                 return -ENOMEM;
5633         laundry_wq = create_singlethread_workqueue("nfsd4");
5634         if (laundry_wq == NULL) {
5635                 ret = -ENOMEM;
5636                 goto out_recovery;
5637         }
5638         ret = nfsd4_create_callback_queue();
5639         if (ret)
5640                 goto out_free_laundry;
5641
5642         set_max_delegations();
5643
5644         return 0;
5645
5646 out_free_laundry:
5647         destroy_workqueue(laundry_wq);
5648 out_recovery:
5649         return ret;
5650 }
5651
5652 void
5653 nfs4_state_shutdown_net(struct net *net)
5654 {
5655         struct nfs4_delegation *dp = NULL;
5656         struct list_head *pos, *next, reaplist;
5657         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
5658
5659         cancel_delayed_work_sync(&nn->laundromat_work);
5660         locks_end_grace(&nn->nfsd4_manager);
5661
5662         nfs4_lock_state();
5663         INIT_LIST_HEAD(&reaplist);
5664         spin_lock(&state_lock);
5665         list_for_each_safe(pos, next, &nn->del_recall_lru) {
5666                 dp = list_entry (pos, struct nfs4_delegation, dl_recall_lru);
5667                 unhash_delegation_locked(dp);
5668                 list_add(&dp->dl_recall_lru, &reaplist);
5669         }
5670         spin_unlock(&state_lock);
5671         list_for_each_safe(pos, next, &reaplist) {
5672                 dp = list_entry (pos, struct nfs4_delegation, dl_recall_lru);
5673                 list_del_init(&dp->dl_recall_lru);
5674                 nfs4_put_stid(&dp->dl_stid);
5675         }
5676
5677         nfsd4_client_tracking_exit(net);
5678         nfs4_state_destroy_net(net);
5679         nfs4_unlock_state();
5680 }
5681
5682 void
5683 nfs4_state_shutdown(void)
5684 {
5685         destroy_workqueue(laundry_wq);
5686         nfsd4_destroy_callback_queue();
5687 }
5688
5689 static void
5690 get_stateid(struct nfsd4_compound_state *cstate, stateid_t *stateid)
5691 {
5692         if (HAS_STATE_ID(cstate, CURRENT_STATE_ID_FLAG) && CURRENT_STATEID(stateid))
5693                 memcpy(stateid, &cstate->current_stateid, sizeof(stateid_t));
5694 }
5695
5696 static void
5697 put_stateid(struct nfsd4_compound_state *cstate, stateid_t *stateid)
5698 {
5699         if (cstate->minorversion) {
5700                 memcpy(&cstate->current_stateid, stateid, sizeof(stateid_t));
5701                 SET_STATE_ID(cstate, CURRENT_STATE_ID_FLAG);
5702         }
5703 }
5704
5705 void
5706 clear_current_stateid(struct nfsd4_compound_state *cstate)
5707 {
5708         CLEAR_STATE_ID(cstate, CURRENT_STATE_ID_FLAG);
5709 }
5710
5711 /*
5712  * functions to set current state id
5713  */
5714 void
5715 nfsd4_set_opendowngradestateid(struct nfsd4_compound_state *cstate, struct nfsd4_open_downgrade *odp)
5716 {
5717         put_stateid(cstate, &odp->od_stateid);
5718 }
5719
5720 void
5721 nfsd4_set_openstateid(struct nfsd4_compound_state *cstate, struct nfsd4_open *open)
5722 {
5723         put_stateid(cstate, &open->op_stateid);
5724 }
5725
5726 void
5727 nfsd4_set_closestateid(struct nfsd4_compound_state *cstate, struct nfsd4_close *close)
5728 {
5729         put_stateid(cstate, &close->cl_stateid);
5730 }
5731
5732 void
5733 nfsd4_set_lockstateid(struct nfsd4_compound_state *cstate, struct nfsd4_lock *lock)
5734 {
5735         put_stateid(cstate, &lock->lk_resp_stateid);
5736 }
5737
5738 /*
5739  * functions to consume current state id
5740  */
5741
5742 void
5743 nfsd4_get_opendowngradestateid(struct nfsd4_compound_state *cstate, struct nfsd4_open_downgrade *odp)
5744 {
5745         get_stateid(cstate, &odp->od_stateid);
5746 }
5747
5748 void
5749 nfsd4_get_delegreturnstateid(struct nfsd4_compound_state *cstate, struct nfsd4_delegreturn *drp)
5750 {
5751         get_stateid(cstate, &drp->dr_stateid);
5752 }
5753
5754 void
5755 nfsd4_get_freestateid(struct nfsd4_compound_state *cstate, struct nfsd4_free_stateid *fsp)
5756 {
5757         get_stateid(cstate, &fsp->fr_stateid);
5758 }
5759
5760 void
5761 nfsd4_get_setattrstateid(struct nfsd4_compound_state *cstate, struct nfsd4_setattr *setattr)
5762 {
5763         get_stateid(cstate, &setattr->sa_stateid);
5764 }
5765
5766 void
5767 nfsd4_get_closestateid(struct nfsd4_compound_state *cstate, struct nfsd4_close *close)
5768 {
5769         get_stateid(cstate, &close->cl_stateid);
5770 }
5771
5772 void
5773 nfsd4_get_lockustateid(struct nfsd4_compound_state *cstate, struct nfsd4_locku *locku)
5774 {
5775         get_stateid(cstate, &locku->lu_stateid);
5776 }
5777
5778 void
5779 nfsd4_get_readstateid(struct nfsd4_compound_state *cstate, struct nfsd4_read *read)
5780 {
5781         get_stateid(cstate, &read->rd_stateid);
5782 }
5783
5784 void
5785 nfsd4_get_writestateid(struct nfsd4_compound_state *cstate, struct nfsd4_write *write)
5786 {
5787         get_stateid(cstate, &write->wr_stateid);
5788 }