GNU Linux-libre 4.14.262-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 static int copy_cred(struct svc_cred *target, struct svc_cred *source)
1974 {
1975         target->cr_principal = kstrdup(source->cr_principal, GFP_KERNEL);
1976         target->cr_raw_principal = kstrdup(source->cr_raw_principal,
1977                                                                 GFP_KERNEL);
1978         if ((source->cr_principal && ! target->cr_principal) ||
1979             (source->cr_raw_principal && ! target->cr_raw_principal))
1980                 return -ENOMEM;
1981
1982         target->cr_flavor = source->cr_flavor;
1983         target->cr_uid = source->cr_uid;
1984         target->cr_gid = source->cr_gid;
1985         target->cr_group_info = source->cr_group_info;
1986         get_group_info(target->cr_group_info);
1987         target->cr_gss_mech = source->cr_gss_mech;
1988         if (source->cr_gss_mech)
1989                 gss_mech_get(source->cr_gss_mech);
1990         return 0;
1991 }
1992
1993 static int
1994 compare_blob(const struct xdr_netobj *o1, const struct xdr_netobj *o2)
1995 {
1996         if (o1->len < o2->len)
1997                 return -1;
1998         if (o1->len > o2->len)
1999                 return 1;
2000         return memcmp(o1->data, o2->data, o1->len);
2001 }
2002
2003 static int same_name(const char *n1, const char *n2)
2004 {
2005         return 0 == memcmp(n1, n2, HEXDIR_LEN);
2006 }
2007
2008 static int
2009 same_verf(nfs4_verifier *v1, nfs4_verifier *v2)
2010 {
2011         return 0 == memcmp(v1->data, v2->data, sizeof(v1->data));
2012 }
2013
2014 static int
2015 same_clid(clientid_t *cl1, clientid_t *cl2)
2016 {
2017         return (cl1->cl_boot == cl2->cl_boot) && (cl1->cl_id == cl2->cl_id);
2018 }
2019
2020 static bool groups_equal(struct group_info *g1, struct group_info *g2)
2021 {
2022         int i;
2023
2024         if (g1->ngroups != g2->ngroups)
2025                 return false;
2026         for (i=0; i<g1->ngroups; i++)
2027                 if (!gid_eq(g1->gid[i], g2->gid[i]))
2028                         return false;
2029         return true;
2030 }
2031
2032 /*
2033  * RFC 3530 language requires clid_inuse be returned when the
2034  * "principal" associated with a requests differs from that previously
2035  * used.  We use uid, gid's, and gss principal string as our best
2036  * approximation.  We also don't want to allow non-gss use of a client
2037  * established using gss: in theory cr_principal should catch that
2038  * change, but in practice cr_principal can be null even in the gss case
2039  * since gssd doesn't always pass down a principal string.
2040  */
2041 static bool is_gss_cred(struct svc_cred *cr)
2042 {
2043         /* Is cr_flavor one of the gss "pseudoflavors"?: */
2044         return (cr->cr_flavor > RPC_AUTH_MAXFLAVOR);
2045 }
2046
2047
2048 static bool
2049 same_creds(struct svc_cred *cr1, struct svc_cred *cr2)
2050 {
2051         if ((is_gss_cred(cr1) != is_gss_cred(cr2))
2052                 || (!uid_eq(cr1->cr_uid, cr2->cr_uid))
2053                 || (!gid_eq(cr1->cr_gid, cr2->cr_gid))
2054                 || !groups_equal(cr1->cr_group_info, cr2->cr_group_info))
2055                 return false;
2056         if (cr1->cr_principal == cr2->cr_principal)
2057                 return true;
2058         if (!cr1->cr_principal || !cr2->cr_principal)
2059                 return false;
2060         return 0 == strcmp(cr1->cr_principal, cr2->cr_principal);
2061 }
2062
2063 static bool svc_rqst_integrity_protected(struct svc_rqst *rqstp)
2064 {
2065         struct svc_cred *cr = &rqstp->rq_cred;
2066         u32 service;
2067
2068         if (!cr->cr_gss_mech)
2069                 return false;
2070         service = gss_pseudoflavor_to_service(cr->cr_gss_mech, cr->cr_flavor);
2071         return service == RPC_GSS_SVC_INTEGRITY ||
2072                service == RPC_GSS_SVC_PRIVACY;
2073 }
2074
2075 bool nfsd4_mach_creds_match(struct nfs4_client *cl, struct svc_rqst *rqstp)
2076 {
2077         struct svc_cred *cr = &rqstp->rq_cred;
2078
2079         if (!cl->cl_mach_cred)
2080                 return true;
2081         if (cl->cl_cred.cr_gss_mech != cr->cr_gss_mech)
2082                 return false;
2083         if (!svc_rqst_integrity_protected(rqstp))
2084                 return false;
2085         if (cl->cl_cred.cr_raw_principal)
2086                 return 0 == strcmp(cl->cl_cred.cr_raw_principal,
2087                                                 cr->cr_raw_principal);
2088         if (!cr->cr_principal)
2089                 return false;
2090         return 0 == strcmp(cl->cl_cred.cr_principal, cr->cr_principal);
2091 }
2092
2093 static void gen_confirm(struct nfs4_client *clp, struct nfsd_net *nn)
2094 {
2095         __be32 verf[2];
2096
2097         /*
2098          * This is opaque to client, so no need to byte-swap. Use
2099          * __force to keep sparse happy
2100          */
2101         verf[0] = (__force __be32)get_seconds();
2102         verf[1] = (__force __be32)nn->clverifier_counter++;
2103         memcpy(clp->cl_confirm.data, verf, sizeof(clp->cl_confirm.data));
2104 }
2105
2106 static void gen_clid(struct nfs4_client *clp, struct nfsd_net *nn)
2107 {
2108         clp->cl_clientid.cl_boot = nn->boot_time;
2109         clp->cl_clientid.cl_id = nn->clientid_counter++;
2110         gen_confirm(clp, nn);
2111 }
2112
2113 static struct nfs4_stid *
2114 find_stateid_locked(struct nfs4_client *cl, stateid_t *t)
2115 {
2116         struct nfs4_stid *ret;
2117
2118         ret = idr_find(&cl->cl_stateids, t->si_opaque.so_id);
2119         if (!ret || !ret->sc_type)
2120                 return NULL;
2121         return ret;
2122 }
2123
2124 static struct nfs4_stid *
2125 find_stateid_by_type(struct nfs4_client *cl, stateid_t *t, char typemask)
2126 {
2127         struct nfs4_stid *s;
2128
2129         spin_lock(&cl->cl_lock);
2130         s = find_stateid_locked(cl, t);
2131         if (s != NULL) {
2132                 if (typemask & s->sc_type)
2133                         atomic_inc(&s->sc_count);
2134                 else
2135                         s = NULL;
2136         }
2137         spin_unlock(&cl->cl_lock);
2138         return s;
2139 }
2140
2141 static struct nfs4_client *create_client(struct xdr_netobj name,
2142                 struct svc_rqst *rqstp, nfs4_verifier *verf)
2143 {
2144         struct nfs4_client *clp;
2145         struct sockaddr *sa = svc_addr(rqstp);
2146         int ret;
2147         struct net *net = SVC_NET(rqstp);
2148
2149         clp = alloc_client(name);
2150         if (clp == NULL)
2151                 return NULL;
2152
2153         ret = copy_cred(&clp->cl_cred, &rqstp->rq_cred);
2154         if (ret) {
2155                 free_client(clp);
2156                 return NULL;
2157         }
2158         nfsd4_init_cb(&clp->cl_cb_null, clp, NULL, NFSPROC4_CLNT_CB_NULL);
2159         clp->cl_time = get_seconds();
2160         clear_bit(0, &clp->cl_cb_slot_busy);
2161         copy_verf(clp, verf);
2162         rpc_copy_addr((struct sockaddr *) &clp->cl_addr, sa);
2163         clp->cl_cb_session = NULL;
2164         clp->net = net;
2165         return clp;
2166 }
2167
2168 static void
2169 add_clp_to_name_tree(struct nfs4_client *new_clp, struct rb_root *root)
2170 {
2171         struct rb_node **new = &(root->rb_node), *parent = NULL;
2172         struct nfs4_client *clp;
2173
2174         while (*new) {
2175                 clp = rb_entry(*new, struct nfs4_client, cl_namenode);
2176                 parent = *new;
2177
2178                 if (compare_blob(&clp->cl_name, &new_clp->cl_name) > 0)
2179                         new = &((*new)->rb_left);
2180                 else
2181                         new = &((*new)->rb_right);
2182         }
2183
2184         rb_link_node(&new_clp->cl_namenode, parent, new);
2185         rb_insert_color(&new_clp->cl_namenode, root);
2186 }
2187
2188 static struct nfs4_client *
2189 find_clp_in_name_tree(struct xdr_netobj *name, struct rb_root *root)
2190 {
2191         int cmp;
2192         struct rb_node *node = root->rb_node;
2193         struct nfs4_client *clp;
2194
2195         while (node) {
2196                 clp = rb_entry(node, struct nfs4_client, cl_namenode);
2197                 cmp = compare_blob(&clp->cl_name, name);
2198                 if (cmp > 0)
2199                         node = node->rb_left;
2200                 else if (cmp < 0)
2201                         node = node->rb_right;
2202                 else
2203                         return clp;
2204         }
2205         return NULL;
2206 }
2207
2208 static void
2209 add_to_unconfirmed(struct nfs4_client *clp)
2210 {
2211         unsigned int idhashval;
2212         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
2213
2214         lockdep_assert_held(&nn->client_lock);
2215
2216         clear_bit(NFSD4_CLIENT_CONFIRMED, &clp->cl_flags);
2217         add_clp_to_name_tree(clp, &nn->unconf_name_tree);
2218         idhashval = clientid_hashval(clp->cl_clientid.cl_id);
2219         list_add(&clp->cl_idhash, &nn->unconf_id_hashtbl[idhashval]);
2220         renew_client_locked(clp);
2221 }
2222
2223 static void
2224 move_to_confirmed(struct nfs4_client *clp)
2225 {
2226         unsigned int idhashval = clientid_hashval(clp->cl_clientid.cl_id);
2227         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
2228
2229         lockdep_assert_held(&nn->client_lock);
2230
2231         dprintk("NFSD: move_to_confirm nfs4_client %p\n", clp);
2232         list_move(&clp->cl_idhash, &nn->conf_id_hashtbl[idhashval]);
2233         rb_erase(&clp->cl_namenode, &nn->unconf_name_tree);
2234         add_clp_to_name_tree(clp, &nn->conf_name_tree);
2235         set_bit(NFSD4_CLIENT_CONFIRMED, &clp->cl_flags);
2236         renew_client_locked(clp);
2237 }
2238
2239 static struct nfs4_client *
2240 find_client_in_id_table(struct list_head *tbl, clientid_t *clid, bool sessions)
2241 {
2242         struct nfs4_client *clp;
2243         unsigned int idhashval = clientid_hashval(clid->cl_id);
2244
2245         list_for_each_entry(clp, &tbl[idhashval], cl_idhash) {
2246                 if (same_clid(&clp->cl_clientid, clid)) {
2247                         if ((bool)clp->cl_minorversion != sessions)
2248                                 return NULL;
2249                         renew_client_locked(clp);
2250                         return clp;
2251                 }
2252         }
2253         return NULL;
2254 }
2255
2256 static struct nfs4_client *
2257 find_confirmed_client(clientid_t *clid, bool sessions, struct nfsd_net *nn)
2258 {
2259         struct list_head *tbl = nn->conf_id_hashtbl;
2260
2261         lockdep_assert_held(&nn->client_lock);
2262         return find_client_in_id_table(tbl, clid, sessions);
2263 }
2264
2265 static struct nfs4_client *
2266 find_unconfirmed_client(clientid_t *clid, bool sessions, struct nfsd_net *nn)
2267 {
2268         struct list_head *tbl = nn->unconf_id_hashtbl;
2269
2270         lockdep_assert_held(&nn->client_lock);
2271         return find_client_in_id_table(tbl, clid, sessions);
2272 }
2273
2274 static bool clp_used_exchangeid(struct nfs4_client *clp)
2275 {
2276         return clp->cl_exchange_flags != 0;
2277
2278
2279 static struct nfs4_client *
2280 find_confirmed_client_by_name(struct xdr_netobj *name, struct nfsd_net *nn)
2281 {
2282         lockdep_assert_held(&nn->client_lock);
2283         return find_clp_in_name_tree(name, &nn->conf_name_tree);
2284 }
2285
2286 static struct nfs4_client *
2287 find_unconfirmed_client_by_name(struct xdr_netobj *name, struct nfsd_net *nn)
2288 {
2289         lockdep_assert_held(&nn->client_lock);
2290         return find_clp_in_name_tree(name, &nn->unconf_name_tree);
2291 }
2292
2293 static void
2294 gen_callback(struct nfs4_client *clp, struct nfsd4_setclientid *se, struct svc_rqst *rqstp)
2295 {
2296         struct nfs4_cb_conn *conn = &clp->cl_cb_conn;
2297         struct sockaddr *sa = svc_addr(rqstp);
2298         u32 scopeid = rpc_get_scope_id(sa);
2299         unsigned short expected_family;
2300
2301         /* Currently, we only support tcp and tcp6 for the callback channel */
2302         if (se->se_callback_netid_len == 3 &&
2303             !memcmp(se->se_callback_netid_val, "tcp", 3))
2304                 expected_family = AF_INET;
2305         else if (se->se_callback_netid_len == 4 &&
2306                  !memcmp(se->se_callback_netid_val, "tcp6", 4))
2307                 expected_family = AF_INET6;
2308         else
2309                 goto out_err;
2310
2311         conn->cb_addrlen = rpc_uaddr2sockaddr(clp->net, se->se_callback_addr_val,
2312                                             se->se_callback_addr_len,
2313                                             (struct sockaddr *)&conn->cb_addr,
2314                                             sizeof(conn->cb_addr));
2315
2316         if (!conn->cb_addrlen || conn->cb_addr.ss_family != expected_family)
2317                 goto out_err;
2318
2319         if (conn->cb_addr.ss_family == AF_INET6)
2320                 ((struct sockaddr_in6 *)&conn->cb_addr)->sin6_scope_id = scopeid;
2321
2322         conn->cb_prog = se->se_callback_prog;
2323         conn->cb_ident = se->se_callback_ident;
2324         memcpy(&conn->cb_saddr, &rqstp->rq_daddr, rqstp->rq_daddrlen);
2325         return;
2326 out_err:
2327         conn->cb_addr.ss_family = AF_UNSPEC;
2328         conn->cb_addrlen = 0;
2329         dprintk("NFSD: this client (clientid %08x/%08x) "
2330                 "will not receive delegations\n",
2331                 clp->cl_clientid.cl_boot, clp->cl_clientid.cl_id);
2332
2333         return;
2334 }
2335
2336 /*
2337  * Cache a reply. nfsd4_check_resp_size() has bounded the cache size.
2338  */
2339 static void
2340 nfsd4_store_cache_entry(struct nfsd4_compoundres *resp)
2341 {
2342         struct xdr_buf *buf = resp->xdr.buf;
2343         struct nfsd4_slot *slot = resp->cstate.slot;
2344         unsigned int base;
2345
2346         dprintk("--> %s slot %p\n", __func__, slot);
2347
2348         slot->sl_flags |= NFSD4_SLOT_INITIALIZED;
2349         slot->sl_opcnt = resp->opcnt;
2350         slot->sl_status = resp->cstate.status;
2351         free_svc_cred(&slot->sl_cred);
2352         copy_cred(&slot->sl_cred, &resp->rqstp->rq_cred);
2353
2354         if (!nfsd4_cache_this(resp)) {
2355                 slot->sl_flags &= ~NFSD4_SLOT_CACHED;
2356                 return;
2357         }
2358         slot->sl_flags |= NFSD4_SLOT_CACHED;
2359
2360         base = resp->cstate.data_offset;
2361         slot->sl_datalen = buf->len - base;
2362         if (read_bytes_from_xdr_buf(buf, base, slot->sl_data, slot->sl_datalen))
2363                 WARN(1, "%s: sessions DRC could not cache compound\n",
2364                      __func__);
2365         return;
2366 }
2367
2368 /*
2369  * Encode the replay sequence operation from the slot values.
2370  * If cachethis is FALSE encode the uncached rep error on the next
2371  * operation which sets resp->p and increments resp->opcnt for
2372  * nfs4svc_encode_compoundres.
2373  *
2374  */
2375 static __be32
2376 nfsd4_enc_sequence_replay(struct nfsd4_compoundargs *args,
2377                           struct nfsd4_compoundres *resp)
2378 {
2379         struct nfsd4_op *op;
2380         struct nfsd4_slot *slot = resp->cstate.slot;
2381
2382         /* Encode the replayed sequence operation */
2383         op = &args->ops[resp->opcnt - 1];
2384         nfsd4_encode_operation(resp, op);
2385
2386         if (slot->sl_flags & NFSD4_SLOT_CACHED)
2387                 return op->status;
2388         if (args->opcnt == 1) {
2389                 /*
2390                  * The original operation wasn't a solo sequence--we
2391                  * always cache those--so this retry must not match the
2392                  * original:
2393                  */
2394                 op->status = nfserr_seq_false_retry;
2395         } else {
2396                 op = &args->ops[resp->opcnt++];
2397                 op->status = nfserr_retry_uncached_rep;
2398                 nfsd4_encode_operation(resp, op);
2399         }
2400         return op->status;
2401 }
2402
2403 /*
2404  * The sequence operation is not cached because we can use the slot and
2405  * session values.
2406  */
2407 static __be32
2408 nfsd4_replay_cache_entry(struct nfsd4_compoundres *resp,
2409                          struct nfsd4_sequence *seq)
2410 {
2411         struct nfsd4_slot *slot = resp->cstate.slot;
2412         struct xdr_stream *xdr = &resp->xdr;
2413         __be32 *p;
2414         __be32 status;
2415
2416         dprintk("--> %s slot %p\n", __func__, slot);
2417
2418         status = nfsd4_enc_sequence_replay(resp->rqstp->rq_argp, resp);
2419         if (status)
2420                 return status;
2421
2422         p = xdr_reserve_space(xdr, slot->sl_datalen);
2423         if (!p) {
2424                 WARN_ON_ONCE(1);
2425                 return nfserr_serverfault;
2426         }
2427         xdr_encode_opaque_fixed(p, slot->sl_data, slot->sl_datalen);
2428         xdr_commit_encode(xdr);
2429
2430         resp->opcnt = slot->sl_opcnt;
2431         return slot->sl_status;
2432 }
2433
2434 /*
2435  * Set the exchange_id flags returned by the server.
2436  */
2437 static void
2438 nfsd4_set_ex_flags(struct nfs4_client *new, struct nfsd4_exchange_id *clid)
2439 {
2440 #ifdef CONFIG_NFSD_PNFS
2441         new->cl_exchange_flags |= EXCHGID4_FLAG_USE_PNFS_MDS;
2442 #else
2443         new->cl_exchange_flags |= EXCHGID4_FLAG_USE_NON_PNFS;
2444 #endif
2445
2446         /* Referrals are supported, Migration is not. */
2447         new->cl_exchange_flags |= EXCHGID4_FLAG_SUPP_MOVED_REFER;
2448
2449         /* set the wire flags to return to client. */
2450         clid->flags = new->cl_exchange_flags;
2451 }
2452
2453 static bool client_has_openowners(struct nfs4_client *clp)
2454 {
2455         struct nfs4_openowner *oo;
2456
2457         list_for_each_entry(oo, &clp->cl_openowners, oo_perclient) {
2458                 if (!list_empty(&oo->oo_owner.so_stateids))
2459                         return true;
2460         }
2461         return false;
2462 }
2463
2464 static bool client_has_state(struct nfs4_client *clp)
2465 {
2466         return client_has_openowners(clp)
2467 #ifdef CONFIG_NFSD_PNFS
2468                 || !list_empty(&clp->cl_lo_states)
2469 #endif
2470                 || !list_empty(&clp->cl_delegations)
2471                 || !list_empty(&clp->cl_sessions);
2472 }
2473
2474 __be32
2475 nfsd4_exchange_id(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
2476                 union nfsd4_op_u *u)
2477 {
2478         struct nfsd4_exchange_id *exid = &u->exchange_id;
2479         struct nfs4_client *conf, *new;
2480         struct nfs4_client *unconf = NULL;
2481         __be32 status;
2482         char                    addr_str[INET6_ADDRSTRLEN];
2483         nfs4_verifier           verf = exid->verifier;
2484         struct sockaddr         *sa = svc_addr(rqstp);
2485         bool    update = exid->flags & EXCHGID4_FLAG_UPD_CONFIRMED_REC_A;
2486         struct nfsd_net         *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
2487
2488         rpc_ntop(sa, addr_str, sizeof(addr_str));
2489         dprintk("%s rqstp=%p exid=%p clname.len=%u clname.data=%p "
2490                 "ip_addr=%s flags %x, spa_how %d\n",
2491                 __func__, rqstp, exid, exid->clname.len, exid->clname.data,
2492                 addr_str, exid->flags, exid->spa_how);
2493
2494         if (exid->flags & ~EXCHGID4_FLAG_MASK_A)
2495                 return nfserr_inval;
2496
2497         new = create_client(exid->clname, rqstp, &verf);
2498         if (new == NULL)
2499                 return nfserr_jukebox;
2500
2501         switch (exid->spa_how) {
2502         case SP4_MACH_CRED:
2503                 exid->spo_must_enforce[0] = 0;
2504                 exid->spo_must_enforce[1] = (
2505                         1 << (OP_BIND_CONN_TO_SESSION - 32) |
2506                         1 << (OP_EXCHANGE_ID - 32) |
2507                         1 << (OP_CREATE_SESSION - 32) |
2508                         1 << (OP_DESTROY_SESSION - 32) |
2509                         1 << (OP_DESTROY_CLIENTID - 32));
2510
2511                 exid->spo_must_allow[0] &= (1 << (OP_CLOSE) |
2512                                         1 << (OP_OPEN_DOWNGRADE) |
2513                                         1 << (OP_LOCKU) |
2514                                         1 << (OP_DELEGRETURN));
2515
2516                 exid->spo_must_allow[1] &= (
2517                                         1 << (OP_TEST_STATEID - 32) |
2518                                         1 << (OP_FREE_STATEID - 32));
2519                 if (!svc_rqst_integrity_protected(rqstp)) {
2520                         status = nfserr_inval;
2521                         goto out_nolock;
2522                 }
2523                 /*
2524                  * Sometimes userspace doesn't give us a principal.
2525                  * Which is a bug, really.  Anyway, we can't enforce
2526                  * MACH_CRED in that case, better to give up now:
2527                  */
2528                 if (!new->cl_cred.cr_principal &&
2529                                         !new->cl_cred.cr_raw_principal) {
2530                         status = nfserr_serverfault;
2531                         goto out_nolock;
2532                 }
2533                 new->cl_mach_cred = true;
2534         case SP4_NONE:
2535                 break;
2536         default:                                /* checked by xdr code */
2537                 WARN_ON_ONCE(1);
2538         case SP4_SSV:
2539                 status = nfserr_encr_alg_unsupp;
2540                 goto out_nolock;
2541         }
2542
2543         /* Cases below refer to rfc 5661 section 18.35.4: */
2544         spin_lock(&nn->client_lock);
2545         conf = find_confirmed_client_by_name(&exid->clname, nn);
2546         if (conf) {
2547                 bool creds_match = same_creds(&conf->cl_cred, &rqstp->rq_cred);
2548                 bool verfs_match = same_verf(&verf, &conf->cl_verifier);
2549
2550                 if (update) {
2551                         if (!clp_used_exchangeid(conf)) { /* buggy client */
2552                                 status = nfserr_inval;
2553                                 goto out;
2554                         }
2555                         if (!nfsd4_mach_creds_match(conf, rqstp)) {
2556                                 status = nfserr_wrong_cred;
2557                                 goto out;
2558                         }
2559                         if (!creds_match) { /* case 9 */
2560                                 status = nfserr_perm;
2561                                 goto out;
2562                         }
2563                         if (!verfs_match) { /* case 8 */
2564                                 status = nfserr_not_same;
2565                                 goto out;
2566                         }
2567                         /* case 6 */
2568                         exid->flags |= EXCHGID4_FLAG_CONFIRMED_R;
2569                         goto out_copy;
2570                 }
2571                 if (!creds_match) { /* case 3 */
2572                         if (client_has_state(conf)) {
2573                                 status = nfserr_clid_inuse;
2574                                 goto out;
2575                         }
2576                         goto out_new;
2577                 }
2578                 if (verfs_match) { /* case 2 */
2579                         conf->cl_exchange_flags |= EXCHGID4_FLAG_CONFIRMED_R;
2580                         goto out_copy;
2581                 }
2582                 /* case 5, client reboot */
2583                 conf = NULL;
2584                 goto out_new;
2585         }
2586
2587         if (update) { /* case 7 */
2588                 status = nfserr_noent;
2589                 goto out;
2590         }
2591
2592         unconf  = find_unconfirmed_client_by_name(&exid->clname, nn);
2593         if (unconf) /* case 4, possible retry or client restart */
2594                 unhash_client_locked(unconf);
2595
2596         /* case 1 (normal case) */
2597 out_new:
2598         if (conf) {
2599                 status = mark_client_expired_locked(conf);
2600                 if (status)
2601                         goto out;
2602         }
2603         new->cl_minorversion = cstate->minorversion;
2604         new->cl_spo_must_allow.u.words[0] = exid->spo_must_allow[0];
2605         new->cl_spo_must_allow.u.words[1] = exid->spo_must_allow[1];
2606
2607         gen_clid(new, nn);
2608         add_to_unconfirmed(new);
2609         swap(new, conf);
2610 out_copy:
2611         exid->clientid.cl_boot = conf->cl_clientid.cl_boot;
2612         exid->clientid.cl_id = conf->cl_clientid.cl_id;
2613
2614         exid->seqid = conf->cl_cs_slot.sl_seqid + 1;
2615         nfsd4_set_ex_flags(conf, exid);
2616
2617         dprintk("nfsd4_exchange_id seqid %d flags %x\n",
2618                 conf->cl_cs_slot.sl_seqid, conf->cl_exchange_flags);
2619         status = nfs_ok;
2620
2621 out:
2622         spin_unlock(&nn->client_lock);
2623 out_nolock:
2624         if (new)
2625                 expire_client(new);
2626         if (unconf)
2627                 expire_client(unconf);
2628         return status;
2629 }
2630
2631 static __be32
2632 check_slot_seqid(u32 seqid, u32 slot_seqid, int slot_inuse)
2633 {
2634         dprintk("%s enter. seqid %d slot_seqid %d\n", __func__, seqid,
2635                 slot_seqid);
2636
2637         /* The slot is in use, and no response has been sent. */
2638         if (slot_inuse) {
2639                 if (seqid == slot_seqid)
2640                         return nfserr_jukebox;
2641                 else
2642                         return nfserr_seq_misordered;
2643         }
2644         /* Note unsigned 32-bit arithmetic handles wraparound: */
2645         if (likely(seqid == slot_seqid + 1))
2646                 return nfs_ok;
2647         if (seqid == slot_seqid)
2648                 return nfserr_replay_cache;
2649         return nfserr_seq_misordered;
2650 }
2651
2652 /*
2653  * Cache the create session result into the create session single DRC
2654  * slot cache by saving the xdr structure. sl_seqid has been set.
2655  * Do this for solo or embedded create session operations.
2656  */
2657 static void
2658 nfsd4_cache_create_session(struct nfsd4_create_session *cr_ses,
2659                            struct nfsd4_clid_slot *slot, __be32 nfserr)
2660 {
2661         slot->sl_status = nfserr;
2662         memcpy(&slot->sl_cr_ses, cr_ses, sizeof(*cr_ses));
2663 }
2664
2665 static __be32
2666 nfsd4_replay_create_session(struct nfsd4_create_session *cr_ses,
2667                             struct nfsd4_clid_slot *slot)
2668 {
2669         memcpy(cr_ses, &slot->sl_cr_ses, sizeof(*cr_ses));
2670         return slot->sl_status;
2671 }
2672
2673 #define NFSD_MIN_REQ_HDR_SEQ_SZ ((\
2674                         2 * 2 + /* credential,verifier: AUTH_NULL, length 0 */ \
2675                         1 +     /* MIN tag is length with zero, only length */ \
2676                         3 +     /* version, opcount, opcode */ \
2677                         XDR_QUADLEN(NFS4_MAX_SESSIONID_LEN) + \
2678                                 /* seqid, slotID, slotID, cache */ \
2679                         4 ) * sizeof(__be32))
2680
2681 #define NFSD_MIN_RESP_HDR_SEQ_SZ ((\
2682                         2 +     /* verifier: AUTH_NULL, length 0 */\
2683                         1 +     /* status */ \
2684                         1 +     /* MIN tag is length with zero, only length */ \
2685                         3 +     /* opcount, opcode, opstatus*/ \
2686                         XDR_QUADLEN(NFS4_MAX_SESSIONID_LEN) + \
2687                                 /* seqid, slotID, slotID, slotID, status */ \
2688                         5 ) * sizeof(__be32))
2689
2690 static __be32 check_forechannel_attrs(struct nfsd4_channel_attrs *ca, struct nfsd_net *nn)
2691 {
2692         u32 maxrpc = nn->nfsd_serv->sv_max_mesg;
2693
2694         if (ca->maxreq_sz < NFSD_MIN_REQ_HDR_SEQ_SZ)
2695                 return nfserr_toosmall;
2696         if (ca->maxresp_sz < NFSD_MIN_RESP_HDR_SEQ_SZ)
2697                 return nfserr_toosmall;
2698         ca->headerpadsz = 0;
2699         ca->maxreq_sz = min_t(u32, ca->maxreq_sz, maxrpc);
2700         ca->maxresp_sz = min_t(u32, ca->maxresp_sz, maxrpc);
2701         ca->maxops = min_t(u32, ca->maxops, NFSD_MAX_OPS_PER_COMPOUND);
2702         ca->maxresp_cached = min_t(u32, ca->maxresp_cached,
2703                         NFSD_SLOT_CACHE_SIZE + NFSD_MIN_HDR_SEQ_SZ);
2704         ca->maxreqs = min_t(u32, ca->maxreqs, NFSD_MAX_SLOTS_PER_SESSION);
2705         /*
2706          * Note decreasing slot size below client's request may make it
2707          * difficult for client to function correctly, whereas
2708          * decreasing the number of slots will (just?) affect
2709          * performance.  When short on memory we therefore prefer to
2710          * decrease number of slots instead of their size.  Clients that
2711          * request larger slots than they need will get poor results:
2712          */
2713         ca->maxreqs = nfsd4_get_drc_mem(ca);
2714         if (!ca->maxreqs)
2715                 return nfserr_jukebox;
2716
2717         return nfs_ok;
2718 }
2719
2720 /*
2721  * Server's NFSv4.1 backchannel support is AUTH_SYS-only for now.
2722  * These are based on similar macros in linux/sunrpc/msg_prot.h .
2723  */
2724 #define RPC_MAX_HEADER_WITH_AUTH_SYS \
2725         (RPC_CALLHDRSIZE + 2 * (2 + UNX_CALLSLACK))
2726
2727 #define RPC_MAX_REPHEADER_WITH_AUTH_SYS \
2728         (RPC_REPHDRSIZE + (2 + NUL_REPLYSLACK))
2729
2730 #define NFSD_CB_MAX_REQ_SZ      ((NFS4_enc_cb_recall_sz + \
2731                                  RPC_MAX_HEADER_WITH_AUTH_SYS) * sizeof(__be32))
2732 #define NFSD_CB_MAX_RESP_SZ     ((NFS4_dec_cb_recall_sz + \
2733                                  RPC_MAX_REPHEADER_WITH_AUTH_SYS) * \
2734                                  sizeof(__be32))
2735
2736 static __be32 check_backchannel_attrs(struct nfsd4_channel_attrs *ca)
2737 {
2738         ca->headerpadsz = 0;
2739
2740         if (ca->maxreq_sz < NFSD_CB_MAX_REQ_SZ)
2741                 return nfserr_toosmall;
2742         if (ca->maxresp_sz < NFSD_CB_MAX_RESP_SZ)
2743                 return nfserr_toosmall;
2744         ca->maxresp_cached = 0;
2745         if (ca->maxops < 2)
2746                 return nfserr_toosmall;
2747
2748         return nfs_ok;
2749 }
2750
2751 static __be32 nfsd4_check_cb_sec(struct nfsd4_cb_sec *cbs)
2752 {
2753         switch (cbs->flavor) {
2754         case RPC_AUTH_NULL:
2755         case RPC_AUTH_UNIX:
2756                 return nfs_ok;
2757         default:
2758                 /*
2759                  * GSS case: the spec doesn't allow us to return this
2760                  * error.  But it also doesn't allow us not to support
2761                  * GSS.
2762                  * I'd rather this fail hard than return some error the
2763                  * client might think it can already handle:
2764                  */
2765                 return nfserr_encr_alg_unsupp;
2766         }
2767 }
2768
2769 __be32
2770 nfsd4_create_session(struct svc_rqst *rqstp,
2771                 struct nfsd4_compound_state *cstate, union nfsd4_op_u *u)
2772 {
2773         struct nfsd4_create_session *cr_ses = &u->create_session;
2774         struct sockaddr *sa = svc_addr(rqstp);
2775         struct nfs4_client *conf, *unconf;
2776         struct nfs4_client *old = NULL;
2777         struct nfsd4_session *new;
2778         struct nfsd4_conn *conn;
2779         struct nfsd4_clid_slot *cs_slot = NULL;
2780         __be32 status = 0;
2781         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
2782
2783         if (cr_ses->flags & ~SESSION4_FLAG_MASK_A)
2784                 return nfserr_inval;
2785         status = nfsd4_check_cb_sec(&cr_ses->cb_sec);
2786         if (status)
2787                 return status;
2788         status = check_forechannel_attrs(&cr_ses->fore_channel, nn);
2789         if (status)
2790                 return status;
2791         status = check_backchannel_attrs(&cr_ses->back_channel);
2792         if (status)
2793                 goto out_release_drc_mem;
2794         status = nfserr_jukebox;
2795         new = alloc_session(&cr_ses->fore_channel, &cr_ses->back_channel);
2796         if (!new)
2797                 goto out_release_drc_mem;
2798         conn = alloc_conn_from_crses(rqstp, cr_ses);
2799         if (!conn)
2800                 goto out_free_session;
2801
2802         spin_lock(&nn->client_lock);
2803         unconf = find_unconfirmed_client(&cr_ses->clientid, true, nn);
2804         conf = find_confirmed_client(&cr_ses->clientid, true, nn);
2805         WARN_ON_ONCE(conf && unconf);
2806
2807         if (conf) {
2808                 status = nfserr_wrong_cred;
2809                 if (!nfsd4_mach_creds_match(conf, rqstp))
2810                         goto out_free_conn;
2811                 cs_slot = &conf->cl_cs_slot;
2812                 status = check_slot_seqid(cr_ses->seqid, cs_slot->sl_seqid, 0);
2813                 if (status) {
2814                         if (status == nfserr_replay_cache)
2815                                 status = nfsd4_replay_create_session(cr_ses, cs_slot);
2816                         goto out_free_conn;
2817                 }
2818         } else if (unconf) {
2819                 if (!same_creds(&unconf->cl_cred, &rqstp->rq_cred) ||
2820                     !rpc_cmp_addr(sa, (struct sockaddr *) &unconf->cl_addr)) {
2821                         status = nfserr_clid_inuse;
2822                         goto out_free_conn;
2823                 }
2824                 status = nfserr_wrong_cred;
2825                 if (!nfsd4_mach_creds_match(unconf, rqstp))
2826                         goto out_free_conn;
2827                 cs_slot = &unconf->cl_cs_slot;
2828                 status = check_slot_seqid(cr_ses->seqid, cs_slot->sl_seqid, 0);
2829                 if (status) {
2830                         /* an unconfirmed replay returns misordered */
2831                         status = nfserr_seq_misordered;
2832                         goto out_free_conn;
2833                 }
2834                 old = find_confirmed_client_by_name(&unconf->cl_name, nn);
2835                 if (old) {
2836                         status = mark_client_expired_locked(old);
2837                         if (status) {
2838                                 old = NULL;
2839                                 goto out_free_conn;
2840                         }
2841                 }
2842                 move_to_confirmed(unconf);
2843                 conf = unconf;
2844         } else {
2845                 status = nfserr_stale_clientid;
2846                 goto out_free_conn;
2847         }
2848         status = nfs_ok;
2849         /* Persistent sessions are not supported */
2850         cr_ses->flags &= ~SESSION4_PERSIST;
2851         /* Upshifting from TCP to RDMA is not supported */
2852         cr_ses->flags &= ~SESSION4_RDMA;
2853
2854         init_session(rqstp, new, conf, cr_ses);
2855         nfsd4_get_session_locked(new);
2856
2857         memcpy(cr_ses->sessionid.data, new->se_sessionid.data,
2858                NFS4_MAX_SESSIONID_LEN);
2859         cs_slot->sl_seqid++;
2860         cr_ses->seqid = cs_slot->sl_seqid;
2861
2862         /* cache solo and embedded create sessions under the client_lock */
2863         nfsd4_cache_create_session(cr_ses, cs_slot, status);
2864         spin_unlock(&nn->client_lock);
2865         /* init connection and backchannel */
2866         nfsd4_init_conn(rqstp, conn, new);
2867         nfsd4_put_session(new);
2868         if (old)
2869                 expire_client(old);
2870         return status;
2871 out_free_conn:
2872         spin_unlock(&nn->client_lock);
2873         free_conn(conn);
2874         if (old)
2875                 expire_client(old);
2876 out_free_session:
2877         __free_session(new);
2878 out_release_drc_mem:
2879         nfsd4_put_drc_mem(&cr_ses->fore_channel);
2880         return status;
2881 }
2882
2883 static __be32 nfsd4_map_bcts_dir(u32 *dir)
2884 {
2885         switch (*dir) {
2886         case NFS4_CDFC4_FORE:
2887         case NFS4_CDFC4_BACK:
2888                 return nfs_ok;
2889         case NFS4_CDFC4_FORE_OR_BOTH:
2890         case NFS4_CDFC4_BACK_OR_BOTH:
2891                 *dir = NFS4_CDFC4_BOTH;
2892                 return nfs_ok;
2893         };
2894         return nfserr_inval;
2895 }
2896
2897 __be32 nfsd4_backchannel_ctl(struct svc_rqst *rqstp,
2898                 struct nfsd4_compound_state *cstate,
2899                 union nfsd4_op_u *u)
2900 {
2901         struct nfsd4_backchannel_ctl *bc = &u->backchannel_ctl;
2902         struct nfsd4_session *session = cstate->session;
2903         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
2904         __be32 status;
2905
2906         status = nfsd4_check_cb_sec(&bc->bc_cb_sec);
2907         if (status)
2908                 return status;
2909         spin_lock(&nn->client_lock);
2910         session->se_cb_prog = bc->bc_cb_program;
2911         session->se_cb_sec = bc->bc_cb_sec;
2912         spin_unlock(&nn->client_lock);
2913
2914         nfsd4_probe_callback(session->se_client);
2915
2916         return nfs_ok;
2917 }
2918
2919 __be32 nfsd4_bind_conn_to_session(struct svc_rqst *rqstp,
2920                      struct nfsd4_compound_state *cstate,
2921                      union nfsd4_op_u *u)
2922 {
2923         struct nfsd4_bind_conn_to_session *bcts = &u->bind_conn_to_session;
2924         __be32 status;
2925         struct nfsd4_conn *conn;
2926         struct nfsd4_session *session;
2927         struct net *net = SVC_NET(rqstp);
2928         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
2929
2930         if (!nfsd4_last_compound_op(rqstp))
2931                 return nfserr_not_only_op;
2932         spin_lock(&nn->client_lock);
2933         session = find_in_sessionid_hashtbl(&bcts->sessionid, net, &status);
2934         spin_unlock(&nn->client_lock);
2935         if (!session)
2936                 goto out_no_session;
2937         status = nfserr_wrong_cred;
2938         if (!nfsd4_mach_creds_match(session->se_client, rqstp))
2939                 goto out;
2940         status = nfsd4_map_bcts_dir(&bcts->dir);
2941         if (status)
2942                 goto out;
2943         conn = alloc_conn(rqstp, bcts->dir);
2944         status = nfserr_jukebox;
2945         if (!conn)
2946                 goto out;
2947         nfsd4_init_conn(rqstp, conn, session);
2948         status = nfs_ok;
2949 out:
2950         nfsd4_put_session(session);
2951 out_no_session:
2952         return status;
2953 }
2954
2955 static bool nfsd4_compound_in_session(struct nfsd4_session *session, struct nfs4_sessionid *sid)
2956 {
2957         if (!session)
2958                 return 0;
2959         return !memcmp(sid, &session->se_sessionid, sizeof(*sid));
2960 }
2961
2962 __be32
2963 nfsd4_destroy_session(struct svc_rqst *r, struct nfsd4_compound_state *cstate,
2964                 union nfsd4_op_u *u)
2965 {
2966         struct nfsd4_destroy_session *sessionid = &u->destroy_session;
2967         struct nfsd4_session *ses;
2968         __be32 status;
2969         int ref_held_by_me = 0;
2970         struct net *net = SVC_NET(r);
2971         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
2972
2973         status = nfserr_not_only_op;
2974         if (nfsd4_compound_in_session(cstate->session, &sessionid->sessionid)) {
2975                 if (!nfsd4_last_compound_op(r))
2976                         goto out;
2977                 ref_held_by_me++;
2978         }
2979         dump_sessionid(__func__, &sessionid->sessionid);
2980         spin_lock(&nn->client_lock);
2981         ses = find_in_sessionid_hashtbl(&sessionid->sessionid, net, &status);
2982         if (!ses)
2983                 goto out_client_lock;
2984         status = nfserr_wrong_cred;
2985         if (!nfsd4_mach_creds_match(ses->se_client, r))
2986                 goto out_put_session;
2987         status = mark_session_dead_locked(ses, 1 + ref_held_by_me);
2988         if (status)
2989                 goto out_put_session;
2990         unhash_session(ses);
2991         spin_unlock(&nn->client_lock);
2992
2993         nfsd4_probe_callback_sync(ses->se_client);
2994
2995         spin_lock(&nn->client_lock);
2996         status = nfs_ok;
2997 out_put_session:
2998         nfsd4_put_session_locked(ses);
2999 out_client_lock:
3000         spin_unlock(&nn->client_lock);
3001 out:
3002         return status;
3003 }
3004
3005 static struct nfsd4_conn *__nfsd4_find_conn(struct svc_xprt *xpt, struct nfsd4_session *s)
3006 {
3007         struct nfsd4_conn *c;
3008
3009         list_for_each_entry(c, &s->se_conns, cn_persession) {
3010                 if (c->cn_xprt == xpt) {
3011                         return c;
3012                 }
3013         }
3014         return NULL;
3015 }
3016
3017 static __be32 nfsd4_sequence_check_conn(struct nfsd4_conn *new, struct nfsd4_session *ses)
3018 {
3019         struct nfs4_client *clp = ses->se_client;
3020         struct nfsd4_conn *c;
3021         __be32 status = nfs_ok;
3022         int ret;
3023
3024         spin_lock(&clp->cl_lock);
3025         c = __nfsd4_find_conn(new->cn_xprt, ses);
3026         if (c)
3027                 goto out_free;
3028         status = nfserr_conn_not_bound_to_session;
3029         if (clp->cl_mach_cred)
3030                 goto out_free;
3031         __nfsd4_hash_conn(new, ses);
3032         spin_unlock(&clp->cl_lock);
3033         ret = nfsd4_register_conn(new);
3034         if (ret)
3035                 /* oops; xprt is already down: */
3036                 nfsd4_conn_lost(&new->cn_xpt_user);
3037         return nfs_ok;
3038 out_free:
3039         spin_unlock(&clp->cl_lock);
3040         free_conn(new);
3041         return status;
3042 }
3043
3044 static bool nfsd4_session_too_many_ops(struct svc_rqst *rqstp, struct nfsd4_session *session)
3045 {
3046         struct nfsd4_compoundargs *args = rqstp->rq_argp;
3047
3048         return args->opcnt > session->se_fchannel.maxops;
3049 }
3050
3051 static bool nfsd4_request_too_big(struct svc_rqst *rqstp,
3052                                   struct nfsd4_session *session)
3053 {
3054         struct xdr_buf *xb = &rqstp->rq_arg;
3055
3056         return xb->len > session->se_fchannel.maxreq_sz;
3057 }
3058
3059 static bool replay_matches_cache(struct svc_rqst *rqstp,
3060                  struct nfsd4_sequence *seq, struct nfsd4_slot *slot)
3061 {
3062         struct nfsd4_compoundargs *argp = rqstp->rq_argp;
3063
3064         if ((bool)(slot->sl_flags & NFSD4_SLOT_CACHETHIS) !=
3065             (bool)seq->cachethis)
3066                 return false;
3067         /*
3068          * If there's an error then the reply can have fewer ops than
3069          * the call.
3070          */
3071         if (slot->sl_opcnt < argp->opcnt && !slot->sl_status)
3072                 return false;
3073         /*
3074          * But if we cached a reply with *more* ops than the call you're
3075          * sending us now, then this new call is clearly not really a
3076          * replay of the old one:
3077          */
3078         if (slot->sl_opcnt > argp->opcnt)
3079                 return false;
3080         /* This is the only check explicitly called by spec: */
3081         if (!same_creds(&rqstp->rq_cred, &slot->sl_cred))
3082                 return false;
3083         /*
3084          * There may be more comparisons we could actually do, but the
3085          * spec doesn't require us to catch every case where the calls
3086          * don't match (that would require caching the call as well as
3087          * the reply), so we don't bother.
3088          */
3089         return true;
3090 }
3091
3092 __be32
3093 nfsd4_sequence(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3094                 union nfsd4_op_u *u)
3095 {
3096         struct nfsd4_sequence *seq = &u->sequence;
3097         struct nfsd4_compoundres *resp = rqstp->rq_resp;
3098         struct xdr_stream *xdr = &resp->xdr;
3099         struct nfsd4_session *session;
3100         struct nfs4_client *clp;
3101         struct nfsd4_slot *slot;
3102         struct nfsd4_conn *conn;
3103         __be32 status;
3104         int buflen;
3105         struct net *net = SVC_NET(rqstp);
3106         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
3107
3108         if (resp->opcnt != 1)
3109                 return nfserr_sequence_pos;
3110
3111         /*
3112          * Will be either used or freed by nfsd4_sequence_check_conn
3113          * below.
3114          */
3115         conn = alloc_conn(rqstp, NFS4_CDFC4_FORE);
3116         if (!conn)
3117                 return nfserr_jukebox;
3118
3119         spin_lock(&nn->client_lock);
3120         session = find_in_sessionid_hashtbl(&seq->sessionid, net, &status);
3121         if (!session)
3122                 goto out_no_session;
3123         clp = session->se_client;
3124
3125         status = nfserr_too_many_ops;
3126         if (nfsd4_session_too_many_ops(rqstp, session))
3127                 goto out_put_session;
3128
3129         status = nfserr_req_too_big;
3130         if (nfsd4_request_too_big(rqstp, session))
3131                 goto out_put_session;
3132
3133         status = nfserr_badslot;
3134         if (seq->slotid >= session->se_fchannel.maxreqs)
3135                 goto out_put_session;
3136
3137         slot = session->se_slots[seq->slotid];
3138         dprintk("%s: slotid %d\n", __func__, seq->slotid);
3139
3140         /* We do not negotiate the number of slots yet, so set the
3141          * maxslots to the session maxreqs which is used to encode
3142          * sr_highest_slotid and the sr_target_slot id to maxslots */
3143         seq->maxslots = session->se_fchannel.maxreqs;
3144
3145         status = check_slot_seqid(seq->seqid, slot->sl_seqid,
3146                                         slot->sl_flags & NFSD4_SLOT_INUSE);
3147         if (status == nfserr_replay_cache) {
3148                 status = nfserr_seq_misordered;
3149                 if (!(slot->sl_flags & NFSD4_SLOT_INITIALIZED))
3150                         goto out_put_session;
3151                 status = nfserr_seq_false_retry;
3152                 if (!replay_matches_cache(rqstp, seq, slot))
3153                         goto out_put_session;
3154                 cstate->slot = slot;
3155                 cstate->session = session;
3156                 cstate->clp = clp;
3157                 /* Return the cached reply status and set cstate->status
3158                  * for nfsd4_proc_compound processing */
3159                 status = nfsd4_replay_cache_entry(resp, seq);
3160                 cstate->status = nfserr_replay_cache;
3161                 goto out;
3162         }
3163         if (status)
3164                 goto out_put_session;
3165
3166         status = nfsd4_sequence_check_conn(conn, session);
3167         conn = NULL;
3168         if (status)
3169                 goto out_put_session;
3170
3171         buflen = (seq->cachethis) ?
3172                         session->se_fchannel.maxresp_cached :
3173                         session->se_fchannel.maxresp_sz;
3174         status = (seq->cachethis) ? nfserr_rep_too_big_to_cache :
3175                                     nfserr_rep_too_big;
3176         if (xdr_restrict_buflen(xdr, buflen - rqstp->rq_auth_slack))
3177                 goto out_put_session;
3178         svc_reserve(rqstp, buflen);
3179
3180         status = nfs_ok;
3181         /* Success! bump slot seqid */
3182         slot->sl_seqid = seq->seqid;
3183         slot->sl_flags |= NFSD4_SLOT_INUSE;
3184         if (seq->cachethis)
3185                 slot->sl_flags |= NFSD4_SLOT_CACHETHIS;
3186         else
3187                 slot->sl_flags &= ~NFSD4_SLOT_CACHETHIS;
3188
3189         cstate->slot = slot;
3190         cstate->session = session;
3191         cstate->clp = clp;
3192
3193 out:
3194         switch (clp->cl_cb_state) {
3195         case NFSD4_CB_DOWN:
3196                 seq->status_flags = SEQ4_STATUS_CB_PATH_DOWN;
3197                 break;
3198         case NFSD4_CB_FAULT:
3199                 seq->status_flags = SEQ4_STATUS_BACKCHANNEL_FAULT;
3200                 break;
3201         default:
3202                 seq->status_flags = 0;
3203         }
3204         if (!list_empty(&clp->cl_revoked))
3205                 seq->status_flags |= SEQ4_STATUS_RECALLABLE_STATE_REVOKED;
3206 out_no_session:
3207         if (conn)
3208                 free_conn(conn);
3209         spin_unlock(&nn->client_lock);
3210         return status;
3211 out_put_session:
3212         nfsd4_put_session_locked(session);
3213         goto out_no_session;
3214 }
3215
3216 void
3217 nfsd4_sequence_done(struct nfsd4_compoundres *resp)
3218 {
3219         struct nfsd4_compound_state *cs = &resp->cstate;
3220
3221         if (nfsd4_has_session(cs)) {
3222                 if (cs->status != nfserr_replay_cache) {
3223                         nfsd4_store_cache_entry(resp);
3224                         cs->slot->sl_flags &= ~NFSD4_SLOT_INUSE;
3225                 }
3226                 /* Drop session reference that was taken in nfsd4_sequence() */
3227                 nfsd4_put_session(cs->session);
3228         } else if (cs->clp)
3229                 put_client_renew(cs->clp);
3230 }
3231
3232 __be32
3233 nfsd4_destroy_clientid(struct svc_rqst *rqstp,
3234                 struct nfsd4_compound_state *cstate,
3235                 union nfsd4_op_u *u)
3236 {
3237         struct nfsd4_destroy_clientid *dc = &u->destroy_clientid;
3238         struct nfs4_client *conf, *unconf;
3239         struct nfs4_client *clp = NULL;
3240         __be32 status = 0;
3241         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
3242
3243         spin_lock(&nn->client_lock);
3244         unconf = find_unconfirmed_client(&dc->clientid, true, nn);
3245         conf = find_confirmed_client(&dc->clientid, true, nn);
3246         WARN_ON_ONCE(conf && unconf);
3247
3248         if (conf) {
3249                 if (client_has_state(conf)) {
3250                         status = nfserr_clientid_busy;
3251                         goto out;
3252                 }
3253                 status = mark_client_expired_locked(conf);
3254                 if (status)
3255                         goto out;
3256                 clp = conf;
3257         } else if (unconf)
3258                 clp = unconf;
3259         else {
3260                 status = nfserr_stale_clientid;
3261                 goto out;
3262         }
3263         if (!nfsd4_mach_creds_match(clp, rqstp)) {
3264                 clp = NULL;
3265                 status = nfserr_wrong_cred;
3266                 goto out;
3267         }
3268         unhash_client_locked(clp);
3269 out:
3270         spin_unlock(&nn->client_lock);
3271         if (clp)
3272                 expire_client(clp);
3273         return status;
3274 }
3275
3276 __be32
3277 nfsd4_reclaim_complete(struct svc_rqst *rqstp,
3278                 struct nfsd4_compound_state *cstate, union nfsd4_op_u *u)
3279 {
3280         struct nfsd4_reclaim_complete *rc = &u->reclaim_complete;
3281         __be32 status = 0;
3282
3283         if (rc->rca_one_fs) {
3284                 if (!cstate->current_fh.fh_dentry)
3285                         return nfserr_nofilehandle;
3286                 /*
3287                  * We don't take advantage of the rca_one_fs case.
3288                  * That's OK, it's optional, we can safely ignore it.
3289                  */
3290                 return nfs_ok;
3291         }
3292
3293         status = nfserr_complete_already;
3294         if (test_and_set_bit(NFSD4_CLIENT_RECLAIM_COMPLETE,
3295                              &cstate->session->se_client->cl_flags))
3296                 goto out;
3297
3298         status = nfserr_stale_clientid;
3299         if (is_client_expired(cstate->session->se_client))
3300                 /*
3301                  * The following error isn't really legal.
3302                  * But we only get here if the client just explicitly
3303                  * destroyed the client.  Surely it no longer cares what
3304                  * error it gets back on an operation for the dead
3305                  * client.
3306                  */
3307                 goto out;
3308
3309         status = nfs_ok;
3310         nfsd4_client_record_create(cstate->session->se_client);
3311 out:
3312         return status;
3313 }
3314
3315 __be32
3316 nfsd4_setclientid(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3317                   union nfsd4_op_u *u)
3318 {
3319         struct nfsd4_setclientid *setclid = &u->setclientid;
3320         struct xdr_netobj       clname = setclid->se_name;
3321         nfs4_verifier           clverifier = setclid->se_verf;
3322         struct nfs4_client      *conf, *new;
3323         struct nfs4_client      *unconf = NULL;
3324         __be32                  status;
3325         struct nfsd_net         *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
3326
3327         new = create_client(clname, rqstp, &clverifier);
3328         if (new == NULL)
3329                 return nfserr_jukebox;
3330         /* Cases below refer to rfc 3530 section 14.2.33: */
3331         spin_lock(&nn->client_lock);
3332         conf = find_confirmed_client_by_name(&clname, nn);
3333         if (conf && client_has_state(conf)) {
3334                 /* case 0: */
3335                 status = nfserr_clid_inuse;
3336                 if (clp_used_exchangeid(conf))
3337                         goto out;
3338                 if (!same_creds(&conf->cl_cred, &rqstp->rq_cred)) {
3339                         char addr_str[INET6_ADDRSTRLEN];
3340                         rpc_ntop((struct sockaddr *) &conf->cl_addr, addr_str,
3341                                  sizeof(addr_str));
3342                         dprintk("NFSD: setclientid: string in use by client "
3343                                 "at %s\n", addr_str);
3344                         goto out;
3345                 }
3346         }
3347         unconf = find_unconfirmed_client_by_name(&clname, nn);
3348         if (unconf)
3349                 unhash_client_locked(unconf);
3350         if (conf && same_verf(&conf->cl_verifier, &clverifier)) {
3351                 /* case 1: probable callback update */
3352                 copy_clid(new, conf);
3353                 gen_confirm(new, nn);
3354         } else /* case 4 (new client) or cases 2, 3 (client reboot): */
3355                 gen_clid(new, nn);
3356         new->cl_minorversion = 0;
3357         gen_callback(new, setclid, rqstp);
3358         add_to_unconfirmed(new);
3359         setclid->se_clientid.cl_boot = new->cl_clientid.cl_boot;
3360         setclid->se_clientid.cl_id = new->cl_clientid.cl_id;
3361         memcpy(setclid->se_confirm.data, new->cl_confirm.data, sizeof(setclid->se_confirm.data));
3362         new = NULL;
3363         status = nfs_ok;
3364 out:
3365         spin_unlock(&nn->client_lock);
3366         if (new)
3367                 free_client(new);
3368         if (unconf)
3369                 expire_client(unconf);
3370         return status;
3371 }
3372
3373
3374 __be32
3375 nfsd4_setclientid_confirm(struct svc_rqst *rqstp,
3376                         struct nfsd4_compound_state *cstate,
3377                         union nfsd4_op_u *u)
3378 {
3379         struct nfsd4_setclientid_confirm *setclientid_confirm =
3380                         &u->setclientid_confirm;
3381         struct nfs4_client *conf, *unconf;
3382         struct nfs4_client *old = NULL;
3383         nfs4_verifier confirm = setclientid_confirm->sc_confirm; 
3384         clientid_t * clid = &setclientid_confirm->sc_clientid;
3385         __be32 status;
3386         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
3387
3388         if (STALE_CLIENTID(clid, nn))
3389                 return nfserr_stale_clientid;
3390
3391         spin_lock(&nn->client_lock);
3392         conf = find_confirmed_client(clid, false, nn);
3393         unconf = find_unconfirmed_client(clid, false, nn);
3394         /*
3395          * We try hard to give out unique clientid's, so if we get an
3396          * attempt to confirm the same clientid with a different cred,
3397          * the client may be buggy; this should never happen.
3398          *
3399          * Nevertheless, RFC 7530 recommends INUSE for this case:
3400          */
3401         status = nfserr_clid_inuse;
3402         if (unconf && !same_creds(&unconf->cl_cred, &rqstp->rq_cred))
3403                 goto out;
3404         if (conf && !same_creds(&conf->cl_cred, &rqstp->rq_cred))
3405                 goto out;
3406         /* cases below refer to rfc 3530 section 14.2.34: */
3407         if (!unconf || !same_verf(&confirm, &unconf->cl_confirm)) {
3408                 if (conf && same_verf(&confirm, &conf->cl_confirm)) {
3409                         /* case 2: probable retransmit */
3410                         status = nfs_ok;
3411                 } else /* case 4: client hasn't noticed we rebooted yet? */
3412                         status = nfserr_stale_clientid;
3413                 goto out;
3414         }
3415         status = nfs_ok;
3416         if (conf) { /* case 1: callback update */
3417                 old = unconf;
3418                 unhash_client_locked(old);
3419                 nfsd4_change_callback(conf, &unconf->cl_cb_conn);
3420         } else { /* case 3: normal case; new or rebooted client */
3421                 old = find_confirmed_client_by_name(&unconf->cl_name, nn);
3422                 if (old) {
3423                         status = nfserr_clid_inuse;
3424                         if (client_has_state(old)
3425                                         && !same_creds(&unconf->cl_cred,
3426                                                         &old->cl_cred))
3427                                 goto out;
3428                         status = mark_client_expired_locked(old);
3429                         if (status) {
3430                                 old = NULL;
3431                                 goto out;
3432                         }
3433                 }
3434                 move_to_confirmed(unconf);
3435                 conf = unconf;
3436         }
3437         get_client_locked(conf);
3438         spin_unlock(&nn->client_lock);
3439         nfsd4_probe_callback(conf);
3440         spin_lock(&nn->client_lock);
3441         put_client_renew_locked(conf);
3442 out:
3443         spin_unlock(&nn->client_lock);
3444         if (old)
3445                 expire_client(old);
3446         return status;
3447 }
3448
3449 static struct nfs4_file *nfsd4_alloc_file(void)
3450 {
3451         return kmem_cache_alloc(file_slab, GFP_KERNEL);
3452 }
3453
3454 /* OPEN Share state helper functions */
3455 static void nfsd4_init_file(struct knfsd_fh *fh, unsigned int hashval,
3456                                 struct nfs4_file *fp)
3457 {
3458         lockdep_assert_held(&state_lock);
3459
3460         atomic_set(&fp->fi_ref, 1);
3461         spin_lock_init(&fp->fi_lock);
3462         INIT_LIST_HEAD(&fp->fi_stateids);
3463         INIT_LIST_HEAD(&fp->fi_delegations);
3464         INIT_LIST_HEAD(&fp->fi_clnt_odstate);
3465         fh_copy_shallow(&fp->fi_fhandle, fh);
3466         fp->fi_deleg_file = NULL;
3467         fp->fi_had_conflict = false;
3468         fp->fi_share_deny = 0;
3469         memset(fp->fi_fds, 0, sizeof(fp->fi_fds));
3470         memset(fp->fi_access, 0, sizeof(fp->fi_access));
3471 #ifdef CONFIG_NFSD_PNFS
3472         INIT_LIST_HEAD(&fp->fi_lo_states);
3473         atomic_set(&fp->fi_lo_recalls, 0);
3474 #endif
3475         hlist_add_head_rcu(&fp->fi_hash, &file_hashtbl[hashval]);
3476 }
3477
3478 void
3479 nfsd4_free_slabs(void)
3480 {
3481         kmem_cache_destroy(odstate_slab);
3482         kmem_cache_destroy(openowner_slab);
3483         kmem_cache_destroy(lockowner_slab);
3484         kmem_cache_destroy(file_slab);
3485         kmem_cache_destroy(stateid_slab);
3486         kmem_cache_destroy(deleg_slab);
3487 }
3488
3489 int
3490 nfsd4_init_slabs(void)
3491 {
3492         openowner_slab = kmem_cache_create("nfsd4_openowners",
3493                         sizeof(struct nfs4_openowner), 0, 0, NULL);
3494         if (openowner_slab == NULL)
3495                 goto out;
3496         lockowner_slab = kmem_cache_create("nfsd4_lockowners",
3497                         sizeof(struct nfs4_lockowner), 0, 0, NULL);
3498         if (lockowner_slab == NULL)
3499                 goto out_free_openowner_slab;
3500         file_slab = kmem_cache_create("nfsd4_files",
3501                         sizeof(struct nfs4_file), 0, 0, NULL);
3502         if (file_slab == NULL)
3503                 goto out_free_lockowner_slab;
3504         stateid_slab = kmem_cache_create("nfsd4_stateids",
3505                         sizeof(struct nfs4_ol_stateid), 0, 0, NULL);
3506         if (stateid_slab == NULL)
3507                 goto out_free_file_slab;
3508         deleg_slab = kmem_cache_create("nfsd4_delegations",
3509                         sizeof(struct nfs4_delegation), 0, 0, NULL);
3510         if (deleg_slab == NULL)
3511                 goto out_free_stateid_slab;
3512         odstate_slab = kmem_cache_create("nfsd4_odstate",
3513                         sizeof(struct nfs4_clnt_odstate), 0, 0, NULL);
3514         if (odstate_slab == NULL)
3515                 goto out_free_deleg_slab;
3516         return 0;
3517
3518 out_free_deleg_slab:
3519         kmem_cache_destroy(deleg_slab);
3520 out_free_stateid_slab:
3521         kmem_cache_destroy(stateid_slab);
3522 out_free_file_slab:
3523         kmem_cache_destroy(file_slab);
3524 out_free_lockowner_slab:
3525         kmem_cache_destroy(lockowner_slab);
3526 out_free_openowner_slab:
3527         kmem_cache_destroy(openowner_slab);
3528 out:
3529         dprintk("nfsd4: out of memory while initializing nfsv4\n");
3530         return -ENOMEM;
3531 }
3532
3533 static void init_nfs4_replay(struct nfs4_replay *rp)
3534 {
3535         rp->rp_status = nfserr_serverfault;
3536         rp->rp_buflen = 0;
3537         rp->rp_buf = rp->rp_ibuf;
3538         mutex_init(&rp->rp_mutex);
3539 }
3540
3541 static void nfsd4_cstate_assign_replay(struct nfsd4_compound_state *cstate,
3542                 struct nfs4_stateowner *so)
3543 {
3544         if (!nfsd4_has_session(cstate)) {
3545                 mutex_lock(&so->so_replay.rp_mutex);
3546                 cstate->replay_owner = nfs4_get_stateowner(so);
3547         }
3548 }
3549
3550 void nfsd4_cstate_clear_replay(struct nfsd4_compound_state *cstate)
3551 {
3552         struct nfs4_stateowner *so = cstate->replay_owner;
3553
3554         if (so != NULL) {
3555                 cstate->replay_owner = NULL;
3556                 mutex_unlock(&so->so_replay.rp_mutex);
3557                 nfs4_put_stateowner(so);
3558         }
3559 }
3560
3561 static inline void *alloc_stateowner(struct kmem_cache *slab, struct xdr_netobj *owner, struct nfs4_client *clp)
3562 {
3563         struct nfs4_stateowner *sop;
3564
3565         sop = kmem_cache_alloc(slab, GFP_KERNEL);
3566         if (!sop)
3567                 return NULL;
3568
3569         sop->so_owner.data = kmemdup(owner->data, owner->len, GFP_KERNEL);
3570         if (!sop->so_owner.data) {
3571                 kmem_cache_free(slab, sop);
3572                 return NULL;
3573         }
3574         sop->so_owner.len = owner->len;
3575
3576         INIT_LIST_HEAD(&sop->so_stateids);
3577         sop->so_client = clp;
3578         init_nfs4_replay(&sop->so_replay);
3579         atomic_set(&sop->so_count, 1);
3580         return sop;
3581 }
3582
3583 static void hash_openowner(struct nfs4_openowner *oo, struct nfs4_client *clp, unsigned int strhashval)
3584 {
3585         lockdep_assert_held(&clp->cl_lock);
3586
3587         list_add(&oo->oo_owner.so_strhash,
3588                  &clp->cl_ownerstr_hashtbl[strhashval]);
3589         list_add(&oo->oo_perclient, &clp->cl_openowners);
3590 }
3591
3592 static void nfs4_unhash_openowner(struct nfs4_stateowner *so)
3593 {
3594         unhash_openowner_locked(openowner(so));
3595 }
3596
3597 static void nfs4_free_openowner(struct nfs4_stateowner *so)
3598 {
3599         struct nfs4_openowner *oo = openowner(so);
3600
3601         kmem_cache_free(openowner_slab, oo);
3602 }
3603
3604 static const struct nfs4_stateowner_operations openowner_ops = {
3605         .so_unhash =    nfs4_unhash_openowner,
3606         .so_free =      nfs4_free_openowner,
3607 };
3608
3609 static struct nfs4_ol_stateid *
3610 nfsd4_find_existing_open(struct nfs4_file *fp, struct nfsd4_open *open)
3611 {
3612         struct nfs4_ol_stateid *local, *ret = NULL;
3613         struct nfs4_openowner *oo = open->op_openowner;
3614
3615         lockdep_assert_held(&fp->fi_lock);
3616
3617         list_for_each_entry(local, &fp->fi_stateids, st_perfile) {
3618                 /* ignore lock owners */
3619                 if (local->st_stateowner->so_is_open_owner == 0)
3620                         continue;
3621                 if (local->st_stateowner != &oo->oo_owner)
3622                         continue;
3623                 if (local->st_stid.sc_type == NFS4_OPEN_STID) {
3624                         ret = local;
3625                         atomic_inc(&ret->st_stid.sc_count);
3626                         break;
3627                 }
3628         }
3629         return ret;
3630 }
3631
3632 static __be32
3633 nfsd4_verify_open_stid(struct nfs4_stid *s)
3634 {
3635         __be32 ret = nfs_ok;
3636
3637         switch (s->sc_type) {
3638         default:
3639                 break;
3640         case NFS4_CLOSED_STID:
3641         case NFS4_CLOSED_DELEG_STID:
3642                 ret = nfserr_bad_stateid;
3643                 break;
3644         case NFS4_REVOKED_DELEG_STID:
3645                 ret = nfserr_deleg_revoked;
3646         }
3647         return ret;
3648 }
3649
3650 /* Lock the stateid st_mutex, and deal with races with CLOSE */
3651 static __be32
3652 nfsd4_lock_ol_stateid(struct nfs4_ol_stateid *stp)
3653 {
3654         __be32 ret;
3655
3656         mutex_lock(&stp->st_mutex);
3657         ret = nfsd4_verify_open_stid(&stp->st_stid);
3658         if (ret != nfs_ok)
3659                 mutex_unlock(&stp->st_mutex);
3660         return ret;
3661 }
3662
3663 static struct nfs4_ol_stateid *
3664 nfsd4_find_and_lock_existing_open(struct nfs4_file *fp, struct nfsd4_open *open)
3665 {
3666         struct nfs4_ol_stateid *stp;
3667         for (;;) {
3668                 spin_lock(&fp->fi_lock);
3669                 stp = nfsd4_find_existing_open(fp, open);
3670                 spin_unlock(&fp->fi_lock);
3671                 if (!stp || nfsd4_lock_ol_stateid(stp) == nfs_ok)
3672                         break;
3673                 nfs4_put_stid(&stp->st_stid);
3674         }
3675         return stp;
3676 }
3677
3678 static struct nfs4_openowner *
3679 alloc_init_open_stateowner(unsigned int strhashval, struct nfsd4_open *open,
3680                            struct nfsd4_compound_state *cstate)
3681 {
3682         struct nfs4_client *clp = cstate->clp;
3683         struct nfs4_openowner *oo, *ret;
3684
3685         oo = alloc_stateowner(openowner_slab, &open->op_owner, clp);
3686         if (!oo)
3687                 return NULL;
3688         oo->oo_owner.so_ops = &openowner_ops;
3689         oo->oo_owner.so_is_open_owner = 1;
3690         oo->oo_owner.so_seqid = open->op_seqid;
3691         oo->oo_flags = 0;
3692         if (nfsd4_has_session(cstate))
3693                 oo->oo_flags |= NFS4_OO_CONFIRMED;
3694         oo->oo_time = 0;
3695         oo->oo_last_closed_stid = NULL;
3696         INIT_LIST_HEAD(&oo->oo_close_lru);
3697         spin_lock(&clp->cl_lock);
3698         ret = find_openstateowner_str_locked(strhashval, open, clp);
3699         if (ret == NULL) {
3700                 hash_openowner(oo, clp, strhashval);
3701                 ret = oo;
3702         } else
3703                 nfs4_free_stateowner(&oo->oo_owner);
3704
3705         spin_unlock(&clp->cl_lock);
3706         return ret;
3707 }
3708
3709 static struct nfs4_ol_stateid *
3710 init_open_stateid(struct nfs4_file *fp, struct nfsd4_open *open)
3711 {
3712
3713         struct nfs4_openowner *oo = open->op_openowner;
3714         struct nfs4_ol_stateid *retstp = NULL;
3715         struct nfs4_ol_stateid *stp;
3716
3717         stp = open->op_stp;
3718         /* We are moving these outside of the spinlocks to avoid the warnings */
3719         mutex_init(&stp->st_mutex);
3720         mutex_lock(&stp->st_mutex);
3721
3722 retry:
3723         spin_lock(&oo->oo_owner.so_client->cl_lock);
3724         spin_lock(&fp->fi_lock);
3725
3726         retstp = nfsd4_find_existing_open(fp, open);
3727         if (retstp)
3728                 goto out_unlock;
3729
3730         open->op_stp = NULL;
3731         atomic_inc(&stp->st_stid.sc_count);
3732         stp->st_stid.sc_type = NFS4_OPEN_STID;
3733         INIT_LIST_HEAD(&stp->st_locks);
3734         stp->st_stateowner = nfs4_get_stateowner(&oo->oo_owner);
3735         get_nfs4_file(fp);
3736         stp->st_stid.sc_file = fp;
3737         stp->st_access_bmap = 0;
3738         stp->st_deny_bmap = 0;
3739         stp->st_openstp = NULL;
3740         list_add(&stp->st_perstateowner, &oo->oo_owner.so_stateids);
3741         list_add(&stp->st_perfile, &fp->fi_stateids);
3742
3743 out_unlock:
3744         spin_unlock(&fp->fi_lock);
3745         spin_unlock(&oo->oo_owner.so_client->cl_lock);
3746         if (retstp) {
3747                 /* Handle races with CLOSE */
3748                 if (nfsd4_lock_ol_stateid(retstp) != nfs_ok) {
3749                         nfs4_put_stid(&retstp->st_stid);
3750                         goto retry;
3751                 }
3752                 /* To keep mutex tracking happy */
3753                 mutex_unlock(&stp->st_mutex);
3754                 stp = retstp;
3755         }
3756         return stp;
3757 }
3758
3759 /*
3760  * In the 4.0 case we need to keep the owners around a little while to handle
3761  * CLOSE replay. We still do need to release any file access that is held by
3762  * them before returning however.
3763  */
3764 static void
3765 move_to_close_lru(struct nfs4_ol_stateid *s, struct net *net)
3766 {
3767         struct nfs4_ol_stateid *last;
3768         struct nfs4_openowner *oo = openowner(s->st_stateowner);
3769         struct nfsd_net *nn = net_generic(s->st_stid.sc_client->net,
3770                                                 nfsd_net_id);
3771
3772         dprintk("NFSD: move_to_close_lru nfs4_openowner %p\n", oo);
3773
3774         /*
3775          * We know that we hold one reference via nfsd4_close, and another
3776          * "persistent" reference for the client. If the refcount is higher
3777          * than 2, then there are still calls in progress that are using this
3778          * stateid. We can't put the sc_file reference until they are finished.
3779          * Wait for the refcount to drop to 2. Since it has been unhashed,
3780          * there should be no danger of the refcount going back up again at
3781          * this point.
3782          */
3783         wait_event(close_wq, atomic_read(&s->st_stid.sc_count) == 2);
3784
3785         release_all_access(s);
3786         if (s->st_stid.sc_file) {
3787                 put_nfs4_file(s->st_stid.sc_file);
3788                 s->st_stid.sc_file = NULL;
3789         }
3790
3791         spin_lock(&nn->client_lock);
3792         last = oo->oo_last_closed_stid;
3793         oo->oo_last_closed_stid = s;
3794         list_move_tail(&oo->oo_close_lru, &nn->close_lru);
3795         oo->oo_time = get_seconds();
3796         spin_unlock(&nn->client_lock);
3797         if (last)
3798                 nfs4_put_stid(&last->st_stid);
3799 }
3800
3801 /* search file_hashtbl[] for file */
3802 static struct nfs4_file *
3803 find_file_locked(struct knfsd_fh *fh, unsigned int hashval)
3804 {
3805         struct nfs4_file *fp;
3806
3807         hlist_for_each_entry_rcu(fp, &file_hashtbl[hashval], fi_hash) {
3808                 if (fh_match(&fp->fi_fhandle, fh)) {
3809                         if (atomic_inc_not_zero(&fp->fi_ref))
3810                                 return fp;
3811                 }
3812         }
3813         return NULL;
3814 }
3815
3816 struct nfs4_file *
3817 find_file(struct knfsd_fh *fh)
3818 {
3819         struct nfs4_file *fp;
3820         unsigned int hashval = file_hashval(fh);
3821
3822         rcu_read_lock();
3823         fp = find_file_locked(fh, hashval);
3824         rcu_read_unlock();
3825         return fp;
3826 }
3827
3828 static struct nfs4_file *
3829 find_or_add_file(struct nfs4_file *new, struct knfsd_fh *fh)
3830 {
3831         struct nfs4_file *fp;
3832         unsigned int hashval = file_hashval(fh);
3833
3834         rcu_read_lock();
3835         fp = find_file_locked(fh, hashval);
3836         rcu_read_unlock();
3837         if (fp)
3838                 return fp;
3839
3840         spin_lock(&state_lock);
3841         fp = find_file_locked(fh, hashval);
3842         if (likely(fp == NULL)) {
3843                 nfsd4_init_file(fh, hashval, new);
3844                 fp = new;
3845         }
3846         spin_unlock(&state_lock);
3847
3848         return fp;
3849 }
3850
3851 /*
3852  * Called to check deny when READ with all zero stateid or
3853  * WRITE with all zero or all one stateid
3854  */
3855 static __be32
3856 nfs4_share_conflict(struct svc_fh *current_fh, unsigned int deny_type)
3857 {
3858         struct nfs4_file *fp;
3859         __be32 ret = nfs_ok;
3860
3861         fp = find_file(&current_fh->fh_handle);
3862         if (!fp)
3863                 return ret;
3864         /* Check for conflicting share reservations */
3865         spin_lock(&fp->fi_lock);
3866         if (fp->fi_share_deny & deny_type)
3867                 ret = nfserr_locked;
3868         spin_unlock(&fp->fi_lock);
3869         put_nfs4_file(fp);
3870         return ret;
3871 }
3872
3873 static void nfsd4_cb_recall_prepare(struct nfsd4_callback *cb)
3874 {
3875         struct nfs4_delegation *dp = cb_to_delegation(cb);
3876         struct nfsd_net *nn = net_generic(dp->dl_stid.sc_client->net,
3877                                           nfsd_net_id);
3878
3879         block_delegations(&dp->dl_stid.sc_file->fi_fhandle);
3880
3881         /*
3882          * We can't do this in nfsd_break_deleg_cb because it is
3883          * already holding inode->i_lock.
3884          *
3885          * If the dl_time != 0, then we know that it has already been
3886          * queued for a lease break. Don't queue it again.
3887          */
3888         spin_lock(&state_lock);
3889         if (delegation_hashed(dp) && dp->dl_time == 0) {
3890                 dp->dl_time = get_seconds();
3891                 list_add_tail(&dp->dl_recall_lru, &nn->del_recall_lru);
3892         }
3893         spin_unlock(&state_lock);
3894 }
3895
3896 static int nfsd4_cb_recall_done(struct nfsd4_callback *cb,
3897                 struct rpc_task *task)
3898 {
3899         struct nfs4_delegation *dp = cb_to_delegation(cb);
3900
3901         if (dp->dl_stid.sc_type == NFS4_CLOSED_DELEG_STID)
3902                 return 1;
3903
3904         switch (task->tk_status) {
3905         case 0:
3906                 return 1;
3907         case -EBADHANDLE:
3908         case -NFS4ERR_BAD_STATEID:
3909                 /*
3910                  * Race: client probably got cb_recall before open reply
3911                  * granting delegation.
3912                  */
3913                 if (dp->dl_retries--) {
3914                         rpc_delay(task, 2 * HZ);
3915                         return 0;
3916                 }
3917                 /*FALLTHRU*/
3918         default:
3919                 return -1;
3920         }
3921 }
3922
3923 static void nfsd4_cb_recall_release(struct nfsd4_callback *cb)
3924 {
3925         struct nfs4_delegation *dp = cb_to_delegation(cb);
3926
3927         nfs4_put_stid(&dp->dl_stid);
3928 }
3929
3930 static const struct nfsd4_callback_ops nfsd4_cb_recall_ops = {
3931         .prepare        = nfsd4_cb_recall_prepare,
3932         .done           = nfsd4_cb_recall_done,
3933         .release        = nfsd4_cb_recall_release,
3934 };
3935
3936 static void nfsd_break_one_deleg(struct nfs4_delegation *dp)
3937 {
3938         /*
3939          * We're assuming the state code never drops its reference
3940          * without first removing the lease.  Since we're in this lease
3941          * callback (and since the lease code is serialized by the kernel
3942          * lock) we know the server hasn't removed the lease yet, we know
3943          * it's safe to take a reference.
3944          */
3945         atomic_inc(&dp->dl_stid.sc_count);
3946         nfsd4_run_cb(&dp->dl_recall);
3947 }
3948
3949 /* Called from break_lease() with i_lock held. */
3950 static bool
3951 nfsd_break_deleg_cb(struct file_lock *fl)
3952 {
3953         bool ret = false;
3954         struct nfs4_file *fp = (struct nfs4_file *)fl->fl_owner;
3955         struct nfs4_delegation *dp;
3956
3957         if (!fp) {
3958                 WARN(1, "(%p)->fl_owner NULL\n", fl);
3959                 return ret;
3960         }
3961         if (fp->fi_had_conflict) {
3962                 WARN(1, "duplicate break on %p\n", fp);
3963                 return ret;
3964         }
3965         /*
3966          * We don't want the locks code to timeout the lease for us;
3967          * we'll remove it ourself if a delegation isn't returned
3968          * in time:
3969          */
3970         fl->fl_break_time = 0;
3971
3972         spin_lock(&fp->fi_lock);
3973         fp->fi_had_conflict = true;
3974         /*
3975          * If there are no delegations on the list, then return true
3976          * so that the lease code will go ahead and delete it.
3977          */
3978         if (list_empty(&fp->fi_delegations))
3979                 ret = true;
3980         else
3981                 list_for_each_entry(dp, &fp->fi_delegations, dl_perfile)
3982                         nfsd_break_one_deleg(dp);
3983         spin_unlock(&fp->fi_lock);
3984         return ret;
3985 }
3986
3987 static int
3988 nfsd_change_deleg_cb(struct file_lock *onlist, int arg,
3989                      struct list_head *dispose)
3990 {
3991         if (arg & F_UNLCK)
3992                 return lease_modify(onlist, arg, dispose);
3993         else
3994                 return -EAGAIN;
3995 }
3996
3997 static const struct lock_manager_operations nfsd_lease_mng_ops = {
3998         .lm_break = nfsd_break_deleg_cb,
3999         .lm_change = nfsd_change_deleg_cb,
4000 };
4001
4002 static __be32 nfsd4_check_seqid(struct nfsd4_compound_state *cstate, struct nfs4_stateowner *so, u32 seqid)
4003 {
4004         if (nfsd4_has_session(cstate))
4005                 return nfs_ok;
4006         if (seqid == so->so_seqid - 1)
4007                 return nfserr_replay_me;
4008         if (seqid == so->so_seqid)
4009                 return nfs_ok;
4010         return nfserr_bad_seqid;
4011 }
4012
4013 static __be32 lookup_clientid(clientid_t *clid,
4014                 struct nfsd4_compound_state *cstate,
4015                 struct nfsd_net *nn)
4016 {
4017         struct nfs4_client *found;
4018
4019         if (cstate->clp) {
4020                 found = cstate->clp;
4021                 if (!same_clid(&found->cl_clientid, clid))
4022                         return nfserr_stale_clientid;
4023                 return nfs_ok;
4024         }
4025
4026         if (STALE_CLIENTID(clid, nn))
4027                 return nfserr_stale_clientid;
4028
4029         /*
4030          * For v4.1+ we get the client in the SEQUENCE op. If we don't have one
4031          * cached already then we know this is for is for v4.0 and "sessions"
4032          * will be false.
4033          */
4034         WARN_ON_ONCE(cstate->session);
4035         spin_lock(&nn->client_lock);
4036         found = find_confirmed_client(clid, false, nn);
4037         if (!found) {
4038                 spin_unlock(&nn->client_lock);
4039                 return nfserr_expired;
4040         }
4041         atomic_inc(&found->cl_refcount);
4042         spin_unlock(&nn->client_lock);
4043
4044         /* Cache the nfs4_client in cstate! */
4045         cstate->clp = found;
4046         return nfs_ok;
4047 }
4048
4049 __be32
4050 nfsd4_process_open1(struct nfsd4_compound_state *cstate,
4051                     struct nfsd4_open *open, struct nfsd_net *nn)
4052 {
4053         clientid_t *clientid = &open->op_clientid;
4054         struct nfs4_client *clp = NULL;
4055         unsigned int strhashval;
4056         struct nfs4_openowner *oo = NULL;
4057         __be32 status;
4058
4059         if (STALE_CLIENTID(&open->op_clientid, nn))
4060                 return nfserr_stale_clientid;
4061         /*
4062          * In case we need it later, after we've already created the
4063          * file and don't want to risk a further failure:
4064          */
4065         open->op_file = nfsd4_alloc_file();
4066         if (open->op_file == NULL)
4067                 return nfserr_jukebox;
4068
4069         status = lookup_clientid(clientid, cstate, nn);
4070         if (status)
4071                 return status;
4072         clp = cstate->clp;
4073
4074         strhashval = ownerstr_hashval(&open->op_owner);
4075         oo = find_openstateowner_str(strhashval, open, clp);
4076         open->op_openowner = oo;
4077         if (!oo) {
4078                 goto new_owner;
4079         }
4080         if (!(oo->oo_flags & NFS4_OO_CONFIRMED)) {
4081                 /* Replace unconfirmed owners without checking for replay. */
4082                 release_openowner(oo);
4083                 open->op_openowner = NULL;
4084                 goto new_owner;
4085         }
4086         status = nfsd4_check_seqid(cstate, &oo->oo_owner, open->op_seqid);
4087         if (status)
4088                 return status;
4089         goto alloc_stateid;
4090 new_owner:
4091         oo = alloc_init_open_stateowner(strhashval, open, cstate);
4092         if (oo == NULL)
4093                 return nfserr_jukebox;
4094         open->op_openowner = oo;
4095 alloc_stateid:
4096         open->op_stp = nfs4_alloc_open_stateid(clp);
4097         if (!open->op_stp)
4098                 return nfserr_jukebox;
4099
4100         if (nfsd4_has_session(cstate) &&
4101             (cstate->current_fh.fh_export->ex_flags & NFSEXP_PNFS)) {
4102                 open->op_odstate = alloc_clnt_odstate(clp);
4103                 if (!open->op_odstate)
4104                         return nfserr_jukebox;
4105         }
4106
4107         return nfs_ok;
4108 }
4109
4110 static inline __be32
4111 nfs4_check_delegmode(struct nfs4_delegation *dp, int flags)
4112 {
4113         if ((flags & WR_STATE) && (dp->dl_type == NFS4_OPEN_DELEGATE_READ))
4114                 return nfserr_openmode;
4115         else
4116                 return nfs_ok;
4117 }
4118
4119 static int share_access_to_flags(u32 share_access)
4120 {
4121         return share_access == NFS4_SHARE_ACCESS_READ ? RD_STATE : WR_STATE;
4122 }
4123
4124 static struct nfs4_delegation *find_deleg_stateid(struct nfs4_client *cl, stateid_t *s)
4125 {
4126         struct nfs4_stid *ret;
4127
4128         ret = find_stateid_by_type(cl, s,
4129                                 NFS4_DELEG_STID|NFS4_REVOKED_DELEG_STID);
4130         if (!ret)
4131                 return NULL;
4132         return delegstateid(ret);
4133 }
4134
4135 static bool nfsd4_is_deleg_cur(struct nfsd4_open *open)
4136 {
4137         return open->op_claim_type == NFS4_OPEN_CLAIM_DELEGATE_CUR ||
4138                open->op_claim_type == NFS4_OPEN_CLAIM_DELEG_CUR_FH;
4139 }
4140
4141 static __be32
4142 nfs4_check_deleg(struct nfs4_client *cl, struct nfsd4_open *open,
4143                 struct nfs4_delegation **dp)
4144 {
4145         int flags;
4146         __be32 status = nfserr_bad_stateid;
4147         struct nfs4_delegation *deleg;
4148
4149         deleg = find_deleg_stateid(cl, &open->op_delegate_stateid);
4150         if (deleg == NULL)
4151                 goto out;
4152         if (deleg->dl_stid.sc_type == NFS4_REVOKED_DELEG_STID) {
4153                 nfs4_put_stid(&deleg->dl_stid);
4154                 if (cl->cl_minorversion)
4155                         status = nfserr_deleg_revoked;
4156                 goto out;
4157         }
4158         flags = share_access_to_flags(open->op_share_access);
4159         status = nfs4_check_delegmode(deleg, flags);
4160         if (status) {
4161                 nfs4_put_stid(&deleg->dl_stid);
4162                 goto out;
4163         }
4164         *dp = deleg;
4165 out:
4166         if (!nfsd4_is_deleg_cur(open))
4167                 return nfs_ok;
4168         if (status)
4169                 return status;
4170         open->op_openowner->oo_flags |= NFS4_OO_CONFIRMED;
4171         return nfs_ok;
4172 }
4173
4174 static inline int nfs4_access_to_access(u32 nfs4_access)
4175 {
4176         int flags = 0;
4177
4178         if (nfs4_access & NFS4_SHARE_ACCESS_READ)
4179                 flags |= NFSD_MAY_READ;
4180         if (nfs4_access & NFS4_SHARE_ACCESS_WRITE)
4181                 flags |= NFSD_MAY_WRITE;
4182         return flags;
4183 }
4184
4185 static inline __be32
4186 nfsd4_truncate(struct svc_rqst *rqstp, struct svc_fh *fh,
4187                 struct nfsd4_open *open)
4188 {
4189         struct iattr iattr = {
4190                 .ia_valid = ATTR_SIZE,
4191                 .ia_size = 0,
4192         };
4193         if (!open->op_truncate)
4194                 return 0;
4195         if (!(open->op_share_access & NFS4_SHARE_ACCESS_WRITE))
4196                 return nfserr_inval;
4197         return nfsd_setattr(rqstp, fh, &iattr, 0, (time_t)0);
4198 }
4199
4200 static __be32 nfs4_get_vfs_file(struct svc_rqst *rqstp, struct nfs4_file *fp,
4201                 struct svc_fh *cur_fh, struct nfs4_ol_stateid *stp,
4202                 struct nfsd4_open *open)
4203 {
4204         struct file *filp = NULL;
4205         __be32 status;
4206         int oflag = nfs4_access_to_omode(open->op_share_access);
4207         int access = nfs4_access_to_access(open->op_share_access);
4208         unsigned char old_access_bmap, old_deny_bmap;
4209
4210         spin_lock(&fp->fi_lock);
4211
4212         /*
4213          * Are we trying to set a deny mode that would conflict with
4214          * current access?
4215          */
4216         status = nfs4_file_check_deny(fp, open->op_share_deny);
4217         if (status != nfs_ok) {
4218                 spin_unlock(&fp->fi_lock);
4219                 goto out;
4220         }
4221
4222         /* set access to the file */
4223         status = nfs4_file_get_access(fp, open->op_share_access);
4224         if (status != nfs_ok) {
4225                 spin_unlock(&fp->fi_lock);
4226                 goto out;
4227         }
4228
4229         /* Set access bits in stateid */
4230         old_access_bmap = stp->st_access_bmap;
4231         set_access(open->op_share_access, stp);
4232
4233         /* Set new deny mask */
4234         old_deny_bmap = stp->st_deny_bmap;
4235         set_deny(open->op_share_deny, stp);
4236         fp->fi_share_deny |= (open->op_share_deny & NFS4_SHARE_DENY_BOTH);
4237
4238         if (!fp->fi_fds[oflag]) {
4239                 spin_unlock(&fp->fi_lock);
4240                 status = nfsd_open(rqstp, cur_fh, S_IFREG, access, &filp);
4241                 if (status)
4242                         goto out_put_access;
4243                 spin_lock(&fp->fi_lock);
4244                 if (!fp->fi_fds[oflag]) {
4245                         fp->fi_fds[oflag] = filp;
4246                         filp = NULL;
4247                 }
4248         }
4249         spin_unlock(&fp->fi_lock);
4250         if (filp)
4251                 fput(filp);
4252
4253         status = nfsd4_truncate(rqstp, cur_fh, open);
4254         if (status)
4255                 goto out_put_access;
4256 out:
4257         return status;
4258 out_put_access:
4259         stp->st_access_bmap = old_access_bmap;
4260         nfs4_file_put_access(fp, open->op_share_access);
4261         reset_union_bmap_deny(bmap_to_share_mode(old_deny_bmap), stp);
4262         goto out;
4263 }
4264
4265 static __be32
4266 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)
4267 {
4268         __be32 status;
4269         unsigned char old_deny_bmap = stp->st_deny_bmap;
4270
4271         if (!test_access(open->op_share_access, stp))
4272                 return nfs4_get_vfs_file(rqstp, fp, cur_fh, stp, open);
4273
4274         /* test and set deny mode */
4275         spin_lock(&fp->fi_lock);
4276         status = nfs4_file_check_deny(fp, open->op_share_deny);
4277         if (status == nfs_ok) {
4278                 set_deny(open->op_share_deny, stp);
4279                 fp->fi_share_deny |=
4280                                 (open->op_share_deny & NFS4_SHARE_DENY_BOTH);
4281         }
4282         spin_unlock(&fp->fi_lock);
4283
4284         if (status != nfs_ok)
4285                 return status;
4286
4287         status = nfsd4_truncate(rqstp, cur_fh, open);
4288         if (status != nfs_ok)
4289                 reset_union_bmap_deny(old_deny_bmap, stp);
4290         return status;
4291 }
4292
4293 /* Should we give out recallable state?: */
4294 static bool nfsd4_cb_channel_good(struct nfs4_client *clp)
4295 {
4296         if (clp->cl_cb_state == NFSD4_CB_UP)
4297                 return true;
4298         /*
4299          * In the sessions case, since we don't have to establish a
4300          * separate connection for callbacks, we assume it's OK
4301          * until we hear otherwise:
4302          */
4303         return clp->cl_minorversion && clp->cl_cb_state == NFSD4_CB_UNKNOWN;
4304 }
4305
4306 static struct file_lock *nfs4_alloc_init_lease(struct nfs4_file *fp, int flag)
4307 {
4308         struct file_lock *fl;
4309
4310         fl = locks_alloc_lock();
4311         if (!fl)
4312                 return NULL;
4313         fl->fl_lmops = &nfsd_lease_mng_ops;
4314         fl->fl_flags = FL_DELEG;
4315         fl->fl_type = flag == NFS4_OPEN_DELEGATE_READ? F_RDLCK: F_WRLCK;
4316         fl->fl_end = OFFSET_MAX;
4317         fl->fl_owner = (fl_owner_t)fp;
4318         fl->fl_pid = current->tgid;
4319         return fl;
4320 }
4321
4322 /**
4323  * nfs4_setlease - Obtain a delegation by requesting lease from vfs layer
4324  * @dp:   a pointer to the nfs4_delegation we're adding.
4325  *
4326  * Return:
4327  *      On success: Return code will be 0 on success.
4328  *
4329  *      On error: -EAGAIN if there was an existing delegation.
4330  *                 nonzero if there is an error in other cases.
4331  *
4332  */
4333
4334 static int nfs4_setlease(struct nfs4_delegation *dp)
4335 {
4336         struct nfs4_file *fp = dp->dl_stid.sc_file;
4337         struct file_lock *fl;
4338         struct file *filp;
4339         int status = 0;
4340
4341         fl = nfs4_alloc_init_lease(fp, NFS4_OPEN_DELEGATE_READ);
4342         if (!fl)
4343                 return -ENOMEM;
4344         filp = find_readable_file(fp);
4345         if (!filp) {
4346                 /* We should always have a readable file here */
4347                 WARN_ON_ONCE(1);
4348                 locks_free_lock(fl);
4349                 return -EBADF;
4350         }
4351         fl->fl_file = filp;
4352         status = vfs_setlease(filp, fl->fl_type, &fl, NULL);
4353         if (fl)
4354                 locks_free_lock(fl);
4355         if (status)
4356                 goto out_fput;
4357         spin_lock(&state_lock);
4358         spin_lock(&fp->fi_lock);
4359         /* Did the lease get broken before we took the lock? */
4360         status = -EAGAIN;
4361         if (fp->fi_had_conflict)
4362                 goto out_unlock;
4363         /* Race breaker */
4364         if (fp->fi_deleg_file) {
4365                 status = hash_delegation_locked(dp, fp);
4366                 goto out_unlock;
4367         }
4368         fp->fi_deleg_file = filp;
4369         fp->fi_delegees = 0;
4370         status = hash_delegation_locked(dp, fp);
4371         spin_unlock(&fp->fi_lock);
4372         spin_unlock(&state_lock);
4373         if (status) {
4374                 /* Should never happen, this is a new fi_deleg_file  */
4375                 WARN_ON_ONCE(1);
4376                 goto out_fput;
4377         }
4378         return 0;
4379 out_unlock:
4380         spin_unlock(&fp->fi_lock);
4381         spin_unlock(&state_lock);
4382 out_fput:
4383         fput(filp);
4384         return status;
4385 }
4386
4387 static struct nfs4_delegation *
4388 nfs4_set_delegation(struct nfs4_client *clp, struct svc_fh *fh,
4389                     struct nfs4_file *fp, struct nfs4_clnt_odstate *odstate)
4390 {
4391         int status;
4392         struct nfs4_delegation *dp;
4393
4394         if (fp->fi_had_conflict)
4395                 return ERR_PTR(-EAGAIN);
4396
4397         spin_lock(&state_lock);
4398         spin_lock(&fp->fi_lock);
4399         status = nfs4_get_existing_delegation(clp, fp);
4400         spin_unlock(&fp->fi_lock);
4401         spin_unlock(&state_lock);
4402
4403         if (status)
4404                 return ERR_PTR(status);
4405
4406         dp = alloc_init_deleg(clp, fh, odstate);
4407         if (!dp)
4408                 return ERR_PTR(-ENOMEM);
4409
4410         get_nfs4_file(fp);
4411         spin_lock(&state_lock);
4412         spin_lock(&fp->fi_lock);
4413         dp->dl_stid.sc_file = fp;
4414         if (!fp->fi_deleg_file) {
4415                 spin_unlock(&fp->fi_lock);
4416                 spin_unlock(&state_lock);
4417                 status = nfs4_setlease(dp);
4418                 goto out;
4419         }
4420         if (fp->fi_had_conflict) {
4421                 status = -EAGAIN;
4422                 goto out_unlock;
4423         }
4424         status = hash_delegation_locked(dp, fp);
4425 out_unlock:
4426         spin_unlock(&fp->fi_lock);
4427         spin_unlock(&state_lock);
4428 out:
4429         if (status) {
4430                 put_clnt_odstate(dp->dl_clnt_odstate);
4431                 nfs4_put_stid(&dp->dl_stid);
4432                 return ERR_PTR(status);
4433         }
4434         return dp;
4435 }
4436
4437 static void nfsd4_open_deleg_none_ext(struct nfsd4_open *open, int status)
4438 {
4439         open->op_delegate_type = NFS4_OPEN_DELEGATE_NONE_EXT;
4440         if (status == -EAGAIN)
4441                 open->op_why_no_deleg = WND4_CONTENTION;
4442         else {
4443                 open->op_why_no_deleg = WND4_RESOURCE;
4444                 switch (open->op_deleg_want) {
4445                 case NFS4_SHARE_WANT_READ_DELEG:
4446                 case NFS4_SHARE_WANT_WRITE_DELEG:
4447                 case NFS4_SHARE_WANT_ANY_DELEG:
4448                         break;
4449                 case NFS4_SHARE_WANT_CANCEL:
4450                         open->op_why_no_deleg = WND4_CANCELLED;
4451                         break;
4452                 case NFS4_SHARE_WANT_NO_DELEG:
4453                         WARN_ON_ONCE(1);
4454                 }
4455         }
4456 }
4457
4458 /*
4459  * Attempt to hand out a delegation.
4460  *
4461  * Note we don't support write delegations, and won't until the vfs has
4462  * proper support for them.
4463  */
4464 static void
4465 nfs4_open_delegation(struct svc_fh *fh, struct nfsd4_open *open,
4466                         struct nfs4_ol_stateid *stp)
4467 {
4468         struct nfs4_delegation *dp;
4469         struct nfs4_openowner *oo = openowner(stp->st_stateowner);
4470         struct nfs4_client *clp = stp->st_stid.sc_client;
4471         int cb_up;
4472         int status = 0;
4473
4474         cb_up = nfsd4_cb_channel_good(oo->oo_owner.so_client);
4475         open->op_recall = 0;
4476         switch (open->op_claim_type) {
4477                 case NFS4_OPEN_CLAIM_PREVIOUS:
4478                         if (!cb_up)
4479                                 open->op_recall = 1;
4480                         if (open->op_delegate_type != NFS4_OPEN_DELEGATE_READ)
4481                                 goto out_no_deleg;
4482                         break;
4483                 case NFS4_OPEN_CLAIM_NULL:
4484                 case NFS4_OPEN_CLAIM_FH:
4485                         /*
4486                          * Let's not give out any delegations till everyone's
4487                          * had the chance to reclaim theirs, *and* until
4488                          * NLM locks have all been reclaimed:
4489                          */
4490                         if (locks_in_grace(clp->net))
4491                                 goto out_no_deleg;
4492                         if (!cb_up || !(oo->oo_flags & NFS4_OO_CONFIRMED))
4493                                 goto out_no_deleg;
4494                         /*
4495                          * Also, if the file was opened for write or
4496                          * create, there's a good chance the client's
4497                          * about to write to it, resulting in an
4498                          * immediate recall (since we don't support
4499                          * write delegations):
4500                          */
4501                         if (open->op_share_access & NFS4_SHARE_ACCESS_WRITE)
4502                                 goto out_no_deleg;
4503                         if (open->op_create == NFS4_OPEN_CREATE)
4504                                 goto out_no_deleg;
4505                         break;
4506                 default:
4507                         goto out_no_deleg;
4508         }
4509         dp = nfs4_set_delegation(clp, fh, stp->st_stid.sc_file, stp->st_clnt_odstate);
4510         if (IS_ERR(dp))
4511                 goto out_no_deleg;
4512
4513         memcpy(&open->op_delegate_stateid, &dp->dl_stid.sc_stateid, sizeof(dp->dl_stid.sc_stateid));
4514
4515         dprintk("NFSD: delegation stateid=" STATEID_FMT "\n",
4516                 STATEID_VAL(&dp->dl_stid.sc_stateid));
4517         open->op_delegate_type = NFS4_OPEN_DELEGATE_READ;
4518         nfs4_put_stid(&dp->dl_stid);
4519         return;
4520 out_no_deleg:
4521         open->op_delegate_type = NFS4_OPEN_DELEGATE_NONE;
4522         if (open->op_claim_type == NFS4_OPEN_CLAIM_PREVIOUS &&
4523             open->op_delegate_type != NFS4_OPEN_DELEGATE_NONE) {
4524                 dprintk("NFSD: WARNING: refusing delegation reclaim\n");
4525                 open->op_recall = 1;
4526         }
4527
4528         /* 4.1 client asking for a delegation? */
4529         if (open->op_deleg_want)
4530                 nfsd4_open_deleg_none_ext(open, status);
4531         return;
4532 }
4533
4534 static void nfsd4_deleg_xgrade_none_ext(struct nfsd4_open *open,
4535                                         struct nfs4_delegation *dp)
4536 {
4537         if (open->op_deleg_want == NFS4_SHARE_WANT_READ_DELEG &&
4538             dp->dl_type == NFS4_OPEN_DELEGATE_WRITE) {
4539                 open->op_delegate_type = NFS4_OPEN_DELEGATE_NONE_EXT;
4540                 open->op_why_no_deleg = WND4_NOT_SUPP_DOWNGRADE;
4541         } else if (open->op_deleg_want == NFS4_SHARE_WANT_WRITE_DELEG &&
4542                    dp->dl_type == NFS4_OPEN_DELEGATE_WRITE) {
4543                 open->op_delegate_type = NFS4_OPEN_DELEGATE_NONE_EXT;
4544                 open->op_why_no_deleg = WND4_NOT_SUPP_UPGRADE;
4545         }
4546         /* Otherwise the client must be confused wanting a delegation
4547          * it already has, therefore we don't return
4548          * NFS4_OPEN_DELEGATE_NONE_EXT and reason.
4549          */
4550 }
4551
4552 __be32
4553 nfsd4_process_open2(struct svc_rqst *rqstp, struct svc_fh *current_fh, struct nfsd4_open *open)
4554 {
4555         struct nfsd4_compoundres *resp = rqstp->rq_resp;
4556         struct nfs4_client *cl = open->op_openowner->oo_owner.so_client;
4557         struct nfs4_file *fp = NULL;
4558         struct nfs4_ol_stateid *stp = NULL;
4559         struct nfs4_delegation *dp = NULL;
4560         __be32 status;
4561         bool new_stp = false;
4562
4563         /*
4564          * Lookup file; if found, lookup stateid and check open request,
4565          * and check for delegations in the process of being recalled.
4566          * If not found, create the nfs4_file struct
4567          */
4568         fp = find_or_add_file(open->op_file, &current_fh->fh_handle);
4569         if (fp != open->op_file) {
4570                 status = nfs4_check_deleg(cl, open, &dp);
4571                 if (status)
4572                         goto out;
4573                 stp = nfsd4_find_and_lock_existing_open(fp, open);
4574         } else {
4575                 open->op_file = NULL;
4576                 status = nfserr_bad_stateid;
4577                 if (nfsd4_is_deleg_cur(open))
4578                         goto out;
4579         }
4580
4581         if (!stp) {
4582                 stp = init_open_stateid(fp, open);
4583                 if (!open->op_stp)
4584                         new_stp = true;
4585         }
4586
4587         /*
4588          * OPEN the file, or upgrade an existing OPEN.
4589          * If truncate fails, the OPEN fails.
4590          *
4591          * stp is already locked.
4592          */
4593         if (!new_stp) {
4594                 /* Stateid was found, this is an OPEN upgrade */
4595                 status = nfs4_upgrade_open(rqstp, fp, current_fh, stp, open);
4596                 if (status) {
4597                         mutex_unlock(&stp->st_mutex);
4598                         goto out;
4599                 }
4600         } else {
4601                 status = nfs4_get_vfs_file(rqstp, fp, current_fh, stp, open);
4602                 if (status) {
4603                         stp->st_stid.sc_type = NFS4_CLOSED_STID;
4604                         release_open_stateid(stp);
4605                         mutex_unlock(&stp->st_mutex);
4606                         goto out;
4607                 }
4608
4609                 stp->st_clnt_odstate = find_or_hash_clnt_odstate(fp,
4610                                                         open->op_odstate);
4611                 if (stp->st_clnt_odstate == open->op_odstate)
4612                         open->op_odstate = NULL;
4613         }
4614
4615         nfs4_inc_and_copy_stateid(&open->op_stateid, &stp->st_stid);
4616         mutex_unlock(&stp->st_mutex);
4617
4618         if (nfsd4_has_session(&resp->cstate)) {
4619                 if (open->op_deleg_want & NFS4_SHARE_WANT_NO_DELEG) {
4620                         open->op_delegate_type = NFS4_OPEN_DELEGATE_NONE_EXT;
4621                         open->op_why_no_deleg = WND4_NOT_WANTED;
4622                         goto nodeleg;
4623                 }
4624         }
4625
4626         /*
4627         * Attempt to hand out a delegation. No error return, because the
4628         * OPEN succeeds even if we fail.
4629         */
4630         nfs4_open_delegation(current_fh, open, stp);
4631 nodeleg:
4632         status = nfs_ok;
4633
4634         dprintk("%s: stateid=" STATEID_FMT "\n", __func__,
4635                 STATEID_VAL(&stp->st_stid.sc_stateid));
4636 out:
4637         /* 4.1 client trying to upgrade/downgrade delegation? */
4638         if (open->op_delegate_type == NFS4_OPEN_DELEGATE_NONE && dp &&
4639             open->op_deleg_want)
4640                 nfsd4_deleg_xgrade_none_ext(open, dp);
4641
4642         if (fp)
4643                 put_nfs4_file(fp);
4644         if (status == 0 && open->op_claim_type == NFS4_OPEN_CLAIM_PREVIOUS)
4645                 open->op_openowner->oo_flags |= NFS4_OO_CONFIRMED;
4646         /*
4647         * To finish the open response, we just need to set the rflags.
4648         */
4649         open->op_rflags = NFS4_OPEN_RESULT_LOCKTYPE_POSIX;
4650         if (nfsd4_has_session(&resp->cstate))
4651                 open->op_rflags |= NFS4_OPEN_RESULT_MAY_NOTIFY_LOCK;
4652         else if (!(open->op_openowner->oo_flags & NFS4_OO_CONFIRMED))
4653                 open->op_rflags |= NFS4_OPEN_RESULT_CONFIRM;
4654
4655         if (dp)
4656                 nfs4_put_stid(&dp->dl_stid);
4657         if (stp)
4658                 nfs4_put_stid(&stp->st_stid);
4659
4660         return status;
4661 }
4662
4663 void nfsd4_cleanup_open_state(struct nfsd4_compound_state *cstate,
4664                               struct nfsd4_open *open)
4665 {
4666         if (open->op_openowner) {
4667                 struct nfs4_stateowner *so = &open->op_openowner->oo_owner;
4668
4669                 nfsd4_cstate_assign_replay(cstate, so);
4670                 nfs4_put_stateowner(so);
4671         }
4672         if (open->op_file)
4673                 kmem_cache_free(file_slab, open->op_file);
4674         if (open->op_stp)
4675                 nfs4_put_stid(&open->op_stp->st_stid);
4676         if (open->op_odstate)
4677                 kmem_cache_free(odstate_slab, open->op_odstate);
4678 }
4679
4680 __be32
4681 nfsd4_renew(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
4682             union nfsd4_op_u *u)
4683 {
4684         clientid_t *clid = &u->renew;
4685         struct nfs4_client *clp;
4686         __be32 status;
4687         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
4688
4689         dprintk("process_renew(%08x/%08x): starting\n", 
4690                         clid->cl_boot, clid->cl_id);
4691         status = lookup_clientid(clid, cstate, nn);
4692         if (status)
4693                 goto out;
4694         clp = cstate->clp;
4695         status = nfserr_cb_path_down;
4696         if (!list_empty(&clp->cl_delegations)
4697                         && clp->cl_cb_state != NFSD4_CB_UP)
4698                 goto out;
4699         status = nfs_ok;
4700 out:
4701         return status;
4702 }
4703
4704 void
4705 nfsd4_end_grace(struct nfsd_net *nn)
4706 {
4707         /* do nothing if grace period already ended */
4708         if (nn->grace_ended)
4709                 return;
4710
4711         dprintk("NFSD: end of grace period\n");
4712         nn->grace_ended = true;
4713         /*
4714          * If the server goes down again right now, an NFSv4
4715          * client will still be allowed to reclaim after it comes back up,
4716          * even if it hasn't yet had a chance to reclaim state this time.
4717          *
4718          */
4719         nfsd4_record_grace_done(nn);
4720         /*
4721          * At this point, NFSv4 clients can still reclaim.  But if the
4722          * server crashes, any that have not yet reclaimed will be out
4723          * of luck on the next boot.
4724          *
4725          * (NFSv4.1+ clients are considered to have reclaimed once they
4726          * call RECLAIM_COMPLETE.  NFSv4.0 clients are considered to
4727          * have reclaimed after their first OPEN.)
4728          */
4729         locks_end_grace(&nn->nfsd4_manager);
4730         /*
4731          * At this point, and once lockd and/or any other containers
4732          * exit their grace period, further reclaims will fail and
4733          * regular locking can resume.
4734          */
4735 }
4736
4737 static time_t
4738 nfs4_laundromat(struct nfsd_net *nn)
4739 {
4740         struct nfs4_client *clp;
4741         struct nfs4_openowner *oo;
4742         struct nfs4_delegation *dp;
4743         struct nfs4_ol_stateid *stp;
4744         struct nfsd4_blocked_lock *nbl;
4745         struct list_head *pos, *next, reaplist;
4746         time_t cutoff = get_seconds() - nn->nfsd4_lease;
4747         time_t t, new_timeo = nn->nfsd4_lease;
4748
4749         dprintk("NFSD: laundromat service - starting\n");
4750         nfsd4_end_grace(nn);
4751         INIT_LIST_HEAD(&reaplist);
4752         spin_lock(&nn->client_lock);
4753         list_for_each_safe(pos, next, &nn->client_lru) {
4754                 clp = list_entry(pos, struct nfs4_client, cl_lru);
4755                 if (time_after((unsigned long)clp->cl_time, (unsigned long)cutoff)) {
4756                         t = clp->cl_time - cutoff;
4757                         new_timeo = min(new_timeo, t);
4758                         break;
4759                 }
4760                 if (mark_client_expired_locked(clp)) {
4761                         dprintk("NFSD: client in use (clientid %08x)\n",
4762                                 clp->cl_clientid.cl_id);
4763                         continue;
4764                 }
4765                 list_add(&clp->cl_lru, &reaplist);
4766         }
4767         spin_unlock(&nn->client_lock);
4768         list_for_each_safe(pos, next, &reaplist) {
4769                 clp = list_entry(pos, struct nfs4_client, cl_lru);
4770                 dprintk("NFSD: purging unused client (clientid %08x)\n",
4771                         clp->cl_clientid.cl_id);
4772                 list_del_init(&clp->cl_lru);
4773                 expire_client(clp);
4774         }
4775         spin_lock(&state_lock);
4776         list_for_each_safe(pos, next, &nn->del_recall_lru) {
4777                 dp = list_entry (pos, struct nfs4_delegation, dl_recall_lru);
4778                 if (time_after((unsigned long)dp->dl_time, (unsigned long)cutoff)) {
4779                         t = dp->dl_time - cutoff;
4780                         new_timeo = min(new_timeo, t);
4781                         break;
4782                 }
4783                 WARN_ON(!unhash_delegation_locked(dp));
4784                 list_add(&dp->dl_recall_lru, &reaplist);
4785         }
4786         spin_unlock(&state_lock);
4787         while (!list_empty(&reaplist)) {
4788                 dp = list_first_entry(&reaplist, struct nfs4_delegation,
4789                                         dl_recall_lru);
4790                 list_del_init(&dp->dl_recall_lru);
4791                 revoke_delegation(dp);
4792         }
4793
4794         spin_lock(&nn->client_lock);
4795         while (!list_empty(&nn->close_lru)) {
4796                 oo = list_first_entry(&nn->close_lru, struct nfs4_openowner,
4797                                         oo_close_lru);
4798                 if (time_after((unsigned long)oo->oo_time,
4799                                (unsigned long)cutoff)) {
4800                         t = oo->oo_time - cutoff;
4801                         new_timeo = min(new_timeo, t);
4802                         break;
4803                 }
4804                 list_del_init(&oo->oo_close_lru);
4805                 stp = oo->oo_last_closed_stid;
4806                 oo->oo_last_closed_stid = NULL;
4807                 spin_unlock(&nn->client_lock);
4808                 nfs4_put_stid(&stp->st_stid);
4809                 spin_lock(&nn->client_lock);
4810         }
4811         spin_unlock(&nn->client_lock);
4812
4813         /*
4814          * It's possible for a client to try and acquire an already held lock
4815          * that is being held for a long time, and then lose interest in it.
4816          * So, we clean out any un-revisited request after a lease period
4817          * under the assumption that the client is no longer interested.
4818          *
4819          * RFC5661, sec. 9.6 states that the client must not rely on getting
4820          * notifications and must continue to poll for locks, even when the
4821          * server supports them. Thus this shouldn't lead to clients blocking
4822          * indefinitely once the lock does become free.
4823          */
4824         BUG_ON(!list_empty(&reaplist));
4825         spin_lock(&nn->blocked_locks_lock);
4826         while (!list_empty(&nn->blocked_locks_lru)) {
4827                 nbl = list_first_entry(&nn->blocked_locks_lru,
4828                                         struct nfsd4_blocked_lock, nbl_lru);
4829                 if (time_after((unsigned long)nbl->nbl_time,
4830                                (unsigned long)cutoff)) {
4831                         t = nbl->nbl_time - cutoff;
4832                         new_timeo = min(new_timeo, t);
4833                         break;
4834                 }
4835                 list_move(&nbl->nbl_lru, &reaplist);
4836                 list_del_init(&nbl->nbl_list);
4837         }
4838         spin_unlock(&nn->blocked_locks_lock);
4839
4840         while (!list_empty(&reaplist)) {
4841                 nbl = list_first_entry(&reaplist,
4842                                         struct nfsd4_blocked_lock, nbl_lru);
4843                 list_del_init(&nbl->nbl_lru);
4844                 posix_unblock_lock(&nbl->nbl_lock);
4845                 free_blocked_lock(nbl);
4846         }
4847
4848         new_timeo = max_t(time_t, new_timeo, NFSD_LAUNDROMAT_MINTIMEOUT);
4849         return new_timeo;
4850 }
4851
4852 static struct workqueue_struct *laundry_wq;
4853 static void laundromat_main(struct work_struct *);
4854
4855 static void
4856 laundromat_main(struct work_struct *laundry)
4857 {
4858         time_t t;
4859         struct delayed_work *dwork = to_delayed_work(laundry);
4860         struct nfsd_net *nn = container_of(dwork, struct nfsd_net,
4861                                            laundromat_work);
4862
4863         t = nfs4_laundromat(nn);
4864         dprintk("NFSD: laundromat_main - sleeping for %ld seconds\n", t);
4865         queue_delayed_work(laundry_wq, &nn->laundromat_work, t*HZ);
4866 }
4867
4868 static inline __be32 nfs4_check_fh(struct svc_fh *fhp, struct nfs4_stid *stp)
4869 {
4870         if (!fh_match(&fhp->fh_handle, &stp->sc_file->fi_fhandle))
4871                 return nfserr_bad_stateid;
4872         return nfs_ok;
4873 }
4874
4875 static inline int
4876 access_permit_read(struct nfs4_ol_stateid *stp)
4877 {
4878         return test_access(NFS4_SHARE_ACCESS_READ, stp) ||
4879                 test_access(NFS4_SHARE_ACCESS_BOTH, stp) ||
4880                 test_access(NFS4_SHARE_ACCESS_WRITE, stp);
4881 }
4882
4883 static inline int
4884 access_permit_write(struct nfs4_ol_stateid *stp)
4885 {
4886         return test_access(NFS4_SHARE_ACCESS_WRITE, stp) ||
4887                 test_access(NFS4_SHARE_ACCESS_BOTH, stp);
4888 }
4889
4890 static
4891 __be32 nfs4_check_openmode(struct nfs4_ol_stateid *stp, int flags)
4892 {
4893         __be32 status = nfserr_openmode;
4894
4895         /* For lock stateid's, we test the parent open, not the lock: */
4896         if (stp->st_openstp)
4897                 stp = stp->st_openstp;
4898         if ((flags & WR_STATE) && !access_permit_write(stp))
4899                 goto out;
4900         if ((flags & RD_STATE) && !access_permit_read(stp))
4901                 goto out;
4902         status = nfs_ok;
4903 out:
4904         return status;
4905 }
4906
4907 static inline __be32
4908 check_special_stateids(struct net *net, svc_fh *current_fh, stateid_t *stateid, int flags)
4909 {
4910         if (ONE_STATEID(stateid) && (flags & RD_STATE))
4911                 return nfs_ok;
4912         else if (opens_in_grace(net)) {
4913                 /* Answer in remaining cases depends on existence of
4914                  * conflicting state; so we must wait out the grace period. */
4915                 return nfserr_grace;
4916         } else if (flags & WR_STATE)
4917                 return nfs4_share_conflict(current_fh,
4918                                 NFS4_SHARE_DENY_WRITE);
4919         else /* (flags & RD_STATE) && ZERO_STATEID(stateid) */
4920                 return nfs4_share_conflict(current_fh,
4921                                 NFS4_SHARE_DENY_READ);
4922 }
4923
4924 /*
4925  * Allow READ/WRITE during grace period on recovered state only for files
4926  * that are not able to provide mandatory locking.
4927  */
4928 static inline int
4929 grace_disallows_io(struct net *net, struct inode *inode)
4930 {
4931         return opens_in_grace(net) && mandatory_lock(inode);
4932 }
4933
4934 static __be32 check_stateid_generation(stateid_t *in, stateid_t *ref, bool has_session)
4935 {
4936         /*
4937          * When sessions are used the stateid generation number is ignored
4938          * when it is zero.
4939          */
4940         if (has_session && in->si_generation == 0)
4941                 return nfs_ok;
4942
4943         if (in->si_generation == ref->si_generation)
4944                 return nfs_ok;
4945
4946         /* If the client sends us a stateid from the future, it's buggy: */
4947         if (nfsd4_stateid_generation_after(in, ref))
4948                 return nfserr_bad_stateid;
4949         /*
4950          * However, we could see a stateid from the past, even from a
4951          * non-buggy client.  For example, if the client sends a lock
4952          * while some IO is outstanding, the lock may bump si_generation
4953          * while the IO is still in flight.  The client could avoid that
4954          * situation by waiting for responses on all the IO requests,
4955          * but better performance may result in retrying IO that
4956          * receives an old_stateid error if requests are rarely
4957          * reordered in flight:
4958          */
4959         return nfserr_old_stateid;
4960 }
4961
4962 static __be32 nfsd4_check_openowner_confirmed(struct nfs4_ol_stateid *ols)
4963 {
4964         if (ols->st_stateowner->so_is_open_owner &&
4965             !(openowner(ols->st_stateowner)->oo_flags & NFS4_OO_CONFIRMED))
4966                 return nfserr_bad_stateid;
4967         return nfs_ok;
4968 }
4969
4970 static __be32 nfsd4_validate_stateid(struct nfs4_client *cl, stateid_t *stateid)
4971 {
4972         struct nfs4_stid *s;
4973         __be32 status = nfserr_bad_stateid;
4974
4975         if (ZERO_STATEID(stateid) || ONE_STATEID(stateid) ||
4976                 CLOSE_STATEID(stateid))
4977                 return status;
4978         /* Client debugging aid. */
4979         if (!same_clid(&stateid->si_opaque.so_clid, &cl->cl_clientid)) {
4980                 char addr_str[INET6_ADDRSTRLEN];
4981                 rpc_ntop((struct sockaddr *)&cl->cl_addr, addr_str,
4982                                  sizeof(addr_str));
4983                 pr_warn_ratelimited("NFSD: client %s testing state ID "
4984                                         "with incorrect client ID\n", addr_str);
4985                 return status;
4986         }
4987         spin_lock(&cl->cl_lock);
4988         s = find_stateid_locked(cl, stateid);
4989         if (!s)
4990                 goto out_unlock;
4991         status = check_stateid_generation(stateid, &s->sc_stateid, 1);
4992         if (status)
4993                 goto out_unlock;
4994         switch (s->sc_type) {
4995         case NFS4_DELEG_STID:
4996                 status = nfs_ok;
4997                 break;
4998         case NFS4_REVOKED_DELEG_STID:
4999                 status = nfserr_deleg_revoked;
5000                 break;
5001         case NFS4_OPEN_STID:
5002         case NFS4_LOCK_STID:
5003                 status = nfsd4_check_openowner_confirmed(openlockstateid(s));
5004                 break;
5005         default:
5006                 printk("unknown stateid type %x\n", s->sc_type);
5007                 /* Fallthrough */
5008         case NFS4_CLOSED_STID:
5009         case NFS4_CLOSED_DELEG_STID:
5010                 status = nfserr_bad_stateid;
5011         }
5012 out_unlock:
5013         spin_unlock(&cl->cl_lock);
5014         return status;
5015 }
5016
5017 __be32
5018 nfsd4_lookup_stateid(struct nfsd4_compound_state *cstate,
5019                      stateid_t *stateid, unsigned char typemask,
5020                      struct nfs4_stid **s, struct nfsd_net *nn)
5021 {
5022         __be32 status;
5023         bool return_revoked = false;
5024
5025         /*
5026          *  only return revoked delegations if explicitly asked.
5027          *  otherwise we report revoked or bad_stateid status.
5028          */
5029         if (typemask & NFS4_REVOKED_DELEG_STID)
5030                 return_revoked = true;
5031         else if (typemask & NFS4_DELEG_STID)
5032                 typemask |= NFS4_REVOKED_DELEG_STID;
5033
5034         if (ZERO_STATEID(stateid) || ONE_STATEID(stateid) ||
5035                 CLOSE_STATEID(stateid))
5036                 return nfserr_bad_stateid;
5037         status = lookup_clientid(&stateid->si_opaque.so_clid, cstate, nn);
5038         if (status == nfserr_stale_clientid) {
5039                 if (cstate->session)
5040                         return nfserr_bad_stateid;
5041                 return nfserr_stale_stateid;
5042         }
5043         if (status)
5044                 return status;
5045         *s = find_stateid_by_type(cstate->clp, stateid, typemask);
5046         if (!*s)
5047                 return nfserr_bad_stateid;
5048         if (((*s)->sc_type == NFS4_REVOKED_DELEG_STID) && !return_revoked) {
5049                 nfs4_put_stid(*s);
5050                 if (cstate->minorversion)
5051                         return nfserr_deleg_revoked;
5052                 return nfserr_bad_stateid;
5053         }
5054         return nfs_ok;
5055 }
5056
5057 static struct file *
5058 nfs4_find_file(struct nfs4_stid *s, int flags)
5059 {
5060         if (!s)
5061                 return NULL;
5062
5063         switch (s->sc_type) {
5064         case NFS4_DELEG_STID:
5065                 if (WARN_ON_ONCE(!s->sc_file->fi_deleg_file))
5066                         return NULL;
5067                 return get_file(s->sc_file->fi_deleg_file);
5068         case NFS4_OPEN_STID:
5069         case NFS4_LOCK_STID:
5070                 if (flags & RD_STATE)
5071                         return find_readable_file(s->sc_file);
5072                 else
5073                         return find_writeable_file(s->sc_file);
5074                 break;
5075         }
5076
5077         return NULL;
5078 }
5079
5080 static __be32
5081 nfs4_check_olstateid(struct svc_fh *fhp, struct nfs4_ol_stateid *ols, int flags)
5082 {
5083         __be32 status;
5084
5085         status = nfsd4_check_openowner_confirmed(ols);
5086         if (status)
5087                 return status;
5088         return nfs4_check_openmode(ols, flags);
5089 }
5090
5091 static __be32
5092 nfs4_check_file(struct svc_rqst *rqstp, struct svc_fh *fhp, struct nfs4_stid *s,
5093                 struct file **filpp, bool *tmp_file, int flags)
5094 {
5095         int acc = (flags & RD_STATE) ? NFSD_MAY_READ : NFSD_MAY_WRITE;
5096         struct file *file;
5097         __be32 status;
5098
5099         file = nfs4_find_file(s, flags);
5100         if (file) {
5101                 status = nfsd_permission(rqstp, fhp->fh_export, fhp->fh_dentry,
5102                                 acc | NFSD_MAY_OWNER_OVERRIDE);
5103                 if (status) {
5104                         fput(file);
5105                         return status;
5106                 }
5107
5108                 *filpp = file;
5109         } else {
5110                 status = nfsd_open(rqstp, fhp, S_IFREG, acc, filpp);
5111                 if (status)
5112                         return status;
5113
5114                 if (tmp_file)
5115                         *tmp_file = true;
5116         }
5117
5118         return 0;
5119 }
5120
5121 /*
5122  * Checks for stateid operations
5123  */
5124 __be32
5125 nfs4_preprocess_stateid_op(struct svc_rqst *rqstp,
5126                 struct nfsd4_compound_state *cstate, struct svc_fh *fhp,
5127                 stateid_t *stateid, int flags, struct file **filpp, bool *tmp_file)
5128 {
5129         struct inode *ino = d_inode(fhp->fh_dentry);
5130         struct net *net = SVC_NET(rqstp);
5131         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
5132         struct nfs4_stid *s = NULL;
5133         __be32 status;
5134
5135         if (filpp)
5136                 *filpp = NULL;
5137         if (tmp_file)
5138                 *tmp_file = false;
5139
5140         if (grace_disallows_io(net, ino))
5141                 return nfserr_grace;
5142
5143         if (ZERO_STATEID(stateid) || ONE_STATEID(stateid)) {
5144                 status = check_special_stateids(net, fhp, stateid, flags);
5145                 goto done;
5146         }
5147
5148         status = nfsd4_lookup_stateid(cstate, stateid,
5149                                 NFS4_DELEG_STID|NFS4_OPEN_STID|NFS4_LOCK_STID,
5150                                 &s, nn);
5151         if (status)
5152                 return status;
5153         status = check_stateid_generation(stateid, &s->sc_stateid,
5154                         nfsd4_has_session(cstate));
5155         if (status)
5156                 goto out;
5157
5158         switch (s->sc_type) {
5159         case NFS4_DELEG_STID:
5160                 status = nfs4_check_delegmode(delegstateid(s), flags);
5161                 break;
5162         case NFS4_OPEN_STID:
5163         case NFS4_LOCK_STID:
5164                 status = nfs4_check_olstateid(fhp, openlockstateid(s), flags);
5165                 break;
5166         default:
5167                 status = nfserr_bad_stateid;
5168                 break;
5169         }
5170         if (status)
5171                 goto out;
5172         status = nfs4_check_fh(fhp, s);
5173
5174 done:
5175         if (!status && filpp)
5176                 status = nfs4_check_file(rqstp, fhp, s, filpp, tmp_file, flags);
5177 out:
5178         if (s)
5179                 nfs4_put_stid(s);
5180         return status;
5181 }
5182
5183 /*
5184  * Test if the stateid is valid
5185  */
5186 __be32
5187 nfsd4_test_stateid(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
5188                    union nfsd4_op_u *u)
5189 {
5190         struct nfsd4_test_stateid *test_stateid = &u->test_stateid;
5191         struct nfsd4_test_stateid_id *stateid;
5192         struct nfs4_client *cl = cstate->session->se_client;
5193
5194         list_for_each_entry(stateid, &test_stateid->ts_stateid_list, ts_id_list)
5195                 stateid->ts_id_status =
5196                         nfsd4_validate_stateid(cl, &stateid->ts_id_stateid);
5197
5198         return nfs_ok;
5199 }
5200
5201 static __be32
5202 nfsd4_free_lock_stateid(stateid_t *stateid, struct nfs4_stid *s)
5203 {
5204         struct nfs4_ol_stateid *stp = openlockstateid(s);
5205         __be32 ret;
5206
5207         mutex_lock(&stp->st_mutex);
5208
5209         ret = check_stateid_generation(stateid, &s->sc_stateid, 1);
5210         if (ret)
5211                 goto out;
5212
5213         ret = nfserr_locks_held;
5214         if (check_for_locks(stp->st_stid.sc_file,
5215                             lockowner(stp->st_stateowner)))
5216                 goto out;
5217
5218         release_lock_stateid(stp);
5219         ret = nfs_ok;
5220
5221 out:
5222         mutex_unlock(&stp->st_mutex);
5223         nfs4_put_stid(s);
5224         return ret;
5225 }
5226
5227 __be32
5228 nfsd4_free_stateid(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
5229                    union nfsd4_op_u *u)
5230 {
5231         struct nfsd4_free_stateid *free_stateid = &u->free_stateid;
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                    union nfsd4_op_u *u)
5354 {
5355         struct nfsd4_open_confirm *oc = &u->open_confirm;
5356         __be32 status;
5357         struct nfs4_openowner *oo;
5358         struct nfs4_ol_stateid *stp;
5359         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
5360
5361         dprintk("NFSD: nfsd4_open_confirm on file %pd\n",
5362                         cstate->current_fh.fh_dentry);
5363
5364         status = fh_verify(rqstp, &cstate->current_fh, S_IFREG, 0);
5365         if (status)
5366                 return status;
5367
5368         status = nfs4_preprocess_seqid_op(cstate,
5369                                         oc->oc_seqid, &oc->oc_req_stateid,
5370                                         NFS4_OPEN_STID, &stp, nn);
5371         if (status)
5372                 goto out;
5373         oo = openowner(stp->st_stateowner);
5374         status = nfserr_bad_stateid;
5375         if (oo->oo_flags & NFS4_OO_CONFIRMED) {
5376                 mutex_unlock(&stp->st_mutex);
5377                 goto put_stateid;
5378         }
5379         oo->oo_flags |= NFS4_OO_CONFIRMED;
5380         nfs4_inc_and_copy_stateid(&oc->oc_resp_stateid, &stp->st_stid);
5381         mutex_unlock(&stp->st_mutex);
5382         dprintk("NFSD: %s: success, seqid=%d stateid=" STATEID_FMT "\n",
5383                 __func__, oc->oc_seqid, STATEID_VAL(&stp->st_stid.sc_stateid));
5384
5385         nfsd4_client_record_create(oo->oo_owner.so_client);
5386         status = nfs_ok;
5387 put_stateid:
5388         nfs4_put_stid(&stp->st_stid);
5389 out:
5390         nfsd4_bump_seqid(cstate, status);
5391         return status;
5392 }
5393
5394 static inline void nfs4_stateid_downgrade_bit(struct nfs4_ol_stateid *stp, u32 access)
5395 {
5396         if (!test_access(access, stp))
5397                 return;
5398         nfs4_file_put_access(stp->st_stid.sc_file, access);
5399         clear_access(access, stp);
5400 }
5401
5402 static inline void nfs4_stateid_downgrade(struct nfs4_ol_stateid *stp, u32 to_access)
5403 {
5404         switch (to_access) {
5405         case NFS4_SHARE_ACCESS_READ:
5406                 nfs4_stateid_downgrade_bit(stp, NFS4_SHARE_ACCESS_WRITE);
5407                 nfs4_stateid_downgrade_bit(stp, NFS4_SHARE_ACCESS_BOTH);
5408                 break;
5409         case NFS4_SHARE_ACCESS_WRITE:
5410                 nfs4_stateid_downgrade_bit(stp, NFS4_SHARE_ACCESS_READ);
5411                 nfs4_stateid_downgrade_bit(stp, NFS4_SHARE_ACCESS_BOTH);
5412                 break;
5413         case NFS4_SHARE_ACCESS_BOTH:
5414                 break;
5415         default:
5416                 WARN_ON_ONCE(1);
5417         }
5418 }
5419
5420 __be32
5421 nfsd4_open_downgrade(struct svc_rqst *rqstp,
5422                      struct nfsd4_compound_state *cstate, union nfsd4_op_u *u)
5423 {
5424         struct nfsd4_open_downgrade *od = &u->open_downgrade;
5425         __be32 status;
5426         struct nfs4_ol_stateid *stp;
5427         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
5428
5429         dprintk("NFSD: nfsd4_open_downgrade on file %pd\n", 
5430                         cstate->current_fh.fh_dentry);
5431
5432         /* We don't yet support WANT bits: */
5433         if (od->od_deleg_want)
5434                 dprintk("NFSD: %s: od_deleg_want=0x%x ignored\n", __func__,
5435                         od->od_deleg_want);
5436
5437         status = nfs4_preprocess_confirmed_seqid_op(cstate, od->od_seqid,
5438                                         &od->od_stateid, &stp, nn);
5439         if (status)
5440                 goto out; 
5441         status = nfserr_inval;
5442         if (!test_access(od->od_share_access, stp)) {
5443                 dprintk("NFSD: access not a subset of current bitmap: 0x%hhx, input access=%08x\n",
5444                         stp->st_access_bmap, od->od_share_access);
5445                 goto put_stateid;
5446         }
5447         if (!test_deny(od->od_share_deny, stp)) {
5448                 dprintk("NFSD: deny not a subset of current bitmap: 0x%hhx, input deny=%08x\n",
5449                         stp->st_deny_bmap, od->od_share_deny);
5450                 goto put_stateid;
5451         }
5452         nfs4_stateid_downgrade(stp, od->od_share_access);
5453         reset_union_bmap_deny(od->od_share_deny, stp);
5454         nfs4_inc_and_copy_stateid(&od->od_stateid, &stp->st_stid);
5455         status = nfs_ok;
5456 put_stateid:
5457         mutex_unlock(&stp->st_mutex);
5458         nfs4_put_stid(&stp->st_stid);
5459 out:
5460         nfsd4_bump_seqid(cstate, status);
5461         return status;
5462 }
5463
5464 static void nfsd4_close_open_stateid(struct nfs4_ol_stateid *s)
5465 {
5466         struct nfs4_client *clp = s->st_stid.sc_client;
5467         bool unhashed;
5468         LIST_HEAD(reaplist);
5469
5470         spin_lock(&clp->cl_lock);
5471         unhashed = unhash_open_stateid(s, &reaplist);
5472
5473         if (clp->cl_minorversion) {
5474                 if (unhashed)
5475                         put_ol_stateid_locked(s, &reaplist);
5476                 spin_unlock(&clp->cl_lock);
5477                 free_ol_stateid_reaplist(&reaplist);
5478         } else {
5479                 spin_unlock(&clp->cl_lock);
5480                 free_ol_stateid_reaplist(&reaplist);
5481                 if (unhashed)
5482                         move_to_close_lru(s, clp->net);
5483         }
5484 }
5485
5486 /*
5487  * nfs4_unlock_state() called after encode
5488  */
5489 __be32
5490 nfsd4_close(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
5491                 union nfsd4_op_u *u)
5492 {
5493         struct nfsd4_close *close = &u->close;
5494         __be32 status;
5495         struct nfs4_ol_stateid *stp;
5496         struct net *net = SVC_NET(rqstp);
5497         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
5498
5499         dprintk("NFSD: nfsd4_close on file %pd\n", 
5500                         cstate->current_fh.fh_dentry);
5501
5502         status = nfs4_preprocess_seqid_op(cstate, close->cl_seqid,
5503                                         &close->cl_stateid,
5504                                         NFS4_OPEN_STID|NFS4_CLOSED_STID,
5505                                         &stp, nn);
5506         nfsd4_bump_seqid(cstate, status);
5507         if (status)
5508                 goto out; 
5509
5510         stp->st_stid.sc_type = NFS4_CLOSED_STID;
5511         nfs4_inc_and_copy_stateid(&close->cl_stateid, &stp->st_stid);
5512
5513         nfsd4_close_open_stateid(stp);
5514         mutex_unlock(&stp->st_mutex);
5515
5516         /* See RFC5661 sectionm 18.2.4 */
5517         if (stp->st_stid.sc_client->cl_minorversion)
5518                 memcpy(&close->cl_stateid, &close_stateid,
5519                                 sizeof(close->cl_stateid));
5520
5521         /* put reference from nfs4_preprocess_seqid_op */
5522         nfs4_put_stid(&stp->st_stid);
5523 out:
5524         return status;
5525 }
5526
5527 __be32
5528 nfsd4_delegreturn(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
5529                   union nfsd4_op_u *u)
5530 {
5531         struct nfsd4_delegreturn *dr = &u->delegreturn;
5532         struct nfs4_delegation *dp;
5533         stateid_t *stateid = &dr->dr_stateid;
5534         struct nfs4_stid *s;
5535         __be32 status;
5536         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
5537
5538         if ((status = fh_verify(rqstp, &cstate->current_fh, S_IFREG, 0)))
5539                 return status;
5540
5541         status = nfsd4_lookup_stateid(cstate, stateid, NFS4_DELEG_STID, &s, nn);
5542         if (status)
5543                 goto out;
5544         dp = delegstateid(s);
5545         status = check_stateid_generation(stateid, &dp->dl_stid.sc_stateid, nfsd4_has_session(cstate));
5546         if (status)
5547                 goto put_stateid;
5548
5549         destroy_delegation(dp);
5550 put_stateid:
5551         nfs4_put_stid(&dp->dl_stid);
5552 out:
5553         return status;
5554 }
5555
5556 static inline u64
5557 end_offset(u64 start, u64 len)
5558 {
5559         u64 end;
5560
5561         end = start + len;
5562         return end >= start ? end: NFS4_MAX_UINT64;
5563 }
5564
5565 /* last octet in a range */
5566 static inline u64
5567 last_byte_offset(u64 start, u64 len)
5568 {
5569         u64 end;
5570
5571         WARN_ON_ONCE(!len);
5572         end = start + len;
5573         return end > start ? end - 1: NFS4_MAX_UINT64;
5574 }
5575
5576 /*
5577  * TODO: Linux file offsets are _signed_ 64-bit quantities, which means that
5578  * we can't properly handle lock requests that go beyond the (2^63 - 1)-th
5579  * byte, because of sign extension problems.  Since NFSv4 calls for 64-bit
5580  * locking, this prevents us from being completely protocol-compliant.  The
5581  * real solution to this problem is to start using unsigned file offsets in
5582  * the VFS, but this is a very deep change!
5583  */
5584 static inline void
5585 nfs4_transform_lock_offset(struct file_lock *lock)
5586 {
5587         if (lock->fl_start < 0)
5588                 lock->fl_start = OFFSET_MAX;
5589         if (lock->fl_end < 0)
5590                 lock->fl_end = OFFSET_MAX;
5591 }
5592
5593 static fl_owner_t
5594 nfsd4_fl_get_owner(fl_owner_t owner)
5595 {
5596         struct nfs4_lockowner *lo = (struct nfs4_lockowner *)owner;
5597
5598         nfs4_get_stateowner(&lo->lo_owner);
5599         return owner;
5600 }
5601
5602 static void
5603 nfsd4_fl_put_owner(fl_owner_t owner)
5604 {
5605         struct nfs4_lockowner *lo = (struct nfs4_lockowner *)owner;
5606
5607         if (lo)
5608                 nfs4_put_stateowner(&lo->lo_owner);
5609 }
5610
5611 static void
5612 nfsd4_lm_notify(struct file_lock *fl)
5613 {
5614         struct nfs4_lockowner           *lo = (struct nfs4_lockowner *)fl->fl_owner;
5615         struct net                      *net = lo->lo_owner.so_client->net;
5616         struct nfsd_net                 *nn = net_generic(net, nfsd_net_id);
5617         struct nfsd4_blocked_lock       *nbl = container_of(fl,
5618                                                 struct nfsd4_blocked_lock, nbl_lock);
5619         bool queue = false;
5620
5621         /* An empty list means that something else is going to be using it */
5622         spin_lock(&nn->blocked_locks_lock);
5623         if (!list_empty(&nbl->nbl_list)) {
5624                 list_del_init(&nbl->nbl_list);
5625                 list_del_init(&nbl->nbl_lru);
5626                 queue = true;
5627         }
5628         spin_unlock(&nn->blocked_locks_lock);
5629
5630         if (queue)
5631                 nfsd4_run_cb(&nbl->nbl_cb);
5632 }
5633
5634 static const struct lock_manager_operations nfsd_posix_mng_ops  = {
5635         .lm_notify = nfsd4_lm_notify,
5636         .lm_get_owner = nfsd4_fl_get_owner,
5637         .lm_put_owner = nfsd4_fl_put_owner,
5638 };
5639
5640 static inline void
5641 nfs4_set_lock_denied(struct file_lock *fl, struct nfsd4_lock_denied *deny)
5642 {
5643         struct nfs4_lockowner *lo;
5644
5645         if (fl->fl_lmops == &nfsd_posix_mng_ops) {
5646                 lo = (struct nfs4_lockowner *) fl->fl_owner;
5647                 deny->ld_owner.data = kmemdup(lo->lo_owner.so_owner.data,
5648                                         lo->lo_owner.so_owner.len, GFP_KERNEL);
5649                 if (!deny->ld_owner.data)
5650                         /* We just don't care that much */
5651                         goto nevermind;
5652                 deny->ld_owner.len = lo->lo_owner.so_owner.len;
5653                 deny->ld_clientid = lo->lo_owner.so_client->cl_clientid;
5654         } else {
5655 nevermind:
5656                 deny->ld_owner.len = 0;
5657                 deny->ld_owner.data = NULL;
5658                 deny->ld_clientid.cl_boot = 0;
5659                 deny->ld_clientid.cl_id = 0;
5660         }
5661         deny->ld_start = fl->fl_start;
5662         deny->ld_length = NFS4_MAX_UINT64;
5663         if (fl->fl_end != NFS4_MAX_UINT64)
5664                 deny->ld_length = fl->fl_end - fl->fl_start + 1;        
5665         deny->ld_type = NFS4_READ_LT;
5666         if (fl->fl_type != F_RDLCK)
5667                 deny->ld_type = NFS4_WRITE_LT;
5668 }
5669
5670 static struct nfs4_lockowner *
5671 find_lockowner_str_locked(struct nfs4_client *clp, struct xdr_netobj *owner)
5672 {
5673         unsigned int strhashval = ownerstr_hashval(owner);
5674         struct nfs4_stateowner *so;
5675
5676         lockdep_assert_held(&clp->cl_lock);
5677
5678         list_for_each_entry(so, &clp->cl_ownerstr_hashtbl[strhashval],
5679                             so_strhash) {
5680                 if (so->so_is_open_owner)
5681                         continue;
5682                 if (same_owner_str(so, owner))
5683                         return lockowner(nfs4_get_stateowner(so));
5684         }
5685         return NULL;
5686 }
5687
5688 static struct nfs4_lockowner *
5689 find_lockowner_str(struct nfs4_client *clp, struct xdr_netobj *owner)
5690 {
5691         struct nfs4_lockowner *lo;
5692
5693         spin_lock(&clp->cl_lock);
5694         lo = find_lockowner_str_locked(clp, owner);
5695         spin_unlock(&clp->cl_lock);
5696         return lo;
5697 }
5698
5699 static void nfs4_unhash_lockowner(struct nfs4_stateowner *sop)
5700 {
5701         unhash_lockowner_locked(lockowner(sop));
5702 }
5703
5704 static void nfs4_free_lockowner(struct nfs4_stateowner *sop)
5705 {
5706         struct nfs4_lockowner *lo = lockowner(sop);
5707
5708         kmem_cache_free(lockowner_slab, lo);
5709 }
5710
5711 static const struct nfs4_stateowner_operations lockowner_ops = {
5712         .so_unhash =    nfs4_unhash_lockowner,
5713         .so_free =      nfs4_free_lockowner,
5714 };
5715
5716 /*
5717  * Alloc a lock owner structure.
5718  * Called in nfsd4_lock - therefore, OPEN and OPEN_CONFIRM (if needed) has 
5719  * occurred. 
5720  *
5721  * strhashval = ownerstr_hashval
5722  */
5723 static struct nfs4_lockowner *
5724 alloc_init_lock_stateowner(unsigned int strhashval, struct nfs4_client *clp,
5725                            struct nfs4_ol_stateid *open_stp,
5726                            struct nfsd4_lock *lock)
5727 {
5728         struct nfs4_lockowner *lo, *ret;
5729
5730         lo = alloc_stateowner(lockowner_slab, &lock->lk_new_owner, clp);
5731         if (!lo)
5732                 return NULL;
5733         INIT_LIST_HEAD(&lo->lo_blocked);
5734         INIT_LIST_HEAD(&lo->lo_owner.so_stateids);
5735         lo->lo_owner.so_is_open_owner = 0;
5736         lo->lo_owner.so_seqid = lock->lk_new_lock_seqid;
5737         lo->lo_owner.so_ops = &lockowner_ops;
5738         spin_lock(&clp->cl_lock);
5739         ret = find_lockowner_str_locked(clp, &lock->lk_new_owner);
5740         if (ret == NULL) {
5741                 list_add(&lo->lo_owner.so_strhash,
5742                          &clp->cl_ownerstr_hashtbl[strhashval]);
5743                 ret = lo;
5744         } else
5745                 nfs4_free_stateowner(&lo->lo_owner);
5746
5747         spin_unlock(&clp->cl_lock);
5748         return ret;
5749 }
5750
5751 static void
5752 init_lock_stateid(struct nfs4_ol_stateid *stp, struct nfs4_lockowner *lo,
5753                   struct nfs4_file *fp, struct inode *inode,
5754                   struct nfs4_ol_stateid *open_stp)
5755 {
5756         struct nfs4_client *clp = lo->lo_owner.so_client;
5757
5758         lockdep_assert_held(&clp->cl_lock);
5759
5760         atomic_inc(&stp->st_stid.sc_count);
5761         stp->st_stid.sc_type = NFS4_LOCK_STID;
5762         stp->st_stateowner = nfs4_get_stateowner(&lo->lo_owner);
5763         get_nfs4_file(fp);
5764         stp->st_stid.sc_file = fp;
5765         stp->st_access_bmap = 0;
5766         stp->st_deny_bmap = open_stp->st_deny_bmap;
5767         stp->st_openstp = open_stp;
5768         mutex_init(&stp->st_mutex);
5769         list_add(&stp->st_locks, &open_stp->st_locks);
5770         list_add(&stp->st_perstateowner, &lo->lo_owner.so_stateids);
5771         spin_lock(&fp->fi_lock);
5772         list_add(&stp->st_perfile, &fp->fi_stateids);
5773         spin_unlock(&fp->fi_lock);
5774 }
5775
5776 static struct nfs4_ol_stateid *
5777 find_lock_stateid(struct nfs4_lockowner *lo, struct nfs4_file *fp)
5778 {
5779         struct nfs4_ol_stateid *lst;
5780         struct nfs4_client *clp = lo->lo_owner.so_client;
5781
5782         lockdep_assert_held(&clp->cl_lock);
5783
5784         list_for_each_entry(lst, &lo->lo_owner.so_stateids, st_perstateowner) {
5785                 if (lst->st_stid.sc_file == fp) {
5786                         atomic_inc(&lst->st_stid.sc_count);
5787                         return lst;
5788                 }
5789         }
5790         return NULL;
5791 }
5792
5793 static struct nfs4_ol_stateid *
5794 find_or_create_lock_stateid(struct nfs4_lockowner *lo, struct nfs4_file *fi,
5795                             struct inode *inode, struct nfs4_ol_stateid *ost,
5796                             bool *new)
5797 {
5798         struct nfs4_stid *ns = NULL;
5799         struct nfs4_ol_stateid *lst;
5800         struct nfs4_openowner *oo = openowner(ost->st_stateowner);
5801         struct nfs4_client *clp = oo->oo_owner.so_client;
5802
5803         spin_lock(&clp->cl_lock);
5804         lst = find_lock_stateid(lo, fi);
5805         if (lst == NULL) {
5806                 spin_unlock(&clp->cl_lock);
5807                 ns = nfs4_alloc_stid(clp, stateid_slab, nfs4_free_lock_stateid);
5808                 if (ns == NULL)
5809                         return NULL;
5810
5811                 spin_lock(&clp->cl_lock);
5812                 lst = find_lock_stateid(lo, fi);
5813                 if (likely(!lst)) {
5814                         lst = openlockstateid(ns);
5815                         init_lock_stateid(lst, lo, fi, inode, ost);
5816                         ns = NULL;
5817                         *new = true;
5818                 }
5819         }
5820         spin_unlock(&clp->cl_lock);
5821         if (ns)
5822                 nfs4_put_stid(ns);
5823         return lst;
5824 }
5825
5826 static int
5827 check_lock_length(u64 offset, u64 length)
5828 {
5829         return ((length == 0) || ((length != NFS4_MAX_UINT64) &&
5830                 (length > ~offset)));
5831 }
5832
5833 static void get_lock_access(struct nfs4_ol_stateid *lock_stp, u32 access)
5834 {
5835         struct nfs4_file *fp = lock_stp->st_stid.sc_file;
5836
5837         lockdep_assert_held(&fp->fi_lock);
5838
5839         if (test_access(access, lock_stp))
5840                 return;
5841         __nfs4_file_get_access(fp, access);
5842         set_access(access, lock_stp);
5843 }
5844
5845 static __be32
5846 lookup_or_create_lock_state(struct nfsd4_compound_state *cstate,
5847                             struct nfs4_ol_stateid *ost,
5848                             struct nfsd4_lock *lock,
5849                             struct nfs4_ol_stateid **plst, bool *new)
5850 {
5851         __be32 status;
5852         struct nfs4_file *fi = ost->st_stid.sc_file;
5853         struct nfs4_openowner *oo = openowner(ost->st_stateowner);
5854         struct nfs4_client *cl = oo->oo_owner.so_client;
5855         struct inode *inode = d_inode(cstate->current_fh.fh_dentry);
5856         struct nfs4_lockowner *lo;
5857         struct nfs4_ol_stateid *lst;
5858         unsigned int strhashval;
5859         bool hashed;
5860
5861         lo = find_lockowner_str(cl, &lock->lk_new_owner);
5862         if (!lo) {
5863                 strhashval = ownerstr_hashval(&lock->lk_new_owner);
5864                 lo = alloc_init_lock_stateowner(strhashval, cl, ost, lock);
5865                 if (lo == NULL)
5866                         return nfserr_jukebox;
5867         } else {
5868                 /* with an existing lockowner, seqids must be the same */
5869                 status = nfserr_bad_seqid;
5870                 if (!cstate->minorversion &&
5871                     lock->lk_new_lock_seqid != lo->lo_owner.so_seqid)
5872                         goto out;
5873         }
5874
5875 retry:
5876         lst = find_or_create_lock_stateid(lo, fi, inode, ost, new);
5877         if (lst == NULL) {
5878                 status = nfserr_jukebox;
5879                 goto out;
5880         }
5881
5882         mutex_lock(&lst->st_mutex);
5883
5884         /* See if it's still hashed to avoid race with FREE_STATEID */
5885         spin_lock(&cl->cl_lock);
5886         hashed = !list_empty(&lst->st_perfile);
5887         spin_unlock(&cl->cl_lock);
5888
5889         if (!hashed) {
5890                 mutex_unlock(&lst->st_mutex);
5891                 nfs4_put_stid(&lst->st_stid);
5892                 goto retry;
5893         }
5894         status = nfs_ok;
5895         *plst = lst;
5896 out:
5897         nfs4_put_stateowner(&lo->lo_owner);
5898         return status;
5899 }
5900
5901 /*
5902  *  LOCK operation 
5903  */
5904 __be32
5905 nfsd4_lock(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
5906            union nfsd4_op_u *u)
5907 {
5908         struct nfsd4_lock *lock = &u->lock;
5909         struct nfs4_openowner *open_sop = NULL;
5910         struct nfs4_lockowner *lock_sop = NULL;
5911         struct nfs4_ol_stateid *lock_stp = NULL;
5912         struct nfs4_ol_stateid *open_stp = NULL;
5913         struct nfs4_file *fp;
5914         struct file *filp = NULL;
5915         struct nfsd4_blocked_lock *nbl = NULL;
5916         struct file_lock *file_lock = NULL;
5917         struct file_lock *conflock = NULL;
5918         __be32 status = 0;
5919         int lkflg;
5920         int err;
5921         bool new = false;
5922         unsigned char fl_type;
5923         unsigned int fl_flags = FL_POSIX;
5924         struct net *net = SVC_NET(rqstp);
5925         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
5926
5927         dprintk("NFSD: nfsd4_lock: start=%Ld length=%Ld\n",
5928                 (long long) lock->lk_offset,
5929                 (long long) lock->lk_length);
5930
5931         if (check_lock_length(lock->lk_offset, lock->lk_length))
5932                  return nfserr_inval;
5933
5934         if ((status = fh_verify(rqstp, &cstate->current_fh,
5935                                 S_IFREG, NFSD_MAY_LOCK))) {
5936                 dprintk("NFSD: nfsd4_lock: permission denied!\n");
5937                 return status;
5938         }
5939
5940         if (lock->lk_is_new) {
5941                 if (nfsd4_has_session(cstate))
5942                         /* See rfc 5661 18.10.3: given clientid is ignored: */
5943                         memcpy(&lock->lk_new_clientid,
5944                                 &cstate->session->se_client->cl_clientid,
5945                                 sizeof(clientid_t));
5946
5947                 status = nfserr_stale_clientid;
5948                 if (STALE_CLIENTID(&lock->lk_new_clientid, nn))
5949                         goto out;
5950
5951                 /* validate and update open stateid and open seqid */
5952                 status = nfs4_preprocess_confirmed_seqid_op(cstate,
5953                                         lock->lk_new_open_seqid,
5954                                         &lock->lk_new_open_stateid,
5955                                         &open_stp, nn);
5956                 if (status)
5957                         goto out;
5958                 mutex_unlock(&open_stp->st_mutex);
5959                 open_sop = openowner(open_stp->st_stateowner);
5960                 status = nfserr_bad_stateid;
5961                 if (!same_clid(&open_sop->oo_owner.so_client->cl_clientid,
5962                                                 &lock->lk_new_clientid))
5963                         goto out;
5964                 status = lookup_or_create_lock_state(cstate, open_stp, lock,
5965                                                         &lock_stp, &new);
5966         } else {
5967                 status = nfs4_preprocess_seqid_op(cstate,
5968                                        lock->lk_old_lock_seqid,
5969                                        &lock->lk_old_lock_stateid,
5970                                        NFS4_LOCK_STID, &lock_stp, nn);
5971         }
5972         if (status)
5973                 goto out;
5974         lock_sop = lockowner(lock_stp->st_stateowner);
5975
5976         lkflg = setlkflg(lock->lk_type);
5977         status = nfs4_check_openmode(lock_stp, lkflg);
5978         if (status)
5979                 goto out;
5980
5981         status = nfserr_grace;
5982         if (locks_in_grace(net) && !lock->lk_reclaim)
5983                 goto out;
5984         status = nfserr_no_grace;
5985         if (!locks_in_grace(net) && lock->lk_reclaim)
5986                 goto out;
5987
5988         fp = lock_stp->st_stid.sc_file;
5989         switch (lock->lk_type) {
5990                 case NFS4_READW_LT:
5991                         if (nfsd4_has_session(cstate))
5992                                 fl_flags |= FL_SLEEP;
5993                         /* Fallthrough */
5994                 case NFS4_READ_LT:
5995                         spin_lock(&fp->fi_lock);
5996                         filp = find_readable_file_locked(fp);
5997                         if (filp)
5998                                 get_lock_access(lock_stp, NFS4_SHARE_ACCESS_READ);
5999                         spin_unlock(&fp->fi_lock);
6000                         fl_type = F_RDLCK;
6001                         break;
6002                 case NFS4_WRITEW_LT:
6003                         if (nfsd4_has_session(cstate))
6004                                 fl_flags |= FL_SLEEP;
6005                         /* Fallthrough */
6006                 case NFS4_WRITE_LT:
6007                         spin_lock(&fp->fi_lock);
6008                         filp = find_writeable_file_locked(fp);
6009                         if (filp)
6010                                 get_lock_access(lock_stp, NFS4_SHARE_ACCESS_WRITE);
6011                         spin_unlock(&fp->fi_lock);
6012                         fl_type = F_WRLCK;
6013                         break;
6014                 default:
6015                         status = nfserr_inval;
6016                 goto out;
6017         }
6018
6019         if (!filp) {
6020                 status = nfserr_openmode;
6021                 goto out;
6022         }
6023
6024         nbl = find_or_allocate_block(lock_sop, &fp->fi_fhandle, nn);
6025         if (!nbl) {
6026                 dprintk("NFSD: %s: unable to allocate block!\n", __func__);
6027                 status = nfserr_jukebox;
6028                 goto out;
6029         }
6030
6031         file_lock = &nbl->nbl_lock;
6032         file_lock->fl_type = fl_type;
6033         file_lock->fl_owner = (fl_owner_t)lockowner(nfs4_get_stateowner(&lock_sop->lo_owner));
6034         file_lock->fl_pid = current->tgid;
6035         file_lock->fl_file = filp;
6036         file_lock->fl_flags = fl_flags;
6037         file_lock->fl_lmops = &nfsd_posix_mng_ops;
6038         file_lock->fl_start = lock->lk_offset;
6039         file_lock->fl_end = last_byte_offset(lock->lk_offset, lock->lk_length);
6040         nfs4_transform_lock_offset(file_lock);
6041
6042         conflock = locks_alloc_lock();
6043         if (!conflock) {
6044                 dprintk("NFSD: %s: unable to allocate lock!\n", __func__);
6045                 status = nfserr_jukebox;
6046                 goto out;
6047         }
6048
6049         if (fl_flags & FL_SLEEP) {
6050                 nbl->nbl_time = get_seconds();
6051                 spin_lock(&nn->blocked_locks_lock);
6052                 list_add_tail(&nbl->nbl_list, &lock_sop->lo_blocked);
6053                 list_add_tail(&nbl->nbl_lru, &nn->blocked_locks_lru);
6054                 spin_unlock(&nn->blocked_locks_lock);
6055         }
6056
6057         err = vfs_lock_file(filp, F_SETLK, file_lock, conflock);
6058         switch (err) {
6059         case 0: /* success! */
6060                 nfs4_inc_and_copy_stateid(&lock->lk_resp_stateid, &lock_stp->st_stid);
6061                 status = 0;
6062                 break;
6063         case FILE_LOCK_DEFERRED:
6064                 nbl = NULL;
6065                 /* Fallthrough */
6066         case -EAGAIN:           /* conflock holds conflicting lock */
6067                 status = nfserr_denied;
6068                 dprintk("NFSD: nfsd4_lock: conflicting lock found!\n");
6069                 nfs4_set_lock_denied(conflock, &lock->lk_denied);
6070                 break;
6071         case -EDEADLK:
6072                 status = nfserr_deadlock;
6073                 break;
6074         default:
6075                 dprintk("NFSD: nfsd4_lock: vfs_lock_file() failed! status %d\n",err);
6076                 status = nfserrno(err);
6077                 break;
6078         }
6079 out:
6080         if (nbl) {
6081                 /* dequeue it if we queued it before */
6082                 if (fl_flags & FL_SLEEP) {
6083                         spin_lock(&nn->blocked_locks_lock);
6084                         list_del_init(&nbl->nbl_list);
6085                         list_del_init(&nbl->nbl_lru);
6086                         spin_unlock(&nn->blocked_locks_lock);
6087                 }
6088                 free_blocked_lock(nbl);
6089         }
6090         if (filp)
6091                 fput(filp);
6092         if (lock_stp) {
6093                 /* Bump seqid manually if the 4.0 replay owner is openowner */
6094                 if (cstate->replay_owner &&
6095                     cstate->replay_owner != &lock_sop->lo_owner &&
6096                     seqid_mutating_err(ntohl(status)))
6097                         lock_sop->lo_owner.so_seqid++;
6098
6099                 mutex_unlock(&lock_stp->st_mutex);
6100
6101                 /*
6102                  * If this is a new, never-before-used stateid, and we are
6103                  * returning an error, then just go ahead and release it.
6104                  */
6105                 if (status && new)
6106                         release_lock_stateid(lock_stp);
6107
6108                 nfs4_put_stid(&lock_stp->st_stid);
6109         }
6110         if (open_stp)
6111                 nfs4_put_stid(&open_stp->st_stid);
6112         nfsd4_bump_seqid(cstate, status);
6113         if (conflock)
6114                 locks_free_lock(conflock);
6115         return status;
6116 }
6117
6118 /*
6119  * The NFSv4 spec allows a client to do a LOCKT without holding an OPEN,
6120  * so we do a temporary open here just to get an open file to pass to
6121  * vfs_test_lock.  (Arguably perhaps test_lock should be done with an
6122  * inode operation.)
6123  */
6124 static __be32 nfsd_test_lock(struct svc_rqst *rqstp, struct svc_fh *fhp, struct file_lock *lock)
6125 {
6126         struct file *file;
6127         __be32 err = nfsd_open(rqstp, fhp, S_IFREG, NFSD_MAY_READ, &file);
6128         if (!err) {
6129                 err = nfserrno(vfs_test_lock(file, lock));
6130                 fput(file);
6131         }
6132         return err;
6133 }
6134
6135 /*
6136  * LOCKT operation
6137  */
6138 __be32
6139 nfsd4_lockt(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
6140             union nfsd4_op_u *u)
6141 {
6142         struct nfsd4_lockt *lockt = &u->lockt;
6143         struct file_lock *file_lock = NULL;
6144         struct nfs4_lockowner *lo = NULL;
6145         __be32 status;
6146         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
6147
6148         if (locks_in_grace(SVC_NET(rqstp)))
6149                 return nfserr_grace;
6150
6151         if (check_lock_length(lockt->lt_offset, lockt->lt_length))
6152                  return nfserr_inval;
6153
6154         if (!nfsd4_has_session(cstate)) {
6155                 status = lookup_clientid(&lockt->lt_clientid, cstate, nn);
6156                 if (status)
6157                         goto out;
6158         }
6159
6160         if ((status = fh_verify(rqstp, &cstate->current_fh, S_IFREG, 0)))
6161                 goto out;
6162
6163         file_lock = locks_alloc_lock();
6164         if (!file_lock) {
6165                 dprintk("NFSD: %s: unable to allocate lock!\n", __func__);
6166                 status = nfserr_jukebox;
6167                 goto out;
6168         }
6169
6170         switch (lockt->lt_type) {
6171                 case NFS4_READ_LT:
6172                 case NFS4_READW_LT:
6173                         file_lock->fl_type = F_RDLCK;
6174                 break;
6175                 case NFS4_WRITE_LT:
6176                 case NFS4_WRITEW_LT:
6177                         file_lock->fl_type = F_WRLCK;
6178                 break;
6179                 default:
6180                         dprintk("NFSD: nfs4_lockt: bad lock type!\n");
6181                         status = nfserr_inval;
6182                 goto out;
6183         }
6184
6185         lo = find_lockowner_str(cstate->clp, &lockt->lt_owner);
6186         if (lo)
6187                 file_lock->fl_owner = (fl_owner_t)lo;
6188         file_lock->fl_pid = current->tgid;
6189         file_lock->fl_flags = FL_POSIX;
6190
6191         file_lock->fl_start = lockt->lt_offset;
6192         file_lock->fl_end = last_byte_offset(lockt->lt_offset, lockt->lt_length);
6193
6194         nfs4_transform_lock_offset(file_lock);
6195
6196         status = nfsd_test_lock(rqstp, &cstate->current_fh, file_lock);
6197         if (status)
6198                 goto out;
6199
6200         if (file_lock->fl_type != F_UNLCK) {
6201                 status = nfserr_denied;
6202                 nfs4_set_lock_denied(file_lock, &lockt->lt_denied);
6203         }
6204 out:
6205         if (lo)
6206                 nfs4_put_stateowner(&lo->lo_owner);
6207         if (file_lock)
6208                 locks_free_lock(file_lock);
6209         return status;
6210 }
6211
6212 __be32
6213 nfsd4_locku(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
6214             union nfsd4_op_u *u)
6215 {
6216         struct nfsd4_locku *locku = &u->locku;
6217         struct nfs4_ol_stateid *stp;
6218         struct file *filp = NULL;
6219         struct file_lock *file_lock = NULL;
6220         __be32 status;
6221         int err;
6222         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
6223
6224         dprintk("NFSD: nfsd4_locku: start=%Ld length=%Ld\n",
6225                 (long long) locku->lu_offset,
6226                 (long long) locku->lu_length);
6227
6228         if (check_lock_length(locku->lu_offset, locku->lu_length))
6229                  return nfserr_inval;
6230
6231         status = nfs4_preprocess_seqid_op(cstate, locku->lu_seqid,
6232                                         &locku->lu_stateid, NFS4_LOCK_STID,
6233                                         &stp, nn);
6234         if (status)
6235                 goto out;
6236         filp = find_any_file(stp->st_stid.sc_file);
6237         if (!filp) {
6238                 status = nfserr_lock_range;
6239                 goto put_stateid;
6240         }
6241         file_lock = locks_alloc_lock();
6242         if (!file_lock) {
6243                 dprintk("NFSD: %s: unable to allocate lock!\n", __func__);
6244                 status = nfserr_jukebox;
6245                 goto fput;
6246         }
6247
6248         file_lock->fl_type = F_UNLCK;
6249         file_lock->fl_owner = (fl_owner_t)lockowner(nfs4_get_stateowner(stp->st_stateowner));
6250         file_lock->fl_pid = current->tgid;
6251         file_lock->fl_file = filp;
6252         file_lock->fl_flags = FL_POSIX;
6253         file_lock->fl_lmops = &nfsd_posix_mng_ops;
6254         file_lock->fl_start = locku->lu_offset;
6255
6256         file_lock->fl_end = last_byte_offset(locku->lu_offset,
6257                                                 locku->lu_length);
6258         nfs4_transform_lock_offset(file_lock);
6259
6260         err = vfs_lock_file(filp, F_SETLK, file_lock, NULL);
6261         if (err) {
6262                 dprintk("NFSD: nfs4_locku: vfs_lock_file failed!\n");
6263                 goto out_nfserr;
6264         }
6265         nfs4_inc_and_copy_stateid(&locku->lu_stateid, &stp->st_stid);
6266 fput:
6267         fput(filp);
6268 put_stateid:
6269         mutex_unlock(&stp->st_mutex);
6270         nfs4_put_stid(&stp->st_stid);
6271 out:
6272         nfsd4_bump_seqid(cstate, status);
6273         if (file_lock)
6274                 locks_free_lock(file_lock);
6275         return status;
6276
6277 out_nfserr:
6278         status = nfserrno(err);
6279         goto fput;
6280 }
6281
6282 /*
6283  * returns
6284  *      true:  locks held by lockowner
6285  *      false: no locks held by lockowner
6286  */
6287 static bool
6288 check_for_locks(struct nfs4_file *fp, struct nfs4_lockowner *lowner)
6289 {
6290         struct file_lock *fl;
6291         int status = false;
6292         struct file *filp = find_any_file(fp);
6293         struct inode *inode;
6294         struct file_lock_context *flctx;
6295
6296         if (!filp) {
6297                 /* Any valid lock stateid should have some sort of access */
6298                 WARN_ON_ONCE(1);
6299                 return status;
6300         }
6301
6302         inode = file_inode(filp);
6303         flctx = inode->i_flctx;
6304
6305         if (flctx && !list_empty_careful(&flctx->flc_posix)) {
6306                 spin_lock(&flctx->flc_lock);
6307                 list_for_each_entry(fl, &flctx->flc_posix, fl_list) {
6308                         if (fl->fl_owner == (fl_owner_t)lowner) {
6309                                 status = true;
6310                                 break;
6311                         }
6312                 }
6313                 spin_unlock(&flctx->flc_lock);
6314         }
6315         fput(filp);
6316         return status;
6317 }
6318
6319 __be32
6320 nfsd4_release_lockowner(struct svc_rqst *rqstp,
6321                         struct nfsd4_compound_state *cstate,
6322                         union nfsd4_op_u *u)
6323 {
6324         struct nfsd4_release_lockowner *rlockowner = &u->release_lockowner;
6325         clientid_t *clid = &rlockowner->rl_clientid;
6326         struct nfs4_stateowner *sop;
6327         struct nfs4_lockowner *lo = NULL;
6328         struct nfs4_ol_stateid *stp;
6329         struct xdr_netobj *owner = &rlockowner->rl_owner;
6330         unsigned int hashval = ownerstr_hashval(owner);
6331         __be32 status;
6332         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
6333         struct nfs4_client *clp;
6334         LIST_HEAD (reaplist);
6335
6336         dprintk("nfsd4_release_lockowner clientid: (%08x/%08x):\n",
6337                 clid->cl_boot, clid->cl_id);
6338
6339         status = lookup_clientid(clid, cstate, nn);
6340         if (status)
6341                 return status;
6342
6343         clp = cstate->clp;
6344         /* Find the matching lock stateowner */
6345         spin_lock(&clp->cl_lock);
6346         list_for_each_entry(sop, &clp->cl_ownerstr_hashtbl[hashval],
6347                             so_strhash) {
6348
6349                 if (sop->so_is_open_owner || !same_owner_str(sop, owner))
6350                         continue;
6351
6352                 /* see if there are still any locks associated with it */
6353                 lo = lockowner(sop);
6354                 list_for_each_entry(stp, &sop->so_stateids, st_perstateowner) {
6355                         if (check_for_locks(stp->st_stid.sc_file, lo)) {
6356                                 status = nfserr_locks_held;
6357                                 spin_unlock(&clp->cl_lock);
6358                                 return status;
6359                         }
6360                 }
6361
6362                 nfs4_get_stateowner(sop);
6363                 break;
6364         }
6365         if (!lo) {
6366                 spin_unlock(&clp->cl_lock);
6367                 return status;
6368         }
6369
6370         unhash_lockowner_locked(lo);
6371         while (!list_empty(&lo->lo_owner.so_stateids)) {
6372                 stp = list_first_entry(&lo->lo_owner.so_stateids,
6373                                        struct nfs4_ol_stateid,
6374                                        st_perstateowner);
6375                 WARN_ON(!unhash_lock_stateid(stp));
6376                 put_ol_stateid_locked(stp, &reaplist);
6377         }
6378         spin_unlock(&clp->cl_lock);
6379         free_ol_stateid_reaplist(&reaplist);
6380         remove_blocked_locks(lo);
6381         nfs4_put_stateowner(&lo->lo_owner);
6382
6383         return status;
6384 }
6385
6386 static inline struct nfs4_client_reclaim *
6387 alloc_reclaim(void)
6388 {
6389         return kmalloc(sizeof(struct nfs4_client_reclaim), GFP_KERNEL);
6390 }
6391
6392 bool
6393 nfs4_has_reclaimed_state(const char *name, struct nfsd_net *nn)
6394 {
6395         struct nfs4_client_reclaim *crp;
6396
6397         crp = nfsd4_find_reclaim_client(name, nn);
6398         return (crp && crp->cr_clp);
6399 }
6400
6401 /*
6402  * failure => all reset bets are off, nfserr_no_grace...
6403  */
6404 struct nfs4_client_reclaim *
6405 nfs4_client_to_reclaim(const char *name, struct nfsd_net *nn)
6406 {
6407         unsigned int strhashval;
6408         struct nfs4_client_reclaim *crp;
6409
6410         dprintk("NFSD nfs4_client_to_reclaim NAME: %.*s\n", HEXDIR_LEN, name);
6411         crp = alloc_reclaim();
6412         if (crp) {
6413                 strhashval = clientstr_hashval(name);
6414                 INIT_LIST_HEAD(&crp->cr_strhash);
6415                 list_add(&crp->cr_strhash, &nn->reclaim_str_hashtbl[strhashval]);
6416                 memcpy(crp->cr_recdir, name, HEXDIR_LEN);
6417                 crp->cr_clp = NULL;
6418                 nn->reclaim_str_hashtbl_size++;
6419         }
6420         return crp;
6421 }
6422
6423 void
6424 nfs4_remove_reclaim_record(struct nfs4_client_reclaim *crp, struct nfsd_net *nn)
6425 {
6426         list_del(&crp->cr_strhash);
6427         kfree(crp);
6428         nn->reclaim_str_hashtbl_size--;
6429 }
6430
6431 void
6432 nfs4_release_reclaim(struct nfsd_net *nn)
6433 {
6434         struct nfs4_client_reclaim *crp = NULL;
6435         int i;
6436
6437         for (i = 0; i < CLIENT_HASH_SIZE; i++) {
6438                 while (!list_empty(&nn->reclaim_str_hashtbl[i])) {
6439                         crp = list_entry(nn->reclaim_str_hashtbl[i].next,
6440                                         struct nfs4_client_reclaim, cr_strhash);
6441                         nfs4_remove_reclaim_record(crp, nn);
6442                 }
6443         }
6444         WARN_ON_ONCE(nn->reclaim_str_hashtbl_size);
6445 }
6446
6447 /*
6448  * called from OPEN, CLAIM_PREVIOUS with a new clientid. */
6449 struct nfs4_client_reclaim *
6450 nfsd4_find_reclaim_client(const char *recdir, struct nfsd_net *nn)
6451 {
6452         unsigned int strhashval;
6453         struct nfs4_client_reclaim *crp = NULL;
6454
6455         dprintk("NFSD: nfs4_find_reclaim_client for recdir %s\n", recdir);
6456
6457         strhashval = clientstr_hashval(recdir);
6458         list_for_each_entry(crp, &nn->reclaim_str_hashtbl[strhashval], cr_strhash) {
6459                 if (same_name(crp->cr_recdir, recdir)) {
6460                         return crp;
6461                 }
6462         }
6463         return NULL;
6464 }
6465
6466 /*
6467 * Called from OPEN. Look for clientid in reclaim list.
6468 */
6469 __be32
6470 nfs4_check_open_reclaim(clientid_t *clid,
6471                 struct nfsd4_compound_state *cstate,
6472                 struct nfsd_net *nn)
6473 {
6474         __be32 status;
6475
6476         /* find clientid in conf_id_hashtbl */
6477         status = lookup_clientid(clid, cstate, nn);
6478         if (status)
6479                 return nfserr_reclaim_bad;
6480
6481         if (test_bit(NFSD4_CLIENT_RECLAIM_COMPLETE, &cstate->clp->cl_flags))
6482                 return nfserr_no_grace;
6483
6484         if (nfsd4_client_record_check(cstate->clp))
6485                 return nfserr_reclaim_bad;
6486
6487         return nfs_ok;
6488 }
6489
6490 #ifdef CONFIG_NFSD_FAULT_INJECTION
6491 static inline void
6492 put_client(struct nfs4_client *clp)
6493 {
6494         atomic_dec(&clp->cl_refcount);
6495 }
6496
6497 static struct nfs4_client *
6498 nfsd_find_client(struct sockaddr_storage *addr, size_t addr_size)
6499 {
6500         struct nfs4_client *clp;
6501         struct nfsd_net *nn = net_generic(current->nsproxy->net_ns,
6502                                           nfsd_net_id);
6503
6504         if (!nfsd_netns_ready(nn))
6505                 return NULL;
6506
6507         list_for_each_entry(clp, &nn->client_lru, cl_lru) {
6508                 if (memcmp(&clp->cl_addr, addr, addr_size) == 0)
6509                         return clp;
6510         }
6511         return NULL;
6512 }
6513
6514 u64
6515 nfsd_inject_print_clients(void)
6516 {
6517         struct nfs4_client *clp;
6518         u64 count = 0;
6519         struct nfsd_net *nn = net_generic(current->nsproxy->net_ns,
6520                                           nfsd_net_id);
6521         char buf[INET6_ADDRSTRLEN];
6522
6523         if (!nfsd_netns_ready(nn))
6524                 return 0;
6525
6526         spin_lock(&nn->client_lock);
6527         list_for_each_entry(clp, &nn->client_lru, cl_lru) {
6528                 rpc_ntop((struct sockaddr *)&clp->cl_addr, buf, sizeof(buf));
6529                 pr_info("NFS Client: %s\n", buf);
6530                 ++count;
6531         }
6532         spin_unlock(&nn->client_lock);
6533
6534         return count;
6535 }
6536
6537 u64
6538 nfsd_inject_forget_client(struct sockaddr_storage *addr, size_t addr_size)
6539 {
6540         u64 count = 0;
6541         struct nfs4_client *clp;
6542         struct nfsd_net *nn = net_generic(current->nsproxy->net_ns,
6543                                           nfsd_net_id);
6544
6545         if (!nfsd_netns_ready(nn))
6546                 return count;
6547
6548         spin_lock(&nn->client_lock);
6549         clp = nfsd_find_client(addr, addr_size);
6550         if (clp) {
6551                 if (mark_client_expired_locked(clp) == nfs_ok)
6552                         ++count;
6553                 else
6554                         clp = NULL;
6555         }
6556         spin_unlock(&nn->client_lock);
6557
6558         if (clp)
6559                 expire_client(clp);
6560
6561         return count;
6562 }
6563
6564 u64
6565 nfsd_inject_forget_clients(u64 max)
6566 {
6567         u64 count = 0;
6568         struct nfs4_client *clp, *next;
6569         struct nfsd_net *nn = net_generic(current->nsproxy->net_ns,
6570                                                 nfsd_net_id);
6571         LIST_HEAD(reaplist);
6572
6573         if (!nfsd_netns_ready(nn))
6574                 return count;
6575
6576         spin_lock(&nn->client_lock);
6577         list_for_each_entry_safe(clp, next, &nn->client_lru, cl_lru) {
6578                 if (mark_client_expired_locked(clp) == nfs_ok) {
6579                         list_add(&clp->cl_lru, &reaplist);
6580                         if (max != 0 && ++count >= max)
6581                                 break;
6582                 }
6583         }
6584         spin_unlock(&nn->client_lock);
6585
6586         list_for_each_entry_safe(clp, next, &reaplist, cl_lru)
6587                 expire_client(clp);
6588
6589         return count;
6590 }
6591
6592 static void nfsd_print_count(struct nfs4_client *clp, unsigned int count,
6593                              const char *type)
6594 {
6595         char buf[INET6_ADDRSTRLEN];
6596         rpc_ntop((struct sockaddr *)&clp->cl_addr, buf, sizeof(buf));
6597         printk(KERN_INFO "NFS Client: %s has %u %s\n", buf, count, type);
6598 }
6599
6600 static void
6601 nfsd_inject_add_lock_to_list(struct nfs4_ol_stateid *lst,
6602                              struct list_head *collect)
6603 {
6604         struct nfs4_client *clp = lst->st_stid.sc_client;
6605         struct nfsd_net *nn = net_generic(current->nsproxy->net_ns,
6606                                           nfsd_net_id);
6607
6608         if (!collect)
6609                 return;
6610
6611         lockdep_assert_held(&nn->client_lock);
6612         atomic_inc(&clp->cl_refcount);
6613         list_add(&lst->st_locks, collect);
6614 }
6615
6616 static u64 nfsd_foreach_client_lock(struct nfs4_client *clp, u64 max,
6617                                     struct list_head *collect,
6618                                     bool (*func)(struct nfs4_ol_stateid *))
6619 {
6620         struct nfs4_openowner *oop;
6621         struct nfs4_ol_stateid *stp, *st_next;
6622         struct nfs4_ol_stateid *lst, *lst_next;
6623         u64 count = 0;
6624
6625         spin_lock(&clp->cl_lock);
6626         list_for_each_entry(oop, &clp->cl_openowners, oo_perclient) {
6627                 list_for_each_entry_safe(stp, st_next,
6628                                 &oop->oo_owner.so_stateids, st_perstateowner) {
6629                         list_for_each_entry_safe(lst, lst_next,
6630                                         &stp->st_locks, st_locks) {
6631                                 if (func) {
6632                                         if (func(lst))
6633                                                 nfsd_inject_add_lock_to_list(lst,
6634                                                                         collect);
6635                                 }
6636                                 ++count;
6637                                 /*
6638                                  * Despite the fact that these functions deal
6639                                  * with 64-bit integers for "count", we must
6640                                  * ensure that it doesn't blow up the
6641                                  * clp->cl_refcount. Throw a warning if we
6642                                  * start to approach INT_MAX here.
6643                                  */
6644                                 WARN_ON_ONCE(count == (INT_MAX / 2));
6645                                 if (count == max)
6646                                         goto out;
6647                         }
6648                 }
6649         }
6650 out:
6651         spin_unlock(&clp->cl_lock);
6652
6653         return count;
6654 }
6655
6656 static u64
6657 nfsd_collect_client_locks(struct nfs4_client *clp, struct list_head *collect,
6658                           u64 max)
6659 {
6660         return nfsd_foreach_client_lock(clp, max, collect, unhash_lock_stateid);
6661 }
6662
6663 static u64
6664 nfsd_print_client_locks(struct nfs4_client *clp)
6665 {
6666         u64 count = nfsd_foreach_client_lock(clp, 0, NULL, NULL);
6667         nfsd_print_count(clp, count, "locked files");
6668         return count;
6669 }
6670
6671 u64
6672 nfsd_inject_print_locks(void)
6673 {
6674         struct nfs4_client *clp;
6675         u64 count = 0;
6676         struct nfsd_net *nn = net_generic(current->nsproxy->net_ns,
6677                                                 nfsd_net_id);
6678
6679         if (!nfsd_netns_ready(nn))
6680                 return 0;
6681
6682         spin_lock(&nn->client_lock);
6683         list_for_each_entry(clp, &nn->client_lru, cl_lru)
6684                 count += nfsd_print_client_locks(clp);
6685         spin_unlock(&nn->client_lock);
6686
6687         return count;
6688 }
6689
6690 static void
6691 nfsd_reap_locks(struct list_head *reaplist)
6692 {
6693         struct nfs4_client *clp;
6694         struct nfs4_ol_stateid *stp, *next;
6695
6696         list_for_each_entry_safe(stp, next, reaplist, st_locks) {
6697                 list_del_init(&stp->st_locks);
6698                 clp = stp->st_stid.sc_client;
6699                 nfs4_put_stid(&stp->st_stid);
6700                 put_client(clp);
6701         }
6702 }
6703
6704 u64
6705 nfsd_inject_forget_client_locks(struct sockaddr_storage *addr, size_t addr_size)
6706 {
6707         unsigned int count = 0;
6708         struct nfs4_client *clp;
6709         struct nfsd_net *nn = net_generic(current->nsproxy->net_ns,
6710                                                 nfsd_net_id);
6711         LIST_HEAD(reaplist);
6712
6713         if (!nfsd_netns_ready(nn))
6714                 return count;
6715
6716         spin_lock(&nn->client_lock);
6717         clp = nfsd_find_client(addr, addr_size);
6718         if (clp)
6719                 count = nfsd_collect_client_locks(clp, &reaplist, 0);
6720         spin_unlock(&nn->client_lock);
6721         nfsd_reap_locks(&reaplist);
6722         return count;
6723 }
6724
6725 u64
6726 nfsd_inject_forget_locks(u64 max)
6727 {
6728         u64 count = 0;
6729         struct nfs4_client *clp;
6730         struct nfsd_net *nn = net_generic(current->nsproxy->net_ns,
6731                                                 nfsd_net_id);
6732         LIST_HEAD(reaplist);
6733
6734         if (!nfsd_netns_ready(nn))
6735                 return count;
6736
6737         spin_lock(&nn->client_lock);
6738         list_for_each_entry(clp, &nn->client_lru, cl_lru) {
6739                 count += nfsd_collect_client_locks(clp, &reaplist, max - count);
6740                 if (max != 0 && count >= max)
6741                         break;
6742         }
6743         spin_unlock(&nn->client_lock);
6744         nfsd_reap_locks(&reaplist);
6745         return count;
6746 }
6747
6748 static u64
6749 nfsd_foreach_client_openowner(struct nfs4_client *clp, u64 max,
6750                               struct list_head *collect,
6751                               void (*func)(struct nfs4_openowner *))
6752 {
6753         struct nfs4_openowner *oop, *next;
6754         struct nfsd_net *nn = net_generic(current->nsproxy->net_ns,
6755                                                 nfsd_net_id);
6756         u64 count = 0;
6757
6758         lockdep_assert_held(&nn->client_lock);
6759
6760         spin_lock(&clp->cl_lock);
6761         list_for_each_entry_safe(oop, next, &clp->cl_openowners, oo_perclient) {
6762                 if (func) {
6763                         func(oop);
6764                         if (collect) {
6765                                 atomic_inc(&clp->cl_refcount);
6766                                 list_add(&oop->oo_perclient, collect);
6767                         }
6768                 }
6769                 ++count;
6770                 /*
6771                  * Despite the fact that these functions deal with
6772                  * 64-bit integers for "count", we must ensure that
6773                  * it doesn't blow up the clp->cl_refcount. Throw a
6774                  * warning if we start to approach INT_MAX here.
6775                  */
6776                 WARN_ON_ONCE(count == (INT_MAX / 2));
6777                 if (count == max)
6778                         break;
6779         }
6780         spin_unlock(&clp->cl_lock);
6781
6782         return count;
6783 }
6784
6785 static u64
6786 nfsd_print_client_openowners(struct nfs4_client *clp)
6787 {
6788         u64 count = nfsd_foreach_client_openowner(clp, 0, NULL, NULL);
6789
6790         nfsd_print_count(clp, count, "openowners");
6791         return count;
6792 }
6793
6794 static u64
6795 nfsd_collect_client_openowners(struct nfs4_client *clp,
6796                                struct list_head *collect, u64 max)
6797 {
6798         return nfsd_foreach_client_openowner(clp, max, collect,
6799                                                 unhash_openowner_locked);
6800 }
6801
6802 u64
6803 nfsd_inject_print_openowners(void)
6804 {
6805         struct nfs4_client *clp;
6806         u64 count = 0;
6807         struct nfsd_net *nn = net_generic(current->nsproxy->net_ns,
6808                                                 nfsd_net_id);
6809
6810         if (!nfsd_netns_ready(nn))
6811                 return 0;
6812
6813         spin_lock(&nn->client_lock);
6814         list_for_each_entry(clp, &nn->client_lru, cl_lru)
6815                 count += nfsd_print_client_openowners(clp);
6816         spin_unlock(&nn->client_lock);
6817
6818         return count;
6819 }
6820
6821 static void
6822 nfsd_reap_openowners(struct list_head *reaplist)
6823 {
6824         struct nfs4_client *clp;
6825         struct nfs4_openowner *oop, *next;
6826
6827         list_for_each_entry_safe(oop, next, reaplist, oo_perclient) {
6828                 list_del_init(&oop->oo_perclient);
6829                 clp = oop->oo_owner.so_client;
6830                 release_openowner(oop);
6831                 put_client(clp);
6832         }
6833 }
6834
6835 u64
6836 nfsd_inject_forget_client_openowners(struct sockaddr_storage *addr,
6837                                      size_t addr_size)
6838 {
6839         unsigned int count = 0;
6840         struct nfs4_client *clp;
6841         struct nfsd_net *nn = net_generic(current->nsproxy->net_ns,
6842                                                 nfsd_net_id);
6843         LIST_HEAD(reaplist);
6844
6845         if (!nfsd_netns_ready(nn))
6846                 return count;
6847
6848         spin_lock(&nn->client_lock);
6849         clp = nfsd_find_client(addr, addr_size);
6850         if (clp)
6851                 count = nfsd_collect_client_openowners(clp, &reaplist, 0);
6852         spin_unlock(&nn->client_lock);
6853         nfsd_reap_openowners(&reaplist);
6854         return count;
6855 }
6856
6857 u64
6858 nfsd_inject_forget_openowners(u64 max)
6859 {
6860         u64 count = 0;
6861         struct nfs4_client *clp;
6862         struct nfsd_net *nn = net_generic(current->nsproxy->net_ns,
6863                                                 nfsd_net_id);
6864         LIST_HEAD(reaplist);
6865
6866         if (!nfsd_netns_ready(nn))
6867                 return count;
6868
6869         spin_lock(&nn->client_lock);
6870         list_for_each_entry(clp, &nn->client_lru, cl_lru) {
6871                 count += nfsd_collect_client_openowners(clp, &reaplist,
6872                                                         max - count);
6873                 if (max != 0 && count >= max)
6874                         break;
6875         }
6876         spin_unlock(&nn->client_lock);
6877         nfsd_reap_openowners(&reaplist);
6878         return count;
6879 }
6880
6881 static u64 nfsd_find_all_delegations(struct nfs4_client *clp, u64 max,
6882                                      struct list_head *victims)
6883 {
6884         struct nfs4_delegation *dp, *next;
6885         struct nfsd_net *nn = net_generic(current->nsproxy->net_ns,
6886                                                 nfsd_net_id);
6887         u64 count = 0;
6888
6889         lockdep_assert_held(&nn->client_lock);
6890
6891         spin_lock(&state_lock);
6892         list_for_each_entry_safe(dp, next, &clp->cl_delegations, dl_perclnt) {
6893                 if (victims) {
6894                         /*
6895                          * It's not safe to mess with delegations that have a
6896                          * non-zero dl_time. They might have already been broken
6897                          * and could be processed by the laundromat outside of
6898                          * the state_lock. Just leave them be.
6899                          */
6900                         if (dp->dl_time != 0)
6901                                 continue;
6902
6903                         atomic_inc(&clp->cl_refcount);
6904                         WARN_ON(!unhash_delegation_locked(dp));
6905                         list_add(&dp->dl_recall_lru, victims);
6906                 }
6907                 ++count;
6908                 /*
6909                  * Despite the fact that these functions deal with
6910                  * 64-bit integers for "count", we must ensure that
6911                  * it doesn't blow up the clp->cl_refcount. Throw a
6912                  * warning if we start to approach INT_MAX here.
6913                  */
6914                 WARN_ON_ONCE(count == (INT_MAX / 2));
6915                 if (count == max)
6916                         break;
6917         }
6918         spin_unlock(&state_lock);
6919         return count;
6920 }
6921
6922 static u64
6923 nfsd_print_client_delegations(struct nfs4_client *clp)
6924 {
6925         u64 count = nfsd_find_all_delegations(clp, 0, NULL);
6926
6927         nfsd_print_count(clp, count, "delegations");
6928         return count;
6929 }
6930
6931 u64
6932 nfsd_inject_print_delegations(void)
6933 {
6934         struct nfs4_client *clp;
6935         u64 count = 0;
6936         struct nfsd_net *nn = net_generic(current->nsproxy->net_ns,
6937                                                 nfsd_net_id);
6938
6939         if (!nfsd_netns_ready(nn))
6940                 return 0;
6941
6942         spin_lock(&nn->client_lock);
6943         list_for_each_entry(clp, &nn->client_lru, cl_lru)
6944                 count += nfsd_print_client_delegations(clp);
6945         spin_unlock(&nn->client_lock);
6946
6947         return count;
6948 }
6949
6950 static void
6951 nfsd_forget_delegations(struct list_head *reaplist)
6952 {
6953         struct nfs4_client *clp;
6954         struct nfs4_delegation *dp, *next;
6955
6956         list_for_each_entry_safe(dp, next, reaplist, dl_recall_lru) {
6957                 list_del_init(&dp->dl_recall_lru);
6958                 clp = dp->dl_stid.sc_client;
6959                 revoke_delegation(dp);
6960                 put_client(clp);
6961         }
6962 }
6963
6964 u64
6965 nfsd_inject_forget_client_delegations(struct sockaddr_storage *addr,
6966                                       size_t addr_size)
6967 {
6968         u64 count = 0;
6969         struct nfs4_client *clp;
6970         struct nfsd_net *nn = net_generic(current->nsproxy->net_ns,
6971                                                 nfsd_net_id);
6972         LIST_HEAD(reaplist);
6973
6974         if (!nfsd_netns_ready(nn))
6975                 return count;
6976
6977         spin_lock(&nn->client_lock);
6978         clp = nfsd_find_client(addr, addr_size);
6979         if (clp)
6980                 count = nfsd_find_all_delegations(clp, 0, &reaplist);
6981         spin_unlock(&nn->client_lock);
6982
6983         nfsd_forget_delegations(&reaplist);
6984         return count;
6985 }
6986
6987 u64
6988 nfsd_inject_forget_delegations(u64 max)
6989 {
6990         u64 count = 0;
6991         struct nfs4_client *clp;
6992         struct nfsd_net *nn = net_generic(current->nsproxy->net_ns,
6993                                                 nfsd_net_id);
6994         LIST_HEAD(reaplist);
6995
6996         if (!nfsd_netns_ready(nn))
6997                 return count;
6998
6999         spin_lock(&nn->client_lock);
7000         list_for_each_entry(clp, &nn->client_lru, cl_lru) {
7001                 count += nfsd_find_all_delegations(clp, max - count, &reaplist);
7002                 if (max != 0 && count >= max)
7003                         break;
7004         }
7005         spin_unlock(&nn->client_lock);
7006         nfsd_forget_delegations(&reaplist);
7007         return count;
7008 }
7009
7010 static void
7011 nfsd_recall_delegations(struct list_head *reaplist)
7012 {
7013         struct nfs4_client *clp;
7014         struct nfs4_delegation *dp, *next;
7015
7016         list_for_each_entry_safe(dp, next, reaplist, dl_recall_lru) {
7017                 list_del_init(&dp->dl_recall_lru);
7018                 clp = dp->dl_stid.sc_client;
7019                 /*
7020                  * We skipped all entries that had a zero dl_time before,
7021                  * so we can now reset the dl_time back to 0. If a delegation
7022                  * break comes in now, then it won't make any difference since
7023                  * we're recalling it either way.
7024                  */
7025                 spin_lock(&state_lock);
7026                 dp->dl_time = 0;
7027                 spin_unlock(&state_lock);
7028                 nfsd_break_one_deleg(dp);
7029                 put_client(clp);
7030         }
7031 }
7032
7033 u64
7034 nfsd_inject_recall_client_delegations(struct sockaddr_storage *addr,
7035                                       size_t addr_size)
7036 {
7037         u64 count = 0;
7038         struct nfs4_client *clp;
7039         struct nfsd_net *nn = net_generic(current->nsproxy->net_ns,
7040                                                 nfsd_net_id);
7041         LIST_HEAD(reaplist);
7042
7043         if (!nfsd_netns_ready(nn))
7044                 return count;
7045
7046         spin_lock(&nn->client_lock);
7047         clp = nfsd_find_client(addr, addr_size);
7048         if (clp)
7049                 count = nfsd_find_all_delegations(clp, 0, &reaplist);
7050         spin_unlock(&nn->client_lock);
7051
7052         nfsd_recall_delegations(&reaplist);
7053         return count;
7054 }
7055
7056 u64
7057 nfsd_inject_recall_delegations(u64 max)
7058 {
7059         u64 count = 0;
7060         struct nfs4_client *clp, *next;
7061         struct nfsd_net *nn = net_generic(current->nsproxy->net_ns,
7062                                                 nfsd_net_id);
7063         LIST_HEAD(reaplist);
7064
7065         if (!nfsd_netns_ready(nn))
7066                 return count;
7067
7068         spin_lock(&nn->client_lock);
7069         list_for_each_entry_safe(clp, next, &nn->client_lru, cl_lru) {
7070                 count += nfsd_find_all_delegations(clp, max - count, &reaplist);
7071                 if (max != 0 && ++count >= max)
7072                         break;
7073         }
7074         spin_unlock(&nn->client_lock);
7075         nfsd_recall_delegations(&reaplist);
7076         return count;
7077 }
7078 #endif /* CONFIG_NFSD_FAULT_INJECTION */
7079
7080 /*
7081  * Since the lifetime of a delegation isn't limited to that of an open, a
7082  * client may quite reasonably hang on to a delegation as long as it has
7083  * the inode cached.  This becomes an obvious problem the first time a
7084  * client's inode cache approaches the size of the server's total memory.
7085  *
7086  * For now we avoid this problem by imposing a hard limit on the number
7087  * of delegations, which varies according to the server's memory size.
7088  */
7089 static void
7090 set_max_delegations(void)
7091 {
7092         /*
7093          * Allow at most 4 delegations per megabyte of RAM.  Quick
7094          * estimates suggest that in the worst case (where every delegation
7095          * is for a different inode), a delegation could take about 1.5K,
7096          * giving a worst case usage of about 6% of memory.
7097          */
7098         max_delegations = nr_free_buffer_pages() >> (20 - 2 - PAGE_SHIFT);
7099 }
7100
7101 static int nfs4_state_create_net(struct net *net)
7102 {
7103         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
7104         int i;
7105
7106         nn->conf_id_hashtbl = kmalloc(sizeof(struct list_head) *
7107                         CLIENT_HASH_SIZE, GFP_KERNEL);
7108         if (!nn->conf_id_hashtbl)
7109                 goto err;
7110         nn->unconf_id_hashtbl = kmalloc(sizeof(struct list_head) *
7111                         CLIENT_HASH_SIZE, GFP_KERNEL);
7112         if (!nn->unconf_id_hashtbl)
7113                 goto err_unconf_id;
7114         nn->sessionid_hashtbl = kmalloc(sizeof(struct list_head) *
7115                         SESSION_HASH_SIZE, GFP_KERNEL);
7116         if (!nn->sessionid_hashtbl)
7117                 goto err_sessionid;
7118
7119         for (i = 0; i < CLIENT_HASH_SIZE; i++) {
7120                 INIT_LIST_HEAD(&nn->conf_id_hashtbl[i]);
7121                 INIT_LIST_HEAD(&nn->unconf_id_hashtbl[i]);
7122         }
7123         for (i = 0; i < SESSION_HASH_SIZE; i++)
7124                 INIT_LIST_HEAD(&nn->sessionid_hashtbl[i]);
7125         nn->conf_name_tree = RB_ROOT;
7126         nn->unconf_name_tree = RB_ROOT;
7127         nn->boot_time = get_seconds();
7128         nn->grace_ended = false;
7129         nn->nfsd4_manager.block_opens = true;
7130         INIT_LIST_HEAD(&nn->nfsd4_manager.list);
7131         INIT_LIST_HEAD(&nn->client_lru);
7132         INIT_LIST_HEAD(&nn->close_lru);
7133         INIT_LIST_HEAD(&nn->del_recall_lru);
7134         spin_lock_init(&nn->client_lock);
7135
7136         spin_lock_init(&nn->blocked_locks_lock);
7137         INIT_LIST_HEAD(&nn->blocked_locks_lru);
7138
7139         INIT_DELAYED_WORK(&nn->laundromat_work, laundromat_main);
7140         get_net(net);
7141
7142         return 0;
7143
7144 err_sessionid:
7145         kfree(nn->unconf_id_hashtbl);
7146 err_unconf_id:
7147         kfree(nn->conf_id_hashtbl);
7148 err:
7149         return -ENOMEM;
7150 }
7151
7152 static void
7153 nfs4_state_destroy_net(struct net *net)
7154 {
7155         int i;
7156         struct nfs4_client *clp = NULL;
7157         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
7158
7159         for (i = 0; i < CLIENT_HASH_SIZE; i++) {
7160                 while (!list_empty(&nn->conf_id_hashtbl[i])) {
7161                         clp = list_entry(nn->conf_id_hashtbl[i].next, struct nfs4_client, cl_idhash);
7162                         destroy_client(clp);
7163                 }
7164         }
7165
7166         WARN_ON(!list_empty(&nn->blocked_locks_lru));
7167
7168         for (i = 0; i < CLIENT_HASH_SIZE; i++) {
7169                 while (!list_empty(&nn->unconf_id_hashtbl[i])) {
7170                         clp = list_entry(nn->unconf_id_hashtbl[i].next, struct nfs4_client, cl_idhash);
7171                         destroy_client(clp);
7172                 }
7173         }
7174
7175         kfree(nn->sessionid_hashtbl);
7176         kfree(nn->unconf_id_hashtbl);
7177         kfree(nn->conf_id_hashtbl);
7178         put_net(net);
7179 }
7180
7181 int
7182 nfs4_state_start_net(struct net *net)
7183 {
7184         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
7185         int ret;
7186
7187         ret = nfs4_state_create_net(net);
7188         if (ret)
7189                 return ret;
7190         locks_start_grace(net, &nn->nfsd4_manager);
7191         nfsd4_client_tracking_init(net);
7192         printk(KERN_INFO "NFSD: starting %ld-second grace period (net %p)\n",
7193                nn->nfsd4_grace, net);
7194         queue_delayed_work(laundry_wq, &nn->laundromat_work, nn->nfsd4_grace * HZ);
7195         return 0;
7196 }
7197
7198 /* initialization to perform when the nfsd service is started: */
7199
7200 int
7201 nfs4_state_start(void)
7202 {
7203         int ret;
7204
7205         ret = set_callback_cred();
7206         if (ret)
7207                 return ret;
7208
7209         laundry_wq = alloc_workqueue("%s", WQ_UNBOUND, 0, "nfsd4");
7210         if (laundry_wq == NULL) {
7211                 ret = -ENOMEM;
7212                 goto out_cleanup_cred;
7213         }
7214         ret = nfsd4_create_callback_queue();
7215         if (ret)
7216                 goto out_free_laundry;
7217
7218         set_max_delegations();
7219         return 0;
7220
7221 out_free_laundry:
7222         destroy_workqueue(laundry_wq);
7223 out_cleanup_cred:
7224         cleanup_callback_cred();
7225         return ret;
7226 }
7227
7228 void
7229 nfs4_state_shutdown_net(struct net *net)
7230 {
7231         struct nfs4_delegation *dp = NULL;
7232         struct list_head *pos, *next, reaplist;
7233         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
7234
7235         cancel_delayed_work_sync(&nn->laundromat_work);
7236         locks_end_grace(&nn->nfsd4_manager);
7237
7238         INIT_LIST_HEAD(&reaplist);
7239         spin_lock(&state_lock);
7240         list_for_each_safe(pos, next, &nn->del_recall_lru) {
7241                 dp = list_entry (pos, struct nfs4_delegation, dl_recall_lru);
7242                 WARN_ON(!unhash_delegation_locked(dp));
7243                 list_add(&dp->dl_recall_lru, &reaplist);
7244         }
7245         spin_unlock(&state_lock);
7246         list_for_each_safe(pos, next, &reaplist) {
7247                 dp = list_entry (pos, struct nfs4_delegation, dl_recall_lru);
7248                 list_del_init(&dp->dl_recall_lru);
7249                 put_clnt_odstate(dp->dl_clnt_odstate);
7250                 nfs4_put_deleg_lease(dp->dl_stid.sc_file);
7251                 nfs4_put_stid(&dp->dl_stid);
7252         }
7253
7254         nfsd4_client_tracking_exit(net);
7255         nfs4_state_destroy_net(net);
7256 }
7257
7258 void
7259 nfs4_state_shutdown(void)
7260 {
7261         destroy_workqueue(laundry_wq);
7262         nfsd4_destroy_callback_queue();
7263         cleanup_callback_cred();
7264 }
7265
7266 static void
7267 get_stateid(struct nfsd4_compound_state *cstate, stateid_t *stateid)
7268 {
7269         if (HAS_STATE_ID(cstate, CURRENT_STATE_ID_FLAG) && CURRENT_STATEID(stateid))
7270                 memcpy(stateid, &cstate->current_stateid, sizeof(stateid_t));
7271 }
7272
7273 static void
7274 put_stateid(struct nfsd4_compound_state *cstate, stateid_t *stateid)
7275 {
7276         if (cstate->minorversion) {
7277                 memcpy(&cstate->current_stateid, stateid, sizeof(stateid_t));
7278                 SET_STATE_ID(cstate, CURRENT_STATE_ID_FLAG);
7279         }
7280 }
7281
7282 void
7283 clear_current_stateid(struct nfsd4_compound_state *cstate)
7284 {
7285         CLEAR_STATE_ID(cstate, CURRENT_STATE_ID_FLAG);
7286 }
7287
7288 /*
7289  * functions to set current state id
7290  */
7291 void
7292 nfsd4_set_opendowngradestateid(struct nfsd4_compound_state *cstate,
7293                 union nfsd4_op_u *u)
7294 {
7295         put_stateid(cstate, &u->open_downgrade.od_stateid);
7296 }
7297
7298 void
7299 nfsd4_set_openstateid(struct nfsd4_compound_state *cstate,
7300                 union nfsd4_op_u *u)
7301 {
7302         put_stateid(cstate, &u->open.op_stateid);
7303 }
7304
7305 void
7306 nfsd4_set_closestateid(struct nfsd4_compound_state *cstate,
7307                 union nfsd4_op_u *u)
7308 {
7309         put_stateid(cstate, &u->close.cl_stateid);
7310 }
7311
7312 void
7313 nfsd4_set_lockstateid(struct nfsd4_compound_state *cstate,
7314                 union nfsd4_op_u *u)
7315 {
7316         put_stateid(cstate, &u->lock.lk_resp_stateid);
7317 }
7318
7319 /*
7320  * functions to consume current state id
7321  */
7322
7323 void
7324 nfsd4_get_opendowngradestateid(struct nfsd4_compound_state *cstate,
7325                 union nfsd4_op_u *u)
7326 {
7327         get_stateid(cstate, &u->open_downgrade.od_stateid);
7328 }
7329
7330 void
7331 nfsd4_get_delegreturnstateid(struct nfsd4_compound_state *cstate,
7332                 union nfsd4_op_u *u)
7333 {
7334         get_stateid(cstate, &u->delegreturn.dr_stateid);
7335 }
7336
7337 void
7338 nfsd4_get_freestateid(struct nfsd4_compound_state *cstate,
7339                 union nfsd4_op_u *u)
7340 {
7341         get_stateid(cstate, &u->free_stateid.fr_stateid);
7342 }
7343
7344 void
7345 nfsd4_get_setattrstateid(struct nfsd4_compound_state *cstate,
7346                 union nfsd4_op_u *u)
7347 {
7348         get_stateid(cstate, &u->setattr.sa_stateid);
7349 }
7350
7351 void
7352 nfsd4_get_closestateid(struct nfsd4_compound_state *cstate,
7353                 union nfsd4_op_u *u)
7354 {
7355         get_stateid(cstate, &u->close.cl_stateid);
7356 }
7357
7358 void
7359 nfsd4_get_lockustateid(struct nfsd4_compound_state *cstate,
7360                 union nfsd4_op_u *u)
7361 {
7362         get_stateid(cstate, &u->locku.lu_stateid);
7363 }
7364
7365 void
7366 nfsd4_get_readstateid(struct nfsd4_compound_state *cstate,
7367                 union nfsd4_op_u *u)
7368 {
7369         get_stateid(cstate, &u->read.rd_stateid);
7370 }
7371
7372 void
7373 nfsd4_get_writestateid(struct nfsd4_compound_state *cstate,
7374                 union nfsd4_op_u *u)
7375 {
7376         get_stateid(cstate, &u->write.wr_stateid);
7377 }