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