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