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