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