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