OSDN Git Service

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