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