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