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