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