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