nfsd4: share file descriptors between stateid's
[linux-2.6.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/smp_lock.h>
37 #include <linux/slab.h>
38 #include <linux/namei.h>
39 #include <linux/swap.h>
40 #include <linux/sunrpc/svcauth_gss.h>
41 #include <linux/sunrpc/clnt.h>
42 #include "xdr4.h"
43 #include "vfs.h"
44
45 #define NFSDDBG_FACILITY                NFSDDBG_PROC
46
47 /* Globals */
48 time_t nfsd4_lease = 90;     /* default lease time */
49 time_t nfsd4_grace = 90;
50 static time_t boot_time;
51 static u32 current_ownerid = 1;
52 static u32 current_fileid = 1;
53 static u32 current_delegid = 1;
54 static stateid_t zerostateid;             /* bits all 0 */
55 static stateid_t onestateid;              /* bits all 1 */
56 static u64 current_sessionid = 1;
57
58 #define ZERO_STATEID(stateid) (!memcmp((stateid), &zerostateid, sizeof(stateid_t)))
59 #define ONE_STATEID(stateid)  (!memcmp((stateid), &onestateid, sizeof(stateid_t)))
60
61 /* forward declarations */
62 static struct nfs4_stateid * find_stateid(stateid_t *stid, int flags);
63 static struct nfs4_delegation * find_delegation_stateid(struct inode *ino, stateid_t *stid);
64 static char user_recovery_dirname[PATH_MAX] = "/var/lib/nfs/v4recovery";
65 static void nfs4_set_recdir(char *recdir);
66
67 /* Locking: */
68
69 /* Currently used for almost all code touching nfsv4 state: */
70 static DEFINE_MUTEX(client_mutex);
71
72 /*
73  * Currently used for the del_recall_lru and file hash table.  In an
74  * effort to decrease the scope of the client_mutex, this spinlock may
75  * eventually cover more:
76  */
77 static DEFINE_SPINLOCK(recall_lock);
78
79 static struct kmem_cache *stateowner_slab = NULL;
80 static struct kmem_cache *file_slab = NULL;
81 static struct kmem_cache *stateid_slab = NULL;
82 static struct kmem_cache *deleg_slab = NULL;
83
84 void
85 nfs4_lock_state(void)
86 {
87         mutex_lock(&client_mutex);
88 }
89
90 void
91 nfs4_unlock_state(void)
92 {
93         mutex_unlock(&client_mutex);
94 }
95
96 static inline u32
97 opaque_hashval(const void *ptr, int nbytes)
98 {
99         unsigned char *cptr = (unsigned char *) ptr;
100
101         u32 x = 0;
102         while (nbytes--) {
103                 x *= 37;
104                 x += *cptr++;
105         }
106         return x;
107 }
108
109 static struct list_head del_recall_lru;
110
111 static inline void
112 put_nfs4_file(struct nfs4_file *fi)
113 {
114         if (atomic_dec_and_lock(&fi->fi_ref, &recall_lock)) {
115                 list_del(&fi->fi_hash);
116                 spin_unlock(&recall_lock);
117                 iput(fi->fi_inode);
118                 kmem_cache_free(file_slab, fi);
119         }
120 }
121
122 static inline void
123 get_nfs4_file(struct nfs4_file *fi)
124 {
125         atomic_inc(&fi->fi_ref);
126 }
127
128 static int num_delegations;
129 unsigned int max_delegations;
130
131 /*
132  * Open owner state (share locks)
133  */
134
135 /* hash tables for nfs4_stateowner */
136 #define OWNER_HASH_BITS              8
137 #define OWNER_HASH_SIZE             (1 << OWNER_HASH_BITS)
138 #define OWNER_HASH_MASK             (OWNER_HASH_SIZE - 1)
139
140 #define ownerid_hashval(id) \
141         ((id) & OWNER_HASH_MASK)
142 #define ownerstr_hashval(clientid, ownername) \
143         (((clientid) + opaque_hashval((ownername.data), (ownername.len))) & OWNER_HASH_MASK)
144
145 static struct list_head ownerid_hashtbl[OWNER_HASH_SIZE];
146 static struct list_head ownerstr_hashtbl[OWNER_HASH_SIZE];
147
148 /* hash table for nfs4_file */
149 #define FILE_HASH_BITS                   8
150 #define FILE_HASH_SIZE                  (1 << FILE_HASH_BITS)
151 #define FILE_HASH_MASK                  (FILE_HASH_SIZE - 1)
152 /* hash table for (open)nfs4_stateid */
153 #define STATEID_HASH_BITS              10
154 #define STATEID_HASH_SIZE              (1 << STATEID_HASH_BITS)
155 #define STATEID_HASH_MASK              (STATEID_HASH_SIZE - 1)
156
157 #define file_hashval(x) \
158         hash_ptr(x, FILE_HASH_BITS)
159 #define stateid_hashval(owner_id, file_id)  \
160         (((owner_id) + (file_id)) & STATEID_HASH_MASK)
161
162 static struct list_head file_hashtbl[FILE_HASH_SIZE];
163 static struct list_head stateid_hashtbl[STATEID_HASH_SIZE];
164
165 static inline void nfs4_file_get_access(struct nfs4_file *fp, int oflag)
166 {
167         BUG_ON(!(fp->fi_fds[oflag] || fp->fi_fds[O_RDWR]));
168         atomic_inc(&fp->fi_access[oflag]);
169 }
170
171 static inline void nfs4_file_put_fd(struct nfs4_file *fp, int oflag)
172 {
173         if (fp->fi_fds[oflag]) {
174                 fput(fp->fi_fds[oflag]);
175                 fp->fi_fds[oflag] = NULL;
176         }
177 }
178
179 static inline void nfs4_file_put_access(struct nfs4_file *fp, int oflag)
180 {
181         if (atomic_dec_and_test(&fp->fi_access[oflag])) {
182                 nfs4_file_put_fd(fp, O_RDWR);
183                 nfs4_file_put_fd(fp, oflag);
184         }
185 }
186
187 static struct nfs4_delegation *
188 alloc_init_deleg(struct nfs4_client *clp, struct nfs4_stateid *stp, struct svc_fh *current_fh, u32 type)
189 {
190         struct nfs4_delegation *dp;
191         struct nfs4_file *fp = stp->st_file;
192         struct nfs4_cb_conn *cb = &stp->st_stateowner->so_client->cl_cb_conn;
193
194         dprintk("NFSD alloc_init_deleg\n");
195         /*
196          * Major work on the lease subsystem (for example, to support
197          * calbacks on stat) will be required before we can support
198          * write delegations properly.
199          */
200         if (type != NFS4_OPEN_DELEGATE_READ)
201                 return NULL;
202         if (fp->fi_had_conflict)
203                 return NULL;
204         if (num_delegations > max_delegations)
205                 return NULL;
206         dp = kmem_cache_alloc(deleg_slab, GFP_KERNEL);
207         if (dp == NULL)
208                 return dp;
209         num_delegations++;
210         INIT_LIST_HEAD(&dp->dl_perfile);
211         INIT_LIST_HEAD(&dp->dl_perclnt);
212         INIT_LIST_HEAD(&dp->dl_recall_lru);
213         dp->dl_client = clp;
214         get_nfs4_file(fp);
215         dp->dl_file = fp;
216         nfs4_file_get_access(fp, O_RDONLY);
217         dp->dl_flock = NULL;
218         dp->dl_type = type;
219         dp->dl_ident = cb->cb_ident;
220         dp->dl_stateid.si_boot = boot_time;
221         dp->dl_stateid.si_stateownerid = current_delegid++;
222         dp->dl_stateid.si_fileid = 0;
223         dp->dl_stateid.si_generation = 0;
224         fh_copy_shallow(&dp->dl_fh, &current_fh->fh_handle);
225         dp->dl_time = 0;
226         atomic_set(&dp->dl_count, 1);
227         list_add(&dp->dl_perfile, &fp->fi_delegations);
228         list_add(&dp->dl_perclnt, &clp->cl_delegations);
229         INIT_WORK(&dp->dl_recall.cb_work, nfsd4_do_callback_rpc);
230         return dp;
231 }
232
233 void
234 nfs4_put_delegation(struct nfs4_delegation *dp)
235 {
236         if (atomic_dec_and_test(&dp->dl_count)) {
237                 dprintk("NFSD: freeing dp %p\n",dp);
238                 put_nfs4_file(dp->dl_file);
239                 kmem_cache_free(deleg_slab, dp);
240                 num_delegations--;
241         }
242 }
243
244 /* Remove the associated file_lock first, then remove the delegation.
245  * lease_modify() is called to remove the FS_LEASE file_lock from
246  * the i_flock list, eventually calling nfsd's lock_manager
247  * fl_release_callback.
248  */
249 static void
250 nfs4_close_delegation(struct nfs4_delegation *dp)
251 {
252         struct file *filp = find_readable_file(dp->dl_file);
253
254         dprintk("NFSD: close_delegation dp %p\n",dp);
255         if (dp->dl_flock)
256                 vfs_setlease(filp, F_UNLCK, &dp->dl_flock);
257         nfs4_file_put_access(dp->dl_file, O_RDONLY);
258 }
259
260 /* Called under the state lock. */
261 static void
262 unhash_delegation(struct nfs4_delegation *dp)
263 {
264         list_del_init(&dp->dl_perfile);
265         list_del_init(&dp->dl_perclnt);
266         spin_lock(&recall_lock);
267         list_del_init(&dp->dl_recall_lru);
268         spin_unlock(&recall_lock);
269         nfs4_close_delegation(dp);
270         nfs4_put_delegation(dp);
271 }
272
273 /* 
274  * SETCLIENTID state 
275  */
276
277 /* client_lock protects the client lru list and session hash table */
278 static DEFINE_SPINLOCK(client_lock);
279
280 /* Hash tables for nfs4_clientid state */
281 #define CLIENT_HASH_BITS                 4
282 #define CLIENT_HASH_SIZE                (1 << CLIENT_HASH_BITS)
283 #define CLIENT_HASH_MASK                (CLIENT_HASH_SIZE - 1)
284
285 #define clientid_hashval(id) \
286         ((id) & CLIENT_HASH_MASK)
287 #define clientstr_hashval(name) \
288         (opaque_hashval((name), 8) & CLIENT_HASH_MASK)
289 /*
290  * reclaim_str_hashtbl[] holds known client info from previous reset/reboot
291  * used in reboot/reset lease grace period processing
292  *
293  * conf_id_hashtbl[], and conf_str_hashtbl[] hold confirmed
294  * setclientid_confirmed info. 
295  *
296  * unconf_str_hastbl[] and unconf_id_hashtbl[] hold unconfirmed 
297  * setclientid info.
298  *
299  * client_lru holds client queue ordered by nfs4_client.cl_time
300  * for lease renewal.
301  *
302  * close_lru holds (open) stateowner queue ordered by nfs4_stateowner.so_time
303  * for last close replay.
304  */
305 static struct list_head reclaim_str_hashtbl[CLIENT_HASH_SIZE];
306 static int reclaim_str_hashtbl_size = 0;
307 static struct list_head conf_id_hashtbl[CLIENT_HASH_SIZE];
308 static struct list_head conf_str_hashtbl[CLIENT_HASH_SIZE];
309 static struct list_head unconf_str_hashtbl[CLIENT_HASH_SIZE];
310 static struct list_head unconf_id_hashtbl[CLIENT_HASH_SIZE];
311 static struct list_head client_lru;
312 static struct list_head close_lru;
313
314 static void unhash_generic_stateid(struct nfs4_stateid *stp)
315 {
316         list_del(&stp->st_hash);
317         list_del(&stp->st_perfile);
318         list_del(&stp->st_perstateowner);
319 }
320
321 static void free_generic_stateid(struct nfs4_stateid *stp)
322 {
323         put_nfs4_file(stp->st_file);
324         kmem_cache_free(stateid_slab, stp);
325 }
326
327 static void release_lock_stateid(struct nfs4_stateid *stp)
328 {
329         struct file *file;
330
331         unhash_generic_stateid(stp);
332         file = find_any_file(stp->st_file);
333         if (file)
334                 locks_remove_posix(file, (fl_owner_t)stp->st_stateowner);
335         free_generic_stateid(stp);
336 }
337
338 static void unhash_lockowner(struct nfs4_stateowner *sop)
339 {
340         struct nfs4_stateid *stp;
341
342         list_del(&sop->so_idhash);
343         list_del(&sop->so_strhash);
344         list_del(&sop->so_perstateid);
345         while (!list_empty(&sop->so_stateids)) {
346                 stp = list_first_entry(&sop->so_stateids,
347                                 struct nfs4_stateid, st_perstateowner);
348                 release_lock_stateid(stp);
349         }
350 }
351
352 static void release_lockowner(struct nfs4_stateowner *sop)
353 {
354         unhash_lockowner(sop);
355         nfs4_put_stateowner(sop);
356 }
357
358 static void
359 release_stateid_lockowners(struct nfs4_stateid *open_stp)
360 {
361         struct nfs4_stateowner *lock_sop;
362
363         while (!list_empty(&open_stp->st_lockowners)) {
364                 lock_sop = list_entry(open_stp->st_lockowners.next,
365                                 struct nfs4_stateowner, so_perstateid);
366                 /* list_del(&open_stp->st_lockowners);  */
367                 BUG_ON(lock_sop->so_is_open_owner);
368                 release_lockowner(lock_sop);
369         }
370 }
371
372 /*
373  * We store the NONE, READ, WRITE, and BOTH bits separately in the
374  * st_{access,deny}_bmap field of the stateid, in order to track not
375  * only what share bits are currently in force, but also what
376  * combinations of share bits previous opens have used.  This allows us
377  * to enforce the recommendation of rfc 3530 14.2.19 that the server
378  * return an error if the client attempt to downgrade to a combination
379  * of share bits not explicable by closing some of its previous opens.
380  *
381  * XXX: This enforcement is actually incomplete, since we don't keep
382  * track of access/deny bit combinations; so, e.g., we allow:
383  *
384  *      OPEN allow read, deny write
385  *      OPEN allow both, deny none
386  *      DOWNGRADE allow read, deny none
387  *
388  * which we should reject.
389  */
390 static void
391 set_access(unsigned int *access, unsigned long bmap) {
392         int i;
393
394         *access = 0;
395         for (i = 1; i < 4; i++) {
396                 if (test_bit(i, &bmap))
397                         *access |= i;
398         }
399 }
400
401 static void
402 set_deny(unsigned int *deny, unsigned long bmap) {
403         int i;
404
405         *deny = 0;
406         for (i = 0; i < 4; i++) {
407                 if (test_bit(i, &bmap))
408                         *deny |= i ;
409         }
410 }
411
412 static int
413 test_share(struct nfs4_stateid *stp, struct nfsd4_open *open) {
414         unsigned int access, deny;
415
416         set_access(&access, stp->st_access_bmap);
417         set_deny(&deny, stp->st_deny_bmap);
418         if ((access & open->op_share_deny) || (deny & open->op_share_access))
419                 return 0;
420         return 1;
421 }
422
423 static int nfs4_access_to_omode(u32 access)
424 {
425         switch (access) {
426         case NFS4_SHARE_ACCESS_READ:
427                 return O_RDONLY;
428         case NFS4_SHARE_ACCESS_WRITE:
429                 return O_WRONLY;
430         case NFS4_SHARE_ACCESS_BOTH:
431                 return O_RDWR;
432         }
433         BUG();
434 }
435
436 static int nfs4_access_bmap_to_omode(struct nfs4_stateid *stp)
437 {
438         unsigned int access;
439
440         set_access(&access, stp->st_access_bmap);
441         return nfs4_access_to_omode(access);
442 }
443
444 static void release_open_stateid(struct nfs4_stateid *stp)
445 {
446         int oflag = nfs4_access_bmap_to_omode(stp);
447
448         unhash_generic_stateid(stp);
449         release_stateid_lockowners(stp);
450         nfs4_file_put_access(stp->st_file, oflag);
451         free_generic_stateid(stp);
452 }
453
454 static void unhash_openowner(struct nfs4_stateowner *sop)
455 {
456         struct nfs4_stateid *stp;
457
458         list_del(&sop->so_idhash);
459         list_del(&sop->so_strhash);
460         list_del(&sop->so_perclient);
461         list_del(&sop->so_perstateid); /* XXX: necessary? */
462         while (!list_empty(&sop->so_stateids)) {
463                 stp = list_first_entry(&sop->so_stateids,
464                                 struct nfs4_stateid, st_perstateowner);
465                 release_open_stateid(stp);
466         }
467 }
468
469 static void release_openowner(struct nfs4_stateowner *sop)
470 {
471         unhash_openowner(sop);
472         list_del(&sop->so_close_lru);
473         nfs4_put_stateowner(sop);
474 }
475
476 #define SESSION_HASH_SIZE       512
477 static struct list_head sessionid_hashtbl[SESSION_HASH_SIZE];
478
479 static inline int
480 hash_sessionid(struct nfs4_sessionid *sessionid)
481 {
482         struct nfsd4_sessionid *sid = (struct nfsd4_sessionid *)sessionid;
483
484         return sid->sequence % SESSION_HASH_SIZE;
485 }
486
487 static inline void
488 dump_sessionid(const char *fn, struct nfs4_sessionid *sessionid)
489 {
490         u32 *ptr = (u32 *)(&sessionid->data[0]);
491         dprintk("%s: %u:%u:%u:%u\n", fn, ptr[0], ptr[1], ptr[2], ptr[3]);
492 }
493
494 static void
495 gen_sessionid(struct nfsd4_session *ses)
496 {
497         struct nfs4_client *clp = ses->se_client;
498         struct nfsd4_sessionid *sid;
499
500         sid = (struct nfsd4_sessionid *)ses->se_sessionid.data;
501         sid->clientid = clp->cl_clientid;
502         sid->sequence = current_sessionid++;
503         sid->reserved = 0;
504 }
505
506 /*
507  * The protocol defines ca_maxresponssize_cached to include the size of
508  * the rpc header, but all we need to cache is the data starting after
509  * the end of the initial SEQUENCE operation--the rest we regenerate
510  * each time.  Therefore we can advertise a ca_maxresponssize_cached
511  * value that is the number of bytes in our cache plus a few additional
512  * bytes.  In order to stay on the safe side, and not promise more than
513  * we can cache, those additional bytes must be the minimum possible: 24
514  * bytes of rpc header (xid through accept state, with AUTH_NULL
515  * verifier), 12 for the compound header (with zero-length tag), and 44
516  * for the SEQUENCE op response:
517  */
518 #define NFSD_MIN_HDR_SEQ_SZ  (24 + 12 + 44)
519
520 /*
521  * Give the client the number of ca_maxresponsesize_cached slots it
522  * requests, of size bounded by NFSD_SLOT_CACHE_SIZE,
523  * NFSD_MAX_MEM_PER_SESSION, and nfsd_drc_max_mem. Do not allow more
524  * than NFSD_MAX_SLOTS_PER_SESSION.
525  *
526  * If we run out of reserved DRC memory we should (up to a point)
527  * re-negotiate active sessions and reduce their slot usage to make
528  * rooom for new connections. For now we just fail the create session.
529  */
530 static int set_forechannel_drc_size(struct nfsd4_channel_attrs *fchan)
531 {
532         int mem, size = fchan->maxresp_cached;
533
534         if (fchan->maxreqs < 1)
535                 return nfserr_inval;
536
537         if (size < NFSD_MIN_HDR_SEQ_SZ)
538                 size = NFSD_MIN_HDR_SEQ_SZ;
539         size -= NFSD_MIN_HDR_SEQ_SZ;
540         if (size > NFSD_SLOT_CACHE_SIZE)
541                 size = NFSD_SLOT_CACHE_SIZE;
542
543         /* bound the maxreqs by NFSD_MAX_MEM_PER_SESSION */
544         mem = fchan->maxreqs * size;
545         if (mem > NFSD_MAX_MEM_PER_SESSION) {
546                 fchan->maxreqs = NFSD_MAX_MEM_PER_SESSION / size;
547                 if (fchan->maxreqs > NFSD_MAX_SLOTS_PER_SESSION)
548                         fchan->maxreqs = NFSD_MAX_SLOTS_PER_SESSION;
549                 mem = fchan->maxreqs * size;
550         }
551
552         spin_lock(&nfsd_drc_lock);
553         /* bound the total session drc memory ussage */
554         if (mem + nfsd_drc_mem_used > nfsd_drc_max_mem) {
555                 fchan->maxreqs = (nfsd_drc_max_mem - nfsd_drc_mem_used) / size;
556                 mem = fchan->maxreqs * size;
557         }
558         nfsd_drc_mem_used += mem;
559         spin_unlock(&nfsd_drc_lock);
560
561         if (fchan->maxreqs == 0)
562                 return nfserr_jukebox;
563
564         fchan->maxresp_cached = size + NFSD_MIN_HDR_SEQ_SZ;
565         return 0;
566 }
567
568 /*
569  * fchan holds the client values on input, and the server values on output
570  * sv_max_mesg is the maximum payload plus one page for overhead.
571  */
572 static int init_forechannel_attrs(struct svc_rqst *rqstp,
573                                   struct nfsd4_channel_attrs *session_fchan,
574                                   struct nfsd4_channel_attrs *fchan)
575 {
576         int status = 0;
577         __u32   maxcount = nfsd_serv->sv_max_mesg;
578
579         /* headerpadsz set to zero in encode routine */
580
581         /* Use the client's max request and max response size if possible */
582         if (fchan->maxreq_sz > maxcount)
583                 fchan->maxreq_sz = maxcount;
584         session_fchan->maxreq_sz = fchan->maxreq_sz;
585
586         if (fchan->maxresp_sz > maxcount)
587                 fchan->maxresp_sz = maxcount;
588         session_fchan->maxresp_sz = fchan->maxresp_sz;
589
590         /* Use the client's maxops if possible */
591         if (fchan->maxops > NFSD_MAX_OPS_PER_COMPOUND)
592                 fchan->maxops = NFSD_MAX_OPS_PER_COMPOUND;
593         session_fchan->maxops = fchan->maxops;
594
595         /* FIXME: Error means no more DRC pages so the server should
596          * recover pages from existing sessions. For now fail session
597          * creation.
598          */
599         status = set_forechannel_drc_size(fchan);
600
601         session_fchan->maxresp_cached = fchan->maxresp_cached;
602         session_fchan->maxreqs = fchan->maxreqs;
603
604         dprintk("%s status %d\n", __func__, status);
605         return status;
606 }
607
608 static void
609 free_session_slots(struct nfsd4_session *ses)
610 {
611         int i;
612
613         for (i = 0; i < ses->se_fchannel.maxreqs; i++)
614                 kfree(ses->se_slots[i]);
615 }
616
617 /*
618  * We don't actually need to cache the rpc and session headers, so we
619  * can allocate a little less for each slot:
620  */
621 static inline int slot_bytes(struct nfsd4_channel_attrs *ca)
622 {
623         return ca->maxresp_cached - NFSD_MIN_HDR_SEQ_SZ;
624 }
625
626 static int
627 alloc_init_session(struct svc_rqst *rqstp, struct nfs4_client *clp,
628                    struct nfsd4_create_session *cses)
629 {
630         struct nfsd4_session *new, tmp;
631         struct nfsd4_slot *sp;
632         int idx, slotsize, cachesize, i;
633         int status;
634
635         memset(&tmp, 0, sizeof(tmp));
636
637         /* FIXME: For now, we just accept the client back channel attributes. */
638         tmp.se_bchannel = cses->back_channel;
639         status = init_forechannel_attrs(rqstp, &tmp.se_fchannel,
640                                         &cses->fore_channel);
641         if (status)
642                 goto out;
643
644         BUILD_BUG_ON(NFSD_MAX_SLOTS_PER_SESSION * sizeof(struct nfsd4_slot)
645                      + sizeof(struct nfsd4_session) > PAGE_SIZE);
646
647         status = nfserr_jukebox;
648         /* allocate struct nfsd4_session and slot table pointers in one piece */
649         slotsize = tmp.se_fchannel.maxreqs * sizeof(struct nfsd4_slot *);
650         new = kzalloc(sizeof(*new) + slotsize, GFP_KERNEL);
651         if (!new)
652                 goto out;
653
654         memcpy(new, &tmp, sizeof(*new));
655
656         /* allocate each struct nfsd4_slot and data cache in one piece */
657         cachesize = slot_bytes(&new->se_fchannel);
658         for (i = 0; i < new->se_fchannel.maxreqs; i++) {
659                 sp = kzalloc(sizeof(*sp) + cachesize, GFP_KERNEL);
660                 if (!sp)
661                         goto out_free;
662                 new->se_slots[i] = sp;
663         }
664
665         new->se_client = clp;
666         gen_sessionid(new);
667         idx = hash_sessionid(&new->se_sessionid);
668         memcpy(clp->cl_sessionid.data, new->se_sessionid.data,
669                NFS4_MAX_SESSIONID_LEN);
670
671         new->se_flags = cses->flags;
672         kref_init(&new->se_ref);
673         spin_lock(&client_lock);
674         list_add(&new->se_hash, &sessionid_hashtbl[idx]);
675         list_add(&new->se_perclnt, &clp->cl_sessions);
676         spin_unlock(&client_lock);
677
678         status = nfs_ok;
679 out:
680         return status;
681 out_free:
682         free_session_slots(new);
683         kfree(new);
684         goto out;
685 }
686
687 /* caller must hold client_lock */
688 static struct nfsd4_session *
689 find_in_sessionid_hashtbl(struct nfs4_sessionid *sessionid)
690 {
691         struct nfsd4_session *elem;
692         int idx;
693
694         dump_sessionid(__func__, sessionid);
695         idx = hash_sessionid(sessionid);
696         /* Search in the appropriate list */
697         list_for_each_entry(elem, &sessionid_hashtbl[idx], se_hash) {
698                 if (!memcmp(elem->se_sessionid.data, sessionid->data,
699                             NFS4_MAX_SESSIONID_LEN)) {
700                         return elem;
701                 }
702         }
703
704         dprintk("%s: session not found\n", __func__);
705         return NULL;
706 }
707
708 /* caller must hold client_lock */
709 static void
710 unhash_session(struct nfsd4_session *ses)
711 {
712         list_del(&ses->se_hash);
713         list_del(&ses->se_perclnt);
714 }
715
716 void
717 free_session(struct kref *kref)
718 {
719         struct nfsd4_session *ses;
720         int mem;
721
722         ses = container_of(kref, struct nfsd4_session, se_ref);
723         spin_lock(&nfsd_drc_lock);
724         mem = ses->se_fchannel.maxreqs * slot_bytes(&ses->se_fchannel);
725         nfsd_drc_mem_used -= mem;
726         spin_unlock(&nfsd_drc_lock);
727         free_session_slots(ses);
728         kfree(ses);
729 }
730
731 /* must be called under the client_lock */
732 static inline void
733 renew_client_locked(struct nfs4_client *clp)
734 {
735         if (is_client_expired(clp)) {
736                 dprintk("%s: client (clientid %08x/%08x) already expired\n",
737                         __func__,
738                         clp->cl_clientid.cl_boot,
739                         clp->cl_clientid.cl_id);
740                 return;
741         }
742
743         /*
744         * Move client to the end to the LRU list.
745         */
746         dprintk("renewing client (clientid %08x/%08x)\n", 
747                         clp->cl_clientid.cl_boot, 
748                         clp->cl_clientid.cl_id);
749         list_move_tail(&clp->cl_lru, &client_lru);
750         clp->cl_time = get_seconds();
751 }
752
753 static inline void
754 renew_client(struct nfs4_client *clp)
755 {
756         spin_lock(&client_lock);
757         renew_client_locked(clp);
758         spin_unlock(&client_lock);
759 }
760
761 /* SETCLIENTID and SETCLIENTID_CONFIRM Helper functions */
762 static int
763 STALE_CLIENTID(clientid_t *clid)
764 {
765         if (clid->cl_boot == boot_time)
766                 return 0;
767         dprintk("NFSD stale clientid (%08x/%08x) boot_time %08lx\n",
768                 clid->cl_boot, clid->cl_id, boot_time);
769         return 1;
770 }
771
772 /* 
773  * XXX Should we use a slab cache ?
774  * This type of memory management is somewhat inefficient, but we use it
775  * anyway since SETCLIENTID is not a common operation.
776  */
777 static struct nfs4_client *alloc_client(struct xdr_netobj name)
778 {
779         struct nfs4_client *clp;
780
781         clp = kzalloc(sizeof(struct nfs4_client), GFP_KERNEL);
782         if (clp == NULL)
783                 return NULL;
784         clp->cl_name.data = kmalloc(name.len, GFP_KERNEL);
785         if (clp->cl_name.data == NULL) {
786                 kfree(clp);
787                 return NULL;
788         }
789         memcpy(clp->cl_name.data, name.data, name.len);
790         clp->cl_name.len = name.len;
791         return clp;
792 }
793
794 static inline void
795 free_client(struct nfs4_client *clp)
796 {
797         if (clp->cl_cred.cr_group_info)
798                 put_group_info(clp->cl_cred.cr_group_info);
799         kfree(clp->cl_principal);
800         kfree(clp->cl_name.data);
801         kfree(clp);
802 }
803
804 void
805 release_session_client(struct nfsd4_session *session)
806 {
807         struct nfs4_client *clp = session->se_client;
808
809         if (!atomic_dec_and_lock(&clp->cl_refcount, &client_lock))
810                 return;
811         if (is_client_expired(clp)) {
812                 free_client(clp);
813                 session->se_client = NULL;
814         } else
815                 renew_client_locked(clp);
816         spin_unlock(&client_lock);
817 }
818
819 /* must be called under the client_lock */
820 static inline void
821 unhash_client_locked(struct nfs4_client *clp)
822 {
823         mark_client_expired(clp);
824         list_del(&clp->cl_lru);
825         while (!list_empty(&clp->cl_sessions)) {
826                 struct nfsd4_session  *ses;
827                 ses = list_entry(clp->cl_sessions.next, struct nfsd4_session,
828                                  se_perclnt);
829                 unhash_session(ses);
830                 nfsd4_put_session(ses);
831         }
832 }
833
834 static void
835 expire_client(struct nfs4_client *clp)
836 {
837         struct nfs4_stateowner *sop;
838         struct nfs4_delegation *dp;
839         struct list_head reaplist;
840
841         INIT_LIST_HEAD(&reaplist);
842         spin_lock(&recall_lock);
843         while (!list_empty(&clp->cl_delegations)) {
844                 dp = list_entry(clp->cl_delegations.next, struct nfs4_delegation, dl_perclnt);
845                 dprintk("NFSD: expire client. dp %p, fp %p\n", dp,
846                                 dp->dl_flock);
847                 list_del_init(&dp->dl_perclnt);
848                 list_move(&dp->dl_recall_lru, &reaplist);
849         }
850         spin_unlock(&recall_lock);
851         while (!list_empty(&reaplist)) {
852                 dp = list_entry(reaplist.next, struct nfs4_delegation, dl_recall_lru);
853                 list_del_init(&dp->dl_recall_lru);
854                 unhash_delegation(dp);
855         }
856         while (!list_empty(&clp->cl_openowners)) {
857                 sop = list_entry(clp->cl_openowners.next, struct nfs4_stateowner, so_perclient);
858                 release_openowner(sop);
859         }
860         nfsd4_set_callback_client(clp, NULL);
861         if (clp->cl_cb_conn.cb_xprt)
862                 svc_xprt_put(clp->cl_cb_conn.cb_xprt);
863         list_del(&clp->cl_idhash);
864         list_del(&clp->cl_strhash);
865         spin_lock(&client_lock);
866         unhash_client_locked(clp);
867         if (atomic_read(&clp->cl_refcount) == 0)
868                 free_client(clp);
869         spin_unlock(&client_lock);
870 }
871
872 static void copy_verf(struct nfs4_client *target, nfs4_verifier *source)
873 {
874         memcpy(target->cl_verifier.data, source->data,
875                         sizeof(target->cl_verifier.data));
876 }
877
878 static void copy_clid(struct nfs4_client *target, struct nfs4_client *source)
879 {
880         target->cl_clientid.cl_boot = source->cl_clientid.cl_boot; 
881         target->cl_clientid.cl_id = source->cl_clientid.cl_id; 
882 }
883
884 static void copy_cred(struct svc_cred *target, struct svc_cred *source)
885 {
886         target->cr_uid = source->cr_uid;
887         target->cr_gid = source->cr_gid;
888         target->cr_group_info = source->cr_group_info;
889         get_group_info(target->cr_group_info);
890 }
891
892 static int same_name(const char *n1, const char *n2)
893 {
894         return 0 == memcmp(n1, n2, HEXDIR_LEN);
895 }
896
897 static int
898 same_verf(nfs4_verifier *v1, nfs4_verifier *v2)
899 {
900         return 0 == memcmp(v1->data, v2->data, sizeof(v1->data));
901 }
902
903 static int
904 same_clid(clientid_t *cl1, clientid_t *cl2)
905 {
906         return (cl1->cl_boot == cl2->cl_boot) && (cl1->cl_id == cl2->cl_id);
907 }
908
909 /* XXX what about NGROUP */
910 static int
911 same_creds(struct svc_cred *cr1, struct svc_cred *cr2)
912 {
913         return cr1->cr_uid == cr2->cr_uid;
914 }
915
916 static void gen_clid(struct nfs4_client *clp)
917 {
918         static u32 current_clientid = 1;
919
920         clp->cl_clientid.cl_boot = boot_time;
921         clp->cl_clientid.cl_id = current_clientid++; 
922 }
923
924 static void gen_confirm(struct nfs4_client *clp)
925 {
926         static u32 i;
927         u32 *p;
928
929         p = (u32 *)clp->cl_confirm.data;
930         *p++ = get_seconds();
931         *p++ = i++;
932 }
933
934 static struct nfs4_client *create_client(struct xdr_netobj name, char *recdir,
935                 struct svc_rqst *rqstp, nfs4_verifier *verf)
936 {
937         struct nfs4_client *clp;
938         struct sockaddr *sa = svc_addr(rqstp);
939         char *princ;
940
941         clp = alloc_client(name);
942         if (clp == NULL)
943                 return NULL;
944
945         princ = svc_gss_principal(rqstp);
946         if (princ) {
947                 clp->cl_principal = kstrdup(princ, GFP_KERNEL);
948                 if (clp->cl_principal == NULL) {
949                         free_client(clp);
950                         return NULL;
951                 }
952         }
953
954         memcpy(clp->cl_recdir, recdir, HEXDIR_LEN);
955         atomic_set(&clp->cl_refcount, 0);
956         atomic_set(&clp->cl_cb_set, 0);
957         INIT_LIST_HEAD(&clp->cl_idhash);
958         INIT_LIST_HEAD(&clp->cl_strhash);
959         INIT_LIST_HEAD(&clp->cl_openowners);
960         INIT_LIST_HEAD(&clp->cl_delegations);
961         INIT_LIST_HEAD(&clp->cl_sessions);
962         INIT_LIST_HEAD(&clp->cl_lru);
963         clp->cl_time = get_seconds();
964         clear_bit(0, &clp->cl_cb_slot_busy);
965         rpc_init_wait_queue(&clp->cl_cb_waitq, "Backchannel slot table");
966         copy_verf(clp, verf);
967         rpc_copy_addr((struct sockaddr *) &clp->cl_addr, sa);
968         clp->cl_flavor = rqstp->rq_flavor;
969         copy_cred(&clp->cl_cred, &rqstp->rq_cred);
970         gen_confirm(clp);
971
972         return clp;
973 }
974
975 static int check_name(struct xdr_netobj name)
976 {
977         if (name.len == 0) 
978                 return 0;
979         if (name.len > NFS4_OPAQUE_LIMIT) {
980                 dprintk("NFSD: check_name: name too long(%d)!\n", name.len);
981                 return 0;
982         }
983         return 1;
984 }
985
986 static void
987 add_to_unconfirmed(struct nfs4_client *clp, unsigned int strhashval)
988 {
989         unsigned int idhashval;
990
991         list_add(&clp->cl_strhash, &unconf_str_hashtbl[strhashval]);
992         idhashval = clientid_hashval(clp->cl_clientid.cl_id);
993         list_add(&clp->cl_idhash, &unconf_id_hashtbl[idhashval]);
994         renew_client(clp);
995 }
996
997 static void
998 move_to_confirmed(struct nfs4_client *clp)
999 {
1000         unsigned int idhashval = clientid_hashval(clp->cl_clientid.cl_id);
1001         unsigned int strhashval;
1002
1003         dprintk("NFSD: move_to_confirm nfs4_client %p\n", clp);
1004         list_move(&clp->cl_idhash, &conf_id_hashtbl[idhashval]);
1005         strhashval = clientstr_hashval(clp->cl_recdir);
1006         list_move(&clp->cl_strhash, &conf_str_hashtbl[strhashval]);
1007         renew_client(clp);
1008 }
1009
1010 static struct nfs4_client *
1011 find_confirmed_client(clientid_t *clid)
1012 {
1013         struct nfs4_client *clp;
1014         unsigned int idhashval = clientid_hashval(clid->cl_id);
1015
1016         list_for_each_entry(clp, &conf_id_hashtbl[idhashval], cl_idhash) {
1017                 if (same_clid(&clp->cl_clientid, clid))
1018                         return clp;
1019         }
1020         return NULL;
1021 }
1022
1023 static struct nfs4_client *
1024 find_unconfirmed_client(clientid_t *clid)
1025 {
1026         struct nfs4_client *clp;
1027         unsigned int idhashval = clientid_hashval(clid->cl_id);
1028
1029         list_for_each_entry(clp, &unconf_id_hashtbl[idhashval], cl_idhash) {
1030                 if (same_clid(&clp->cl_clientid, clid))
1031                         return clp;
1032         }
1033         return NULL;
1034 }
1035
1036 /*
1037  * Return 1 iff clp's clientid establishment method matches the use_exchange_id
1038  * parameter. Matching is based on the fact the at least one of the
1039  * EXCHGID4_FLAG_USE_{NON_PNFS,PNFS_MDS,PNFS_DS} flags must be set for v4.1
1040  *
1041  * FIXME: we need to unify the clientid namespaces for nfsv4.x
1042  * and correctly deal with client upgrade/downgrade in EXCHANGE_ID
1043  * and SET_CLIENTID{,_CONFIRM}
1044  */
1045 static inline int
1046 match_clientid_establishment(struct nfs4_client *clp, bool use_exchange_id)
1047 {
1048         bool has_exchange_flags = (clp->cl_exchange_flags != 0);
1049         return use_exchange_id == has_exchange_flags;
1050 }
1051
1052 static struct nfs4_client *
1053 find_confirmed_client_by_str(const char *dname, unsigned int hashval,
1054                              bool use_exchange_id)
1055 {
1056         struct nfs4_client *clp;
1057
1058         list_for_each_entry(clp, &conf_str_hashtbl[hashval], cl_strhash) {
1059                 if (same_name(clp->cl_recdir, dname) &&
1060                     match_clientid_establishment(clp, use_exchange_id))
1061                         return clp;
1062         }
1063         return NULL;
1064 }
1065
1066 static struct nfs4_client *
1067 find_unconfirmed_client_by_str(const char *dname, unsigned int hashval,
1068                                bool use_exchange_id)
1069 {
1070         struct nfs4_client *clp;
1071
1072         list_for_each_entry(clp, &unconf_str_hashtbl[hashval], cl_strhash) {
1073                 if (same_name(clp->cl_recdir, dname) &&
1074                     match_clientid_establishment(clp, use_exchange_id))
1075                         return clp;
1076         }
1077         return NULL;
1078 }
1079
1080 static void
1081 gen_callback(struct nfs4_client *clp, struct nfsd4_setclientid *se, u32 scopeid)
1082 {
1083         struct nfs4_cb_conn *cb = &clp->cl_cb_conn;
1084         unsigned short expected_family;
1085
1086         /* Currently, we only support tcp and tcp6 for the callback channel */
1087         if (se->se_callback_netid_len == 3 &&
1088             !memcmp(se->se_callback_netid_val, "tcp", 3))
1089                 expected_family = AF_INET;
1090         else if (se->se_callback_netid_len == 4 &&
1091                  !memcmp(se->se_callback_netid_val, "tcp6", 4))
1092                 expected_family = AF_INET6;
1093         else
1094                 goto out_err;
1095
1096         cb->cb_addrlen = rpc_uaddr2sockaddr(se->se_callback_addr_val,
1097                                             se->se_callback_addr_len,
1098                                             (struct sockaddr *) &cb->cb_addr,
1099                                             sizeof(cb->cb_addr));
1100
1101         if (!cb->cb_addrlen || cb->cb_addr.ss_family != expected_family)
1102                 goto out_err;
1103
1104         if (cb->cb_addr.ss_family == AF_INET6)
1105                 ((struct sockaddr_in6 *) &cb->cb_addr)->sin6_scope_id = scopeid;
1106
1107         cb->cb_minorversion = 0;
1108         cb->cb_prog = se->se_callback_prog;
1109         cb->cb_ident = se->se_callback_ident;
1110         return;
1111 out_err:
1112         cb->cb_addr.ss_family = AF_UNSPEC;
1113         cb->cb_addrlen = 0;
1114         dprintk(KERN_INFO "NFSD: this client (clientid %08x/%08x) "
1115                 "will not receive delegations\n",
1116                 clp->cl_clientid.cl_boot, clp->cl_clientid.cl_id);
1117
1118         return;
1119 }
1120
1121 /*
1122  * Cache a reply. nfsd4_check_drc_limit() has bounded the cache size.
1123  */
1124 void
1125 nfsd4_store_cache_entry(struct nfsd4_compoundres *resp)
1126 {
1127         struct nfsd4_slot *slot = resp->cstate.slot;
1128         unsigned int base;
1129
1130         dprintk("--> %s slot %p\n", __func__, slot);
1131
1132         slot->sl_opcnt = resp->opcnt;
1133         slot->sl_status = resp->cstate.status;
1134
1135         if (nfsd4_not_cached(resp)) {
1136                 slot->sl_datalen = 0;
1137                 return;
1138         }
1139         slot->sl_datalen = (char *)resp->p - (char *)resp->cstate.datap;
1140         base = (char *)resp->cstate.datap -
1141                                         (char *)resp->xbuf->head[0].iov_base;
1142         if (read_bytes_from_xdr_buf(resp->xbuf, base, slot->sl_data,
1143                                     slot->sl_datalen))
1144                 WARN("%s: sessions DRC could not cache compound\n", __func__);
1145         return;
1146 }
1147
1148 /*
1149  * Encode the replay sequence operation from the slot values.
1150  * If cachethis is FALSE encode the uncached rep error on the next
1151  * operation which sets resp->p and increments resp->opcnt for
1152  * nfs4svc_encode_compoundres.
1153  *
1154  */
1155 static __be32
1156 nfsd4_enc_sequence_replay(struct nfsd4_compoundargs *args,
1157                           struct nfsd4_compoundres *resp)
1158 {
1159         struct nfsd4_op *op;
1160         struct nfsd4_slot *slot = resp->cstate.slot;
1161
1162         dprintk("--> %s resp->opcnt %d cachethis %u \n", __func__,
1163                 resp->opcnt, resp->cstate.slot->sl_cachethis);
1164
1165         /* Encode the replayed sequence operation */
1166         op = &args->ops[resp->opcnt - 1];
1167         nfsd4_encode_operation(resp, op);
1168
1169         /* Return nfserr_retry_uncached_rep in next operation. */
1170         if (args->opcnt > 1 && slot->sl_cachethis == 0) {
1171                 op = &args->ops[resp->opcnt++];
1172                 op->status = nfserr_retry_uncached_rep;
1173                 nfsd4_encode_operation(resp, op);
1174         }
1175         return op->status;
1176 }
1177
1178 /*
1179  * The sequence operation is not cached because we can use the slot and
1180  * session values.
1181  */
1182 __be32
1183 nfsd4_replay_cache_entry(struct nfsd4_compoundres *resp,
1184                          struct nfsd4_sequence *seq)
1185 {
1186         struct nfsd4_slot *slot = resp->cstate.slot;
1187         __be32 status;
1188
1189         dprintk("--> %s slot %p\n", __func__, slot);
1190
1191         /* Either returns 0 or nfserr_retry_uncached */
1192         status = nfsd4_enc_sequence_replay(resp->rqstp->rq_argp, resp);
1193         if (status == nfserr_retry_uncached_rep)
1194                 return status;
1195
1196         /* The sequence operation has been encoded, cstate->datap set. */
1197         memcpy(resp->cstate.datap, slot->sl_data, slot->sl_datalen);
1198
1199         resp->opcnt = slot->sl_opcnt;
1200         resp->p = resp->cstate.datap + XDR_QUADLEN(slot->sl_datalen);
1201         status = slot->sl_status;
1202
1203         return status;
1204 }
1205
1206 /*
1207  * Set the exchange_id flags returned by the server.
1208  */
1209 static void
1210 nfsd4_set_ex_flags(struct nfs4_client *new, struct nfsd4_exchange_id *clid)
1211 {
1212         /* pNFS is not supported */
1213         new->cl_exchange_flags |= EXCHGID4_FLAG_USE_NON_PNFS;
1214
1215         /* Referrals are supported, Migration is not. */
1216         new->cl_exchange_flags |= EXCHGID4_FLAG_SUPP_MOVED_REFER;
1217
1218         /* set the wire flags to return to client. */
1219         clid->flags = new->cl_exchange_flags;
1220 }
1221
1222 __be32
1223 nfsd4_exchange_id(struct svc_rqst *rqstp,
1224                   struct nfsd4_compound_state *cstate,
1225                   struct nfsd4_exchange_id *exid)
1226 {
1227         struct nfs4_client *unconf, *conf, *new;
1228         int status;
1229         unsigned int            strhashval;
1230         char                    dname[HEXDIR_LEN];
1231         char                    addr_str[INET6_ADDRSTRLEN];
1232         nfs4_verifier           verf = exid->verifier;
1233         struct sockaddr         *sa = svc_addr(rqstp);
1234
1235         rpc_ntop(sa, addr_str, sizeof(addr_str));
1236         dprintk("%s rqstp=%p exid=%p clname.len=%u clname.data=%p "
1237                 "ip_addr=%s flags %x, spa_how %d\n",
1238                 __func__, rqstp, exid, exid->clname.len, exid->clname.data,
1239                 addr_str, exid->flags, exid->spa_how);
1240
1241         if (!check_name(exid->clname) || (exid->flags & ~EXCHGID4_FLAG_MASK_A))
1242                 return nfserr_inval;
1243
1244         /* Currently only support SP4_NONE */
1245         switch (exid->spa_how) {
1246         case SP4_NONE:
1247                 break;
1248         case SP4_SSV:
1249                 return nfserr_encr_alg_unsupp;
1250         default:
1251                 BUG();                          /* checked by xdr code */
1252         case SP4_MACH_CRED:
1253                 return nfserr_serverfault;      /* no excuse :-/ */
1254         }
1255
1256         status = nfs4_make_rec_clidname(dname, &exid->clname);
1257
1258         if (status)
1259                 goto error;
1260
1261         strhashval = clientstr_hashval(dname);
1262
1263         nfs4_lock_state();
1264         status = nfs_ok;
1265
1266         conf = find_confirmed_client_by_str(dname, strhashval, true);
1267         if (conf) {
1268                 if (!same_verf(&verf, &conf->cl_verifier)) {
1269                         /* 18.35.4 case 8 */
1270                         if (exid->flags & EXCHGID4_FLAG_UPD_CONFIRMED_REC_A) {
1271                                 status = nfserr_not_same;
1272                                 goto out;
1273                         }
1274                         /* Client reboot: destroy old state */
1275                         expire_client(conf);
1276                         goto out_new;
1277                 }
1278                 if (!same_creds(&conf->cl_cred, &rqstp->rq_cred)) {
1279                         /* 18.35.4 case 9 */
1280                         if (exid->flags & EXCHGID4_FLAG_UPD_CONFIRMED_REC_A) {
1281                                 status = nfserr_perm;
1282                                 goto out;
1283                         }
1284                         expire_client(conf);
1285                         goto out_new;
1286                 }
1287                 /*
1288                  * Set bit when the owner id and verifier map to an already
1289                  * confirmed client id (18.35.3).
1290                  */
1291                 exid->flags |= EXCHGID4_FLAG_CONFIRMED_R;
1292
1293                 /*
1294                  * Falling into 18.35.4 case 2, possible router replay.
1295                  * Leave confirmed record intact and return same result.
1296                  */
1297                 copy_verf(conf, &verf);
1298                 new = conf;
1299                 goto out_copy;
1300         }
1301
1302         /* 18.35.4 case 7 */
1303         if (exid->flags & EXCHGID4_FLAG_UPD_CONFIRMED_REC_A) {
1304                 status = nfserr_noent;
1305                 goto out;
1306         }
1307
1308         unconf  = find_unconfirmed_client_by_str(dname, strhashval, true);
1309         if (unconf) {
1310                 /*
1311                  * Possible retry or client restart.  Per 18.35.4 case 4,
1312                  * a new unconfirmed record should be generated regardless
1313                  * of whether any properties have changed.
1314                  */
1315                 expire_client(unconf);
1316         }
1317
1318 out_new:
1319         /* Normal case */
1320         new = create_client(exid->clname, dname, rqstp, &verf);
1321         if (new == NULL) {
1322                 status = nfserr_jukebox;
1323                 goto out;
1324         }
1325
1326         gen_clid(new);
1327         add_to_unconfirmed(new, strhashval);
1328 out_copy:
1329         exid->clientid.cl_boot = new->cl_clientid.cl_boot;
1330         exid->clientid.cl_id = new->cl_clientid.cl_id;
1331
1332         exid->seqid = 1;
1333         nfsd4_set_ex_flags(new, exid);
1334
1335         dprintk("nfsd4_exchange_id seqid %d flags %x\n",
1336                 new->cl_cs_slot.sl_seqid, new->cl_exchange_flags);
1337         status = nfs_ok;
1338
1339 out:
1340         nfs4_unlock_state();
1341 error:
1342         dprintk("nfsd4_exchange_id returns %d\n", ntohl(status));
1343         return status;
1344 }
1345
1346 static int
1347 check_slot_seqid(u32 seqid, u32 slot_seqid, int slot_inuse)
1348 {
1349         dprintk("%s enter. seqid %d slot_seqid %d\n", __func__, seqid,
1350                 slot_seqid);
1351
1352         /* The slot is in use, and no response has been sent. */
1353         if (slot_inuse) {
1354                 if (seqid == slot_seqid)
1355                         return nfserr_jukebox;
1356                 else
1357                         return nfserr_seq_misordered;
1358         }
1359         /* Normal */
1360         if (likely(seqid == slot_seqid + 1))
1361                 return nfs_ok;
1362         /* Replay */
1363         if (seqid == slot_seqid)
1364                 return nfserr_replay_cache;
1365         /* Wraparound */
1366         if (seqid == 1 && (slot_seqid + 1) == 0)
1367                 return nfs_ok;
1368         /* Misordered replay or misordered new request */
1369         return nfserr_seq_misordered;
1370 }
1371
1372 /*
1373  * Cache the create session result into the create session single DRC
1374  * slot cache by saving the xdr structure. sl_seqid has been set.
1375  * Do this for solo or embedded create session operations.
1376  */
1377 static void
1378 nfsd4_cache_create_session(struct nfsd4_create_session *cr_ses,
1379                            struct nfsd4_clid_slot *slot, int nfserr)
1380 {
1381         slot->sl_status = nfserr;
1382         memcpy(&slot->sl_cr_ses, cr_ses, sizeof(*cr_ses));
1383 }
1384
1385 static __be32
1386 nfsd4_replay_create_session(struct nfsd4_create_session *cr_ses,
1387                             struct nfsd4_clid_slot *slot)
1388 {
1389         memcpy(cr_ses, &slot->sl_cr_ses, sizeof(*cr_ses));
1390         return slot->sl_status;
1391 }
1392
1393 __be32
1394 nfsd4_create_session(struct svc_rqst *rqstp,
1395                      struct nfsd4_compound_state *cstate,
1396                      struct nfsd4_create_session *cr_ses)
1397 {
1398         struct sockaddr *sa = svc_addr(rqstp);
1399         struct nfs4_client *conf, *unconf;
1400         struct nfsd4_clid_slot *cs_slot = NULL;
1401         int status = 0;
1402
1403         nfs4_lock_state();
1404         unconf = find_unconfirmed_client(&cr_ses->clientid);
1405         conf = find_confirmed_client(&cr_ses->clientid);
1406
1407         if (conf) {
1408                 cs_slot = &conf->cl_cs_slot;
1409                 status = check_slot_seqid(cr_ses->seqid, cs_slot->sl_seqid, 0);
1410                 if (status == nfserr_replay_cache) {
1411                         dprintk("Got a create_session replay! seqid= %d\n",
1412                                 cs_slot->sl_seqid);
1413                         /* Return the cached reply status */
1414                         status = nfsd4_replay_create_session(cr_ses, cs_slot);
1415                         goto out;
1416                 } else if (cr_ses->seqid != cs_slot->sl_seqid + 1) {
1417                         status = nfserr_seq_misordered;
1418                         dprintk("Sequence misordered!\n");
1419                         dprintk("Expected seqid= %d but got seqid= %d\n",
1420                                 cs_slot->sl_seqid, cr_ses->seqid);
1421                         goto out;
1422                 }
1423                 cs_slot->sl_seqid++;
1424         } else if (unconf) {
1425                 if (!same_creds(&unconf->cl_cred, &rqstp->rq_cred) ||
1426                     !rpc_cmp_addr(sa, (struct sockaddr *) &unconf->cl_addr)) {
1427                         status = nfserr_clid_inuse;
1428                         goto out;
1429                 }
1430
1431                 cs_slot = &unconf->cl_cs_slot;
1432                 status = check_slot_seqid(cr_ses->seqid, cs_slot->sl_seqid, 0);
1433                 if (status) {
1434                         /* an unconfirmed replay returns misordered */
1435                         status = nfserr_seq_misordered;
1436                         goto out_cache;
1437                 }
1438
1439                 cs_slot->sl_seqid++; /* from 0 to 1 */
1440                 move_to_confirmed(unconf);
1441
1442                 if (cr_ses->flags & SESSION4_BACK_CHAN) {
1443                         unconf->cl_cb_conn.cb_xprt = rqstp->rq_xprt;
1444                         svc_xprt_get(rqstp->rq_xprt);
1445                         rpc_copy_addr(
1446                                 (struct sockaddr *)&unconf->cl_cb_conn.cb_addr,
1447                                 sa);
1448                         unconf->cl_cb_conn.cb_addrlen = svc_addr_len(sa);
1449                         unconf->cl_cb_conn.cb_minorversion =
1450                                 cstate->minorversion;
1451                         unconf->cl_cb_conn.cb_prog = cr_ses->callback_prog;
1452                         unconf->cl_cb_seq_nr = 1;
1453                         nfsd4_probe_callback(unconf, &unconf->cl_cb_conn);
1454                 }
1455                 conf = unconf;
1456         } else {
1457                 status = nfserr_stale_clientid;
1458                 goto out;
1459         }
1460
1461         /*
1462          * We do not support RDMA or persistent sessions
1463          */
1464         cr_ses->flags &= ~SESSION4_PERSIST;
1465         cr_ses->flags &= ~SESSION4_RDMA;
1466
1467         status = alloc_init_session(rqstp, conf, cr_ses);
1468         if (status)
1469                 goto out;
1470
1471         memcpy(cr_ses->sessionid.data, conf->cl_sessionid.data,
1472                NFS4_MAX_SESSIONID_LEN);
1473         cr_ses->seqid = cs_slot->sl_seqid;
1474
1475 out_cache:
1476         /* cache solo and embedded create sessions under the state lock */
1477         nfsd4_cache_create_session(cr_ses, cs_slot, status);
1478 out:
1479         nfs4_unlock_state();
1480         dprintk("%s returns %d\n", __func__, ntohl(status));
1481         return status;
1482 }
1483
1484 static bool nfsd4_last_compound_op(struct svc_rqst *rqstp)
1485 {
1486         struct nfsd4_compoundres *resp = rqstp->rq_resp;
1487         struct nfsd4_compoundargs *argp = rqstp->rq_argp;
1488
1489         return argp->opcnt == resp->opcnt;
1490 }
1491
1492 static bool nfsd4_compound_in_session(struct nfsd4_session *session, struct nfs4_sessionid *sid)
1493 {
1494         if (!session)
1495                 return 0;
1496         return !memcmp(sid, &session->se_sessionid, sizeof(*sid));
1497 }
1498
1499 __be32
1500 nfsd4_destroy_session(struct svc_rqst *r,
1501                       struct nfsd4_compound_state *cstate,
1502                       struct nfsd4_destroy_session *sessionid)
1503 {
1504         struct nfsd4_session *ses;
1505         u32 status = nfserr_badsession;
1506
1507         /* Notes:
1508          * - The confirmed nfs4_client->cl_sessionid holds destroyed sessinid
1509          * - Should we return nfserr_back_chan_busy if waiting for
1510          *   callbacks on to-be-destroyed session?
1511          * - Do we need to clear any callback info from previous session?
1512          */
1513
1514         if (nfsd4_compound_in_session(cstate->session, &sessionid->sessionid)) {
1515                 if (!nfsd4_last_compound_op(r))
1516                         return nfserr_not_only_op;
1517         }
1518         dump_sessionid(__func__, &sessionid->sessionid);
1519         spin_lock(&client_lock);
1520         ses = find_in_sessionid_hashtbl(&sessionid->sessionid);
1521         if (!ses) {
1522                 spin_unlock(&client_lock);
1523                 goto out;
1524         }
1525
1526         unhash_session(ses);
1527         spin_unlock(&client_lock);
1528
1529         nfs4_lock_state();
1530         /* wait for callbacks */
1531         nfsd4_set_callback_client(ses->se_client, NULL);
1532         nfs4_unlock_state();
1533         nfsd4_put_session(ses);
1534         status = nfs_ok;
1535 out:
1536         dprintk("%s returns %d\n", __func__, ntohl(status));
1537         return status;
1538 }
1539
1540 __be32
1541 nfsd4_sequence(struct svc_rqst *rqstp,
1542                struct nfsd4_compound_state *cstate,
1543                struct nfsd4_sequence *seq)
1544 {
1545         struct nfsd4_compoundres *resp = rqstp->rq_resp;
1546         struct nfsd4_session *session;
1547         struct nfsd4_slot *slot;
1548         int status;
1549
1550         if (resp->opcnt != 1)
1551                 return nfserr_sequence_pos;
1552
1553         spin_lock(&client_lock);
1554         status = nfserr_badsession;
1555         session = find_in_sessionid_hashtbl(&seq->sessionid);
1556         if (!session)
1557                 goto out;
1558
1559         status = nfserr_badslot;
1560         if (seq->slotid >= session->se_fchannel.maxreqs)
1561                 goto out;
1562
1563         slot = session->se_slots[seq->slotid];
1564         dprintk("%s: slotid %d\n", __func__, seq->slotid);
1565
1566         /* We do not negotiate the number of slots yet, so set the
1567          * maxslots to the session maxreqs which is used to encode
1568          * sr_highest_slotid and the sr_target_slot id to maxslots */
1569         seq->maxslots = session->se_fchannel.maxreqs;
1570
1571         status = check_slot_seqid(seq->seqid, slot->sl_seqid, slot->sl_inuse);
1572         if (status == nfserr_replay_cache) {
1573                 cstate->slot = slot;
1574                 cstate->session = session;
1575                 /* Return the cached reply status and set cstate->status
1576                  * for nfsd4_proc_compound processing */
1577                 status = nfsd4_replay_cache_entry(resp, seq);
1578                 cstate->status = nfserr_replay_cache;
1579                 goto out;
1580         }
1581         if (status)
1582                 goto out;
1583
1584         /* Success! bump slot seqid */
1585         slot->sl_inuse = true;
1586         slot->sl_seqid = seq->seqid;
1587         slot->sl_cachethis = seq->cachethis;
1588
1589         cstate->slot = slot;
1590         cstate->session = session;
1591
1592 out:
1593         /* Hold a session reference until done processing the compound. */
1594         if (cstate->session) {
1595                 nfsd4_get_session(cstate->session);
1596                 atomic_inc(&session->se_client->cl_refcount);
1597         }
1598         spin_unlock(&client_lock);
1599         dprintk("%s: return %d\n", __func__, ntohl(status));
1600         return status;
1601 }
1602
1603 __be32
1604 nfsd4_reclaim_complete(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_reclaim_complete *rc)
1605 {
1606         if (rc->rca_one_fs) {
1607                 if (!cstate->current_fh.fh_dentry)
1608                         return nfserr_nofilehandle;
1609                 /*
1610                  * We don't take advantage of the rca_one_fs case.
1611                  * That's OK, it's optional, we can safely ignore it.
1612                  */
1613                  return nfs_ok;
1614         }
1615         nfs4_lock_state();
1616         if (is_client_expired(cstate->session->se_client)) {
1617                 nfs4_unlock_state();
1618                 /*
1619                  * The following error isn't really legal.
1620                  * But we only get here if the client just explicitly
1621                  * destroyed the client.  Surely it no longer cares what
1622                  * error it gets back on an operation for the dead
1623                  * client.
1624                  */
1625                 return nfserr_stale_clientid;
1626         }
1627         nfsd4_create_clid_dir(cstate->session->se_client);
1628         nfs4_unlock_state();
1629         return nfs_ok;
1630 }
1631
1632 __be32
1633 nfsd4_setclientid(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
1634                   struct nfsd4_setclientid *setclid)
1635 {
1636         struct sockaddr         *sa = svc_addr(rqstp);
1637         struct xdr_netobj       clname = { 
1638                 .len = setclid->se_namelen,
1639                 .data = setclid->se_name,
1640         };
1641         nfs4_verifier           clverifier = setclid->se_verf;
1642         unsigned int            strhashval;
1643         struct nfs4_client      *conf, *unconf, *new;
1644         __be32                  status;
1645         char                    dname[HEXDIR_LEN];
1646         
1647         if (!check_name(clname))
1648                 return nfserr_inval;
1649
1650         status = nfs4_make_rec_clidname(dname, &clname);
1651         if (status)
1652                 return status;
1653
1654         /* 
1655          * XXX The Duplicate Request Cache (DRC) has been checked (??)
1656          * We get here on a DRC miss.
1657          */
1658
1659         strhashval = clientstr_hashval(dname);
1660
1661         nfs4_lock_state();
1662         conf = find_confirmed_client_by_str(dname, strhashval, false);
1663         if (conf) {
1664                 /* RFC 3530 14.2.33 CASE 0: */
1665                 status = nfserr_clid_inuse;
1666                 if (!same_creds(&conf->cl_cred, &rqstp->rq_cred)) {
1667                         char addr_str[INET6_ADDRSTRLEN];
1668                         rpc_ntop((struct sockaddr *) &conf->cl_addr, addr_str,
1669                                  sizeof(addr_str));
1670                         dprintk("NFSD: setclientid: string in use by client "
1671                                 "at %s\n", addr_str);
1672                         goto out;
1673                 }
1674         }
1675         /*
1676          * section 14.2.33 of RFC 3530 (under the heading "IMPLEMENTATION")
1677          * has a description of SETCLIENTID request processing consisting
1678          * of 5 bullet points, labeled as CASE0 - CASE4 below.
1679          */
1680         unconf = find_unconfirmed_client_by_str(dname, strhashval, false);
1681         status = nfserr_resource;
1682         if (!conf) {
1683                 /*
1684                  * RFC 3530 14.2.33 CASE 4:
1685                  * placed first, because it is the normal case
1686                  */
1687                 if (unconf)
1688                         expire_client(unconf);
1689                 new = create_client(clname, dname, rqstp, &clverifier);
1690                 if (new == NULL)
1691                         goto out;
1692                 gen_clid(new);
1693         } else if (same_verf(&conf->cl_verifier, &clverifier)) {
1694                 /*
1695                  * RFC 3530 14.2.33 CASE 1:
1696                  * probable callback update
1697                  */
1698                 if (unconf) {
1699                         /* Note this is removing unconfirmed {*x***},
1700                          * which is stronger than RFC recommended {vxc**}.
1701                          * This has the advantage that there is at most
1702                          * one {*x***} in either list at any time.
1703                          */
1704                         expire_client(unconf);
1705                 }
1706                 new = create_client(clname, dname, rqstp, &clverifier);
1707                 if (new == NULL)
1708                         goto out;
1709                 copy_clid(new, conf);
1710         } else if (!unconf) {
1711                 /*
1712                  * RFC 3530 14.2.33 CASE 2:
1713                  * probable client reboot; state will be removed if
1714                  * confirmed.
1715                  */
1716                 new = create_client(clname, dname, rqstp, &clverifier);
1717                 if (new == NULL)
1718                         goto out;
1719                 gen_clid(new);
1720         } else {
1721                 /*
1722                  * RFC 3530 14.2.33 CASE 3:
1723                  * probable client reboot; state will be removed if
1724                  * confirmed.
1725                  */
1726                 expire_client(unconf);
1727                 new = create_client(clname, dname, rqstp, &clverifier);
1728                 if (new == NULL)
1729                         goto out;
1730                 gen_clid(new);
1731         }
1732         gen_callback(new, setclid, rpc_get_scope_id(sa));
1733         add_to_unconfirmed(new, strhashval);
1734         setclid->se_clientid.cl_boot = new->cl_clientid.cl_boot;
1735         setclid->se_clientid.cl_id = new->cl_clientid.cl_id;
1736         memcpy(setclid->se_confirm.data, new->cl_confirm.data, sizeof(setclid->se_confirm.data));
1737         status = nfs_ok;
1738 out:
1739         nfs4_unlock_state();
1740         return status;
1741 }
1742
1743
1744 /*
1745  * Section 14.2.34 of RFC 3530 (under the heading "IMPLEMENTATION") has
1746  * a description of SETCLIENTID_CONFIRM request processing consisting of 4
1747  * bullets, labeled as CASE1 - CASE4 below.
1748  */
1749 __be32
1750 nfsd4_setclientid_confirm(struct svc_rqst *rqstp,
1751                          struct nfsd4_compound_state *cstate,
1752                          struct nfsd4_setclientid_confirm *setclientid_confirm)
1753 {
1754         struct sockaddr *sa = svc_addr(rqstp);
1755         struct nfs4_client *conf, *unconf;
1756         nfs4_verifier confirm = setclientid_confirm->sc_confirm; 
1757         clientid_t * clid = &setclientid_confirm->sc_clientid;
1758         __be32 status;
1759
1760         if (STALE_CLIENTID(clid))
1761                 return nfserr_stale_clientid;
1762         /* 
1763          * XXX The Duplicate Request Cache (DRC) has been checked (??)
1764          * We get here on a DRC miss.
1765          */
1766
1767         nfs4_lock_state();
1768
1769         conf = find_confirmed_client(clid);
1770         unconf = find_unconfirmed_client(clid);
1771
1772         status = nfserr_clid_inuse;
1773         if (conf && !rpc_cmp_addr((struct sockaddr *) &conf->cl_addr, sa))
1774                 goto out;
1775         if (unconf && !rpc_cmp_addr((struct sockaddr *) &unconf->cl_addr, sa))
1776                 goto out;
1777
1778         /*
1779          * section 14.2.34 of RFC 3530 has a description of
1780          * SETCLIENTID_CONFIRM request processing consisting
1781          * of 4 bullet points, labeled as CASE1 - CASE4 below.
1782          */
1783         if (conf && unconf && same_verf(&confirm, &unconf->cl_confirm)) {
1784                 /*
1785                  * RFC 3530 14.2.34 CASE 1:
1786                  * callback update
1787                  */
1788                 if (!same_creds(&conf->cl_cred, &unconf->cl_cred))
1789                         status = nfserr_clid_inuse;
1790                 else {
1791                         atomic_set(&conf->cl_cb_set, 0);
1792                         nfsd4_probe_callback(conf, &unconf->cl_cb_conn);
1793                         expire_client(unconf);
1794                         status = nfs_ok;
1795
1796                 }
1797         } else if (conf && !unconf) {
1798                 /*
1799                  * RFC 3530 14.2.34 CASE 2:
1800                  * probable retransmitted request; play it safe and
1801                  * do nothing.
1802                  */
1803                 if (!same_creds(&conf->cl_cred, &rqstp->rq_cred))
1804                         status = nfserr_clid_inuse;
1805                 else
1806                         status = nfs_ok;
1807         } else if (!conf && unconf
1808                         && same_verf(&unconf->cl_confirm, &confirm)) {
1809                 /*
1810                  * RFC 3530 14.2.34 CASE 3:
1811                  * Normal case; new or rebooted client:
1812                  */
1813                 if (!same_creds(&unconf->cl_cred, &rqstp->rq_cred)) {
1814                         status = nfserr_clid_inuse;
1815                 } else {
1816                         unsigned int hash =
1817                                 clientstr_hashval(unconf->cl_recdir);
1818                         conf = find_confirmed_client_by_str(unconf->cl_recdir,
1819                                                             hash, false);
1820                         if (conf) {
1821                                 nfsd4_remove_clid_dir(conf);
1822                                 expire_client(conf);
1823                         }
1824                         move_to_confirmed(unconf);
1825                         conf = unconf;
1826                         nfsd4_probe_callback(conf, &conf->cl_cb_conn);
1827                         status = nfs_ok;
1828                 }
1829         } else if ((!conf || (conf && !same_verf(&conf->cl_confirm, &confirm)))
1830             && (!unconf || (unconf && !same_verf(&unconf->cl_confirm,
1831                                                                 &confirm)))) {
1832                 /*
1833                  * RFC 3530 14.2.34 CASE 4:
1834                  * Client probably hasn't noticed that we rebooted yet.
1835                  */
1836                 status = nfserr_stale_clientid;
1837         } else {
1838                 /* check that we have hit one of the cases...*/
1839                 status = nfserr_clid_inuse;
1840         }
1841 out:
1842         nfs4_unlock_state();
1843         return status;
1844 }
1845
1846 /* OPEN Share state helper functions */
1847 static inline struct nfs4_file *
1848 alloc_init_file(struct inode *ino)
1849 {
1850         struct nfs4_file *fp;
1851         unsigned int hashval = file_hashval(ino);
1852
1853         fp = kmem_cache_alloc(file_slab, GFP_KERNEL);
1854         if (fp) {
1855                 atomic_set(&fp->fi_ref, 1);
1856                 INIT_LIST_HEAD(&fp->fi_hash);
1857                 INIT_LIST_HEAD(&fp->fi_stateids);
1858                 INIT_LIST_HEAD(&fp->fi_delegations);
1859                 fp->fi_inode = igrab(ino);
1860                 fp->fi_id = current_fileid++;
1861                 fp->fi_had_conflict = false;
1862                 memset(fp->fi_fds, 0, sizeof(fp->fi_fds));
1863                 memset(fp->fi_access, 0, sizeof(fp->fi_access));
1864                 spin_lock(&recall_lock);
1865                 list_add(&fp->fi_hash, &file_hashtbl[hashval]);
1866                 spin_unlock(&recall_lock);
1867                 return fp;
1868         }
1869         return NULL;
1870 }
1871
1872 static void
1873 nfsd4_free_slab(struct kmem_cache **slab)
1874 {
1875         if (*slab == NULL)
1876                 return;
1877         kmem_cache_destroy(*slab);
1878         *slab = NULL;
1879 }
1880
1881 void
1882 nfsd4_free_slabs(void)
1883 {
1884         nfsd4_free_slab(&stateowner_slab);
1885         nfsd4_free_slab(&file_slab);
1886         nfsd4_free_slab(&stateid_slab);
1887         nfsd4_free_slab(&deleg_slab);
1888 }
1889
1890 static int
1891 nfsd4_init_slabs(void)
1892 {
1893         stateowner_slab = kmem_cache_create("nfsd4_stateowners",
1894                         sizeof(struct nfs4_stateowner), 0, 0, NULL);
1895         if (stateowner_slab == NULL)
1896                 goto out_nomem;
1897         file_slab = kmem_cache_create("nfsd4_files",
1898                         sizeof(struct nfs4_file), 0, 0, NULL);
1899         if (file_slab == NULL)
1900                 goto out_nomem;
1901         stateid_slab = kmem_cache_create("nfsd4_stateids",
1902                         sizeof(struct nfs4_stateid), 0, 0, NULL);
1903         if (stateid_slab == NULL)
1904                 goto out_nomem;
1905         deleg_slab = kmem_cache_create("nfsd4_delegations",
1906                         sizeof(struct nfs4_delegation), 0, 0, NULL);
1907         if (deleg_slab == NULL)
1908                 goto out_nomem;
1909         return 0;
1910 out_nomem:
1911         nfsd4_free_slabs();
1912         dprintk("nfsd4: out of memory while initializing nfsv4\n");
1913         return -ENOMEM;
1914 }
1915
1916 void
1917 nfs4_free_stateowner(struct kref *kref)
1918 {
1919         struct nfs4_stateowner *sop =
1920                 container_of(kref, struct nfs4_stateowner, so_ref);
1921         kfree(sop->so_owner.data);
1922         kmem_cache_free(stateowner_slab, sop);
1923 }
1924
1925 static inline struct nfs4_stateowner *
1926 alloc_stateowner(struct xdr_netobj *owner)
1927 {
1928         struct nfs4_stateowner *sop;
1929
1930         if ((sop = kmem_cache_alloc(stateowner_slab, GFP_KERNEL))) {
1931                 if ((sop->so_owner.data = kmalloc(owner->len, GFP_KERNEL))) {
1932                         memcpy(sop->so_owner.data, owner->data, owner->len);
1933                         sop->so_owner.len = owner->len;
1934                         kref_init(&sop->so_ref);
1935                         return sop;
1936                 } 
1937                 kmem_cache_free(stateowner_slab, sop);
1938         }
1939         return NULL;
1940 }
1941
1942 static struct nfs4_stateowner *
1943 alloc_init_open_stateowner(unsigned int strhashval, struct nfs4_client *clp, struct nfsd4_open *open) {
1944         struct nfs4_stateowner *sop;
1945         struct nfs4_replay *rp;
1946         unsigned int idhashval;
1947
1948         if (!(sop = alloc_stateowner(&open->op_owner)))
1949                 return NULL;
1950         idhashval = ownerid_hashval(current_ownerid);
1951         INIT_LIST_HEAD(&sop->so_idhash);
1952         INIT_LIST_HEAD(&sop->so_strhash);
1953         INIT_LIST_HEAD(&sop->so_perclient);
1954         INIT_LIST_HEAD(&sop->so_stateids);
1955         INIT_LIST_HEAD(&sop->so_perstateid);  /* not used */
1956         INIT_LIST_HEAD(&sop->so_close_lru);
1957         sop->so_time = 0;
1958         list_add(&sop->so_idhash, &ownerid_hashtbl[idhashval]);
1959         list_add(&sop->so_strhash, &ownerstr_hashtbl[strhashval]);
1960         list_add(&sop->so_perclient, &clp->cl_openowners);
1961         sop->so_is_open_owner = 1;
1962         sop->so_id = current_ownerid++;
1963         sop->so_client = clp;
1964         sop->so_seqid = open->op_seqid;
1965         sop->so_confirmed = 0;
1966         rp = &sop->so_replay;
1967         rp->rp_status = nfserr_serverfault;
1968         rp->rp_buflen = 0;
1969         rp->rp_buf = rp->rp_ibuf;
1970         return sop;
1971 }
1972
1973 static inline void
1974 init_stateid(struct nfs4_stateid *stp, struct nfs4_file *fp, struct nfsd4_open *open) {
1975         struct nfs4_stateowner *sop = open->op_stateowner;
1976         unsigned int hashval = stateid_hashval(sop->so_id, fp->fi_id);
1977
1978         INIT_LIST_HEAD(&stp->st_hash);
1979         INIT_LIST_HEAD(&stp->st_perstateowner);
1980         INIT_LIST_HEAD(&stp->st_lockowners);
1981         INIT_LIST_HEAD(&stp->st_perfile);
1982         list_add(&stp->st_hash, &stateid_hashtbl[hashval]);
1983         list_add(&stp->st_perstateowner, &sop->so_stateids);
1984         list_add(&stp->st_perfile, &fp->fi_stateids);
1985         stp->st_stateowner = sop;
1986         get_nfs4_file(fp);
1987         stp->st_file = fp;
1988         stp->st_stateid.si_boot = boot_time;
1989         stp->st_stateid.si_stateownerid = sop->so_id;
1990         stp->st_stateid.si_fileid = fp->fi_id;
1991         stp->st_stateid.si_generation = 0;
1992         stp->st_access_bmap = 0;
1993         stp->st_deny_bmap = 0;
1994         __set_bit(open->op_share_access & ~NFS4_SHARE_WANT_MASK,
1995                   &stp->st_access_bmap);
1996         __set_bit(open->op_share_deny, &stp->st_deny_bmap);
1997         stp->st_openstp = NULL;
1998 }
1999
2000 static void
2001 move_to_close_lru(struct nfs4_stateowner *sop)
2002 {
2003         dprintk("NFSD: move_to_close_lru nfs4_stateowner %p\n", sop);
2004
2005         list_move_tail(&sop->so_close_lru, &close_lru);
2006         sop->so_time = get_seconds();
2007 }
2008
2009 static int
2010 same_owner_str(struct nfs4_stateowner *sop, struct xdr_netobj *owner,
2011                                                         clientid_t *clid)
2012 {
2013         return (sop->so_owner.len == owner->len) &&
2014                 0 == memcmp(sop->so_owner.data, owner->data, owner->len) &&
2015                 (sop->so_client->cl_clientid.cl_id == clid->cl_id);
2016 }
2017
2018 static struct nfs4_stateowner *
2019 find_openstateowner_str(unsigned int hashval, struct nfsd4_open *open)
2020 {
2021         struct nfs4_stateowner *so = NULL;
2022
2023         list_for_each_entry(so, &ownerstr_hashtbl[hashval], so_strhash) {
2024                 if (same_owner_str(so, &open->op_owner, &open->op_clientid))
2025                         return so;
2026         }
2027         return NULL;
2028 }
2029
2030 /* search file_hashtbl[] for file */
2031 static struct nfs4_file *
2032 find_file(struct inode *ino)
2033 {
2034         unsigned int hashval = file_hashval(ino);
2035         struct nfs4_file *fp;
2036
2037         spin_lock(&recall_lock);
2038         list_for_each_entry(fp, &file_hashtbl[hashval], fi_hash) {
2039                 if (fp->fi_inode == ino) {
2040                         get_nfs4_file(fp);
2041                         spin_unlock(&recall_lock);
2042                         return fp;
2043                 }
2044         }
2045         spin_unlock(&recall_lock);
2046         return NULL;
2047 }
2048
2049 static inline int access_valid(u32 x, u32 minorversion)
2050 {
2051         if ((x & NFS4_SHARE_ACCESS_MASK) < NFS4_SHARE_ACCESS_READ)
2052                 return 0;
2053         if ((x & NFS4_SHARE_ACCESS_MASK) > NFS4_SHARE_ACCESS_BOTH)
2054                 return 0;
2055         x &= ~NFS4_SHARE_ACCESS_MASK;
2056         if (minorversion && x) {
2057                 if ((x & NFS4_SHARE_WANT_MASK) > NFS4_SHARE_WANT_CANCEL)
2058                         return 0;
2059                 if ((x & NFS4_SHARE_WHEN_MASK) > NFS4_SHARE_PUSH_DELEG_WHEN_UNCONTENDED)
2060                         return 0;
2061                 x &= ~(NFS4_SHARE_WANT_MASK | NFS4_SHARE_WHEN_MASK);
2062         }
2063         if (x)
2064                 return 0;
2065         return 1;
2066 }
2067
2068 static inline int deny_valid(u32 x)
2069 {
2070         /* Note: unlike access bits, deny bits may be zero. */
2071         return x <= NFS4_SHARE_DENY_BOTH;
2072 }
2073
2074 /*
2075  * Called to check deny when READ with all zero stateid or
2076  * WRITE with all zero or all one stateid
2077  */
2078 static __be32
2079 nfs4_share_conflict(struct svc_fh *current_fh, unsigned int deny_type)
2080 {
2081         struct inode *ino = current_fh->fh_dentry->d_inode;
2082         struct nfs4_file *fp;
2083         struct nfs4_stateid *stp;
2084         __be32 ret;
2085
2086         dprintk("NFSD: nfs4_share_conflict\n");
2087
2088         fp = find_file(ino);
2089         if (!fp)
2090                 return nfs_ok;
2091         ret = nfserr_locked;
2092         /* Search for conflicting share reservations */
2093         list_for_each_entry(stp, &fp->fi_stateids, st_perfile) {
2094                 if (test_bit(deny_type, &stp->st_deny_bmap) ||
2095                     test_bit(NFS4_SHARE_DENY_BOTH, &stp->st_deny_bmap))
2096                         goto out;
2097         }
2098         ret = nfs_ok;
2099 out:
2100         put_nfs4_file(fp);
2101         return ret;
2102 }
2103
2104 static inline void
2105 nfs4_file_downgrade(struct nfs4_file *fp, unsigned int share_access)
2106 {
2107         if (share_access & NFS4_SHARE_ACCESS_WRITE)
2108                 nfs4_file_put_access(fp, O_WRONLY);
2109         if (share_access & NFS4_SHARE_ACCESS_READ)
2110                 nfs4_file_put_access(fp, O_RDONLY);
2111 }
2112
2113 /*
2114  * Spawn a thread to perform a recall on the delegation represented
2115  * by the lease (file_lock)
2116  *
2117  * Called from break_lease() with lock_kernel() held.
2118  * Note: we assume break_lease will only call this *once* for any given
2119  * lease.
2120  */
2121 static
2122 void nfsd_break_deleg_cb(struct file_lock *fl)
2123 {
2124         struct nfs4_delegation *dp = (struct nfs4_delegation *)fl->fl_owner;
2125
2126         dprintk("NFSD nfsd_break_deleg_cb: dp %p fl %p\n",dp,fl);
2127         if (!dp)
2128                 return;
2129
2130         /* We're assuming the state code never drops its reference
2131          * without first removing the lease.  Since we're in this lease
2132          * callback (and since the lease code is serialized by the kernel
2133          * lock) we know the server hasn't removed the lease yet, we know
2134          * it's safe to take a reference: */
2135         atomic_inc(&dp->dl_count);
2136
2137         spin_lock(&recall_lock);
2138         list_add_tail(&dp->dl_recall_lru, &del_recall_lru);
2139         spin_unlock(&recall_lock);
2140
2141         /* only place dl_time is set. protected by lock_kernel*/
2142         dp->dl_time = get_seconds();
2143
2144         /*
2145          * We don't want the locks code to timeout the lease for us;
2146          * we'll remove it ourself if the delegation isn't returned
2147          * in time.
2148          */
2149         fl->fl_break_time = 0;
2150
2151         dp->dl_file->fi_had_conflict = true;
2152         nfsd4_cb_recall(dp);
2153 }
2154
2155 /*
2156  * The file_lock is being reapd.
2157  *
2158  * Called by locks_free_lock() with lock_kernel() held.
2159  */
2160 static
2161 void nfsd_release_deleg_cb(struct file_lock *fl)
2162 {
2163         struct nfs4_delegation *dp = (struct nfs4_delegation *)fl->fl_owner;
2164
2165         dprintk("NFSD nfsd_release_deleg_cb: fl %p dp %p dl_count %d\n", fl,dp, atomic_read(&dp->dl_count));
2166
2167         if (!(fl->fl_flags & FL_LEASE) || !dp)
2168                 return;
2169         dp->dl_flock = NULL;
2170 }
2171
2172 /*
2173  * Set the delegation file_lock back pointer.
2174  *
2175  * Called from setlease() with lock_kernel() held.
2176  */
2177 static
2178 void nfsd_copy_lock_deleg_cb(struct file_lock *new, struct file_lock *fl)
2179 {
2180         struct nfs4_delegation *dp = (struct nfs4_delegation *)new->fl_owner;
2181
2182         dprintk("NFSD: nfsd_copy_lock_deleg_cb: new fl %p dp %p\n", new, dp);
2183         if (!dp)
2184                 return;
2185         dp->dl_flock = new;
2186 }
2187
2188 /*
2189  * Called from setlease() with lock_kernel() held
2190  */
2191 static
2192 int nfsd_same_client_deleg_cb(struct file_lock *onlist, struct file_lock *try)
2193 {
2194         struct nfs4_delegation *onlistd =
2195                 (struct nfs4_delegation *)onlist->fl_owner;
2196         struct nfs4_delegation *tryd =
2197                 (struct nfs4_delegation *)try->fl_owner;
2198
2199         if (onlist->fl_lmops != try->fl_lmops)
2200                 return 0;
2201
2202         return onlistd->dl_client == tryd->dl_client;
2203 }
2204
2205
2206 static
2207 int nfsd_change_deleg_cb(struct file_lock **onlist, int arg)
2208 {
2209         if (arg & F_UNLCK)
2210                 return lease_modify(onlist, arg);
2211         else
2212                 return -EAGAIN;
2213 }
2214
2215 static const struct lock_manager_operations nfsd_lease_mng_ops = {
2216         .fl_break = nfsd_break_deleg_cb,
2217         .fl_release_private = nfsd_release_deleg_cb,
2218         .fl_copy_lock = nfsd_copy_lock_deleg_cb,
2219         .fl_mylease = nfsd_same_client_deleg_cb,
2220         .fl_change = nfsd_change_deleg_cb,
2221 };
2222
2223
2224 __be32
2225 nfsd4_process_open1(struct nfsd4_compound_state *cstate,
2226                     struct nfsd4_open *open)
2227 {
2228         clientid_t *clientid = &open->op_clientid;
2229         struct nfs4_client *clp = NULL;
2230         unsigned int strhashval;
2231         struct nfs4_stateowner *sop = NULL;
2232
2233         if (!check_name(open->op_owner))
2234                 return nfserr_inval;
2235
2236         if (STALE_CLIENTID(&open->op_clientid))
2237                 return nfserr_stale_clientid;
2238
2239         strhashval = ownerstr_hashval(clientid->cl_id, open->op_owner);
2240         sop = find_openstateowner_str(strhashval, open);
2241         open->op_stateowner = sop;
2242         if (!sop) {
2243                 /* Make sure the client's lease hasn't expired. */
2244                 clp = find_confirmed_client(clientid);
2245                 if (clp == NULL)
2246                         return nfserr_expired;
2247                 goto renew;
2248         }
2249         /* When sessions are used, skip open sequenceid processing */
2250         if (nfsd4_has_session(cstate))
2251                 goto renew;
2252         if (!sop->so_confirmed) {
2253                 /* Replace unconfirmed owners without checking for replay. */
2254                 clp = sop->so_client;
2255                 release_openowner(sop);
2256                 open->op_stateowner = NULL;
2257                 goto renew;
2258         }
2259         if (open->op_seqid == sop->so_seqid - 1) {
2260                 if (sop->so_replay.rp_buflen)
2261                         return nfserr_replay_me;
2262                 /* The original OPEN failed so spectacularly
2263                  * that we don't even have replay data saved!
2264                  * Therefore, we have no choice but to continue
2265                  * processing this OPEN; presumably, we'll
2266                  * fail again for the same reason.
2267                  */
2268                 dprintk("nfsd4_process_open1: replay with no replay cache\n");
2269                 goto renew;
2270         }
2271         if (open->op_seqid != sop->so_seqid)
2272                 return nfserr_bad_seqid;
2273 renew:
2274         if (open->op_stateowner == NULL) {
2275                 sop = alloc_init_open_stateowner(strhashval, clp, open);
2276                 if (sop == NULL)
2277                         return nfserr_resource;
2278                 open->op_stateowner = sop;
2279         }
2280         list_del_init(&sop->so_close_lru);
2281         renew_client(sop->so_client);
2282         return nfs_ok;
2283 }
2284
2285 static inline __be32
2286 nfs4_check_delegmode(struct nfs4_delegation *dp, int flags)
2287 {
2288         if ((flags & WR_STATE) && (dp->dl_type == NFS4_OPEN_DELEGATE_READ))
2289                 return nfserr_openmode;
2290         else
2291                 return nfs_ok;
2292 }
2293
2294 static struct nfs4_delegation *
2295 find_delegation_file(struct nfs4_file *fp, stateid_t *stid)
2296 {
2297         struct nfs4_delegation *dp;
2298
2299         list_for_each_entry(dp, &fp->fi_delegations, dl_perfile) {
2300                 if (dp->dl_stateid.si_stateownerid == stid->si_stateownerid)
2301                         return dp;
2302         }
2303         return NULL;
2304 }
2305
2306 int share_access_to_flags(u32 share_access)
2307 {
2308         share_access &= ~NFS4_SHARE_WANT_MASK;
2309
2310         return share_access == NFS4_SHARE_ACCESS_READ ? RD_STATE : WR_STATE;
2311 }
2312
2313 static __be32
2314 nfs4_check_deleg(struct nfs4_file *fp, struct nfsd4_open *open,
2315                 struct nfs4_delegation **dp)
2316 {
2317         int flags;
2318         __be32 status = nfserr_bad_stateid;
2319
2320         *dp = find_delegation_file(fp, &open->op_delegate_stateid);
2321         if (*dp == NULL)
2322                 goto out;
2323         flags = share_access_to_flags(open->op_share_access);
2324         status = nfs4_check_delegmode(*dp, flags);
2325         if (status)
2326                 *dp = NULL;
2327 out:
2328         if (open->op_claim_type != NFS4_OPEN_CLAIM_DELEGATE_CUR)
2329                 return nfs_ok;
2330         if (status)
2331                 return status;
2332         open->op_stateowner->so_confirmed = 1;
2333         return nfs_ok;
2334 }
2335
2336 static __be32
2337 nfs4_check_open(struct nfs4_file *fp, struct nfsd4_open *open, struct nfs4_stateid **stpp)
2338 {
2339         struct nfs4_stateid *local;
2340         __be32 status = nfserr_share_denied;
2341         struct nfs4_stateowner *sop = open->op_stateowner;
2342
2343         list_for_each_entry(local, &fp->fi_stateids, st_perfile) {
2344                 /* ignore lock owners */
2345                 if (local->st_stateowner->so_is_open_owner == 0)
2346                         continue;
2347                 /* remember if we have seen this open owner */
2348                 if (local->st_stateowner == sop)
2349                         *stpp = local;
2350                 /* check for conflicting share reservations */
2351                 if (!test_share(local, open))
2352                         goto out;
2353         }
2354         status = 0;
2355 out:
2356         return status;
2357 }
2358
2359 static inline struct nfs4_stateid *
2360 nfs4_alloc_stateid(void)
2361 {
2362         return kmem_cache_alloc(stateid_slab, GFP_KERNEL);
2363 }
2364
2365 static inline int nfs4_access_to_access(u32 nfs4_access)
2366 {
2367         int flags = 0;
2368
2369         if (nfs4_access & NFS4_SHARE_ACCESS_READ)
2370                 flags |= NFSD_MAY_READ;
2371         if (nfs4_access & NFS4_SHARE_ACCESS_WRITE)
2372                 flags |= NFSD_MAY_WRITE;
2373         return flags;
2374 }
2375
2376 static __be32 nfs4_get_vfs_file(struct svc_rqst *rqstp, struct nfs4_file
2377 *fp, struct svc_fh *cur_fh, u32 nfs4_access)
2378 {
2379         __be32 status;
2380         int oflag = nfs4_access_to_omode(nfs4_access);
2381         int access = nfs4_access_to_access(nfs4_access);
2382
2383         if (!fp->fi_fds[oflag]) {
2384                 status = nfsd_open(rqstp, cur_fh, S_IFREG, access,
2385                         &fp->fi_fds[oflag]);
2386                 if (status == nfserr_dropit)
2387                         status = nfserr_jukebox;
2388                 if (status)
2389                         return status;
2390         }
2391         nfs4_file_get_access(fp, oflag);
2392
2393         return nfs_ok;
2394 }
2395
2396 static __be32
2397 nfs4_new_open(struct svc_rqst *rqstp, struct nfs4_stateid **stpp,
2398                 struct nfs4_file *fp, struct svc_fh *cur_fh,
2399                 struct nfsd4_open *open)
2400 {
2401         struct nfs4_stateid *stp;
2402         __be32 status;
2403
2404         stp = nfs4_alloc_stateid();
2405         if (stp == NULL)
2406                 return nfserr_resource;
2407
2408         status = nfs4_get_vfs_file(rqstp, fp, cur_fh, open->op_share_access);
2409         if (status) {
2410                 kmem_cache_free(stateid_slab, stp);
2411                 return status;
2412         }
2413         *stpp = stp;
2414         return 0;
2415 }
2416
2417 static inline __be32
2418 nfsd4_truncate(struct svc_rqst *rqstp, struct svc_fh *fh,
2419                 struct nfsd4_open *open)
2420 {
2421         struct iattr iattr = {
2422                 .ia_valid = ATTR_SIZE,
2423                 .ia_size = 0,
2424         };
2425         if (!open->op_truncate)
2426                 return 0;
2427         if (!(open->op_share_access & NFS4_SHARE_ACCESS_WRITE))
2428                 return nfserr_inval;
2429         return nfsd_setattr(rqstp, fh, &iattr, 0, (time_t)0);
2430 }
2431
2432 static __be32
2433 nfs4_upgrade_open(struct svc_rqst *rqstp, struct nfs4_file *fp, struct svc_fh *cur_fh, struct nfs4_stateid *stp, struct nfsd4_open *open)
2434 {
2435         u32 op_share_access, new_access;
2436         __be32 status;
2437
2438         set_access(&new_access, stp->st_access_bmap);
2439         new_access = (~new_access) & open->op_share_access & ~NFS4_SHARE_WANT_MASK;
2440
2441         if (new_access) {
2442                 status = nfs4_get_vfs_file(rqstp, fp, cur_fh, new_access);
2443                 if (status)
2444                         return status;
2445         }
2446         status = nfsd4_truncate(rqstp, cur_fh, open);
2447         if (status) {
2448                 if (new_access) {
2449                         int oflag = nfs4_access_to_omode(new_access);
2450                         nfs4_file_put_access(fp, oflag);
2451                 }
2452                 return status;
2453         }
2454         /* remember the open */
2455         op_share_access = open->op_share_access & ~NFS4_SHARE_WANT_MASK;
2456         __set_bit(op_share_access, &stp->st_access_bmap);
2457         __set_bit(open->op_share_deny, &stp->st_deny_bmap);
2458
2459         return nfs_ok;
2460 }
2461
2462
2463 static void
2464 nfs4_set_claim_prev(struct nfsd4_open *open)
2465 {
2466         open->op_stateowner->so_confirmed = 1;
2467         open->op_stateowner->so_client->cl_firststate = 1;
2468 }
2469
2470 /*
2471  * Attempt to hand out a delegation.
2472  */
2473 static void
2474 nfs4_open_delegation(struct svc_fh *fh, struct nfsd4_open *open, struct nfs4_stateid *stp)
2475 {
2476         struct nfs4_delegation *dp;
2477         struct nfs4_stateowner *sop = stp->st_stateowner;
2478         int cb_up = atomic_read(&sop->so_client->cl_cb_set);
2479         struct file_lock fl, *flp = &fl;
2480         int status, flag = 0;
2481
2482         flag = NFS4_OPEN_DELEGATE_NONE;
2483         open->op_recall = 0;
2484         switch (open->op_claim_type) {
2485                 case NFS4_OPEN_CLAIM_PREVIOUS:
2486                         if (!cb_up)
2487                                 open->op_recall = 1;
2488                         flag = open->op_delegate_type;
2489                         if (flag == NFS4_OPEN_DELEGATE_NONE)
2490                                 goto out;
2491                         break;
2492                 case NFS4_OPEN_CLAIM_NULL:
2493                         /* Let's not give out any delegations till everyone's
2494                          * had the chance to reclaim theirs.... */
2495                         if (locks_in_grace())
2496                                 goto out;
2497                         if (!cb_up || !sop->so_confirmed)
2498                                 goto out;
2499                         if (open->op_share_access & NFS4_SHARE_ACCESS_WRITE)
2500                                 flag = NFS4_OPEN_DELEGATE_WRITE;
2501                         else
2502                                 flag = NFS4_OPEN_DELEGATE_READ;
2503                         break;
2504                 default:
2505                         goto out;
2506         }
2507
2508         dp = alloc_init_deleg(sop->so_client, stp, fh, flag);
2509         if (dp == NULL) {
2510                 flag = NFS4_OPEN_DELEGATE_NONE;
2511                 goto out;
2512         }
2513         locks_init_lock(&fl);
2514         fl.fl_lmops = &nfsd_lease_mng_ops;
2515         fl.fl_flags = FL_LEASE;
2516         fl.fl_type = flag == NFS4_OPEN_DELEGATE_READ? F_RDLCK: F_WRLCK;
2517         fl.fl_end = OFFSET_MAX;
2518         fl.fl_owner =  (fl_owner_t)dp;
2519         fl.fl_file = find_readable_file(stp->st_file);
2520         BUG_ON(!fl.fl_file);
2521         fl.fl_pid = current->tgid;
2522
2523         /* vfs_setlease checks to see if delegation should be handed out.
2524          * the lock_manager callbacks fl_mylease and fl_change are used
2525          */
2526         if ((status = vfs_setlease(fl.fl_file, fl.fl_type, &flp))) {
2527                 dprintk("NFSD: setlease failed [%d], no delegation\n", status);
2528                 unhash_delegation(dp);
2529                 flag = NFS4_OPEN_DELEGATE_NONE;
2530                 goto out;
2531         }
2532
2533         memcpy(&open->op_delegate_stateid, &dp->dl_stateid, sizeof(dp->dl_stateid));
2534
2535         dprintk("NFSD: delegation stateid=" STATEID_FMT "\n",
2536                 STATEID_VAL(&dp->dl_stateid));
2537 out:
2538         if (open->op_claim_type == NFS4_OPEN_CLAIM_PREVIOUS
2539                         && flag == NFS4_OPEN_DELEGATE_NONE
2540                         && open->op_delegate_type != NFS4_OPEN_DELEGATE_NONE)
2541                 dprintk("NFSD: WARNING: refusing delegation reclaim\n");
2542         open->op_delegate_type = flag;
2543 }
2544
2545 /*
2546  * called with nfs4_lock_state() held.
2547  */
2548 __be32
2549 nfsd4_process_open2(struct svc_rqst *rqstp, struct svc_fh *current_fh, struct nfsd4_open *open)
2550 {
2551         struct nfsd4_compoundres *resp = rqstp->rq_resp;
2552         struct nfs4_file *fp = NULL;
2553         struct inode *ino = current_fh->fh_dentry->d_inode;
2554         struct nfs4_stateid *stp = NULL;
2555         struct nfs4_delegation *dp = NULL;
2556         __be32 status;
2557
2558         status = nfserr_inval;
2559         if (!access_valid(open->op_share_access, resp->cstate.minorversion)
2560                         || !deny_valid(open->op_share_deny))
2561                 goto out;
2562         /*
2563          * Lookup file; if found, lookup stateid and check open request,
2564          * and check for delegations in the process of being recalled.
2565          * If not found, create the nfs4_file struct
2566          */
2567         fp = find_file(ino);
2568         if (fp) {
2569                 if ((status = nfs4_check_open(fp, open, &stp)))
2570                         goto out;
2571                 status = nfs4_check_deleg(fp, open, &dp);
2572                 if (status)
2573                         goto out;
2574         } else {
2575                 status = nfserr_bad_stateid;
2576                 if (open->op_claim_type == NFS4_OPEN_CLAIM_DELEGATE_CUR)
2577                         goto out;
2578                 status = nfserr_resource;
2579                 fp = alloc_init_file(ino);
2580                 if (fp == NULL)
2581                         goto out;
2582         }
2583
2584         /*
2585          * OPEN the file, or upgrade an existing OPEN.
2586          * If truncate fails, the OPEN fails.
2587          */
2588         if (stp) {
2589                 /* Stateid was found, this is an OPEN upgrade */
2590                 status = nfs4_upgrade_open(rqstp, fp, current_fh, stp, open);
2591                 if (status)
2592                         goto out;
2593                 update_stateid(&stp->st_stateid);
2594         } else {
2595                 status = nfs4_new_open(rqstp, &stp, fp, current_fh, open);
2596                 if (status)
2597                         goto out;
2598                 init_stateid(stp, fp, open);
2599                 status = nfsd4_truncate(rqstp, current_fh, open);
2600                 if (status) {
2601                         release_open_stateid(stp);
2602                         goto out;
2603                 }
2604                 if (nfsd4_has_session(&resp->cstate))
2605                         update_stateid(&stp->st_stateid);
2606         }
2607         memcpy(&open->op_stateid, &stp->st_stateid, sizeof(stateid_t));
2608
2609         if (nfsd4_has_session(&resp->cstate))
2610                 open->op_stateowner->so_confirmed = 1;
2611
2612         /*
2613         * Attempt to hand out a delegation. No error return, because the
2614         * OPEN succeeds even if we fail.
2615         */
2616         nfs4_open_delegation(current_fh, open, stp);
2617
2618         status = nfs_ok;
2619
2620         dprintk("%s: stateid=" STATEID_FMT "\n", __func__,
2621                 STATEID_VAL(&stp->st_stateid));
2622 out:
2623         if (fp)
2624                 put_nfs4_file(fp);
2625         if (status == 0 && open->op_claim_type == NFS4_OPEN_CLAIM_PREVIOUS)
2626                 nfs4_set_claim_prev(open);
2627         /*
2628         * To finish the open response, we just need to set the rflags.
2629         */
2630         open->op_rflags = NFS4_OPEN_RESULT_LOCKTYPE_POSIX;
2631         if (!open->op_stateowner->so_confirmed &&
2632             !nfsd4_has_session(&resp->cstate))
2633                 open->op_rflags |= NFS4_OPEN_RESULT_CONFIRM;
2634
2635         return status;
2636 }
2637
2638 __be32
2639 nfsd4_renew(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
2640             clientid_t *clid)
2641 {
2642         struct nfs4_client *clp;
2643         __be32 status;
2644
2645         nfs4_lock_state();
2646         dprintk("process_renew(%08x/%08x): starting\n", 
2647                         clid->cl_boot, clid->cl_id);
2648         status = nfserr_stale_clientid;
2649         if (STALE_CLIENTID(clid))
2650                 goto out;
2651         clp = find_confirmed_client(clid);
2652         status = nfserr_expired;
2653         if (clp == NULL) {
2654                 /* We assume the client took too long to RENEW. */
2655                 dprintk("nfsd4_renew: clientid not found!\n");
2656                 goto out;
2657         }
2658         renew_client(clp);
2659         status = nfserr_cb_path_down;
2660         if (!list_empty(&clp->cl_delegations)
2661                         && !atomic_read(&clp->cl_cb_set))
2662                 goto out;
2663         status = nfs_ok;
2664 out:
2665         nfs4_unlock_state();
2666         return status;
2667 }
2668
2669 struct lock_manager nfsd4_manager = {
2670 };
2671
2672 static void
2673 nfsd4_end_grace(void)
2674 {
2675         dprintk("NFSD: end of grace period\n");
2676         nfsd4_recdir_purge_old();
2677         locks_end_grace(&nfsd4_manager);
2678         /*
2679          * Now that every NFSv4 client has had the chance to recover and
2680          * to see the (possibly new, possibly shorter) lease time, we
2681          * can safely set the next grace time to the current lease time:
2682          */
2683         nfsd4_grace = nfsd4_lease;
2684 }
2685
2686 static time_t
2687 nfs4_laundromat(void)
2688 {
2689         struct nfs4_client *clp;
2690         struct nfs4_stateowner *sop;
2691         struct nfs4_delegation *dp;
2692         struct list_head *pos, *next, reaplist;
2693         time_t cutoff = get_seconds() - nfsd4_lease;
2694         time_t t, clientid_val = nfsd4_lease;
2695         time_t u, test_val = nfsd4_lease;
2696
2697         nfs4_lock_state();
2698
2699         dprintk("NFSD: laundromat service - starting\n");
2700         if (locks_in_grace())
2701                 nfsd4_end_grace();
2702         INIT_LIST_HEAD(&reaplist);
2703         spin_lock(&client_lock);
2704         list_for_each_safe(pos, next, &client_lru) {
2705                 clp = list_entry(pos, struct nfs4_client, cl_lru);
2706                 if (time_after((unsigned long)clp->cl_time, (unsigned long)cutoff)) {
2707                         t = clp->cl_time - cutoff;
2708                         if (clientid_val > t)
2709                                 clientid_val = t;
2710                         break;
2711                 }
2712                 if (atomic_read(&clp->cl_refcount)) {
2713                         dprintk("NFSD: client in use (clientid %08x)\n",
2714                                 clp->cl_clientid.cl_id);
2715                         continue;
2716                 }
2717                 unhash_client_locked(clp);
2718                 list_add(&clp->cl_lru, &reaplist);
2719         }
2720         spin_unlock(&client_lock);
2721         list_for_each_safe(pos, next, &reaplist) {
2722                 clp = list_entry(pos, struct nfs4_client, cl_lru);
2723                 dprintk("NFSD: purging unused client (clientid %08x)\n",
2724                         clp->cl_clientid.cl_id);
2725                 nfsd4_remove_clid_dir(clp);
2726                 expire_client(clp);
2727         }
2728         spin_lock(&recall_lock);
2729         list_for_each_safe(pos, next, &del_recall_lru) {
2730                 dp = list_entry (pos, struct nfs4_delegation, dl_recall_lru);
2731                 if (time_after((unsigned long)dp->dl_time, (unsigned long)cutoff)) {
2732                         u = dp->dl_time - cutoff;
2733                         if (test_val > u)
2734                                 test_val = u;
2735                         break;
2736                 }
2737                 dprintk("NFSD: purging unused delegation dp %p, fp %p\n",
2738                                     dp, dp->dl_flock);
2739                 list_move(&dp->dl_recall_lru, &reaplist);
2740         }
2741         spin_unlock(&recall_lock);
2742         list_for_each_safe(pos, next, &reaplist) {
2743                 dp = list_entry (pos, struct nfs4_delegation, dl_recall_lru);
2744                 list_del_init(&dp->dl_recall_lru);
2745                 unhash_delegation(dp);
2746         }
2747         test_val = nfsd4_lease;
2748         list_for_each_safe(pos, next, &close_lru) {
2749                 sop = list_entry(pos, struct nfs4_stateowner, so_close_lru);
2750                 if (time_after((unsigned long)sop->so_time, (unsigned long)cutoff)) {
2751                         u = sop->so_time - cutoff;
2752                         if (test_val > u)
2753                                 test_val = u;
2754                         break;
2755                 }
2756                 dprintk("NFSD: purging unused open stateowner (so_id %d)\n",
2757                         sop->so_id);
2758                 release_openowner(sop);
2759         }
2760         if (clientid_val < NFSD_LAUNDROMAT_MINTIMEOUT)
2761                 clientid_val = NFSD_LAUNDROMAT_MINTIMEOUT;
2762         nfs4_unlock_state();
2763         return clientid_val;
2764 }
2765
2766 static struct workqueue_struct *laundry_wq;
2767 static void laundromat_main(struct work_struct *);
2768 static DECLARE_DELAYED_WORK(laundromat_work, laundromat_main);
2769
2770 static void
2771 laundromat_main(struct work_struct *not_used)
2772 {
2773         time_t t;
2774
2775         t = nfs4_laundromat();
2776         dprintk("NFSD: laundromat_main - sleeping for %ld seconds\n", t);
2777         queue_delayed_work(laundry_wq, &laundromat_work, t*HZ);
2778 }
2779
2780 static struct nfs4_stateowner *
2781 search_close_lru(u32 st_id, int flags)
2782 {
2783         struct nfs4_stateowner *local = NULL;
2784
2785         if (flags & CLOSE_STATE) {
2786                 list_for_each_entry(local, &close_lru, so_close_lru) {
2787                         if (local->so_id == st_id)
2788                                 return local;
2789                 }
2790         }
2791         return NULL;
2792 }
2793
2794 static inline int
2795 nfs4_check_fh(struct svc_fh *fhp, struct nfs4_stateid *stp)
2796 {
2797         return fhp->fh_dentry->d_inode != stp->st_file->fi_inode;
2798 }
2799
2800 static int
2801 STALE_STATEID(stateid_t *stateid)
2802 {
2803         if (stateid->si_boot == boot_time)
2804                 return 0;
2805         dprintk("NFSD: stale stateid " STATEID_FMT "!\n",
2806                 STATEID_VAL(stateid));
2807         return 1;
2808 }
2809
2810 static inline int
2811 access_permit_read(unsigned long access_bmap)
2812 {
2813         return test_bit(NFS4_SHARE_ACCESS_READ, &access_bmap) ||
2814                 test_bit(NFS4_SHARE_ACCESS_BOTH, &access_bmap) ||
2815                 test_bit(NFS4_SHARE_ACCESS_WRITE, &access_bmap);
2816 }
2817
2818 static inline int
2819 access_permit_write(unsigned long access_bmap)
2820 {
2821         return test_bit(NFS4_SHARE_ACCESS_WRITE, &access_bmap) ||
2822                 test_bit(NFS4_SHARE_ACCESS_BOTH, &access_bmap);
2823 }
2824
2825 static
2826 __be32 nfs4_check_openmode(struct nfs4_stateid *stp, int flags)
2827 {
2828         __be32 status = nfserr_openmode;
2829
2830         /* For lock stateid's, we test the parent open, not the lock: */
2831         if (stp->st_openstp)
2832                 stp = stp->st_openstp;
2833         if ((flags & WR_STATE) && (!access_permit_write(stp->st_access_bmap)))
2834                 goto out;
2835         if ((flags & RD_STATE) && (!access_permit_read(stp->st_access_bmap)))
2836                 goto out;
2837         status = nfs_ok;
2838 out:
2839         return status;
2840 }
2841
2842 static inline __be32
2843 check_special_stateids(svc_fh *current_fh, stateid_t *stateid, int flags)
2844 {
2845         if (ONE_STATEID(stateid) && (flags & RD_STATE))
2846                 return nfs_ok;
2847         else if (locks_in_grace()) {
2848                 /* Answer in remaining cases depends on existance of
2849                  * conflicting state; so we must wait out the grace period. */
2850                 return nfserr_grace;
2851         } else if (flags & WR_STATE)
2852                 return nfs4_share_conflict(current_fh,
2853                                 NFS4_SHARE_DENY_WRITE);
2854         else /* (flags & RD_STATE) && ZERO_STATEID(stateid) */
2855                 return nfs4_share_conflict(current_fh,
2856                                 NFS4_SHARE_DENY_READ);
2857 }
2858
2859 /*
2860  * Allow READ/WRITE during grace period on recovered state only for files
2861  * that are not able to provide mandatory locking.
2862  */
2863 static inline int
2864 grace_disallows_io(struct inode *inode)
2865 {
2866         return locks_in_grace() && mandatory_lock(inode);
2867 }
2868
2869 static int check_stateid_generation(stateid_t *in, stateid_t *ref, int flags)
2870 {
2871         /*
2872          * When sessions are used the stateid generation number is ignored
2873          * when it is zero.
2874          */
2875         if ((flags & HAS_SESSION) && in->si_generation == 0)
2876                 goto out;
2877
2878         /* If the client sends us a stateid from the future, it's buggy: */
2879         if (in->si_generation > ref->si_generation)
2880                 return nfserr_bad_stateid;
2881         /*
2882          * The following, however, can happen.  For example, if the
2883          * client sends an open and some IO at the same time, the open
2884          * may bump si_generation while the IO is still in flight.
2885          * Thanks to hard links and renames, the client never knows what
2886          * file an open will affect.  So it could avoid that situation
2887          * only by serializing all opens and IO from the same open
2888          * owner.  To recover from the old_stateid error, the client
2889          * will just have to retry the IO:
2890          */
2891         if (in->si_generation < ref->si_generation)
2892                 return nfserr_old_stateid;
2893 out:
2894         return nfs_ok;
2895 }
2896
2897 static int is_delegation_stateid(stateid_t *stateid)
2898 {
2899         return stateid->si_fileid == 0;
2900 }
2901
2902 /*
2903 * Checks for stateid operations
2904 */
2905 __be32
2906 nfs4_preprocess_stateid_op(struct nfsd4_compound_state *cstate,
2907                            stateid_t *stateid, int flags, struct file **filpp)
2908 {
2909         struct nfs4_stateid *stp = NULL;
2910         struct nfs4_delegation *dp = NULL;
2911         struct svc_fh *current_fh = &cstate->current_fh;
2912         struct inode *ino = current_fh->fh_dentry->d_inode;
2913         __be32 status;
2914
2915         if (filpp)
2916                 *filpp = NULL;
2917
2918         if (grace_disallows_io(ino))
2919                 return nfserr_grace;
2920
2921         if (nfsd4_has_session(cstate))
2922                 flags |= HAS_SESSION;
2923
2924         if (ZERO_STATEID(stateid) || ONE_STATEID(stateid))
2925                 return check_special_stateids(current_fh, stateid, flags);
2926
2927         status = nfserr_stale_stateid;
2928         if (STALE_STATEID(stateid)) 
2929                 goto out;
2930
2931         status = nfserr_bad_stateid;
2932         if (is_delegation_stateid(stateid)) {
2933                 dp = find_delegation_stateid(ino, stateid);
2934                 if (!dp)
2935                         goto out;
2936                 status = check_stateid_generation(stateid, &dp->dl_stateid,
2937                                                   flags);
2938                 if (status)
2939                         goto out;
2940                 status = nfs4_check_delegmode(dp, flags);
2941                 if (status)
2942                         goto out;
2943                 renew_client(dp->dl_client);
2944                 if (filpp)
2945                         *filpp = find_readable_file(dp->dl_file);
2946                 BUG_ON(!*filpp);
2947         } else { /* open or lock stateid */
2948                 stp = find_stateid(stateid, flags);
2949                 if (!stp)
2950                         goto out;
2951                 if (nfs4_check_fh(current_fh, stp))
2952                         goto out;
2953                 if (!stp->st_stateowner->so_confirmed)
2954                         goto out;
2955                 status = check_stateid_generation(stateid, &stp->st_stateid,
2956                                                   flags);
2957                 if (status)
2958                         goto out;
2959                 status = nfs4_check_openmode(stp, flags);
2960                 if (status)
2961                         goto out;
2962                 renew_client(stp->st_stateowner->so_client);
2963                 if (filpp) {
2964                         if (flags & RD_STATE)
2965                                 *filpp = find_readable_file(stp->st_file);
2966                         else
2967                                 *filpp = find_writeable_file(stp->st_file);
2968                         BUG_ON(!*filpp); /* assured by check_openmode */
2969                 }
2970         }
2971         status = nfs_ok;
2972 out:
2973         return status;
2974 }
2975
2976 static inline int
2977 setlkflg (int type)
2978 {
2979         return (type == NFS4_READW_LT || type == NFS4_READ_LT) ?
2980                 RD_STATE : WR_STATE;
2981 }
2982
2983 /* 
2984  * Checks for sequence id mutating operations. 
2985  */
2986 static __be32
2987 nfs4_preprocess_seqid_op(struct nfsd4_compound_state *cstate, u32 seqid,
2988                          stateid_t *stateid, int flags,
2989                          struct nfs4_stateowner **sopp,
2990                          struct nfs4_stateid **stpp, struct nfsd4_lock *lock)
2991 {
2992         struct nfs4_stateid *stp;
2993         struct nfs4_stateowner *sop;
2994         struct svc_fh *current_fh = &cstate->current_fh;
2995         __be32 status;
2996
2997         dprintk("NFSD: %s: seqid=%d stateid = " STATEID_FMT "\n", __func__,
2998                 seqid, STATEID_VAL(stateid));
2999
3000         *stpp = NULL;
3001         *sopp = NULL;
3002
3003         if (ZERO_STATEID(stateid) || ONE_STATEID(stateid)) {
3004                 dprintk("NFSD: preprocess_seqid_op: magic stateid!\n");
3005                 return nfserr_bad_stateid;
3006         }
3007
3008         if (STALE_STATEID(stateid))
3009                 return nfserr_stale_stateid;
3010
3011         if (nfsd4_has_session(cstate))
3012                 flags |= HAS_SESSION;
3013
3014         /*
3015         * We return BAD_STATEID if filehandle doesn't match stateid, 
3016         * the confirmed flag is incorrecly set, or the generation 
3017         * number is incorrect.  
3018         */
3019         stp = find_stateid(stateid, flags);
3020         if (stp == NULL) {
3021                 /*
3022                  * Also, we should make sure this isn't just the result of
3023                  * a replayed close:
3024                  */
3025                 sop = search_close_lru(stateid->si_stateownerid, flags);
3026                 if (sop == NULL)
3027                         return nfserr_bad_stateid;
3028                 *sopp = sop;
3029                 goto check_replay;
3030         }
3031
3032         *stpp = stp;
3033         *sopp = sop = stp->st_stateowner;
3034
3035         if (lock) {
3036                 clientid_t *lockclid = &lock->v.new.clientid;
3037                 struct nfs4_client *clp = sop->so_client;
3038                 int lkflg = 0;
3039                 __be32 status;
3040
3041                 lkflg = setlkflg(lock->lk_type);
3042
3043                 if (lock->lk_is_new) {
3044                         if (!sop->so_is_open_owner)
3045                                 return nfserr_bad_stateid;
3046                         if (!(flags & HAS_SESSION) &&
3047                             !same_clid(&clp->cl_clientid, lockclid))
3048                                 return nfserr_bad_stateid;
3049                         /* stp is the open stateid */
3050                         status = nfs4_check_openmode(stp, lkflg);
3051                         if (status)
3052                                 return status;
3053                 } else {
3054                         /* stp is the lock stateid */
3055                         status = nfs4_check_openmode(stp->st_openstp, lkflg);
3056                         if (status)
3057                                 return status;
3058                }
3059         }
3060
3061         if (nfs4_check_fh(current_fh, stp)) {
3062                 dprintk("NFSD: preprocess_seqid_op: fh-stateid mismatch!\n");
3063                 return nfserr_bad_stateid;
3064         }
3065
3066         /*
3067         *  We now validate the seqid and stateid generation numbers.
3068         *  For the moment, we ignore the possibility of 
3069         *  generation number wraparound.
3070         */
3071         if (!(flags & HAS_SESSION) && seqid != sop->so_seqid)
3072                 goto check_replay;
3073
3074         if (sop->so_confirmed && flags & CONFIRM) {
3075                 dprintk("NFSD: preprocess_seqid_op: expected"
3076                                 " unconfirmed stateowner!\n");
3077                 return nfserr_bad_stateid;
3078         }
3079         if (!sop->so_confirmed && !(flags & CONFIRM)) {
3080                 dprintk("NFSD: preprocess_seqid_op: stateowner not"
3081                                 " confirmed yet!\n");
3082                 return nfserr_bad_stateid;
3083         }
3084         status = check_stateid_generation(stateid, &stp->st_stateid, flags);
3085         if (status)
3086                 return status;
3087         renew_client(sop->so_client);
3088         return nfs_ok;
3089
3090 check_replay:
3091         if (seqid == sop->so_seqid - 1) {
3092                 dprintk("NFSD: preprocess_seqid_op: retransmission?\n");
3093                 /* indicate replay to calling function */
3094                 return nfserr_replay_me;
3095         }
3096         dprintk("NFSD: preprocess_seqid_op: bad seqid (expected %d, got %d)\n",
3097                         sop->so_seqid, seqid);
3098         *sopp = NULL;
3099         return nfserr_bad_seqid;
3100 }
3101
3102 __be32
3103 nfsd4_open_confirm(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3104                    struct nfsd4_open_confirm *oc)
3105 {
3106         __be32 status;
3107         struct nfs4_stateowner *sop;
3108         struct nfs4_stateid *stp;
3109
3110         dprintk("NFSD: nfsd4_open_confirm on file %.*s\n",
3111                         (int)cstate->current_fh.fh_dentry->d_name.len,
3112                         cstate->current_fh.fh_dentry->d_name.name);
3113
3114         status = fh_verify(rqstp, &cstate->current_fh, S_IFREG, 0);
3115         if (status)
3116                 return status;
3117
3118         nfs4_lock_state();
3119
3120         if ((status = nfs4_preprocess_seqid_op(cstate,
3121                                         oc->oc_seqid, &oc->oc_req_stateid,
3122                                         CONFIRM | OPEN_STATE,
3123                                         &oc->oc_stateowner, &stp, NULL)))
3124                 goto out; 
3125
3126         sop = oc->oc_stateowner;
3127         sop->so_confirmed = 1;
3128         update_stateid(&stp->st_stateid);
3129         memcpy(&oc->oc_resp_stateid, &stp->st_stateid, sizeof(stateid_t));
3130         dprintk("NFSD: %s: success, seqid=%d stateid=" STATEID_FMT "\n",
3131                 __func__, oc->oc_seqid, STATEID_VAL(&stp->st_stateid));
3132
3133         nfsd4_create_clid_dir(sop->so_client);
3134 out:
3135         if (oc->oc_stateowner) {
3136                 nfs4_get_stateowner(oc->oc_stateowner);
3137                 cstate->replay_owner = oc->oc_stateowner;
3138         }
3139         nfs4_unlock_state();
3140         return status;
3141 }
3142
3143
3144 /*
3145  * unset all bits in union bitmap (bmap) that
3146  * do not exist in share (from successful OPEN_DOWNGRADE)
3147  */
3148 static void
3149 reset_union_bmap_access(unsigned long access, unsigned long *bmap)
3150 {
3151         int i;
3152         for (i = 1; i < 4; i++) {
3153                 if ((i & access) != i)
3154                         __clear_bit(i, bmap);
3155         }
3156 }
3157
3158 static void
3159 reset_union_bmap_deny(unsigned long deny, unsigned long *bmap)
3160 {
3161         int i;
3162         for (i = 0; i < 4; i++) {
3163                 if ((i & deny) != i)
3164                         __clear_bit(i, bmap);
3165         }
3166 }
3167
3168 __be32
3169 nfsd4_open_downgrade(struct svc_rqst *rqstp,
3170                      struct nfsd4_compound_state *cstate,
3171                      struct nfsd4_open_downgrade *od)
3172 {
3173         __be32 status;
3174         struct nfs4_stateid *stp;
3175         unsigned int share_access;
3176
3177         dprintk("NFSD: nfsd4_open_downgrade on file %.*s\n", 
3178                         (int)cstate->current_fh.fh_dentry->d_name.len,
3179                         cstate->current_fh.fh_dentry->d_name.name);
3180
3181         if (!access_valid(od->od_share_access, cstate->minorversion)
3182                         || !deny_valid(od->od_share_deny))
3183                 return nfserr_inval;
3184
3185         nfs4_lock_state();
3186         if ((status = nfs4_preprocess_seqid_op(cstate,
3187                                         od->od_seqid,
3188                                         &od->od_stateid, 
3189                                         OPEN_STATE,
3190                                         &od->od_stateowner, &stp, NULL)))
3191                 goto out; 
3192
3193         status = nfserr_inval;
3194         if (!test_bit(od->od_share_access, &stp->st_access_bmap)) {
3195                 dprintk("NFSD:access not a subset current bitmap: 0x%lx, input access=%08x\n",
3196                         stp->st_access_bmap, od->od_share_access);
3197                 goto out;
3198         }
3199         if (!test_bit(od->od_share_deny, &stp->st_deny_bmap)) {
3200                 dprintk("NFSD:deny not a subset current bitmap: 0x%lx, input deny=%08x\n",
3201                         stp->st_deny_bmap, od->od_share_deny);
3202                 goto out;
3203         }
3204         set_access(&share_access, stp->st_access_bmap);
3205         nfs4_file_downgrade(stp->st_file, share_access & ~od->od_share_access);
3206
3207         reset_union_bmap_access(od->od_share_access, &stp->st_access_bmap);
3208         reset_union_bmap_deny(od->od_share_deny, &stp->st_deny_bmap);
3209
3210         update_stateid(&stp->st_stateid);
3211         memcpy(&od->od_stateid, &stp->st_stateid, sizeof(stateid_t));
3212         status = nfs_ok;
3213 out:
3214         if (od->od_stateowner) {
3215                 nfs4_get_stateowner(od->od_stateowner);
3216                 cstate->replay_owner = od->od_stateowner;
3217         }
3218         nfs4_unlock_state();
3219         return status;
3220 }
3221
3222 /*
3223  * nfs4_unlock_state() called after encode
3224  */
3225 __be32
3226 nfsd4_close(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3227             struct nfsd4_close *close)
3228 {
3229         __be32 status;
3230         struct nfs4_stateid *stp;
3231
3232         dprintk("NFSD: nfsd4_close on file %.*s\n", 
3233                         (int)cstate->current_fh.fh_dentry->d_name.len,
3234                         cstate->current_fh.fh_dentry->d_name.name);
3235
3236         nfs4_lock_state();
3237         /* check close_lru for replay */
3238         if ((status = nfs4_preprocess_seqid_op(cstate,
3239                                         close->cl_seqid,
3240                                         &close->cl_stateid, 
3241                                         OPEN_STATE | CLOSE_STATE,
3242                                         &close->cl_stateowner, &stp, NULL)))
3243                 goto out; 
3244         status = nfs_ok;
3245         update_stateid(&stp->st_stateid);
3246         memcpy(&close->cl_stateid, &stp->st_stateid, sizeof(stateid_t));
3247
3248         /* release_stateid() calls nfsd_close() if needed */
3249         release_open_stateid(stp);
3250
3251         /* place unused nfs4_stateowners on so_close_lru list to be
3252          * released by the laundromat service after the lease period
3253          * to enable us to handle CLOSE replay
3254          */
3255         if (list_empty(&close->cl_stateowner->so_stateids))
3256                 move_to_close_lru(close->cl_stateowner);
3257 out:
3258         if (close->cl_stateowner) {
3259                 nfs4_get_stateowner(close->cl_stateowner);
3260                 cstate->replay_owner = close->cl_stateowner;
3261         }
3262         nfs4_unlock_state();
3263         return status;
3264 }
3265
3266 __be32
3267 nfsd4_delegreturn(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3268                   struct nfsd4_delegreturn *dr)
3269 {
3270         struct nfs4_delegation *dp;
3271         stateid_t *stateid = &dr->dr_stateid;
3272         struct inode *inode;
3273         __be32 status;
3274         int flags = 0;
3275
3276         if ((status = fh_verify(rqstp, &cstate->current_fh, S_IFREG, 0)))
3277                 return status;
3278         inode = cstate->current_fh.fh_dentry->d_inode;
3279
3280         if (nfsd4_has_session(cstate))
3281                 flags |= HAS_SESSION;
3282         nfs4_lock_state();
3283         status = nfserr_bad_stateid;
3284         if (ZERO_STATEID(stateid) || ONE_STATEID(stateid))
3285                 goto out;
3286         status = nfserr_stale_stateid;
3287         if (STALE_STATEID(stateid))
3288                 goto out;
3289         status = nfserr_bad_stateid;
3290         if (!is_delegation_stateid(stateid))
3291                 goto out;
3292         dp = find_delegation_stateid(inode, stateid);
3293         if (!dp)
3294                 goto out;
3295         status = check_stateid_generation(stateid, &dp->dl_stateid, flags);
3296         if (status)
3297                 goto out;
3298         renew_client(dp->dl_client);
3299
3300         unhash_delegation(dp);
3301 out:
3302         nfs4_unlock_state();
3303
3304         return status;
3305 }
3306
3307
3308 /* 
3309  * Lock owner state (byte-range locks)
3310  */
3311 #define LOFF_OVERFLOW(start, len)      ((u64)(len) > ~(u64)(start))
3312 #define LOCK_HASH_BITS              8
3313 #define LOCK_HASH_SIZE             (1 << LOCK_HASH_BITS)
3314 #define LOCK_HASH_MASK             (LOCK_HASH_SIZE - 1)
3315
3316 static inline u64
3317 end_offset(u64 start, u64 len)
3318 {
3319         u64 end;
3320
3321         end = start + len;
3322         return end >= start ? end: NFS4_MAX_UINT64;
3323 }
3324
3325 /* last octet in a range */
3326 static inline u64
3327 last_byte_offset(u64 start, u64 len)
3328 {
3329         u64 end;
3330
3331         BUG_ON(!len);
3332         end = start + len;
3333         return end > start ? end - 1: NFS4_MAX_UINT64;
3334 }
3335
3336 #define lockownerid_hashval(id) \
3337         ((id) & LOCK_HASH_MASK)
3338
3339 static inline unsigned int
3340 lock_ownerstr_hashval(struct inode *inode, u32 cl_id,
3341                 struct xdr_netobj *ownername)
3342 {
3343         return (file_hashval(inode) + cl_id
3344                         + opaque_hashval(ownername->data, ownername->len))
3345                 & LOCK_HASH_MASK;
3346 }
3347
3348 static struct list_head lock_ownerid_hashtbl[LOCK_HASH_SIZE];
3349 static struct list_head lock_ownerstr_hashtbl[LOCK_HASH_SIZE];
3350 static struct list_head lockstateid_hashtbl[STATEID_HASH_SIZE];
3351
3352 static struct nfs4_stateid *
3353 find_stateid(stateid_t *stid, int flags)
3354 {
3355         struct nfs4_stateid *local;
3356         u32 st_id = stid->si_stateownerid;
3357         u32 f_id = stid->si_fileid;
3358         unsigned int hashval;
3359
3360         dprintk("NFSD: find_stateid flags 0x%x\n",flags);
3361         if (flags & (LOCK_STATE | RD_STATE | WR_STATE)) {
3362                 hashval = stateid_hashval(st_id, f_id);
3363                 list_for_each_entry(local, &lockstateid_hashtbl[hashval], st_hash) {
3364                         if ((local->st_stateid.si_stateownerid == st_id) &&
3365                             (local->st_stateid.si_fileid == f_id))
3366                                 return local;
3367                 }
3368         } 
3369
3370         if (flags & (OPEN_STATE | RD_STATE | WR_STATE)) {
3371                 hashval = stateid_hashval(st_id, f_id);
3372                 list_for_each_entry(local, &stateid_hashtbl[hashval], st_hash) {
3373                         if ((local->st_stateid.si_stateownerid == st_id) &&
3374                             (local->st_stateid.si_fileid == f_id))
3375                                 return local;
3376                 }
3377         }
3378         return NULL;
3379 }
3380
3381 static struct nfs4_delegation *
3382 find_delegation_stateid(struct inode *ino, stateid_t *stid)
3383 {
3384         struct nfs4_file *fp;
3385         struct nfs4_delegation *dl;
3386
3387         dprintk("NFSD: %s: stateid=" STATEID_FMT "\n", __func__,
3388                 STATEID_VAL(stid));
3389
3390         fp = find_file(ino);
3391         if (!fp)
3392                 return NULL;
3393         dl = find_delegation_file(fp, stid);
3394         put_nfs4_file(fp);
3395         return dl;
3396 }
3397
3398 /*
3399  * TODO: Linux file offsets are _signed_ 64-bit quantities, which means that
3400  * we can't properly handle lock requests that go beyond the (2^63 - 1)-th
3401  * byte, because of sign extension problems.  Since NFSv4 calls for 64-bit
3402  * locking, this prevents us from being completely protocol-compliant.  The
3403  * real solution to this problem is to start using unsigned file offsets in
3404  * the VFS, but this is a very deep change!
3405  */
3406 static inline void
3407 nfs4_transform_lock_offset(struct file_lock *lock)
3408 {
3409         if (lock->fl_start < 0)
3410                 lock->fl_start = OFFSET_MAX;
3411         if (lock->fl_end < 0)
3412                 lock->fl_end = OFFSET_MAX;
3413 }
3414
3415 /* Hack!: For now, we're defining this just so we can use a pointer to it
3416  * as a unique cookie to identify our (NFSv4's) posix locks. */
3417 static const struct lock_manager_operations nfsd_posix_mng_ops  = {
3418 };
3419
3420 static inline void
3421 nfs4_set_lock_denied(struct file_lock *fl, struct nfsd4_lock_denied *deny)
3422 {
3423         struct nfs4_stateowner *sop;
3424         unsigned int hval;
3425
3426         if (fl->fl_lmops == &nfsd_posix_mng_ops) {
3427                 sop = (struct nfs4_stateowner *) fl->fl_owner;
3428                 hval = lockownerid_hashval(sop->so_id);
3429                 kref_get(&sop->so_ref);
3430                 deny->ld_sop = sop;
3431                 deny->ld_clientid = sop->so_client->cl_clientid;
3432         } else {
3433                 deny->ld_sop = NULL;
3434                 deny->ld_clientid.cl_boot = 0;
3435                 deny->ld_clientid.cl_id = 0;
3436         }
3437         deny->ld_start = fl->fl_start;
3438         deny->ld_length = NFS4_MAX_UINT64;
3439         if (fl->fl_end != NFS4_MAX_UINT64)
3440                 deny->ld_length = fl->fl_end - fl->fl_start + 1;        
3441         deny->ld_type = NFS4_READ_LT;
3442         if (fl->fl_type != F_RDLCK)
3443                 deny->ld_type = NFS4_WRITE_LT;
3444 }
3445
3446 static struct nfs4_stateowner *
3447 find_lockstateowner_str(struct inode *inode, clientid_t *clid,
3448                 struct xdr_netobj *owner)
3449 {
3450         unsigned int hashval = lock_ownerstr_hashval(inode, clid->cl_id, owner);
3451         struct nfs4_stateowner *op;
3452
3453         list_for_each_entry(op, &lock_ownerstr_hashtbl[hashval], so_strhash) {
3454                 if (same_owner_str(op, owner, clid))
3455                         return op;
3456         }
3457         return NULL;
3458 }
3459
3460 /*
3461  * Alloc a lock owner structure.
3462  * Called in nfsd4_lock - therefore, OPEN and OPEN_CONFIRM (if needed) has 
3463  * occured. 
3464  *
3465  * strhashval = lock_ownerstr_hashval 
3466  */
3467
3468 static struct nfs4_stateowner *
3469 alloc_init_lock_stateowner(unsigned int strhashval, struct nfs4_client *clp, struct nfs4_stateid *open_stp, struct nfsd4_lock *lock) {
3470         struct nfs4_stateowner *sop;
3471         struct nfs4_replay *rp;
3472         unsigned int idhashval;
3473
3474         if (!(sop = alloc_stateowner(&lock->lk_new_owner)))
3475                 return NULL;
3476         idhashval = lockownerid_hashval(current_ownerid);
3477         INIT_LIST_HEAD(&sop->so_idhash);
3478         INIT_LIST_HEAD(&sop->so_strhash);
3479         INIT_LIST_HEAD(&sop->so_perclient);
3480         INIT_LIST_HEAD(&sop->so_stateids);
3481         INIT_LIST_HEAD(&sop->so_perstateid);
3482         INIT_LIST_HEAD(&sop->so_close_lru); /* not used */
3483         sop->so_time = 0;
3484         list_add(&sop->so_idhash, &lock_ownerid_hashtbl[idhashval]);
3485         list_add(&sop->so_strhash, &lock_ownerstr_hashtbl[strhashval]);
3486         list_add(&sop->so_perstateid, &open_stp->st_lockowners);
3487         sop->so_is_open_owner = 0;
3488         sop->so_id = current_ownerid++;
3489         sop->so_client = clp;
3490         /* It is the openowner seqid that will be incremented in encode in the
3491          * case of new lockowners; so increment the lock seqid manually: */
3492         sop->so_seqid = lock->lk_new_lock_seqid + 1;
3493         sop->so_confirmed = 1;
3494         rp = &sop->so_replay;
3495         rp->rp_status = nfserr_serverfault;
3496         rp->rp_buflen = 0;
3497         rp->rp_buf = rp->rp_ibuf;
3498         return sop;
3499 }
3500
3501 static struct nfs4_stateid *
3502 alloc_init_lock_stateid(struct nfs4_stateowner *sop, struct nfs4_file *fp, struct nfs4_stateid *open_stp)
3503 {
3504         struct nfs4_stateid *stp;
3505         unsigned int hashval = stateid_hashval(sop->so_id, fp->fi_id);
3506
3507         stp = nfs4_alloc_stateid();
3508         if (stp == NULL)
3509                 goto out;
3510         INIT_LIST_HEAD(&stp->st_hash);
3511         INIT_LIST_HEAD(&stp->st_perfile);
3512         INIT_LIST_HEAD(&stp->st_perstateowner);
3513         INIT_LIST_HEAD(&stp->st_lockowners); /* not used */
3514         list_add(&stp->st_hash, &lockstateid_hashtbl[hashval]);
3515         list_add(&stp->st_perfile, &fp->fi_stateids);
3516         list_add(&stp->st_perstateowner, &sop->so_stateids);
3517         stp->st_stateowner = sop;
3518         get_nfs4_file(fp);
3519         stp->st_file = fp;
3520         stp->st_stateid.si_boot = boot_time;
3521         stp->st_stateid.si_stateownerid = sop->so_id;
3522         stp->st_stateid.si_fileid = fp->fi_id;
3523         stp->st_stateid.si_generation = 0;
3524         stp->st_deny_bmap = open_stp->st_deny_bmap;
3525         stp->st_openstp = open_stp;
3526
3527 out:
3528         return stp;
3529 }
3530
3531 static int
3532 check_lock_length(u64 offset, u64 length)
3533 {
3534         return ((length == 0)  || ((length != NFS4_MAX_UINT64) &&
3535              LOFF_OVERFLOW(offset, length)));
3536 }
3537
3538 /*
3539  *  LOCK operation 
3540  */
3541 __be32
3542 nfsd4_lock(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3543            struct nfsd4_lock *lock)
3544 {
3545         struct nfs4_stateowner *open_sop = NULL;
3546         struct nfs4_stateowner *lock_sop = NULL;
3547         struct nfs4_stateid *lock_stp;
3548         struct file *filp;
3549         struct file_lock file_lock;
3550         struct file_lock conflock;
3551         __be32 status = 0;
3552         unsigned int strhashval;
3553         unsigned int cmd;
3554         int err;
3555
3556         dprintk("NFSD: nfsd4_lock: start=%Ld length=%Ld\n",
3557                 (long long) lock->lk_offset,
3558                 (long long) lock->lk_length);
3559
3560         if (check_lock_length(lock->lk_offset, lock->lk_length))
3561                  return nfserr_inval;
3562
3563         if ((status = fh_verify(rqstp, &cstate->current_fh,
3564                                 S_IFREG, NFSD_MAY_LOCK))) {
3565                 dprintk("NFSD: nfsd4_lock: permission denied!\n");
3566                 return status;
3567         }
3568
3569         nfs4_lock_state();
3570
3571         if (lock->lk_is_new) {
3572                 /*
3573                  * Client indicates that this is a new lockowner.
3574                  * Use open owner and open stateid to create lock owner and
3575                  * lock stateid.
3576                  */
3577                 struct nfs4_stateid *open_stp = NULL;
3578                 struct nfs4_file *fp;
3579                 
3580                 status = nfserr_stale_clientid;
3581                 if (!nfsd4_has_session(cstate) &&
3582                     STALE_CLIENTID(&lock->lk_new_clientid))
3583                         goto out;
3584
3585                 /* validate and update open stateid and open seqid */
3586                 status = nfs4_preprocess_seqid_op(cstate,
3587                                         lock->lk_new_open_seqid,
3588                                         &lock->lk_new_open_stateid,
3589                                         OPEN_STATE,
3590                                         &lock->lk_replay_owner, &open_stp,
3591                                         lock);
3592                 if (status)
3593                         goto out;
3594                 open_sop = lock->lk_replay_owner;
3595                 /* create lockowner and lock stateid */
3596                 fp = open_stp->st_file;
3597                 strhashval = lock_ownerstr_hashval(fp->fi_inode, 
3598                                 open_sop->so_client->cl_clientid.cl_id, 
3599                                 &lock->v.new.owner);
3600                 /* XXX: Do we need to check for duplicate stateowners on
3601                  * the same file, or should they just be allowed (and
3602                  * create new stateids)? */
3603                 status = nfserr_resource;
3604                 lock_sop = alloc_init_lock_stateowner(strhashval,
3605                                 open_sop->so_client, open_stp, lock);
3606                 if (lock_sop == NULL)
3607                         goto out;
3608                 lock_stp = alloc_init_lock_stateid(lock_sop, fp, open_stp);
3609                 if (lock_stp == NULL)
3610                         goto out;
3611         } else {
3612                 /* lock (lock owner + lock stateid) already exists */
3613                 status = nfs4_preprocess_seqid_op(cstate,
3614                                        lock->lk_old_lock_seqid, 
3615                                        &lock->lk_old_lock_stateid, 
3616                                        LOCK_STATE,
3617                                        &lock->lk_replay_owner, &lock_stp, lock);
3618                 if (status)
3619                         goto out;
3620                 lock_sop = lock->lk_replay_owner;
3621         }
3622         /* lock->lk_replay_owner and lock_stp have been created or found */
3623
3624         status = nfserr_grace;
3625         if (locks_in_grace() && !lock->lk_reclaim)
3626                 goto out;
3627         status = nfserr_no_grace;
3628         if (!locks_in_grace() && lock->lk_reclaim)
3629                 goto out;
3630
3631         locks_init_lock(&file_lock);
3632         switch (lock->lk_type) {
3633                 case NFS4_READ_LT:
3634                 case NFS4_READW_LT:
3635                         filp = find_readable_file(lock_stp->st_file);
3636                         file_lock.fl_type = F_RDLCK;
3637                         cmd = F_SETLK;
3638                 break;
3639                 case NFS4_WRITE_LT:
3640                 case NFS4_WRITEW_LT:
3641                         filp = find_writeable_file(lock_stp->st_file);
3642                         file_lock.fl_type = F_WRLCK;
3643                         cmd = F_SETLK;
3644                 break;
3645                 default:
3646                         status = nfserr_inval;
3647                 goto out;
3648         }
3649         if (!filp) {
3650                 status = nfserr_openmode;
3651                 goto out;
3652         }
3653         file_lock.fl_owner = (fl_owner_t)lock_sop;
3654         file_lock.fl_pid = current->tgid;
3655         file_lock.fl_file = filp;
3656         file_lock.fl_flags = FL_POSIX;
3657         file_lock.fl_lmops = &nfsd_posix_mng_ops;
3658
3659         file_lock.fl_start = lock->lk_offset;
3660         file_lock.fl_end = last_byte_offset(lock->lk_offset, lock->lk_length);
3661         nfs4_transform_lock_offset(&file_lock);
3662
3663         /*
3664         * Try to lock the file in the VFS.
3665         * Note: locks.c uses the BKL to protect the inode's lock list.
3666         */
3667
3668         err = vfs_lock_file(filp, cmd, &file_lock, &conflock);
3669         switch (-err) {
3670         case 0: /* success! */
3671                 update_stateid(&lock_stp->st_stateid);
3672                 memcpy(&lock->lk_resp_stateid, &lock_stp->st_stateid, 
3673                                 sizeof(stateid_t));
3674                 status = 0;
3675                 break;
3676         case (EAGAIN):          /* conflock holds conflicting lock */
3677                 status = nfserr_denied;
3678                 dprintk("NFSD: nfsd4_lock: conflicting lock found!\n");
3679                 nfs4_set_lock_denied(&conflock, &lock->lk_denied);
3680                 break;
3681         case (EDEADLK):
3682                 status = nfserr_deadlock;
3683                 break;
3684         default:        
3685                 dprintk("NFSD: nfsd4_lock: vfs_lock_file() failed! status %d\n",err);
3686                 status = nfserr_resource;
3687                 break;
3688         }
3689 out:
3690         if (status && lock->lk_is_new && lock_sop)
3691                 release_lockowner(lock_sop);
3692         if (lock->lk_replay_owner) {
3693                 nfs4_get_stateowner(lock->lk_replay_owner);
3694                 cstate->replay_owner = lock->lk_replay_owner;
3695         }
3696         nfs4_unlock_state();
3697         return status;
3698 }
3699
3700 /*
3701  * The NFSv4 spec allows a client to do a LOCKT without holding an OPEN,
3702  * so we do a temporary open here just to get an open file to pass to
3703  * vfs_test_lock.  (Arguably perhaps test_lock should be done with an
3704  * inode operation.)
3705  */
3706 static int nfsd_test_lock(struct svc_rqst *rqstp, struct svc_fh *fhp, struct file_lock *lock)
3707 {
3708         struct file *file;
3709         int err;
3710
3711         err = nfsd_open(rqstp, fhp, S_IFREG, NFSD_MAY_READ, &file);
3712         if (err)
3713                 return err;
3714         err = vfs_test_lock(file, lock);
3715         nfsd_close(file);
3716         return err;
3717 }
3718
3719 /*
3720  * LOCKT operation
3721  */
3722 __be32
3723 nfsd4_lockt(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3724             struct nfsd4_lockt *lockt)
3725 {
3726         struct inode *inode;
3727         struct file_lock file_lock;
3728         int error;
3729         __be32 status;
3730
3731         if (locks_in_grace())
3732                 return nfserr_grace;
3733
3734         if (check_lock_length(lockt->lt_offset, lockt->lt_length))
3735                  return nfserr_inval;
3736
3737         lockt->lt_stateowner = NULL;
3738         nfs4_lock_state();
3739
3740         status = nfserr_stale_clientid;
3741         if (!nfsd4_has_session(cstate) && STALE_CLIENTID(&lockt->lt_clientid))
3742                 goto out;
3743
3744         if ((status = fh_verify(rqstp, &cstate->current_fh, S_IFREG, 0))) {
3745                 dprintk("NFSD: nfsd4_lockt: fh_verify() failed!\n");
3746                 if (status == nfserr_symlink)
3747                         status = nfserr_inval;
3748                 goto out;
3749         }
3750
3751         inode = cstate->current_fh.fh_dentry->d_inode;
3752         locks_init_lock(&file_lock);
3753         switch (lockt->lt_type) {
3754                 case NFS4_READ_LT:
3755                 case NFS4_READW_LT:
3756                         file_lock.fl_type = F_RDLCK;
3757                 break;
3758                 case NFS4_WRITE_LT:
3759                 case NFS4_WRITEW_LT:
3760                         file_lock.fl_type = F_WRLCK;
3761                 break;
3762                 default:
3763                         dprintk("NFSD: nfs4_lockt: bad lock type!\n");
3764                         status = nfserr_inval;
3765                 goto out;
3766         }
3767
3768         lockt->lt_stateowner = find_lockstateowner_str(inode,
3769                         &lockt->lt_clientid, &lockt->lt_owner);
3770         if (lockt->lt_stateowner)
3771                 file_lock.fl_owner = (fl_owner_t)lockt->lt_stateowner;
3772         file_lock.fl_pid = current->tgid;
3773         file_lock.fl_flags = FL_POSIX;
3774
3775         file_lock.fl_start = lockt->lt_offset;
3776         file_lock.fl_end = last_byte_offset(lockt->lt_offset, lockt->lt_length);
3777
3778         nfs4_transform_lock_offset(&file_lock);
3779
3780         status = nfs_ok;
3781         error = nfsd_test_lock(rqstp, &cstate->current_fh, &file_lock);
3782         if (error) {
3783                 status = nfserrno(error);
3784                 goto out;
3785         }
3786         if (file_lock.fl_type != F_UNLCK) {
3787                 status = nfserr_denied;
3788                 nfs4_set_lock_denied(&file_lock, &lockt->lt_denied);
3789         }
3790 out:
3791         nfs4_unlock_state();
3792         return status;
3793 }
3794
3795 __be32
3796 nfsd4_locku(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
3797             struct nfsd4_locku *locku)
3798 {
3799         struct nfs4_stateid *stp;
3800         struct file *filp = NULL;
3801         struct file_lock file_lock;
3802         __be32 status;
3803         int err;
3804                                                         
3805         dprintk("NFSD: nfsd4_locku: start=%Ld length=%Ld\n",
3806                 (long long) locku->lu_offset,
3807                 (long long) locku->lu_length);
3808
3809         if (check_lock_length(locku->lu_offset, locku->lu_length))
3810                  return nfserr_inval;
3811
3812         nfs4_lock_state();
3813                                                                                 
3814         if ((status = nfs4_preprocess_seqid_op(cstate,
3815                                         locku->lu_seqid, 
3816                                         &locku->lu_stateid, 
3817                                         LOCK_STATE,
3818                                         &locku->lu_stateowner, &stp, NULL)))
3819                 goto out;
3820
3821         filp = find_any_file(stp->st_file);
3822         if (!filp) {
3823                 status = nfserr_lock_range;
3824                 goto out;
3825         }
3826         BUG_ON(!filp);
3827         locks_init_lock(&file_lock);
3828         file_lock.fl_type = F_UNLCK;
3829         file_lock.fl_owner = (fl_owner_t) locku->lu_stateowner;
3830         file_lock.fl_pid = current->tgid;
3831         file_lock.fl_file = filp;
3832         file_lock.fl_flags = FL_POSIX; 
3833         file_lock.fl_lmops = &nfsd_posix_mng_ops;
3834         file_lock.fl_start = locku->lu_offset;
3835
3836         file_lock.fl_end = last_byte_offset(locku->lu_offset, locku->lu_length);
3837         nfs4_transform_lock_offset(&file_lock);
3838
3839         /*
3840         *  Try to unlock the file in the VFS.
3841         */
3842         err = vfs_lock_file(filp, F_SETLK, &file_lock, NULL);
3843         if (err) {
3844                 dprintk("NFSD: nfs4_locku: vfs_lock_file failed!\n");
3845                 goto out_nfserr;
3846         }
3847         /*
3848         * OK, unlock succeeded; the only thing left to do is update the stateid.
3849         */
3850         update_stateid(&stp->st_stateid);
3851         memcpy(&locku->lu_stateid, &stp->st_stateid, sizeof(stateid_t));
3852
3853 out:
3854         if (locku->lu_stateowner) {
3855                 nfs4_get_stateowner(locku->lu_stateowner);
3856                 cstate->replay_owner = locku->lu_stateowner;
3857         }
3858         nfs4_unlock_state();
3859         return status;
3860
3861 out_nfserr:
3862         status = nfserrno(err);
3863         goto out;
3864 }
3865
3866 /*
3867  * returns
3868  *      1: locks held by lockowner
3869  *      0: no locks held by lockowner
3870  */
3871 static int
3872 check_for_locks(struct nfs4_file *filp, struct nfs4_stateowner *lowner)
3873 {
3874         struct file_lock **flpp;
3875         struct inode *inode = filp->fi_inode;
3876         int status = 0;
3877
3878         lock_kernel();
3879         for (flpp = &inode->i_flock; *flpp != NULL; flpp = &(*flpp)->fl_next) {
3880                 if ((*flpp)->fl_owner == (fl_owner_t)lowner) {
3881                         status = 1;
3882                         goto out;
3883                 }
3884         }
3885 out:
3886         unlock_kernel();
3887         return status;
3888 }
3889
3890 __be32
3891 nfsd4_release_lockowner(struct svc_rqst *rqstp,
3892                         struct nfsd4_compound_state *cstate,
3893                         struct nfsd4_release_lockowner *rlockowner)
3894 {
3895         clientid_t *clid = &rlockowner->rl_clientid;
3896         struct nfs4_stateowner *sop;
3897         struct nfs4_stateid *stp;
3898         struct xdr_netobj *owner = &rlockowner->rl_owner;
3899         struct list_head matches;
3900         int i;
3901         __be32 status;
3902
3903         dprintk("nfsd4_release_lockowner clientid: (%08x/%08x):\n",
3904                 clid->cl_boot, clid->cl_id);
3905
3906         /* XXX check for lease expiration */
3907
3908         status = nfserr_stale_clientid;
3909         if (STALE_CLIENTID(clid))
3910                 return status;
3911
3912         nfs4_lock_state();
3913
3914         status = nfserr_locks_held;
3915         /* XXX: we're doing a linear search through all the lockowners.
3916          * Yipes!  For now we'll just hope clients aren't really using
3917          * release_lockowner much, but eventually we have to fix these
3918          * data structures. */
3919         INIT_LIST_HEAD(&matches);
3920         for (i = 0; i < LOCK_HASH_SIZE; i++) {
3921                 list_for_each_entry(sop, &lock_ownerid_hashtbl[i], so_idhash) {
3922                         if (!same_owner_str(sop, owner, clid))
3923                                 continue;
3924                         list_for_each_entry(stp, &sop->so_stateids,
3925                                         st_perstateowner) {
3926                                 if (check_for_locks(stp->st_file, sop))
3927                                         goto out;
3928                                 /* Note: so_perclient unused for lockowners,
3929                                  * so it's OK to fool with here. */
3930                                 list_add(&sop->so_perclient, &matches);
3931                         }
3932                 }
3933         }
3934         /* Clients probably won't expect us to return with some (but not all)
3935          * of the lockowner state released; so don't release any until all
3936          * have been checked. */
3937         status = nfs_ok;
3938         while (!list_empty(&matches)) {
3939                 sop = list_entry(matches.next, struct nfs4_stateowner,
3940                                                                 so_perclient);
3941                 /* unhash_stateowner deletes so_perclient only
3942                  * for openowners. */
3943                 list_del(&sop->so_perclient);
3944                 release_lockowner(sop);
3945         }
3946 out:
3947         nfs4_unlock_state();
3948         return status;
3949 }
3950
3951 static inline struct nfs4_client_reclaim *
3952 alloc_reclaim(void)
3953 {
3954         return kmalloc(sizeof(struct nfs4_client_reclaim), GFP_KERNEL);
3955 }
3956
3957 int
3958 nfs4_has_reclaimed_state(const char *name, bool use_exchange_id)
3959 {
3960         unsigned int strhashval = clientstr_hashval(name);
3961         struct nfs4_client *clp;
3962
3963         clp = find_confirmed_client_by_str(name, strhashval, use_exchange_id);
3964         return clp ? 1 : 0;
3965 }
3966
3967 /*
3968  * failure => all reset bets are off, nfserr_no_grace...
3969  */
3970 int
3971 nfs4_client_to_reclaim(const char *name)
3972 {
3973         unsigned int strhashval;
3974         struct nfs4_client_reclaim *crp = NULL;
3975
3976         dprintk("NFSD nfs4_client_to_reclaim NAME: %.*s\n", HEXDIR_LEN, name);
3977         crp = alloc_reclaim();
3978         if (!crp)
3979                 return 0;
3980         strhashval = clientstr_hashval(name);
3981         INIT_LIST_HEAD(&crp->cr_strhash);
3982         list_add(&crp->cr_strhash, &reclaim_str_hashtbl[strhashval]);
3983         memcpy(crp->cr_recdir, name, HEXDIR_LEN);
3984         reclaim_str_hashtbl_size++;
3985         return 1;
3986 }
3987
3988 static void
3989 nfs4_release_reclaim(void)
3990 {
3991         struct nfs4_client_reclaim *crp = NULL;
3992         int i;
3993
3994         for (i = 0; i < CLIENT_HASH_SIZE; i++) {
3995                 while (!list_empty(&reclaim_str_hashtbl[i])) {
3996                         crp = list_entry(reclaim_str_hashtbl[i].next,
3997                                         struct nfs4_client_reclaim, cr_strhash);
3998                         list_del(&crp->cr_strhash);
3999                         kfree(crp);
4000                         reclaim_str_hashtbl_size--;
4001                 }
4002         }
4003         BUG_ON(reclaim_str_hashtbl_size);
4004 }
4005
4006 /*
4007  * called from OPEN, CLAIM_PREVIOUS with a new clientid. */
4008 static struct nfs4_client_reclaim *
4009 nfs4_find_reclaim_client(clientid_t *clid)
4010 {
4011         unsigned int strhashval;
4012         struct nfs4_client *clp;
4013         struct nfs4_client_reclaim *crp = NULL;
4014
4015
4016         /* find clientid in conf_id_hashtbl */
4017         clp = find_confirmed_client(clid);
4018         if (clp == NULL)
4019                 return NULL;
4020
4021         dprintk("NFSD: nfs4_find_reclaim_client for %.*s with recdir %s\n",
4022                             clp->cl_name.len, clp->cl_name.data,
4023                             clp->cl_recdir);
4024
4025         /* find clp->cl_name in reclaim_str_hashtbl */
4026         strhashval = clientstr_hashval(clp->cl_recdir);
4027         list_for_each_entry(crp, &reclaim_str_hashtbl[strhashval], cr_strhash) {
4028                 if (same_name(crp->cr_recdir, clp->cl_recdir)) {
4029                         return crp;
4030                 }
4031         }
4032         return NULL;
4033 }
4034
4035 /*
4036 * Called from OPEN. Look for clientid in reclaim list.
4037 */
4038 __be32
4039 nfs4_check_open_reclaim(clientid_t *clid)
4040 {
4041         return nfs4_find_reclaim_client(clid) ? nfs_ok : nfserr_reclaim_bad;
4042 }
4043
4044 /* initialization to perform at module load time: */
4045
4046 int
4047 nfs4_state_init(void)
4048 {
4049         int i, status;
4050
4051         status = nfsd4_init_slabs();
4052         if (status)
4053                 return status;
4054         for (i = 0; i < CLIENT_HASH_SIZE; i++) {
4055                 INIT_LIST_HEAD(&conf_id_hashtbl[i]);
4056                 INIT_LIST_HEAD(&conf_str_hashtbl[i]);
4057                 INIT_LIST_HEAD(&unconf_str_hashtbl[i]);
4058                 INIT_LIST_HEAD(&unconf_id_hashtbl[i]);
4059                 INIT_LIST_HEAD(&reclaim_str_hashtbl[i]);
4060         }
4061         for (i = 0; i < SESSION_HASH_SIZE; i++)
4062                 INIT_LIST_HEAD(&sessionid_hashtbl[i]);
4063         for (i = 0; i < FILE_HASH_SIZE; i++) {
4064                 INIT_LIST_HEAD(&file_hashtbl[i]);
4065         }
4066         for (i = 0; i < OWNER_HASH_SIZE; i++) {
4067                 INIT_LIST_HEAD(&ownerstr_hashtbl[i]);
4068                 INIT_LIST_HEAD(&ownerid_hashtbl[i]);
4069         }
4070         for (i = 0; i < STATEID_HASH_SIZE; i++) {
4071                 INIT_LIST_HEAD(&stateid_hashtbl[i]);
4072                 INIT_LIST_HEAD(&lockstateid_hashtbl[i]);
4073         }
4074         for (i = 0; i < LOCK_HASH_SIZE; i++) {
4075                 INIT_LIST_HEAD(&lock_ownerid_hashtbl[i]);
4076                 INIT_LIST_HEAD(&lock_ownerstr_hashtbl[i]);
4077         }
4078         memset(&onestateid, ~0, sizeof(stateid_t));
4079         INIT_LIST_HEAD(&close_lru);
4080         INIT_LIST_HEAD(&client_lru);
4081         INIT_LIST_HEAD(&del_recall_lru);
4082         reclaim_str_hashtbl_size = 0;
4083         return 0;
4084 }
4085
4086 static void
4087 nfsd4_load_reboot_recovery_data(void)
4088 {
4089         int status;
4090
4091         nfs4_lock_state();
4092         nfsd4_init_recdir(user_recovery_dirname);
4093         status = nfsd4_recdir_load();
4094         nfs4_unlock_state();
4095         if (status)
4096                 printk("NFSD: Failure reading reboot recovery data\n");
4097 }
4098
4099 /*
4100  * Since the lifetime of a delegation isn't limited to that of an open, a
4101  * client may quite reasonably hang on to a delegation as long as it has
4102  * the inode cached.  This becomes an obvious problem the first time a
4103  * client's inode cache approaches the size of the server's total memory.
4104  *
4105  * For now we avoid this problem by imposing a hard limit on the number
4106  * of delegations, which varies according to the server's memory size.
4107  */
4108 static void
4109 set_max_delegations(void)
4110 {
4111         /*
4112          * Allow at most 4 delegations per megabyte of RAM.  Quick
4113          * estimates suggest that in the worst case (where every delegation
4114          * is for a different inode), a delegation could take about 1.5K,
4115          * giving a worst case usage of about 6% of memory.
4116          */
4117         max_delegations = nr_free_buffer_pages() >> (20 - 2 - PAGE_SHIFT);
4118 }
4119
4120 /* initialization to perform when the nfsd service is started: */
4121
4122 static int
4123 __nfs4_state_start(void)
4124 {
4125         int ret;
4126
4127         boot_time = get_seconds();
4128         locks_start_grace(&nfsd4_manager);
4129         printk(KERN_INFO "NFSD: starting %ld-second grace period\n",
4130                nfsd4_grace);
4131         ret = set_callback_cred();
4132         if (ret)
4133                 return -ENOMEM;
4134         laundry_wq = create_singlethread_workqueue("nfsd4");
4135         if (laundry_wq == NULL)
4136                 return -ENOMEM;
4137         ret = nfsd4_create_callback_queue();
4138         if (ret)
4139                 goto out_free_laundry;
4140         queue_delayed_work(laundry_wq, &laundromat_work, nfsd4_grace * HZ);
4141         set_max_delegations();
4142         return 0;
4143 out_free_laundry:
4144         destroy_workqueue(laundry_wq);
4145         return ret;
4146 }
4147
4148 int
4149 nfs4_state_start(void)
4150 {
4151         nfsd4_load_reboot_recovery_data();
4152         return __nfs4_state_start();
4153 }
4154
4155 static void
4156 __nfs4_state_shutdown(void)
4157 {
4158         int i;
4159         struct nfs4_client *clp = NULL;
4160         struct nfs4_delegation *dp = NULL;
4161         struct list_head *pos, *next, reaplist;
4162
4163         for (i = 0; i < CLIENT_HASH_SIZE; i++) {
4164                 while (!list_empty(&conf_id_hashtbl[i])) {
4165                         clp = list_entry(conf_id_hashtbl[i].next, struct nfs4_client, cl_idhash);
4166                         expire_client(clp);
4167                 }
4168                 while (!list_empty(&unconf_str_hashtbl[i])) {
4169                         clp = list_entry(unconf_str_hashtbl[i].next, struct nfs4_client, cl_strhash);
4170                         expire_client(clp);
4171                 }
4172         }
4173         INIT_LIST_HEAD(&reaplist);
4174         spin_lock(&recall_lock);
4175         list_for_each_safe(pos, next, &del_recall_lru) {
4176                 dp = list_entry (pos, struct nfs4_delegation, dl_recall_lru);
4177                 list_move(&dp->dl_recall_lru, &reaplist);
4178         }
4179         spin_unlock(&recall_lock);
4180         list_for_each_safe(pos, next, &reaplist) {
4181                 dp = list_entry (pos, struct nfs4_delegation, dl_recall_lru);
4182                 list_del_init(&dp->dl_recall_lru);
4183                 unhash_delegation(dp);
4184         }
4185
4186         nfsd4_shutdown_recdir();
4187 }
4188
4189 void
4190 nfs4_state_shutdown(void)
4191 {
4192         cancel_rearming_delayed_workqueue(laundry_wq, &laundromat_work);
4193         destroy_workqueue(laundry_wq);
4194         locks_end_grace(&nfsd4_manager);
4195         nfs4_lock_state();
4196         nfs4_release_reclaim();
4197         __nfs4_state_shutdown();
4198         nfsd4_destroy_callback_queue();
4199         nfs4_unlock_state();
4200 }
4201
4202 /*
4203  * user_recovery_dirname is protected by the nfsd_mutex since it's only
4204  * accessed when nfsd is starting.
4205  */
4206 static void
4207 nfs4_set_recdir(char *recdir)
4208 {
4209         strcpy(user_recovery_dirname, recdir);
4210 }
4211
4212 /*
4213  * Change the NFSv4 recovery directory to recdir.
4214  */
4215 int
4216 nfs4_reset_recoverydir(char *recdir)
4217 {
4218         int status;
4219         struct path path;
4220
4221         status = kern_path(recdir, LOOKUP_FOLLOW, &path);
4222         if (status)
4223                 return status;
4224         status = -ENOTDIR;
4225         if (S_ISDIR(path.dentry->d_inode->i_mode)) {
4226                 nfs4_set_recdir(recdir);
4227                 status = 0;
4228         }
4229         path_put(&path);
4230         return status;
4231 }
4232
4233 char *
4234 nfs4_recoverydir(void)
4235 {
4236         return user_recovery_dirname;
4237 }