Whamcloud - gitweb
- landing of b_fid after merge with b_hd_cleanup_merge.
[fs/lustre-release.git] / lustre / mds / handler.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  *  lustre/mds/handler.c
5  *  Lustre Metadata Server (mds) request handler
6  *
7  *  Copyright (c) 2001-2003 Cluster File Systems, Inc.
8  *   Author: Peter Braam <braam@clusterfs.com>
9  *   Author: Andreas Dilger <adilger@clusterfs.com>
10  *   Author: Phil Schwan <phil@clusterfs.com>
11  *   Author: Mike Shaver <shaver@clusterfs.com>
12  *
13  *   This file is part of Lustre, http://www.lustre.org.
14  *
15  *   Lustre is free software; you can redistribute it and/or
16  *   modify it under the terms of version 2 of the GNU General Public
17  *   License as published by the Free Software Foundation.
18  *
19  *   Lustre is distributed in the hope that it will be useful,
20  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
21  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  *   GNU General Public License for more details.
23  *
24  *   You should have received a copy of the GNU General Public License
25  *   along with Lustre; if not, write to the Free Software
26  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27  */
28
29 #ifndef EXPORT_SYMTAB
30 # define EXPORT_SYMTAB
31 #endif
32 #define DEBUG_SUBSYSTEM S_MDS
33
34 #include <linux/module.h>
35 #include <linux/lustre_mds.h>
36 #include <linux/lustre_dlm.h>
37 #include <linux/init.h>
38 #include <linux/obd_class.h>
39 #include <linux/random.h>
40 #include <linux/fs.h>
41 #include <linux/jbd.h>
42 #include <linux/ext3_fs.h>
43 #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0))
44 # include <linux/smp_lock.h>
45 # include <linux/buffer_head.h>
46 # include <linux/workqueue.h>
47 # include <linux/mount.h>
48 #else
49 # include <linux/locks.h>
50 #endif
51 #include <linux/obd_lov.h>
52 #include <linux/obd_ost.h>
53 #include <linux/lustre_mds.h>
54 #include <linux/lustre_fsfilt.h>
55 #include <linux/lprocfs_status.h>
56 #include <linux/lustre_commit_confd.h>
57
58 #include "mds_internal.h"
59
60 static int mds_intent_policy(struct ldlm_namespace *ns,
61                              struct ldlm_lock **lockp, void *req_cookie,
62                              ldlm_mode_t mode, int flags, void *data);
63 static int mds_postsetup(struct obd_device *obd);
64 static int mds_cleanup(struct obd_device *obd, int flags);
65
66
67 /* Assumes caller has already pushed into the kernel filesystem context */
68 static int mds_sendpage(struct ptlrpc_request *req, struct file *file,
69                         loff_t offset, int count)
70 {
71         struct ptlrpc_bulk_desc *desc;
72         struct l_wait_info lwi;
73         struct page **pages;
74         int rc = 0, npages, i, tmpcount, tmpsize = 0;
75         ENTRY;
76
77         LASSERT((offset & (PAGE_SIZE - 1)) == 0); /* I'm dubious about this */
78
79         npages = (count + PAGE_SIZE - 1) >> PAGE_SHIFT;
80         OBD_ALLOC(pages, sizeof(*pages) * npages);
81         if (!pages)
82                 GOTO(out, rc = -ENOMEM);
83
84         desc = ptlrpc_prep_bulk_exp(req, npages, BULK_PUT_SOURCE,
85                                     MDS_BULK_PORTAL);
86         if (desc == NULL)
87                 GOTO(out_free, rc = -ENOMEM);
88
89         for (i = 0, tmpcount = count; i < npages; i++, tmpcount -= tmpsize) {
90                 tmpsize = tmpcount > PAGE_SIZE ? PAGE_SIZE : tmpcount;
91
92                 pages[i] = alloc_pages(GFP_KERNEL, 0);
93                 if (pages[i] == NULL)
94                         GOTO(cleanup_buf, rc = -ENOMEM);
95
96                 ptlrpc_prep_bulk_page(desc, pages[i], 0, tmpsize);
97         }
98
99         for (i = 0, tmpcount = count; i < npages; i++, tmpcount -= tmpsize) {
100                 tmpsize = tmpcount > PAGE_SIZE ? PAGE_SIZE : tmpcount;
101                 CDEBUG(D_EXT2, "reading %u@%llu from dir %lu (size %llu)\n",
102                        tmpsize, offset, file->f_dentry->d_inode->i_ino,
103                        file->f_dentry->d_inode->i_size);
104
105                 rc = fsfilt_readpage(req->rq_export->exp_obd, file,
106                                      kmap(pages[i]), tmpsize, &offset);
107                 kunmap(pages[i]);
108
109                 if (rc != tmpsize)
110                         GOTO(cleanup_buf, rc = -EIO);
111         }
112
113         LASSERT(desc->bd_nob == count);
114
115         rc = ptlrpc_start_bulk_transfer(desc);
116         if (rc)
117                 GOTO(cleanup_buf, rc);
118
119         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_SENDPAGE)) {
120                 CERROR("obd_fail_loc=%x, fail operation rc=%d\n",
121                        OBD_FAIL_MDS_SENDPAGE, rc = -EIO);
122                 GOTO(abort_bulk, rc);
123         }
124
125         lwi = LWI_TIMEOUT(obd_timeout * HZ / 4, NULL, NULL);
126         rc = l_wait_event(desc->bd_waitq, !ptlrpc_bulk_active(desc), &lwi);
127         LASSERT (rc == 0 || rc == -ETIMEDOUT);
128
129         if (rc == 0) {
130                 if (desc->bd_success &&
131                     desc->bd_nob_transferred == count)
132                         GOTO(cleanup_buf, rc);
133
134                 rc = -ETIMEDOUT; /* XXX should this be a different errno? */
135         }
136
137         DEBUG_REQ(D_ERROR, req, "bulk failed: %s %d(%d), evicting %s@%s\n",
138                   (rc == -ETIMEDOUT) ? "timeout" : "network error",
139                   desc->bd_nob_transferred, count,
140                   req->rq_export->exp_client_uuid.uuid,
141                   req->rq_export->exp_connection->c_remote_uuid.uuid);
142
143         ptlrpc_fail_export(req->rq_export);
144
145         EXIT;
146  abort_bulk:
147         ptlrpc_abort_bulk (desc);
148  cleanup_buf:
149         for (i = 0; i < npages; i++)
150                 if (pages[i])
151                         __free_pages(pages[i], 0);
152
153         ptlrpc_free_bulk(desc);
154  out_free:
155         OBD_FREE(pages, sizeof(*pages) * npages);
156  out:
157         return rc;
158 }
159
160 int mds_lock_mode_for_dir(struct obd_device *obd,
161                           struct dentry *dentry, int mode)
162 {
163         int ret_mode, split;
164
165         /* any dir access needs couple locks:
166          * 1) on part of dir we gonna lookup/modify in
167          * 2) on a whole dir to protect it from concurrent splitting
168          *    and to flush client's cache for readdir()
169          * so, for a given mode and dentry this routine decides what
170          * lock mode to use for lock #2:
171          * 1) if caller's gonna lookup in dir then we need to protect
172          *    dir from being splitted only - LCK_CR
173          * 2) if caller's gonna modify dir then we need to protect
174          *    dir from being splitted and to flush cache - LCK_CW
175          * 3) if caller's gonna modify dir and that dir seems ready
176          *    for splitting then we need to protect it from any
177          *    type of access (lookup/modify/split) - LCK_EX -bzzz */
178
179         split = mds_splitting_expected(obd, dentry);
180         
181         /*
182          * it is important to check here only for MDS_NO_SPLITTABLE. The reason
183          * is that MDS_NO_SPLITTABLE means dir is not splittable in principle
184          * and another thread will not split it on the quiet. But if we have
185          * MDS_NO_SPLIT_EXPECTED, this means, that dir may be splitted anytime,
186          * but not now (for current thread) and we should consider that it can
187          * happen soon and go that branch which can yield LCK_EX to protect from
188          * possible splitting.
189          */
190         if (split == MDS_NO_SPLITTABLE) {
191                 /*
192                  * this inode won't be splitted. so we need not to protect from
193                  * just flush client's cache on modification.
194                  */
195                 ret_mode = 0;
196                 if (mode == LCK_PW)
197                         ret_mode = LCK_CW;
198         } else {
199                 if (mode == LCK_EX)
200                         return LCK_EX;
201                 
202                 if (mode == LCK_PR) {
203                         ret_mode = LCK_CR;
204                 } else if (mode == LCK_PW) {
205                         /*
206                          * caller gonna modify directory.we use concurrent write
207                          * lock here to retract client's cache for readdir.
208                          */
209                         ret_mode = LCK_CW;
210                         if (split == MDS_EXPECT_SPLIT) {
211                                 /*
212                                  * splitting possible. serialize any access the
213                                  * idea is that first one seen dir is splittable
214                                  * is given exclusive lock and split
215                                  * directory. caller passes lock mode to
216                                  * mds_try_to_split_dir() and splitting would be
217                                  * done with exclusive lock only -bzzz.
218                                  */
219                                 CDEBUG(D_OTHER, "%s: gonna split %lu/%lu\n",
220                                        obd->obd_name,
221                                        (unsigned long)dentry->d_inode->i_ino,
222                                        (unsigned long)dentry->d_inode->i_generation);
223                                 ret_mode = LCK_EX;
224                         }
225                 }
226         }
227         return ret_mode;
228 }
229
230 /* only valid locked dentries or errors should be returned */
231 struct dentry *mds_id2locked_dentry(struct obd_device *obd, struct lustre_id *id,
232                                     struct vfsmount **mnt, int lock_mode,
233                                     struct lustre_handle *lockh, int *mode,
234                                     char *name, int namelen, __u64 lockpart)
235 {
236         struct dentry *de = mds_id2dentry(obd, id, mnt), *retval = de;
237         ldlm_policy_data_t policy = { .l_inodebits = { lockpart } };
238         struct ldlm_res_id res_id = { .name = {0} };
239         int flags = 0, rc;
240         ENTRY;
241
242         if (IS_ERR(de))
243                 RETURN(de);
244
245         res_id.name[0] = id_fid(id);
246         res_id.name[1] = id_group(id);
247         lockh[1].cookie = 0;
248 #ifdef S_PDIROPS
249         if (name && IS_PDIROPS(de->d_inode)) {
250                 ldlm_policy_data_t cpolicy =
251                         { .l_inodebits = { MDS_INODELOCK_UPDATE } };
252                 LASSERT(mode != NULL);
253                 *mode = mds_lock_mode_for_dir(obd, de, lock_mode);
254                 if (*mode) {
255                         rc = ldlm_cli_enqueue(NULL, NULL, obd->obd_namespace,
256                                               res_id, LDLM_IBITS,
257                                               &cpolicy, *mode, &flags,
258                                               mds_blocking_ast,
259                                               ldlm_completion_ast, NULL, NULL,
260                                               NULL, 0, NULL, lockh + 1);
261                         if (rc != ELDLM_OK) {
262                                 l_dput(de);
263                                 RETURN(ERR_PTR(-ENOLCK));
264                         }
265                 }
266                 flags = 0;
267
268                 res_id.name[2] = full_name_hash(name, namelen);
269
270                 CDEBUG(D_INFO, "take lock on "DLID4":"LPX64"\n",
271                        OLID4(id), res_id.name[2]);
272         }
273 #else
274 #warning "No PDIROPS support in the kernel"
275 #endif
276         rc = ldlm_cli_enqueue(NULL, NULL, obd->obd_namespace, res_id,
277                               LDLM_IBITS, &policy, lock_mode, &flags,
278                               mds_blocking_ast, ldlm_completion_ast,
279                               NULL, NULL, NULL, 0, NULL, lockh);
280         if (rc != ELDLM_OK) {
281                 l_dput(de);
282                 retval = ERR_PTR(-EIO); /* XXX translate ldlm code */
283 #ifdef S_PDIROPS
284                 if (lockh[1].cookie)
285                         ldlm_lock_decref(lockh + 1, LCK_CW);
286 #endif
287         }
288
289         RETURN(retval);
290 }
291
292 #ifndef DCACHE_DISCONNECTED
293 #define DCACHE_DISCONNECTED DCACHE_NFSD_DISCONNECTED
294 #endif
295
296
297 /* Look up an entry by inode number. This function ONLY returns valid dget'd
298  * dentries with an initialized inode or errors */
299 struct dentry *mds_id2dentry(struct obd_device *obd, struct lustre_id *id,
300                              struct vfsmount **mnt)
301 {
302         char idname[32];
303         struct inode *inode;
304         struct dentry *result;
305
306         struct mds_obd *mds = &obd->u.mds;
307         __u32 generation = (__u32)id_gen(id);
308         unsigned long ino = (unsigned long)id_ino(id);
309
310         if (ino == 0)
311                 RETURN(ERR_PTR(-ESTALE));
312
313         snprintf(idname, sizeof(idname), "0x%lx", ino);
314
315         CDEBUG(D_DENTRY, "--> mds_id2dentry: ino/gen %lu/%u, sb %p\n",
316                ino, generation, mds->mds_sb);
317
318         /* under ext3 this is neither supposed to return bad inodes nor NULL
319            inodes. */
320         result = ll_lookup_one_len(idname, mds->mds_id_de, 
321                                    strlen(idname));
322         if (IS_ERR(result))
323                 RETURN(result);
324
325         inode = result->d_inode;
326         if (!inode)
327                 RETURN(ERR_PTR(-ENOENT));
328
329         if (is_bad_inode(inode)) {
330                 CERROR("bad inode returned %lu/%u\n",
331                        inode->i_ino, inode->i_generation);
332                 dput(result);
333                 RETURN(ERR_PTR(-ENOENT));
334         }
335
336         /* here we disabled generation check, as root inode i_generation
337          * of cache mds and real mds are different. */
338         if (inode->i_ino != id_ino(&mds->mds_rootid) && generation &&
339             inode->i_generation != generation) {
340                 /* we didn't find the right inode.. */
341                 CERROR("bad inode %lu, link: %lu ct: %d or generation %u/%u\n",
342                        inode->i_ino, (unsigned long)inode->i_nlink,
343                        atomic_read(&inode->i_count), inode->i_generation,
344                        generation);
345                 dput(result);
346                 RETURN(ERR_PTR(-ENOENT));
347         }
348
349         if (mnt) {
350                 *mnt = mds->mds_vfsmnt;
351                 mntget(*mnt);
352         }
353
354         RETURN(result);
355 }
356
357
358 /* Establish a connection to the MDS.
359  *
360  * This will set up an export structure for the client to hold state data about
361  * that client, like open files, the last operation number it did on the server,
362  * etc.
363  */
364 static int mds_connect(struct lustre_handle *conn, struct obd_device *obd,
365                        struct obd_uuid *cluuid, unsigned long flags)
366 {
367         struct mds_obd *mds = &obd->u.mds;
368         struct mds_export_data *med;
369         struct mds_client_data *mcd;
370         struct obd_export *exp;
371         int rc;
372         ENTRY;
373
374         if (!conn || !obd || !cluuid)
375                 RETURN(-EINVAL);
376
377         /* XXX There is a small race between checking the list and adding a new
378          * connection for the same UUID, but the real threat (list corruption
379          * when multiple different clients connect) is solved.
380          *
381          * There is a second race between adding the export to the list, and
382          * filling in the client data below.  Hence skipping the case of NULL
383          * mcd above.  We should already be controlling multiple connects at the
384          * client, and we can't hold the spinlock over memory allocations
385          * without risk of deadlocking.
386          */
387         rc = class_connect(conn, obd, cluuid);
388         if (rc)
389                 RETURN(rc);
390         exp = class_conn2export(conn);
391         
392         LASSERT(exp != NULL);
393         med = &exp->exp_mds_data;
394
395         OBD_ALLOC(mcd, sizeof(*mcd));
396         if (!mcd) {
397                 CERROR("%s: out of memory for client data.\n",
398                         obd->obd_name);
399                 GOTO(out, rc = -ENOMEM);
400         }
401
402         memcpy(mcd->mcd_uuid, cluuid, sizeof(mcd->mcd_uuid));
403         med->med_mcd = mcd;
404
405         rc = mds_client_add(obd, &obd->u.mds, med, -1);
406         if (rc)
407                 GOTO(out, rc);
408
409         if (!(flags & OBD_OPT_MDS_CONNECTION)) {
410                 if (!(exp->exp_flags & OBD_OPT_REAL_CLIENT)) {
411                         atomic_inc(&mds->mds_real_clients);
412                         CDEBUG(D_OTHER,"%s: peer from %s is real client (%d)\n",
413                                obd->obd_name, exp->exp_client_uuid.uuid,
414                                atomic_read(&mds->mds_real_clients));
415                         exp->exp_flags |= OBD_OPT_REAL_CLIENT;
416                 }
417                 if (mds->mds_lmv_name)
418                         rc = mds_lmv_connect(obd, mds->mds_lmv_name);
419         }
420     
421         EXIT;
422 out:
423         if (rc) {
424                 OBD_FREE(mcd, sizeof(*mcd));
425                 class_disconnect(exp, 0);
426         } else {
427                 class_export_put(exp);
428         }
429         RETURN(rc);
430 }
431
432 static int mds_init_export(struct obd_export *exp)
433 {
434         struct mds_export_data *med = &exp->exp_mds_data;
435
436         INIT_LIST_HEAD(&med->med_open_head);
437         spin_lock_init(&med->med_open_lock);
438         RETURN(0);
439 }
440
441 static int mds_destroy_export(struct obd_export *export)
442 {
443         struct mds_export_data *med;
444         struct obd_device *obd = export->exp_obd;
445         struct lvfs_run_ctxt saved;
446         int rc = 0;
447         ENTRY;
448
449         med = &export->exp_mds_data;
450         target_destroy_export(export);
451
452         if (obd_uuid_equals(&export->exp_client_uuid, &obd->obd_uuid))
453                 GOTO(out, 0);
454
455         push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
456
457         /* Close any open files (which may also cause orphan unlinking). */
458         spin_lock(&med->med_open_lock);
459         while (!list_empty(&med->med_open_head)) {
460                 struct list_head *tmp = med->med_open_head.next;
461                 struct mds_file_data *mfd =
462                         list_entry(tmp, struct mds_file_data, mfd_list);
463                 BDEVNAME_DECLARE_STORAGE(btmp);
464
465                 /* bug 1579: fix force-closing for 2.5 */
466                 struct dentry *dentry = mfd->mfd_dentry;
467
468                 list_del(&mfd->mfd_list);
469                 spin_unlock(&med->med_open_lock);
470
471                 /* If you change this message, be sure to update
472                  * replay_single:test_46 */
473                 CERROR("force closing client file handle for %*s (%s:%lu)\n",
474                        dentry->d_name.len, dentry->d_name.name,
475                        ll_bdevname(dentry->d_inode->i_sb, btmp),
476                        dentry->d_inode->i_ino);
477                 /* child inode->i_alloc_sem protects orphan_dec_test and
478                  * is_orphan race, mds_mfd_close drops it */
479                 DOWN_WRITE_I_ALLOC_SEM(dentry->d_inode);
480                 rc = mds_mfd_close(NULL, 0, obd, mfd,
481                                    !(export->exp_flags & OBD_OPT_FAILOVER));
482                 if (rc)
483                         CDEBUG(D_INODE, "Error closing file: %d\n", rc);
484                 spin_lock(&med->med_open_lock);
485         }
486         spin_unlock(&med->med_open_lock);
487         pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
488
489 out:
490         mds_client_free(export, !(export->exp_flags & OBD_OPT_FAILOVER));
491
492         RETURN(rc);
493 }
494
495 static int mds_disconnect(struct obd_export *exp, int flags)
496 {
497         unsigned long irqflags;
498         struct obd_device *obd;
499         struct mds_obd *mds;
500         int rc;
501         ENTRY;
502
503         LASSERT(exp != NULL);
504         obd = class_exp2obd(exp);
505         if (obd == NULL) {
506                 CDEBUG(D_IOCTL, "invalid client cookie "LPX64"\n",
507                        exp->exp_handle.h_cookie);
508                 RETURN(-EINVAL);
509         }
510         mds = &obd->u.mds;
511
512         /*
513          * suppress any inter-mds requests durring disconnecting lmv if this is
514          * detected --force mode. This is needed to avoid endless recovery.
515          */
516         if (atomic_read(&mds->mds_real_clients) > 0 &&
517             !(exp->exp_flags & OBD_OPT_REAL_CLIENT))
518                 flags |= OBD_OPT_FORCE;
519                                                                                               
520         if (!(exp->exp_flags & OBD_OPT_REAL_CLIENT)
521             && !atomic_read(&mds->mds_real_clients)) {
522                 /* there was no client at all */
523                 mds_lmv_disconnect(obd, flags);
524         }
525
526         if ((exp->exp_flags & OBD_OPT_REAL_CLIENT)
527             && atomic_dec_and_test(&mds->mds_real_clients)) {
528                 /* time to drop LMV connections */
529                 CDEBUG(D_OTHER, "%s: last real client %s disconnected.  "
530                        "Disconnnect from LMV now\n",
531                        obd->obd_name, exp->exp_client_uuid.uuid);
532                 mds_lmv_disconnect(obd, flags);
533         }
534
535         spin_lock_irqsave(&exp->exp_lock, irqflags);
536         exp->exp_flags = flags;
537         spin_unlock_irqrestore(&exp->exp_lock, irqflags);
538
539         /* disconnect early so that clients can't keep using export */
540         rc = class_disconnect(exp, flags);
541         ldlm_cancel_locks_for_export(exp);
542
543         /* complete all outstanding replies */
544         spin_lock_irqsave(&exp->exp_lock, irqflags);
545         while (!list_empty(&exp->exp_outstanding_replies)) {
546                 struct ptlrpc_reply_state *rs =
547                         list_entry(exp->exp_outstanding_replies.next,
548                                    struct ptlrpc_reply_state, rs_exp_list);
549                 struct ptlrpc_service *svc = rs->rs_srv_ni->sni_service;
550
551                 spin_lock(&svc->srv_lock);
552                 list_del_init(&rs->rs_exp_list);
553                 ptlrpc_schedule_difficult_reply(rs);
554                 spin_unlock(&svc->srv_lock);
555         }
556         spin_unlock_irqrestore(&exp->exp_lock, irqflags);
557         RETURN(rc);
558 }
559
560 static int mds_getstatus(struct ptlrpc_request *req)
561 {
562         struct mds_obd *mds = mds_req2mds(req);
563         struct mds_body *body;
564         int rc, size;
565         ENTRY;
566
567         size = sizeof(*body);
568         
569         rc = lustre_pack_reply(req, 1, &size, NULL);
570         if (rc || OBD_FAIL_CHECK(OBD_FAIL_MDS_GETSTATUS_PACK)) {
571                 CERROR("mds: out of memory for message: size=%d\n", size);
572                 req->rq_status = -ENOMEM;       /* superfluous? */
573                 RETURN(-ENOMEM);
574         }
575
576         body = lustre_msg_buf(req->rq_repmsg, 0, sizeof(*body));
577         
578         body->valid |= OBD_MD_FID;
579         memcpy(&body->id1, &mds->mds_rootid, sizeof(body->id1));
580
581         /*
582          * the last_committed and last_xid fields are filled in for all replies
583          * already - no need to do so here also.
584          */
585         RETURN(0);
586 }
587
588 int mds_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
589                      void *data, int flag)
590 {
591         int do_ast;
592         ENTRY;
593
594         if (flag == LDLM_CB_CANCELING) {
595                 /* Don't need to do anything here. */
596                 RETURN(0);
597         }
598
599         /* XXX layering violation!  -phil */
600         l_lock(&lock->l_resource->lr_namespace->ns_lock);
601         
602         /*
603          * get this: if mds_blocking_ast is racing with mds_intent_policy, such
604          * that mds_blocking_ast is called just before l_i_p takes the ns_lock,
605          * then by the time we get the lock, we might not be the correct
606          * blocking function anymore.  So check, and return early, if so.
607          */
608         if (lock->l_blocking_ast != mds_blocking_ast) {
609                 l_unlock(&lock->l_resource->lr_namespace->ns_lock);
610                 RETURN(0);
611         }
612
613         lock->l_flags |= LDLM_FL_CBPENDING;
614         do_ast = (!lock->l_readers && !lock->l_writers);
615         l_unlock(&lock->l_resource->lr_namespace->ns_lock);
616
617         if (do_ast) {
618                 struct lustre_handle lockh;
619                 int rc;
620
621                 LDLM_DEBUG(lock, "already unused, calling ldlm_cli_cancel");
622                 ldlm_lock2handle(lock, &lockh);
623                 rc = ldlm_cli_cancel(&lockh);
624                 if (rc < 0)
625                         CERROR("ldlm_cli_cancel: %d\n", rc);
626         } else {
627                 LDLM_DEBUG(lock, "Lock still has references, will be "
628                            "cancelled later");
629         }
630         RETURN(0);
631 }
632
633 int mds_get_md(struct obd_device *obd, struct inode *inode, void *md,
634                int *size, int lock)
635 {
636         int rc = 0;
637         int lmm_size;
638
639         if (lock)
640                 down(&inode->i_sem);
641         rc = fsfilt_get_md(obd, inode, md, *size);
642         if (lock)
643                 up(&inode->i_sem);
644
645         if (rc < 0) {
646                 CERROR("Error %d reading eadata for ino %lu\n",
647                        rc, inode->i_ino);
648         } else if (rc > 0) {
649                 lmm_size = rc;
650                 
651                 if (S_ISREG(inode->i_mode))
652                         rc = mds_convert_lov_ea(obd, inode, md, lmm_size);
653                 if (S_ISDIR(inode->i_mode))
654                         rc = mds_convert_mea_ea(obd, inode, md, lmm_size);
655
656                 if (rc == 0) {
657                         *size = lmm_size;
658                         rc = lmm_size;
659                 } else if (rc > 0) {
660                         *size = rc;
661                 }
662         }
663
664         RETURN (rc);
665 }
666
667
668 /* Call with lock=1 if you want mds_pack_md to take the i_sem.
669  * Call with lock=0 if the caller has already taken the i_sem. */
670 int mds_pack_md(struct obd_device *obd, struct lustre_msg *msg, int offset,
671                 struct mds_body *body, struct inode *inode, int lock)
672 {
673         struct mds_obd *mds = &obd->u.mds;
674         void *lmm;
675         int lmm_size;
676         int rc;
677         ENTRY;
678
679         lmm = lustre_msg_buf(msg, offset, 0);
680         if (lmm == NULL) {
681                 /* Some problem with getting eadata when I sized the reply
682                  * buffer... */
683                 CDEBUG(D_INFO, "no space reserved for inode %lu MD\n",
684                        inode->i_ino);
685                 RETURN(0);
686         }
687         lmm_size = msg->buflens[offset];
688
689         /* I don't really like this, but it is a sanity check on the client
690          * MD request.  However, if the client doesn't know how much space
691          * to reserve for the MD, it shouldn't be bad to have too much space.
692          */
693         if (lmm_size > mds->mds_max_mdsize) {
694                 CWARN("Reading MD for inode %lu of %d bytes > max %d\n",
695                        inode->i_ino, lmm_size, mds->mds_max_mdsize);
696                 // RETURN(-EINVAL);
697         }
698
699         rc = mds_get_md(obd, inode, lmm, &lmm_size, lock);
700         if (rc > 0) {
701                 if (S_ISDIR(inode->i_mode))
702                         body->valid |= OBD_MD_FLDIREA;
703                 else
704                         body->valid |= OBD_MD_FLEASIZE;
705                 body->eadatasize = lmm_size;
706                 rc = 0;
707         }
708
709         RETURN(rc);
710 }
711
712 void mds_squash_root(struct mds_obd *mds, struct mds_req_sec_desc *rsd,
713                      ptl_nid_t *peernid)
714 {
715         if (!mds->mds_squash_uid ||
716             (rsd->rsd_uid && rsd->rsd_fsuid))
717                 return;
718
719         if (*peernid == mds->mds_nosquash_nid)
720                 return;
721
722         CDEBUG(D_OTHER, "squash req from 0x%llx, (%d:%d/%x)=>(%d:%d/%x)\n",
723                 *peernid, rsd->rsd_fsuid, rsd->rsd_fsgid, rsd->rsd_cap,
724                 mds->mds_squash_uid, mds->mds_squash_gid,
725                 (rsd->rsd_cap & ~CAP_FS_MASK));
726
727         rsd->rsd_uid = mds->mds_squash_uid;
728         rsd->rsd_fsuid = mds->mds_squash_uid;
729         rsd->rsd_fsgid = mds->mds_squash_gid;
730
731         /* XXX should we remove all capabilities? */
732         rsd->rsd_cap &= ~CAP_FS_MASK;
733 }
734
735 static int mds_getattr_internal(struct obd_device *obd, struct dentry *dentry,
736                                 struct ptlrpc_request *req, struct mds_body *reqbody,
737                                 int reply_off)
738 {
739         struct inode *inode = dentry->d_inode;
740         struct mds_body *body;
741         int rc = 0;
742         ENTRY;
743
744         if (inode == NULL && !(dentry->d_flags & DCACHE_CROSS_REF))
745                 RETURN(-ENOENT);
746
747         body = lustre_msg_buf(req->rq_repmsg, reply_off, sizeof(*body));
748         LASSERT(body != NULL);                 /* caller prepped reply */
749
750         if (dentry->d_flags & DCACHE_CROSS_REF) {
751                 mds_pack_dentry2body(obd, body, dentry,
752                                      (reqbody->valid & OBD_MD_FID));
753                 CDEBUG(D_OTHER, "cross reference: "DLID4"\n",
754                        OLID4(&body->id1));
755                 RETURN(0);
756         }
757         
758         mds_pack_inode2body(obd, body, inode, (reqbody->valid & OBD_MD_FID));
759
760         if ((S_ISREG(inode->i_mode) && (reqbody->valid & OBD_MD_FLEASIZE)) ||
761             (S_ISDIR(inode->i_mode) && (reqbody->valid & OBD_MD_FLDIREA))) {
762                 rc = mds_pack_md(obd, req->rq_repmsg, reply_off + 1, body,
763                                  inode, 1);
764
765                 /* if we have LOV EA data, the OST holds size, atime, mtime. */
766                 if (!(body->valid & OBD_MD_FLEASIZE) &&
767                     !(body->valid & OBD_MD_FLDIREA))
768                         body->valid |= (OBD_MD_FLSIZE | OBD_MD_FLBLOCKS |
769                                         OBD_MD_FLATIME | OBD_MD_FLMTIME);
770         } else if (S_ISLNK(inode->i_mode) &&
771                    (reqbody->valid & OBD_MD_LINKNAME) != 0) {
772                 int len = req->rq_repmsg->buflens[reply_off + 1];
773                 char *symname = lustre_msg_buf(req->rq_repmsg, reply_off + 1, 0);
774
775                 LASSERT(symname != NULL);       /* caller prepped reply */
776
777                 if (!inode->i_op->readlink) {
778                         rc = -ENOSYS;
779                 } else {
780                         rc = inode->i_op->readlink(dentry, symname, len);
781                         if (rc < 0) {
782                                 CERROR("readlink failed: %d\n", rc);
783                         } else if (rc != len - 1) {
784                                 CERROR("Unexpected readlink rc %d: expecting %d\n",
785                                         rc, len - 1);
786                                 rc = -EINVAL;
787                         } else {
788                                 CDEBUG(D_INODE, "read symlink dest %s\n", symname);
789                                 body->valid |= OBD_MD_LINKNAME;
790                                 body->eadatasize = rc + 1;
791                                 symname[rc] = 0;
792                                 rc = 0;
793                         }
794                 }
795         }
796
797         RETURN(rc);
798 }
799
800 static int mds_getattr_pack_msg_cf(struct ptlrpc_request *req,
801                                    struct dentry *dentry,
802                                    int offset)
803 {
804         int rc = 0, size[1] = {sizeof(struct mds_body)};
805         ENTRY;
806
807         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_GETATTR_PACK)) {
808                 CERROR("failed MDS_GETATTR_PACK test\n");
809                 req->rq_status = -ENOMEM;
810                 GOTO(out, rc = -ENOMEM);
811         }
812
813         rc = lustre_pack_reply(req, 1, size, NULL);
814         if (rc) {
815                 CERROR("lustre_pack_reply failed: rc %d\n", rc);
816                 GOTO(out, req->rq_status = rc);
817         }
818
819  out:
820         RETURN(rc);
821 }
822
823 static int mds_getattr_pack_msg(struct ptlrpc_request *req, struct inode *inode,
824                                 int offset)
825 {
826         struct mds_obd *mds = mds_req2mds(req);
827         struct mds_body *body;
828         int rc = 0, size[2] = {sizeof(*body)}, bufcount = 1;
829         ENTRY;
830
831         body = lustre_msg_buf(req->rq_reqmsg, offset, sizeof (*body));
832         LASSERT(body != NULL);                 /* checked by caller */
833         LASSERT_REQSWABBED(req, offset);       /* swabbed by caller */
834
835         if ((S_ISREG(inode->i_mode) && (body->valid & OBD_MD_FLEASIZE)) ||
836             (S_ISDIR(inode->i_mode) && (body->valid & OBD_MD_FLDIREA))) {
837                 int rc;
838                 down(&inode->i_sem);
839                 rc = fsfilt_get_md(req->rq_export->exp_obd, inode, NULL, 0);
840                 up(&inode->i_sem);
841                 CDEBUG(D_INODE, "got %d bytes MD data for inode %lu\n",
842                        rc, inode->i_ino);
843                 if (rc < 0) {
844                         if (rc != -ENODATA)
845                                 CERROR("error getting inode %lu MD: rc = %d\n",
846                                        inode->i_ino, rc);
847                         size[bufcount] = 0;
848                 } else if (rc > mds->mds_max_mdsize) {
849                         size[bufcount] = 0;
850                         CERROR("MD size %d larger than maximum possible %u\n",
851                                rc, mds->mds_max_mdsize);
852                 } else {
853                         size[bufcount] = rc;
854                 }
855                 bufcount++;
856         } else if (S_ISLNK(inode->i_mode) && (body->valid & OBD_MD_LINKNAME)) {
857                 if (inode->i_size + 1 != body->eadatasize)
858                         CERROR("symlink size: %Lu, reply space: %d\n",
859                                inode->i_size + 1, body->eadatasize);
860                 size[bufcount] = min_t(int, inode->i_size+1, body->eadatasize);
861                 bufcount++;
862                 CDEBUG(D_INODE, "symlink size: %Lu, reply space: %d\n",
863                        inode->i_size + 1, body->eadatasize);
864         }
865
866         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_GETATTR_PACK)) {
867                 CERROR("failed MDS_GETATTR_PACK test\n");
868                 req->rq_status = -ENOMEM;
869                 GOTO(out, rc = -ENOMEM);
870         }
871
872         rc = lustre_pack_reply(req, bufcount, size, NULL);
873         if (rc) {
874                 CERROR("out of memory\n");
875                 GOTO(out, req->rq_status = rc);
876         }
877
878  out:
879         RETURN(rc);
880 }
881
882 int mds_check_mds_num(struct obd_device *obd, struct inode* inode,
883                       char *name, int namelen)
884 {
885         struct mea *mea = NULL;
886         int mea_size, rc = 0;
887         ENTRY;
888         
889         rc = mds_get_lmv_attr(obd, inode, &mea, &mea_size);
890         if (rc)
891                 RETURN(rc);
892         if (mea != NULL) {
893                 /*
894                  * dir is already splitted, check if requested filename should
895                  * live at this MDS or at another one.
896                  */
897                 int i = mea_name2idx(mea, name, namelen - 1);
898                 if (mea->mea_master != id_group(&mea->mea_ids[i])) {
899                         CDEBUG(D_OTHER,
900                                "inapropriate MDS(%d) for %s. should be "
901                                "%lu(%d)\n", mea->mea_master, name, 
902                                (unsigned long)id_group(&mea->mea_ids[i]), i);
903                         rc = -ERESTART;
904                 }
905         }
906
907         if (mea)
908                 OBD_FREE(mea, mea_size);
909         RETURN(rc);
910 }
911
912 static int mds_getattr_lock(struct ptlrpc_request *req, int offset,
913                             struct lustre_handle *child_lockh, int child_part)
914 {
915         struct obd_device *obd = req->rq_export->exp_obd;
916         struct mds_obd *mds = &obd->u.mds;
917         struct ldlm_reply *rep = NULL;
918         struct lvfs_run_ctxt saved;
919         struct mds_req_sec_desc *rsd;
920         struct mds_body *body;
921         struct dentry *dparent = NULL, *dchild = NULL;
922         struct lvfs_ucred uc;
923         struct lustre_handle parent_lockh[2] = {{0}, {0}};
924         unsigned int namesize;
925         int rc = 0, cleanup_phase = 0, resent_req = 0, update_mode, reply_offset;
926         char *name = NULL;
927         ENTRY;
928
929         LASSERT(!strcmp(obd->obd_type->typ_name, LUSTRE_MDS_NAME));
930         MDS_UPDATE_COUNTER((&obd->u.mds), MDS_GETATTR_NAME_COUNT);
931
932         rsd = lustre_swab_mds_secdesc(req, MDS_REQ_SECDESC_OFF);
933         if (!rsd) {
934                 CERROR("Can't unpack security desc\n");
935                 RETURN(-EFAULT);
936         }
937         mds_squash_root(mds, rsd, &req->rq_peer.peer_id.nid); 
938
939         /* swab now, before anyone looks inside the request. */
940         body = lustre_swab_reqbuf(req, offset, sizeof(*body),
941                                   lustre_swab_mds_body);
942         if (body == NULL) {
943                 CERROR("Can't swab mds_body\n");
944                 GOTO(cleanup, rc = -EFAULT);
945         }
946
947         LASSERT_REQSWAB(req, offset + 1);
948         name = lustre_msg_string(req->rq_reqmsg, offset + 1, 0);
949         if (name == NULL) {
950                 CERROR("Can't unpack name\n");
951                 GOTO(cleanup, rc = -EFAULT);
952         }
953         namesize = req->rq_reqmsg->buflens[offset + 1];
954
955         /* namesize less than 2 means we have empty name, probably came from
956            revalidate by cfid, so no point in having name to be set */
957         if (namesize <= 1)
958                 name = NULL;
959
960         LASSERT (offset == 1 || offset == 3);
961         if (offset == 3) {
962                 rep = lustre_msg_buf(req->rq_repmsg, 0, sizeof (*rep));
963                 reply_offset = 1;
964         } else {
965                 reply_offset = 0;
966         }
967
968         rc = mds_init_ucred(&uc, rsd);
969         if (rc) {
970                 CERROR("can't init ucred\n");
971                 GOTO(cleanup, rc);
972         }
973
974         push_ctxt(&saved, &obd->obd_lvfs_ctxt, &uc);
975         cleanup_phase = 1; /* kernel context */
976         intent_set_disposition(rep, DISP_LOOKUP_EXECD);
977
978         LASSERT(namesize > 0);
979         if (child_lockh->cookie != 0) {
980                 LASSERT(lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT);
981                 resent_req = 1;
982         }
983 #if 0        
984 #if HAVE_LOOKUP_RAW
985         if (body->valid == OBD_MD_FLID) {
986                 struct mds_body *mds_reply;
987                 int size = sizeof(*mds_reply);
988                 struct inode *dir;
989                 ino_t inum;
990
991                 dparent = mds_id2dentry(obd, &body->id1, NULL);
992                 if (IS_ERR(dparent)) {
993                         rc = PTR_ERR(dparent);
994                         GOTO(cleanup, rc);
995                 }
996
997                 /*
998                  * the user requested ONLY the inode number, so do a raw lookup.
999                  */
1000                 rc = lustre_pack_reply(req, 1, &size, NULL);
1001                 if (rc) {
1002                         CERROR("out of memory\n");
1003                         l_dput(dparent);
1004                         GOTO(cleanup, rc);
1005                 }
1006                 dir  = dparent->d_inode;
1007                 LASSERT(dir->i_op->lookup_raw != NULL);
1008                 rc = dir->i_op->lookup_raw(dir, name, namesize - 1, &inum);
1009                 l_dput(dparent);
1010                 mds_reply = lustre_msg_buf(req->rq_repmsg, 0,
1011                                            sizeof(*mds_reply));
1012
1013                 id_ino(&mds_reply->id1) = inum;
1014                 mds_reply->valid = OBD_MD_FLID;
1015                 GOTO(cleanup, rc);
1016         }
1017 #endif
1018 #endif
1019         if (resent_req == 0) {
1020                 if (name) {
1021                         rc = mds_get_parent_child_locked(obd, mds, &body->id1,
1022                                                          parent_lockh, &dparent,
1023                                                          LCK_PR, 
1024                                                          MDS_INODELOCK_LOOKUP,
1025                                                          &update_mode, 
1026                                                          name, namesize,
1027                                                          child_lockh, &dchild, 
1028                                                          LCK_PR, child_part);
1029                 } else {
1030                         /* we have no dentry here, drop LOOKUP bit */
1031                         /*FIXME: we need MDS_INODELOCK_LOOKUP or not*/
1032                         child_part &= ~MDS_INODELOCK_LOOKUP;
1033                         CDEBUG(D_OTHER, "%s: retrieve attrs for %lu/%lu\n",
1034                                obd->obd_name, (unsigned long)id_ino(&body->id1),
1035                                (unsigned long)id_gen(&body->id1));
1036
1037 #if 0
1038                         dchild = mds_id2locked_dentry(obd, &body->id1, NULL, 
1039                                                       LCK_PR, parent_lockh, 
1040                                                       &update_mode,
1041                                                       NULL, 0, child_part);
1042 #else
1043                         dchild = mds_id2locked_dentry(obd, &body->id1, NULL,
1044                                                       LCK_PR, parent_lockh,
1045                                                       &update_mode,
1046                                                       NULL, 0, 
1047                                                       MDS_INODELOCK_UPDATE);
1048 #endif 
1049                         if (IS_ERR(dchild)) {
1050                                 CERROR("can't find inode: %d\n", 
1051                                        (int) PTR_ERR(dchild));
1052                                 GOTO(cleanup, rc = PTR_ERR(dchild));
1053                         }
1054                         memcpy(child_lockh, parent_lockh, 
1055                                sizeof(parent_lockh[0]));
1056 #ifdef S_PDIROPS
1057                         if (parent_lockh[1].cookie)
1058                                 ldlm_lock_decref(parent_lockh + 1, update_mode);
1059 #endif
1060                         cleanup_phase = 2;
1061                         goto fill_inode;
1062                 }
1063                 if (rc)
1064                         GOTO(cleanup, rc);
1065                 
1066                 /* let's make sure this name should leave on this mds node */
1067                 rc = mds_check_mds_num(obd, dparent->d_inode, name, namesize);
1068                 if (rc)
1069                         GOTO(cleanup, rc);
1070         } else {
1071                 struct ldlm_lock *granted_lock;
1072
1073                 DEBUG_REQ(D_DLMTRACE, req, "resent, not enqueuing new locks");
1074                 granted_lock = ldlm_handle2lock(child_lockh);
1075
1076                 LASSERTF(granted_lock != NULL, LPU64"/%lu lockh "LPX64"\n",
1077                          id_fid(&body->id1), (unsigned long)id_group(&body->id1),
1078                          child_lockh->cookie);
1079
1080                 dparent = mds_id2dentry(obd, &body->id1, NULL);
1081                 LASSERT(!IS_ERR(dparent));
1082
1083                 dchild = ll_lookup_one_len(name, dparent, namesize - 1);
1084                 LASSERT(!IS_ERR(dchild));
1085                 
1086                 l_dput(dparent);
1087                 resent_req = 1;
1088         }
1089
1090         cleanup_phase = 2; /* dchild, dparent, locks */
1091
1092 fill_inode:
1093         if (!DENTRY_VALID(dchild)) {
1094                 intent_set_disposition(rep, DISP_LOOKUP_NEG);
1095                 /*
1096                  * in the intent case, the policy clears this error: the
1097                  * disposition is enough.
1098                  */
1099                 rc = -ENOENT;
1100                 GOTO(cleanup, rc);
1101         } else {
1102                 intent_set_disposition(rep, DISP_LOOKUP_POS);
1103         }
1104
1105         if (req->rq_repmsg == NULL) {
1106                 if (dchild->d_flags & DCACHE_CROSS_REF)
1107                         rc = mds_getattr_pack_msg_cf(req, dchild, offset);
1108                 else
1109                         rc = mds_getattr_pack_msg(req, dchild->d_inode, offset);
1110                 if (rc != 0) {
1111                         CERROR ("mds_getattr_pack_msg: %d\n", rc);
1112                         GOTO (cleanup, rc);
1113                 }
1114         }
1115
1116         rc = mds_getattr_internal(obd, dchild, req, body, reply_offset);
1117         GOTO(cleanup, rc); /* returns the lock to the client */
1118
1119  cleanup:
1120         switch (cleanup_phase) {
1121         case 2:
1122                 if (resent_req == 0) {
1123                         if (rc && DENTRY_VALID(dchild))
1124                                 ldlm_lock_decref(child_lockh, LCK_PR);
1125                         if (name) {
1126                                 ldlm_lock_decref(parent_lockh, LCK_PR);
1127                         }
1128 #ifdef S_PDIROPS
1129                         if (parent_lockh[1].cookie != 0)
1130                                 ldlm_lock_decref(parent_lockh + 1, update_mode);
1131 #endif
1132                         if (dparent)
1133                                 l_dput(dparent);
1134                 }
1135                 l_dput(dchild);
1136         case 1:
1137                 pop_ctxt(&saved, &obd->obd_lvfs_ctxt, &uc);
1138                 mds_exit_ucred(&uc);
1139         }
1140         RETURN(rc);
1141 }
1142
1143 static int mds_getattr(struct ptlrpc_request *req, int offset)
1144 {
1145         struct obd_device *obd = req->rq_export->exp_obd;
1146         struct mds_obd *mds = &obd->u.mds;
1147         struct lvfs_run_ctxt saved;
1148         struct dentry *de;
1149         struct mds_req_sec_desc *rsd;
1150         struct mds_body *body;
1151         struct lvfs_ucred uc;
1152         int rc = 0;
1153         ENTRY;
1154
1155         rsd = lustre_swab_mds_secdesc(req, MDS_REQ_SECDESC_OFF);
1156         if (!rsd) {
1157                 CERROR("Can't unpack security desc\n");
1158                 RETURN(-EFAULT);
1159         }
1160
1161         body = lustre_swab_reqbuf(req, offset, sizeof(*body),
1162                                   lustre_swab_mds_body);
1163         if (body == NULL) {
1164                 CERROR ("Can't unpack body\n");
1165                 RETURN (-EFAULT);
1166         }
1167
1168         MDS_UPDATE_COUNTER(mds, MDS_GETATTR_COUNT);
1169
1170         rc = mds_init_ucred(&uc, rsd);
1171         if (rc) {
1172                 CERROR("can't init ucred\n");
1173                 RETURN(rc);
1174         }
1175
1176         push_ctxt(&saved, &obd->obd_lvfs_ctxt, &uc);
1177         de = mds_id2dentry(obd, &body->id1, NULL);
1178         if (IS_ERR(de)) {
1179                 rc = req->rq_status = PTR_ERR(de);
1180                 GOTO(out_pop, rc);
1181         }
1182
1183         rc = mds_getattr_pack_msg(req, de->d_inode, offset);
1184         if (rc != 0) {
1185                 CERROR("mds_getattr_pack_msg: %d\n", rc);
1186                 GOTO(out_pop, rc);
1187         }
1188
1189         req->rq_status = mds_getattr_internal(obd, de, req, body, 0);
1190
1191         l_dput(de);
1192         GOTO(out_pop, rc);
1193 out_pop:
1194         pop_ctxt(&saved, &obd->obd_lvfs_ctxt, &uc);
1195         mds_exit_ucred(&uc);
1196         RETURN(rc);
1197 }
1198
1199 static int mds_obd_statfs(struct obd_device *obd, struct obd_statfs *osfs,
1200                           unsigned long max_age)
1201 {
1202         int rc;
1203         ENTRY;
1204
1205         spin_lock(&obd->obd_osfs_lock);
1206         rc = fsfilt_statfs(obd, obd->u.mds.mds_sb, max_age);
1207         if (rc == 0)
1208                 memcpy(osfs, &obd->obd_osfs, sizeof(*osfs));
1209         spin_unlock(&obd->obd_osfs_lock);
1210
1211         RETURN(rc);
1212 }
1213
1214 static int mds_statfs(struct ptlrpc_request *req)
1215 {
1216         struct obd_device *obd = req->rq_export->exp_obd;
1217         int rc, size = sizeof(struct obd_statfs);
1218         ENTRY;
1219
1220         rc = lustre_pack_reply(req, 1, &size, NULL);
1221         if (rc || OBD_FAIL_CHECK(OBD_FAIL_MDS_STATFS_PACK)) {
1222                 CERROR("mds: statfs lustre_pack_reply failed: rc = %d\n", rc);
1223                 GOTO(out, rc);
1224         }
1225
1226         MDS_UPDATE_COUNTER((&obd->u.mds), MDS_STATFS_COUNT);
1227
1228         /* We call this so that we can cache a bit - 1 jiffie worth */
1229         rc = mds_obd_statfs(obd, lustre_msg_buf(req->rq_repmsg, 0, size),
1230                             jiffies - HZ);
1231         if (rc) {
1232                 CERROR("mds_obd_statfs failed: rc %d\n", rc);
1233                 GOTO(out, rc);
1234         }
1235
1236 out:
1237         req->rq_status = rc;
1238         RETURN(0);
1239 }
1240
1241 static int mds_sync(struct ptlrpc_request *req, int offset)
1242 {
1243         struct obd_device *obd = req->rq_export->exp_obd;
1244         struct mds_obd *mds = &obd->u.mds;
1245         struct mds_body *body;
1246         int rc, size = sizeof(*body);
1247         ENTRY;
1248
1249         body = lustre_msg_buf(req->rq_reqmsg, offset, sizeof(*body));
1250         if (body == NULL)
1251                 GOTO(out, rc = -EPROTO);
1252
1253         rc = lustre_pack_reply(req, 1, &size, NULL);
1254         if (rc || OBD_FAIL_CHECK(OBD_FAIL_MDS_SYNC_PACK)) {
1255                 CERROR("fsync lustre_pack_reply failed: rc = %d\n", rc);
1256                 GOTO(out, rc);
1257         }
1258
1259         if (id_ino(&body->id1) == 0) {
1260                 /* an id of zero is taken to mean "sync whole filesystem" */
1261                 rc = fsfilt_sync(obd, mds->mds_sb);
1262                 if (rc)
1263                         GOTO(out, rc);
1264         } else {
1265                 /* just any file to grab fsync method - "file" arg unused */
1266                 struct file *file = mds->mds_rcvd_filp;
1267                 struct dentry *de;
1268
1269                 de = mds_id2dentry(obd, &body->id1, NULL);
1270                 if (IS_ERR(de))
1271                         GOTO(out, rc = PTR_ERR(de));
1272
1273                 rc = file->f_op->fsync(NULL, de, 1);
1274                 if (rc)
1275                         GOTO(out, rc);
1276
1277                 body = lustre_msg_buf(req->rq_repmsg, 0, sizeof(*body));
1278                 mds_pack_inode2body(obd, body, de->d_inode, 0);
1279                 l_dput(de);
1280         }
1281 out:
1282         req->rq_status = rc;
1283         RETURN(0);
1284 }
1285
1286 /* mds_readpage does not take a DLM lock on the inode, because the client must
1287  * already have a PR lock.
1288  *
1289  * If we were to take another one here, a deadlock will result, if another
1290  * thread is already waiting for a PW lock. */
1291 static int mds_readpage(struct ptlrpc_request *req, int offset)
1292 {
1293         struct obd_device *obd = req->rq_export->exp_obd;
1294         struct mds_obd *mds = &obd->u.mds;
1295         struct vfsmount *mnt;
1296         struct dentry *de;
1297         struct file *file;
1298         struct mds_req_sec_desc *rsd;
1299         struct mds_body *body, *repbody;
1300         struct lvfs_run_ctxt saved;
1301         int rc, size = sizeof(*repbody);
1302         struct lvfs_ucred uc;
1303         ENTRY;
1304
1305         rc = lustre_pack_reply(req, 1, &size, NULL);
1306         if (rc || OBD_FAIL_CHECK(OBD_FAIL_MDS_READPAGE_PACK)) {
1307                 CERROR("mds: out of memory\n");
1308                 GOTO(out, rc = -ENOMEM);
1309         }
1310
1311         rsd = lustre_swab_mds_secdesc(req, MDS_REQ_SECDESC_OFF);
1312         if (!rsd) {
1313                 CERROR("Can't unpack security desc\n");
1314                 GOTO (out, rc = -EFAULT);
1315         }
1316         mds_squash_root(mds, rsd, &req->rq_peer.peer_id.nid); 
1317
1318         body = lustre_swab_reqbuf(req, offset, sizeof(*body),
1319                                   lustre_swab_mds_body);
1320         if (body == NULL) {
1321                 CERROR("Can't unpack body\n");
1322                 GOTO (out, rc = -EFAULT);
1323         }
1324
1325         rc = mds_init_ucred(&uc, rsd);
1326         if (rc) {
1327                 CERROR("can't init ucred\n");
1328                 GOTO(out, rc);
1329         }
1330
1331         push_ctxt(&saved, &obd->obd_lvfs_ctxt, &uc);
1332         de = mds_id2dentry(obd, &body->id1, &mnt);
1333         if (IS_ERR(de))
1334                 GOTO(out_pop, rc = PTR_ERR(de));
1335
1336         CDEBUG(D_INODE, "ino %lu\n", de->d_inode->i_ino);
1337
1338         file = dentry_open(de, mnt, O_RDONLY | O_LARGEFILE);
1339         /* note: in case of an error, dentry_open puts dentry */
1340         if (IS_ERR(file))
1341                 GOTO(out_pop, rc = PTR_ERR(file));
1342
1343         /* body->size is actually the offset -eeb */
1344         if ((body->size & (de->d_inode->i_blksize - 1)) != 0) {
1345                 CERROR("offset "LPU64" not on a block boundary of %lu\n",
1346                        body->size, de->d_inode->i_blksize);
1347                 GOTO(out_file, rc = -EFAULT);
1348         }
1349
1350         /* body->nlink is actually the #bytes to read -eeb */
1351         if (body->nlink & (de->d_inode->i_blksize - 1)) {
1352                 CERROR("size %u is not multiple of blocksize %lu\n",
1353                        body->nlink, de->d_inode->i_blksize);
1354                 GOTO(out_file, rc = -EFAULT);
1355         }
1356
1357         repbody = lustre_msg_buf(req->rq_repmsg, 0, sizeof (*repbody));
1358         repbody->size = file->f_dentry->d_inode->i_size;
1359         repbody->valid = OBD_MD_FLSIZE;
1360
1361         /* to make this asynchronous make sure that the handling function
1362            doesn't send a reply when this function completes. Instead a
1363            callback function would send the reply */
1364         /* body->size is actually the offset -eeb */
1365         rc = mds_sendpage(req, file, body->size, body->nlink);
1366
1367 out_file:
1368         filp_close(file, 0);
1369 out_pop:
1370         pop_ctxt(&saved, &obd->obd_lvfs_ctxt, &uc);
1371         mds_exit_ucred(&uc);
1372 out:
1373         req->rq_status = rc;
1374         RETURN(0);
1375 }
1376
1377 /* update master MDS ID, which is stored in local inode EA. */
1378 int mds_update_mid(struct obd_device *obd, struct lustre_id *id,
1379                    void *data, int data_len)
1380 {
1381         struct mds_obd *mds = &obd->u.mds;
1382         struct dentry *dentry;
1383         void *handle;
1384         int rc = 0;
1385         ENTRY;
1386
1387         LASSERT(id);
1388         LASSERT(obd);
1389         
1390         dentry = mds_id2dentry(obd, id, NULL);
1391         if (IS_ERR(dentry))
1392                 GOTO(out, rc = PTR_ERR(dentry));
1393
1394         if (!dentry->d_inode) {
1395                 CERROR("Can't find object "DLID4".\n",
1396                        OLID4(id));
1397                 GOTO(out_dentry, rc = -EINVAL);
1398         }
1399
1400         handle = fsfilt_start(obd, dentry->d_inode,
1401                               FSFILT_OP_SETATTR, NULL);
1402         if (IS_ERR(handle))
1403                 GOTO(out_dentry, rc = PTR_ERR(handle));
1404
1405         rc = mds_update_inode_mid(obd, dentry->d_inode, handle,
1406                                   (struct lustre_id *)data);
1407         if (rc) {
1408                 CERROR("Can't update inode "DLID4" master id, "
1409                        "error = %d.\n", OLID4(id), rc);
1410                 GOTO(out_commit, rc);
1411         }
1412
1413 out_commit:
1414         fsfilt_commit(obd, mds->mds_sb, dentry->d_inode,
1415                       handle, 0);
1416 out_dentry:
1417         l_dput(dentry);
1418 out:
1419         RETURN(rc);
1420 }
1421 EXPORT_SYMBOL(mds_update_mid);
1422
1423 /* read master MDS ID, which is stored in local inode EA. */
1424 int mds_read_mid(struct obd_device *obd, struct lustre_id *id,
1425                  void *data, int data_len)
1426 {
1427         struct dentry *dentry;
1428         int rc = 0;
1429         ENTRY;
1430
1431         LASSERT(id);
1432         LASSERT(obd);
1433         
1434         dentry = mds_id2dentry(obd, id, NULL);
1435         if (IS_ERR(dentry))
1436                 GOTO(out, rc = PTR_ERR(dentry));
1437
1438         if (!dentry->d_inode) {
1439                 CERROR("Can't find object "DLID4".\n",
1440                        OLID4(id));
1441                 GOTO(out_dentry, rc = -EINVAL);
1442         }
1443
1444         down(&dentry->d_inode->i_sem);
1445         rc = mds_read_inode_mid(obd, dentry->d_inode,
1446                                 (struct lustre_id *)data);
1447         up(&dentry->d_inode->i_sem);
1448         if (rc) {
1449                 CERROR("Can't read inode "DLID4" master id, "
1450                        "error = %d.\n", OLID4(id), rc);
1451                 GOTO(out_dentry, rc);
1452         }
1453
1454 out_dentry:
1455         l_dput(dentry);
1456 out:
1457         RETURN(rc);
1458 }
1459 EXPORT_SYMBOL(mds_read_mid);
1460
1461 int mds_reint(struct ptlrpc_request *req, int offset,
1462               struct lustre_handle *lockh)
1463 {
1464         struct mds_obd *mds = &req->rq_export->exp_obd->u.mds;
1465         struct mds_update_record *rec;
1466         struct mds_req_sec_desc *rsd;
1467         int rc;
1468         ENTRY;
1469
1470         OBD_ALLOC(rec, sizeof(*rec));
1471         if (rec == NULL)
1472                 RETURN(-ENOMEM);
1473
1474         rsd = lustre_swab_mds_secdesc(req, MDS_REQ_SECDESC_OFF);
1475         if (!rsd) {
1476                 CERROR("Can't unpack security desc\n");
1477                 GOTO(out, rc = -EFAULT);
1478         }
1479         mds_squash_root(mds, rsd, &req->rq_peer.peer_id.nid); 
1480
1481         rc = mds_update_unpack(req, offset, rec);
1482         if (rc || OBD_FAIL_CHECK(OBD_FAIL_MDS_REINT_UNPACK)) {
1483                 CERROR("invalid record\n");
1484                 GOTO(out, req->rq_status = -EINVAL);
1485         }
1486
1487         rc = mds_init_ucred(&rec->ur_uc, rsd);
1488         if (rc) {
1489                 CERROR("can't init ucred\n");
1490                 GOTO(out, rc);
1491         }
1492
1493         /* rc will be used to interrupt a for loop over multiple records */
1494         rc = mds_reint_rec(rec, offset, req, lockh);
1495         mds_exit_ucred(&rec->ur_uc);
1496  out:
1497         OBD_FREE(rec, sizeof(*rec));
1498         RETURN(rc);
1499 }
1500
1501 static int mds_filter_recovery_request(struct ptlrpc_request *req,
1502                                        struct obd_device *obd, int *process)
1503 {
1504         switch (req->rq_reqmsg->opc) {
1505         case MDS_CONNECT: /* This will never get here, but for completeness. */
1506         case OST_CONNECT: /* This will never get here, but for completeness. */
1507         case MDS_DISCONNECT:
1508         case OST_DISCONNECT:
1509                *process = 1;
1510                RETURN(0);
1511
1512         case MDS_CLOSE:
1513         case MDS_SYNC: /* used in unmounting */
1514         case OBD_PING:
1515         case MDS_REINT:
1516         case LDLM_ENQUEUE:
1517         case OST_CREATE:
1518                 *process = target_queue_recovery_request(req, obd);
1519                 RETURN(0);
1520
1521         default:
1522                 DEBUG_REQ(D_ERROR, req, "not permitted during recovery");
1523                 *process = 0;
1524                 /* XXX what should we set rq_status to here? */
1525                 req->rq_status = -EAGAIN;
1526                 RETURN(ptlrpc_error(req));
1527         }
1528 }
1529
1530 static char *reint_names[] = {
1531         [REINT_SETATTR] "setattr",
1532         [REINT_CREATE]  "create",
1533         [REINT_LINK]    "link",
1534         [REINT_UNLINK]  "unlink",
1535         [REINT_RENAME]  "rename",
1536         [REINT_OPEN]    "open",
1537 };
1538
1539 #define FILTER_VALID_FLAGS (OBD_MD_FLTYPE | OBD_MD_FLMODE | OBD_MD_FLGENER  | \
1540                             OBD_MD_FLSIZE | OBD_MD_FLBLOCKS | OBD_MD_FLBLKSZ| \
1541                             OBD_MD_FLATIME | OBD_MD_FLMTIME | OBD_MD_FLCTIME| \
1542                             OBD_MD_FLID) 
1543
1544 static void reconstruct_create(struct ptlrpc_request *req)
1545 {
1546         struct mds_export_data *med = &req->rq_export->exp_mds_data;
1547         struct mds_client_data *mcd = med->med_mcd;
1548         struct dentry *dentry;
1549         struct ost_body *body;
1550         struct lustre_id id;
1551         int rc;
1552         ENTRY;
1553
1554         /* copy rc, transno and disp; steal locks */
1555         mds_req_from_mcd(req, mcd);
1556         if (req->rq_status) {
1557                 EXIT;
1558                 return;
1559         }
1560
1561         id_gen(&id) = 0;
1562         id_group(&id) = 0;
1563
1564         id_ino(&id) = mcd->mcd_last_data;
1565         LASSERT(id_ino(&id) != 0);
1566
1567         dentry = mds_id2dentry(req2obd(req), &id, NULL);
1568         if (IS_ERR(dentry)) {
1569                 CERROR("can't find inode "LPU64"\n", id_ino(&id));
1570                 req->rq_status = PTR_ERR(dentry);
1571                 EXIT;
1572                 return;
1573         }
1574
1575         CWARN("reconstruct reply for x"LPU64" (remote ino) "LPU64" -> %lu/%u\n",
1576               req->rq_xid, id_ino(&id), dentry->d_inode->i_ino,
1577               dentry->d_inode->i_generation);
1578
1579         body = lustre_msg_buf(req->rq_repmsg, 0, sizeof (*body));
1580         obdo_from_inode(&body->oa, dentry->d_inode, FILTER_VALID_FLAGS);
1581         body->oa.o_id = dentry->d_inode->i_ino;
1582         body->oa.o_generation = dentry->d_inode->i_generation;
1583         body->oa.o_valid |= OBD_MD_FLID | OBD_MD_FLGENER;
1584
1585         down(&dentry->d_inode->i_sem);
1586         rc = mds_read_inode_sid(req2obd(req), dentry->d_inode, &id);
1587         up(&dentry->d_inode->i_sem);
1588         if (rc) {
1589                 CERROR("Can't read inode self id, inode %lu, "
1590                        "rc %d\n", dentry->d_inode->i_ino, rc);
1591                 id_fid(&id) = 0;
1592         }
1593
1594         body->oa.o_fid = id_fid(&id);
1595         body->oa.o_mds = id_group(&id);
1596         l_dput(dentry);
1597
1598         EXIT;
1599 }
1600
1601 static int mdt_obj_create(struct ptlrpc_request *req)
1602 {
1603         struct obd_device *obd = req->rq_export->exp_obd;
1604         struct mds_obd *mds = &obd->u.mds;
1605         struct ost_body *body, *repbody;
1606         char idname[LL_ID_NAMELEN];
1607         int size = sizeof(*repbody);
1608         struct inode *parent_inode;
1609         struct lvfs_run_ctxt saved;
1610         int rc, cleanup_phase = 0;
1611         struct dentry *new = NULL;
1612         struct dentry_params dp;
1613         int mealen, flags = 0;
1614         struct lvfs_ucred uc;
1615         struct lustre_id id;
1616         struct mea *mea;
1617         void *handle = NULL;
1618         unsigned long cr_inum = 0;
1619         ENTRY;
1620        
1621         DEBUG_REQ(D_HA, req, "create remote object");
1622
1623         parent_inode = mds->mds_unnamed_dir->d_inode;
1624
1625         body = lustre_swab_reqbuf(req, 0, sizeof(*body),
1626                                   lustre_swab_ost_body);
1627         if (body == NULL)
1628                 RETURN(-EFAULT);
1629
1630         rc = lustre_pack_reply(req, 1, &size, NULL);
1631         if (rc)
1632                 RETURN(rc);
1633
1634         MDS_CHECK_RESENT(req, reconstruct_create(req));
1635
1636         /* FIXME don't understand what security context we should
1637          * take here. check this -ericm
1638          */
1639         uc.luc_fsuid = body->oa.o_uid;
1640         uc.luc_fsgid = body->oa.o_gid;
1641         uc.luc_uid = body->oa.o_uid;
1642         uc.luc_ghash = mds_get_group_entry(mds, body->oa.o_uid);
1643         uc.luc_ginfo = NULL;
1644         push_ctxt(&saved, &obd->obd_lvfs_ctxt, &uc);
1645         
1646         repbody = lustre_msg_buf(req->rq_repmsg, 0, sizeof(*repbody));
1647
1648         /* in the case of recreate body->oa should have store cookie part
1649          * initialized too, as it is needed to check if object is already
1650          * created. But this is not cache flush case, as object was not created
1651          * on this MDS at least once and its store cookie is not known. */
1652         if (body->oa.o_flags & OBD_FL_RECREATE_OBJS) {
1653                 /* this is re-create request from MDS holding directory name.
1654                  * we have to lookup given ino/gen first. if it exists
1655                  * (good case) then there is nothing to do. if it does not then
1656                  * we have to recreate it */
1657                 id_fid(&id) = 0;
1658                 id_group(&id) = 0;
1659
1660                 id_ino(&id) = body->oa.o_id;
1661                 id_gen(&id) = body->oa.o_generation;
1662  
1663                 new = mds_id2dentry(obd, &id, NULL);
1664                 if (!IS_ERR(new) && new->d_inode) {
1665                         struct lustre_id sid;
1666                                 
1667                         CWARN("mkdir() repairing is on its way: %lu/%lu\n",
1668                               (unsigned long)id_ino(&id), (unsigned long)id_gen(&id));
1669                         
1670                         obdo_from_inode(&repbody->oa, new->d_inode,
1671                                         FILTER_VALID_FLAGS);
1672                         
1673                         repbody->oa.o_id = new->d_inode->i_ino;
1674                         repbody->oa.o_generation = new->d_inode->i_generation;
1675                         repbody->oa.o_valid |= OBD_MD_FLID | OBD_MD_FLGENER;
1676                         cleanup_phase = 1;
1677
1678                         down(&new->d_inode->i_sem);
1679                         rc = mds_read_inode_sid(obd, new->d_inode, &sid);
1680                         up(&new->d_inode->i_sem);
1681                         if (rc) {
1682                                 CERROR("Can't read inode self id "
1683                                        "inode %lu, rc %d.\n",
1684                                        new->d_inode->i_ino, rc);
1685                                 GOTO(cleanup, rc);
1686                         }
1687
1688                         repbody->oa.o_fid = id_fid(&sid);
1689                         repbody->oa.o_mds = id_group(&sid);
1690                         cr_inum = new->d_inode->i_ino;
1691                         GOTO(cleanup, rc = 0);
1692                 }
1693                 CWARN("for some reason dir %lu/%lu (or reply) got lost\n",
1694                       (unsigned long)id_ino(&id), (unsigned long)id_gen(&id));
1695                 
1696                 LASSERT(new->d_inode == NULL ||
1697                         new->d_inode->i_generation != id_gen(&id));
1698                 
1699                 l_dput(new); 
1700         }
1701         
1702         down(&parent_inode->i_sem);
1703         handle = fsfilt_start(obd, parent_inode, FSFILT_OP_MKDIR, NULL);
1704         if (IS_ERR(handle)) {
1705                 up(&parent_inode->i_sem);
1706                 CERROR("fsfilt_start() failed, rc = %d\n",
1707                        (int)PTR_ERR(handle));
1708                 GOTO(cleanup, rc = PTR_ERR(handle));
1709         }
1710         cleanup_phase = 1; /* transaction */
1711
1712 repeat:
1713         rc = sprintf(idname, "%u.%u", ll_insecure_random_int(), current->pid);
1714         new = lookup_one_len(idname, mds->mds_unnamed_dir, rc);
1715         if (IS_ERR(new)) {
1716                 CERROR("%s: can't lookup new inode (%s) for mkdir: %d\n",
1717                        obd->obd_name, idname, (int) PTR_ERR(new));
1718                 fsfilt_commit(obd, mds->mds_sb, new->d_inode, handle, 0);
1719                 up(&parent_inode->i_sem);
1720                 RETURN(PTR_ERR(new));
1721         } else if (new->d_inode) {
1722                 CERROR("%s: name exists. repeat\n", obd->obd_name);
1723                 goto repeat;
1724         }
1725
1726         new->d_fsdata = (void *)&dp;
1727         dp.p_inum = 0;
1728         dp.p_ptr = req;
1729
1730         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY) {
1731                 DEBUG_REQ(D_HA, req, "replay create obj %lu/%lu",
1732                           (unsigned long)body->oa.o_id,
1733                           (unsigned long)body->oa.o_generation);
1734                 dp.p_inum = body->oa.o_id;
1735         }
1736
1737         rc = vfs_mkdir(parent_inode, new, body->oa.o_mode);
1738         if (rc == 0) {
1739                 if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY) {
1740                         new->d_inode->i_generation = body->oa.o_generation;
1741                         mark_inode_dirty(new->d_inode);
1742                         
1743                         /*
1744                          * avoiding asserts in cache flush case, as
1745                          * @body->oa.o_id should be zero.
1746                          */
1747                         if (body->oa.o_id) {
1748                                 LASSERTF(body->oa.o_id == new->d_inode->i_ino, 
1749                                          "BUG 3550: failed to recreate obj "
1750                                          LPU64" -> %lu\n", body->oa.o_id,
1751                                          new->d_inode->i_ino);
1752                                 
1753                                 LASSERTF(body->oa.o_generation == 
1754                                          new->d_inode->i_generation,
1755                                          "BUG 3550: failed to recreate obj/gen "
1756                                          LPU64"/%u -> %lu/%u\n", body->oa.o_id,
1757                                          body->oa.o_generation,
1758                                          new->d_inode->i_ino, 
1759                                          new->d_inode->i_generation);
1760                         }
1761                 }
1762                 
1763                 obdo_from_inode(&repbody->oa, new->d_inode, FILTER_VALID_FLAGS);
1764                 repbody->oa.o_id = new->d_inode->i_ino;
1765                 repbody->oa.o_generation = new->d_inode->i_generation;
1766                 repbody->oa.o_valid |= OBD_MD_FLID | OBD_MD_FLGENER;
1767
1768                 if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY) {
1769                         /* building lustre_id on passed @oa. */
1770                         id_group(&id) = mds->mds_num;
1771                 
1772                         LASSERT(body->oa.o_fid != 0);
1773                         id_fid(&id) = body->oa.o_fid;
1774
1775                         id_ino(&id) = repbody->oa.o_id;
1776                         id_gen(&id) = repbody->oa.o_generation;
1777                 
1778                         down(&new->d_inode->i_sem);
1779                         rc = mds_update_inode_sid(obd, new->d_inode, handle, &id);
1780                         up(&new->d_inode->i_sem);
1781
1782                         spin_lock(&mds->mds_fid_lock);
1783                         if (id_fid(&id) > mds->mds_last_fid)
1784                                 mds->mds_last_fid = id_fid(&id);
1785                         spin_unlock(&mds->mds_fid_lock);
1786                 } else {
1787                         down(&new->d_inode->i_sem);
1788                         rc = mds_alloc_inode_sid(obd, new->d_inode, handle, &id);
1789                         up(&new->d_inode->i_sem);
1790                 }
1791                 if (rc) {
1792                         CERROR("Can't update lustre ID for inode %lu, "
1793                                "error = %d\n", new->d_inode->i_ino, rc);
1794                         GOTO(cleanup, rc);
1795                 }
1796
1797                 /* initializing o_fid after it is allocated. */
1798                 repbody->oa.o_fid = id_fid(&id);
1799                 repbody->oa.o_mds = id_group(&id);
1800
1801                 rc = fsfilt_del_dir_entry(obd, new);
1802                 up(&parent_inode->i_sem);
1803                 if (rc) {
1804                         CERROR("can't remove name for object: %d\n", rc);
1805                         GOTO(cleanup, rc);
1806                 }
1807                 
1808                 cleanup_phase = 2; /* created directory object */
1809
1810                 CDEBUG(D_OTHER, "created dirobj: %lu/%lu mode %o\n",
1811                        (unsigned long)new->d_inode->i_ino,
1812                        (unsigned long)new->d_inode->i_generation,
1813                        (unsigned)new->d_inode->i_mode);
1814                 cr_inum = new->d_inode->i_ino;
1815         } else {
1816                 up(&parent_inode->i_sem);
1817                 CERROR("%s: can't create dirobj: %d\n", obd->obd_name, rc);
1818                 GOTO(cleanup, rc);
1819         }
1820
1821         if (body->oa.o_valid & OBD_MD_FLID) {
1822                 /* this is new object for splitted dir. We have to prevent
1823                  * recursive splitting on it -bzzz */
1824                 mealen = obd_size_diskmd(mds->mds_lmv_exp, NULL);
1825
1826                 OBD_ALLOC(mea, mealen);
1827                 if (mea == NULL)
1828                         GOTO(cleanup, rc = -ENOMEM);
1829
1830                 mea->mea_magic = MEA_MAGIC_ALL_CHARS;
1831                 mea->mea_master = 0;
1832                 mea->mea_count = 0;
1833
1834                 down(&new->d_inode->i_sem);
1835                 rc = fsfilt_set_md(obd, new->d_inode, handle, mea, mealen);
1836                 up(&new->d_inode->i_sem);
1837                 if (rc)
1838                         CERROR("fsfilt_set_md() failed, rc = %d\n", rc);
1839
1840                 OBD_FREE(mea, mealen);
1841                 CDEBUG(D_OTHER, "%s: mark non-splittable %lu/%u - %d\n",
1842                        obd->obd_name, new->d_inode->i_ino,
1843                        new->d_inode->i_generation, flags);
1844         } else if (body->oa.o_easize) {
1845                 /* we pass LCK_EX to split routine to signal that we have
1846                  * exclusive access to the directory. simple because nobody
1847                  * knows it already exists -bzzz */
1848                 rc = mds_try_to_split_dir(obd, new, NULL,
1849                                           body->oa.o_easize, LCK_EX);
1850                 if (rc < 0) {
1851                         CERROR("Can't split directory %lu, error = %d.\n",
1852                                new->d_inode->i_ino, rc);
1853                 } else {
1854                         rc = 0;
1855                 }
1856         }
1857
1858 cleanup:
1859         switch (cleanup_phase) {
1860         case 2: /* object has been created, but we'll may want to replay it later */
1861                 if (rc == 0)
1862                         ptlrpc_require_repack(req);
1863         case 1: /* transaction */
1864                 rc = mds_finish_transno(mds, parent_inode, handle,
1865                                         req, rc, cr_inum);
1866         }
1867
1868         l_dput(new);
1869         pop_ctxt(&saved, &obd->obd_lvfs_ctxt, &uc);
1870         mds_put_group_entry(mds, uc.luc_ghash);
1871         RETURN(rc);
1872 }
1873
1874 static int mdt_get_info(struct ptlrpc_request *req)
1875 {
1876         struct obd_export *exp = req->rq_export;
1877         int keylen, rc = 0;
1878         char *key;
1879         ENTRY;
1880
1881         key = lustre_msg_buf(req->rq_reqmsg, 0, 1);
1882         if (key == NULL) {
1883                 DEBUG_REQ(D_HA, req, "no get_info key");
1884                 RETURN(-EFAULT);
1885         }
1886         keylen = req->rq_reqmsg->buflens[0];
1887
1888         if ((keylen < strlen("mdsize") || strcmp(key, "mdsize") != 0) &&
1889             (keylen < strlen("mdsnum") || strcmp(key, "mdsnum") != 0) &&
1890             (keylen < strlen("rootid") || strcmp(key, "rootid") != 0))
1891                 RETURN(-EPROTO);
1892
1893         if (keylen >= strlen("rootid") && !strcmp(key, "rootid")) {
1894                 struct lustre_id *reply;
1895                 int size = sizeof(*reply);
1896                 
1897                 rc = lustre_pack_reply(req, 1, &size, NULL);
1898                 if (rc)
1899                         RETURN(rc);
1900
1901                 reply = lustre_msg_buf(req->rq_repmsg, 0, size);
1902                 rc = obd_get_info(exp, keylen, key, &size, reply);
1903         } else {
1904                 obd_id *reply;
1905                 int size = sizeof(*reply);
1906                 
1907                 rc = lustre_pack_reply(req, 1, &size, NULL);
1908                 if (rc)
1909                         RETURN(rc);
1910
1911                 reply = lustre_msg_buf(req->rq_repmsg, 0, size);
1912                 rc = obd_get_info(exp, keylen, key, &size, reply);
1913         }
1914
1915         req->rq_repmsg->status = 0;
1916         RETURN(rc);
1917 }
1918
1919 static int mds_set_info(struct obd_export *exp, __u32 keylen,
1920                         void *key, __u32 vallen, void *val)
1921 {
1922         struct obd_device *obd;
1923         struct mds_obd *mds;
1924         int rc = 0;
1925         ENTRY;
1926
1927         obd = class_exp2obd(exp);
1928         if (obd == NULL) {
1929                 CDEBUG(D_IOCTL, "invalid client cookie "LPX64"\n",
1930                        exp->exp_handle.h_cookie);
1931                 RETURN(-EINVAL);
1932         }
1933
1934         mds = &obd->u.mds;
1935         if (keylen >= strlen("mds_type") &&
1936              memcmp(key, "mds_type", keylen) == 0) {
1937                 int valsize;
1938                 __u32 group;
1939                 
1940                 CDEBUG(D_IOCTL, "set mds type to %x\n", *(int*)val);
1941                 
1942                 mds->mds_obd_type = *(int*)val;
1943                 group = FILTER_GROUP_FIRST_MDS + mds->mds_obd_type;
1944                 valsize = sizeof(group);
1945                 
1946                 /* mds number has been changed, so the corresponding obdfilter
1947                  * exp need to be changed too. */
1948                 rc = obd_set_info(mds->mds_lov_exp, strlen("mds_conn"),
1949                                   "mds_conn", valsize, &group);
1950                 RETURN(rc);
1951         }
1952         CDEBUG(D_IOCTL, "invalid key\n");
1953         RETURN(-EINVAL);
1954 }
1955
1956 static int mdt_set_info(struct ptlrpc_request *req)
1957 {
1958         char *key, *val;
1959         struct obd_export *exp = req->rq_export;
1960         int keylen, rc = 0, vallen;
1961         ENTRY;
1962
1963         key = lustre_msg_buf(req->rq_reqmsg, 0, 1);
1964         if (key == NULL) {
1965                 DEBUG_REQ(D_HA, req, "no set_info key");
1966                 RETURN(-EFAULT);
1967         }
1968         keylen = req->rq_reqmsg->buflens[0];
1969
1970         if (keylen == strlen("mds_type") &&
1971             memcmp(key, "mds_type", keylen) == 0) {
1972                 rc = lustre_pack_reply(req, 0, NULL, NULL);
1973                 if (rc)
1974                         RETURN(rc);
1975                 
1976                 val = lustre_msg_buf(req->rq_reqmsg, 1, 0);
1977                 vallen = req->rq_reqmsg->buflens[1];
1978
1979                 rc = obd_set_info(exp, keylen, key, vallen, val);
1980                 req->rq_repmsg->status = 0;
1981                 RETURN(rc);
1982         }
1983         CDEBUG(D_IOCTL, "invalid key\n");
1984         RETURN(-EINVAL);
1985 }
1986
1987 static int mds_msg_check_version(struct lustre_msg *msg)
1988 {
1989         int rc;
1990
1991         switch (msg->opc) {
1992         case MDS_CONNECT:
1993         case MDS_DISCONNECT:
1994         case OBD_PING:
1995                 rc = lustre_msg_check_version(msg, LUSTRE_OBD_VERSION);
1996                 if (rc)
1997                         CERROR("bad opc %u version %08x, expecting %08x\n",
1998                                msg->opc, msg->version, LUSTRE_OBD_VERSION);
1999                 break;
2000         case MDS_STATFS:
2001         case MDS_GETSTATUS:
2002         case MDS_GETATTR:
2003         case MDS_GETATTR_LOCK:
2004         case MDS_READPAGE:
2005         case MDS_REINT:
2006         case MDS_CLOSE:
2007         case MDS_DONE_WRITING:
2008         case MDS_PIN:
2009         case MDS_SYNC:
2010                 rc = lustre_msg_check_version(msg, LUSTRE_MDS_VERSION);
2011                 if (rc)
2012                         CERROR("bad opc %u version %08x, expecting %08x\n",
2013                                msg->opc, msg->version, LUSTRE_MDS_VERSION);
2014                 break;
2015         case LDLM_ENQUEUE:
2016         case LDLM_CONVERT:
2017         case LDLM_BL_CALLBACK:
2018         case LDLM_CP_CALLBACK:
2019                 rc = lustre_msg_check_version(msg, LUSTRE_DLM_VERSION);
2020                 if (rc)
2021                         CERROR("bad opc %u version %08x, expecting %08x\n",
2022                                msg->opc, msg->version, LUSTRE_DLM_VERSION);
2023                 break;
2024         case OBD_LOG_CANCEL:
2025         case LLOG_ORIGIN_HANDLE_OPEN:
2026         case LLOG_ORIGIN_HANDLE_NEXT_BLOCK:
2027         case LLOG_ORIGIN_HANDLE_PREV_BLOCK:
2028         case LLOG_ORIGIN_HANDLE_READ_HEADER:
2029         case LLOG_ORIGIN_HANDLE_CLOSE:
2030         case LLOG_CATINFO:
2031                 rc = lustre_msg_check_version(msg, LUSTRE_LOG_VERSION);
2032                 if (rc)
2033                         CERROR("bad opc %u version %08x, expecting %08x\n",
2034                                msg->opc, msg->version, LUSTRE_LOG_VERSION);
2035                 break;
2036         case OST_CREATE:
2037         case OST_WRITE:
2038         case OST_GET_INFO:
2039         case OST_SET_INFO:
2040                 rc = lustre_msg_check_version(msg, LUSTRE_OBD_VERSION);
2041                 if (rc)
2042                         CERROR("bad opc %u version %08x, expecting %08x\n",
2043                                msg->opc, msg->version, LUSTRE_OBD_VERSION);
2044                 break;
2045         default:
2046                 CERROR("MDS unknown opcode %d\n", msg->opc);
2047                 rc = -ENOTSUPP;
2048                 break;
2049         }
2050
2051         return rc;
2052 }
2053
2054 static char str[PTL_NALFMT_SIZE];
2055 int mds_handle(struct ptlrpc_request *req)
2056 {
2057         int should_process, fail = OBD_FAIL_MDS_ALL_REPLY_NET;
2058         int rc = 0;
2059         struct mds_obd *mds = NULL; /* quell gcc overwarning */
2060         struct obd_device *obd = NULL;
2061         ENTRY;
2062
2063         OBD_FAIL_RETURN(OBD_FAIL_MDS_ALL_REQUEST_NET | OBD_FAIL_ONCE, 0);
2064
2065         rc = mds_msg_check_version(req->rq_reqmsg);
2066         if (rc) {
2067                 CERROR("MDS drop mal-formed request\n");
2068                 RETURN(rc);
2069         }
2070
2071         LASSERT(current->journal_info == NULL);
2072         /* XXX identical to OST */
2073         if (req->rq_reqmsg->opc != MDS_CONNECT) {
2074                 struct mds_export_data *med;
2075                 int recovering;
2076
2077                 if (req->rq_export == NULL) {
2078                         CERROR("operation %d on unconnected MDS from NID %s\n",
2079                                req->rq_reqmsg->opc,
2080                                ptlrpc_peernid2str(&req->rq_peer, str));
2081                         req->rq_status = -ENOTCONN;
2082                         GOTO(out, rc = -ENOTCONN);
2083                 }
2084
2085                 med = &req->rq_export->exp_mds_data;
2086                 obd = req->rq_export->exp_obd;
2087                 mds = &obd->u.mds;
2088
2089                 /* sanity check: if the xid matches, the request must
2090                  * be marked as a resent or replayed */
2091                 if (req->rq_xid == med->med_mcd->mcd_last_xid) {
2092                         LASSERTF(lustre_msg_get_flags(req->rq_reqmsg) &
2093                                  (MSG_RESENT | MSG_REPLAY),
2094                                  "rq_xid "LPU64" matches last_xid, "
2095                                  "expected RESENT flag\n",
2096                                  req->rq_xid);
2097                 }
2098                 /* else: note the opposite is not always true; a
2099                  * RESENT req after a failover will usually not match
2100                  * the last_xid, since it was likely never
2101                  * committed. A REPLAYed request will almost never
2102                  * match the last xid, however it could for a
2103                  * committed, but still retained, open. */
2104
2105                 spin_lock_bh(&obd->obd_processing_task_lock);
2106                 recovering = obd->obd_recovering;
2107                 spin_unlock_bh(&obd->obd_processing_task_lock);
2108                 if (recovering) {
2109                         rc = mds_filter_recovery_request(req, obd,
2110                                                          &should_process);
2111                         if (rc || should_process == 0) {
2112                                 RETURN(rc);
2113                         } else if (should_process < 0) {
2114                                 req->rq_status = should_process;
2115                                 rc = ptlrpc_error(req);
2116                                 RETURN(rc);
2117                         }
2118                 }
2119         }
2120
2121         switch (req->rq_reqmsg->opc) {
2122         case MDS_CONNECT:
2123                 DEBUG_REQ(D_INODE, req, "connect");
2124                 OBD_FAIL_RETURN(OBD_FAIL_MDS_CONNECT_NET, 0);
2125                 rc = target_handle_connect(req);
2126                 if (!rc)
2127                         /* Now that we have an export, set mds. */
2128                         mds = mds_req2mds(req);
2129                 break;
2130
2131         case MDS_DISCONNECT:
2132                 DEBUG_REQ(D_INODE, req, "disconnect");
2133                 OBD_FAIL_RETURN(OBD_FAIL_MDS_DISCONNECT_NET, 0);
2134                 rc = target_handle_disconnect(req);
2135                 req->rq_status = rc;            /* superfluous? */
2136                 break;
2137
2138         case MDS_GETSTATUS:
2139                 DEBUG_REQ(D_INODE, req, "getstatus");
2140                 OBD_FAIL_RETURN(OBD_FAIL_MDS_GETSTATUS_NET, 0);
2141                 rc = mds_getstatus(req);
2142                 break;
2143
2144         case MDS_GETATTR:
2145                 DEBUG_REQ(D_INODE, req, "getattr");
2146                 OBD_FAIL_RETURN(OBD_FAIL_MDS_GETATTR_NET, 0);
2147                 rc = mds_getattr(req, MDS_REQ_REC_OFF);
2148                 break;
2149
2150         case MDS_GETATTR_LOCK: {
2151                 struct lustre_handle lockh;
2152                 DEBUG_REQ(D_INODE, req, "getattr_name");
2153                 OBD_FAIL_RETURN(OBD_FAIL_MDS_GETATTR_LOCK_NET, 0);
2154
2155                 /* If this request gets a reconstructed reply, we won't be
2156                  * acquiring any new locks in mds_getattr_lock, so we don't
2157                  * want to cancel.
2158                  */
2159                 lockh.cookie = 0;
2160                 rc = mds_getattr_lock(req, MDS_REQ_REC_OFF, &lockh,
2161                                       MDS_INODELOCK_UPDATE);
2162                 /* this non-intent call (from an ioctl) is special */
2163                 req->rq_status = rc;
2164                 if (rc == 0 && lockh.cookie)
2165                         ldlm_lock_decref(&lockh, LCK_PR);
2166                 break;
2167         }
2168         case MDS_STATFS:
2169                 DEBUG_REQ(D_INODE, req, "statfs");
2170                 OBD_FAIL_RETURN(OBD_FAIL_MDS_STATFS_NET, 0);
2171                 rc = mds_statfs(req);
2172                 break;
2173
2174         case MDS_READPAGE:
2175                 DEBUG_REQ(D_INODE, req, "readpage");
2176                 OBD_FAIL_RETURN(OBD_FAIL_MDS_READPAGE_NET, 0);
2177                 rc = mds_readpage(req, MDS_REQ_REC_OFF);
2178
2179                 if (OBD_FAIL_CHECK_ONCE(OBD_FAIL_MDS_SENDPAGE)) {
2180                         if (req->rq_reply_state) {
2181                                 lustre_free_reply_state (req->rq_reply_state);
2182                                 req->rq_reply_state = NULL;
2183                         }
2184                         RETURN(0);
2185                 }
2186
2187                 break;
2188         case MDS_REINT: {
2189                 __u32 *opcp = lustre_msg_buf(req->rq_reqmsg, MDS_REQ_REC_OFF,
2190                                              sizeof (*opcp));
2191                 __u32  opc;
2192                 int size[3] = {sizeof(struct mds_body), mds->mds_max_mdsize,
2193                                mds->mds_max_cookiesize};
2194                 int bufcount;
2195
2196                 /* NB only peek inside req now; mds_reint() will swab it */
2197                 if (opcp == NULL) {
2198                         CERROR ("Can't inspect opcode\n");
2199                         rc = -EINVAL;
2200                         break;
2201                 }
2202                 opc = *opcp;
2203                 if (lustre_msg_swabbed (req->rq_reqmsg))
2204                         __swab32s(&opc);
2205
2206                 DEBUG_REQ(D_INODE, req, "reint %d (%s)", opc,
2207                           (opc < sizeof(reint_names) / sizeof(reint_names[0]) ||
2208                            reint_names[opc] == NULL) ? reint_names[opc] :
2209                                                        "unknown opcode");
2210
2211                 OBD_FAIL_RETURN(OBD_FAIL_MDS_REINT_NET, 0);
2212
2213                 if (opc == REINT_UNLINK || opc == REINT_RENAME)
2214                         bufcount = 3;
2215                 else if (opc == REINT_OPEN)
2216                         bufcount = 2;
2217                 else
2218                         bufcount = 1;
2219
2220                 rc = lustre_pack_reply(req, bufcount, size, NULL);
2221                 if (rc)
2222                         break;
2223
2224                 rc = mds_reint(req, MDS_REQ_REC_OFF, NULL);
2225                 fail = OBD_FAIL_MDS_REINT_NET_REP;
2226                 break;
2227         }
2228
2229         case MDS_CLOSE:
2230                 DEBUG_REQ(D_INODE, req, "close");
2231                 OBD_FAIL_RETURN(OBD_FAIL_MDS_CLOSE_NET, 0);
2232                 rc = mds_close(req, MDS_REQ_REC_OFF);
2233                 break;
2234
2235         case MDS_DONE_WRITING:
2236                 DEBUG_REQ(D_INODE, req, "done_writing");
2237                 OBD_FAIL_RETURN(OBD_FAIL_MDS_DONE_WRITING_NET, 0);
2238                 rc = mds_done_writing(req, MDS_REQ_REC_OFF);
2239                 break;
2240
2241         case MDS_PIN:
2242                 DEBUG_REQ(D_INODE, req, "pin");
2243                 OBD_FAIL_RETURN(OBD_FAIL_MDS_PIN_NET, 0);
2244                 rc = mds_pin(req, MDS_REQ_REC_OFF);
2245                 break;
2246
2247         case MDS_SYNC:
2248                 DEBUG_REQ(D_INODE, req, "sync");
2249                 OBD_FAIL_RETURN(OBD_FAIL_MDS_SYNC_NET, 0);
2250                 rc = mds_sync(req, MDS_REQ_REC_OFF);
2251                 break;
2252
2253         case OBD_PING:
2254                 DEBUG_REQ(D_INODE, req, "ping");
2255                 rc = target_handle_ping(req);
2256                 break;
2257
2258         case OBD_LOG_CANCEL:
2259                 CDEBUG(D_INODE, "log cancel\n");
2260                 OBD_FAIL_RETURN(OBD_FAIL_OBD_LOG_CANCEL_NET, 0);
2261                 rc = -ENOTSUPP; /* la la la */
2262                 break;
2263
2264         case LDLM_ENQUEUE:
2265                 DEBUG_REQ(D_INODE, req, "enqueue");
2266                 OBD_FAIL_RETURN(OBD_FAIL_LDLM_ENQUEUE, 0);
2267                 rc = ldlm_handle_enqueue(req, ldlm_server_completion_ast,
2268                                          ldlm_server_blocking_ast, NULL);
2269                 fail = OBD_FAIL_LDLM_REPLY;
2270                 break;
2271         case LDLM_CONVERT:
2272                 DEBUG_REQ(D_INODE, req, "convert");
2273                 OBD_FAIL_RETURN(OBD_FAIL_LDLM_CONVERT, 0);
2274                 rc = ldlm_handle_convert(req);
2275                 break;
2276         case LDLM_BL_CALLBACK:
2277         case LDLM_CP_CALLBACK:
2278                 DEBUG_REQ(D_INODE, req, "callback");
2279                 CERROR("callbacks should not happen on MDS\n");
2280                 LBUG();
2281                 OBD_FAIL_RETURN(OBD_FAIL_LDLM_BL_CALLBACK, 0);
2282                 break;
2283         case LLOG_ORIGIN_HANDLE_OPEN:
2284                 DEBUG_REQ(D_INODE, req, "llog_init");
2285                 OBD_FAIL_RETURN(OBD_FAIL_OBD_LOGD_NET, 0);
2286                 rc = llog_origin_handle_open(req);
2287                 break;
2288         case LLOG_ORIGIN_HANDLE_NEXT_BLOCK:
2289                 DEBUG_REQ(D_INODE, req, "llog next block");
2290                 OBD_FAIL_RETURN(OBD_FAIL_OBD_LOGD_NET, 0);
2291                 rc = llog_origin_handle_next_block(req);
2292                 break;
2293         case LLOG_ORIGIN_HANDLE_PREV_BLOCK:
2294                 DEBUG_REQ(D_INODE, req, "llog prev block");
2295                 OBD_FAIL_RETURN(OBD_FAIL_OBD_LOGD_NET, 0);
2296                 rc = llog_origin_handle_prev_block(req);
2297                 break;
2298         case LLOG_ORIGIN_HANDLE_READ_HEADER:
2299                 DEBUG_REQ(D_INODE, req, "llog read header");
2300                 OBD_FAIL_RETURN(OBD_FAIL_OBD_LOGD_NET, 0);
2301                 rc = llog_origin_handle_read_header(req);
2302                 break;
2303         case LLOG_ORIGIN_HANDLE_CLOSE:
2304                 DEBUG_REQ(D_INODE, req, "llog close");
2305                 OBD_FAIL_RETURN(OBD_FAIL_OBD_LOGD_NET, 0);
2306                 rc = llog_origin_handle_close(req);
2307                 break;
2308         case OST_CREATE:
2309                 DEBUG_REQ(D_INODE, req, "ost_create");
2310                 rc = mdt_obj_create(req);
2311                 break;
2312         case OST_GET_INFO:
2313                 DEBUG_REQ(D_INODE, req, "get_info");
2314                 rc = mdt_get_info(req);
2315                 break;
2316         case OST_SET_INFO:
2317                 DEBUG_REQ(D_INODE, req, "set_info");
2318                 rc = mdt_set_info(req);
2319                 break;
2320         case OST_WRITE:
2321                 CDEBUG(D_INODE, "write\n");
2322                 OBD_FAIL_RETURN(OBD_FAIL_OST_BRW_NET, 0);
2323                 rc = ost_brw_write(req, NULL);
2324                 LASSERT(current->journal_info == NULL);
2325                 /* mdt_brw sends its own replies */
2326                 RETURN(rc);
2327                 break;
2328         case LLOG_CATINFO:
2329                 DEBUG_REQ(D_INODE, req, "llog catinfo");
2330                 OBD_FAIL_RETURN(OBD_FAIL_OBD_LOGD_NET, 0);
2331                 rc = llog_catinfo(req);
2332                 break;
2333         default:
2334                 req->rq_status = -ENOTSUPP;
2335                 rc = ptlrpc_error(req);
2336                 RETURN(rc);
2337         }
2338
2339         LASSERT(current->journal_info == NULL);
2340
2341         EXIT;
2342
2343         /* If we're DISCONNECTing, the mds_export_data is already freed */
2344         if (!rc && req->rq_reqmsg->opc != MDS_DISCONNECT) {
2345                 struct mds_export_data *med = &req->rq_export->exp_mds_data;
2346                 struct obd_device *obd = list_entry(mds, struct obd_device,
2347                                                     u.mds);
2348                 req->rq_repmsg->last_xid =
2349                         le64_to_cpu(med->med_mcd->mcd_last_xid);
2350
2351                 if (!obd->obd_no_transno) {
2352                         req->rq_repmsg->last_committed =
2353                                 obd->obd_last_committed;
2354                 } else {
2355                         DEBUG_REQ(D_IOCTL, req,
2356                                   "not sending last_committed update");
2357                 }
2358                 CDEBUG(D_INFO, "last_transno "LPU64", last_committed "LPU64
2359                        ", xid "LPU64"\n",
2360                        mds->mds_last_transno, obd->obd_last_committed,
2361                        req->rq_xid);
2362         }
2363  out:
2364
2365         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LAST_REPLAY) {
2366                 if (obd && obd->obd_recovering) {
2367                         DEBUG_REQ(D_HA, req, "LAST_REPLAY, queuing reply");
2368                         return target_queue_final_reply(req, rc);
2369                 }
2370                 /* Lost a race with recovery; let the error path DTRT. */
2371                 rc = req->rq_status = -ENOTCONN;
2372         }
2373
2374         target_send_reply(req, rc, fail);
2375         return 0;
2376 }
2377
2378 /* Update the server data on disk.  This stores the new mount_count and also the
2379  * last_rcvd value to disk.  If we don't have a clean shutdown, then the server
2380  * last_rcvd value may be less than that of the clients.  This will alert us
2381  * that we may need to do client recovery.
2382  *
2383  * Also assumes for mds_last_transno that we are not modifying it (no locking).
2384  */
2385 int mds_update_server_data(struct obd_device *obd, int force_sync)
2386 {
2387         struct mds_obd *mds = &obd->u.mds;
2388         struct mds_server_data *msd = mds->mds_server_data;
2389         struct file *filp = mds->mds_rcvd_filp;
2390         struct lvfs_run_ctxt saved;
2391         loff_t off = 0;
2392         int rc;
2393         ENTRY;
2394
2395         push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
2396         msd->msd_last_transno = cpu_to_le64(mds->mds_last_transno);
2397
2398         CDEBUG(D_SUPER, "MDS mount_count is "LPU64", last_transno is "LPU64"\n",
2399                mds->mds_mount_count, mds->mds_last_transno);
2400         rc = fsfilt_write_record(obd, filp, msd, sizeof(*msd), &off,force_sync);
2401         if (rc)
2402                 CERROR("error writing MDS server data: rc = %d\n", rc);
2403         pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
2404
2405         RETURN(rc);
2406 }
2407
2408 /* saves last allocated fid counter to file. */
2409 int mds_update_last_fid(struct obd_device *obd, int force_sync)
2410 {
2411         struct mds_obd *mds = &obd->u.mds;
2412         struct file *filp = mds->mds_fid_filp;
2413         struct lvfs_run_ctxt saved;
2414         loff_t off = 0;
2415         int rc;
2416         ENTRY;
2417
2418         push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
2419
2420         CDEBUG(D_SUPER, "MDS last_fid is "LPU64"\n", mds->mds_last_fid);
2421         
2422         rc = fsfilt_write_record(obd, filp, &mds->mds_last_fid,
2423                                  sizeof(mds->mds_last_fid),
2424                                  &off, force_sync);
2425         if (rc)
2426                 CERROR("error writing MDS last_fid: rc = %d\n", rc);
2427         pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
2428
2429         RETURN(rc);
2430 }
2431
2432 void mds_commit_last_transno_cb(struct obd_device *obd,
2433                                 __u64 transno, void *data,
2434                                 int error)
2435 {
2436         obd_transno_commit_cb(obd, transno, error);
2437 }
2438
2439 void mds_commit_last_fid_cb(struct obd_device *obd,
2440                             __u64 fid, void *data,
2441                             int error)
2442 {
2443         if (error) {
2444                 CERROR("%s: fid "LPD64" commit error: %d\n",
2445                        obd->obd_name, fid, error);
2446                 return;
2447         }
2448         
2449         CDEBUG(D_HA, "%s: fid "LPD64" committed\n",
2450                obd->obd_name, fid);
2451 }
2452
2453 /*
2454  * allocates new lustre_id on passed @inode and saves it to inode EA.
2455  */
2456 int mds_alloc_inode_sid(struct obd_device *obd, struct inode *inode,
2457                         void *handle, struct lustre_id *id)
2458 {
2459         struct mds_obd *mds = &obd->u.mds;
2460         int rc = 0;
2461         ENTRY;
2462
2463         LASSERT(id != NULL);
2464         LASSERT(obd != NULL);
2465
2466         id_group(id) = mds->mds_num;
2467         
2468         spin_lock(&mds->mds_fid_lock);
2469         id_fid(id) = mds->mds_last_fid++;
2470         spin_unlock(&mds->mds_fid_lock);
2471
2472         id_ino(id) = inode->i_ino;
2473         id_gen(id) = inode->i_generation;
2474         id_type(id) = (S_IFMT & inode->i_mode);
2475
2476         rc = mds_update_inode_sid(obd, inode, handle, id);
2477         if (rc) {
2478                 CERROR("Can't update inode FID EA, "
2479                        "rc = %d\n", rc);
2480         }
2481         RETURN(rc);
2482 }
2483
2484 /*
2485  * reads inode self id from inode EA. Probably later this should be replaced by
2486  * caching inode self id to avoid raeding it every time it is needed.
2487  */
2488 int mds_read_inode_sid(struct obd_device *obd, struct inode *inode,
2489                        struct lustre_id *id)
2490 {
2491         int rc;
2492         ENTRY;
2493
2494         LASSERT(id != NULL);
2495         LASSERT(obd != NULL);
2496         LASSERT(inode != NULL);
2497
2498         rc = fsfilt_get_sid(obd, inode, &id->li_fid,
2499                             sizeof(id->li_fid));
2500         if (rc < 0) {
2501                 CERROR("fsfilt_get_sid() failed, "
2502                        "rc = %d\n", rc);
2503                 RETURN(rc);
2504         } else if (!rc) {
2505                 rc = -ENODATA;
2506                 RETURN(rc);
2507         } else {
2508                 rc = 0;
2509         }
2510
2511         RETURN(rc);
2512 }
2513
2514 /* updates inode self id in EA. */
2515 int mds_update_inode_sid(struct obd_device *obd, struct inode *inode,
2516                          void *handle, struct lustre_id *id)
2517 {
2518         int rc = 0;
2519         ENTRY;
2520
2521         LASSERT(id != NULL);
2522         LASSERT(obd != NULL);
2523         LASSERT(inode != NULL);
2524         
2525         rc = fsfilt_set_sid(obd, inode, handle, &id->li_fid,
2526                             sizeof(id->li_fid));
2527         if (rc) {
2528                 CERROR("fsfilt_set_sid() failed, rc = %d\n", rc);
2529                 RETURN(rc);
2530         }
2531
2532         RETURN(rc);
2533 }
2534
2535 /* 
2536  * reads inode id on master MDS. This is usualy done by CMOBD to update requests
2537  * to master MDS by correct store cookie, needed to find inode on master MDS
2538  * quickly.
2539  */
2540 int mds_read_inode_mid(struct obd_device *obd, struct inode *inode,
2541                        struct lustre_id *id)
2542 {
2543         int rc;
2544         ENTRY;
2545
2546         LASSERT(id != NULL);
2547         LASSERT(obd != NULL);
2548         LASSERT(inode != NULL);
2549
2550         rc = fsfilt_get_mid(obd, inode, id, sizeof(*id));
2551         if (rc < 0) {
2552                 CERROR("fsfilt_get_mid() failed, "
2553                        "rc = %d\n", rc);
2554                 RETURN(rc);
2555         } else if (!rc) {
2556                 rc = -ENODATA;
2557                 RETURN(rc);
2558         } else {
2559                 rc = 0;
2560         }
2561
2562         RETURN(rc);
2563 }
2564
2565 /*
2566  * updates master inode id. Usualy this is done by CMOBD after an inode is
2567  * created and relationship between cache MDS and master one should be
2568  * established.
2569  */
2570 int mds_update_inode_mid(struct obd_device *obd, struct inode *inode,
2571                          void *handle, struct lustre_id *id)
2572 {
2573         int rc = 0;
2574         ENTRY;
2575
2576         LASSERT(id != NULL);
2577         LASSERT(obd != NULL);
2578         LASSERT(inode != NULL);
2579         
2580         rc = fsfilt_set_mid(obd, inode, handle, id, sizeof(*id));
2581         if (rc) {
2582                 CERROR("fsfilt_set_mid() failed, rc = %d\n", rc);
2583                 RETURN(rc);
2584         }
2585
2586         RETURN(rc);
2587 }
2588
2589 /* mount the file system (secretly) */
2590 static int mds_setup(struct obd_device *obd, obd_count len, void *buf)
2591 {
2592         struct lustre_cfg* lcfg = buf;
2593         struct mds_obd *mds = &obd->u.mds;
2594         char *options = NULL;
2595         struct vfsmount *mnt;
2596         char ns_name[48];
2597         unsigned long page;
2598         int rc = 0;
2599         ENTRY;
2600
2601         dev_clear_rdonly(2);
2602
2603         if (!lcfg->lcfg_inlbuf1 || !lcfg->lcfg_inlbuf2)
2604                 RETURN(rc = -EINVAL);
2605
2606         obd->obd_fsops = fsfilt_get_ops(lcfg->lcfg_inlbuf2);
2607         if (IS_ERR(obd->obd_fsops))
2608                 RETURN(rc = PTR_ERR(obd->obd_fsops));
2609
2610         mds->mds_max_mdsize = sizeof(struct lov_mds_md);
2611
2612         page = __get_free_page(GFP_KERNEL);
2613         if (!page)
2614                 RETURN(-ENOMEM);
2615
2616         options = (char *)page;
2617         memset(options, 0, PAGE_SIZE);
2618
2619         /*
2620          * here we use "iopen_nopriv" hardcoded, because it affects MDS utility
2621          * and the rest of options are passed by mount options. Probably this
2622          * should be moved to somewhere else like startup scripts or lconf.
2623          */
2624         sprintf(options, "iopen_nopriv");
2625
2626         if (lcfg->lcfg_inllen4 > 0 && lcfg->lcfg_inlbuf4)
2627                 sprintf(options + strlen(options), ",%s",
2628                         lcfg->lcfg_inlbuf4);
2629
2630         /* we have to know mdsnum before touching underlying fs -bzzz */
2631         sema_init(&mds->mds_lmv_sem, 1);
2632         mds->mds_lmv_connected = 0;
2633         if (lcfg->lcfg_inllen5 > 0 && lcfg->lcfg_inlbuf5 && 
2634             strcmp(lcfg->lcfg_inlbuf5, "dumb")) {
2635                 class_uuid_t uuid;
2636
2637                 CDEBUG(D_OTHER, "MDS: %s is master for %s\n",
2638                        obd->obd_name, lcfg->lcfg_inlbuf5);
2639
2640                 generate_random_uuid(uuid);
2641                 class_uuid_unparse(uuid, &mds->mds_lmv_uuid);
2642
2643                 OBD_ALLOC(mds->mds_lmv_name, lcfg->lcfg_inllen5);
2644                 if (mds->mds_lmv_name == NULL) 
2645                         RETURN(rc = -ENOMEM);
2646
2647                 memcpy(mds->mds_lmv_name, lcfg->lcfg_inlbuf5,
2648                        lcfg->lcfg_inllen5);
2649                 
2650                 rc = mds_lmv_connect(obd, mds->mds_lmv_name);
2651                 if (rc) {
2652                         OBD_FREE(mds->mds_lmv_name, lcfg->lcfg_inllen5);
2653                         GOTO(err_ops, rc);
2654                 }
2655         }
2656         
2657         mds->mds_obd_type = MDS_MASTER_OBD;
2658
2659         if (lcfg->lcfg_inllen6 > 0 && lcfg->lcfg_inlbuf6 &&
2660             strcmp(lcfg->lcfg_inlbuf6, "dumb")) {
2661                 if (!memcmp(lcfg->lcfg_inlbuf6, "master", strlen("master"))) {
2662                         mds->mds_obd_type = MDS_MASTER_OBD;
2663                 } else if (!memcmp(lcfg->lcfg_inlbuf6, "cache", strlen("cache"))) {
2664                         mds->mds_obd_type = MDS_CACHE_OBD;
2665                 }     
2666         }
2667
2668         mnt = do_kern_mount(lcfg->lcfg_inlbuf2, 0, lcfg->lcfg_inlbuf1, options);
2669         free_page(page);
2670
2671         if (IS_ERR(mnt)) {
2672                 rc = PTR_ERR(mnt);
2673                 CERROR("do_kern_mount failed: rc = %d\n", rc);
2674                 GOTO(err_ops, rc);
2675         }
2676
2677         CDEBUG(D_SUPER, "%s: mnt = %p\n", lcfg->lcfg_inlbuf1, mnt);
2678
2679         sema_init(&mds->mds_epoch_sem, 1);
2680         spin_lock_init(&mds->mds_fid_lock);
2681         atomic_set(&mds->mds_real_clients, 0);
2682         spin_lock_init(&mds->mds_transno_lock);
2683         sema_init(&mds->mds_orphan_recovery_sem, 1);
2684         mds->mds_max_cookiesize = sizeof(struct llog_cookie);
2685
2686         sprintf(ns_name, "mds-%s", obd->obd_uuid.uuid);
2687         obd->obd_namespace = ldlm_namespace_new(ns_name, LDLM_NAMESPACE_SERVER);
2688
2689         if (obd->obd_namespace == NULL) {
2690                 mds_cleanup(obd, 0);
2691                 GOTO(err_put, rc = -ENOMEM);
2692         }
2693         ldlm_register_intent(obd->obd_namespace, mds_intent_policy);
2694
2695         rc = mds_fs_setup(obd, mnt);
2696         if (rc) {
2697                 CERROR("%s: MDS filesystem method init failed: rc = %d\n",
2698                        obd->obd_name, rc);
2699                 GOTO(err_ns, rc);
2700         }
2701         
2702         rc = llog_start_commit_thread();
2703         if (rc < 0)
2704                 GOTO(err_fs, rc);
2705
2706         /*
2707          * this check for @dumb string is needed to handle mounting MDS with
2708          * smfs. Read lconf:MDSDEV.write_conf() for more details.
2709          */
2710         if (lcfg->lcfg_inllen3 > 0 && lcfg->lcfg_inlbuf3 &&
2711             strcmp(lcfg->lcfg_inlbuf3, "dumb")) {
2712                 class_uuid_t uuid;
2713
2714                 generate_random_uuid(uuid);
2715                 class_uuid_unparse(uuid, &mds->mds_lov_uuid);
2716
2717                 OBD_ALLOC(mds->mds_profile, lcfg->lcfg_inllen3);
2718                 if (mds->mds_profile == NULL)
2719                         GOTO(err_fs, rc = -ENOMEM);
2720
2721                 memcpy(mds->mds_profile, lcfg->lcfg_inlbuf3,
2722                        lcfg->lcfg_inllen3);
2723
2724                 /*
2725                  * setup root id in the case this is not clients write
2726                  * setup. This is important, as in the case of LMV we need
2727                  * mds->mds_num to be already assigned to form correct root fid.
2728                  */
2729                 rc = mds_fs_setup_rootid(obd);
2730                 if (rc)
2731                         GOTO(err_fs, rc);
2732
2733                 /* setup lustre id for ID directory. */
2734                 rc = mds_fs_setup_virtid(obd);
2735                 if (rc)
2736                         GOTO(err_fs, rc);
2737         }
2738
2739         ptlrpc_init_client(LDLM_CB_REQUEST_PORTAL, LDLM_CB_REPLY_PORTAL,
2740                            "mds_ldlm_client", &obd->obd_ldlm_client);
2741         obd->obd_replayable = 1;
2742
2743         mds->mds_counters = lprocfs_alloc_mds_counters();
2744
2745         rc = mds_postsetup(obd);
2746         if (rc)
2747                 GOTO(err_fs, rc);
2748
2749         RETURN(0);
2750
2751 err_fs:
2752         /* No extra cleanup needed for llog_init_commit_thread() */
2753         mds_fs_cleanup(obd, 0);
2754 err_ns:
2755         ldlm_namespace_free(obd->obd_namespace, 0);
2756         obd->obd_namespace = NULL;
2757 err_put:
2758         unlock_kernel();
2759         mntput(mds->mds_vfsmnt);
2760         mds->mds_sb = 0;
2761         lock_kernel();
2762 err_ops:
2763         fsfilt_put_ops(obd->obd_fsops);
2764         return rc;
2765 }
2766
2767 static int mds_postsetup(struct obd_device *obd)
2768 {
2769         struct mds_obd *mds = &obd->u.mds;
2770         int rc = 0;
2771         ENTRY;
2772
2773         rc = obd_llog_setup(obd, &obd->obd_llogs, LLOG_CONFIG_ORIG_CTXT, 
2774                             obd, 0, NULL, &llog_lvfs_ops);
2775         if (rc)
2776                 RETURN(rc);
2777
2778         if (mds->mds_profile) {
2779                 struct llog_ctxt *lgctxt;
2780                 struct lvfs_run_ctxt saved;
2781                 struct lustre_profile *lprof;
2782                 struct config_llog_instance cfg;
2783
2784                 cfg.cfg_instance = NULL;
2785                 cfg.cfg_uuid = mds->mds_lov_uuid;
2786                 push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
2787
2788                 lgctxt = llog_get_context(&obd->obd_llogs, LLOG_CONFIG_ORIG_CTXT);
2789                 if (!lgctxt) {
2790                         pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
2791                         GOTO(err_llog, rc = -EINVAL);
2792                 }
2793                 
2794                 rc = class_config_process_llog(lgctxt, mds->mds_profile, &cfg);
2795                 pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
2796
2797                 if (rc)
2798                         GOTO(err_llog, rc);
2799
2800                 lprof = class_get_profile(mds->mds_profile);
2801                 if (lprof == NULL) {
2802                         CERROR("No profile found: %s\n", mds->mds_profile);
2803                         GOTO(err_cleanup, rc = -ENOENT);
2804                 }
2805                 rc = mds_lov_connect(obd, lprof->lp_lov);
2806                 if (rc)
2807                         GOTO(err_cleanup, rc);
2808
2809                 rc = mds_lmv_postsetup(obd);
2810                 if (rc)
2811                         GOTO(err_cleanup, rc);
2812         }
2813
2814         RETURN(rc);
2815
2816 err_cleanup:
2817         mds_lov_clean(obd);
2818 err_llog:
2819         obd_llog_cleanup(llog_get_context(&obd->obd_llogs,
2820                                           LLOG_CONFIG_ORIG_CTXT));
2821         RETURN(rc);
2822 }
2823
2824 int mds_postrecov(struct obd_device *obd)
2825 {
2826         struct mds_obd *mds = &obd->u.mds;
2827         struct llog_ctxt *ctxt;
2828         int rc, item = 0, valsize;
2829          __u32 group;
2830         ENTRY;
2831
2832         LASSERT(!obd->obd_recovering);
2833         ctxt = llog_get_context(&obd->obd_llogs, LLOG_UNLINK_ORIG_CTXT);
2834         LASSERT(ctxt != NULL);
2835
2836         /* set nextid first, so we are sure it happens */
2837         rc = mds_lov_set_nextid(obd);
2838         if (rc) {
2839                 CERROR("%s: mds_lov_set_nextid failed\n", obd->obd_name);
2840                 GOTO(out, rc);
2841         }
2842
2843         /* clean PENDING dir */
2844         rc = mds_cleanup_orphans(obd);
2845         if (rc < 0)
2846                 GOTO(out, rc);
2847         item = rc;
2848
2849         group = FILTER_GROUP_FIRST_MDS + mds->mds_num;
2850         valsize = sizeof(group);
2851         rc = obd_set_info(mds->mds_lov_exp, strlen("mds_conn"), "mds_conn",
2852                           valsize, &group);
2853         if (rc)
2854                 GOTO(out, rc);
2855
2856         rc = llog_connect(ctxt, obd->u.mds.mds_lov_desc.ld_tgt_count,
2857                           NULL, NULL, NULL);
2858         if (rc) {
2859                 CERROR("%s: failed at llog_origin_connect: %d\n", 
2860                        obd->obd_name, rc);
2861                 GOTO(out, rc);
2862         }
2863
2864         /* remove the orphaned precreated objects */
2865         rc = mds_lov_clearorphans(mds, NULL /* all OSTs */);
2866         if (rc)
2867                 GOTO(err_llog, rc);
2868
2869 out:
2870         RETURN(rc < 0 ? rc : item);
2871
2872 err_llog:
2873         /* cleanup all llogging subsystems */
2874         rc = obd_llog_finish(obd, &obd->obd_llogs,
2875                              mds->mds_lov_desc.ld_tgt_count);
2876         if (rc)
2877                 CERROR("%s: failed to cleanup llogging subsystems\n",
2878                         obd->obd_name);
2879         goto out;
2880 }
2881
2882 int mds_lov_clean(struct obd_device *obd)
2883 {
2884         struct mds_obd *mds = &obd->u.mds;
2885
2886         if (mds->mds_profile) {
2887                 char * cln_prof;
2888                 struct llog_ctxt *llctx;
2889                 struct lvfs_run_ctxt saved;
2890                 struct config_llog_instance cfg;
2891                 int len = strlen(mds->mds_profile) + sizeof("-clean") + 1;
2892
2893                 OBD_ALLOC(cln_prof, len);
2894                 sprintf(cln_prof, "%s-clean", mds->mds_profile);
2895
2896                 cfg.cfg_instance = NULL;
2897                 cfg.cfg_uuid = mds->mds_lov_uuid;
2898
2899                 push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
2900                 llctx = llog_get_context(&obd->obd_llogs,
2901                                          LLOG_CONFIG_ORIG_CTXT);
2902                 class_config_process_llog(llctx, cln_prof, &cfg);
2903                 pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
2904
2905                 OBD_FREE(cln_prof, len);
2906                 OBD_FREE(mds->mds_profile, strlen(mds->mds_profile) + 1);
2907                 mds->mds_profile = NULL;
2908         }
2909         RETURN(0);
2910 }
2911
2912 int mds_lmv_clean(struct obd_device *obd)
2913 {
2914         struct mds_obd *mds = &obd->u.mds;
2915
2916         if (mds->mds_lmv_name) {
2917                 OBD_FREE(mds->mds_lmv_name, strlen(mds->mds_lmv_name) + 1);
2918                 mds->mds_lmv_name = NULL;
2919         }
2920         RETURN(0);
2921 }
2922
2923 static int mds_precleanup(struct obd_device *obd, int flags)
2924 {
2925         int rc = 0;
2926         ENTRY;
2927
2928         mds_lmv_clean(obd);
2929         mds_lov_disconnect(obd, flags);
2930         mds_lov_clean(obd);
2931         obd_llog_cleanup(llog_get_context(&obd->obd_llogs, LLOG_CONFIG_ORIG_CTXT));
2932         RETURN(rc);
2933 }
2934
2935 static int mds_cleanup(struct obd_device *obd, int flags)
2936 {
2937         struct mds_obd *mds = &obd->u.mds;
2938         ENTRY;
2939
2940         if (mds->mds_sb == NULL)
2941                 RETURN(0);
2942
2943         mds_update_last_fid(obd, 1);
2944         mds_update_server_data(obd, 1);
2945         
2946         if (mds->mds_lov_objids != NULL) {
2947                 int size = mds->mds_lov_desc.ld_tgt_count *
2948                         sizeof(obd_id);
2949                 OBD_FREE(mds->mds_lov_objids, size);
2950         }
2951         mds_fs_cleanup(obd, flags);
2952
2953         unlock_kernel();
2954
2955         /*
2956          * 2 seems normal on mds, (may_umount() also expects 2 fwiw), but we
2957          * only see 1 at this point in obdfilter.
2958          */
2959         if (atomic_read(&obd->u.mds.mds_vfsmnt->mnt_count) > 2)
2960                 CERROR("%s: mount busy, mnt_count %d != 2\n", obd->obd_name,
2961                        atomic_read(&obd->u.mds.mds_vfsmnt->mnt_count));
2962
2963         mntput(mds->mds_vfsmnt);
2964         mds->mds_sb = 0;
2965
2966         ldlm_namespace_free(obd->obd_namespace, flags & OBD_OPT_FORCE);
2967
2968         if (mds->mds_counters) {
2969                 lprocfs_free_mds_counters(mds->mds_counters);
2970         }
2971
2972         spin_lock_bh(&obd->obd_processing_task_lock);
2973         if (obd->obd_recovering) {
2974                 target_cancel_recovery_timer(obd);
2975                 obd->obd_recovering = 0;
2976         }
2977         spin_unlock_bh(&obd->obd_processing_task_lock);
2978
2979         lock_kernel();
2980         dev_clear_rdonly(2);
2981         fsfilt_put_ops(obd->obd_fsops);
2982
2983         RETURN(0);
2984 }
2985
2986 static void fixup_handle_for_resent_req(struct ptlrpc_request *req,
2987                                         int offset,
2988                                         struct ldlm_lock *new_lock,
2989                                         struct ldlm_lock **old_lock,
2990                                         struct lustre_handle *lockh)
2991 {
2992         struct obd_export *exp = req->rq_export;
2993         struct obd_device *obd = exp->exp_obd;
2994         struct ldlm_request *dlmreq =
2995                 lustre_msg_buf(req->rq_reqmsg, offset, sizeof (*dlmreq));
2996         struct lustre_handle remote_hdl = dlmreq->lock_handle1;
2997         struct list_head *iter;
2998
2999         if (!(lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT))
3000                 return;
3001
3002         l_lock(&obd->obd_namespace->ns_lock);
3003         list_for_each(iter, &exp->exp_ldlm_data.led_held_locks) {
3004                 struct ldlm_lock *lock;
3005                 lock = list_entry(iter, struct ldlm_lock, l_export_chain);
3006                 if (lock == new_lock)
3007                         continue;
3008                 if (lock->l_remote_handle.cookie == remote_hdl.cookie) {
3009                         lockh->cookie = lock->l_handle.h_cookie;
3010                         LDLM_DEBUG(lock, "restoring lock cookie");
3011                         DEBUG_REQ(D_HA, req, "restoring lock cookie "LPX64,
3012                                   lockh->cookie);
3013                         if (old_lock)
3014                                 *old_lock = LDLM_LOCK_GET(lock);
3015                         l_unlock(&obd->obd_namespace->ns_lock);
3016                         return;
3017                 }
3018         }
3019         l_unlock(&obd->obd_namespace->ns_lock);
3020
3021         /* If the xid matches, then we know this is a resent request,
3022          * and allow it. (It's probably an OPEN, for which we don't
3023          * send a lock */
3024         if (req->rq_xid == exp->exp_mds_data.med_mcd->mcd_last_xid)
3025                 return;
3026
3027         /* This remote handle isn't enqueued, so we never received or
3028          * processed this request.  Clear MSG_RESENT, because it can
3029          * be handled like any normal request now. */
3030
3031         lustre_msg_clear_flags(req->rq_reqmsg, MSG_RESENT);
3032
3033         DEBUG_REQ(D_HA, req, "no existing lock with rhandle "LPX64,
3034                   remote_hdl.cookie);
3035 }
3036
3037 int intent_disposition(struct ldlm_reply *rep, int flag)
3038 {
3039         if (!rep)
3040                 return 0;
3041         return (rep->lock_policy_res1 & flag);
3042 }
3043
3044 void intent_set_disposition(struct ldlm_reply *rep, int flag)
3045 {
3046         if (!rep)
3047                 return;
3048         rep->lock_policy_res1 |= flag;
3049 }
3050
3051 static int mds_intent_policy(struct ldlm_namespace *ns,
3052                              struct ldlm_lock **lockp, void *req_cookie,
3053                              ldlm_mode_t mode, int flags, void *data)
3054 {
3055         struct ptlrpc_request *req = req_cookie;
3056         struct ldlm_lock *lock = *lockp;
3057         struct ldlm_intent *it;
3058         struct mds_obd *mds = &req->rq_export->exp_obd->u.mds;
3059         struct ldlm_reply *rep;
3060         struct lustre_handle lockh[2] = {{0}, {0}};
3061         struct ldlm_lock *new_lock = NULL;
3062         int getattr_part = MDS_INODELOCK_UPDATE;
3063         int rc, repsize[4] = { sizeof(struct ldlm_reply),
3064                                sizeof(struct mds_body),
3065                                mds->mds_max_mdsize,
3066                                mds->mds_max_cookiesize };
3067         int offset = MDS_REQ_INTENT_REC_OFF; 
3068         ENTRY;
3069
3070         LASSERT(req != NULL);
3071
3072         if (req->rq_reqmsg->bufcount <= MDS_REQ_INTENT_IT_OFF) {
3073                 /* No intent was provided */
3074                 int size = sizeof(struct ldlm_reply);
3075                 rc = lustre_pack_reply(req, 1, &size, NULL);
3076                 LASSERT(rc == 0);
3077                 RETURN(0);
3078         }
3079
3080         it = lustre_swab_reqbuf(req, MDS_REQ_INTENT_IT_OFF, sizeof(*it),
3081                                 lustre_swab_ldlm_intent);
3082         if (it == NULL) {
3083                 CERROR("Intent missing\n");
3084                 RETURN(req->rq_status = -EFAULT);
3085         }
3086
3087         LDLM_DEBUG(lock, "intent policy, opc: %s", ldlm_it2str(it->opc));
3088
3089         rc = lustre_pack_reply(req, 3, repsize, NULL);
3090         if (rc)
3091                 RETURN(req->rq_status = rc);
3092
3093         rep = lustre_msg_buf(req->rq_repmsg, 0, sizeof(*rep));
3094         LASSERT(rep != NULL);
3095
3096         intent_set_disposition(rep, DISP_IT_EXECD);
3097
3098         /* execute policy */
3099         switch ((long)it->opc) {
3100         case IT_OPEN:
3101         case IT_CREAT|IT_OPEN:
3102                 /* XXX swab here to assert that an mds_open reint
3103                  * packet is following */
3104                 fixup_handle_for_resent_req(req, MDS_REQ_INTENT_LOCKREQ_OFF, 
3105                                             lock, NULL, lockh);
3106                 rep->lock_policy_res2 = mds_reint(req, offset, lockh);
3107 #if 0
3108                 /* We abort the lock if the lookup was negative and
3109                  * we did not make it to the OPEN portion */
3110                 if (!intent_disposition(rep, DISP_LOOKUP_EXECD))
3111                         RETURN(ELDLM_LOCK_ABORTED);
3112                 if (intent_disposition(rep, DISP_LOOKUP_NEG) &&
3113                     !intent_disposition(rep, DISP_OPEN_OPEN))
3114 #endif
3115                 /* IT_OPEN may return lock on cross-node dentry
3116                  * that we want to hold during attr retrival -bzzz */
3117                 if (rc != 0 || lockh[0].cookie == 0)
3118                         RETURN(ELDLM_LOCK_ABORTED);
3119                 break;
3120         case IT_LOOKUP:
3121                 getattr_part = MDS_INODELOCK_LOOKUP;
3122         case IT_CHDIR:
3123         case IT_GETATTR:
3124                 getattr_part |= MDS_INODELOCK_LOOKUP;
3125         case IT_READDIR:
3126                 fixup_handle_for_resent_req(req, MDS_REQ_INTENT_LOCKREQ_OFF, 
3127                                             lock, &new_lock, lockh);
3128                 rep->lock_policy_res2 = mds_getattr_lock(req, offset, lockh,
3129                                                          getattr_part);
3130                 /* FIXME: LDLM can set req->rq_status. MDS sets
3131                    policy_res{1,2} with disposition and status.
3132                    - replay: returns 0 & req->status is old status
3133                    - otherwise: returns req->status */
3134                 if (intent_disposition(rep, DISP_LOOKUP_NEG))
3135                         rep->lock_policy_res2 = 0;
3136                 if (!intent_disposition(rep, DISP_LOOKUP_POS) ||
3137                     rep->lock_policy_res2)
3138                         RETURN(ELDLM_LOCK_ABORTED);
3139                 if (req->rq_status != 0) {
3140                         LBUG();
3141                         rep->lock_policy_res2 = req->rq_status;
3142                         RETURN(ELDLM_LOCK_ABORTED);
3143                 }
3144                 break;
3145         case IT_UNLINK:
3146                 rc = mds_lock_and_check_slave(offset, req, lockh);
3147                 if ((rep->lock_policy_res2 = rc)) {
3148                         if (rc == ENOLCK)
3149                                 rep->lock_policy_res2 = 0;
3150                         RETURN(ELDLM_LOCK_ABORTED);
3151                 }
3152                 break;
3153         default:
3154                 CERROR("Unhandled intent "LPD64"\n", it->opc);
3155                 LBUG();
3156         }
3157
3158         /* By this point, whatever function we called above must have either
3159          * filled in 'lockh', been an intent replay, or returned an error.  We
3160          * want to allow replayed RPCs to not get a lock, since we would just
3161          * drop it below anyways because lock replay is done separately by the
3162          * client afterwards.  For regular RPCs we want to give the new lock to
3163          * the client instead of whatever lock it was about to get. */
3164         if (new_lock == NULL)
3165                 new_lock = ldlm_handle2lock(&lockh[0]);
3166         if (new_lock == NULL && (flags & LDLM_FL_INTENT_ONLY))
3167                 RETURN(0);
3168
3169         LASSERTF(new_lock != NULL, "op "LPX64" lockh "LPX64"\n",
3170                  it->opc, lockh[0].cookie);
3171  
3172         /* If we've already given this lock to a client once, then we should
3173          * have no readers or writers.  Otherwise, we should have one reader
3174          * _or_ writer ref (which will be zeroed below) before returning the
3175          * lock to a client. */
3176         if (new_lock->l_export == req->rq_export) {
3177                 LASSERT(new_lock->l_readers + new_lock->l_writers == 0);
3178         } else {
3179                 LASSERT(new_lock->l_export == NULL);
3180                 LASSERT(new_lock->l_readers + new_lock->l_writers == 1);
3181         }
3182
3183         *lockp = new_lock;
3184
3185         if (new_lock->l_export == req->rq_export) {
3186                 /* Already gave this to the client, which means that we
3187                  * reconstructed a reply. */
3188                 LASSERT(lustre_msg_get_flags(req->rq_reqmsg) &
3189                         MSG_RESENT);
3190                 RETURN(ELDLM_LOCK_REPLACED);
3191         }
3192
3193         /* Fixup the lock to be given to the client */
3194         l_lock(&new_lock->l_resource->lr_namespace->ns_lock);
3195         new_lock->l_readers = 0;
3196         new_lock->l_writers = 0;
3197
3198         new_lock->l_export = class_export_get(req->rq_export);
3199         list_add(&new_lock->l_export_chain,
3200                  &new_lock->l_export->exp_ldlm_data.led_held_locks);
3201
3202         new_lock->l_blocking_ast = lock->l_blocking_ast;
3203         new_lock->l_completion_ast = lock->l_completion_ast;
3204
3205         memcpy(&new_lock->l_remote_handle, &lock->l_remote_handle,
3206                sizeof(lock->l_remote_handle));
3207
3208         new_lock->l_flags &= ~LDLM_FL_LOCAL;
3209
3210         LDLM_LOCK_PUT(new_lock);
3211         l_unlock(&new_lock->l_resource->lr_namespace->ns_lock);
3212
3213         RETURN(ELDLM_LOCK_REPLACED);
3214 }
3215
3216 int mds_attach(struct obd_device *dev, obd_count len, void *data)
3217 {
3218         struct lprocfs_static_vars lvars;
3219
3220         lprocfs_init_multi_vars(0, &lvars);
3221         return lprocfs_obd_attach(dev, lvars.obd_vars);
3222 }
3223
3224 int mds_detach(struct obd_device *dev)
3225 {
3226         return lprocfs_obd_detach(dev);
3227 }
3228
3229 int mdt_attach(struct obd_device *dev, obd_count len, void *data)
3230 {
3231         struct lprocfs_static_vars lvars;
3232
3233         lprocfs_init_multi_vars(1, &lvars);
3234         return lprocfs_obd_attach(dev, lvars.obd_vars);
3235 }
3236
3237 int mdt_detach(struct obd_device *dev)
3238 {
3239         return lprocfs_obd_detach(dev);
3240 }
3241
3242 static int mdt_setup(struct obd_device *obd, obd_count len, void *buf)
3243 {
3244         struct mds_obd *mds = &obd->u.mds;
3245         int rc = 0;
3246         ENTRY;
3247
3248         mds->mds_service =
3249                 ptlrpc_init_svc(MDS_NBUFS, MDS_BUFSIZE, MDS_MAXREQSIZE,
3250                                 MDS_REQUEST_PORTAL, MDC_REPLY_PORTAL,
3251                                 mds_handle, "mds", obd->obd_proc_entry);
3252
3253         if (!mds->mds_service) {
3254                 CERROR("failed to start service\n");
3255                 RETURN(-ENOMEM);
3256         }
3257
3258         rc = ptlrpc_start_n_threads(obd, mds->mds_service, MDT_NUM_THREADS,
3259                                     "ll_mdt");
3260         if (rc)
3261                 GOTO(err_thread, rc);
3262
3263         mds->mds_setattr_service =
3264                 ptlrpc_init_svc(MDS_NBUFS, MDS_BUFSIZE, MDS_MAXREQSIZE,
3265                                 MDS_SETATTR_PORTAL, MDC_REPLY_PORTAL,
3266                                 mds_handle, "mds_setattr",
3267                                 obd->obd_proc_entry);
3268         if (!mds->mds_setattr_service) {
3269                 CERROR("failed to start getattr service\n");
3270                 GOTO(err_thread, rc = -ENOMEM);
3271         }
3272
3273         rc = ptlrpc_start_n_threads(obd, mds->mds_setattr_service,
3274                                     MDT_NUM_THREADS, "ll_mdt_attr");
3275         if (rc)
3276                 GOTO(err_thread2, rc);
3277
3278         mds->mds_readpage_service =
3279                 ptlrpc_init_svc(MDS_NBUFS, MDS_BUFSIZE, MDS_MAXREQSIZE,
3280                                 MDS_READPAGE_PORTAL, MDC_REPLY_PORTAL,
3281                                 mds_handle, "mds_readpage",
3282                                 obd->obd_proc_entry);
3283         if (!mds->mds_readpage_service) {
3284                 CERROR("failed to start readpage service\n");
3285                 GOTO(err_thread2, rc = -ENOMEM);
3286         }
3287
3288         rc = ptlrpc_start_n_threads(obd, mds->mds_readpage_service,
3289                                     MDT_NUM_THREADS, "ll_mdt_rdpg");
3290
3291         if (rc)
3292                 GOTO(err_thread3, rc);
3293
3294         RETURN(0);
3295
3296 err_thread3:
3297         ptlrpc_unregister_service(mds->mds_readpage_service);
3298 err_thread2:
3299         ptlrpc_unregister_service(mds->mds_setattr_service);
3300 err_thread:
3301         ptlrpc_unregister_service(mds->mds_service);
3302         return rc;
3303 }
3304
3305 static int mdt_cleanup(struct obd_device *obd, int flags)
3306 {
3307         struct mds_obd *mds = &obd->u.mds;
3308         ENTRY;
3309
3310         ptlrpc_stop_all_threads(mds->mds_readpage_service);
3311         ptlrpc_unregister_service(mds->mds_readpage_service);
3312
3313         ptlrpc_stop_all_threads(mds->mds_setattr_service);
3314         ptlrpc_unregister_service(mds->mds_setattr_service);
3315
3316         ptlrpc_stop_all_threads(mds->mds_service);
3317         ptlrpc_unregister_service(mds->mds_service);
3318
3319         RETURN(0);
3320 }
3321
3322 static struct dentry *mds_lvfs_id2dentry(__u64 ino, __u32 gen,
3323                                          __u64 gr, void *data)
3324 {
3325         struct lustre_id id;
3326         struct obd_device *obd = data;
3327         
3328         id_ino(&id) = ino;
3329         id_gen(&id) = gen;
3330         return mds_id2dentry(obd, &id, NULL);
3331 }
3332
3333 static int mds_get_info(struct obd_export *exp, __u32 keylen,
3334                         void *key, __u32 *valsize, void *val)
3335 {
3336         struct obd_device *obd;
3337         struct mds_obd *mds;
3338         ENTRY;
3339
3340         obd = class_exp2obd(exp);
3341         mds = &obd->u.mds;
3342         
3343         if (obd == NULL) {
3344                 CDEBUG(D_IOCTL, "invalid client cookie "LPX64"\n",
3345                        exp->exp_handle.h_cookie);
3346                 RETURN(-EINVAL);
3347         }
3348
3349         if (keylen >= strlen("reint_log") && memcmp(key, "reint_log", 9) == 0) {
3350                 /* get log_context handle. */
3351                 unsigned long *llh_handle = val;
3352                 *valsize = sizeof(unsigned long);
3353                 *llh_handle = (unsigned long)obd->obd_llog_ctxt[LLOG_REINT_ORIG_CTXT];
3354                 RETURN(0);
3355         }
3356         if (keylen >= strlen("cache_sb") && memcmp(key, "cache_sb", 8) == 0) {
3357                 /* get log_context handle. */
3358                 unsigned long *sb = val;
3359                 *valsize = sizeof(unsigned long);
3360                 *sb = (unsigned long)obd->u.mds.mds_sb;
3361                 RETURN(0);
3362         }
3363
3364         if (keylen >= strlen("mdsize") && memcmp(key, "mdsize", keylen) == 0) {
3365                 __u32 *mdsize = val;
3366                 *valsize = sizeof(*mdsize);
3367                 *mdsize = mds->mds_max_mdsize;
3368                 RETURN(0);
3369         }
3370
3371         if (keylen >= strlen("mdsnum") && strcmp(key, "mdsnum") == 0) {
3372                 __u32 *mdsnum = val;
3373                 *valsize = sizeof(*mdsnum);
3374                 *mdsnum = mds->mds_num;
3375                 RETURN(0);
3376         }
3377
3378         if (keylen >= strlen("rootid") && strcmp(key, "rootid") == 0) {
3379                 struct lustre_id *rootid = val;
3380                 *valsize = sizeof(struct lustre_id);
3381                 *rootid = mds->mds_rootid;
3382                 RETURN(0);
3383         }
3384
3385         CDEBUG(D_IOCTL, "invalid key\n");
3386         RETURN(-EINVAL);
3387
3388 }
3389 struct lvfs_callback_ops mds_lvfs_ops = {
3390         l_id2dentry:     mds_lvfs_id2dentry,
3391 };
3392
3393 int mds_preprw(int cmd, struct obd_export *exp, struct obdo *oa,
3394                 int objcount, struct obd_ioobj *obj,
3395                 int niocount, struct niobuf_remote *nb,
3396                 struct niobuf_local *res,
3397                 struct obd_trans_info *oti);
3398
3399 int mds_commitrw(int cmd, struct obd_export *exp, struct obdo *oa,
3400                  int objcount, struct obd_ioobj *obj, int niocount,
3401                  struct niobuf_local *res, struct obd_trans_info *oti,
3402                  int rc);
3403
3404 /* use obd ops to offer management infrastructure */
3405 static struct obd_ops mds_obd_ops = {
3406         .o_owner           = THIS_MODULE,
3407         .o_attach          = mds_attach,
3408         .o_detach          = mds_detach,
3409         .o_connect         = mds_connect,
3410         .o_init_export     = mds_init_export,
3411         .o_destroy_export  = mds_destroy_export,
3412         .o_disconnect      = mds_disconnect,
3413         .o_setup           = mds_setup,
3414         .o_precleanup      = mds_precleanup,
3415         .o_cleanup         = mds_cleanup,
3416         .o_postrecov       = mds_postrecov,
3417         .o_statfs          = mds_obd_statfs,
3418         .o_iocontrol       = mds_iocontrol,
3419         .o_create          = mds_obd_create,
3420         .o_destroy         = mds_obd_destroy,
3421         .o_llog_init       = mds_llog_init,
3422         .o_llog_finish     = mds_llog_finish,
3423         .o_notify          = mds_notify,
3424         .o_get_info        = mds_get_info,
3425         .o_set_info        = mds_set_info,
3426         .o_preprw          = mds_preprw, 
3427         .o_commitrw        = mds_commitrw,
3428 };
3429
3430 static struct obd_ops mdt_obd_ops = {
3431         .o_owner           = THIS_MODULE,
3432         .o_attach          = mdt_attach,
3433         .o_detach          = mdt_detach,
3434         .o_setup           = mdt_setup,
3435         .o_cleanup         = mdt_cleanup,
3436 };
3437
3438 static int __init mds_init(void)
3439 {
3440         struct lprocfs_static_vars lvars;
3441
3442         mds_group_hash_init();
3443
3444         lprocfs_init_multi_vars(0, &lvars);
3445         class_register_type(&mds_obd_ops, NULL, lvars.module_vars,
3446                             LUSTRE_MDS_NAME);
3447         lprocfs_init_multi_vars(1, &lvars);
3448         class_register_type(&mdt_obd_ops, NULL, lvars.module_vars,
3449                             LUSTRE_MDT_NAME);
3450
3451         return 0;
3452 }
3453
3454 static void /*__exit*/ mds_exit(void)
3455 {
3456         mds_group_hash_cleanup();
3457
3458         class_unregister_type(LUSTRE_MDS_NAME);
3459         class_unregister_type(LUSTRE_MDT_NAME);
3460 }
3461
3462 MODULE_AUTHOR("Cluster File Systems, Inc. <info@clusterfs.com>");
3463 MODULE_DESCRIPTION("Lustre Metadata Server (MDS)");
3464 MODULE_LICENSE("GPL");
3465
3466 module_init(mds_init);
3467 module_exit(mds_exit);