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