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