nfsd: clean up races in lock stateid searching and creation
[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(struct nfs4_client *cl, stateid_t *t)
1693 {
1694         struct nfs4_stid *ret;
1695
1696         spin_lock(&cl->cl_lock);
1697         ret = find_stateid_locked(cl, t);
1698         spin_unlock(&cl->cl_lock);
1699         return ret;
1700 }
1701
1702 static struct nfs4_stid *
1703 find_stateid_by_type(struct nfs4_client *cl, stateid_t *t, char typemask)
1704 {
1705         struct nfs4_stid *s;
1706
1707         spin_lock(&cl->cl_lock);
1708         s = find_stateid_locked(cl, t);
1709         if (s != NULL && !(typemask & s->sc_type))
1710                 s = NULL;
1711         spin_unlock(&cl->cl_lock);
1712         return s;
1713 }
1714
1715 static struct nfs4_client *create_client(struct xdr_netobj name,
1716                 struct svc_rqst *rqstp, nfs4_verifier *verf)
1717 {
1718         struct nfs4_client *clp;
1719         struct sockaddr *sa = svc_addr(rqstp);
1720         int ret;
1721         struct net *net = SVC_NET(rqstp);
1722         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
1723
1724         clp = alloc_client(name);
1725         if (clp == NULL)
1726                 return NULL;
1727
1728         ret = copy_cred(&clp->cl_cred, &rqstp->rq_cred);
1729         if (ret) {
1730                 spin_lock(&nn->client_lock);
1731                 free_client(clp);
1732                 spin_unlock(&nn->client_lock);
1733                 return NULL;
1734         }
1735         INIT_WORK(&clp->cl_cb_null.cb_work, nfsd4_run_cb_null);
1736         clp->cl_time = get_seconds();
1737         clear_bit(0, &clp->cl_cb_slot_busy);
1738         copy_verf(clp, verf);
1739         rpc_copy_addr((struct sockaddr *) &clp->cl_addr, sa);
1740         gen_confirm(clp);
1741         clp->cl_cb_session = NULL;
1742         clp->net = net;
1743         return clp;
1744 }
1745
1746 static void
1747 add_clp_to_name_tree(struct nfs4_client *new_clp, struct rb_root *root)
1748 {
1749         struct rb_node **new = &(root->rb_node), *parent = NULL;
1750         struct nfs4_client *clp;
1751
1752         while (*new) {
1753                 clp = rb_entry(*new, struct nfs4_client, cl_namenode);
1754                 parent = *new;
1755
1756                 if (compare_blob(&clp->cl_name, &new_clp->cl_name) > 0)
1757                         new = &((*new)->rb_left);
1758                 else
1759                         new = &((*new)->rb_right);
1760         }
1761
1762         rb_link_node(&new_clp->cl_namenode, parent, new);
1763         rb_insert_color(&new_clp->cl_namenode, root);
1764 }
1765
1766 static struct nfs4_client *
1767 find_clp_in_name_tree(struct xdr_netobj *name, struct rb_root *root)
1768 {
1769         long long cmp;
1770         struct rb_node *node = root->rb_node;
1771         struct nfs4_client *clp;
1772
1773         while (node) {
1774                 clp = rb_entry(node, struct nfs4_client, cl_namenode);
1775                 cmp = compare_blob(&clp->cl_name, name);
1776                 if (cmp > 0)
1777                         node = node->rb_left;
1778                 else if (cmp < 0)
1779                         node = node->rb_right;
1780                 else
1781                         return clp;
1782         }
1783         return NULL;
1784 }
1785
1786 static void
1787 add_to_unconfirmed(struct nfs4_client *clp)
1788 {
1789         unsigned int idhashval;
1790         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
1791
1792         clear_bit(NFSD4_CLIENT_CONFIRMED, &clp->cl_flags);
1793         add_clp_to_name_tree(clp, &nn->unconf_name_tree);
1794         idhashval = clientid_hashval(clp->cl_clientid.cl_id);
1795         list_add(&clp->cl_idhash, &nn->unconf_id_hashtbl[idhashval]);
1796         renew_client(clp);
1797 }
1798
1799 static void
1800 move_to_confirmed(struct nfs4_client *clp)
1801 {
1802         unsigned int idhashval = clientid_hashval(clp->cl_clientid.cl_id);
1803         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
1804
1805         dprintk("NFSD: move_to_confirm nfs4_client %p\n", clp);
1806         list_move(&clp->cl_idhash, &nn->conf_id_hashtbl[idhashval]);
1807         rb_erase(&clp->cl_namenode, &nn->unconf_name_tree);
1808         add_clp_to_name_tree(clp, &nn->conf_name_tree);
1809         set_bit(NFSD4_CLIENT_CONFIRMED, &clp->cl_flags);
1810         renew_client(clp);
1811 }
1812
1813 static struct nfs4_client *
1814 find_client_in_id_table(struct list_head *tbl, clientid_t *clid, bool sessions)
1815 {
1816         struct nfs4_client *clp;
1817         unsigned int idhashval = clientid_hashval(clid->cl_id);
1818
1819         list_for_each_entry(clp, &tbl[idhashval], cl_idhash) {
1820                 if (same_clid(&clp->cl_clientid, clid)) {
1821                         if ((bool)clp->cl_minorversion != sessions)
1822                                 return NULL;
1823                         renew_client(clp);
1824                         return clp;
1825                 }
1826         }
1827         return NULL;
1828 }
1829
1830 static struct nfs4_client *
1831 find_confirmed_client(clientid_t *clid, bool sessions, struct nfsd_net *nn)
1832 {
1833         struct list_head *tbl = nn->conf_id_hashtbl;
1834
1835         return find_client_in_id_table(tbl, clid, sessions);
1836 }
1837
1838 static struct nfs4_client *
1839 find_unconfirmed_client(clientid_t *clid, bool sessions, struct nfsd_net *nn)
1840 {
1841         struct list_head *tbl = nn->unconf_id_hashtbl;
1842
1843         return find_client_in_id_table(tbl, clid, sessions);
1844 }
1845
1846 static bool clp_used_exchangeid(struct nfs4_client *clp)
1847 {
1848         return clp->cl_exchange_flags != 0;
1849
1850
1851 static struct nfs4_client *
1852 find_confirmed_client_by_name(struct xdr_netobj *name, struct nfsd_net *nn)
1853 {
1854         return find_clp_in_name_tree(name, &nn->conf_name_tree);
1855 }
1856
1857 static struct nfs4_client *
1858 find_unconfirmed_client_by_name(struct xdr_netobj *name, struct nfsd_net *nn)
1859 {
1860         return find_clp_in_name_tree(name, &nn->unconf_name_tree);
1861 }
1862
1863 static void
1864 gen_callback(struct nfs4_client *clp, struct nfsd4_setclientid *se, struct svc_rqst *rqstp)
1865 {
1866         struct nfs4_cb_conn *conn = &clp->cl_cb_conn;
1867         struct sockaddr *sa = svc_addr(rqstp);
1868         u32 scopeid = rpc_get_scope_id(sa);
1869         unsigned short expected_family;
1870
1871         /* Currently, we only support tcp and tcp6 for the callback channel */
1872         if (se->se_callback_netid_len == 3 &&
1873             !memcmp(se->se_callback_netid_val, "tcp", 3))
1874                 expected_family = AF_INET;
1875         else if (se->se_callback_netid_len == 4 &&
1876                  !memcmp(se->se_callback_netid_val, "tcp6", 4))
1877                 expected_family = AF_INET6;
1878         else
1879                 goto out_err;
1880
1881         conn->cb_addrlen = rpc_uaddr2sockaddr(clp->net, se->se_callback_addr_val,
1882                                             se->se_callback_addr_len,
1883                                             (struct sockaddr *)&conn->cb_addr,
1884                                             sizeof(conn->cb_addr));
1885
1886         if (!conn->cb_addrlen || conn->cb_addr.ss_family != expected_family)
1887                 goto out_err;
1888
1889         if (conn->cb_addr.ss_family == AF_INET6)
1890                 ((struct sockaddr_in6 *)&conn->cb_addr)->sin6_scope_id = scopeid;
1891
1892         conn->cb_prog = se->se_callback_prog;
1893         conn->cb_ident = se->se_callback_ident;
1894         memcpy(&conn->cb_saddr, &rqstp->rq_daddr, rqstp->rq_daddrlen);
1895         return;
1896 out_err:
1897         conn->cb_addr.ss_family = AF_UNSPEC;
1898         conn->cb_addrlen = 0;
1899         dprintk(KERN_INFO "NFSD: this client (clientid %08x/%08x) "
1900                 "will not receive delegations\n",
1901                 clp->cl_clientid.cl_boot, clp->cl_clientid.cl_id);
1902
1903         return;
1904 }
1905
1906 /*
1907  * Cache a reply. nfsd4_check_resp_size() has bounded the cache size.
1908  */
1909 static void
1910 nfsd4_store_cache_entry(struct nfsd4_compoundres *resp)
1911 {
1912         struct xdr_buf *buf = resp->xdr.buf;
1913         struct nfsd4_slot *slot = resp->cstate.slot;
1914         unsigned int base;
1915
1916         dprintk("--> %s slot %p\n", __func__, slot);
1917
1918         slot->sl_opcnt = resp->opcnt;
1919         slot->sl_status = resp->cstate.status;
1920
1921         slot->sl_flags |= NFSD4_SLOT_INITIALIZED;
1922         if (nfsd4_not_cached(resp)) {
1923                 slot->sl_datalen = 0;
1924                 return;
1925         }
1926         base = resp->cstate.data_offset;
1927         slot->sl_datalen = buf->len - base;
1928         if (read_bytes_from_xdr_buf(buf, base, slot->sl_data, slot->sl_datalen))
1929                 WARN("%s: sessions DRC could not cache compound\n", __func__);
1930         return;
1931 }
1932
1933 /*
1934  * Encode the replay sequence operation from the slot values.
1935  * If cachethis is FALSE encode the uncached rep error on the next
1936  * operation which sets resp->p and increments resp->opcnt for
1937  * nfs4svc_encode_compoundres.
1938  *
1939  */
1940 static __be32
1941 nfsd4_enc_sequence_replay(struct nfsd4_compoundargs *args,
1942                           struct nfsd4_compoundres *resp)
1943 {
1944         struct nfsd4_op *op;
1945         struct nfsd4_slot *slot = resp->cstate.slot;
1946
1947         /* Encode the replayed sequence operation */
1948         op = &args->ops[resp->opcnt - 1];
1949         nfsd4_encode_operation(resp, op);
1950
1951         /* Return nfserr_retry_uncached_rep in next operation. */
1952         if (args->opcnt > 1 && !(slot->sl_flags & NFSD4_SLOT_CACHETHIS)) {
1953                 op = &args->ops[resp->opcnt++];
1954                 op->status = nfserr_retry_uncached_rep;
1955                 nfsd4_encode_operation(resp, op);
1956         }
1957         return op->status;
1958 }
1959
1960 /*
1961  * The sequence operation is not cached because we can use the slot and
1962  * session values.
1963  */
1964 static __be32
1965 nfsd4_replay_cache_entry(struct nfsd4_compoundres *resp,
1966                          struct nfsd4_sequence *seq)
1967 {
1968         struct nfsd4_slot *slot = resp->cstate.slot;
1969         struct xdr_stream *xdr = &resp->xdr;
1970         __be32 *p;
1971         __be32 status;
1972
1973         dprintk("--> %s slot %p\n", __func__, slot);
1974
1975         status = nfsd4_enc_sequence_replay(resp->rqstp->rq_argp, resp);
1976         if (status)
1977                 return status;
1978
1979         p = xdr_reserve_space(xdr, slot->sl_datalen);
1980         if (!p) {
1981                 WARN_ON_ONCE(1);
1982                 return nfserr_serverfault;
1983         }
1984         xdr_encode_opaque_fixed(p, slot->sl_data, slot->sl_datalen);
1985         xdr_commit_encode(xdr);
1986
1987         resp->opcnt = slot->sl_opcnt;
1988         return slot->sl_status;
1989 }
1990
1991 /*
1992  * Set the exchange_id flags returned by the server.
1993  */
1994 static void
1995 nfsd4_set_ex_flags(struct nfs4_client *new, struct nfsd4_exchange_id *clid)
1996 {
1997         /* pNFS is not supported */
1998         new->cl_exchange_flags |= EXCHGID4_FLAG_USE_NON_PNFS;
1999
2000         /* Referrals are supported, Migration is not. */
2001         new->cl_exchange_flags |= EXCHGID4_FLAG_SUPP_MOVED_REFER;
2002
2003         /* set the wire flags to return to client. */
2004         clid->flags = new->cl_exchange_flags;
2005 }
2006
2007 static bool client_has_state(struct nfs4_client *clp)
2008 {
2009         /*
2010          * Note clp->cl_openowners check isn't quite right: there's no
2011          * need to count owners without stateid's.
2012          *
2013          * Also note we should probably be using this in 4.0 case too.
2014          */
2015         return !list_empty(&clp->cl_openowners)
2016                 || !list_empty(&clp->cl_delegations)
2017                 || !list_empty(&clp->cl_sessions);
2018 }
2019
2020 __be32
2021 nfsd4_exchange_id(struct svc_rqst *rqstp,
2022                   struct nfsd4_compound_state *cstate,
2023                   struct nfsd4_exchange_id *exid)
2024 {
2025         struct nfs4_client *unconf, *conf, *new;
2026         __be32 status;
2027         char                    addr_str[INET6_ADDRSTRLEN];
2028         nfs4_verifier           verf = exid->verifier;
2029         struct sockaddr         *sa = svc_addr(rqstp);
2030         bool    update = exid->flags & EXCHGID4_FLAG_UPD_CONFIRMED_REC_A;
2031         struct nfsd_net         *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
2032
2033         rpc_ntop(sa, addr_str, sizeof(addr_str));
2034         dprintk("%s rqstp=%p exid=%p clname.len=%u clname.data=%p "
2035                 "ip_addr=%s flags %x, spa_how %d\n",
2036                 __func__, rqstp, exid, exid->clname.len, exid->clname.data,
2037                 addr_str, exid->flags, exid->spa_how);
2038
2039         if (exid->flags & ~EXCHGID4_FLAG_MASK_A)
2040                 return nfserr_inval;
2041
2042         switch (exid->spa_how) {
2043         case SP4_MACH_CRED:
2044                 if (!svc_rqst_integrity_protected(rqstp))
2045                         return nfserr_inval;
2046         case SP4_NONE:
2047                 break;
2048         default:                                /* checked by xdr code */
2049                 WARN_ON_ONCE(1);
2050         case SP4_SSV:
2051                 return nfserr_encr_alg_unsupp;
2052         }
2053
2054         /* Cases below refer to rfc 5661 section 18.35.4: */
2055         nfs4_lock_state();
2056         conf = find_confirmed_client_by_name(&exid->clname, nn);
2057         if (conf) {
2058                 bool creds_match = same_creds(&conf->cl_cred, &rqstp->rq_cred);
2059                 bool verfs_match = same_verf(&verf, &conf->cl_verifier);
2060
2061                 if (update) {
2062                         if (!clp_used_exchangeid(conf)) { /* buggy client */
2063                                 status = nfserr_inval;
2064                                 goto out;
2065                         }
2066                         if (!mach_creds_match(conf, rqstp)) {
2067                                 status = nfserr_wrong_cred;
2068                                 goto out;
2069                         }
2070                         if (!creds_match) { /* case 9 */
2071                                 status = nfserr_perm;
2072                                 goto out;
2073                         }
2074                         if (!verfs_match) { /* case 8 */
2075                                 status = nfserr_not_same;
2076                                 goto out;
2077                         }
2078                         /* case 6 */
2079                         exid->flags |= EXCHGID4_FLAG_CONFIRMED_R;
2080                         new = conf;
2081                         goto out_copy;
2082                 }
2083                 if (!creds_match) { /* case 3 */
2084                         if (client_has_state(conf)) {
2085                                 status = nfserr_clid_inuse;
2086                                 goto out;
2087                         }
2088                         expire_client(conf);
2089                         goto out_new;
2090                 }
2091                 if (verfs_match) { /* case 2 */
2092                         conf->cl_exchange_flags |= EXCHGID4_FLAG_CONFIRMED_R;
2093                         new = conf;
2094                         goto out_copy;
2095                 }
2096                 /* case 5, client reboot */
2097                 goto out_new;
2098         }
2099
2100         if (update) { /* case 7 */
2101                 status = nfserr_noent;
2102                 goto out;
2103         }
2104
2105         unconf  = find_unconfirmed_client_by_name(&exid->clname, nn);
2106         if (unconf) /* case 4, possible retry or client restart */
2107                 expire_client(unconf);
2108
2109         /* case 1 (normal case) */
2110 out_new:
2111         new = create_client(exid->clname, rqstp, &verf);
2112         if (new == NULL) {
2113                 status = nfserr_jukebox;
2114                 goto out;
2115         }
2116         new->cl_minorversion = cstate->minorversion;
2117         new->cl_mach_cred = (exid->spa_how == SP4_MACH_CRED);
2118
2119         gen_clid(new, nn);
2120         add_to_unconfirmed(new);
2121 out_copy:
2122         exid->clientid.cl_boot = new->cl_clientid.cl_boot;
2123         exid->clientid.cl_id = new->cl_clientid.cl_id;
2124
2125         exid->seqid = new->cl_cs_slot.sl_seqid + 1;
2126         nfsd4_set_ex_flags(new, exid);
2127
2128         dprintk("nfsd4_exchange_id seqid %d flags %x\n",
2129                 new->cl_cs_slot.sl_seqid, new->cl_exchange_flags);
2130         status = nfs_ok;
2131
2132 out:
2133         nfs4_unlock_state();
2134         return status;
2135 }
2136
2137 static __be32
2138 check_slot_seqid(u32 seqid, u32 slot_seqid, int slot_inuse)
2139 {
2140         dprintk("%s enter. seqid %d slot_seqid %d\n", __func__, seqid,
2141                 slot_seqid);
2142
2143         /* The slot is in use, and no response has been sent. */
2144         if (slot_inuse) {
2145                 if (seqid == slot_seqid)
2146                         return nfserr_jukebox;
2147                 else
2148                         return nfserr_seq_misordered;
2149         }
2150         /* Note unsigned 32-bit arithmetic handles wraparound: */
2151         if (likely(seqid == slot_seqid + 1))
2152                 return nfs_ok;
2153         if (seqid == slot_seqid)
2154                 return nfserr_replay_cache;
2155         return nfserr_seq_misordered;
2156 }
2157
2158 /*
2159  * Cache the create session result into the create session single DRC
2160  * slot cache by saving the xdr structure. sl_seqid has been set.
2161  * Do this for solo or embedded create session operations.
2162  */
2163 static void
2164 nfsd4_cache_create_session(struct nfsd4_create_session *cr_ses,
2165                            struct nfsd4_clid_slot *slot, __be32 nfserr)
2166 {
2167         slot->sl_status = nfserr;
2168         memcpy(&slot->sl_cr_ses, cr_ses, sizeof(*cr_ses));
2169 }
2170
2171 static __be32
2172 nfsd4_replay_create_session(struct nfsd4_create_session *cr_ses,
2173                             struct nfsd4_clid_slot *slot)
2174 {
2175         memcpy(cr_ses, &slot->sl_cr_ses, sizeof(*cr_ses));
2176         return slot->sl_status;
2177 }
2178
2179 #define NFSD_MIN_REQ_HDR_SEQ_SZ ((\
2180                         2 * 2 + /* credential,verifier: AUTH_NULL, length 0 */ \
2181                         1 +     /* MIN tag is length with zero, only length */ \
2182                         3 +     /* version, opcount, opcode */ \
2183                         XDR_QUADLEN(NFS4_MAX_SESSIONID_LEN) + \
2184                                 /* seqid, slotID, slotID, cache */ \
2185                         4 ) * sizeof(__be32))
2186
2187 #define NFSD_MIN_RESP_HDR_SEQ_SZ ((\
2188                         2 +     /* verifier: AUTH_NULL, length 0 */\
2189                         1 +     /* status */ \
2190                         1 +     /* MIN tag is length with zero, only length */ \
2191                         3 +     /* opcount, opcode, opstatus*/ \
2192                         XDR_QUADLEN(NFS4_MAX_SESSIONID_LEN) + \
2193                                 /* seqid, slotID, slotID, slotID, status */ \
2194                         5 ) * sizeof(__be32))
2195
2196 static __be32 check_forechannel_attrs(struct nfsd4_channel_attrs *ca, struct nfsd_net *nn)
2197 {
2198         u32 maxrpc = nn->nfsd_serv->sv_max_mesg;
2199
2200         if (ca->maxreq_sz < NFSD_MIN_REQ_HDR_SEQ_SZ)
2201                 return nfserr_toosmall;
2202         if (ca->maxresp_sz < NFSD_MIN_RESP_HDR_SEQ_SZ)
2203                 return nfserr_toosmall;
2204         ca->headerpadsz = 0;
2205         ca->maxreq_sz = min_t(u32, ca->maxreq_sz, maxrpc);
2206         ca->maxresp_sz = min_t(u32, ca->maxresp_sz, maxrpc);
2207         ca->maxops = min_t(u32, ca->maxops, NFSD_MAX_OPS_PER_COMPOUND);
2208         ca->maxresp_cached = min_t(u32, ca->maxresp_cached,
2209                         NFSD_SLOT_CACHE_SIZE + NFSD_MIN_HDR_SEQ_SZ);
2210         ca->maxreqs = min_t(u32, ca->maxreqs, NFSD_MAX_SLOTS_PER_SESSION);
2211         /*
2212          * Note decreasing slot size below client's request may make it
2213          * difficult for client to function correctly, whereas
2214          * decreasing the number of slots will (just?) affect
2215          * performance.  When short on memory we therefore prefer to
2216          * decrease number of slots instead of their size.  Clients that
2217          * request larger slots than they need will get poor results:
2218          */
2219         ca->maxreqs = nfsd4_get_drc_mem(ca);
2220         if (!ca->maxreqs)
2221                 return nfserr_jukebox;
2222
2223         return nfs_ok;
2224 }
2225
2226 #define NFSD_CB_MAX_REQ_SZ      ((NFS4_enc_cb_recall_sz + \
2227                                  RPC_MAX_HEADER_WITH_AUTH) * sizeof(__be32))
2228 #define NFSD_CB_MAX_RESP_SZ     ((NFS4_dec_cb_recall_sz + \
2229                                  RPC_MAX_REPHEADER_WITH_AUTH) * sizeof(__be32))
2230
2231 static __be32 check_backchannel_attrs(struct nfsd4_channel_attrs *ca)
2232 {
2233         ca->headerpadsz = 0;
2234
2235         /*
2236          * These RPC_MAX_HEADER macros are overkill, especially since we
2237          * don't even do gss on the backchannel yet.  But this is still
2238          * less than 1k.  Tighten up this estimate in the unlikely event
2239          * it turns out to be a problem for some client:
2240          */
2241         if (ca->maxreq_sz < NFSD_CB_MAX_REQ_SZ)
2242                 return nfserr_toosmall;
2243         if (ca->maxresp_sz < NFSD_CB_MAX_RESP_SZ)
2244                 return nfserr_toosmall;
2245         ca->maxresp_cached = 0;
2246         if (ca->maxops < 2)
2247                 return nfserr_toosmall;
2248
2249         return nfs_ok;
2250 }
2251
2252 static __be32 nfsd4_check_cb_sec(struct nfsd4_cb_sec *cbs)
2253 {
2254         switch (cbs->flavor) {
2255         case RPC_AUTH_NULL:
2256         case RPC_AUTH_UNIX:
2257                 return nfs_ok;
2258         default:
2259                 /*
2260                  * GSS case: the spec doesn't allow us to return this
2261                  * error.  But it also doesn't allow us not to support
2262                  * GSS.
2263                  * I'd rather this fail hard than return some error the
2264                  * client might think it can already handle:
2265                  */
2266                 return nfserr_encr_alg_unsupp;
2267         }
2268 }
2269
2270 __be32
2271 nfsd4_create_session(struct svc_rqst *rqstp,
2272                      struct nfsd4_compound_state *cstate,
2273                      struct nfsd4_create_session *cr_ses)
2274 {
2275         struct sockaddr *sa = svc_addr(rqstp);
2276         struct nfs4_client *conf, *unconf;
2277         struct nfsd4_session *new;
2278         struct nfsd4_conn *conn;
2279         struct nfsd4_clid_slot *cs_slot = NULL;
2280         __be32 status = 0;
2281         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
2282
2283         if (cr_ses->flags & ~SESSION4_FLAG_MASK_A)
2284                 return nfserr_inval;
2285         status = nfsd4_check_cb_sec(&cr_ses->cb_sec);
2286         if (status)
2287                 return status;
2288         status = check_forechannel_attrs(&cr_ses->fore_channel, nn);
2289         if (status)
2290                 return status;
2291         status = check_backchannel_attrs(&cr_ses->back_channel);
2292         if (status)
2293                 goto out_release_drc_mem;
2294         status = nfserr_jukebox;
2295         new = alloc_session(&cr_ses->fore_channel, &cr_ses->back_channel);
2296         if (!new)
2297                 goto out_release_drc_mem;
2298         conn = alloc_conn_from_crses(rqstp, cr_ses);
2299         if (!conn)
2300                 goto out_free_session;
2301
2302         nfs4_lock_state();
2303         unconf = find_unconfirmed_client(&cr_ses->clientid, true, nn);
2304         conf = find_confirmed_client(&cr_ses->clientid, true, nn);
2305         WARN_ON_ONCE(conf && unconf);
2306
2307         if (conf) {
2308                 status = nfserr_wrong_cred;
2309                 if (!mach_creds_match(conf, rqstp))
2310                         goto out_free_conn;
2311                 cs_slot = &conf->cl_cs_slot;
2312                 status = check_slot_seqid(cr_ses->seqid, cs_slot->sl_seqid, 0);
2313                 if (status == nfserr_replay_cache) {
2314                         status = nfsd4_replay_create_session(cr_ses, cs_slot);
2315                         goto out_free_conn;
2316                 } else if (cr_ses->seqid != cs_slot->sl_seqid + 1) {
2317                         status = nfserr_seq_misordered;
2318                         goto out_free_conn;
2319                 }
2320         } else if (unconf) {
2321                 struct nfs4_client *old;
2322                 if (!same_creds(&unconf->cl_cred, &rqstp->rq_cred) ||
2323                     !rpc_cmp_addr(sa, (struct sockaddr *) &unconf->cl_addr)) {
2324                         status = nfserr_clid_inuse;
2325                         goto out_free_conn;
2326                 }
2327                 status = nfserr_wrong_cred;
2328                 if (!mach_creds_match(unconf, rqstp))
2329                         goto out_free_conn;
2330                 cs_slot = &unconf->cl_cs_slot;
2331                 status = check_slot_seqid(cr_ses->seqid, cs_slot->sl_seqid, 0);
2332                 if (status) {
2333                         /* an unconfirmed replay returns misordered */
2334                         status = nfserr_seq_misordered;
2335                         goto out_free_conn;
2336                 }
2337                 old = find_confirmed_client_by_name(&unconf->cl_name, nn);
2338                 if (old) {
2339                         status = mark_client_expired(old);
2340                         if (status)
2341                                 goto out_free_conn;
2342                         expire_client(old);
2343                 }
2344                 move_to_confirmed(unconf);
2345                 conf = unconf;
2346         } else {
2347                 status = nfserr_stale_clientid;
2348                 goto out_free_conn;
2349         }
2350         status = nfs_ok;
2351         /*
2352          * We do not support RDMA or persistent sessions
2353          */
2354         cr_ses->flags &= ~SESSION4_PERSIST;
2355         cr_ses->flags &= ~SESSION4_RDMA;
2356
2357         init_session(rqstp, new, conf, cr_ses);
2358         nfsd4_init_conn(rqstp, conn, new);
2359
2360         memcpy(cr_ses->sessionid.data, new->se_sessionid.data,
2361                NFS4_MAX_SESSIONID_LEN);
2362         cs_slot->sl_seqid++;
2363         cr_ses->seqid = cs_slot->sl_seqid;
2364
2365         /* cache solo and embedded create sessions under the state lock */
2366         nfsd4_cache_create_session(cr_ses, cs_slot, status);
2367         nfs4_unlock_state();
2368         return status;
2369 out_free_conn:
2370         nfs4_unlock_state();
2371         free_conn(conn);
2372 out_free_session:
2373         __free_session(new);
2374 out_release_drc_mem:
2375         nfsd4_put_drc_mem(&cr_ses->fore_channel);
2376         return status;
2377 }
2378
2379 static __be32 nfsd4_map_bcts_dir(u32 *dir)
2380 {
2381         switch (*dir) {
2382         case NFS4_CDFC4_FORE:
2383         case NFS4_CDFC4_BACK:
2384                 return nfs_ok;
2385         case NFS4_CDFC4_FORE_OR_BOTH:
2386         case NFS4_CDFC4_BACK_OR_BOTH:
2387                 *dir = NFS4_CDFC4_BOTH;
2388                 return nfs_ok;
2389         };
2390         return nfserr_inval;
2391 }
2392
2393 __be32 nfsd4_backchannel_ctl(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_backchannel_ctl *bc)
2394 {
2395         struct nfsd4_session *session = cstate->session;
2396         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
2397         __be32 status;
2398
2399         status = nfsd4_check_cb_sec(&bc->bc_cb_sec);
2400         if (status)
2401                 return status;
2402         spin_lock(&nn->client_lock);
2403         session->se_cb_prog = bc->bc_cb_program;
2404         session->se_cb_sec = bc->bc_cb_sec;
2405         spin_unlock(&nn->client_lock);
2406
2407         nfsd4_probe_callback(session->se_client);
2408
2409         return nfs_ok;
2410 }
2411
2412 __be32 nfsd4_bind_conn_to_session(struct svc_rqst *rqstp,
2413                      struct nfsd4_compound_state *cstate,
2414                      struct nfsd4_bind_conn_to_session *bcts)
2415 {
2416         __be32 status;
2417         struct nfsd4_conn *conn;
2418         struct nfsd4_session *session;
2419         struct net *net = SVC_NET(rqstp);
2420         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
2421
2422         if (!nfsd4_last_compound_op(rqstp))
2423                 return nfserr_not_only_op;
2424         nfs4_lock_state();
2425         spin_lock(&nn->client_lock);
2426         session = find_in_sessionid_hashtbl(&bcts->sessionid, net, &status);
2427         spin_unlock(&nn->client_lock);
2428         if (!session)
2429                 goto out_no_session;
2430         status = nfserr_wrong_cred;
2431         if (!mach_creds_match(session->se_client, rqstp))
2432                 goto out;
2433         status = nfsd4_map_bcts_dir(&bcts->dir);
2434         if (status)
2435                 goto out;
2436         conn = alloc_conn(rqstp, bcts->dir);
2437         status = nfserr_jukebox;
2438         if (!conn)
2439                 goto out;
2440         nfsd4_init_conn(rqstp, conn, session);
2441         status = nfs_ok;
2442 out:
2443         nfsd4_put_session(session);
2444 out_no_session:
2445         nfs4_unlock_state();
2446         return status;
2447 }
2448
2449 static bool nfsd4_compound_in_session(struct nfsd4_session *session, struct nfs4_sessionid *sid)
2450 {
2451         if (!session)
2452                 return 0;
2453         return !memcmp(sid, &session->se_sessionid, sizeof(*sid));
2454 }
2455
2456 __be32
2457 nfsd4_destroy_session(struct svc_rqst *r,
2458                       struct nfsd4_compound_state *cstate,
2459                       struct nfsd4_destroy_session *sessionid)
2460 {
2461         struct nfsd4_session *ses;
2462         __be32 status;
2463         int ref_held_by_me = 0;
2464         struct net *net = SVC_NET(r);
2465         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
2466
2467         nfs4_lock_state();
2468         status = nfserr_not_only_op;
2469         if (nfsd4_compound_in_session(cstate->session, &sessionid->sessionid)) {
2470                 if (!nfsd4_last_compound_op(r))
2471                         goto out;
2472                 ref_held_by_me++;
2473         }
2474         dump_sessionid(__func__, &sessionid->sessionid);
2475         spin_lock(&nn->client_lock);
2476         ses = find_in_sessionid_hashtbl(&sessionid->sessionid, net, &status);
2477         if (!ses)
2478                 goto out_client_lock;
2479         status = nfserr_wrong_cred;
2480         if (!mach_creds_match(ses->se_client, r))
2481                 goto out_put_session;
2482         status = mark_session_dead_locked(ses, 1 + ref_held_by_me);
2483         if (status)
2484                 goto out_put_session;
2485         unhash_session(ses);
2486         spin_unlock(&nn->client_lock);
2487
2488         nfsd4_probe_callback_sync(ses->se_client);
2489
2490         spin_lock(&nn->client_lock);
2491         status = nfs_ok;
2492 out_put_session:
2493         nfsd4_put_session_locked(ses);
2494 out_client_lock:
2495         spin_unlock(&nn->client_lock);
2496 out:
2497         nfs4_unlock_state();
2498         return status;
2499 }
2500
2501 static struct nfsd4_conn *__nfsd4_find_conn(struct svc_xprt *xpt, struct nfsd4_session *s)
2502 {
2503         struct nfsd4_conn *c;
2504
2505         list_for_each_entry(c, &s->se_conns, cn_persession) {
2506                 if (c->cn_xprt == xpt) {
2507                         return c;
2508                 }
2509         }
2510         return NULL;
2511 }
2512
2513 static __be32 nfsd4_sequence_check_conn(struct nfsd4_conn *new, struct nfsd4_session *ses)
2514 {
2515         struct nfs4_client *clp = ses->se_client;
2516         struct nfsd4_conn *c;
2517         __be32 status = nfs_ok;
2518         int ret;
2519
2520         spin_lock(&clp->cl_lock);
2521         c = __nfsd4_find_conn(new->cn_xprt, ses);
2522         if (c)
2523                 goto out_free;
2524         status = nfserr_conn_not_bound_to_session;
2525         if (clp->cl_mach_cred)
2526                 goto out_free;
2527         __nfsd4_hash_conn(new, ses);
2528         spin_unlock(&clp->cl_lock);
2529         ret = nfsd4_register_conn(new);
2530         if (ret)
2531                 /* oops; xprt is already down: */
2532                 nfsd4_conn_lost(&new->cn_xpt_user);
2533         return nfs_ok;
2534 out_free:
2535         spin_unlock(&clp->cl_lock);
2536         free_conn(new);
2537         return status;
2538 }
2539
2540 static bool nfsd4_session_too_many_ops(struct svc_rqst *rqstp, struct nfsd4_session *session)
2541 {
2542         struct nfsd4_compoundargs *args = rqstp->rq_argp;
2543
2544         return args->opcnt > session->se_fchannel.maxops;
2545 }
2546
2547 static bool nfsd4_request_too_big(struct svc_rqst *rqstp,
2548                                   struct nfsd4_session *session)
2549 {
2550         struct xdr_buf *xb = &rqstp->rq_arg;
2551
2552         return xb->len > session->se_fchannel.maxreq_sz;
2553 }
2554
2555 __be32
2556 nfsd4_sequence(struct svc_rqst *rqstp,
2557                struct nfsd4_compound_state *cstate,
2558                struct nfsd4_sequence *seq)
2559 {
2560         struct nfsd4_compoundres *resp = rqstp->rq_resp;
2561         struct xdr_stream *xdr = &resp->xdr;
2562         struct nfsd4_session *session;
2563         struct nfs4_client *clp;
2564         struct nfsd4_slot *slot;
2565         struct nfsd4_conn *conn;
2566         __be32 status;
2567         int buflen;
2568         struct net *net = SVC_NET(rqstp);
2569         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
2570
2571         if (resp->opcnt != 1)
2572                 return nfserr_sequence_pos;
2573
2574         /*
2575          * Will be either used or freed by nfsd4_sequence_check_conn
2576          * below.
2577          */
2578         conn = alloc_conn(rqstp, NFS4_CDFC4_FORE);
2579         if (!conn)
2580                 return nfserr_jukebox;
2581
2582         spin_lock(&nn->client_lock);
2583         session = find_in_sessionid_hashtbl(&seq->sessionid, net, &status);
2584         if (!session)
2585                 goto out_no_session;
2586         clp = session->se_client;
2587
2588         status = nfserr_too_many_ops;
2589         if (nfsd4_session_too_many_ops(rqstp, session))
2590                 goto out_put_session;
2591
2592         status = nfserr_req_too_big;
2593         if (nfsd4_request_too_big(rqstp, session))
2594                 goto out_put_session;
2595
2596         status = nfserr_badslot;
2597         if (seq->slotid >= session->se_fchannel.maxreqs)
2598                 goto out_put_session;
2599
2600         slot = session->se_slots[seq->slotid];
2601         dprintk("%s: slotid %d\n", __func__, seq->slotid);
2602
2603         /* We do not negotiate the number of slots yet, so set the
2604          * maxslots to the session maxreqs which is used to encode
2605          * sr_highest_slotid and the sr_target_slot id to maxslots */
2606         seq->maxslots = session->se_fchannel.maxreqs;
2607
2608         status = check_slot_seqid(seq->seqid, slot->sl_seqid,
2609                                         slot->sl_flags & NFSD4_SLOT_INUSE);
2610         if (status == nfserr_replay_cache) {
2611                 status = nfserr_seq_misordered;
2612                 if (!(slot->sl_flags & NFSD4_SLOT_INITIALIZED))
2613                         goto out_put_session;
2614                 cstate->slot = slot;
2615                 cstate->session = session;
2616                 cstate->clp = clp;
2617                 /* Return the cached reply status and set cstate->status
2618                  * for nfsd4_proc_compound processing */
2619                 status = nfsd4_replay_cache_entry(resp, seq);
2620                 cstate->status = nfserr_replay_cache;
2621                 goto out;
2622         }
2623         if (status)
2624                 goto out_put_session;
2625
2626         status = nfsd4_sequence_check_conn(conn, session);
2627         conn = NULL;
2628         if (status)
2629                 goto out_put_session;
2630
2631         buflen = (seq->cachethis) ?
2632                         session->se_fchannel.maxresp_cached :
2633                         session->se_fchannel.maxresp_sz;
2634         status = (seq->cachethis) ? nfserr_rep_too_big_to_cache :
2635                                     nfserr_rep_too_big;
2636         if (xdr_restrict_buflen(xdr, buflen - rqstp->rq_auth_slack))
2637                 goto out_put_session;
2638         svc_reserve(rqstp, buflen);
2639
2640         status = nfs_ok;
2641         /* Success! bump slot seqid */
2642         slot->sl_seqid = seq->seqid;
2643         slot->sl_flags |= NFSD4_SLOT_INUSE;
2644         if (seq->cachethis)
2645                 slot->sl_flags |= NFSD4_SLOT_CACHETHIS;
2646         else
2647                 slot->sl_flags &= ~NFSD4_SLOT_CACHETHIS;
2648
2649         cstate->slot = slot;
2650         cstate->session = session;
2651         cstate->clp = clp;
2652
2653 out:
2654         switch (clp->cl_cb_state) {
2655         case NFSD4_CB_DOWN:
2656                 seq->status_flags = SEQ4_STATUS_CB_PATH_DOWN;
2657                 break;
2658         case NFSD4_CB_FAULT:
2659                 seq->status_flags = SEQ4_STATUS_BACKCHANNEL_FAULT;
2660                 break;
2661         default:
2662                 seq->status_flags = 0;
2663         }
2664         if (!list_empty(&clp->cl_revoked))
2665                 seq->status_flags |= SEQ4_STATUS_RECALLABLE_STATE_REVOKED;
2666 out_no_session:
2667         if (conn)
2668                 free_conn(conn);
2669         spin_unlock(&nn->client_lock);
2670         return status;
2671 out_put_session:
2672         nfsd4_put_session_locked(session);
2673         goto out_no_session;
2674 }
2675
2676 void
2677 nfsd4_sequence_done(struct nfsd4_compoundres *resp)
2678 {
2679         struct nfsd4_compound_state *cs = &resp->cstate;
2680
2681         if (nfsd4_has_session(cs)) {
2682                 if (cs->status != nfserr_replay_cache) {
2683                         nfsd4_store_cache_entry(resp);
2684                         cs->slot->sl_flags &= ~NFSD4_SLOT_INUSE;
2685                 }
2686                 /* Drop session reference that was taken in nfsd4_sequence() */
2687                 nfsd4_put_session(cs->session);
2688         } else if (cs->clp)
2689                 put_client_renew(cs->clp);
2690 }
2691
2692 __be32
2693 nfsd4_destroy_clientid(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_destroy_clientid *dc)
2694 {
2695         struct nfs4_client *conf, *unconf, *clp;
2696         __be32 status = 0;
2697         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
2698
2699         nfs4_lock_state();
2700         unconf = find_unconfirmed_client(&dc->clientid, true, nn);
2701         conf = find_confirmed_client(&dc->clientid, true, nn);
2702         WARN_ON_ONCE(conf && unconf);
2703
2704         if (conf) {
2705                 clp = conf;
2706
2707                 if (client_has_state(conf)) {
2708                         status = nfserr_clientid_busy;
2709                         goto out;
2710                 }
2711         } else if (unconf)
2712                 clp = unconf;
2713         else {
2714                 status = nfserr_stale_clientid;
2715                 goto out;
2716         }
2717         if (!mach_creds_match(clp, rqstp)) {
2718                 status = nfserr_wrong_cred;
2719                 goto out;
2720         }
2721         expire_client(clp);
2722 out:
2723         nfs4_unlock_state();
2724         return status;
2725 }
2726
2727 __be32
2728 nfsd4_reclaim_complete(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_reclaim_complete *rc)
2729 {
2730         __be32 status = 0;
2731
2732         if (rc->rca_one_fs) {
2733                 if (!cstate->current_fh.fh_dentry)
2734                         return nfserr_nofilehandle;
2735                 /*
2736                  * We don't take advantage of the rca_one_fs case.
2737                  * That's OK, it's optional, we can safely ignore it.
2738                  */
2739                  return nfs_ok;
2740         }
2741
2742         nfs4_lock_state();
2743         status = nfserr_complete_already;
2744         if (test_and_set_bit(NFSD4_CLIENT_RECLAIM_COMPLETE,
2745                              &cstate->session->se_client->cl_flags))
2746                 goto out;
2747
2748         status = nfserr_stale_clientid;
2749         if (is_client_expired(cstate->session->se_client))
2750                 /*
2751                  * The following error isn't really legal.
2752                  * But we only get here if the client just explicitly
2753                  * destroyed the client.  Surely it no longer cares what
2754                  * error it gets back on an operation for the dead
2755                  * client.
2756                  */
2757                 goto out;
2758
2759         status = nfs_ok;
2760         nfsd4_client_record_create(cstate->session->se_client);
2761 out:
2762         nfs4_unlock_state();
2763         return status;
2764 }
2765
2766 __be32
2767 nfsd4_setclientid(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
2768                   struct nfsd4_setclientid *setclid)
2769 {
2770         struct xdr_netobj       clname = setclid->se_name;
2771         nfs4_verifier           clverifier = setclid->se_verf;
2772         struct nfs4_client      *conf, *unconf, *new;
2773         __be32                  status;
2774         struct nfsd_net         *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
2775
2776         /* Cases below refer to rfc 3530 section 14.2.33: */
2777         nfs4_lock_state();
2778         conf = find_confirmed_client_by_name(&clname, nn);
2779         if (conf) {
2780                 /* case 0: */
2781                 status = nfserr_clid_inuse;
2782                 if (clp_used_exchangeid(conf))
2783                         goto out;
2784                 if (!same_creds(&conf->cl_cred, &rqstp->rq_cred)) {
2785                         char addr_str[INET6_ADDRSTRLEN];
2786                         rpc_ntop((struct sockaddr *) &conf->cl_addr, addr_str,
2787                                  sizeof(addr_str));
2788                         dprintk("NFSD: setclientid: string in use by client "
2789                                 "at %s\n", addr_str);
2790                         goto out;
2791                 }
2792         }
2793         unconf = find_unconfirmed_client_by_name(&clname, nn);
2794         if (unconf)
2795                 expire_client(unconf);
2796         status = nfserr_jukebox;
2797         new = create_client(clname, rqstp, &clverifier);
2798         if (new == NULL)
2799                 goto out;
2800         if (conf && same_verf(&conf->cl_verifier, &clverifier))
2801                 /* case 1: probable callback update */
2802                 copy_clid(new, conf);
2803         else /* case 4 (new client) or cases 2, 3 (client reboot): */
2804                 gen_clid(new, nn);
2805         new->cl_minorversion = 0;
2806         gen_callback(new, setclid, rqstp);
2807         add_to_unconfirmed(new);
2808         setclid->se_clientid.cl_boot = new->cl_clientid.cl_boot;
2809         setclid->se_clientid.cl_id = new->cl_clientid.cl_id;
2810         memcpy(setclid->se_confirm.data, new->cl_confirm.data, sizeof(setclid->se_confirm.data));
2811         status = nfs_ok;
2812 out:
2813         nfs4_unlock_state();
2814         return status;
2815 }
2816
2817
2818 __be32
2819 nfsd4_setclientid_confirm(struct svc_rqst *rqstp,
2820                          struct nfsd4_compound_state *cstate,
2821                          struct nfsd4_setclientid_confirm *setclientid_confirm)
2822 {
2823         struct nfs4_client *conf, *unconf;
2824         nfs4_verifier confirm = setclientid_confirm->sc_confirm; 
2825         clientid_t * clid = &setclientid_confirm->sc_clientid;
2826         __be32 status;
2827         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
2828
2829         if (STALE_CLIENTID(clid, nn))
2830                 return nfserr_stale_clientid;
2831         nfs4_lock_state();
2832
2833         conf = find_confirmed_client(clid, false, nn);
2834         unconf = find_unconfirmed_client(clid, false, nn);
2835         /*
2836          * We try hard to give out unique clientid's, so if we get an
2837          * attempt to confirm the same clientid with a different cred,
2838          * there's a bug somewhere.  Let's charitably assume it's our
2839          * bug.
2840          */
2841         status = nfserr_serverfault;
2842         if (unconf && !same_creds(&unconf->cl_cred, &rqstp->rq_cred))
2843                 goto out;
2844         if (conf && !same_creds(&conf->cl_cred, &rqstp->rq_cred))
2845                 goto out;
2846         /* cases below refer to rfc 3530 section 14.2.34: */
2847         if (!unconf || !same_verf(&confirm, &unconf->cl_confirm)) {
2848                 if (conf && !unconf) /* case 2: probable retransmit */
2849                         status = nfs_ok;
2850                 else /* case 4: client hasn't noticed we rebooted yet? */
2851                         status = nfserr_stale_clientid;
2852                 goto out;
2853         }
2854         status = nfs_ok;
2855         if (conf) { /* case 1: callback update */
2856                 nfsd4_change_callback(conf, &unconf->cl_cb_conn);
2857                 nfsd4_probe_callback(conf);
2858                 expire_client(unconf);
2859         } else { /* case 3: normal case; new or rebooted client */
2860                 conf = find_confirmed_client_by_name(&unconf->cl_name, nn);
2861                 if (conf) {
2862                         status = mark_client_expired(conf);
2863                         if (status)
2864                                 goto out;
2865                         expire_client(conf);
2866                 }
2867                 move_to_confirmed(unconf);
2868                 nfsd4_probe_callback(unconf);
2869         }
2870 out:
2871         nfs4_unlock_state();
2872         return status;
2873 }
2874
2875 static struct nfs4_file *nfsd4_alloc_file(void)
2876 {
2877         return kmem_cache_alloc(file_slab, GFP_KERNEL);
2878 }
2879
2880 /* OPEN Share state helper functions */
2881 static void nfsd4_init_file(struct nfs4_file *fp, struct knfsd_fh *fh)
2882 {
2883         unsigned int hashval = file_hashval(fh);
2884
2885         lockdep_assert_held(&state_lock);
2886
2887         atomic_set(&fp->fi_ref, 1);
2888         spin_lock_init(&fp->fi_lock);
2889         INIT_LIST_HEAD(&fp->fi_stateids);
2890         INIT_LIST_HEAD(&fp->fi_delegations);
2891         fh_copy_shallow(&fp->fi_fhandle, fh);
2892         fp->fi_had_conflict = false;
2893         fp->fi_lease = NULL;
2894         fp->fi_share_deny = 0;
2895         memset(fp->fi_fds, 0, sizeof(fp->fi_fds));
2896         memset(fp->fi_access, 0, sizeof(fp->fi_access));
2897         hlist_add_head(&fp->fi_hash, &file_hashtbl[hashval]);
2898 }
2899
2900 void
2901 nfsd4_free_slabs(void)
2902 {
2903         kmem_cache_destroy(openowner_slab);
2904         kmem_cache_destroy(lockowner_slab);
2905         kmem_cache_destroy(file_slab);
2906         kmem_cache_destroy(stateid_slab);
2907         kmem_cache_destroy(deleg_slab);
2908 }
2909
2910 int
2911 nfsd4_init_slabs(void)
2912 {
2913         openowner_slab = kmem_cache_create("nfsd4_openowners",
2914                         sizeof(struct nfs4_openowner), 0, 0, NULL);
2915         if (openowner_slab == NULL)
2916                 goto out;
2917         lockowner_slab = kmem_cache_create("nfsd4_lockowners",
2918                         sizeof(struct nfs4_lockowner), 0, 0, NULL);
2919         if (lockowner_slab == NULL)
2920                 goto out_free_openowner_slab;
2921         file_slab = kmem_cache_create("nfsd4_files",
2922                         sizeof(struct nfs4_file), 0, 0, NULL);
2923         if (file_slab == NULL)
2924                 goto out_free_lockowner_slab;
2925         stateid_slab = kmem_cache_create("nfsd4_stateids",
2926                         sizeof(struct nfs4_ol_stateid), 0, 0, NULL);
2927         if (stateid_slab == NULL)
2928                 goto out_free_file_slab;
2929         deleg_slab = kmem_cache_create("nfsd4_delegations",
2930                         sizeof(struct nfs4_delegation), 0, 0, NULL);
2931         if (deleg_slab == NULL)
2932                 goto out_free_stateid_slab;
2933         return 0;
2934
2935 out_free_stateid_slab:
2936         kmem_cache_destroy(stateid_slab);
2937 out_free_file_slab:
2938         kmem_cache_destroy(file_slab);
2939 out_free_lockowner_slab:
2940         kmem_cache_destroy(lockowner_slab);
2941 out_free_openowner_slab:
2942         kmem_cache_destroy(openowner_slab);
2943 out:
2944         dprintk("nfsd4: out of memory while initializing nfsv4\n");
2945         return -ENOMEM;
2946 }
2947
2948 static void init_nfs4_replay(struct nfs4_replay *rp)
2949 {
2950         rp->rp_status = nfserr_serverfault;
2951         rp->rp_buflen = 0;
2952         rp->rp_buf = rp->rp_ibuf;
2953 }
2954
2955 static inline void *alloc_stateowner(struct kmem_cache *slab, struct xdr_netobj *owner, struct nfs4_client *clp)
2956 {
2957         struct nfs4_stateowner *sop;
2958
2959         sop = kmem_cache_alloc(slab, GFP_KERNEL);
2960         if (!sop)
2961                 return NULL;
2962
2963         sop->so_owner.data = kmemdup(owner->data, owner->len, GFP_KERNEL);
2964         if (!sop->so_owner.data) {
2965                 kmem_cache_free(slab, sop);
2966                 return NULL;
2967         }
2968         sop->so_owner.len = owner->len;
2969
2970         INIT_LIST_HEAD(&sop->so_stateids);
2971         sop->so_client = clp;
2972         init_nfs4_replay(&sop->so_replay);
2973         return sop;
2974 }
2975
2976 static void hash_openowner(struct nfs4_openowner *oo, struct nfs4_client *clp, unsigned int strhashval)
2977 {
2978         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
2979
2980         list_add(&oo->oo_owner.so_strhash, &nn->ownerstr_hashtbl[strhashval]);
2981         list_add(&oo->oo_perclient, &clp->cl_openowners);
2982 }
2983
2984 static struct nfs4_openowner *
2985 alloc_init_open_stateowner(unsigned int strhashval, struct nfsd4_open *open,
2986                            struct nfsd4_compound_state *cstate)
2987 {
2988         struct nfs4_client *clp = cstate->clp;
2989         struct nfs4_openowner *oo;
2990
2991         oo = alloc_stateowner(openowner_slab, &open->op_owner, clp);
2992         if (!oo)
2993                 return NULL;
2994         oo->oo_owner.so_is_open_owner = 1;
2995         oo->oo_owner.so_seqid = open->op_seqid;
2996         oo->oo_flags = NFS4_OO_NEW;
2997         if (nfsd4_has_session(cstate))
2998                 oo->oo_flags |= NFS4_OO_CONFIRMED;
2999         oo->oo_time = 0;
3000         oo->oo_last_closed_stid = NULL;
3001         INIT_LIST_HEAD(&oo->oo_close_lru);
3002         hash_openowner(oo, clp, strhashval);
3003         return oo;
3004 }
3005
3006 static void init_open_stateid(struct nfs4_ol_stateid *stp, struct nfs4_file *fp, struct nfsd4_open *open) {
3007         struct nfs4_openowner *oo = open->op_openowner;
3008
3009         stp->st_stid.sc_type = NFS4_OPEN_STID;
3010         INIT_LIST_HEAD(&stp->st_locks);
3011         stp->st_stateowner = &oo->oo_owner;
3012         get_nfs4_file(fp);
3013         stp->st_stid.sc_file = fp;
3014         stp->st_access_bmap = 0;
3015         stp->st_deny_bmap = 0;
3016         stp->st_openstp = NULL;
3017         spin_lock(&oo->oo_owner.so_client->cl_lock);
3018         list_add(&stp->st_perstateowner, &oo->oo_owner.so_stateids);
3019         spin_lock(&fp->fi_lock);
3020         list_add(&stp->st_perfile, &fp->fi_stateids);
3021         spin_unlock(&fp->fi_lock);
3022         spin_unlock(&oo->oo_owner.so_client->cl_lock);
3023 }
3024
3025 static void
3026 move_to_close_lru(struct nfs4_openowner *oo, struct net *net)
3027 {
3028         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
3029
3030         dprintk("NFSD: move_to_close_lru nfs4_openowner %p\n", oo);
3031
3032         list_move_tail(&oo->oo_close_lru, &nn->close_lru);
3033         oo->oo_time = get_seconds();
3034 }
3035
3036 static int
3037 same_owner_str(struct nfs4_stateowner *sop, struct xdr_netobj *owner,
3038                                                         clientid_t *clid)
3039 {
3040         return (sop->so_owner.len == owner->len) &&
3041                 0 == memcmp(sop->so_owner.data, owner->data, owner->len) &&
3042                 (sop->so_client->cl_clientid.cl_id == clid->cl_id);
3043 }
3044
3045 static struct nfs4_openowner *
3046 find_openstateowner_str(unsigned int hashval, struct nfsd4_open *open,
3047                         bool sessions, struct nfsd_net *nn)
3048 {
3049         struct nfs4_stateowner *so;
3050         struct nfs4_openowner *oo;
3051         struct nfs4_client *clp;
3052
3053         list_for_each_entry(so, &nn->ownerstr_hashtbl[hashval], so_strhash) {
3054                 if (!so->so_is_open_owner)
3055                         continue;
3056                 if (same_owner_str(so, &open->op_owner, &open->op_clientid)) {
3057                         oo = openowner(so);
3058                         clp = oo->oo_owner.so_client;
3059                         if ((bool)clp->cl_minorversion != sessions)
3060                                 return NULL;
3061                         renew_client(oo->oo_owner.so_client);
3062                         return oo;
3063                 }
3064         }
3065         return NULL;
3066 }
3067
3068 /* search file_hashtbl[] for file */
3069 static struct nfs4_file *
3070 find_file_locked(struct knfsd_fh *fh)
3071 {
3072         unsigned int hashval = file_hashval(fh);
3073         struct nfs4_file *fp;
3074
3075         lockdep_assert_held(&state_lock);
3076
3077         hlist_for_each_entry(fp, &file_hashtbl[hashval], fi_hash) {
3078                 if (nfsd_fh_match(&fp->fi_fhandle, fh)) {
3079                         get_nfs4_file(fp);
3080                         return fp;
3081                 }
3082         }
3083         return NULL;
3084 }
3085
3086 static struct nfs4_file *
3087 find_file(struct knfsd_fh *fh)
3088 {
3089         struct nfs4_file *fp;
3090
3091         spin_lock(&state_lock);
3092         fp = find_file_locked(fh);
3093         spin_unlock(&state_lock);
3094         return fp;
3095 }
3096
3097 static struct nfs4_file *
3098 find_or_add_file(struct nfs4_file *new, struct knfsd_fh *fh)
3099 {
3100         struct nfs4_file *fp;
3101
3102         spin_lock(&state_lock);
3103         fp = find_file_locked(fh);
3104         if (fp == NULL) {
3105                 nfsd4_init_file(new, fh);
3106                 fp = new;
3107         }
3108         spin_unlock(&state_lock);
3109
3110         return fp;
3111 }
3112
3113 /*
3114  * Called to check deny when READ with all zero stateid or
3115  * WRITE with all zero or all one stateid
3116  */
3117 static __be32
3118 nfs4_share_conflict(struct svc_fh *current_fh, unsigned int deny_type)
3119 {
3120         struct nfs4_file *fp;
3121         __be32 ret = nfs_ok;
3122
3123         fp = find_file(&current_fh->fh_handle);
3124         if (!fp)
3125                 return ret;
3126         /* Check for conflicting share reservations */
3127         spin_lock(&fp->fi_lock);
3128         if (fp->fi_share_deny & deny_type)
3129                 ret = nfserr_locked;
3130         spin_unlock(&fp->fi_lock);
3131         put_nfs4_file(fp);
3132         return ret;
3133 }
3134
3135 void nfsd4_prepare_cb_recall(struct nfs4_delegation *dp)
3136 {
3137         struct nfsd_net *nn = net_generic(dp->dl_stid.sc_client->net,
3138                                           nfsd_net_id);
3139
3140         block_delegations(&dp->dl_stid.sc_file->fi_fhandle);
3141
3142         /*
3143          * We can't do this in nfsd_break_deleg_cb because it is
3144          * already holding inode->i_lock.
3145          *
3146          * If the dl_time != 0, then we know that it has already been
3147          * queued for a lease break. Don't queue it again.
3148          */
3149         spin_lock(&state_lock);
3150         if (dp->dl_time == 0) {
3151                 dp->dl_time = get_seconds();
3152                 list_add_tail(&dp->dl_recall_lru, &nn->del_recall_lru);
3153         }
3154         spin_unlock(&state_lock);
3155 }
3156
3157 static void nfsd_break_one_deleg(struct nfs4_delegation *dp)
3158 {
3159         /*
3160          * We're assuming the state code never drops its reference
3161          * without first removing the lease.  Since we're in this lease
3162          * callback (and since the lease code is serialized by the kernel
3163          * lock) we know the server hasn't removed the lease yet, we know
3164          * it's safe to take a reference.
3165          */
3166         atomic_inc(&dp->dl_stid.sc_count);
3167         nfsd4_cb_recall(dp);
3168 }
3169
3170 /* Called from break_lease() with i_lock held. */
3171 static void nfsd_break_deleg_cb(struct file_lock *fl)
3172 {
3173         struct nfs4_file *fp = (struct nfs4_file *)fl->fl_owner;
3174         struct nfs4_delegation *dp;
3175
3176         if (!fp) {
3177                 WARN(1, "(%p)->fl_owner NULL\n", fl);
3178                 return;
3179         }
3180         if (fp->fi_had_conflict) {
3181                 WARN(1, "duplicate break on %p\n", fp);
3182                 return;
3183         }
3184         /*
3185          * We don't want the locks code to timeout the lease for us;
3186          * we'll remove it ourself if a delegation isn't returned
3187          * in time:
3188          */
3189         fl->fl_break_time = 0;
3190
3191         spin_lock(&fp->fi_lock);
3192         fp->fi_had_conflict = true;
3193         /*
3194          * If there are no delegations on the list, then we can't count on this
3195          * lease ever being cleaned up. Set the fl_break_time to jiffies so that
3196          * time_out_leases will do it ASAP. The fact that fi_had_conflict is now
3197          * true should keep any new delegations from being hashed.
3198          */
3199         if (list_empty(&fp->fi_delegations))
3200                 fl->fl_break_time = jiffies;
3201         else
3202                 list_for_each_entry(dp, &fp->fi_delegations, dl_perfile)
3203                         nfsd_break_one_deleg(dp);
3204         spin_unlock(&fp->fi_lock);
3205 }
3206
3207 static
3208 int nfsd_change_deleg_cb(struct file_lock **onlist, int arg)
3209 {
3210         if (arg & F_UNLCK)
3211                 return lease_modify(onlist, arg);
3212         else
3213                 return -EAGAIN;
3214 }
3215
3216 static const struct lock_manager_operations nfsd_lease_mng_ops = {
3217         .lm_break = nfsd_break_deleg_cb,
3218         .lm_change = nfsd_change_deleg_cb,
3219 };
3220
3221 static __be32 nfsd4_check_seqid(struct nfsd4_compound_state *cstate, struct nfs4_stateowner *so, u32 seqid)
3222 {
3223         if (nfsd4_has_session(cstate))
3224                 return nfs_ok;
3225         if (seqid == so->so_seqid - 1)
3226                 return nfserr_replay_me;
3227         if (seqid == so->so_seqid)
3228                 return nfs_ok;
3229         return nfserr_bad_seqid;
3230 }
3231
3232 static __be32 lookup_clientid(clientid_t *clid,
3233                 struct nfsd4_compound_state *cstate,
3234                 struct nfsd_net *nn)
3235 {
3236         struct nfs4_client *found;
3237
3238         if (cstate->clp) {
3239                 found = cstate->clp;
3240                 if (!same_clid(&found->cl_clientid, clid))
3241                         return nfserr_stale_clientid;
3242                 return nfs_ok;
3243         }
3244
3245         if (STALE_CLIENTID(clid, nn))
3246                 return nfserr_stale_clientid;
3247
3248         /*
3249          * For v4.1+ we get the client in the SEQUENCE op. If we don't have one
3250          * cached already then we know this is for is for v4.0 and "sessions"
3251          * will be false.
3252          */
3253         WARN_ON_ONCE(cstate->session);
3254         found = find_confirmed_client(clid, false, nn);
3255         if (!found)
3256                 return nfserr_expired;
3257
3258         /* Cache the nfs4_client in cstate! */
3259         cstate->clp = found;
3260         atomic_inc(&found->cl_refcount);
3261         return nfs_ok;
3262 }
3263
3264 __be32
3265 nfsd4_process_open1(struct nfsd4_compound_state *cstate,
3266                     struct nfsd4_open *open, struct nfsd_net *nn)
3267 {
3268         clientid_t *clientid = &open->op_clientid;
3269         struct nfs4_client *clp = NULL;
3270         unsigned int strhashval;
3271         struct nfs4_openowner *oo = NULL;
3272         __be32 status;
3273
3274         if (STALE_CLIENTID(&open->op_clientid, nn))
3275                 return nfserr_stale_clientid;
3276         /*
3277          * In case we need it later, after we've already created the
3278          * file and don't want to risk a further failure:
3279          */
3280         open->op_file = nfsd4_alloc_file();
3281         if (open->op_file == NULL)
3282                 return nfserr_jukebox;
3283
3284         status = lookup_clientid(clientid, cstate, nn);
3285         if (status)
3286                 return status;
3287         clp = cstate->clp;
3288
3289         strhashval = ownerstr_hashval(clientid->cl_id, &open->op_owner);
3290         oo = find_openstateowner_str(strhashval, open, cstate->minorversion, nn);
3291         open->op_openowner = oo;
3292         if (!oo) {
3293                 goto new_owner;
3294         }
3295         if (!(oo->oo_flags & NFS4_OO_CONFIRMED)) {
3296                 /* Replace unconfirmed owners without checking for replay. */
3297                 release_openowner(oo);
3298                 open->op_openowner = NULL;
3299                 goto new_owner;
3300         }
3301         status = nfsd4_check_seqid(cstate, &oo->oo_owner, open->op_seqid);
3302         if (status)
3303                 return status;
3304         goto alloc_stateid;
3305 new_owner:
3306         oo = alloc_init_open_stateowner(strhashval, open, cstate);
3307         if (oo == NULL)
3308                 return nfserr_jukebox;
3309         open->op_openowner = oo;
3310 alloc_stateid:
3311         open->op_stp = nfs4_alloc_open_stateid(clp);
3312         if (!open->op_stp)
3313                 return nfserr_jukebox;
3314         return nfs_ok;
3315 }
3316
3317 static inline __be32
3318 nfs4_check_delegmode(struct nfs4_delegation *dp, int flags)
3319 {
3320         if ((flags & WR_STATE) && (dp->dl_type == NFS4_OPEN_DELEGATE_READ))
3321                 return nfserr_openmode;
3322         else
3323                 return nfs_ok;
3324 }
3325
3326 static int share_access_to_flags(u32 share_access)
3327 {
3328         return share_access == NFS4_SHARE_ACCESS_READ ? RD_STATE : WR_STATE;
3329 }
3330
3331 static struct nfs4_delegation *find_deleg_stateid(struct nfs4_client *cl, stateid_t *s)
3332 {
3333         struct nfs4_stid *ret;
3334
3335         ret = find_stateid_by_type(cl, s, NFS4_DELEG_STID);
3336         if (!ret)
3337                 return NULL;
3338         return delegstateid(ret);
3339 }
3340
3341 static bool nfsd4_is_deleg_cur(struct nfsd4_open *open)
3342 {
3343         return open->op_claim_type == NFS4_OPEN_CLAIM_DELEGATE_CUR ||
3344                open->op_claim_type == NFS4_OPEN_CLAIM_DELEG_CUR_FH;
3345 }
3346
3347 static __be32
3348 nfs4_check_deleg(struct nfs4_client *cl, struct nfsd4_open *open,
3349                 struct nfs4_delegation **dp)
3350 {
3351         int flags;
3352         __be32 status = nfserr_bad_stateid;
3353
3354         *dp = find_deleg_stateid(cl, &open->op_delegate_stateid);
3355         if (*dp == NULL)
3356                 goto out;
3357         flags = share_access_to_flags(open->op_share_access);
3358         status = nfs4_check_delegmode(*dp, flags);
3359         if (status)
3360                 *dp = NULL;
3361 out:
3362         if (!nfsd4_is_deleg_cur(open))
3363                 return nfs_ok;
3364         if (status)
3365                 return status;
3366         open->op_openowner->oo_flags |= NFS4_OO_CONFIRMED;
3367         return nfs_ok;
3368 }
3369
3370 static struct nfs4_ol_stateid *
3371 nfsd4_find_existing_open(struct nfs4_file *fp, struct nfsd4_open *open)
3372 {
3373         struct nfs4_ol_stateid *local, *ret = NULL;
3374         struct nfs4_openowner *oo = open->op_openowner;
3375
3376         spin_lock(&fp->fi_lock);
3377         list_for_each_entry(local, &fp->fi_stateids, st_perfile) {
3378                 /* ignore lock owners */
3379                 if (local->st_stateowner->so_is_open_owner == 0)
3380                         continue;
3381                 if (local->st_stateowner == &oo->oo_owner) {
3382                         ret = local;
3383                         break;
3384                 }
3385         }
3386         spin_unlock(&fp->fi_lock);
3387         return ret;
3388 }
3389
3390 static inline int nfs4_access_to_access(u32 nfs4_access)
3391 {
3392         int flags = 0;
3393
3394         if (nfs4_access & NFS4_SHARE_ACCESS_READ)
3395                 flags |= NFSD_MAY_READ;
3396         if (nfs4_access & NFS4_SHARE_ACCESS_WRITE)
3397                 flags |= NFSD_MAY_WRITE;
3398         return flags;
3399 }
3400
3401 static inline __be32
3402 nfsd4_truncate(struct svc_rqst *rqstp, struct svc_fh *fh,
3403                 struct nfsd4_open *open)
3404 {
3405         struct iattr iattr = {
3406                 .ia_valid = ATTR_SIZE,
3407                 .ia_size = 0,
3408         };
3409         if (!open->op_truncate)
3410                 return 0;
3411         if (!(open->op_share_access & NFS4_SHARE_ACCESS_WRITE))
3412                 return nfserr_inval;
3413         return nfsd_setattr(rqstp, fh, &iattr, 0, (time_t)0);
3414 }
3415
3416 static __be32 nfs4_get_vfs_file(struct svc_rqst *rqstp, struct nfs4_file *fp,
3417                 struct svc_fh *cur_fh, struct nfs4_ol_stateid *stp,
3418                 struct nfsd4_open *open)
3419 {
3420         struct file *filp = NULL;
3421         __be32 status;
3422         int oflag = nfs4_access_to_omode(open->op_share_access);
3423         int access = nfs4_access_to_access(open->op_share_access);
3424         unsigned char old_access_bmap, old_deny_bmap;
3425
3426         spin_lock(&fp->fi_lock);
3427
3428         /*
3429          * Are we trying to set a deny mode that would conflict with
3430          * current access?
3431          */
3432         status = nfs4_file_check_deny(fp, open->op_share_deny);
3433         if (status != nfs_ok) {
3434                 spin_unlock(&fp->fi_lock);
3435                 goto out;
3436         }
3437
3438         /* set access to the file */
3439         status = nfs4_file_get_access(fp, open->op_share_access);
3440         if (status != nfs_ok) {
3441                 spin_unlock(&fp->fi_lock);
3442                 goto out;
3443         }
3444
3445         /* Set access bits in stateid */
3446         old_access_bmap = stp->st_access_bmap;
3447         set_access(open->op_share_access, stp);
3448
3449         /* Set new deny mask */
3450         old_deny_bmap = stp->st_deny_bmap;
3451         set_deny(open->op_share_deny, stp);
3452         fp->fi_share_deny |= (open->op_share_deny & NFS4_SHARE_DENY_BOTH);
3453
3454         if (!fp->fi_fds[oflag]) {
3455                 spin_unlock(&fp->fi_lock);
3456                 status = nfsd_open(rqstp, cur_fh, S_IFREG, access, &filp);
3457                 if (status)
3458                         goto out_put_access;
3459                 spin_lock(&fp->fi_lock);
3460                 if (!fp->fi_fds[oflag]) {
3461                         fp->fi_fds[oflag] = filp;
3462                         filp = NULL;
3463                 }
3464         }
3465         spin_unlock(&fp->fi_lock);
3466         if (filp)
3467                 fput(filp);
3468
3469         status = nfsd4_truncate(rqstp, cur_fh, open);
3470         if (status)
3471                 goto out_put_access;
3472 out:
3473         return status;
3474 out_put_access:
3475         stp->st_access_bmap = old_access_bmap;
3476         nfs4_file_put_access(fp, open->op_share_access);
3477         reset_union_bmap_deny(bmap_to_share_mode(old_deny_bmap), stp);
3478         goto out;
3479 }
3480
3481 static __be32
3482 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)
3483 {
3484         __be32 status;
3485         unsigned char old_deny_bmap;
3486
3487         if (!test_access(open->op_share_access, stp))
3488                 return nfs4_get_vfs_file(rqstp, fp, cur_fh, stp, open);
3489
3490         /* test and set deny mode */
3491         spin_lock(&fp->fi_lock);
3492         status = nfs4_file_check_deny(fp, open->op_share_deny);
3493         if (status == nfs_ok) {
3494                 old_deny_bmap = stp->st_deny_bmap;
3495                 set_deny(open->op_share_deny, stp);
3496                 fp->fi_share_deny |=
3497                                 (open->op_share_deny & NFS4_SHARE_DENY_BOTH);
3498         }
3499         spin_unlock(&fp->fi_lock);
3500
3501         if (status != nfs_ok)
3502                 return status;
3503
3504         status = nfsd4_truncate(rqstp, cur_fh, open);
3505         if (status != nfs_ok)
3506                 reset_union_bmap_deny(old_deny_bmap, stp);
3507         return status;
3508 }
3509
3510 static void
3511 nfs4_set_claim_prev(struct nfsd4_open *open, bool has_session)
3512 {
3513         open->op_openowner->oo_flags |= NFS4_OO_CONFIRMED;
3514 }
3515
3516 /* Should we give out recallable state?: */
3517 static bool nfsd4_cb_channel_good(struct nfs4_client *clp)
3518 {
3519         if (clp->cl_cb_state == NFSD4_CB_UP)
3520                 return true;
3521         /*
3522          * In the sessions case, since we don't have to establish a
3523          * separate connection for callbacks, we assume it's OK
3524          * until we hear otherwise:
3525          */
3526         return clp->cl_minorversion && clp->cl_cb_state == NFSD4_CB_UNKNOWN;
3527 }
3528
3529 static struct file_lock *nfs4_alloc_init_lease(struct nfs4_file *fp, int flag)
3530 {
3531         struct file_lock *fl;
3532
3533         fl = locks_alloc_lock();
3534         if (!fl)
3535                 return NULL;
3536         locks_init_lock(fl);
3537         fl->fl_lmops = &nfsd_lease_mng_ops;
3538         fl->fl_flags = FL_DELEG;
3539         fl->fl_type = flag == NFS4_OPEN_DELEGATE_READ? F_RDLCK: F_WRLCK;
3540         fl->fl_end = OFFSET_MAX;
3541         fl->fl_owner = (fl_owner_t)fp;
3542         fl->fl_pid = current->tgid;
3543         return fl;
3544 }
3545
3546 static int nfs4_setlease(struct nfs4_delegation *dp)
3547 {
3548         struct nfs4_file *fp = dp->dl_stid.sc_file;
3549         struct file_lock *fl;
3550         struct file *filp;
3551         int status = 0;
3552
3553         fl = nfs4_alloc_init_lease(fp, NFS4_OPEN_DELEGATE_READ);
3554         if (!fl)
3555                 return -ENOMEM;
3556         filp = find_readable_file(fp);
3557         if (!filp) {
3558                 /* We should always have a readable file here */
3559                 WARN_ON_ONCE(1);
3560                 return -EBADF;
3561         }
3562         fl->fl_file = filp;
3563         status = vfs_setlease(filp, fl->fl_type, &fl);
3564         if (status) {
3565                 locks_free_lock(fl);
3566                 goto out_fput;
3567         }
3568         spin_lock(&state_lock);
3569         spin_lock(&fp->fi_lock);
3570         /* Did the lease get broken before we took the lock? */
3571         status = -EAGAIN;
3572         if (fp->fi_had_conflict)
3573                 goto out_unlock;
3574         /* Race breaker */
3575         if (fp->fi_lease) {
3576                 status = 0;
3577                 atomic_inc(&fp->fi_delegees);
3578                 hash_delegation_locked(dp, fp);
3579                 goto out_unlock;
3580         }
3581         fp->fi_lease = fl;
3582         fp->fi_deleg_file = filp;
3583         atomic_set(&fp->fi_delegees, 1);
3584         hash_delegation_locked(dp, fp);
3585         spin_unlock(&fp->fi_lock);
3586         spin_unlock(&state_lock);
3587         return 0;
3588 out_unlock:
3589         spin_unlock(&fp->fi_lock);
3590         spin_unlock(&state_lock);
3591 out_fput:
3592         fput(filp);
3593         return status;
3594 }
3595
3596 static struct nfs4_delegation *
3597 nfs4_set_delegation(struct nfs4_client *clp, struct svc_fh *fh,
3598                     struct nfs4_file *fp)
3599 {
3600         int status;
3601         struct nfs4_delegation *dp;
3602
3603         if (fp->fi_had_conflict)
3604                 return ERR_PTR(-EAGAIN);
3605
3606         dp = alloc_init_deleg(clp, fh);
3607         if (!dp)
3608                 return ERR_PTR(-ENOMEM);
3609
3610         get_nfs4_file(fp);
3611         spin_lock(&state_lock);
3612         spin_lock(&fp->fi_lock);
3613         dp->dl_stid.sc_file = fp;
3614         if (!fp->fi_lease) {
3615                 spin_unlock(&fp->fi_lock);
3616                 spin_unlock(&state_lock);
3617                 status = nfs4_setlease(dp);
3618                 goto out;
3619         }
3620         atomic_inc(&fp->fi_delegees);
3621         if (fp->fi_had_conflict) {
3622                 status = -EAGAIN;
3623                 goto out_unlock;
3624         }
3625         hash_delegation_locked(dp, fp);
3626         status = 0;
3627 out_unlock:
3628         spin_unlock(&fp->fi_lock);
3629         spin_unlock(&state_lock);
3630 out:
3631         if (status) {
3632                 nfs4_put_stid(&dp->dl_stid);
3633                 return ERR_PTR(status);
3634         }
3635         return dp;
3636 }
3637
3638 static void nfsd4_open_deleg_none_ext(struct nfsd4_open *open, int status)
3639 {
3640         open->op_delegate_type = NFS4_OPEN_DELEGATE_NONE_EXT;
3641         if (status == -EAGAIN)
3642                 open->op_why_no_deleg = WND4_CONTENTION;
3643         else {
3644                 open->op_why_no_deleg = WND4_RESOURCE;
3645                 switch (open->op_deleg_want) {
3646                 case NFS4_SHARE_WANT_READ_DELEG:
3647                 case NFS4_SHARE_WANT_WRITE_DELEG:
3648                 case NFS4_SHARE_WANT_ANY_DELEG:
3649                         break;
3650                 case NFS4_SHARE_WANT_CANCEL:
3651                         open->op_why_no_deleg = WND4_CANCELLED;
3652                         break;
3653                 case NFS4_SHARE_WANT_NO_DELEG:
3654                         WARN_ON_ONCE(1);
3655                 }
3656         }
3657 }
3658
3659 /*
3660  * Attempt to hand out a delegation.
3661  *
3662  * Note we don't support write delegations, and won't until the vfs has
3663  * proper support for them.
3664  */
3665 static void
3666 nfs4_open_delegation(struct svc_fh *fh, struct nfsd4_open *open,
3667                         struct nfs4_ol_stateid *stp)
3668 {
3669         struct nfs4_delegation *dp;
3670         struct nfs4_openowner *oo = openowner(stp->st_stateowner);
3671         struct nfs4_client *clp = stp->st_stid.sc_client;
3672         int cb_up;
3673         int status = 0;
3674
3675         cb_up = nfsd4_cb_channel_good(oo->oo_owner.so_client);
3676         open->op_recall = 0;
3677         switch (open->op_claim_type) {
3678                 case NFS4_OPEN_CLAIM_PREVIOUS:
3679                         if (!cb_up)
3680                                 open->op_recall = 1;
3681                         if (open->op_delegate_type != NFS4_OPEN_DELEGATE_READ)
3682                                 goto out_no_deleg;
3683                         break;
3684                 case NFS4_OPEN_CLAIM_NULL:
3685                 case NFS4_OPEN_CLAIM_FH:
3686                         /*
3687                          * Let's not give out any delegations till everyone's
3688                          * had the chance to reclaim theirs....
3689                          */
3690                         if (locks_in_grace(clp->net))
3691                                 goto out_no_deleg;
3692                         if (!cb_up || !(oo->oo_flags & NFS4_OO_CONFIRMED))
3693                                 goto out_no_deleg;
3694                         /*
3695                          * Also, if the file was opened for write or
3696                          * create, there's a good chance the client's
3697                          * about to write to it, resulting in an
3698                          * immediate recall (since we don't support
3699                          * write delegations):
3700                          */
3701                         if (open->op_share_access & NFS4_SHARE_ACCESS_WRITE)
3702                                 goto out_no_deleg;
3703                         if (open->op_create == NFS4_OPEN_CREATE)
3704                                 goto out_no_deleg;
3705                         break;
3706                 default:
3707                         goto out_no_deleg;
3708         }
3709         dp = nfs4_set_delegation(clp, fh, stp->st_stid.sc_file);
3710         if (IS_ERR(dp))
3711                 goto out_no_deleg;
3712
3713         memcpy(&open->op_delegate_stateid, &dp->dl_stid.sc_stateid, sizeof(dp->dl_stid.sc_stateid));
3714
3715         dprintk("NFSD: delegation stateid=" STATEID_FMT "\n",
3716                 STATEID_VAL(&dp->dl_stid.sc_stateid));
3717         open->op_delegate_type = NFS4_OPEN_DELEGATE_READ;
3718         return;
3719 out_no_deleg:
3720         open->op_delegate_type = NFS4_OPEN_DELEGATE_NONE;
3721         if (open->op_claim_type == NFS4_OPEN_CLAIM_PREVIOUS &&
3722             open->op_delegate_type != NFS4_OPEN_DELEGATE_NONE) {
3723                 dprintk("NFSD: WARNING: refusing delegation reclaim\n");
3724                 open->op_recall = 1;
3725         }
3726
3727         /* 4.1 client asking for a delegation? */
3728         if (open->op_deleg_want)
3729                 nfsd4_open_deleg_none_ext(open, status);
3730         return;
3731 }
3732
3733 static void nfsd4_deleg_xgrade_none_ext(struct nfsd4_open *open,
3734                                         struct nfs4_delegation *dp)
3735 {
3736         if (open->op_deleg_want == NFS4_SHARE_WANT_READ_DELEG &&
3737             dp->dl_type == NFS4_OPEN_DELEGATE_WRITE) {
3738                 open->op_delegate_type = NFS4_OPEN_DELEGATE_NONE_EXT;
3739                 open->op_why_no_deleg = WND4_NOT_SUPP_DOWNGRADE;
3740         } else if (open->op_deleg_want == NFS4_SHARE_WANT_WRITE_DELEG &&
3741                    dp->dl_type == NFS4_OPEN_DELEGATE_WRITE) {
3742                 open->op_delegate_type = NFS4_OPEN_DELEGATE_NONE_EXT;
3743                 open->op_why_no_deleg = WND4_NOT_SUPP_UPGRADE;
3744         }
3745         /* Otherwise the client must be confused wanting a delegation
3746          * it already has, therefore we don't return
3747          * NFS4_OPEN_DELEGATE_NONE_EXT and reason.
3748          */
3749 }
3750
3751 /*
3752  * called with nfs4_lock_state() held.
3753  */
3754 __be32
3755 nfsd4_process_open2(struct svc_rqst *rqstp, struct svc_fh *current_fh, struct nfsd4_open *open)
3756 {
3757         struct nfsd4_compoundres *resp = rqstp->rq_resp;
3758         struct nfs4_client *cl = open->op_openowner->oo_owner.so_client;
3759         struct nfs4_file *fp = NULL;
3760         struct nfs4_ol_stateid *stp = NULL;
3761         struct nfs4_delegation *dp = NULL;
3762         __be32 status;
3763
3764         /*
3765          * Lookup file; if found, lookup stateid and check open request,
3766          * and check for delegations in the process of being recalled.
3767          * If not found, create the nfs4_file struct
3768          */
3769         fp = find_or_add_file(open->op_file, &current_fh->fh_handle);
3770         if (fp != open->op_file) {
3771                 status = nfs4_check_deleg(cl, open, &dp);
3772                 if (status)
3773                         goto out;
3774                 stp = nfsd4_find_existing_open(fp, open);
3775         } else {
3776                 open->op_file = NULL;
3777                 status = nfserr_bad_stateid;
3778                 if (nfsd4_is_deleg_cur(open))
3779                         goto out;
3780                 status = nfserr_jukebox;
3781         }
3782
3783         /*
3784          * OPEN the file, or upgrade an existing OPEN.
3785          * If truncate fails, the OPEN fails.
3786          */
3787         if (stp) {
3788                 /* Stateid was found, this is an OPEN upgrade */
3789                 status = nfs4_upgrade_open(rqstp, fp, current_fh, stp, open);
3790                 if (status)
3791                         goto out;
3792         } else {
3793                 stp = open->op_stp;
3794                 open->op_stp = NULL;
3795                 init_open_stateid(stp, fp, open);
3796                 status = nfs4_get_vfs_file(rqstp, fp, current_fh, stp, open);
3797                 if (status) {
3798                         release_open_stateid(stp);
3799                         goto out;
3800                 }
3801         }
3802         update_stateid(&stp->st_stid.sc_stateid);
3803         memcpy(&open->op_stateid, &stp->st_stid.sc_stateid, sizeof(stateid_t));
3804
3805         if (nfsd4_has_session(&resp->cstate)) {
3806                 if (open->op_deleg_want & NFS4_SHARE_WANT_NO_DELEG) {
3807                         open->op_delegate_type = NFS4_OPEN_DELEGATE_NONE_EXT;
3808                         open->op_why_no_deleg = WND4_NOT_WANTED;
3809                         goto nodeleg;
3810                 }
3811         }
3812
3813         /*
3814         * Attempt to hand out a delegation. No error return, because the
3815         * OPEN succeeds even if we fail.
3816         */
3817         nfs4_open_delegation(current_fh, open, stp);
3818 nodeleg:
3819         status = nfs_ok;
3820
3821         dprintk("%s: stateid=" STATEID_FMT "\n", __func__,
3822                 STATEID_VAL(&stp->st_stid.sc_stateid));
3823 out:
3824         /* 4.1 client trying to upgrade/downgrade delegation? */
3825         if (open->op_delegate_type == NFS4_OPEN_DELEGATE_NONE && dp &&
3826             open->op_deleg_want)
3827                 nfsd4_deleg_xgrade_none_ext(open, dp);
3828
3829         if (fp)
3830                 put_nfs4_file(fp);
3831         if (status == 0 && open->op_claim_type == NFS4_OPEN_CLAIM_PREVIOUS)
3832                 nfs4_set_claim_prev(open, nfsd4_has_session(&resp->cstate));
3833         /*
3834         * To finish the open response, we just need to set the rflags.
3835         */
3836         open->op_rflags = NFS4_OPEN_RESULT_LOCKTYPE_POSIX;
3837         if (!(open->op_openowner->oo_flags & NFS4_OO_CONFIRMED) &&
3838             !nfsd4_has_session(&resp->cstate))
3839                 open->op_rflags |= NFS4_OPEN_RESULT_CONFIRM;
3840
3841         return status;
3842 }
3843
3844 void nfsd4_cleanup_open_state(struct nfsd4_open *open, __be32 status)
3845 {
3846         if (open->op_openowner) {
3847                 struct nfs4_openowner *oo = open->op_openowner;
3848
3849                 if (!list_empty(&oo->oo_owner.so_stateids))
3850                         list_del_init(&oo->oo_close_lru);
3851                 if (oo->oo_flags & NFS4_OO_NEW) {
3852                         if (status) {
3853                                 release_openowner(oo);
3854                                 open->op_openowner = NULL;
3855                         } else
3856                                 oo->oo_flags &= ~NFS4_OO_NEW;
3857                 }
3858         }
3859         if (open->op_file)
3860                 nfsd4_free_file(open->op_file);
3861         if (open->op_stp)
3862                 nfs4_put_stid(&open->op_stp->st_stid);
3863 }
3864
3865 __be32
3866 nfsd4_renew(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3867             clientid_t *clid)
3868 {
3869         struct nfs4_client *clp;
3870         __be32 status;
3871         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
3872
3873         nfs4_lock_state();
3874         dprintk("process_renew(%08x/%08x): starting\n", 
3875                         clid->cl_boot, clid->cl_id);
3876         status = lookup_clientid(clid, cstate, nn);
3877         if (status)
3878                 goto out;
3879         clp = cstate->clp;
3880         status = nfserr_cb_path_down;
3881         if (!list_empty(&clp->cl_delegations)
3882                         && clp->cl_cb_state != NFSD4_CB_UP)
3883                 goto out;
3884         status = nfs_ok;
3885 out:
3886         nfs4_unlock_state();
3887         return status;
3888 }
3889
3890 static void
3891 nfsd4_end_grace(struct nfsd_net *nn)
3892 {
3893         /* do nothing if grace period already ended */
3894         if (nn->grace_ended)
3895                 return;
3896
3897         dprintk("NFSD: end of grace period\n");
3898         nn->grace_ended = true;
3899         nfsd4_record_grace_done(nn, nn->boot_time);
3900         locks_end_grace(&nn->nfsd4_manager);
3901         /*
3902          * Now that every NFSv4 client has had the chance to recover and
3903          * to see the (possibly new, possibly shorter) lease time, we
3904          * can safely set the next grace time to the current lease time:
3905          */
3906         nn->nfsd4_grace = nn->nfsd4_lease;
3907 }
3908
3909 static time_t
3910 nfs4_laundromat(struct nfsd_net *nn)
3911 {
3912         struct nfs4_client *clp;
3913         struct nfs4_openowner *oo;
3914         struct nfs4_delegation *dp;
3915         struct list_head *pos, *next, reaplist;
3916         time_t cutoff = get_seconds() - nn->nfsd4_lease;
3917         time_t t, new_timeo = nn->nfsd4_lease;
3918
3919         nfs4_lock_state();
3920
3921         dprintk("NFSD: laundromat service - starting\n");
3922         nfsd4_end_grace(nn);
3923         INIT_LIST_HEAD(&reaplist);
3924         spin_lock(&nn->client_lock);
3925         list_for_each_safe(pos, next, &nn->client_lru) {
3926                 clp = list_entry(pos, struct nfs4_client, cl_lru);
3927                 if (time_after((unsigned long)clp->cl_time, (unsigned long)cutoff)) {
3928                         t = clp->cl_time - cutoff;
3929                         new_timeo = min(new_timeo, t);
3930                         break;
3931                 }
3932                 if (mark_client_expired_locked(clp)) {
3933                         dprintk("NFSD: client in use (clientid %08x)\n",
3934                                 clp->cl_clientid.cl_id);
3935                         continue;
3936                 }
3937                 list_move(&clp->cl_lru, &reaplist);
3938         }
3939         spin_unlock(&nn->client_lock);
3940         list_for_each_safe(pos, next, &reaplist) {
3941                 clp = list_entry(pos, struct nfs4_client, cl_lru);
3942                 dprintk("NFSD: purging unused client (clientid %08x)\n",
3943                         clp->cl_clientid.cl_id);
3944                 expire_client(clp);
3945         }
3946         spin_lock(&state_lock);
3947         list_for_each_safe(pos, next, &nn->del_recall_lru) {
3948                 dp = list_entry (pos, struct nfs4_delegation, dl_recall_lru);
3949                 if (net_generic(dp->dl_stid.sc_client->net, nfsd_net_id) != nn)
3950                         continue;
3951                 if (time_after((unsigned long)dp->dl_time, (unsigned long)cutoff)) {
3952                         t = dp->dl_time - cutoff;
3953                         new_timeo = min(new_timeo, t);
3954                         break;
3955                 }
3956                 unhash_delegation_locked(dp);
3957                 list_add(&dp->dl_recall_lru, &reaplist);
3958         }
3959         spin_unlock(&state_lock);
3960         while (!list_empty(&reaplist)) {
3961                 dp = list_first_entry(&reaplist, struct nfs4_delegation,
3962                                         dl_recall_lru);
3963                 list_del_init(&dp->dl_recall_lru);
3964                 revoke_delegation(dp);
3965         }
3966         list_for_each_safe(pos, next, &nn->close_lru) {
3967                 oo = container_of(pos, struct nfs4_openowner, oo_close_lru);
3968                 if (time_after((unsigned long)oo->oo_time, (unsigned long)cutoff)) {
3969                         t = oo->oo_time - cutoff;
3970                         new_timeo = min(new_timeo, t);
3971                         break;
3972                 }
3973                 release_openowner(oo);
3974         }
3975         new_timeo = max_t(time_t, new_timeo, NFSD_LAUNDROMAT_MINTIMEOUT);
3976         nfs4_unlock_state();
3977         return new_timeo;
3978 }
3979
3980 static struct workqueue_struct *laundry_wq;
3981 static void laundromat_main(struct work_struct *);
3982
3983 static void
3984 laundromat_main(struct work_struct *laundry)
3985 {
3986         time_t t;
3987         struct delayed_work *dwork = container_of(laundry, struct delayed_work,
3988                                                   work);
3989         struct nfsd_net *nn = container_of(dwork, struct nfsd_net,
3990                                            laundromat_work);
3991
3992         t = nfs4_laundromat(nn);
3993         dprintk("NFSD: laundromat_main - sleeping for %ld seconds\n", t);
3994         queue_delayed_work(laundry_wq, &nn->laundromat_work, t*HZ);
3995 }
3996
3997 static inline __be32 nfs4_check_fh(struct svc_fh *fhp, struct nfs4_ol_stateid *stp)
3998 {
3999         if (!nfsd_fh_match(&fhp->fh_handle, &stp->st_stid.sc_file->fi_fhandle))
4000                 return nfserr_bad_stateid;
4001         return nfs_ok;
4002 }
4003
4004 static inline int
4005 access_permit_read(struct nfs4_ol_stateid *stp)
4006 {
4007         return test_access(NFS4_SHARE_ACCESS_READ, stp) ||
4008                 test_access(NFS4_SHARE_ACCESS_BOTH, stp) ||
4009                 test_access(NFS4_SHARE_ACCESS_WRITE, stp);
4010 }
4011
4012 static inline int
4013 access_permit_write(struct nfs4_ol_stateid *stp)
4014 {
4015         return test_access(NFS4_SHARE_ACCESS_WRITE, stp) ||
4016                 test_access(NFS4_SHARE_ACCESS_BOTH, stp);
4017 }
4018
4019 static
4020 __be32 nfs4_check_openmode(struct nfs4_ol_stateid *stp, int flags)
4021 {
4022         __be32 status = nfserr_openmode;
4023
4024         /* For lock stateid's, we test the parent open, not the lock: */
4025         if (stp->st_openstp)
4026                 stp = stp->st_openstp;
4027         if ((flags & WR_STATE) && !access_permit_write(stp))
4028                 goto out;
4029         if ((flags & RD_STATE) && !access_permit_read(stp))
4030                 goto out;
4031         status = nfs_ok;
4032 out:
4033         return status;
4034 }
4035
4036 static inline __be32
4037 check_special_stateids(struct net *net, svc_fh *current_fh, stateid_t *stateid, int flags)
4038 {
4039         if (ONE_STATEID(stateid) && (flags & RD_STATE))
4040                 return nfs_ok;
4041         else if (locks_in_grace(net)) {
4042                 /* Answer in remaining cases depends on existence of
4043                  * conflicting state; so we must wait out the grace period. */
4044                 return nfserr_grace;
4045         } else if (flags & WR_STATE)
4046                 return nfs4_share_conflict(current_fh,
4047                                 NFS4_SHARE_DENY_WRITE);
4048         else /* (flags & RD_STATE) && ZERO_STATEID(stateid) */
4049                 return nfs4_share_conflict(current_fh,
4050                                 NFS4_SHARE_DENY_READ);
4051 }
4052
4053 /*
4054  * Allow READ/WRITE during grace period on recovered state only for files
4055  * that are not able to provide mandatory locking.
4056  */
4057 static inline int
4058 grace_disallows_io(struct net *net, struct inode *inode)
4059 {
4060         return locks_in_grace(net) && mandatory_lock(inode);
4061 }
4062
4063 /* Returns true iff a is later than b: */
4064 static bool stateid_generation_after(stateid_t *a, stateid_t *b)
4065 {
4066         return (s32)(a->si_generation - b->si_generation) > 0;
4067 }
4068
4069 static __be32 check_stateid_generation(stateid_t *in, stateid_t *ref, bool has_session)
4070 {
4071         /*
4072          * When sessions are used the stateid generation number is ignored
4073          * when it is zero.
4074          */
4075         if (has_session && in->si_generation == 0)
4076                 return nfs_ok;
4077
4078         if (in->si_generation == ref->si_generation)
4079                 return nfs_ok;
4080
4081         /* If the client sends us a stateid from the future, it's buggy: */
4082         if (stateid_generation_after(in, ref))
4083                 return nfserr_bad_stateid;
4084         /*
4085          * However, we could see a stateid from the past, even from a
4086          * non-buggy client.  For example, if the client sends a lock
4087          * while some IO is outstanding, the lock may bump si_generation
4088          * while the IO is still in flight.  The client could avoid that
4089          * situation by waiting for responses on all the IO requests,
4090          * but better performance may result in retrying IO that
4091          * receives an old_stateid error if requests are rarely
4092          * reordered in flight:
4093          */
4094         return nfserr_old_stateid;
4095 }
4096
4097 static __be32 nfsd4_validate_stateid(struct nfs4_client *cl, stateid_t *stateid)
4098 {
4099         struct nfs4_stid *s;
4100         struct nfs4_ol_stateid *ols;
4101         __be32 status;
4102
4103         if (ZERO_STATEID(stateid) || ONE_STATEID(stateid))
4104                 return nfserr_bad_stateid;
4105         /* Client debugging aid. */
4106         if (!same_clid(&stateid->si_opaque.so_clid, &cl->cl_clientid)) {
4107                 char addr_str[INET6_ADDRSTRLEN];
4108                 rpc_ntop((struct sockaddr *)&cl->cl_addr, addr_str,
4109                                  sizeof(addr_str));
4110                 pr_warn_ratelimited("NFSD: client %s testing state ID "
4111                                         "with incorrect client ID\n", addr_str);
4112                 return nfserr_bad_stateid;
4113         }
4114         s = find_stateid(cl, stateid);
4115         if (!s)
4116                 return nfserr_bad_stateid;
4117         status = check_stateid_generation(stateid, &s->sc_stateid, 1);
4118         if (status)
4119                 return status;
4120         switch (s->sc_type) {
4121         case NFS4_DELEG_STID:
4122                 return nfs_ok;
4123         case NFS4_REVOKED_DELEG_STID:
4124                 return nfserr_deleg_revoked;
4125         case NFS4_OPEN_STID:
4126         case NFS4_LOCK_STID:
4127                 ols = openlockstateid(s);
4128                 if (ols->st_stateowner->so_is_open_owner
4129                                 && !(openowner(ols->st_stateowner)->oo_flags
4130                                                 & NFS4_OO_CONFIRMED))
4131                         return nfserr_bad_stateid;
4132                 return nfs_ok;
4133         default:
4134                 printk("unknown stateid type %x\n", s->sc_type);
4135                 /* Fallthrough */
4136         case NFS4_CLOSED_STID:
4137         case NFS4_CLOSED_DELEG_STID:
4138                 return nfserr_bad_stateid;
4139         }
4140 }
4141
4142 static __be32
4143 nfsd4_lookup_stateid(struct nfsd4_compound_state *cstate,
4144                      stateid_t *stateid, unsigned char typemask,
4145                      struct nfs4_stid **s, struct nfsd_net *nn)
4146 {
4147         __be32 status;
4148
4149         if (ZERO_STATEID(stateid) || ONE_STATEID(stateid))
4150                 return nfserr_bad_stateid;
4151         status = lookup_clientid(&stateid->si_opaque.so_clid, cstate, nn);
4152         if (status == nfserr_stale_clientid) {
4153                 if (cstate->session)
4154                         return nfserr_bad_stateid;
4155                 return nfserr_stale_stateid;
4156         }
4157         if (status)
4158                 return status;
4159         *s = find_stateid_by_type(cstate->clp, stateid, typemask);
4160         if (!*s)
4161                 return nfserr_bad_stateid;
4162         return nfs_ok;
4163 }
4164
4165 /*
4166 * Checks for stateid operations
4167 */
4168 __be32
4169 nfs4_preprocess_stateid_op(struct net *net, struct nfsd4_compound_state *cstate,
4170                            stateid_t *stateid, int flags, struct file **filpp)
4171 {
4172         struct nfs4_stid *s;
4173         struct nfs4_ol_stateid *stp = NULL;
4174         struct nfs4_delegation *dp = NULL;
4175         struct svc_fh *current_fh = &cstate->current_fh;
4176         struct inode *ino = current_fh->fh_dentry->d_inode;
4177         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
4178         struct file *file = NULL;
4179         __be32 status;
4180
4181         if (filpp)
4182                 *filpp = NULL;
4183
4184         if (grace_disallows_io(net, ino))
4185                 return nfserr_grace;
4186
4187         if (ZERO_STATEID(stateid) || ONE_STATEID(stateid))
4188                 return check_special_stateids(net, current_fh, stateid, flags);
4189
4190         nfs4_lock_state();
4191
4192         status = nfsd4_lookup_stateid(cstate, stateid,
4193                                 NFS4_DELEG_STID|NFS4_OPEN_STID|NFS4_LOCK_STID,
4194                                 &s, nn);
4195         if (status)
4196                 goto out;
4197         status = check_stateid_generation(stateid, &s->sc_stateid, nfsd4_has_session(cstate));
4198         if (status)
4199                 goto out;
4200         switch (s->sc_type) {
4201         case NFS4_DELEG_STID:
4202                 dp = delegstateid(s);
4203                 status = nfs4_check_delegmode(dp, flags);
4204                 if (status)
4205                         goto out;
4206                 if (filpp) {
4207                         file = dp->dl_stid.sc_file->fi_deleg_file;
4208                         if (!file) {
4209                                 WARN_ON_ONCE(1);
4210                                 status = nfserr_serverfault;
4211                                 goto out;
4212                         }
4213                         get_file(file);
4214                 }
4215                 break;
4216         case NFS4_OPEN_STID:
4217         case NFS4_LOCK_STID:
4218                 stp = openlockstateid(s);
4219                 status = nfs4_check_fh(current_fh, stp);
4220                 if (status)
4221                         goto out;
4222                 if (stp->st_stateowner->so_is_open_owner
4223                     && !(openowner(stp->st_stateowner)->oo_flags & NFS4_OO_CONFIRMED))
4224                         goto out;
4225                 status = nfs4_check_openmode(stp, flags);
4226                 if (status)
4227                         goto out;
4228                 if (filpp) {
4229                         struct nfs4_file *fp = stp->st_stid.sc_file;
4230
4231                         if (flags & RD_STATE)
4232                                 file = find_readable_file(fp);
4233                         else
4234                                 file = find_writeable_file(fp);
4235                 }
4236                 break;
4237         default:
4238                 status = nfserr_bad_stateid;
4239                 goto out;
4240         }
4241         status = nfs_ok;
4242         if (file)
4243                 *filpp = file;
4244 out:
4245         nfs4_unlock_state();
4246         return status;
4247 }
4248
4249 static __be32
4250 nfsd4_free_lock_stateid(struct nfs4_ol_stateid *stp)
4251 {
4252         struct nfs4_lockowner *lo = lockowner(stp->st_stateowner);
4253
4254         if (check_for_locks(stp->st_stid.sc_file, lo))
4255                 return nfserr_locks_held;
4256         release_lockowner_if_empty(lo);
4257         return nfs_ok;
4258 }
4259
4260 /*
4261  * Test if the stateid is valid
4262  */
4263 __be32
4264 nfsd4_test_stateid(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
4265                    struct nfsd4_test_stateid *test_stateid)
4266 {
4267         struct nfsd4_test_stateid_id *stateid;
4268         struct nfs4_client *cl = cstate->session->se_client;
4269
4270         nfs4_lock_state();
4271         list_for_each_entry(stateid, &test_stateid->ts_stateid_list, ts_id_list)
4272                 stateid->ts_id_status =
4273                         nfsd4_validate_stateid(cl, &stateid->ts_id_stateid);
4274         nfs4_unlock_state();
4275
4276         return nfs_ok;
4277 }
4278
4279 __be32
4280 nfsd4_free_stateid(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
4281                    struct nfsd4_free_stateid *free_stateid)
4282 {
4283         stateid_t *stateid = &free_stateid->fr_stateid;
4284         struct nfs4_stid *s;
4285         struct nfs4_delegation *dp;
4286         struct nfs4_client *cl = cstate->session->se_client;
4287         __be32 ret = nfserr_bad_stateid;
4288
4289         nfs4_lock_state();
4290         s = find_stateid(cl, stateid);
4291         if (!s)
4292                 goto out;
4293         switch (s->sc_type) {
4294         case NFS4_DELEG_STID:
4295                 ret = nfserr_locks_held;
4296                 goto out;
4297         case NFS4_OPEN_STID:
4298         case NFS4_LOCK_STID:
4299                 ret = check_stateid_generation(stateid, &s->sc_stateid, 1);
4300                 if (ret)
4301                         goto out;
4302                 if (s->sc_type == NFS4_LOCK_STID)
4303                         ret = nfsd4_free_lock_stateid(openlockstateid(s));
4304                 else
4305                         ret = nfserr_locks_held;
4306                 break;
4307         case NFS4_REVOKED_DELEG_STID:
4308                 dp = delegstateid(s);
4309                 spin_lock(&cl->cl_lock);
4310                 list_del_init(&dp->dl_recall_lru);
4311                 spin_unlock(&cl->cl_lock);
4312                 nfs4_put_stid(s);
4313                 ret = nfs_ok;
4314                 break;
4315         default:
4316                 ret = nfserr_bad_stateid;
4317         }
4318 out:
4319         nfs4_unlock_state();
4320         return ret;
4321 }
4322
4323 static inline int
4324 setlkflg (int type)
4325 {
4326         return (type == NFS4_READW_LT || type == NFS4_READ_LT) ?
4327                 RD_STATE : WR_STATE;
4328 }
4329
4330 static __be32 nfs4_seqid_op_checks(struct nfsd4_compound_state *cstate, stateid_t *stateid, u32 seqid, struct nfs4_ol_stateid *stp)
4331 {
4332         struct svc_fh *current_fh = &cstate->current_fh;
4333         struct nfs4_stateowner *sop = stp->st_stateowner;
4334         __be32 status;
4335
4336         status = nfsd4_check_seqid(cstate, sop, seqid);
4337         if (status)
4338                 return status;
4339         if (stp->st_stid.sc_type == NFS4_CLOSED_STID
4340                 || stp->st_stid.sc_type == NFS4_REVOKED_DELEG_STID)
4341                 /*
4342                  * "Closed" stateid's exist *only* to return
4343                  * nfserr_replay_me from the previous step, and
4344                  * revoked delegations are kept only for free_stateid.
4345                  */
4346                 return nfserr_bad_stateid;
4347         status = check_stateid_generation(stateid, &stp->st_stid.sc_stateid, nfsd4_has_session(cstate));
4348         if (status)
4349                 return status;
4350         return nfs4_check_fh(current_fh, stp);
4351 }
4352
4353 /* 
4354  * Checks for sequence id mutating operations. 
4355  */
4356 static __be32
4357 nfs4_preprocess_seqid_op(struct nfsd4_compound_state *cstate, u32 seqid,
4358                          stateid_t *stateid, char typemask,
4359                          struct nfs4_ol_stateid **stpp,
4360                          struct nfsd_net *nn)
4361 {
4362         __be32 status;
4363         struct nfs4_stid *s;
4364         struct nfs4_ol_stateid *stp = NULL;
4365
4366         dprintk("NFSD: %s: seqid=%d stateid = " STATEID_FMT "\n", __func__,
4367                 seqid, STATEID_VAL(stateid));
4368
4369         *stpp = NULL;
4370         status = nfsd4_lookup_stateid(cstate, stateid, typemask, &s, nn);
4371         if (status)
4372                 return status;
4373         stp = openlockstateid(s);
4374         if (!nfsd4_has_session(cstate))
4375                 cstate->replay_owner = stp->st_stateowner;
4376
4377         status = nfs4_seqid_op_checks(cstate, stateid, seqid, stp);
4378         if (!status)
4379                 *stpp = stp;
4380         return status;
4381 }
4382
4383 static __be32 nfs4_preprocess_confirmed_seqid_op(struct nfsd4_compound_state *cstate, u32 seqid,
4384                                                  stateid_t *stateid, struct nfs4_ol_stateid **stpp, struct nfsd_net *nn)
4385 {
4386         __be32 status;
4387         struct nfs4_openowner *oo;
4388
4389         status = nfs4_preprocess_seqid_op(cstate, seqid, stateid,
4390                                                 NFS4_OPEN_STID, stpp, nn);
4391         if (status)
4392                 return status;
4393         oo = openowner((*stpp)->st_stateowner);
4394         if (!(oo->oo_flags & NFS4_OO_CONFIRMED))
4395                 return nfserr_bad_stateid;
4396         return nfs_ok;
4397 }
4398
4399 __be32
4400 nfsd4_open_confirm(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
4401                    struct nfsd4_open_confirm *oc)
4402 {
4403         __be32 status;
4404         struct nfs4_openowner *oo;
4405         struct nfs4_ol_stateid *stp;
4406         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
4407
4408         dprintk("NFSD: nfsd4_open_confirm on file %pd\n",
4409                         cstate->current_fh.fh_dentry);
4410
4411         status = fh_verify(rqstp, &cstate->current_fh, S_IFREG, 0);
4412         if (status)
4413                 return status;
4414
4415         nfs4_lock_state();
4416
4417         status = nfs4_preprocess_seqid_op(cstate,
4418                                         oc->oc_seqid, &oc->oc_req_stateid,
4419                                         NFS4_OPEN_STID, &stp, nn);
4420         if (status)
4421                 goto out;
4422         oo = openowner(stp->st_stateowner);
4423         status = nfserr_bad_stateid;
4424         if (oo->oo_flags & NFS4_OO_CONFIRMED)
4425                 goto out;
4426         oo->oo_flags |= NFS4_OO_CONFIRMED;
4427         update_stateid(&stp->st_stid.sc_stateid);
4428         memcpy(&oc->oc_resp_stateid, &stp->st_stid.sc_stateid, sizeof(stateid_t));
4429         dprintk("NFSD: %s: success, seqid=%d stateid=" STATEID_FMT "\n",
4430                 __func__, oc->oc_seqid, STATEID_VAL(&stp->st_stid.sc_stateid));
4431
4432         nfsd4_client_record_create(oo->oo_owner.so_client);
4433         status = nfs_ok;
4434 out:
4435         nfsd4_bump_seqid(cstate, status);
4436         if (!cstate->replay_owner)
4437                 nfs4_unlock_state();
4438         return status;
4439 }
4440
4441 static inline void nfs4_stateid_downgrade_bit(struct nfs4_ol_stateid *stp, u32 access)
4442 {
4443         if (!test_access(access, stp))
4444                 return;
4445         nfs4_file_put_access(stp->st_stid.sc_file, access);
4446         clear_access(access, stp);
4447 }
4448
4449 static inline void nfs4_stateid_downgrade(struct nfs4_ol_stateid *stp, u32 to_access)
4450 {
4451         switch (to_access) {
4452         case NFS4_SHARE_ACCESS_READ:
4453                 nfs4_stateid_downgrade_bit(stp, NFS4_SHARE_ACCESS_WRITE);
4454                 nfs4_stateid_downgrade_bit(stp, NFS4_SHARE_ACCESS_BOTH);
4455                 break;
4456         case NFS4_SHARE_ACCESS_WRITE:
4457                 nfs4_stateid_downgrade_bit(stp, NFS4_SHARE_ACCESS_READ);
4458                 nfs4_stateid_downgrade_bit(stp, NFS4_SHARE_ACCESS_BOTH);
4459                 break;
4460         case NFS4_SHARE_ACCESS_BOTH:
4461                 break;
4462         default:
4463                 WARN_ON_ONCE(1);
4464         }
4465 }
4466
4467 __be32
4468 nfsd4_open_downgrade(struct svc_rqst *rqstp,
4469                      struct nfsd4_compound_state *cstate,
4470                      struct nfsd4_open_downgrade *od)
4471 {
4472         __be32 status;
4473         struct nfs4_ol_stateid *stp;
4474         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
4475
4476         dprintk("NFSD: nfsd4_open_downgrade on file %pd\n", 
4477                         cstate->current_fh.fh_dentry);
4478
4479         /* We don't yet support WANT bits: */
4480         if (od->od_deleg_want)
4481                 dprintk("NFSD: %s: od_deleg_want=0x%x ignored\n", __func__,
4482                         od->od_deleg_want);
4483
4484         nfs4_lock_state();
4485         status = nfs4_preprocess_confirmed_seqid_op(cstate, od->od_seqid,
4486                                         &od->od_stateid, &stp, nn);
4487         if (status)
4488                 goto out; 
4489         status = nfserr_inval;
4490         if (!test_access(od->od_share_access, stp)) {
4491                 dprintk("NFSD: access not a subset of current bitmap: 0x%hhx, input access=%08x\n",
4492                         stp->st_access_bmap, od->od_share_access);
4493                 goto out;
4494         }
4495         if (!test_deny(od->od_share_deny, stp)) {
4496                 dprintk("NFSD: deny not a subset of current bitmap: 0x%hhx, input deny=%08x\n",
4497                         stp->st_deny_bmap, od->od_share_deny);
4498                 goto out;
4499         }
4500         nfs4_stateid_downgrade(stp, od->od_share_access);
4501
4502         reset_union_bmap_deny(od->od_share_deny, stp);
4503
4504         update_stateid(&stp->st_stid.sc_stateid);
4505         memcpy(&od->od_stateid, &stp->st_stid.sc_stateid, sizeof(stateid_t));
4506         status = nfs_ok;
4507 out:
4508         nfsd4_bump_seqid(cstate, status);
4509         if (!cstate->replay_owner)
4510                 nfs4_unlock_state();
4511         return status;
4512 }
4513
4514 static void nfsd4_close_open_stateid(struct nfs4_ol_stateid *s)
4515 {
4516         struct nfs4_client *clp = s->st_stid.sc_client;
4517         struct nfs4_openowner *oo = openowner(s->st_stateowner);
4518
4519         s->st_stid.sc_type = NFS4_CLOSED_STID;
4520         unhash_open_stateid(s);
4521
4522         if (clp->cl_minorversion) {
4523                 if (list_empty(&oo->oo_owner.so_stateids))
4524                         release_openowner(oo);
4525                 nfs4_put_stid(&s->st_stid);
4526         } else {
4527                 /*
4528                  * In the 4.0 case we need to keep the owners around a
4529                  * little while to handle CLOSE replay. We still do need
4530                  * to release any file access that is held by them
4531                  * before returning however.
4532                  */
4533                 release_all_access(s);
4534                 if (s->st_stid.sc_file) {
4535                         put_nfs4_file(s->st_stid.sc_file);
4536                         s->st_stid.sc_file = NULL;
4537                 }
4538                 oo->oo_last_closed_stid = s;
4539                 if (list_empty(&oo->oo_owner.so_stateids))
4540                         move_to_close_lru(oo, clp->net);
4541         }
4542 }
4543
4544 /*
4545  * nfs4_unlock_state() called after encode
4546  */
4547 __be32
4548 nfsd4_close(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
4549             struct nfsd4_close *close)
4550 {
4551         __be32 status;
4552         struct nfs4_ol_stateid *stp;
4553         struct net *net = SVC_NET(rqstp);
4554         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
4555
4556         dprintk("NFSD: nfsd4_close on file %pd\n", 
4557                         cstate->current_fh.fh_dentry);
4558
4559         nfs4_lock_state();
4560         status = nfs4_preprocess_seqid_op(cstate, close->cl_seqid,
4561                                         &close->cl_stateid,
4562                                         NFS4_OPEN_STID|NFS4_CLOSED_STID,
4563                                         &stp, nn);
4564         nfsd4_bump_seqid(cstate, status);
4565         if (status)
4566                 goto out; 
4567         update_stateid(&stp->st_stid.sc_stateid);
4568         memcpy(&close->cl_stateid, &stp->st_stid.sc_stateid, sizeof(stateid_t));
4569
4570         nfsd4_close_open_stateid(stp);
4571 out:
4572         if (!cstate->replay_owner)
4573                 nfs4_unlock_state();
4574         return status;
4575 }
4576
4577 __be32
4578 nfsd4_delegreturn(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
4579                   struct nfsd4_delegreturn *dr)
4580 {
4581         struct nfs4_delegation *dp;
4582         stateid_t *stateid = &dr->dr_stateid;
4583         struct nfs4_stid *s;
4584         __be32 status;
4585         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
4586
4587         if ((status = fh_verify(rqstp, &cstate->current_fh, S_IFREG, 0)))
4588                 return status;
4589
4590         nfs4_lock_state();
4591         status = nfsd4_lookup_stateid(cstate, stateid, NFS4_DELEG_STID, &s, nn);
4592         if (status)
4593                 goto out;
4594         dp = delegstateid(s);
4595         status = check_stateid_generation(stateid, &dp->dl_stid.sc_stateid, nfsd4_has_session(cstate));
4596         if (status)
4597                 goto out;
4598
4599         destroy_delegation(dp);
4600 out:
4601         nfs4_unlock_state();
4602
4603         return status;
4604 }
4605
4606
4607 #define LOFF_OVERFLOW(start, len)      ((u64)(len) > ~(u64)(start))
4608
4609 static inline u64
4610 end_offset(u64 start, u64 len)
4611 {
4612         u64 end;
4613
4614         end = start + len;
4615         return end >= start ? end: NFS4_MAX_UINT64;
4616 }
4617
4618 /* last octet in a range */
4619 static inline u64
4620 last_byte_offset(u64 start, u64 len)
4621 {
4622         u64 end;
4623
4624         WARN_ON_ONCE(!len);
4625         end = start + len;
4626         return end > start ? end - 1: NFS4_MAX_UINT64;
4627 }
4628
4629 /*
4630  * TODO: Linux file offsets are _signed_ 64-bit quantities, which means that
4631  * we can't properly handle lock requests that go beyond the (2^63 - 1)-th
4632  * byte, because of sign extension problems.  Since NFSv4 calls for 64-bit
4633  * locking, this prevents us from being completely protocol-compliant.  The
4634  * real solution to this problem is to start using unsigned file offsets in
4635  * the VFS, but this is a very deep change!
4636  */
4637 static inline void
4638 nfs4_transform_lock_offset(struct file_lock *lock)
4639 {
4640         if (lock->fl_start < 0)
4641                 lock->fl_start = OFFSET_MAX;
4642         if (lock->fl_end < 0)
4643                 lock->fl_end = OFFSET_MAX;
4644 }
4645
4646 /* Hack!: For now, we're defining this just so we can use a pointer to it
4647  * as a unique cookie to identify our (NFSv4's) posix locks. */
4648 static const struct lock_manager_operations nfsd_posix_mng_ops  = {
4649 };
4650
4651 static inline void
4652 nfs4_set_lock_denied(struct file_lock *fl, struct nfsd4_lock_denied *deny)
4653 {
4654         struct nfs4_lockowner *lo;
4655
4656         if (fl->fl_lmops == &nfsd_posix_mng_ops) {
4657                 lo = (struct nfs4_lockowner *) fl->fl_owner;
4658                 deny->ld_owner.data = kmemdup(lo->lo_owner.so_owner.data,
4659                                         lo->lo_owner.so_owner.len, GFP_KERNEL);
4660                 if (!deny->ld_owner.data)
4661                         /* We just don't care that much */
4662                         goto nevermind;
4663                 deny->ld_owner.len = lo->lo_owner.so_owner.len;
4664                 deny->ld_clientid = lo->lo_owner.so_client->cl_clientid;
4665         } else {
4666 nevermind:
4667                 deny->ld_owner.len = 0;
4668                 deny->ld_owner.data = NULL;
4669                 deny->ld_clientid.cl_boot = 0;
4670                 deny->ld_clientid.cl_id = 0;
4671         }
4672         deny->ld_start = fl->fl_start;
4673         deny->ld_length = NFS4_MAX_UINT64;
4674         if (fl->fl_end != NFS4_MAX_UINT64)
4675                 deny->ld_length = fl->fl_end - fl->fl_start + 1;        
4676         deny->ld_type = NFS4_READ_LT;
4677         if (fl->fl_type != F_RDLCK)
4678                 deny->ld_type = NFS4_WRITE_LT;
4679 }
4680
4681 static struct nfs4_lockowner *
4682 find_lockowner_str(clientid_t *clid, struct xdr_netobj *owner,
4683                 struct nfsd_net *nn)
4684 {
4685         unsigned int strhashval = ownerstr_hashval(clid->cl_id, owner);
4686         struct nfs4_stateowner *so;
4687
4688         list_for_each_entry(so, &nn->ownerstr_hashtbl[strhashval], so_strhash) {
4689                 if (so->so_is_open_owner)
4690                         continue;
4691                 if (!same_owner_str(so, owner, clid))
4692                         continue;
4693                 return lockowner(so);
4694         }
4695         return NULL;
4696 }
4697
4698 /*
4699  * Alloc a lock owner structure.
4700  * Called in nfsd4_lock - therefore, OPEN and OPEN_CONFIRM (if needed) has 
4701  * occurred. 
4702  *
4703  * strhashval = ownerstr_hashval
4704  */
4705 static struct nfs4_lockowner *
4706 alloc_init_lock_stateowner(unsigned int strhashval, struct nfs4_client *clp, struct nfs4_ol_stateid *open_stp, struct nfsd4_lock *lock) {
4707         struct nfs4_lockowner *lo;
4708         struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id);
4709
4710         lo = alloc_stateowner(lockowner_slab, &lock->lk_new_owner, clp);
4711         if (!lo)
4712                 return NULL;
4713         INIT_LIST_HEAD(&lo->lo_owner.so_stateids);
4714         lo->lo_owner.so_is_open_owner = 0;
4715         /* It is the openowner seqid that will be incremented in encode in the
4716          * case of new lockowners; so increment the lock seqid manually: */
4717         lo->lo_owner.so_seqid = lock->lk_new_lock_seqid + 1;
4718         list_add(&lo->lo_owner.so_strhash, &nn->ownerstr_hashtbl[strhashval]);
4719         return lo;
4720 }
4721
4722 static void
4723 init_lock_stateid(struct nfs4_ol_stateid *stp, struct nfs4_lockowner *lo,
4724                   struct nfs4_file *fp, struct inode *inode,
4725                   struct nfs4_ol_stateid *open_stp)
4726 {
4727         struct nfs4_client *clp = lo->lo_owner.so_client;
4728
4729         lockdep_assert_held(&clp->cl_lock);
4730
4731         stp->st_stid.sc_type = NFS4_LOCK_STID;
4732         stp->st_stateowner = &lo->lo_owner;
4733         get_nfs4_file(fp);
4734         stp->st_stid.sc_file = fp;
4735         stp->st_stid.sc_free = nfs4_free_lock_stateid;
4736         stp->st_access_bmap = 0;
4737         stp->st_deny_bmap = open_stp->st_deny_bmap;
4738         stp->st_openstp = open_stp;
4739         list_add(&stp->st_locks, &open_stp->st_locks);
4740         list_add(&stp->st_perstateowner, &lo->lo_owner.so_stateids);
4741         spin_lock(&fp->fi_lock);
4742         list_add(&stp->st_perfile, &fp->fi_stateids);
4743         spin_unlock(&fp->fi_lock);
4744 }
4745
4746 static struct nfs4_ol_stateid *
4747 find_lock_stateid(struct nfs4_lockowner *lo, struct nfs4_file *fp)
4748 {
4749         struct nfs4_ol_stateid *lst;
4750         struct nfs4_client *clp = lo->lo_owner.so_client;
4751
4752         lockdep_assert_held(&clp->cl_lock);
4753
4754         list_for_each_entry(lst, &lo->lo_owner.so_stateids, st_perstateowner) {
4755                 if (lst->st_stid.sc_file == fp)
4756                         return lst;
4757         }
4758         return NULL;
4759 }
4760
4761 static struct nfs4_ol_stateid *
4762 find_or_create_lock_stateid(struct nfs4_lockowner *lo, struct nfs4_file *fi,
4763                             struct inode *inode, struct nfs4_ol_stateid *ost,
4764                             bool *new)
4765 {
4766         struct nfs4_stid *ns = NULL;
4767         struct nfs4_ol_stateid *lst;
4768         struct nfs4_openowner *oo = openowner(ost->st_stateowner);
4769         struct nfs4_client *clp = oo->oo_owner.so_client;
4770
4771         spin_lock(&clp->cl_lock);
4772         lst = find_lock_stateid(lo, fi);
4773         if (lst == NULL) {
4774                 spin_unlock(&clp->cl_lock);
4775                 ns = nfs4_alloc_stid(clp, stateid_slab);
4776                 if (ns == NULL)
4777                         return NULL;
4778
4779                 spin_lock(&clp->cl_lock);
4780                 lst = find_lock_stateid(lo, fi);
4781                 if (likely(!lst)) {
4782                         lst = openlockstateid(ns);
4783                         init_lock_stateid(lst, lo, fi, inode, ost);
4784                         ns = NULL;
4785                         *new = true;
4786                 }
4787         }
4788         spin_unlock(&clp->cl_lock);
4789         if (ns)
4790                 nfs4_put_stid(ns);
4791         return lst;
4792 }
4793
4794 static int
4795 check_lock_length(u64 offset, u64 length)
4796 {
4797         return ((length == 0)  || ((length != NFS4_MAX_UINT64) &&
4798              LOFF_OVERFLOW(offset, length)));
4799 }
4800
4801 static void get_lock_access(struct nfs4_ol_stateid *lock_stp, u32 access)
4802 {
4803         struct nfs4_file *fp = lock_stp->st_stid.sc_file;
4804
4805         lockdep_assert_held(&fp->fi_lock);
4806
4807         if (test_access(access, lock_stp))
4808                 return;
4809         __nfs4_file_get_access(fp, access);
4810         set_access(access, lock_stp);
4811 }
4812
4813 static __be32
4814 lookup_or_create_lock_state(struct nfsd4_compound_state *cstate,
4815                             struct nfs4_ol_stateid *ost,
4816                             struct nfsd4_lock *lock,
4817                             struct nfs4_ol_stateid **lst, bool *new)
4818 {
4819         struct nfs4_file *fi = ost->st_stid.sc_file;
4820         struct nfs4_openowner *oo = openowner(ost->st_stateowner);
4821         struct nfs4_client *cl = oo->oo_owner.so_client;
4822         struct inode *inode = cstate->current_fh.fh_dentry->d_inode;
4823         struct nfs4_lockowner *lo;
4824         unsigned int strhashval;
4825         struct nfsd_net *nn = net_generic(cl->net, nfsd_net_id);
4826
4827         lo = find_lockowner_str(&cl->cl_clientid, &lock->v.new.owner, nn);
4828         if (!lo) {
4829                 strhashval = ownerstr_hashval(cl->cl_clientid.cl_id,
4830                                 &lock->v.new.owner);
4831                 lo = alloc_init_lock_stateowner(strhashval, cl, ost, lock);
4832                 if (lo == NULL)
4833                         return nfserr_jukebox;
4834         } else {
4835                 /* with an existing lockowner, seqids must be the same */
4836                 if (!cstate->minorversion &&
4837                     lock->lk_new_lock_seqid != lo->lo_owner.so_seqid)
4838                         return nfserr_bad_seqid;
4839         }
4840
4841         *lst = find_or_create_lock_stateid(lo, fi, inode, ost, new);
4842         if (*lst == NULL) {
4843                 release_lockowner_if_empty(lo);
4844                 return nfserr_jukebox;
4845         }
4846         return nfs_ok;
4847 }
4848
4849 /*
4850  *  LOCK operation 
4851  */
4852 __be32
4853 nfsd4_lock(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
4854            struct nfsd4_lock *lock)
4855 {
4856         struct nfs4_openowner *open_sop = NULL;
4857         struct nfs4_lockowner *lock_sop = NULL;
4858         struct nfs4_ol_stateid *lock_stp;
4859         struct nfs4_file *fp;
4860         struct file *filp = NULL;
4861         struct file_lock *file_lock = NULL;
4862         struct file_lock *conflock = NULL;
4863         __be32 status = 0;
4864         bool new_state = false;
4865         int lkflg;
4866         int err;
4867         struct net *net = SVC_NET(rqstp);
4868         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
4869
4870         dprintk("NFSD: nfsd4_lock: start=%Ld length=%Ld\n",
4871                 (long long) lock->lk_offset,
4872                 (long long) lock->lk_length);
4873
4874         if (check_lock_length(lock->lk_offset, lock->lk_length))
4875                  return nfserr_inval;
4876
4877         if ((status = fh_verify(rqstp, &cstate->current_fh,
4878                                 S_IFREG, NFSD_MAY_LOCK))) {
4879                 dprintk("NFSD: nfsd4_lock: permission denied!\n");
4880                 return status;
4881         }
4882
4883         nfs4_lock_state();
4884
4885         if (lock->lk_is_new) {
4886                 struct nfs4_ol_stateid *open_stp = NULL;
4887
4888                 if (nfsd4_has_session(cstate))
4889                         /* See rfc 5661 18.10.3: given clientid is ignored: */
4890                         memcpy(&lock->v.new.clientid,
4891                                 &cstate->session->se_client->cl_clientid,
4892                                 sizeof(clientid_t));
4893
4894                 status = nfserr_stale_clientid;
4895                 if (STALE_CLIENTID(&lock->lk_new_clientid, nn))
4896                         goto out;
4897
4898                 /* validate and update open stateid and open seqid */
4899                 status = nfs4_preprocess_confirmed_seqid_op(cstate,
4900                                         lock->lk_new_open_seqid,
4901                                         &lock->lk_new_open_stateid,
4902                                         &open_stp, nn);
4903                 if (status)
4904                         goto out;
4905                 open_sop = openowner(open_stp->st_stateowner);
4906                 status = nfserr_bad_stateid;
4907                 if (!same_clid(&open_sop->oo_owner.so_client->cl_clientid,
4908                                                 &lock->v.new.clientid))
4909                         goto out;
4910                 status = lookup_or_create_lock_state(cstate, open_stp, lock,
4911                                                         &lock_stp, &new_state);
4912         } else
4913                 status = nfs4_preprocess_seqid_op(cstate,
4914                                        lock->lk_old_lock_seqid,
4915                                        &lock->lk_old_lock_stateid,
4916                                        NFS4_LOCK_STID, &lock_stp, nn);
4917         if (status)
4918                 goto out;
4919         lock_sop = lockowner(lock_stp->st_stateowner);
4920
4921         lkflg = setlkflg(lock->lk_type);
4922         status = nfs4_check_openmode(lock_stp, lkflg);
4923         if (status)
4924                 goto out;
4925
4926         status = nfserr_grace;
4927         if (locks_in_grace(net) && !lock->lk_reclaim)
4928                 goto out;
4929         status = nfserr_no_grace;
4930         if (!locks_in_grace(net) && lock->lk_reclaim)
4931                 goto out;
4932
4933         file_lock = locks_alloc_lock();
4934         if (!file_lock) {
4935                 dprintk("NFSD: %s: unable to allocate lock!\n", __func__);
4936                 status = nfserr_jukebox;
4937                 goto out;
4938         }
4939
4940         fp = lock_stp->st_stid.sc_file;
4941         locks_init_lock(file_lock);
4942         switch (lock->lk_type) {
4943                 case NFS4_READ_LT:
4944                 case NFS4_READW_LT:
4945                         spin_lock(&fp->fi_lock);
4946                         filp = find_readable_file_locked(fp);
4947                         if (filp)
4948                                 get_lock_access(lock_stp, NFS4_SHARE_ACCESS_READ);
4949                         spin_unlock(&fp->fi_lock);
4950                         file_lock->fl_type = F_RDLCK;
4951                         break;
4952                 case NFS4_WRITE_LT:
4953                 case NFS4_WRITEW_LT:
4954                         spin_lock(&fp->fi_lock);
4955                         filp = find_writeable_file_locked(fp);
4956                         if (filp)
4957                                 get_lock_access(lock_stp, NFS4_SHARE_ACCESS_WRITE);
4958                         spin_unlock(&fp->fi_lock);
4959                         file_lock->fl_type = F_WRLCK;
4960                         break;
4961                 default:
4962                         status = nfserr_inval;
4963                 goto out;
4964         }
4965         if (!filp) {
4966                 status = nfserr_openmode;
4967                 goto out;
4968         }
4969         file_lock->fl_owner = (fl_owner_t)lock_sop;
4970         file_lock->fl_pid = current->tgid;
4971         file_lock->fl_file = filp;
4972         file_lock->fl_flags = FL_POSIX;
4973         file_lock->fl_lmops = &nfsd_posix_mng_ops;
4974         file_lock->fl_start = lock->lk_offset;
4975         file_lock->fl_end = last_byte_offset(lock->lk_offset, lock->lk_length);
4976         nfs4_transform_lock_offset(file_lock);
4977
4978         conflock = locks_alloc_lock();
4979         if (!conflock) {
4980                 dprintk("NFSD: %s: unable to allocate lock!\n", __func__);
4981                 status = nfserr_jukebox;
4982                 goto out;
4983         }
4984
4985         err = vfs_lock_file(filp, F_SETLK, file_lock, conflock);
4986         switch (-err) {
4987         case 0: /* success! */
4988                 update_stateid(&lock_stp->st_stid.sc_stateid);
4989                 memcpy(&lock->lk_resp_stateid, &lock_stp->st_stid.sc_stateid, 
4990                                 sizeof(stateid_t));
4991                 status = 0;
4992                 break;
4993         case (EAGAIN):          /* conflock holds conflicting lock */
4994                 status = nfserr_denied;
4995                 dprintk("NFSD: nfsd4_lock: conflicting lock found!\n");
4996                 nfs4_set_lock_denied(conflock, &lock->lk_denied);
4997                 break;
4998         case (EDEADLK):
4999                 status = nfserr_deadlock;
5000                 break;
5001         default:
5002                 dprintk("NFSD: nfsd4_lock: vfs_lock_file() failed! status %d\n",err);
5003                 status = nfserrno(err);
5004                 break;
5005         }
5006 out:
5007         if (filp)
5008                 fput(filp);
5009         if (status && new_state)
5010                 release_lock_stateid(lock_stp);
5011         nfsd4_bump_seqid(cstate, status);
5012         if (!cstate->replay_owner)
5013                 nfs4_unlock_state();
5014         if (file_lock)
5015                 locks_free_lock(file_lock);
5016         if (conflock)
5017                 locks_free_lock(conflock);
5018         return status;
5019 }
5020
5021 /*
5022  * The NFSv4 spec allows a client to do a LOCKT without holding an OPEN,
5023  * so we do a temporary open here just to get an open file to pass to
5024  * vfs_test_lock.  (Arguably perhaps test_lock should be done with an
5025  * inode operation.)
5026  */
5027 static __be32 nfsd_test_lock(struct svc_rqst *rqstp, struct svc_fh *fhp, struct file_lock *lock)
5028 {
5029         struct file *file;
5030         __be32 err = nfsd_open(rqstp, fhp, S_IFREG, NFSD_MAY_READ, &file);
5031         if (!err) {
5032                 err = nfserrno(vfs_test_lock(file, lock));
5033                 nfsd_close(file);
5034         }
5035         return err;
5036 }
5037
5038 /*
5039  * LOCKT operation
5040  */
5041 __be32
5042 nfsd4_lockt(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
5043             struct nfsd4_lockt *lockt)
5044 {
5045         struct file_lock *file_lock = NULL;
5046         struct nfs4_lockowner *lo;
5047         __be32 status;
5048         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
5049
5050         if (locks_in_grace(SVC_NET(rqstp)))
5051                 return nfserr_grace;
5052
5053         if (check_lock_length(lockt->lt_offset, lockt->lt_length))
5054                  return nfserr_inval;
5055
5056         nfs4_lock_state();
5057
5058         if (!nfsd4_has_session(cstate)) {
5059                 status = lookup_clientid(&lockt->lt_clientid, cstate, nn);
5060                 if (status)
5061                         goto out;
5062         }
5063
5064         if ((status = fh_verify(rqstp, &cstate->current_fh, S_IFREG, 0)))
5065                 goto out;
5066
5067         file_lock = locks_alloc_lock();
5068         if (!file_lock) {
5069                 dprintk("NFSD: %s: unable to allocate lock!\n", __func__);
5070                 status = nfserr_jukebox;
5071                 goto out;
5072         }
5073         locks_init_lock(file_lock);
5074         switch (lockt->lt_type) {
5075                 case NFS4_READ_LT:
5076                 case NFS4_READW_LT:
5077                         file_lock->fl_type = F_RDLCK;
5078                 break;
5079                 case NFS4_WRITE_LT:
5080                 case NFS4_WRITEW_LT:
5081                         file_lock->fl_type = F_WRLCK;
5082                 break;
5083                 default:
5084                         dprintk("NFSD: nfs4_lockt: bad lock type!\n");
5085                         status = nfserr_inval;
5086                 goto out;
5087         }
5088
5089         lo = find_lockowner_str(&lockt->lt_clientid, &lockt->lt_owner, nn);
5090         if (lo)
5091                 file_lock->fl_owner = (fl_owner_t)lo;
5092         file_lock->fl_pid = current->tgid;
5093         file_lock->fl_flags = FL_POSIX;
5094
5095         file_lock->fl_start = lockt->lt_offset;
5096         file_lock->fl_end = last_byte_offset(lockt->lt_offset, lockt->lt_length);
5097
5098         nfs4_transform_lock_offset(file_lock);
5099
5100         status = nfsd_test_lock(rqstp, &cstate->current_fh, file_lock);
5101         if (status)
5102                 goto out;
5103
5104         if (file_lock->fl_type != F_UNLCK) {
5105                 status = nfserr_denied;
5106                 nfs4_set_lock_denied(file_lock, &lockt->lt_denied);
5107         }
5108 out:
5109         nfs4_unlock_state();
5110         if (file_lock)
5111                 locks_free_lock(file_lock);
5112         return status;
5113 }
5114
5115 __be32
5116 nfsd4_locku(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
5117             struct nfsd4_locku *locku)
5118 {
5119         struct nfs4_ol_stateid *stp;
5120         struct file *filp = NULL;
5121         struct file_lock *file_lock = NULL;
5122         __be32 status;
5123         int err;
5124         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
5125
5126         dprintk("NFSD: nfsd4_locku: start=%Ld length=%Ld\n",
5127                 (long long) locku->lu_offset,
5128                 (long long) locku->lu_length);
5129
5130         if (check_lock_length(locku->lu_offset, locku->lu_length))
5131                  return nfserr_inval;
5132
5133         nfs4_lock_state();
5134                                                                                 
5135         status = nfs4_preprocess_seqid_op(cstate, locku->lu_seqid,
5136                                         &locku->lu_stateid, NFS4_LOCK_STID,
5137                                         &stp, nn);
5138         if (status)
5139                 goto out;
5140         filp = find_any_file(stp->st_stid.sc_file);
5141         if (!filp) {
5142                 status = nfserr_lock_range;
5143                 goto out;
5144         }
5145         file_lock = locks_alloc_lock();
5146         if (!file_lock) {
5147                 dprintk("NFSD: %s: unable to allocate lock!\n", __func__);
5148                 status = nfserr_jukebox;
5149                 goto fput;
5150         }
5151         locks_init_lock(file_lock);
5152         file_lock->fl_type = F_UNLCK;
5153         file_lock->fl_owner = (fl_owner_t)lockowner(stp->st_stateowner);
5154         file_lock->fl_pid = current->tgid;
5155         file_lock->fl_file = filp;
5156         file_lock->fl_flags = FL_POSIX;
5157         file_lock->fl_lmops = &nfsd_posix_mng_ops;
5158         file_lock->fl_start = locku->lu_offset;
5159
5160         file_lock->fl_end = last_byte_offset(locku->lu_offset,
5161                                                 locku->lu_length);
5162         nfs4_transform_lock_offset(file_lock);
5163
5164         err = vfs_lock_file(filp, F_SETLK, file_lock, NULL);
5165         if (err) {
5166                 dprintk("NFSD: nfs4_locku: vfs_lock_file failed!\n");
5167                 goto out_nfserr;
5168         }
5169         update_stateid(&stp->st_stid.sc_stateid);
5170         memcpy(&locku->lu_stateid, &stp->st_stid.sc_stateid, sizeof(stateid_t));
5171 fput:
5172         fput(filp);
5173 out:
5174         nfsd4_bump_seqid(cstate, status);
5175         if (!cstate->replay_owner)
5176                 nfs4_unlock_state();
5177         if (file_lock)
5178                 locks_free_lock(file_lock);
5179         return status;
5180
5181 out_nfserr:
5182         status = nfserrno(err);
5183         goto fput;
5184 }
5185
5186 /*
5187  * returns
5188  *      true:  locks held by lockowner
5189  *      false: no locks held by lockowner
5190  */
5191 static bool
5192 check_for_locks(struct nfs4_file *fp, struct nfs4_lockowner *lowner)
5193 {
5194         struct file_lock **flpp;
5195         int status = false;
5196         struct file *filp = find_any_file(fp);
5197         struct inode *inode;
5198
5199         if (!filp) {
5200                 /* Any valid lock stateid should have some sort of access */
5201                 WARN_ON_ONCE(1);
5202                 return status;
5203         }
5204
5205         inode = file_inode(filp);
5206
5207         spin_lock(&inode->i_lock);
5208         for (flpp = &inode->i_flock; *flpp != NULL; flpp = &(*flpp)->fl_next) {
5209                 if ((*flpp)->fl_owner == (fl_owner_t)lowner) {
5210                         status = true;
5211                         break;
5212                 }
5213         }
5214         spin_unlock(&inode->i_lock);
5215         fput(filp);
5216         return status;
5217 }
5218
5219 __be32
5220 nfsd4_release_lockowner(struct svc_rqst *rqstp,
5221                         struct nfsd4_compound_state *cstate,
5222                         struct nfsd4_release_lockowner *rlockowner)
5223 {
5224         clientid_t *clid = &rlockowner->rl_clientid;
5225         struct nfs4_stateowner *sop = NULL, *tmp;
5226         struct nfs4_lockowner *lo;
5227         struct nfs4_ol_stateid *stp;
5228         struct xdr_netobj *owner = &rlockowner->rl_owner;
5229         unsigned int hashval = ownerstr_hashval(clid->cl_id, owner);
5230         __be32 status;
5231         struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
5232
5233         dprintk("nfsd4_release_lockowner clientid: (%08x/%08x):\n",
5234                 clid->cl_boot, clid->cl_id);
5235
5236         nfs4_lock_state();
5237
5238         status = lookup_clientid(clid, cstate, nn);
5239         if (status)
5240                 goto out;
5241
5242         status = nfserr_locks_held;
5243
5244         /* Find the matching lock stateowner */
5245         list_for_each_entry(tmp, &nn->ownerstr_hashtbl[hashval], so_strhash) {
5246                 if (tmp->so_is_open_owner)
5247                         continue;
5248                 if (same_owner_str(tmp, owner, clid)) {
5249                         sop = tmp;
5250                         break;
5251                 }
5252         }
5253
5254         /* No matching owner found, maybe a replay? Just declare victory... */
5255         if (!sop) {
5256                 status = nfs_ok;
5257                 goto out;
5258         }
5259
5260         lo = lockowner(sop);
5261         /* see if there are still any locks associated with it */
5262         list_for_each_entry(stp, &sop->so_stateids, st_perstateowner) {
5263                 if (check_for_locks(stp->st_stid.sc_file, lo))
5264                         goto out;
5265         }
5266
5267         status = nfs_ok;
5268         release_lockowner(lo);
5269 out:
5270         nfs4_unlock_state();
5271         return status;
5272 }
5273
5274 static inline struct nfs4_client_reclaim *
5275 alloc_reclaim(void)
5276 {
5277         return kmalloc(sizeof(struct nfs4_client_reclaim), GFP_KERNEL);
5278 }
5279
5280 bool
5281 nfs4_has_reclaimed_state(const char *name, struct nfsd_net *nn)
5282 {
5283         struct nfs4_client_reclaim *crp;
5284
5285         crp = nfsd4_find_reclaim_client(name, nn);
5286         return (crp && crp->cr_clp);
5287 }
5288
5289 /*
5290  * failure => all reset bets are off, nfserr_no_grace...
5291  */
5292 struct nfs4_client_reclaim *
5293 nfs4_client_to_reclaim(const char *name, struct nfsd_net *nn)
5294 {
5295         unsigned int strhashval;
5296         struct nfs4_client_reclaim *crp;
5297
5298         dprintk("NFSD nfs4_client_to_reclaim NAME: %.*s\n", HEXDIR_LEN, name);
5299         crp = alloc_reclaim();
5300         if (crp) {
5301                 strhashval = clientstr_hashval(name);
5302                 INIT_LIST_HEAD(&crp->cr_strhash);
5303                 list_add(&crp->cr_strhash, &nn->reclaim_str_hashtbl[strhashval]);
5304                 memcpy(crp->cr_recdir, name, HEXDIR_LEN);
5305                 crp->cr_clp = NULL;
5306                 nn->reclaim_str_hashtbl_size++;
5307         }
5308         return crp;
5309 }
5310
5311 void
5312 nfs4_remove_reclaim_record(struct nfs4_client_reclaim *crp, struct nfsd_net *nn)
5313 {
5314         list_del(&crp->cr_strhash);
5315         kfree(crp);
5316         nn->reclaim_str_hashtbl_size--;
5317 }
5318
5319 void
5320 nfs4_release_reclaim(struct nfsd_net *nn)
5321 {
5322         struct nfs4_client_reclaim *crp = NULL;
5323         int i;
5324
5325         for (i = 0; i < CLIENT_HASH_SIZE; i++) {
5326                 while (!list_empty(&nn->reclaim_str_hashtbl[i])) {
5327                         crp = list_entry(nn->reclaim_str_hashtbl[i].next,
5328                                         struct nfs4_client_reclaim, cr_strhash);
5329                         nfs4_remove_reclaim_record(crp, nn);
5330                 }
5331         }
5332         WARN_ON_ONCE(nn->reclaim_str_hashtbl_size);
5333 }
5334
5335 /*
5336  * called from OPEN, CLAIM_PREVIOUS with a new clientid. */
5337 struct nfs4_client_reclaim *
5338 nfsd4_find_reclaim_client(const char *recdir, struct nfsd_net *nn)
5339 {
5340         unsigned int strhashval;
5341         struct nfs4_client_reclaim *crp = NULL;
5342
5343         dprintk("NFSD: nfs4_find_reclaim_client for recdir %s\n", recdir);
5344
5345         strhashval = clientstr_hashval(recdir);
5346         list_for_each_entry(crp, &nn->reclaim_str_hashtbl[strhashval], cr_strhash) {
5347                 if (same_name(crp->cr_recdir, recdir)) {
5348                         return crp;
5349                 }
5350         }
5351         return NULL;
5352 }
5353
5354 /*
5355 * Called from OPEN. Look for clientid in reclaim list.
5356 */
5357 __be32
5358 nfs4_check_open_reclaim(clientid_t *clid,
5359                 struct nfsd4_compound_state *cstate,
5360                 struct nfsd_net *nn)
5361 {
5362         __be32 status;
5363
5364         /* find clientid in conf_id_hashtbl */
5365         status = lookup_clientid(clid, cstate, nn);
5366         if (status)
5367                 return nfserr_reclaim_bad;
5368
5369         if (nfsd4_client_record_check(cstate->clp))
5370                 return nfserr_reclaim_bad;
5371
5372         return nfs_ok;
5373 }
5374
5375 #ifdef CONFIG_NFSD_FAULT_INJECTION
5376
5377 u64 nfsd_forget_client(struct nfs4_client *clp, u64 max)
5378 {
5379         if (mark_client_expired(clp))
5380                 return 0;
5381         expire_client(clp);
5382         return 1;
5383 }
5384
5385 u64 nfsd_print_client(struct nfs4_client *clp, u64 num)
5386 {
5387         char buf[INET6_ADDRSTRLEN];
5388         rpc_ntop((struct sockaddr *)&clp->cl_addr, buf, sizeof(buf));
5389         printk(KERN_INFO "NFS Client: %s\n", buf);
5390         return 1;
5391 }
5392
5393 static void nfsd_print_count(struct nfs4_client *clp, unsigned int count,
5394                              const char *type)
5395 {
5396         char buf[INET6_ADDRSTRLEN];
5397         rpc_ntop((struct sockaddr *)&clp->cl_addr, buf, sizeof(buf));
5398         printk(KERN_INFO "NFS Client: %s has %u %s\n", buf, count, type);
5399 }
5400
5401 static u64 nfsd_foreach_client_lock(struct nfs4_client *clp, u64 max,
5402                                     void (*func)(struct nfs4_ol_stateid *))
5403 {
5404         struct nfs4_openowner *oop;
5405         struct nfs4_ol_stateid *stp, *st_next;
5406         struct nfs4_ol_stateid *lst, *lst_next;
5407         u64 count = 0;
5408
5409         list_for_each_entry(oop, &clp->cl_openowners, oo_perclient) {
5410                 list_for_each_entry_safe(stp, st_next,
5411                                 &oop->oo_owner.so_stateids, st_perstateowner) {
5412                         list_for_each_entry_safe(lst, lst_next,
5413                                         &stp->st_locks, st_locks) {
5414                                 if (func)
5415                                         func(lst);
5416                                 if (++count == max)
5417                                         return count;
5418                         }
5419                 }
5420         }
5421
5422         return count;
5423 }
5424
5425 u64 nfsd_forget_client_locks(struct nfs4_client *clp, u64 max)
5426 {
5427         return nfsd_foreach_client_lock(clp, max, release_lock_stateid);
5428 }
5429
5430 u64 nfsd_print_client_locks(struct nfs4_client *clp, u64 max)
5431 {
5432         u64 count = nfsd_foreach_client_lock(clp, max, NULL);
5433         nfsd_print_count(clp, count, "locked files");
5434         return count;
5435 }
5436
5437 static u64 nfsd_foreach_client_open(struct nfs4_client *clp, u64 max, void (*func)(struct nfs4_openowner *))
5438 {
5439         struct nfs4_openowner *oop, *next;
5440         u64 count = 0;
5441
5442         list_for_each_entry_safe(oop, next, &clp->cl_openowners, oo_perclient) {
5443                 if (func)
5444                         func(oop);
5445                 if (++count == max)
5446                         break;
5447         }
5448
5449         return count;
5450 }
5451
5452 u64 nfsd_forget_client_openowners(struct nfs4_client *clp, u64 max)
5453 {
5454         return nfsd_foreach_client_open(clp, max, release_openowner);
5455 }
5456
5457 u64 nfsd_print_client_openowners(struct nfs4_client *clp, u64 max)
5458 {
5459         u64 count = nfsd_foreach_client_open(clp, max, NULL);
5460         nfsd_print_count(clp, count, "open files");
5461         return count;
5462 }
5463
5464 static u64 nfsd_find_all_delegations(struct nfs4_client *clp, u64 max,
5465                                      struct list_head *victims)
5466 {
5467         struct nfs4_delegation *dp, *next;
5468         u64 count = 0;
5469
5470         lockdep_assert_held(&state_lock);
5471         list_for_each_entry_safe(dp, next, &clp->cl_delegations, dl_perclnt) {
5472                 if (victims) {
5473                         /*
5474                          * It's not safe to mess with delegations that have a
5475                          * non-zero dl_time. They might have already been broken
5476                          * and could be processed by the laundromat outside of
5477                          * the state_lock. Just leave them be.
5478                          */
5479                         if (dp->dl_time != 0)
5480                                 continue;
5481
5482                         unhash_delegation_locked(dp);
5483                         list_add(&dp->dl_recall_lru, victims);
5484                 }
5485                 if (++count == max)
5486                         break;
5487         }
5488         return count;
5489 }
5490
5491 u64 nfsd_forget_client_delegations(struct nfs4_client *clp, u64 max)
5492 {
5493         struct nfs4_delegation *dp, *next;
5494         LIST_HEAD(victims);
5495         u64 count;
5496
5497         spin_lock(&state_lock);
5498         count = nfsd_find_all_delegations(clp, max, &victims);
5499         spin_unlock(&state_lock);
5500
5501         list_for_each_entry_safe(dp, next, &victims, dl_recall_lru) {
5502                 list_del_init(&dp->dl_recall_lru);
5503                 revoke_delegation(dp);
5504         }
5505
5506         return count;
5507 }
5508
5509 u64 nfsd_recall_client_delegations(struct nfs4_client *clp, u64 max)
5510 {
5511         struct nfs4_delegation *dp;
5512         LIST_HEAD(victims);
5513         u64 count;
5514
5515         spin_lock(&state_lock);
5516         count = nfsd_find_all_delegations(clp, max, &victims);
5517         while (!list_empty(&victims)) {
5518                 dp = list_first_entry(&victims, struct nfs4_delegation,
5519                                         dl_recall_lru);
5520                 list_del_init(&dp->dl_recall_lru);
5521                 dp->dl_time = 0;
5522                 nfsd_break_one_deleg(dp);
5523         }
5524         spin_unlock(&state_lock);
5525
5526         return count;
5527 }
5528
5529 u64 nfsd_print_client_delegations(struct nfs4_client *clp, u64 max)
5530 {
5531         u64 count = 0;
5532
5533         spin_lock(&state_lock);
5534         count = nfsd_find_all_delegations(clp, max, NULL);
5535         spin_unlock(&state_lock);
5536
5537         nfsd_print_count(clp, count, "delegations");
5538         return count;
5539 }
5540
5541 u64 nfsd_for_n_state(u64 max, u64 (*func)(struct nfs4_client *, u64))
5542 {
5543         struct nfs4_client *clp, *next;
5544         u64 count = 0;
5545         struct nfsd_net *nn = net_generic(current->nsproxy->net_ns, nfsd_net_id);
5546
5547         if (!nfsd_netns_ready(nn))
5548                 return 0;
5549
5550         list_for_each_entry_safe(clp, next, &nn->client_lru, cl_lru) {
5551                 count += func(clp, max - count);
5552                 if ((max != 0) && (count >= max))
5553                         break;
5554         }
5555
5556         return count;
5557 }
5558
5559 struct nfs4_client *nfsd_find_client(struct sockaddr_storage *addr, size_t addr_size)
5560 {
5561         struct nfs4_client *clp;
5562         struct nfsd_net *nn = net_generic(current->nsproxy->net_ns, nfsd_net_id);
5563
5564         if (!nfsd_netns_ready(nn))
5565                 return NULL;
5566
5567         list_for_each_entry(clp, &nn->client_lru, cl_lru) {
5568                 if (memcmp(&clp->cl_addr, addr, addr_size) == 0)
5569                         return clp;
5570         }
5571         return NULL;
5572 }
5573
5574 #endif /* CONFIG_NFSD_FAULT_INJECTION */
5575
5576 /*
5577  * Since the lifetime of a delegation isn't limited to that of an open, a
5578  * client may quite reasonably hang on to a delegation as long as it has
5579  * the inode cached.  This becomes an obvious problem the first time a
5580  * client's inode cache approaches the size of the server's total memory.
5581  *
5582  * For now we avoid this problem by imposing a hard limit on the number
5583  * of delegations, which varies according to the server's memory size.
5584  */
5585 static void
5586 set_max_delegations(void)
5587 {
5588         /*
5589          * Allow at most 4 delegations per megabyte of RAM.  Quick
5590          * estimates suggest that in the worst case (where every delegation
5591          * is for a different inode), a delegation could take about 1.5K,
5592          * giving a worst case usage of about 6% of memory.
5593          */
5594         max_delegations = nr_free_buffer_pages() >> (20 - 2 - PAGE_SHIFT);
5595 }
5596
5597 static int nfs4_state_create_net(struct net *net)
5598 {
5599         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
5600         int i;
5601
5602         nn->conf_id_hashtbl = kmalloc(sizeof(struct list_head) *
5603                         CLIENT_HASH_SIZE, GFP_KERNEL);
5604         if (!nn->conf_id_hashtbl)
5605                 goto err;
5606         nn->unconf_id_hashtbl = kmalloc(sizeof(struct list_head) *
5607                         CLIENT_HASH_SIZE, GFP_KERNEL);
5608         if (!nn->unconf_id_hashtbl)
5609                 goto err_unconf_id;
5610         nn->ownerstr_hashtbl = kmalloc(sizeof(struct list_head) *
5611                         OWNER_HASH_SIZE, GFP_KERNEL);
5612         if (!nn->ownerstr_hashtbl)
5613                 goto err_ownerstr;
5614         nn->sessionid_hashtbl = kmalloc(sizeof(struct list_head) *
5615                         SESSION_HASH_SIZE, GFP_KERNEL);
5616         if (!nn->sessionid_hashtbl)
5617                 goto err_sessionid;
5618
5619         for (i = 0; i < CLIENT_HASH_SIZE; i++) {
5620                 INIT_LIST_HEAD(&nn->conf_id_hashtbl[i]);
5621                 INIT_LIST_HEAD(&nn->unconf_id_hashtbl[i]);
5622         }
5623         for (i = 0; i < OWNER_HASH_SIZE; i++)
5624                 INIT_LIST_HEAD(&nn->ownerstr_hashtbl[i]);
5625         for (i = 0; i < SESSION_HASH_SIZE; i++)
5626                 INIT_LIST_HEAD(&nn->sessionid_hashtbl[i]);
5627         nn->conf_name_tree = RB_ROOT;
5628         nn->unconf_name_tree = RB_ROOT;
5629         INIT_LIST_HEAD(&nn->client_lru);
5630         INIT_LIST_HEAD(&nn->close_lru);
5631         INIT_LIST_HEAD(&nn->del_recall_lru);
5632         spin_lock_init(&nn->client_lock);
5633
5634         INIT_DELAYED_WORK(&nn->laundromat_work, laundromat_main);
5635         get_net(net);
5636
5637         return 0;
5638
5639 err_sessionid:
5640         kfree(nn->ownerstr_hashtbl);
5641 err_ownerstr:
5642         kfree(nn->unconf_id_hashtbl);
5643 err_unconf_id:
5644         kfree(nn->conf_id_hashtbl);
5645 err:
5646         return -ENOMEM;
5647 }
5648
5649 static void
5650 nfs4_state_destroy_net(struct net *net)
5651 {
5652         int i;
5653         struct nfs4_client *clp = NULL;
5654         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
5655
5656         for (i = 0; i < CLIENT_HASH_SIZE; i++) {
5657                 while (!list_empty(&nn->conf_id_hashtbl[i])) {
5658                         clp = list_entry(nn->conf_id_hashtbl[i].next, struct nfs4_client, cl_idhash);
5659                         destroy_client(clp);
5660                 }
5661         }
5662
5663         for (i = 0; i < CLIENT_HASH_SIZE; i++) {
5664                 while (!list_empty(&nn->unconf_id_hashtbl[i])) {
5665                         clp = list_entry(nn->unconf_id_hashtbl[i].next, struct nfs4_client, cl_idhash);
5666                         destroy_client(clp);
5667                 }
5668         }
5669
5670         kfree(nn->sessionid_hashtbl);
5671         kfree(nn->ownerstr_hashtbl);
5672         kfree(nn->unconf_id_hashtbl);
5673         kfree(nn->conf_id_hashtbl);
5674         put_net(net);
5675 }
5676
5677 int
5678 nfs4_state_start_net(struct net *net)
5679 {
5680         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
5681         int ret;
5682
5683         ret = nfs4_state_create_net(net);
5684         if (ret)
5685                 return ret;
5686         nfsd4_client_tracking_init(net);
5687         nn->boot_time = get_seconds();
5688         locks_start_grace(net, &nn->nfsd4_manager);
5689         nn->grace_ended = false;
5690         printk(KERN_INFO "NFSD: starting %ld-second grace period (net %p)\n",
5691                nn->nfsd4_grace, net);
5692         queue_delayed_work(laundry_wq, &nn->laundromat_work, nn->nfsd4_grace * HZ);
5693         return 0;
5694 }
5695
5696 /* initialization to perform when the nfsd service is started: */
5697
5698 int
5699 nfs4_state_start(void)
5700 {
5701         int ret;
5702
5703         ret = set_callback_cred();
5704         if (ret)
5705                 return -ENOMEM;
5706         laundry_wq = create_singlethread_workqueue("nfsd4");
5707         if (laundry_wq == NULL) {
5708                 ret = -ENOMEM;
5709                 goto out_recovery;
5710         }
5711         ret = nfsd4_create_callback_queue();
5712         if (ret)
5713                 goto out_free_laundry;
5714
5715         set_max_delegations();
5716
5717         return 0;
5718
5719 out_free_laundry:
5720         destroy_workqueue(laundry_wq);
5721 out_recovery:
5722         return ret;
5723 }
5724
5725 void
5726 nfs4_state_shutdown_net(struct net *net)
5727 {
5728         struct nfs4_delegation *dp = NULL;
5729         struct list_head *pos, *next, reaplist;
5730         struct nfsd_net *nn = net_generic(net, nfsd_net_id);
5731
5732         cancel_delayed_work_sync(&nn->laundromat_work);
5733         locks_end_grace(&nn->nfsd4_manager);
5734
5735         nfs4_lock_state();
5736         INIT_LIST_HEAD(&reaplist);
5737         spin_lock(&state_lock);
5738         list_for_each_safe(pos, next, &nn->del_recall_lru) {
5739                 dp = list_entry (pos, struct nfs4_delegation, dl_recall_lru);
5740                 unhash_delegation_locked(dp);
5741                 list_add(&dp->dl_recall_lru, &reaplist);
5742         }
5743         spin_unlock(&state_lock);
5744         list_for_each_safe(pos, next, &reaplist) {
5745                 dp = list_entry (pos, struct nfs4_delegation, dl_recall_lru);
5746                 list_del_init(&dp->dl_recall_lru);
5747                 nfs4_put_stid(&dp->dl_stid);
5748         }
5749
5750         nfsd4_client_tracking_exit(net);
5751         nfs4_state_destroy_net(net);
5752         nfs4_unlock_state();
5753 }
5754
5755 void
5756 nfs4_state_shutdown(void)
5757 {
5758         destroy_workqueue(laundry_wq);
5759         nfsd4_destroy_callback_queue();
5760 }
5761
5762 static void
5763 get_stateid(struct nfsd4_compound_state *cstate, stateid_t *stateid)
5764 {
5765         if (HAS_STATE_ID(cstate, CURRENT_STATE_ID_FLAG) && CURRENT_STATEID(stateid))
5766                 memcpy(stateid, &cstate->current_stateid, sizeof(stateid_t));
5767 }
5768
5769 static void
5770 put_stateid(struct nfsd4_compound_state *cstate, stateid_t *stateid)
5771 {
5772         if (cstate->minorversion) {
5773                 memcpy(&cstate->current_stateid, stateid, sizeof(stateid_t));
5774                 SET_STATE_ID(cstate, CURRENT_STATE_ID_FLAG);
5775         }
5776 }
5777
5778 void
5779 clear_current_stateid(struct nfsd4_compound_state *cstate)
5780 {
5781         CLEAR_STATE_ID(cstate, CURRENT_STATE_ID_FLAG);
5782 }
5783
5784 /*
5785  * functions to set current state id
5786  */
5787 void
5788 nfsd4_set_opendowngradestateid(struct nfsd4_compound_state *cstate, struct nfsd4_open_downgrade *odp)
5789 {
5790         put_stateid(cstate, &odp->od_stateid);
5791 }
5792
5793 void
5794 nfsd4_set_openstateid(struct nfsd4_compound_state *cstate, struct nfsd4_open *open)
5795 {
5796         put_stateid(cstate, &open->op_stateid);
5797 }
5798
5799 void
5800 nfsd4_set_closestateid(struct nfsd4_compound_state *cstate, struct nfsd4_close *close)
5801 {
5802         put_stateid(cstate, &close->cl_stateid);
5803 }
5804
5805 void
5806 nfsd4_set_lockstateid(struct nfsd4_compound_state *cstate, struct nfsd4_lock *lock)
5807 {
5808         put_stateid(cstate, &lock->lk_resp_stateid);
5809 }
5810
5811 /*
5812  * functions to consume current state id
5813  */
5814
5815 void
5816 nfsd4_get_opendowngradestateid(struct nfsd4_compound_state *cstate, struct nfsd4_open_downgrade *odp)
5817 {
5818         get_stateid(cstate, &odp->od_stateid);
5819 }
5820
5821 void
5822 nfsd4_get_delegreturnstateid(struct nfsd4_compound_state *cstate, struct nfsd4_delegreturn *drp)
5823 {
5824         get_stateid(cstate, &drp->dr_stateid);
5825 }
5826
5827 void
5828 nfsd4_get_freestateid(struct nfsd4_compound_state *cstate, struct nfsd4_free_stateid *fsp)
5829 {
5830         get_stateid(cstate, &fsp->fr_stateid);
5831 }
5832
5833 void
5834 nfsd4_get_setattrstateid(struct nfsd4_compound_state *cstate, struct nfsd4_setattr *setattr)
5835 {
5836         get_stateid(cstate, &setattr->sa_stateid);
5837 }
5838
5839 void
5840 nfsd4_get_closestateid(struct nfsd4_compound_state *cstate, struct nfsd4_close *close)
5841 {
5842         get_stateid(cstate, &close->cl_stateid);
5843 }
5844
5845 void
5846 nfsd4_get_lockustateid(struct nfsd4_compound_state *cstate, struct nfsd4_locku *locku)
5847 {
5848         get_stateid(cstate, &locku->lu_stateid);
5849 }
5850
5851 void
5852 nfsd4_get_readstateid(struct nfsd4_compound_state *cstate, struct nfsd4_read *read)
5853 {
5854         get_stateid(cstate, &read->rd_stateid);
5855 }
5856
5857 void
5858 nfsd4_get_writestateid(struct nfsd4_compound_state *cstate, struct nfsd4_write *write)
5859 {
5860         get_stateid(cstate, &write->wr_stateid);
5861 }