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