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