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