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