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