Whamcloud - gitweb
Branch HEAD
[fs/lustre-release.git] / lustre / mdt / mdt_handler.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright  2008 Sun Microsystems, Inc. All rights reserved
30  * Use is subject to license terms.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/mdt/mdt_handler.c
37  *
38  * Lustre Metadata Target (mdt) request handler
39  *
40  * Author: Peter Braam <braam@clusterfs.com>
41  * Author: Andreas Dilger <adilger@clusterfs.com>
42  * Author: Phil Schwan <phil@clusterfs.com>
43  * Author: Mike Shaver <shaver@clusterfs.com>
44  * Author: Nikita Danilov <nikita@clusterfs.com>
45  * Author: Huang Hua <huanghua@clusterfs.com>
46  * Author: Yury Umanets <umka@clusterfs.com>
47  */
48
49 #ifndef EXPORT_SYMTAB
50 # define EXPORT_SYMTAB
51 #endif
52 #define DEBUG_SUBSYSTEM S_MDS
53
54 #include <linux/module.h>
55 /*
56  * struct OBD_{ALLOC,FREE}*()
57  */
58 #include <obd_support.h>
59 /* struct ptlrpc_request */
60 #include <lustre_net.h>
61 /* struct obd_export */
62 #include <lustre_export.h>
63 /* struct obd_device */
64 #include <obd.h>
65 /* lu2dt_dev() */
66 #include <dt_object.h>
67 #include <lustre_mds.h>
68 #include <lustre_mdt.h>
69 #include "mdt_internal.h"
70 #ifdef HAVE_QUOTA_SUPPORT
71 # include <lustre_quota.h>
72 #endif
73 #include <lustre_acl.h>
74 #include <lustre_param.h>
75 #include <lustre_fsfilt.h>
76
77 mdl_mode_t mdt_mdl_lock_modes[] = {
78         [LCK_MINMODE] = MDL_MINMODE,
79         [LCK_EX]      = MDL_EX,
80         [LCK_PW]      = MDL_PW,
81         [LCK_PR]      = MDL_PR,
82         [LCK_CW]      = MDL_CW,
83         [LCK_CR]      = MDL_CR,
84         [LCK_NL]      = MDL_NL,
85         [LCK_GROUP]   = MDL_GROUP
86 };
87
88 ldlm_mode_t mdt_dlm_lock_modes[] = {
89         [MDL_MINMODE] = LCK_MINMODE,
90         [MDL_EX]      = LCK_EX,
91         [MDL_PW]      = LCK_PW,
92         [MDL_PR]      = LCK_PR,
93         [MDL_CW]      = LCK_CW,
94         [MDL_CR]      = LCK_CR,
95         [MDL_NL]      = LCK_NL,
96         [MDL_GROUP]   = LCK_GROUP
97 };
98
99 /*
100  * Initialized in mdt_mod_init().
101  */
102 unsigned long mdt_num_threads;
103
104 /* ptlrpc request handler for MDT. All handlers are
105  * grouped into several slices - struct mdt_opc_slice,
106  * and stored in an array - mdt_handlers[].
107  */
108 struct mdt_handler {
109         /* The name of this handler. */
110         const char *mh_name;
111         /* Fail id for this handler, checked at the beginning of this handler*/
112         int         mh_fail_id;
113         /* Operation code for this handler */
114         __u32       mh_opc;
115         /* flags are listed in enum mdt_handler_flags below. */
116         __u32       mh_flags;
117         /* The actual handler function to execute. */
118         int (*mh_act)(struct mdt_thread_info *info);
119         /* Request format for this request. */
120         const struct req_format *mh_fmt;
121 };
122
123 enum mdt_handler_flags {
124         /*
125          * struct mdt_body is passed in the incoming message, and object
126          * identified by this fid exists on disk.
127          *
128          * "habeo corpus" == "I have a body"
129          */
130         HABEO_CORPUS = (1 << 0),
131         /*
132          * struct ldlm_request is passed in the incoming message.
133          *
134          * "habeo clavis" == "I have a key"
135          */
136         HABEO_CLAVIS = (1 << 1),
137         /*
138          * this request has fixed reply format, so that reply message can be
139          * packed by generic code.
140          *
141          * "habeo refero" == "I have a reply"
142          */
143         HABEO_REFERO = (1 << 2),
144         /*
145          * this request will modify something, so check whether the filesystem
146          * is readonly or not, then return -EROFS to client asap if necessary.
147          *
148          * "mutabor" == "I shall modify"
149          */
150         MUTABOR      = (1 << 3)
151 };
152
153 struct mdt_opc_slice {
154         __u32               mos_opc_start;
155         int                 mos_opc_end;
156         struct mdt_handler *mos_hs;
157 };
158
159 static struct mdt_opc_slice mdt_regular_handlers[];
160 static struct mdt_opc_slice mdt_readpage_handlers[];
161 static struct mdt_opc_slice mdt_xmds_handlers[];
162 static struct mdt_opc_slice mdt_seq_handlers[];
163 static struct mdt_opc_slice mdt_fld_handlers[];
164
165 static struct mdt_device *mdt_dev(struct lu_device *d);
166 static int mdt_regular_handle(struct ptlrpc_request *req);
167 static int mdt_unpack_req_pack_rep(struct mdt_thread_info *info, __u32 flags);
168 static int mdt_fid2path(const struct lu_env *env, struct mdt_device *mdt,
169                         struct getinfo_fid2path *fp);
170
171 static const struct lu_object_operations mdt_obj_ops;
172
173 int mdt_get_disposition(struct ldlm_reply *rep, int flag)
174 {
175         if (!rep)
176                 return 0;
177         return (rep->lock_policy_res1 & flag);
178 }
179
180 void mdt_clear_disposition(struct mdt_thread_info *info,
181                            struct ldlm_reply *rep, int flag)
182 {
183         if (info)
184                 info->mti_opdata &= ~flag;
185         if (rep)
186                 rep->lock_policy_res1 &= ~flag;
187 }
188
189 void mdt_set_disposition(struct mdt_thread_info *info,
190                          struct ldlm_reply *rep, int flag)
191 {
192         if (info)
193                 info->mti_opdata |= flag;
194         if (rep)
195                 rep->lock_policy_res1 |= flag;
196 }
197
198 void mdt_lock_reg_init(struct mdt_lock_handle *lh, ldlm_mode_t lm)
199 {
200         lh->mlh_pdo_hash = 0;
201         lh->mlh_reg_mode = lm;
202         lh->mlh_type = MDT_REG_LOCK;
203 }
204
205 void mdt_lock_pdo_init(struct mdt_lock_handle *lh, ldlm_mode_t lm,
206                        const char *name, int namelen)
207 {
208         lh->mlh_reg_mode = lm;
209         lh->mlh_type = MDT_PDO_LOCK;
210
211         if (name != NULL) {
212                 LASSERT(namelen > 0);
213                 lh->mlh_pdo_hash = full_name_hash(name, namelen);
214         } else {
215                 LASSERT(namelen == 0);
216                 lh->mlh_pdo_hash = 0ull;
217         }
218 }
219
220 static void mdt_lock_pdo_mode(struct mdt_thread_info *info, struct mdt_object *o,
221                               struct mdt_lock_handle *lh)
222 {
223         mdl_mode_t mode;
224         ENTRY;
225
226         /*
227          * Any dir access needs couple of locks:
228          *
229          * 1) on part of dir we gonna take lookup/modify;
230          *
231          * 2) on whole dir to protect it from concurrent splitting and/or to
232          * flush client's cache for readdir().
233          *
234          * so, for a given mode and object this routine decides what lock mode
235          * to use for lock #2:
236          *
237          * 1) if caller's gonna lookup in dir then we need to protect dir from
238          * being splitted only - LCK_CR
239          *
240          * 2) if caller's gonna modify dir then we need to protect dir from
241          * being splitted and to flush cache - LCK_CW
242          *
243          * 3) if caller's gonna modify dir and that dir seems ready for
244          * splitting then we need to protect it from any type of access
245          * (lookup/modify/split) - LCK_EX --bzzz
246          */
247
248         LASSERT(lh->mlh_reg_mode != LCK_MINMODE);
249         LASSERT(lh->mlh_pdo_mode == LCK_MINMODE);
250
251         /*
252          * Ask underlaying level its opinion about preferable PDO lock mode
253          * having access type passed as regular lock mode:
254          *
255          * - MDL_MINMODE means that lower layer does not want to specify lock
256          * mode;
257          *
258          * - MDL_NL means that no PDO lock should be taken. This is used in some
259          * cases. Say, for non-splittable directories no need to use PDO locks
260          * at all.
261          */
262         mode = mdo_lock_mode(info->mti_env, mdt_object_child(o),
263                              mdt_dlm_mode2mdl_mode(lh->mlh_reg_mode));
264
265         if (mode != MDL_MINMODE) {
266                 lh->mlh_pdo_mode = mdt_mdl_mode2dlm_mode(mode);
267         } else {
268                 /*
269                  * Lower layer does not want to specify locking mode. We do it
270                  * our selves. No special protection is needed, just flush
271                  * client's cache on modification and allow concurrent
272                  * mondification.
273                  */
274                 switch (lh->mlh_reg_mode) {
275                 case LCK_EX:
276                         lh->mlh_pdo_mode = LCK_EX;
277                         break;
278                 case LCK_PR:
279                         lh->mlh_pdo_mode = LCK_CR;
280                         break;
281                 case LCK_PW:
282                         lh->mlh_pdo_mode = LCK_CW;
283                         break;
284                 default:
285                         CERROR("Not expected lock type (0x%x)\n",
286                                (int)lh->mlh_reg_mode);
287                         LBUG();
288                 }
289         }
290
291         LASSERT(lh->mlh_pdo_mode != LCK_MINMODE);
292         EXIT;
293 }
294
295 static int mdt_getstatus(struct mdt_thread_info *info)
296 {
297         struct mdt_device *mdt  = info->mti_mdt;
298         struct md_device  *next = mdt->mdt_child;
299         struct mdt_body   *repbody;
300         int                rc;
301
302         ENTRY;
303
304         rc = mdt_check_ucred(info);
305         if (rc)
306                 RETURN(err_serious(rc));
307
308         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_GETSTATUS_PACK))
309                 RETURN(err_serious(-ENOMEM));
310
311         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
312         rc = next->md_ops->mdo_root_get(info->mti_env, next, &repbody->fid1);
313         if (rc != 0)
314                 RETURN(rc);
315
316         repbody->valid |= OBD_MD_FLID;
317
318         if (mdt->mdt_opts.mo_mds_capa &&
319             info->mti_exp->exp_connect_flags & OBD_CONNECT_MDS_CAPA) {
320                 struct mdt_object  *root;
321                 struct lustre_capa *capa;
322
323                 root = mdt_object_find(info->mti_env, mdt, &repbody->fid1);
324                 if (IS_ERR(root))
325                         RETURN(PTR_ERR(root));
326
327                 capa = req_capsule_server_get(info->mti_pill, &RMF_CAPA1);
328                 LASSERT(capa);
329                 capa->lc_opc = CAPA_OPC_MDS_DEFAULT;
330                 rc = mo_capa_get(info->mti_env, mdt_object_child(root), capa,
331                                  0);
332                 mdt_object_put(info->mti_env, root);
333                 if (rc == 0)
334                         repbody->valid |= OBD_MD_FLMDSCAPA;
335         }
336
337         RETURN(rc);
338 }
339
340 static int mdt_statfs(struct mdt_thread_info *info)
341 {
342         struct md_device      *next  = info->mti_mdt->mdt_child;
343         struct ptlrpc_service *svc;
344         struct obd_statfs     *osfs;
345         int                    rc;
346
347         ENTRY;
348
349         svc = info->mti_pill->rc_req->rq_rqbd->rqbd_service;
350
351         /* This will trigger a watchdog timeout */
352         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_STATFS_LCW_SLEEP,
353                          (MDT_SERVICE_WATCHDOG_FACTOR *
354                           at_get(&svc->srv_at_estimate)) + 1);
355
356         rc = mdt_check_ucred(info);
357         if (rc)
358                 RETURN(err_serious(rc));
359
360         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_STATFS_PACK)) {
361                 rc = err_serious(-ENOMEM);
362         } else {
363                 osfs = req_capsule_server_get(info->mti_pill, &RMF_OBD_STATFS);
364                 rc = next->md_ops->mdo_statfs(info->mti_env, next,
365                                               &info->mti_u.ksfs);
366                 statfs_pack(osfs, &info->mti_u.ksfs);
367         }
368         RETURN(rc);
369 }
370
371 void mdt_pack_size2body(struct mdt_thread_info *info, struct mdt_object *o)
372 {
373         struct mdt_body *b;
374         struct lu_attr *attr = &info->mti_attr.ma_attr;
375
376         b = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
377
378         /* Check if Size-on-MDS is enabled. */
379         if ((mdt_conn_flags(info) & OBD_CONNECT_SOM) &&
380             S_ISREG(attr->la_mode) && mdt_sizeonmds_enabled(o)) {
381                 b->valid |= (OBD_MD_FLSIZE | OBD_MD_FLBLOCKS);
382                 b->size = attr->la_size;
383                 b->blocks = attr->la_blocks;
384         }
385 }
386
387 void mdt_pack_attr2body(struct mdt_thread_info *info, struct mdt_body *b,
388                         const struct lu_attr *attr, const struct lu_fid *fid)
389 {
390         /*XXX should pack the reply body according to lu_valid*/
391         b->valid |= OBD_MD_FLCTIME | OBD_MD_FLUID   |
392                     OBD_MD_FLGID   | OBD_MD_FLTYPE  |
393                     OBD_MD_FLMODE  | OBD_MD_FLNLINK | OBD_MD_FLFLAGS |
394                     OBD_MD_FLATIME | OBD_MD_FLMTIME ;
395
396         if (!S_ISREG(attr->la_mode))
397                 b->valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS | OBD_MD_FLRDEV;
398
399         b->atime      = attr->la_atime;
400         b->mtime      = attr->la_mtime;
401         b->ctime      = attr->la_ctime;
402         b->mode       = attr->la_mode;
403         b->size       = attr->la_size;
404         b->blocks     = attr->la_blocks;
405         b->uid        = attr->la_uid;
406         b->gid        = attr->la_gid;
407         b->flags      = attr->la_flags;
408         b->nlink      = attr->la_nlink;
409         b->rdev       = attr->la_rdev;
410
411         if (fid) {
412                 b->fid1 = *fid;
413                 b->valid |= OBD_MD_FLID;
414
415                 /* FIXME: these should be fixed when new igif ready.*/
416                 b->ino  =  fid_oid(fid);       /* 1.6 compatibility */
417                 b->generation = fid_ver(fid);  /* 1.6 compatibility */
418                 b->valid |= OBD_MD_FLGENER;    /* 1.6 compatibility */
419
420                 CDEBUG(D_INODE, DFID": nlink=%d, mode=%o, size="LPU64"\n",
421                                 PFID(fid), b->nlink, b->mode, b->size);
422         }
423
424         if (info)
425                 mdt_body_reverse_idmap(info, b);
426 }
427
428 static inline int mdt_body_has_lov(const struct lu_attr *la,
429                                    const struct mdt_body *body)
430 {
431         return ((S_ISREG(la->la_mode) && (body->valid & OBD_MD_FLEASIZE)) ||
432                 (S_ISDIR(la->la_mode) && (body->valid & OBD_MD_FLDIREA )) );
433 }
434
435 static int mdt_getattr_internal(struct mdt_thread_info *info,
436                                 struct mdt_object *o)
437 {
438         struct md_object        *next = mdt_object_child(o);
439         const struct mdt_body   *reqbody = info->mti_body;
440         struct ptlrpc_request   *req = mdt_info_req(info);
441         struct md_attr          *ma = &info->mti_attr;
442         struct lu_attr          *la = &ma->ma_attr;
443         struct req_capsule      *pill = info->mti_pill;
444         const struct lu_env     *env = info->mti_env;
445         struct mdt_body         *repbody;
446         struct lu_buf           *buffer = &info->mti_buf;
447         int                     rc;
448         ENTRY;
449
450         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_GETATTR_PACK))
451                 RETURN(err_serious(-ENOMEM));
452
453         repbody = req_capsule_server_get(pill, &RMF_MDT_BODY);
454
455         ma->ma_valid = 0;
456
457         rc = mdt_object_exists(o);
458         if (rc < 0) {
459                 /* This object is located on remote node.*/
460                 repbody->fid1 = *mdt_object_fid(o);
461                 repbody->valid = OBD_MD_FLID | OBD_MD_MDS;
462                 RETURN(0);
463         }
464
465         buffer->lb_buf = req_capsule_server_get(pill, &RMF_MDT_MD);
466         buffer->lb_len = req_capsule_get_size(pill, &RMF_MDT_MD, RCL_SERVER);
467
468         /* If it is dir object and client require MEA, then we got MEA */
469         if (S_ISDIR(lu_object_attr(&next->mo_lu)) &&
470             reqbody->valid & OBD_MD_MEA) {
471                 /* Assumption: MDT_MD size is enough for lmv size. */
472                 ma->ma_lmv = buffer->lb_buf;
473                 ma->ma_lmv_size = buffer->lb_len;
474                 ma->ma_need = MA_LMV | MA_INODE;
475         } else {
476                 ma->ma_lmm = buffer->lb_buf;
477                 ma->ma_lmm_size = buffer->lb_len;
478                 ma->ma_need = MA_LOV | MA_INODE;
479         }
480
481         if (S_ISDIR(lu_object_attr(&next->mo_lu)) &&
482             reqbody->valid & OBD_MD_FLDIREA  &&
483             lustre_msg_get_opc(req->rq_reqmsg) == MDS_GETATTR) {
484                 /* get default stripe info for this dir. */
485                 ma->ma_need |= MA_LOV_DEF;
486         }
487         rc = mo_attr_get(env, next, ma);
488         if (unlikely(rc)) {
489                 CERROR("getattr error for "DFID": %d\n",
490                         PFID(mdt_object_fid(o)), rc);
491                 RETURN(rc);
492         }
493
494         if (likely(ma->ma_valid & MA_INODE))
495                 mdt_pack_attr2body(info, repbody, la, mdt_object_fid(o));
496         else
497                 RETURN(-EFAULT);
498
499         if (mdt_body_has_lov(la, reqbody)) {
500                 if (ma->ma_valid & MA_LOV) {
501                         LASSERT(ma->ma_lmm_size);
502                         mdt_dump_lmm(D_INFO, ma->ma_lmm);
503                         repbody->eadatasize = ma->ma_lmm_size;
504                         if (S_ISDIR(la->la_mode))
505                                 repbody->valid |= OBD_MD_FLDIREA;
506                         else
507                                 repbody->valid |= OBD_MD_FLEASIZE;
508                 }
509                 if (ma->ma_valid & MA_LMV) {
510                         LASSERT(S_ISDIR(la->la_mode));
511                         repbody->eadatasize = ma->ma_lmv_size;
512                         repbody->valid |= (OBD_MD_FLDIREA|OBD_MD_MEA);
513                 }
514                 if (!(ma->ma_valid & MA_LOV) && !(ma->ma_valid & MA_LMV)) {
515                         repbody->valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS;
516                 }
517         } else if (S_ISLNK(la->la_mode) &&
518                    reqbody->valid & OBD_MD_LINKNAME) {
519                 buffer->lb_buf = ma->ma_lmm;
520                 buffer->lb_len = reqbody->eadatasize;
521                 rc = mo_readlink(env, next, buffer);
522                 if (unlikely(rc <= 0)) {
523                         CERROR("readlink failed: %d\n", rc);
524                         rc = -EFAULT;
525                 } else {
526                         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_READLINK_EPROTO))
527                                  rc -= 2;
528                         repbody->valid |= OBD_MD_LINKNAME;
529                         repbody->eadatasize = rc;
530                         /* NULL terminate */
531                         ((char*)ma->ma_lmm)[rc - 1] = 0;
532                         CDEBUG(D_INODE, "symlink dest %s, len = %d\n",
533                                (char*)ma->ma_lmm, rc);
534                         rc = 0;
535                 }
536         }
537
538         if (reqbody->valid & OBD_MD_FLMODEASIZE) {
539                 repbody->max_cookiesize = info->mti_mdt->mdt_max_cookiesize;
540                 repbody->max_mdsize = info->mti_mdt->mdt_max_mdsize;
541                 repbody->valid |= OBD_MD_FLMODEASIZE;
542                 CDEBUG(D_INODE, "I am going to change the MAX_MD_SIZE & "
543                        "MAX_COOKIE to : %d:%d\n", repbody->max_mdsize,
544                        repbody->max_cookiesize);
545         }
546
547         if (exp_connect_rmtclient(info->mti_exp) &&
548             reqbody->valid & OBD_MD_FLRMTPERM) {
549                 void *buf = req_capsule_server_get(pill, &RMF_ACL);
550
551                 /* mdt_getattr_lock only */
552                 rc = mdt_pack_remote_perm(info, o, buf);
553                 if (rc) {
554                         repbody->valid &= ~OBD_MD_FLRMTPERM;
555                         repbody->aclsize = 0;
556                         RETURN(rc);
557                 } else {
558                         repbody->valid |= OBD_MD_FLRMTPERM;
559                         repbody->aclsize = sizeof(struct mdt_remote_perm);
560                 }
561         }
562 #ifdef CONFIG_FS_POSIX_ACL
563         else if ((req->rq_export->exp_connect_flags & OBD_CONNECT_ACL) &&
564                  (reqbody->valid & OBD_MD_FLACL)) {
565                 buffer->lb_buf = req_capsule_server_get(pill, &RMF_ACL);
566                 buffer->lb_len = req_capsule_get_size(pill,
567                                                       &RMF_ACL, RCL_SERVER);
568                 if (buffer->lb_len > 0) {
569                         rc = mo_xattr_get(env, next, buffer,
570                                           XATTR_NAME_ACL_ACCESS);
571                         if (rc < 0) {
572                                 if (rc == -ENODATA) {
573                                         repbody->aclsize = 0;
574                                         repbody->valid |= OBD_MD_FLACL;
575                                         rc = 0;
576                                 } else if (rc == -EOPNOTSUPP) {
577                                         rc = 0;
578                                 } else {
579                                         CERROR("got acl size: %d\n", rc);
580                                 }
581                         } else {
582                                 repbody->aclsize = rc;
583                                 repbody->valid |= OBD_MD_FLACL;
584                                 rc = 0;
585                         }
586                 }
587         }
588 #endif
589
590         if (reqbody->valid & OBD_MD_FLMDSCAPA &&
591             info->mti_mdt->mdt_opts.mo_mds_capa &&
592             info->mti_exp->exp_connect_flags & OBD_CONNECT_MDS_CAPA) {
593                 struct lustre_capa *capa;
594
595                 capa = req_capsule_server_get(pill, &RMF_CAPA1);
596                 LASSERT(capa);
597                 capa->lc_opc = CAPA_OPC_MDS_DEFAULT;
598                 rc = mo_capa_get(env, next, capa, 0);
599                 if (rc)
600                         RETURN(rc);
601                 repbody->valid |= OBD_MD_FLMDSCAPA;
602         }
603         RETURN(rc);
604 }
605
606 static int mdt_renew_capa(struct mdt_thread_info *info)
607 {
608         struct mdt_object  *obj = info->mti_object;
609         struct mdt_body    *body;
610         struct lustre_capa *capa, *c;
611         int rc;
612         ENTRY;
613
614         /* if object doesn't exist, or server has disabled capability,
615          * return directly, client will find body->valid OBD_MD_FLOSSCAPA
616          * flag not set.
617          */
618         if (!obj || !info->mti_mdt->mdt_opts.mo_oss_capa ||
619             !(info->mti_exp->exp_connect_flags & OBD_CONNECT_OSS_CAPA))
620                 RETURN(0);
621
622         body = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
623         LASSERT(body != NULL);
624
625         c = req_capsule_client_get(info->mti_pill, &RMF_CAPA1);
626         LASSERT(c);
627
628         capa = req_capsule_server_get(info->mti_pill, &RMF_CAPA2);
629         LASSERT(capa);
630
631         *capa = *c;
632         rc = mo_capa_get(info->mti_env, mdt_object_child(obj), capa, 1);
633         if (rc == 0)
634                 body->valid |= OBD_MD_FLOSSCAPA;
635         RETURN(rc);
636 }
637
638 static int mdt_getattr(struct mdt_thread_info *info)
639 {
640         struct mdt_object       *obj = info->mti_object;
641         struct req_capsule      *pill = info->mti_pill;
642         struct mdt_body         *reqbody;
643         struct mdt_body         *repbody;
644         mode_t                   mode;
645         int                      md_size;
646         int rc;
647         ENTRY;
648
649         reqbody = req_capsule_client_get(pill, &RMF_MDT_BODY);
650         LASSERT(reqbody);
651
652         if (reqbody->valid & OBD_MD_FLOSSCAPA) {
653                 rc = req_capsule_server_pack(pill);
654                 if (unlikely(rc))
655                         RETURN(err_serious(rc));
656                 rc = mdt_renew_capa(info);
657                 GOTO(out_shrink, rc);
658         }
659
660         LASSERT(obj != NULL);
661         LASSERT(lu_object_assert_exists(&obj->mot_obj.mo_lu));
662
663         mode = lu_object_attr(&obj->mot_obj.mo_lu);
664         if (S_ISLNK(mode) && (reqbody->valid & OBD_MD_LINKNAME) &&
665             (reqbody->eadatasize > info->mti_mdt->mdt_max_mdsize))
666                 md_size = reqbody->eadatasize;
667         else
668                 md_size = info->mti_mdt->mdt_max_mdsize;
669
670         req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER, md_size);
671
672         rc = req_capsule_server_pack(pill);
673         if (unlikely(rc != 0))
674                 RETURN(err_serious(rc));
675
676         repbody = req_capsule_server_get(pill, &RMF_MDT_BODY);
677         LASSERT(repbody != NULL);
678         repbody->eadatasize = 0;
679         repbody->aclsize = 0;
680
681         if (reqbody->valid & OBD_MD_FLRMTPERM)
682                 rc = mdt_init_ucred(info, reqbody);
683         else
684                 rc = mdt_check_ucred(info);
685         if (unlikely(rc))
686                 GOTO(out_shrink, rc);
687
688         info->mti_spec.sp_ck_split = !!(reqbody->valid & OBD_MD_FLCKSPLIT);
689         info->mti_cross_ref = !!(reqbody->valid & OBD_MD_FLCROSSREF);
690
691         /*
692          * Don't check capability at all, because rename might getattr for
693          * remote obj, and at that time no capability is available.
694          */
695         mdt_set_capainfo(info, 1, &reqbody->fid1, BYPASS_CAPA);
696         rc = mdt_getattr_internal(info, obj);
697         if (reqbody->valid & OBD_MD_FLRMTPERM)
698                 mdt_exit_ucred(info);
699         EXIT;
700 out_shrink:
701         mdt_shrink_reply(info);
702         return rc;
703 }
704
705 static int mdt_is_subdir(struct mdt_thread_info *info)
706 {
707         struct mdt_object     *o = info->mti_object;
708         struct req_capsule    *pill = info->mti_pill;
709         const struct mdt_body *body = info->mti_body;
710         struct mdt_body       *repbody;
711         int                    rc;
712         ENTRY;
713
714         LASSERT(o != NULL);
715
716         repbody = req_capsule_server_get(pill, &RMF_MDT_BODY);
717
718         /*
719          * We save last checked parent fid to @repbody->fid1 for remote
720          * directory case.
721          */
722         LASSERT(fid_is_sane(&body->fid2));
723         LASSERT(mdt_object_exists(o) > 0);
724         rc = mdo_is_subdir(info->mti_env, mdt_object_child(o),
725                            &body->fid2, &repbody->fid1);
726         if (rc == 0 || rc == -EREMOTE)
727                 repbody->valid |= OBD_MD_FLID;
728
729         RETURN(rc);
730 }
731
732 static int mdt_raw_lookup(struct mdt_thread_info *info,
733                           struct mdt_object *parent,
734                           const struct lu_name *lname,
735                           struct ldlm_reply *ldlm_rep)
736 {
737         struct md_object *next = mdt_object_child(info->mti_object);
738         const struct mdt_body *reqbody = info->mti_body;
739         struct lu_fid *child_fid = &info->mti_tmp_fid1;
740         struct mdt_body *repbody;
741         int rc;
742         ENTRY;
743
744         if (reqbody->valid != OBD_MD_FLID)
745                 RETURN(0);
746
747         LASSERT(!info->mti_cross_ref);
748
749         /* Only got the fid of this obj by name */
750         rc = mdo_lookup(info->mti_env, next, lname, child_fid,
751                         &info->mti_spec);
752 #if 0
753         /* XXX is raw_lookup possible as intent operation? */
754         if (rc != 0) {
755                 if (rc == -ENOENT)
756                         mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_NEG);
757                 RETURN(rc);
758         } else
759                 mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_POS);
760
761         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
762 #endif
763         if (rc == 0) {
764                 repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
765                 repbody->fid1 = *child_fid;
766                 repbody->valid = OBD_MD_FLID;
767         }
768         RETURN(1);
769 }
770
771 /*
772  * UPDATE lock should be taken against parent, and be release before exit;
773  * child_bits lock should be taken against child, and be returned back:
774  *            (1)normal request should release the child lock;
775  *            (2)intent request will grant the lock to client.
776  */
777 static int mdt_getattr_name_lock(struct mdt_thread_info *info,
778                                  struct mdt_lock_handle *lhc,
779                                  __u64 child_bits,
780                                  struct ldlm_reply *ldlm_rep)
781 {
782         struct ptlrpc_request  *req       = mdt_info_req(info);
783         struct mdt_body        *reqbody   = NULL;
784         struct mdt_object      *parent    = info->mti_object;
785         struct mdt_object      *child;
786         struct md_object       *next      = mdt_object_child(parent);
787         struct lu_fid          *child_fid = &info->mti_tmp_fid1;
788         struct lu_name         *lname     = NULL;
789         const char             *name      = NULL;
790         int                     namelen   = 0;
791         struct mdt_lock_handle *lhp;
792         struct ldlm_lock       *lock;
793         struct ldlm_res_id     *res_id;
794         int                     is_resent;
795         int                     rc;
796
797         ENTRY;
798
799         is_resent = lustre_handle_is_used(&lhc->mlh_reg_lh);
800         LASSERT(ergo(is_resent,
801                      lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT));
802
803         LASSERT(parent != NULL);
804         name = req_capsule_client_get(info->mti_pill, &RMF_NAME);
805         if (name == NULL)
806                 RETURN(err_serious(-EFAULT));
807
808         namelen = req_capsule_get_size(info->mti_pill, &RMF_NAME,
809                                        RCL_CLIENT) - 1;
810         if (!info->mti_cross_ref) {
811                 /*
812                  * XXX: Check for "namelen == 0" is for getattr by fid
813                  * (OBD_CONNECT_ATTRFID), otherwise do not allow empty name,
814                  * that is the name must contain at least one character and
815                  * the terminating '\0'
816                  */
817                 if (namelen == 0) {
818                         reqbody = req_capsule_client_get(info->mti_pill,
819                                                          &RMF_MDT_BODY);
820                         LASSERT(fid_is_sane(&reqbody->fid2));
821                         name = NULL;
822
823                         CDEBUG(D_INODE, "getattr with lock for "DFID"/"DFID", "
824                                "ldlm_rep = %p\n",
825                                PFID(mdt_object_fid(parent)), PFID(&reqbody->fid2),
826                                ldlm_rep);
827                 } else {
828                         lname = mdt_name(info->mti_env, (char *)name, namelen);
829                         CDEBUG(D_INODE, "getattr with lock for "DFID"/%s, "
830                                "ldlm_rep = %p\n", PFID(mdt_object_fid(parent)),
831                                name, ldlm_rep);
832                 }
833         }
834         mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_EXECD);
835
836         rc = mdt_object_exists(parent);
837         if (unlikely(rc == 0)) {
838                 LU_OBJECT_DEBUG(D_WARNING, info->mti_env,
839                                 &parent->mot_obj.mo_lu,
840                                 "Parent doesn't exist!\n");
841                 RETURN(-ESTALE);
842         } else if (!info->mti_cross_ref) {
843                 LASSERTF(rc > 0, "Parent "DFID" is on remote server\n",
844                          PFID(mdt_object_fid(parent)));
845         }
846         if (lname) {
847                 rc = mdt_raw_lookup(info, parent, lname, ldlm_rep);
848                 if (rc != 0) {
849                         if (rc > 0)
850                                 rc = 0;
851                         RETURN(rc);
852                 }
853         }
854
855         if (info->mti_cross_ref) {
856                 /* Only getattr on the child. Parent is on another node. */
857                 mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_POS);
858                 child = parent;
859                 CDEBUG(D_INODE, "partial getattr_name child_fid = "DFID", "
860                        "ldlm_rep=%p\n", PFID(mdt_object_fid(child)), ldlm_rep);
861
862                 if (is_resent) {
863                         /* Do not take lock for resent case. */
864                         lock = ldlm_handle2lock(&lhc->mlh_reg_lh);
865                         LASSERTF(lock != NULL, "Invalid lock handle "LPX64"\n",
866                                  lhc->mlh_reg_lh.cookie);
867                         LASSERT(fid_res_name_eq(mdt_object_fid(child),
868                                                 &lock->l_resource->lr_name));
869                         LDLM_LOCK_PUT(lock);
870                         rc = 0;
871                 } else {
872                         mdt_lock_handle_init(lhc);
873                         mdt_lock_reg_init(lhc, LCK_PR);
874
875                         /*
876                          * Object's name is on another MDS, no lookup lock is
877                          * needed here but update is.
878                          */
879                         child_bits &= ~MDS_INODELOCK_LOOKUP;
880                         child_bits |= MDS_INODELOCK_UPDATE;
881
882                         rc = mdt_object_lock(info, child, lhc, child_bits,
883                                              MDT_LOCAL_LOCK);
884                 }
885                 if (rc == 0) {
886                         /* Finally, we can get attr for child. */
887                         mdt_set_capainfo(info, 0, mdt_object_fid(child),
888                                          BYPASS_CAPA);
889                         rc = mdt_getattr_internal(info, child);
890                         if (unlikely(rc != 0))
891                                 mdt_object_unlock(info, child, lhc, 1);
892                 }
893                 RETURN(rc);
894         }
895
896         /* step 1: lock parent */
897         lhp = &info->mti_lh[MDT_LH_PARENT];
898         mdt_lock_pdo_init(lhp, LCK_PR, name, namelen);
899         rc = mdt_object_lock(info, parent, lhp, MDS_INODELOCK_UPDATE,
900                              MDT_LOCAL_LOCK);
901
902         if (unlikely(rc != 0))
903                 RETURN(rc);
904
905         if (lname) {
906                 /* step 2: lookup child's fid by name */
907                 rc = mdo_lookup(info->mti_env, next, lname, child_fid,
908                                 &info->mti_spec);
909
910                 if (rc != 0) {
911                         if (rc == -ENOENT)
912                                 mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_NEG);
913                         GOTO(out_parent, rc);
914                 } else
915                         mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_POS);
916         } else {
917                 *child_fid = reqbody->fid2;
918                 mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_POS);
919         }
920
921         /*
922          *step 3: find the child object by fid & lock it.
923          *        regardless if it is local or remote.
924          */
925         child = mdt_object_find(info->mti_env, info->mti_mdt, child_fid);
926
927         if (unlikely(IS_ERR(child)))
928                 GOTO(out_parent, rc = PTR_ERR(child));
929         if (is_resent) {
930                 /* Do not take lock for resent case. */
931                 lock = ldlm_handle2lock(&lhc->mlh_reg_lh);
932                 LASSERTF(lock != NULL, "Invalid lock handle "LPX64"\n",
933                          lhc->mlh_reg_lh.cookie);
934
935                 res_id = &lock->l_resource->lr_name;
936                 if (!fid_res_name_eq(mdt_object_fid(child),
937                                     &lock->l_resource->lr_name)) {
938                          LASSERTF(fid_res_name_eq(mdt_object_fid(parent),
939                                                  &lock->l_resource->lr_name),
940                                  "Lock res_id: %lu/%lu/%lu, Fid: "DFID".\n",
941                                  (unsigned long)res_id->name[0],
942                                  (unsigned long)res_id->name[1],
943                                  (unsigned long)res_id->name[2],
944                                  PFID(mdt_object_fid(parent)));
945                           CWARN("Although resent, but still not get child lock"
946                                 "parent:"DFID" child:"DFID"\n",
947                                 PFID(mdt_object_fid(parent)),
948                                 PFID(mdt_object_fid(child)));
949                           lustre_msg_clear_flags(req->rq_reqmsg, MSG_RESENT);
950                           LDLM_LOCK_PUT(lock);
951                           GOTO(relock, 0);
952                 }
953                 LDLM_LOCK_PUT(lock);
954                 rc = 0;
955         } else {
956                 struct md_attr *ma;
957 relock:
958                 ma = &info->mti_attr;
959
960                 mdt_lock_handle_init(lhc);
961                 mdt_lock_reg_init(lhc, LCK_PR);
962
963                 if (mdt_object_exists(child) == 0) {
964                         LU_OBJECT_DEBUG(D_WARNING, info->mti_env,
965                                         &child->mot_obj.mo_lu,
966                                         "Object doesn't exist!\n");
967                         GOTO(out_child, rc = -ESTALE);
968                 }
969
970                 ma->ma_valid = 0;
971                 ma->ma_need = MA_INODE;
972                 rc = mo_attr_get(info->mti_env, next, ma);
973                 if (unlikely(rc != 0))
974                         GOTO(out_child, rc);
975
976                 /* If the file has not been changed for some time, we return
977                  * not only a LOOKUP lock, but also an UPDATE lock and this
978                  * might save us RPC on later STAT. For directories, it also
979                  * let negative dentry starts working for this dir. */
980                 if (ma->ma_valid & MA_INODE &&
981                     ma->ma_attr.la_valid & LA_CTIME &&
982                     info->mti_mdt->mdt_namespace->ns_ctime_age_limit +
983                     ma->ma_attr.la_ctime < cfs_time_current_sec())
984                         child_bits |= MDS_INODELOCK_UPDATE;
985
986                 rc = mdt_object_lock(info, child, lhc, child_bits,
987                                      MDT_CROSS_LOCK);
988
989                 if (unlikely(rc != 0))
990                         GOTO(out_child, rc);
991         }
992
993         /* finally, we can get attr for child. */
994         mdt_set_capainfo(info, 1, child_fid, BYPASS_CAPA);
995         rc = mdt_getattr_internal(info, child);
996         if (unlikely(rc != 0)) {
997                 mdt_object_unlock(info, child, lhc, 1);
998         } else {
999                 lock = ldlm_handle2lock(&lhc->mlh_reg_lh);
1000                 if (lock) {
1001                         struct mdt_body *repbody;
1002
1003                         /* Debugging code. */
1004                         res_id = &lock->l_resource->lr_name;
1005                         LDLM_DEBUG(lock, "Returning lock to client\n");
1006                         LASSERTF(fid_res_name_eq(mdt_object_fid(child),
1007                                                  &lock->l_resource->lr_name),
1008                                  "Lock res_id: %lu/%lu/%lu, Fid: "DFID".\n",
1009                                  (unsigned long)res_id->name[0],
1010                                  (unsigned long)res_id->name[1],
1011                                  (unsigned long)res_id->name[2],
1012                                  PFID(mdt_object_fid(child)));
1013                         /*
1014                          * Pack Size-on-MDS inode attributes to the body if
1015                          * update lock is given.
1016                          */
1017                         repbody = req_capsule_server_get(info->mti_pill,
1018                                                          &RMF_MDT_BODY);
1019                         if (lock->l_policy_data.l_inodebits.bits &
1020                             MDS_INODELOCK_UPDATE)
1021                                 mdt_pack_size2body(info, child);
1022                         LDLM_LOCK_PUT(lock);
1023                 }
1024         }
1025         EXIT;
1026 out_child:
1027         mdt_object_put(info->mti_env, child);
1028 out_parent:
1029         mdt_object_unlock(info, parent, lhp, 1);
1030         return rc;
1031 }
1032
1033 /* normal handler: should release the child lock */
1034 static int mdt_getattr_name(struct mdt_thread_info *info)
1035 {
1036         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_CHILD];
1037         struct mdt_body        *reqbody;
1038         struct mdt_body        *repbody;
1039         int rc;
1040         ENTRY;
1041
1042         reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
1043         LASSERT(reqbody != NULL);
1044         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
1045         LASSERT(repbody != NULL);
1046
1047         info->mti_spec.sp_ck_split = !!(reqbody->valid & OBD_MD_FLCKSPLIT);
1048         info->mti_cross_ref = !!(reqbody->valid & OBD_MD_FLCROSSREF);
1049         repbody->eadatasize = 0;
1050         repbody->aclsize = 0;
1051
1052         rc = mdt_init_ucred(info, reqbody);
1053         if (unlikely(rc))
1054                 GOTO(out_shrink, rc);
1055
1056         rc = mdt_getattr_name_lock(info, lhc, MDS_INODELOCK_UPDATE, NULL);
1057         if (lustre_handle_is_used(&lhc->mlh_reg_lh)) {
1058                 ldlm_lock_decref(&lhc->mlh_reg_lh, lhc->mlh_reg_mode);
1059                 lhc->mlh_reg_lh.cookie = 0;
1060         }
1061         mdt_exit_ucred(info);
1062         EXIT;
1063 out_shrink:
1064         mdt_shrink_reply(info);
1065         return rc;
1066 }
1067
1068 static const struct lu_device_operations mdt_lu_ops;
1069
1070 static int lu_device_is_mdt(struct lu_device *d)
1071 {
1072         return ergo(d != NULL && d->ld_ops != NULL, d->ld_ops == &mdt_lu_ops);
1073 }
1074
1075 static int mdt_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
1076                          void *karg, void *uarg);
1077
1078 static int mdt_set_info(struct mdt_thread_info *info)
1079 {
1080         struct ptlrpc_request *req = mdt_info_req(info);
1081         char *key;
1082         void *val;
1083         int keylen, vallen, rc = 0;
1084         ENTRY;
1085
1086         rc = req_capsule_server_pack(info->mti_pill);
1087         if (rc)
1088                 RETURN(rc);
1089
1090         key = req_capsule_client_get(info->mti_pill, &RMF_SETINFO_KEY);
1091         if (key == NULL) {
1092                 DEBUG_REQ(D_HA, req, "no set_info key");
1093                 RETURN(-EFAULT);
1094         }
1095
1096         keylen = req_capsule_get_size(info->mti_pill, &RMF_SETINFO_KEY,
1097                                       RCL_CLIENT);
1098
1099         val = req_capsule_client_get(info->mti_pill, &RMF_SETINFO_VAL);
1100         if (val == NULL) {
1101                 DEBUG_REQ(D_HA, req, "no set_info val");
1102                 RETURN(-EFAULT);
1103         }
1104
1105         vallen = req_capsule_get_size(info->mti_pill, &RMF_SETINFO_VAL,
1106                                       RCL_CLIENT);
1107
1108         /* Swab any part of val you need to here */
1109         if (KEY_IS(KEY_READ_ONLY)) {
1110                 req->rq_status = 0;
1111                 lustre_msg_set_status(req->rq_repmsg, 0);
1112
1113                 spin_lock(&req->rq_export->exp_lock);
1114                 if (*(__u32 *)val)
1115                         req->rq_export->exp_connect_flags |= OBD_CONNECT_RDONLY;
1116                 else
1117                         req->rq_export->exp_connect_flags &=~OBD_CONNECT_RDONLY;
1118                 spin_unlock(&req->rq_export->exp_lock);
1119
1120         } else if (KEY_IS(KEY_CHANGELOG_CLEAR)) {
1121                 struct changelog_setinfo *cs =
1122                         (struct changelog_setinfo *)val;
1123                 if (vallen != sizeof(*cs)) {
1124                         CERROR("Bad changelog_clear setinfo size %d\n", vallen);
1125                         RETURN(-EINVAL);
1126                 }
1127                 if (lustre_msg_swabbed(req->rq_reqmsg)) {
1128                         __swab64s(&cs->cs_recno);
1129                         __swab32s(&cs->cs_id);
1130                 }
1131
1132                 rc = mdt_iocontrol(OBD_IOC_CHANGELOG_CLEAR, info->mti_exp,
1133                                    vallen, val, NULL);
1134                 lustre_msg_set_status(req->rq_repmsg, rc);
1135
1136         } else {
1137                 RETURN(-EINVAL);
1138         }
1139         RETURN(0);
1140 }
1141
1142 static int mdt_connect(struct mdt_thread_info *info)
1143 {
1144         int rc;
1145         struct ptlrpc_request *req;
1146
1147         req = mdt_info_req(info);
1148         rc = target_handle_connect(req);
1149         if (rc == 0) {
1150                 LASSERT(req->rq_export != NULL);
1151                 info->mti_mdt = mdt_dev(req->rq_export->exp_obd->obd_lu_dev);
1152                 rc = mdt_init_sec_level(info);
1153                 if (rc == 0)
1154                         rc = mdt_init_idmap(info);
1155                 if (rc != 0)
1156                         obd_disconnect(class_export_get(req->rq_export));
1157         } else {
1158                 rc = err_serious(rc);
1159         }
1160         return rc;
1161 }
1162
1163 static int mdt_disconnect(struct mdt_thread_info *info)
1164 {
1165         int rc;
1166         ENTRY;
1167
1168         rc = target_handle_disconnect(mdt_info_req(info));
1169         if (rc)
1170                 rc = err_serious(rc);
1171         RETURN(rc);
1172 }
1173
1174 static int mdt_sendpage(struct mdt_thread_info *info,
1175                         struct lu_rdpg *rdpg)
1176 {
1177         struct ptlrpc_request   *req = mdt_info_req(info);
1178         struct ptlrpc_bulk_desc *desc;
1179         struct l_wait_info      *lwi = &info->mti_u.rdpg.mti_wait_info;
1180         int                      tmpcount;
1181         int                      tmpsize;
1182         int                      timeout;
1183         int                      i;
1184         int                      rc;
1185         ENTRY;
1186
1187         desc = ptlrpc_prep_bulk_exp(req, rdpg->rp_npages, BULK_PUT_SOURCE,
1188                                     MDS_BULK_PORTAL);
1189         if (desc == NULL)
1190                 RETURN(-ENOMEM);
1191
1192         for (i = 0, tmpcount = rdpg->rp_count;
1193                 i < rdpg->rp_npages; i++, tmpcount -= tmpsize) {
1194                 tmpsize = min_t(int, tmpcount, CFS_PAGE_SIZE);
1195                 ptlrpc_prep_bulk_page(desc, rdpg->rp_pages[i], 0, tmpsize);
1196         }
1197
1198         LASSERT(desc->bd_nob == rdpg->rp_count);
1199         rc = sptlrpc_svc_wrap_bulk(req, desc);
1200         if (rc)
1201                 GOTO(free_desc, rc);
1202
1203         rc = ptlrpc_start_bulk_transfer(desc);
1204         if (rc)
1205                 GOTO(free_desc, rc);
1206
1207         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_SENDPAGE))
1208                 GOTO(abort_bulk, rc = 0);
1209
1210         timeout = (int) req->rq_deadline - cfs_time_current_sec();
1211         if (timeout < 0)
1212                 CERROR("Req deadline already passed %lu (now: %lu)\n",
1213                        req->rq_deadline, cfs_time_current_sec());
1214         *lwi = LWI_TIMEOUT(cfs_time_seconds(max(timeout, 1)), NULL, NULL);
1215         rc = l_wait_event(desc->bd_waitq, !ptlrpc_server_bulk_active(desc), lwi);
1216         LASSERT (rc == 0 || rc == -ETIMEDOUT);
1217
1218         if (rc == 0) {
1219                 if (desc->bd_success &&
1220                     desc->bd_nob_transferred == rdpg->rp_count)
1221                         GOTO(free_desc, rc);
1222
1223                 rc = -ETIMEDOUT; /* XXX should this be a different errno? */
1224         }
1225
1226         DEBUG_REQ(D_ERROR, req, "bulk failed: %s %d(%d), evicting %s@%s",
1227                   (rc == -ETIMEDOUT) ? "timeout" : "network error",
1228                   desc->bd_nob_transferred, rdpg->rp_count,
1229                   req->rq_export->exp_client_uuid.uuid,
1230                   req->rq_export->exp_connection->c_remote_uuid.uuid);
1231
1232         class_fail_export(req->rq_export);
1233
1234         EXIT;
1235 abort_bulk:
1236         ptlrpc_abort_bulk(desc);
1237 free_desc:
1238         ptlrpc_free_bulk(desc);
1239         return rc;
1240 }
1241
1242 #ifdef HAVE_SPLIT_SUPPORT
1243 /*
1244  * Retrieve dir entry from the page and insert it to the slave object, actually,
1245  * this should be in osd layer, but since it will not in the final product, so
1246  * just do it here and do not define more moo api anymore for this.
1247  */
1248 static int mdt_write_dir_page(struct mdt_thread_info *info, struct page *page,
1249                               int size)
1250 {
1251         struct mdt_object *object = info->mti_object;
1252         struct lu_fid *lf = &info->mti_tmp_fid2;
1253         struct md_attr *ma = &info->mti_attr;
1254         struct lu_dirpage *dp;
1255         struct lu_dirent *ent;
1256         int rc = 0, offset = 0;
1257         ENTRY;
1258
1259         /* Make sure we have at least one entry. */
1260         if (size == 0)
1261                 RETURN(-EINVAL);
1262
1263         /*
1264          * Disable trans for this name insert, since it will include many trans
1265          * for this.
1266          */
1267         info->mti_no_need_trans = 1;
1268         /*
1269          * When write_dir_page, no need update parent's ctime,
1270          * and no permission check for name_insert.
1271          */
1272         ma->ma_attr.la_ctime = 0;
1273         ma->ma_attr.la_valid = LA_MODE;
1274         ma->ma_valid = MA_INODE;
1275
1276         cfs_kmap(page);
1277         dp = page_address(page);
1278         offset = (int)((__u32)lu_dirent_start(dp) - (__u32)dp);
1279
1280         for (ent = lu_dirent_start(dp); ent != NULL;
1281              ent = lu_dirent_next(ent)) {
1282                 struct lu_name *lname;
1283                 char *name;
1284
1285                 if (le16_to_cpu(ent->lde_namelen) == 0)
1286                         continue;
1287
1288                 fid_le_to_cpu(lf, &ent->lde_fid);
1289                 if (le64_to_cpu(ent->lde_hash) & MAX_HASH_HIGHEST_BIT)
1290                         ma->ma_attr.la_mode = S_IFDIR;
1291                 else
1292                         ma->ma_attr.la_mode = 0;
1293                 OBD_ALLOC(name, le16_to_cpu(ent->lde_namelen) + 1);
1294                 if (name == NULL)
1295                         GOTO(out, rc = -ENOMEM);
1296
1297                 memcpy(name, ent->lde_name, le16_to_cpu(ent->lde_namelen));
1298                 lname = mdt_name(info->mti_env, name,
1299                                  le16_to_cpu(ent->lde_namelen));
1300                 ma->ma_attr_flags |= (MDS_PERM_BYPASS | MDS_QUOTA_IGNORE);
1301                 rc = mdo_name_insert(info->mti_env,
1302                                      md_object_next(&object->mot_obj),
1303                                      lname, lf, ma);
1304                 OBD_FREE(name, le16_to_cpu(ent->lde_namelen) + 1);
1305                 if (rc) {
1306                         CERROR("Can't insert %*.*s, rc %d\n",
1307                                le16_to_cpu(ent->lde_namelen),
1308                                le16_to_cpu(ent->lde_namelen),
1309                                ent->lde_name, rc);
1310                         GOTO(out, rc);
1311                 }
1312
1313                 offset += lu_dirent_size(ent);
1314                 if (offset >= size)
1315                         break;
1316         }
1317         EXIT;
1318 out:
1319         cfs_kunmap(page);
1320         return rc;
1321 }
1322
1323 static int mdt_bulk_timeout(void *data)
1324 {
1325         ENTRY;
1326
1327         CERROR("mdt bulk transfer timeout \n");
1328
1329         RETURN(1);
1330 }
1331
1332 static int mdt_writepage(struct mdt_thread_info *info)
1333 {
1334         struct ptlrpc_request   *req = mdt_info_req(info);
1335         struct mdt_body         *reqbody;
1336         struct l_wait_info      *lwi;
1337         struct ptlrpc_bulk_desc *desc;
1338         struct page             *page;
1339         int                rc;
1340         ENTRY;
1341
1342
1343         reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
1344         if (reqbody == NULL)
1345                 RETURN(err_serious(-EFAULT));
1346
1347         desc = ptlrpc_prep_bulk_exp(req, 1, BULK_GET_SINK, MDS_BULK_PORTAL);
1348         if (desc == NULL)
1349                 RETURN(err_serious(-ENOMEM));
1350
1351         /* allocate the page for the desc */
1352         page = cfs_alloc_page(CFS_ALLOC_STD);
1353         if (page == NULL)
1354                 GOTO(desc_cleanup, rc = -ENOMEM);
1355
1356         CDEBUG(D_INFO, "Received page offset %d size %d \n",
1357                (int)reqbody->size, (int)reqbody->nlink);
1358
1359         ptlrpc_prep_bulk_page(desc, page, (int)reqbody->size,
1360                               (int)reqbody->nlink);
1361
1362         rc = sptlrpc_svc_prep_bulk(req, desc);
1363         if (rc != 0)
1364                 GOTO(cleanup_page, rc);
1365         /*
1366          * Check if client was evicted while we were doing i/o before touching
1367          * network.
1368          */
1369         OBD_ALLOC_PTR(lwi);
1370         if (!lwi)
1371                 GOTO(cleanup_page, rc = -ENOMEM);
1372
1373         if (desc->bd_export->exp_failed)
1374                 rc = -ENOTCONN;
1375         else
1376                 rc = ptlrpc_start_bulk_transfer (desc);
1377         if (rc == 0) {
1378                 *lwi = LWI_TIMEOUT_INTERVAL(obd_timeout * HZ / 4, HZ,
1379                                             mdt_bulk_timeout, desc);
1380                 rc = l_wait_event(desc->bd_waitq, !ptlrpc_bulk_active(desc) ||
1381                                   desc->bd_export->exp_failed, lwi);
1382                 LASSERT(rc == 0 || rc == -ETIMEDOUT);
1383                 if (rc == -ETIMEDOUT) {
1384                         DEBUG_REQ(D_ERROR, req, "timeout on bulk GET");
1385                         ptlrpc_abort_bulk(desc);
1386                 } else if (desc->bd_export->exp_failed) {
1387                         DEBUG_REQ(D_ERROR, req, "Eviction on bulk GET");
1388                         rc = -ENOTCONN;
1389                         ptlrpc_abort_bulk(desc);
1390                 } else if (!desc->bd_success ||
1391                            desc->bd_nob_transferred != desc->bd_nob) {
1392                         DEBUG_REQ(D_ERROR, req, "%s bulk GET %d(%d)",
1393                                   desc->bd_success ?
1394                                   "truncated" : "network error on",
1395                                   desc->bd_nob_transferred, desc->bd_nob);
1396                         /* XXX should this be a different errno? */
1397                         rc = -ETIMEDOUT;
1398                 }
1399         } else {
1400                 DEBUG_REQ(D_ERROR, req, "ptlrpc_bulk_get failed: rc %d", rc);
1401         }
1402         if (rc)
1403                 GOTO(cleanup_lwi, rc);
1404         rc = mdt_write_dir_page(info, page, reqbody->nlink);
1405
1406 cleanup_lwi:
1407         OBD_FREE_PTR(lwi);
1408 cleanup_page:
1409         cfs_free_page(page);
1410 desc_cleanup:
1411         ptlrpc_free_bulk(desc);
1412         RETURN(rc);
1413 }
1414 #endif
1415
1416 static int mdt_readpage(struct mdt_thread_info *info)
1417 {
1418         struct mdt_object *object = info->mti_object;
1419         struct lu_rdpg    *rdpg = &info->mti_u.rdpg.mti_rdpg;
1420         struct mdt_body   *reqbody;
1421         struct mdt_body   *repbody;
1422         int                rc;
1423         int                i;
1424         ENTRY;
1425
1426         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_READPAGE_PACK))
1427                 RETURN(err_serious(-ENOMEM));
1428
1429         reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
1430         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
1431         if (reqbody == NULL || repbody == NULL)
1432                 RETURN(err_serious(-EFAULT));
1433
1434         /*
1435          * prepare @rdpg before calling lower layers and transfer itself. Here
1436          * reqbody->size contains offset of where to start to read and
1437          * reqbody->nlink contains number bytes to read.
1438          */
1439         rdpg->rp_hash = reqbody->size;
1440         if (rdpg->rp_hash != reqbody->size) {
1441                 CERROR("Invalid hash: "LPX64" != "LPX64"\n",
1442                        rdpg->rp_hash, reqbody->size);
1443                 RETURN(-EFAULT);
1444         }
1445
1446         rdpg->rp_attrs = reqbody->mode;
1447         rdpg->rp_count  = reqbody->nlink;
1448         rdpg->rp_npages = (rdpg->rp_count + CFS_PAGE_SIZE - 1)>>CFS_PAGE_SHIFT;
1449         OBD_ALLOC(rdpg->rp_pages, rdpg->rp_npages * sizeof rdpg->rp_pages[0]);
1450         if (rdpg->rp_pages == NULL)
1451                 RETURN(-ENOMEM);
1452
1453         for (i = 0; i < rdpg->rp_npages; ++i) {
1454                 rdpg->rp_pages[i] = cfs_alloc_page(CFS_ALLOC_STD);
1455                 if (rdpg->rp_pages[i] == NULL)
1456                         GOTO(free_rdpg, rc = -ENOMEM);
1457         }
1458
1459         /* call lower layers to fill allocated pages with directory data */
1460         rc = mo_readpage(info->mti_env, mdt_object_child(object), rdpg);
1461         if (rc)
1462                 GOTO(free_rdpg, rc);
1463
1464         /* send pages to client */
1465         rc = mdt_sendpage(info, rdpg);
1466
1467         EXIT;
1468 free_rdpg:
1469
1470         for (i = 0; i < rdpg->rp_npages; i++)
1471                 if (rdpg->rp_pages[i] != NULL)
1472                         cfs_free_page(rdpg->rp_pages[i]);
1473         OBD_FREE(rdpg->rp_pages, rdpg->rp_npages * sizeof rdpg->rp_pages[0]);
1474
1475         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_SENDPAGE))
1476                 RETURN(0);
1477
1478         return rc;
1479 }
1480
1481 static int mdt_reint_internal(struct mdt_thread_info *info,
1482                               struct mdt_lock_handle *lhc,
1483                               __u32 op)
1484 {
1485         struct req_capsule      *pill = info->mti_pill;
1486         struct mdt_device       *mdt = info->mti_mdt;
1487         struct mdt_body         *repbody;
1488         int                      rc = 0;
1489         ENTRY;
1490
1491         /* pack reply */
1492         if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
1493                 req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER,
1494                                      mdt->mdt_max_mdsize);
1495         if (req_capsule_has_field(pill, &RMF_LOGCOOKIES, RCL_SERVER))
1496                 req_capsule_set_size(pill, &RMF_LOGCOOKIES, RCL_SERVER,
1497                                      mdt->mdt_max_cookiesize);
1498
1499         rc = req_capsule_server_pack(pill);
1500         if (rc != 0) {
1501                 CERROR("Can't pack response, rc %d\n", rc);
1502                 RETURN(err_serious(rc));
1503         }
1504
1505         if (req_capsule_has_field(pill, &RMF_MDT_BODY, RCL_SERVER)) {
1506                 repbody = req_capsule_server_get(pill, &RMF_MDT_BODY);
1507                 LASSERT(repbody);
1508                 repbody->eadatasize = 0;
1509                 repbody->aclsize = 0;
1510         }
1511
1512         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_REINT_UNPACK))
1513                 GOTO(out_shrink, rc = err_serious(-EFAULT));
1514
1515         rc = mdt_reint_unpack(info, op);
1516         if (rc != 0) {
1517                 CERROR("Can't unpack reint, rc %d\n", rc);
1518                 GOTO(out_shrink, rc = err_serious(rc));
1519         }
1520
1521         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_REINT_DELAY, 10);
1522
1523         /* for replay no cookkie / lmm need, because client have this already */
1524         if (info->mti_spec.no_create == 1)  {
1525                 if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
1526                         req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER, 0);
1527
1528                 if (req_capsule_has_field(pill, &RMF_LOGCOOKIES, RCL_SERVER))
1529                         req_capsule_set_size(pill, &RMF_LOGCOOKIES, RCL_SERVER,
1530                                              0);
1531         }
1532
1533         rc = mdt_init_ucred_reint(info);
1534         if (rc)
1535                 GOTO(out_shrink, rc);
1536
1537         rc = mdt_fix_attr_ucred(info, op);
1538         if (rc != 0)
1539                 GOTO(out_ucred, rc = err_serious(rc));
1540
1541         if (mdt_check_resent(info, mdt_reconstruct, lhc)) {
1542                 rc = lustre_msg_get_status(mdt_info_req(info)->rq_repmsg);
1543                 GOTO(out_ucred, rc);
1544         }
1545         rc = mdt_reint_rec(info, lhc);
1546         EXIT;
1547 out_ucred:
1548         mdt_exit_ucred(info);
1549 out_shrink:
1550         mdt_shrink_reply(info);
1551         return rc;
1552 }
1553
1554 static long mdt_reint_opcode(struct mdt_thread_info *info,
1555                              const struct req_format **fmt)
1556 {
1557         struct mdt_rec_reint *rec;
1558         long opc;
1559
1560         opc = err_serious(-EFAULT);
1561         rec = req_capsule_client_get(info->mti_pill, &RMF_REC_REINT);
1562         if (rec != NULL) {
1563                 opc = rec->rr_opcode;
1564                 DEBUG_REQ(D_INODE, mdt_info_req(info), "reint opt = %ld", opc);
1565                 if (opc < REINT_MAX && fmt[opc] != NULL)
1566                         req_capsule_extend(info->mti_pill, fmt[opc]);
1567                 else {
1568                         CERROR("Unsupported opc: %ld\n", opc);
1569                         opc = err_serious(opc);
1570                 }
1571         }
1572         return opc;
1573 }
1574
1575 static int mdt_reint(struct mdt_thread_info *info)
1576 {
1577         long opc;
1578         int  rc;
1579
1580         static const struct req_format *reint_fmts[REINT_MAX] = {
1581                 [REINT_SETATTR]  = &RQF_MDS_REINT_SETATTR,
1582                 [REINT_CREATE]   = &RQF_MDS_REINT_CREATE,
1583                 [REINT_LINK]     = &RQF_MDS_REINT_LINK,
1584                 [REINT_UNLINK]   = &RQF_MDS_REINT_UNLINK,
1585                 [REINT_RENAME]   = &RQF_MDS_REINT_RENAME,
1586                 [REINT_OPEN]     = &RQF_MDS_REINT_OPEN,
1587                 [REINT_SETXATTR] = &RQF_MDS_REINT_SETXATTR
1588         };
1589
1590         ENTRY;
1591
1592         opc = mdt_reint_opcode(info, reint_fmts);
1593         if (opc >= 0) {
1594                 /*
1595                  * No lock possible here from client to pass it to reint code
1596                  * path.
1597                  */
1598                 rc = mdt_reint_internal(info, NULL, opc);
1599         } else {
1600                 rc = opc;
1601         }
1602
1603         info->mti_fail_id = OBD_FAIL_MDS_REINT_NET_REP;
1604         RETURN(rc);
1605 }
1606
1607 /* this should sync the whole device */
1608 static int mdt_device_sync(const struct lu_env *env, struct mdt_device *mdt)
1609 {
1610         struct dt_device *dt = mdt->mdt_bottom;
1611         int rc;
1612         ENTRY;
1613
1614         rc = dt->dd_ops->dt_sync(env, dt);
1615         RETURN(rc);
1616 }
1617
1618 /* this should sync this object */
1619 static int mdt_object_sync(struct mdt_thread_info *info)
1620 {
1621         struct md_object *next;
1622         int rc;
1623         ENTRY;
1624
1625         if (!mdt_object_exists(info->mti_object)) {
1626                 CWARN("Non existing object  "DFID"!\n",
1627                       PFID(mdt_object_fid(info->mti_object)));
1628                 RETURN(-ESTALE);
1629         }
1630         next = mdt_object_child(info->mti_object);
1631         rc = mo_object_sync(info->mti_env, next);
1632
1633         RETURN(rc);
1634 }
1635
1636 static int mdt_sync(struct mdt_thread_info *info)
1637 {
1638         struct req_capsule *pill = info->mti_pill;
1639         struct mdt_body *body;
1640         int rc;
1641         ENTRY;
1642
1643         /* The fid may be zero, so we req_capsule_set manually */
1644         req_capsule_set(pill, &RQF_MDS_SYNC);
1645
1646         body = req_capsule_client_get(pill, &RMF_MDT_BODY);
1647         if (body == NULL)
1648                 RETURN(err_serious(-EINVAL));
1649
1650         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_SYNC_PACK))
1651                 RETURN(err_serious(-ENOMEM));
1652
1653         if (fid_seq(&body->fid1) == 0) {
1654                 /* sync the whole device */
1655                 rc = req_capsule_server_pack(pill);
1656                 if (rc == 0)
1657                         rc = mdt_device_sync(info->mti_env, info->mti_mdt);
1658                 else
1659                         rc = err_serious(rc);
1660         } else {
1661                 /* sync an object */
1662                 rc = mdt_unpack_req_pack_rep(info, HABEO_CORPUS|HABEO_REFERO);
1663                 if (rc == 0) {
1664                         rc = mdt_object_sync(info);
1665                         if (rc == 0) {
1666                                 struct md_object *next;
1667                                 const struct lu_fid *fid;
1668                                 struct lu_attr *la = &info->mti_attr.ma_attr;
1669
1670                                 next = mdt_object_child(info->mti_object);
1671                                 info->mti_attr.ma_need = MA_INODE;
1672                                 info->mti_attr.ma_valid = 0;
1673                                 rc = mo_attr_get(info->mti_env, next,
1674                                                  &info->mti_attr);
1675                                 if (rc == 0) {
1676                                         body = req_capsule_server_get(pill,
1677                                                                 &RMF_MDT_BODY);
1678                                         fid = mdt_object_fid(info->mti_object);
1679                                         mdt_pack_attr2body(info, body, la, fid);
1680                                 }
1681                         }
1682                 } else
1683                         rc = err_serious(rc);
1684         }
1685         RETURN(rc);
1686 }
1687
1688 #ifdef HAVE_QUOTA_SUPPORT
1689 static int mdt_quotacheck_handle(struct mdt_thread_info *info)
1690 {
1691         struct obd_quotactl *oqctl;
1692         struct req_capsule *pill = info->mti_pill;
1693         struct obd_export *exp = info->mti_exp;
1694         struct md_device *next = info->mti_mdt->mdt_child;
1695         int rc;
1696         ENTRY;
1697
1698         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_QUOTACHECK_NET))
1699                 RETURN(0);
1700
1701         oqctl = req_capsule_client_get(pill, &RMF_OBD_QUOTACTL);
1702         if (oqctl == NULL)
1703                 RETURN(-EPROTO);
1704
1705         /* remote client has no permission for quotacheck */
1706         if (unlikely(exp_connect_rmtclient(exp)))
1707                 RETURN(-EPERM);
1708
1709         rc = req_capsule_server_pack(pill);
1710         if (rc)
1711                 RETURN(rc);
1712
1713         rc = next->md_ops->mdo_quota.mqo_check(info->mti_env, next, exp,
1714                                                oqctl->qc_type);
1715         RETURN(rc);
1716 }
1717
1718 static int mdt_quotactl_handle(struct mdt_thread_info *info)
1719 {
1720         struct obd_quotactl *oqctl, *repoqc;
1721         struct req_capsule *pill = info->mti_pill;
1722         struct obd_export *exp = info->mti_exp;
1723         struct md_device *next = info->mti_mdt->mdt_child;
1724         const struct md_quota_operations *mqo = &next->md_ops->mdo_quota;
1725         int id, rc;
1726         ENTRY;
1727
1728         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_QUOTACTL_NET))
1729                 RETURN(0);
1730
1731         oqctl = req_capsule_client_get(pill, &RMF_OBD_QUOTACTL);
1732         if (oqctl == NULL)
1733                 RETURN(-EPROTO);
1734
1735         id = oqctl->qc_id;
1736         if (exp_connect_rmtclient(exp)) {
1737                 struct ptlrpc_request *req = mdt_info_req(info);
1738                 struct mdt_export_data *med = mdt_req2med(req);
1739                 struct lustre_idmap_table *idmap = med->med_idmap;
1740
1741                 if (unlikely(oqctl->qc_cmd != Q_GETQUOTA &&
1742                              oqctl->qc_cmd != Q_GETINFO))
1743                         RETURN(-EPERM);
1744
1745
1746                 if (oqctl->qc_type == USRQUOTA)
1747                         id = lustre_idmap_lookup_uid(NULL, idmap, 0,
1748                                                      oqctl->qc_id);
1749                 else if (oqctl->qc_type == GRPQUOTA)
1750                         id = lustre_idmap_lookup_gid(NULL, idmap, 0,
1751                                                      oqctl->qc_id);
1752                 else
1753                         RETURN(-EINVAL);
1754
1755                 if (id == CFS_IDMAP_NOTFOUND) {
1756                         CDEBUG(D_QUOTA, "no mapping for id %u\n",
1757                                oqctl->qc_id);
1758                         RETURN(-EACCES);
1759                 }
1760         }
1761
1762         rc = req_capsule_server_pack(pill);
1763         if (rc)
1764                 RETURN(rc);
1765
1766         repoqc = req_capsule_server_get(pill, &RMF_OBD_QUOTACTL);
1767         LASSERT(repoqc != NULL);
1768
1769         switch (oqctl->qc_cmd) {
1770         case Q_QUOTAON:
1771                 rc = mqo->mqo_on(info->mti_env, next, oqctl->qc_type);
1772                 break;
1773         case Q_QUOTAOFF:
1774                 rc = mqo->mqo_off(info->mti_env, next, oqctl->qc_type);
1775                 break;
1776         case Q_SETINFO:
1777                 rc = mqo->mqo_setinfo(info->mti_env, next, oqctl->qc_type, id,
1778                                       &oqctl->qc_dqinfo);
1779                 break;
1780         case Q_GETINFO:
1781                 rc = mqo->mqo_getinfo(info->mti_env, next, oqctl->qc_type, id,
1782                                       &oqctl->qc_dqinfo);
1783                 break;
1784         case Q_SETQUOTA:
1785                 rc = mqo->mqo_setquota(info->mti_env, next, oqctl->qc_type, id,
1786                                        &oqctl->qc_dqblk);
1787                 break;
1788         case Q_GETQUOTA:
1789                 rc = mqo->mqo_getquota(info->mti_env, next, oqctl->qc_type, id,
1790                                        &oqctl->qc_dqblk);
1791                 break;
1792         case Q_GETOINFO:
1793                 rc = mqo->mqo_getoinfo(info->mti_env, next, oqctl->qc_type, id,
1794                                        &oqctl->qc_dqinfo);
1795                 break;
1796         case Q_GETOQUOTA:
1797                 rc = mqo->mqo_getoquota(info->mti_env, next, oqctl->qc_type, id,
1798                                         &oqctl->qc_dqblk);
1799                 break;
1800         case LUSTRE_Q_INVALIDATE:
1801                 rc = mqo->mqo_invalidate(info->mti_env, next, oqctl->qc_type);
1802                 break;
1803         case LUSTRE_Q_FINVALIDATE:
1804                 rc = mqo->mqo_finvalidate(info->mti_env, next, oqctl->qc_type);
1805                 break;
1806         default:
1807                 CERROR("unsupported mdt_quotactl command: %d\n",
1808                        oqctl->qc_cmd);
1809                 RETURN(-EFAULT);
1810         }
1811
1812         *repoqc = *oqctl;
1813         RETURN(rc);
1814 }
1815 #endif
1816
1817
1818 /*
1819  * OBD PING and other handlers.
1820  */
1821 static int mdt_obd_ping(struct mdt_thread_info *info)
1822 {
1823         int rc;
1824         ENTRY;
1825
1826         req_capsule_set(info->mti_pill, &RQF_OBD_PING);
1827
1828         rc = target_handle_ping(mdt_info_req(info));
1829         if (rc < 0)
1830                 rc = err_serious(rc);
1831         RETURN(rc);
1832 }
1833
1834 static int mdt_obd_log_cancel(struct mdt_thread_info *info)
1835 {
1836         return err_serious(-EOPNOTSUPP);
1837 }
1838
1839 static int mdt_obd_qc_callback(struct mdt_thread_info *info)
1840 {
1841         return err_serious(-EOPNOTSUPP);
1842 }
1843
1844
1845 /*
1846  * LLOG handlers.
1847  */
1848
1849 /** clone llog ctxt from child (mdd)
1850  * This allows remote llog (replicator) access.
1851  * We can either pass all llog RPCs (eg mdt_llog_create) on to child where the
1852  * context was originally set up, or we can handle them directly.
1853  * I choose the latter, but that means I need any llog
1854  * contexts set up by child to be accessable by the mdt.  So we clone the
1855  * context into our context list here.
1856  */
1857 static int mdt_llog_ctxt_clone(const struct lu_env *env, struct mdt_device *mdt,
1858                                int idx)
1859 {
1860         struct md_device  *next = mdt->mdt_child;
1861         struct llog_ctxt *ctxt;
1862         int rc;
1863
1864         if (!llog_ctxt_null(mdt2obd_dev(mdt), idx))
1865                 return 0;
1866
1867         rc = next->md_ops->mdo_llog_ctxt_get(env, next, idx, (void **)&ctxt);
1868         if (rc || ctxt == NULL) {
1869                 CERROR("Can't get mdd ctxt %d\n", rc);
1870                 return rc;
1871         }
1872
1873         rc = llog_group_set_ctxt(&mdt2obd_dev(mdt)->obd_olg, ctxt, idx);
1874         if (rc)
1875                 CERROR("Can't set mdt ctxt %d\n", rc);
1876
1877         return rc;
1878 }
1879
1880 static int mdt_llog_ctxt_unclone(const struct lu_env *env,
1881                                  struct mdt_device *mdt, int idx)
1882 {
1883         struct llog_ctxt *ctxt;
1884
1885         ctxt = llog_get_context(mdt2obd_dev(mdt), idx);
1886         if (ctxt == NULL)
1887                 return 0;
1888         /* Put once for the get we just did, and once for the clone */
1889         llog_ctxt_put(ctxt);
1890         llog_ctxt_put(ctxt);
1891         return 0;
1892 }
1893
1894 static int mdt_llog_create(struct mdt_thread_info *info)
1895 {
1896         int rc;
1897
1898         req_capsule_set(info->mti_pill, &RQF_LLOG_ORIGIN_HANDLE_CREATE);
1899         rc = llog_origin_handle_create(mdt_info_req(info));
1900         return (rc < 0 ? err_serious(rc) : rc);
1901 }
1902
1903 static int mdt_llog_destroy(struct mdt_thread_info *info)
1904 {
1905         int rc;
1906
1907         req_capsule_set(info->mti_pill, &RQF_LLOG_ORIGIN_HANDLE_DESTROY);
1908         rc = llog_origin_handle_destroy(mdt_info_req(info));
1909         return (rc < 0 ? err_serious(rc) : rc);
1910 }
1911
1912 static int mdt_llog_read_header(struct mdt_thread_info *info)
1913 {
1914         int rc;
1915
1916         req_capsule_set(info->mti_pill, &RQF_LLOG_ORIGIN_HANDLE_READ_HEADER);
1917         rc = llog_origin_handle_read_header(mdt_info_req(info));
1918         return (rc < 0 ? err_serious(rc) : rc);
1919 }
1920
1921 static int mdt_llog_next_block(struct mdt_thread_info *info)
1922 {
1923         int rc;
1924
1925         req_capsule_set(info->mti_pill, &RQF_LLOG_ORIGIN_HANDLE_NEXT_BLOCK);
1926         rc = llog_origin_handle_next_block(mdt_info_req(info));
1927         return (rc < 0 ? err_serious(rc) : rc);
1928 }
1929
1930 static int mdt_llog_prev_block(struct mdt_thread_info *info)
1931 {
1932         int rc;
1933
1934         req_capsule_set(info->mti_pill, &RQF_LLOG_ORIGIN_HANDLE_PREV_BLOCK);
1935         rc = llog_origin_handle_prev_block(mdt_info_req(info));
1936         return (rc < 0 ? err_serious(rc) : rc);
1937 }
1938
1939
1940 /*
1941  * DLM handlers.
1942  */
1943 static struct ldlm_callback_suite cbs = {
1944         .lcs_completion = ldlm_server_completion_ast,
1945         .lcs_blocking   = ldlm_server_blocking_ast,
1946         .lcs_glimpse    = NULL
1947 };
1948
1949 static int mdt_enqueue(struct mdt_thread_info *info)
1950 {
1951         struct ptlrpc_request *req;
1952         __u64 req_bits;
1953         int rc;
1954
1955         /*
1956          * info->mti_dlm_req already contains swapped and (if necessary)
1957          * converted dlm request.
1958          */
1959         LASSERT(info->mti_dlm_req != NULL);
1960
1961         req = mdt_info_req(info);
1962
1963         /*
1964          * Lock without inodebits makes no sense and will oops later in
1965          * ldlm. Let's check it now to see if we have wrong lock from client or
1966          * bits get corrupted somewhere in mdt_intent_policy().
1967          */
1968         req_bits = info->mti_dlm_req->lock_desc.l_policy_data.l_inodebits.bits;
1969         /* This is disabled because we need to support liblustre flock.
1970          * LASSERT(req_bits != 0);
1971          */
1972
1973         rc = ldlm_handle_enqueue0(info->mti_mdt->mdt_namespace,
1974                                   req, info->mti_dlm_req, &cbs);
1975         info->mti_fail_id = OBD_FAIL_LDLM_REPLY;
1976         return rc ? err_serious(rc) : req->rq_status;
1977 }
1978
1979 static int mdt_convert(struct mdt_thread_info *info)
1980 {
1981         int rc;
1982         struct ptlrpc_request *req;
1983
1984         LASSERT(info->mti_dlm_req);
1985         req = mdt_info_req(info);
1986         rc = ldlm_handle_convert0(req, info->mti_dlm_req);
1987         return rc ? err_serious(rc) : req->rq_status;
1988 }
1989
1990 static int mdt_bl_callback(struct mdt_thread_info *info)
1991 {
1992         CERROR("bl callbacks should not happen on MDS\n");
1993         LBUG();
1994         return err_serious(-EOPNOTSUPP);
1995 }
1996
1997 static int mdt_cp_callback(struct mdt_thread_info *info)
1998 {
1999         CERROR("cp callbacks should not happen on MDS\n");
2000         LBUG();
2001         return err_serious(-EOPNOTSUPP);
2002 }
2003
2004 /*
2005  * sec context handlers
2006  */
2007 static int mdt_sec_ctx_handle(struct mdt_thread_info *info)
2008 {
2009         int rc;
2010
2011         rc = mdt_handle_idmap(info);
2012
2013         if (unlikely(rc)) {
2014                 struct ptlrpc_request *req = mdt_info_req(info);
2015                 __u32                  opc;
2016
2017                 opc = lustre_msg_get_opc(req->rq_reqmsg);
2018                 if (opc == SEC_CTX_INIT || opc == SEC_CTX_INIT_CONT)
2019                         sptlrpc_svc_ctx_invalidate(req);
2020         }
2021
2022         OBD_FAIL_TIMEOUT(OBD_FAIL_SEC_CTX_HDL_PAUSE, obd_fail_val);
2023
2024         return rc;
2025 }
2026
2027 static struct mdt_object *mdt_obj(struct lu_object *o)
2028 {
2029         LASSERT(lu_device_is_mdt(o->lo_dev));
2030         return container_of0(o, struct mdt_object, mot_obj.mo_lu);
2031 }
2032
2033 struct mdt_object *mdt_object_find(const struct lu_env *env,
2034                                    struct mdt_device *d,
2035                                    const struct lu_fid *f)
2036 {
2037         struct lu_object *o;
2038         struct mdt_object *m;
2039         ENTRY;
2040
2041         CDEBUG(D_INFO, "Find object for "DFID"\n", PFID(f));
2042         o = lu_object_find(env, &d->mdt_md_dev.md_lu_dev, f, NULL);
2043         if (unlikely(IS_ERR(o)))
2044                 m = (struct mdt_object *)o;
2045         else
2046                 m = mdt_obj(o);
2047         RETURN(m);
2048 }
2049
2050 /**
2051  * Asyncronous commit for mdt device.
2052  *
2053  * Pass asynchonous commit call down the MDS stack.
2054  *
2055  * \param env environment
2056  * \param mdt the mdt device
2057  */
2058 static void mdt_device_commit_async(const struct lu_env *env,
2059                                     struct mdt_device *mdt)
2060 {
2061         struct dt_device *dt = mdt->mdt_bottom;
2062         int rc;
2063
2064         rc = dt->dd_ops->dt_commit_async(env, dt);
2065         if (unlikely(rc != 0))
2066                 CWARN("async commit start failed with rc = %d", rc);
2067 }
2068
2069 /**
2070  * Mark the lock as "synchonous".
2071  *
2072  * Mark the lock to deffer transaction commit to the unlock time.
2073  *
2074  * \param lock the lock to mark as "synchonous"
2075  *
2076  * \see mdt_is_lock_sync
2077  * \see mdt_save_lock
2078  */
2079 static inline void mdt_set_lock_sync(struct ldlm_lock *lock)
2080 {
2081         lock->l_ast_data = (void*)1;
2082 }
2083
2084 /**
2085  * Check whehter the lock "synchonous" or not.
2086  *
2087  * \param lock the lock to check
2088  * \retval 1 the lock is "synchonous"
2089  * \retval 0 the lock isn't "synchronous"
2090  *
2091  * \see mdt_set_lock_sync
2092  * \see mdt_save_lock
2093  */
2094 static inline int mdt_is_lock_sync(struct ldlm_lock *lock)
2095 {
2096         return lock->l_ast_data != NULL;
2097 }
2098
2099 /**
2100  * Blocking AST for mdt locks.
2101  *
2102  * Starts transaction commit if in case of COS lock conflict or
2103  * deffers such a commit to the mdt_save_lock.
2104  *
2105  * \param lock the lock which blocks a request or cancelling lock
2106  * \param desc unused
2107  * \param data unused
2108  * \param flag indicates whether this cancelling or blocking callback
2109  * \retval 0
2110  * \see ldlm_blocking_ast_nocheck
2111  */
2112 int mdt_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
2113                      void *data, int flag)
2114 {
2115         struct obd_device *obd = lock->l_resource->lr_namespace->ns_obd;
2116         struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
2117         int rc;
2118         ENTRY;
2119
2120         if (flag == LDLM_CB_CANCELING)
2121                 RETURN(0);
2122         lock_res_and_lock(lock);
2123         if (lock->l_blocking_ast != mdt_blocking_ast) {
2124                 unlock_res_and_lock(lock);
2125                 RETURN(0);
2126         }
2127         if (mdt_cos_is_enabled(mdt) &&
2128             lock->l_req_mode & (LCK_PW | LCK_EX) &&
2129             lock->l_blocking_lock != NULL &&
2130             lock->l_client_cookie != lock->l_blocking_lock->l_client_cookie) {
2131                 mdt_set_lock_sync(lock);
2132         }
2133         rc = ldlm_blocking_ast_nocheck(lock);
2134
2135         /* There is no lock conflict if l_blocking_lock == NULL,
2136          * it indicates a blocking ast sent from ldlm_lock_decref_internal
2137          * when the last reference to a local lock was released */
2138         if (lock->l_req_mode == LCK_COS && lock->l_blocking_lock != NULL) {
2139                 struct lu_env env;
2140
2141                 rc = lu_env_init(&env, LCT_MD_THREAD);
2142                 if (unlikely(rc != 0))
2143                         CWARN("lu_env initialization failed with rc = %d,"
2144                               "cannot start asynchronous commit\n", rc);
2145                 else
2146                         mdt_device_commit_async(&env, mdt);
2147                 lu_env_fini(&env);
2148         }
2149         RETURN(rc);
2150 }
2151
2152 int mdt_object_lock(struct mdt_thread_info *info, struct mdt_object *o,
2153                     struct mdt_lock_handle *lh, __u64 ibits, int locality)
2154 {
2155         struct ldlm_namespace *ns = info->mti_mdt->mdt_namespace;
2156         ldlm_policy_data_t *policy = &info->mti_policy;
2157         struct ldlm_res_id *res_id = &info->mti_res_id;
2158         int rc;
2159         ENTRY;
2160
2161         LASSERT(!lustre_handle_is_used(&lh->mlh_reg_lh));
2162         LASSERT(!lustre_handle_is_used(&lh->mlh_pdo_lh));
2163         LASSERT(lh->mlh_reg_mode != LCK_MINMODE);
2164         LASSERT(lh->mlh_type != MDT_NUL_LOCK);
2165
2166         if (mdt_object_exists(o) < 0) {
2167                 if (locality == MDT_CROSS_LOCK) {
2168                         /* cross-ref object fix */
2169                         ibits &= ~MDS_INODELOCK_UPDATE;
2170                         ibits |= MDS_INODELOCK_LOOKUP;
2171                 } else {
2172                         LASSERT(!(ibits & MDS_INODELOCK_UPDATE));
2173                         LASSERT(ibits & MDS_INODELOCK_LOOKUP);
2174                 }
2175                 /* No PDO lock on remote object */
2176                 LASSERT(lh->mlh_type != MDT_PDO_LOCK);
2177         }
2178
2179         if (lh->mlh_type == MDT_PDO_LOCK) {
2180                 /* check for exists after object is locked */
2181                 if (mdt_object_exists(o) == 0) {
2182                         /* Non-existent object shouldn't have PDO lock */
2183                         RETURN(-ESTALE);
2184                 } else {
2185                         /* Non-dir object shouldn't have PDO lock */
2186                         LASSERT(S_ISDIR(lu_object_attr(&o->mot_obj.mo_lu)));
2187                 }
2188         }
2189
2190         memset(policy, 0, sizeof(*policy));
2191         fid_build_reg_res_name(mdt_object_fid(o), res_id);
2192
2193         /*
2194          * Take PDO lock on whole directory and build correct @res_id for lock
2195          * on part of directory.
2196          */
2197         if (lh->mlh_pdo_hash != 0) {
2198                 LASSERT(lh->mlh_type == MDT_PDO_LOCK);
2199                 mdt_lock_pdo_mode(info, o, lh);
2200                 if (lh->mlh_pdo_mode != LCK_NL) {
2201                         /*
2202                          * Do not use LDLM_FL_LOCAL_ONLY for parallel lock, it
2203                          * is never going to be sent to client and we do not
2204                          * want it slowed down due to possible cancels.
2205                          */
2206                         policy->l_inodebits.bits = MDS_INODELOCK_UPDATE;
2207                         rc = mdt_fid_lock(ns, &lh->mlh_pdo_lh, lh->mlh_pdo_mode,
2208                                           policy, res_id, LDLM_FL_ATOMIC_CB,
2209                                           &info->mti_exp->exp_handle.h_cookie);
2210                         if (unlikely(rc))
2211                                 RETURN(rc);
2212                 }
2213
2214                 /*
2215                  * Finish res_id initializing by name hash marking part of
2216                  * directory which is taking modification.
2217                  */
2218                 res_id->name[LUSTRE_RES_ID_HSH_OFF] = lh->mlh_pdo_hash;
2219         }
2220
2221         policy->l_inodebits.bits = ibits;
2222
2223         /*
2224          * Use LDLM_FL_LOCAL_ONLY for this lock. We do not know yet if it is
2225          * going to be sent to client. If it is - mdt_intent_policy() path will
2226          * fix it up and turn FL_LOCAL flag off.
2227          */
2228         rc = mdt_fid_lock(ns, &lh->mlh_reg_lh, lh->mlh_reg_mode, policy,
2229                           res_id, LDLM_FL_LOCAL_ONLY | LDLM_FL_ATOMIC_CB,
2230                           &info->mti_exp->exp_handle.h_cookie);
2231         if (rc)
2232                 GOTO(out, rc);
2233
2234 out:
2235         if (rc)
2236                 mdt_object_unlock(info, o, lh, 1);
2237
2238
2239         RETURN(rc);
2240 }
2241
2242 /**
2243  * Save a lock within request object.
2244  *
2245  * Keep the lock referenced until whether client ACK or transaction
2246  * commit happens or release the lock immediately depending on input
2247  * parameters. If COS is ON, a write lock is converted to COS lock
2248  * before saving.
2249  *
2250  * \param info thead info object
2251  * \param h lock handle
2252  * \param mode lock mode
2253  * \param decref force immediate lock releasing
2254  */
2255 static
2256 void mdt_save_lock(struct mdt_thread_info *info, struct lustre_handle *h,
2257                    ldlm_mode_t mode, int decref)
2258 {
2259         ENTRY;
2260
2261         if (lustre_handle_is_used(h)) {
2262                 if (decref || !info->mti_has_trans ||
2263                     !(mode & (LCK_PW | LCK_EX))){
2264                         mdt_fid_unlock(h, mode);
2265                 } else {
2266                         struct mdt_device *mdt = info->mti_mdt;
2267                         struct ldlm_lock *lock = ldlm_handle2lock(h);
2268                         struct ptlrpc_request *req = mdt_info_req(info);
2269                         int no_ack = 0;
2270
2271                         LASSERTF(lock != NULL, "no lock for cookie "LPX64"\n",
2272                                  h->cookie);
2273                         CDEBUG(D_HA, "request = %p reply state = %p"
2274                                " transno = "LPD64"\n",
2275                                req, req->rq_reply_state, req->rq_transno);
2276                         if (mdt_cos_is_enabled(mdt)) {
2277                                 no_ack = 1;
2278                                 ldlm_lock_downgrade(lock, LCK_COS);
2279                                 mode = LCK_COS;
2280                         }
2281                         ptlrpc_save_lock(req, h, mode, no_ack);
2282                         if (mdt_is_lock_sync(lock)) {
2283                                 CDEBUG(D_HA, "found sync-lock,"
2284                                        " async commit started\n");
2285                                 mdt_device_commit_async(info->mti_env,
2286                                                         mdt);
2287                         }
2288                         LDLM_LOCK_PUT(lock);
2289                 }
2290                 h->cookie = 0ull;
2291         }
2292
2293         EXIT;
2294 }
2295
2296 /**
2297  * Unlock mdt object.
2298  *
2299  * Immeditely release the regular lock and the PDO lock or save the
2300  * lock in reqeuest and keep them referenced until client ACK or
2301  * transaction commit.
2302  *
2303  * \param info thread info object
2304  * \param o mdt object
2305  * \param h mdt lock handle referencing regular and PDO locks
2306  * \param decref force immediate lock releasing
2307  */
2308 void mdt_object_unlock(struct mdt_thread_info *info, struct mdt_object *o,
2309                        struct mdt_lock_handle *lh, int decref)
2310 {
2311         ENTRY;
2312
2313         mdt_save_lock(info, &lh->mlh_pdo_lh, lh->mlh_pdo_mode, decref);
2314         mdt_save_lock(info, &lh->mlh_reg_lh, lh->mlh_reg_mode, decref);
2315
2316         EXIT;
2317 }
2318
2319 struct mdt_object *mdt_object_find_lock(struct mdt_thread_info *info,
2320                                         const struct lu_fid *f,
2321                                         struct mdt_lock_handle *lh,
2322                                         __u64 ibits)
2323 {
2324         struct mdt_object *o;
2325
2326         o = mdt_object_find(info->mti_env, info->mti_mdt, f);
2327         if (!IS_ERR(o)) {
2328                 int rc;
2329
2330                 rc = mdt_object_lock(info, o, lh, ibits,
2331                                      MDT_LOCAL_LOCK);
2332                 if (rc != 0) {
2333                         mdt_object_put(info->mti_env, o);
2334                         o = ERR_PTR(rc);
2335                 }
2336         }
2337         return o;
2338 }
2339
2340 void mdt_object_unlock_put(struct mdt_thread_info * info,
2341                            struct mdt_object * o,
2342                            struct mdt_lock_handle *lh,
2343                            int decref)
2344 {
2345         mdt_object_unlock(info, o, lh, decref);
2346         mdt_object_put(info->mti_env, o);
2347 }
2348
2349 static struct mdt_handler *mdt_handler_find(__u32 opc,
2350                                             struct mdt_opc_slice *supported)
2351 {
2352         struct mdt_opc_slice *s;
2353         struct mdt_handler   *h;
2354
2355         h = NULL;
2356         for (s = supported; s->mos_hs != NULL; s++) {
2357                 if (s->mos_opc_start <= opc && opc < s->mos_opc_end) {
2358                         h = s->mos_hs + (opc - s->mos_opc_start);
2359                         if (likely(h->mh_opc != 0))
2360                                 LASSERTF(h->mh_opc == opc,
2361                                          "opcode mismatch %d != %d\n",
2362                                          h->mh_opc, opc);
2363                         else
2364                                 h = NULL; /* unsupported opc */
2365                         break;
2366                 }
2367         }
2368         return h;
2369 }
2370
2371 static int mdt_lock_resname_compat(struct mdt_device *m,
2372                                    struct ldlm_request *req)
2373 {
2374         /* XXX something... later. */
2375         return 0;
2376 }
2377
2378 static int mdt_lock_reply_compat(struct mdt_device *m, struct ldlm_reply *rep)
2379 {
2380         /* XXX something... later. */
2381         return 0;
2382 }
2383
2384 /*
2385  * Generic code handling requests that have struct mdt_body passed in:
2386  *
2387  *  - extract mdt_body from request and save it in @info, if present;
2388  *
2389  *  - create lu_object, corresponding to the fid in mdt_body, and save it in
2390  *  @info;
2391  *
2392  *  - if HABEO_CORPUS flag is set for this request type check whether object
2393  *  actually exists on storage (lu_object_exists()).
2394  *
2395  */
2396 static int mdt_body_unpack(struct mdt_thread_info *info, __u32 flags)
2397 {
2398         const struct mdt_body    *body;
2399         struct mdt_object        *obj;
2400         const struct lu_env      *env;
2401         struct req_capsule       *pill;
2402         int                       rc;
2403         ENTRY;
2404
2405         env = info->mti_env;
2406         pill = info->mti_pill;
2407
2408         body = info->mti_body = req_capsule_client_get(pill, &RMF_MDT_BODY);
2409         if (body == NULL)
2410                 RETURN(-EFAULT);
2411
2412         if (!(body->valid & OBD_MD_FLID))
2413                 RETURN(0);
2414
2415         if (!fid_is_sane(&body->fid1)) {
2416                 CERROR("Invalid fid: "DFID"\n", PFID(&body->fid1));
2417                 RETURN(-EINVAL);
2418         }
2419
2420         /*
2421          * Do not get size or any capa fields before we check that request
2422          * contains capa actually. There are some requests which do not, for
2423          * instance MDS_IS_SUBDIR.
2424          */
2425         if (req_capsule_has_field(pill, &RMF_CAPA1, RCL_CLIENT) &&
2426             req_capsule_get_size(pill, &RMF_CAPA1, RCL_CLIENT))
2427                 mdt_set_capainfo(info, 0, &body->fid1,
2428                                  req_capsule_client_get(pill, &RMF_CAPA1));
2429
2430         obj = mdt_object_find(env, info->mti_mdt, &body->fid1);
2431         if (!IS_ERR(obj)) {
2432                 if ((flags & HABEO_CORPUS) &&
2433                     !mdt_object_exists(obj)) {
2434                         mdt_object_put(env, obj);
2435                         /* for capability renew ENOENT will be handled in
2436                          * mdt_renew_capa */
2437                         if (body->valid & OBD_MD_FLOSSCAPA)
2438                                 rc = 0;
2439                         else
2440                                 rc = -ENOENT;
2441                 } else {
2442                         info->mti_object = obj;
2443                         rc = 0;
2444                 }
2445         } else
2446                 rc = PTR_ERR(obj);
2447
2448         RETURN(rc);
2449 }
2450
2451 static int mdt_unpack_req_pack_rep(struct mdt_thread_info *info, __u32 flags)
2452 {
2453         struct req_capsule *pill = info->mti_pill;
2454         int rc;
2455         ENTRY;
2456
2457         if (req_capsule_has_field(pill, &RMF_MDT_BODY, RCL_CLIENT))
2458                 rc = mdt_body_unpack(info, flags);
2459         else
2460                 rc = 0;
2461
2462         if (rc == 0 && (flags & HABEO_REFERO)) {
2463                 struct mdt_device *mdt = info->mti_mdt;
2464
2465                 /* Pack reply. */
2466
2467                 if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
2468                         req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER,
2469                                              mdt->mdt_max_mdsize);
2470                 if (req_capsule_has_field(pill, &RMF_LOGCOOKIES, RCL_SERVER))
2471                         req_capsule_set_size(pill, &RMF_LOGCOOKIES, RCL_SERVER,
2472                                              mdt->mdt_max_cookiesize);
2473
2474                 rc = req_capsule_server_pack(pill);
2475         }
2476         RETURN(rc);
2477 }
2478
2479 static int mdt_init_capa_ctxt(const struct lu_env *env, struct mdt_device *m)
2480 {
2481         struct md_device *next = m->mdt_child;
2482
2483         return next->md_ops->mdo_init_capa_ctxt(env, next,
2484                                                 m->mdt_opts.mo_mds_capa,
2485                                                 m->mdt_capa_timeout,
2486                                                 m->mdt_capa_alg,
2487                                                 m->mdt_capa_keys);
2488 }
2489
2490 /*
2491  * Invoke handler for this request opc. Also do necessary preprocessing
2492  * (according to handler ->mh_flags), and post-processing (setting of
2493  * ->last_{xid,committed}).
2494  */
2495 static int mdt_req_handle(struct mdt_thread_info *info,
2496                           struct mdt_handler *h, struct ptlrpc_request *req)
2497 {
2498         int   rc, serious = 0;
2499         __u32 flags;
2500
2501         ENTRY;
2502
2503         LASSERT(h->mh_act != NULL);
2504         LASSERT(h->mh_opc == lustre_msg_get_opc(req->rq_reqmsg));
2505         LASSERT(current->journal_info == NULL);
2506
2507         /*
2508          * Checking for various OBD_FAIL_$PREF_$OPC_NET codes. _Do_ not try
2509          * to put same checks into handlers like mdt_close(), mdt_reint(),
2510          * etc., without talking to mdt authors first. Checking same thing
2511          * there again is useless and returning 0 error wihtout packing reply
2512          * is buggy! Handlers either pack reply or return error.
2513          *
2514          * We return 0 here and do not send any reply in order to emulate
2515          * network failure. Do not send any reply in case any of NET related
2516          * fail_id has occured.
2517          */
2518         if (OBD_FAIL_CHECK_ORSET(h->mh_fail_id, OBD_FAIL_ONCE))
2519                 RETURN(0);
2520
2521         rc = 0;
2522         flags = h->mh_flags;
2523         LASSERT(ergo(flags & (HABEO_CORPUS|HABEO_REFERO), h->mh_fmt != NULL));
2524
2525         if (h->mh_fmt != NULL) {
2526                 req_capsule_set(info->mti_pill, h->mh_fmt);
2527                 rc = mdt_unpack_req_pack_rep(info, flags);
2528         }
2529
2530         if (rc == 0 && flags & MUTABOR &&
2531             req->rq_export->exp_connect_flags & OBD_CONNECT_RDONLY)
2532                 /* should it be rq_status? */
2533                 rc = -EROFS;
2534
2535         if (rc == 0 && flags & HABEO_CLAVIS) {
2536                 struct ldlm_request *dlm_req;
2537
2538                 LASSERT(h->mh_fmt != NULL);
2539
2540                 dlm_req = req_capsule_client_get(info->mti_pill, &RMF_DLM_REQ);
2541                 if (dlm_req != NULL) {
2542                         if (info->mti_mdt->mdt_opts.mo_compat_resname)
2543                                 rc = mdt_lock_resname_compat(info->mti_mdt,
2544                                                              dlm_req);
2545                         info->mti_dlm_req = dlm_req;
2546                 } else {
2547                         rc = -EFAULT;
2548                 }
2549         }
2550
2551         /* capability setting changed via /proc, needs reinitialize ctxt */
2552         if (info->mti_mdt && info->mti_mdt->mdt_capa_conf) {
2553                 mdt_init_capa_ctxt(info->mti_env, info->mti_mdt);
2554                 info->mti_mdt->mdt_capa_conf = 0;
2555         }
2556
2557         if (likely(rc == 0)) {
2558                 /*
2559                  * Process request, there can be two types of rc:
2560                  * 1) errors with msg unpack/pack, other failures outside the
2561                  * operation itself. This is counted as serious errors;
2562                  * 2) errors during fs operation, should be placed in rq_status
2563                  * only
2564                  */
2565                 rc = h->mh_act(info);
2566                 if (rc == 0 &&
2567                     !req->rq_no_reply && req->rq_reply_state == NULL) {
2568                         DEBUG_REQ(D_ERROR, req, "MDT \"handler\" %s did not "
2569                                   "pack reply and returned 0 error\n",
2570                                   h->mh_name);
2571                         LBUG();
2572                 }
2573                 serious = is_serious(rc);
2574                 rc = clear_serious(rc);
2575         } else
2576                 serious = 1;
2577
2578         req->rq_status = rc;
2579
2580         /*
2581          * ELDLM_* codes which > 0 should be in rq_status only as well as
2582          * all non-serious errors.
2583          */
2584         if (rc > 0 || !serious)
2585                 rc = 0;
2586
2587         LASSERT(current->journal_info == NULL);
2588
2589         if (rc == 0 && (flags & HABEO_CLAVIS) &&
2590             info->mti_mdt->mdt_opts.mo_compat_resname) {
2591                 struct ldlm_reply *dlmrep;
2592
2593                 dlmrep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
2594                 if (dlmrep != NULL)
2595                         rc = mdt_lock_reply_compat(info->mti_mdt, dlmrep);
2596         }
2597
2598         /* If we're DISCONNECTing, the mdt_export_data is already freed */
2599         if (likely(rc == 0 && req->rq_export && h->mh_opc != MDS_DISCONNECT))
2600                 target_committed_to_req(req);
2601
2602         if (unlikely((lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY) &&
2603                      lustre_msg_get_transno(req->rq_reqmsg) == 0)) {
2604                 DEBUG_REQ(D_ERROR, req, "transno is 0 during REPLAY");
2605                 LBUG();
2606         }
2607
2608         target_send_reply(req, rc, info->mti_fail_id);
2609         RETURN(0);
2610 }
2611
2612 void mdt_lock_handle_init(struct mdt_lock_handle *lh)
2613 {
2614         lh->mlh_type = MDT_NUL_LOCK;
2615         lh->mlh_reg_lh.cookie = 0ull;
2616         lh->mlh_reg_mode = LCK_MINMODE;
2617         lh->mlh_pdo_lh.cookie = 0ull;
2618         lh->mlh_pdo_mode = LCK_MINMODE;
2619 }
2620
2621 void mdt_lock_handle_fini(struct mdt_lock_handle *lh)
2622 {
2623         LASSERT(!lustre_handle_is_used(&lh->mlh_reg_lh));
2624         LASSERT(!lustre_handle_is_used(&lh->mlh_pdo_lh));
2625 }
2626
2627 /*
2628  * Initialize fields of struct mdt_thread_info. Other fields are left in
2629  * uninitialized state, because it's too expensive to zero out whole
2630  * mdt_thread_info (> 1K) on each request arrival.
2631  */
2632 static void mdt_thread_info_init(struct ptlrpc_request *req,
2633                                  struct mdt_thread_info *info)
2634 {
2635         int i;
2636         struct md_capainfo *ci;
2637
2638         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
2639         info->mti_pill = &req->rq_pill;
2640
2641         /* lock handle */
2642         for (i = 0; i < ARRAY_SIZE(info->mti_lh); i++)
2643                 mdt_lock_handle_init(&info->mti_lh[i]);
2644
2645         /* mdt device: it can be NULL while CONNECT */
2646         if (req->rq_export) {
2647                 info->mti_mdt = mdt_dev(req->rq_export->exp_obd->obd_lu_dev);
2648                 info->mti_exp = req->rq_export;
2649         } else
2650                 info->mti_mdt = NULL;
2651         info->mti_env = req->rq_svc_thread->t_env;
2652         ci = md_capainfo(info->mti_env);
2653         memset(ci, 0, sizeof *ci);
2654         if (req->rq_export) {
2655                 if (exp_connect_rmtclient(req->rq_export))
2656                         ci->mc_auth = LC_ID_CONVERT;
2657                 else if (req->rq_export->exp_connect_flags &
2658                          OBD_CONNECT_MDS_CAPA)
2659                         ci->mc_auth = LC_ID_PLAIN;
2660                 else
2661                         ci->mc_auth = LC_ID_NONE;
2662         }
2663
2664         info->mti_fail_id = OBD_FAIL_MDS_ALL_REPLY_NET;
2665         info->mti_transno = lustre_msg_get_transno(req->rq_reqmsg);
2666         info->mti_mos[0] = NULL;
2667         info->mti_mos[1] = NULL;
2668         info->mti_mos[2] = NULL;
2669         info->mti_mos[3] = NULL;
2670
2671         memset(&info->mti_attr, 0, sizeof(info->mti_attr));
2672         info->mti_body = NULL;
2673         info->mti_object = NULL;
2674         info->mti_dlm_req = NULL;
2675         info->mti_has_trans = 0;
2676         info->mti_no_need_trans = 0;
2677         info->mti_cross_ref = 0;
2678         info->mti_opdata = 0;
2679
2680         /* To not check for split by default. */
2681         info->mti_spec.sp_ck_split = 0;
2682         info->mti_spec.no_create = 0;
2683 }
2684
2685 static void mdt_thread_info_fini(struct mdt_thread_info *info)
2686 {
2687         int i;
2688
2689         req_capsule_fini(info->mti_pill);
2690         if (info->mti_object != NULL) {
2691                 /*
2692                  * freeing an object may lead to OSD level transaction, do not
2693                  * let it mess with MDT. bz19385.
2694                  */
2695                 info->mti_no_need_trans = 1;
2696                 mdt_object_put(info->mti_env, info->mti_object);
2697                 info->mti_object = NULL;
2698         }
2699         for (i = 0; i < ARRAY_SIZE(info->mti_lh); i++)
2700                 mdt_lock_handle_fini(&info->mti_lh[i]);
2701         info->mti_env = NULL;
2702 }
2703
2704 static int mdt_filter_recovery_request(struct ptlrpc_request *req,
2705                                        struct obd_device *obd, int *process)
2706 {
2707         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2708         case MDS_CONNECT: /* This will never get here, but for completeness. */
2709         case OST_CONNECT: /* This will never get here, but for completeness. */
2710         case MDS_DISCONNECT:
2711         case OST_DISCONNECT:
2712                *process = 1;
2713                RETURN(0);
2714
2715         case MDS_CLOSE:
2716         case MDS_DONE_WRITING:
2717         case MDS_SYNC: /* used in unmounting */
2718         case OBD_PING:
2719         case MDS_REINT:
2720         case SEQ_QUERY:
2721         case FLD_QUERY:
2722         case LDLM_ENQUEUE:
2723                 *process = target_queue_recovery_request(req, obd);
2724                 RETURN(0);
2725
2726         default:
2727                 DEBUG_REQ(D_ERROR, req, "not permitted during recovery");
2728                 *process = -EAGAIN;
2729                 RETURN(0);
2730         }
2731 }
2732
2733 /*
2734  * Handle recovery. Return:
2735  *        +1: continue request processing;
2736  *       -ve: abort immediately with the given error code;
2737  *         0: send reply with error code in req->rq_status;
2738  */
2739 static int mdt_recovery(struct mdt_thread_info *info)
2740 {
2741         struct ptlrpc_request *req = mdt_info_req(info);
2742         int recovering;
2743         struct obd_device *obd;
2744
2745         ENTRY;
2746
2747         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2748         case MDS_CONNECT:
2749         case SEC_CTX_INIT:
2750         case SEC_CTX_INIT_CONT:
2751         case SEC_CTX_FINI:
2752                 {
2753 #if 0
2754                         int rc;
2755
2756                         rc = mdt_handle_idmap(info);
2757                         if (rc)
2758                                 RETURN(rc);
2759                         else
2760 #endif
2761                                 RETURN(+1);
2762                 }
2763         }
2764
2765         if (unlikely(req->rq_export == NULL)) {
2766                 CERROR("operation %d on unconnected MDS from %s\n",
2767                        lustre_msg_get_opc(req->rq_reqmsg),
2768                        libcfs_id2str(req->rq_peer));
2769                 /* FIXME: For CMD cleanup, when mds_B stop, the req from
2770                  * mds_A will get -ENOTCONN(especially for ping req),
2771                  * which will cause that mds_A deactive timeout, then when
2772                  * mds_A cleanup, the cleanup process will be suspended since
2773                  * deactive timeout is not zero.
2774                  */
2775                 req->rq_status = -ENOTCONN;
2776                 target_send_reply(req, -ENOTCONN, info->mti_fail_id);
2777                 RETURN(0);
2778         }
2779
2780         /* sanity check: if the xid matches, the request must be marked as a
2781          * resent or replayed */
2782         if (req_xid_is_last(req)) {
2783                 if (!(lustre_msg_get_flags(req->rq_reqmsg) &
2784                       (MSG_RESENT | MSG_REPLAY))) {
2785                         DEBUG_REQ(D_WARNING, req, "rq_xid "LPU64" matches last_xid, "
2786                                   "expected REPLAY or RESENT flag (%x)", req->rq_xid,
2787                                   lustre_msg_get_flags(req->rq_reqmsg));
2788                         LBUG();
2789                         req->rq_status = -ENOTCONN;
2790                         RETURN(-ENOTCONN);
2791                 }
2792         }
2793
2794         /* else: note the opposite is not always true; a RESENT req after a
2795          * failover will usually not match the last_xid, since it was likely
2796          * never committed. A REPLAYed request will almost never match the
2797          * last xid, however it could for a committed, but still retained,
2798          * open. */
2799
2800         obd = req->rq_export->exp_obd;
2801
2802         /* Check for aborted recovery... */
2803         spin_lock_bh(&obd->obd_processing_task_lock);
2804         recovering = obd->obd_recovering;
2805         spin_unlock_bh(&obd->obd_processing_task_lock);
2806         if (unlikely(recovering)) {
2807                 int rc;
2808                 int should_process;
2809                 DEBUG_REQ(D_INFO, req, "Got new replay");
2810                 rc = mdt_filter_recovery_request(req, obd, &should_process);
2811                 if (rc != 0 || !should_process)
2812                         RETURN(rc);
2813                 else if (should_process < 0) {
2814                         req->rq_status = should_process;
2815                         rc = ptlrpc_error(req);
2816                         RETURN(rc);
2817                 }
2818         }
2819         RETURN(+1);
2820 }
2821
2822 static int mdt_msg_check_version(struct lustre_msg *msg)
2823 {
2824         int rc;
2825
2826         switch (lustre_msg_get_opc(msg)) {
2827         case MDS_CONNECT:
2828         case MDS_DISCONNECT:
2829         case MDS_SET_INFO:
2830         case OBD_PING:
2831         case SEC_CTX_INIT:
2832         case SEC_CTX_INIT_CONT:
2833         case SEC_CTX_FINI:
2834                 rc = lustre_msg_check_version(msg, LUSTRE_OBD_VERSION);
2835                 if (rc)
2836                         CERROR("bad opc %u version %08x, expecting %08x\n",
2837                                lustre_msg_get_opc(msg),
2838                                lustre_msg_get_version(msg),
2839                                LUSTRE_OBD_VERSION);
2840                 break;
2841         case MDS_GETSTATUS:
2842         case MDS_GETATTR:
2843         case MDS_GETATTR_NAME:
2844         case MDS_STATFS:
2845         case MDS_READPAGE:
2846         case MDS_WRITEPAGE:
2847         case MDS_IS_SUBDIR:
2848         case MDS_REINT:
2849         case MDS_CLOSE:
2850         case MDS_DONE_WRITING:
2851         case MDS_PIN:
2852         case MDS_SYNC:
2853         case MDS_GETXATTR:
2854         case MDS_SETXATTR:
2855         case MDS_GET_INFO:
2856         case MDS_QUOTACHECK:
2857         case MDS_QUOTACTL:
2858         case QUOTA_DQACQ:
2859         case QUOTA_DQREL:
2860         case SEQ_QUERY:
2861         case FLD_QUERY:
2862                 rc = lustre_msg_check_version(msg, LUSTRE_MDS_VERSION);
2863                 if (rc)
2864                         CERROR("bad opc %u version %08x, expecting %08x\n",
2865                                lustre_msg_get_opc(msg),
2866                                lustre_msg_get_version(msg),
2867                                LUSTRE_MDS_VERSION);
2868                 break;
2869         case LDLM_ENQUEUE:
2870         case LDLM_CONVERT:
2871         case LDLM_BL_CALLBACK:
2872         case LDLM_CP_CALLBACK:
2873                 rc = lustre_msg_check_version(msg, LUSTRE_DLM_VERSION);
2874                 if (rc)
2875                         CERROR("bad opc %u version %08x, expecting %08x\n",
2876                                lustre_msg_get_opc(msg),
2877                                lustre_msg_get_version(msg),
2878                                LUSTRE_DLM_VERSION);
2879                 break;
2880         case OBD_LOG_CANCEL:
2881         case LLOG_ORIGIN_HANDLE_CREATE:
2882         case LLOG_ORIGIN_HANDLE_NEXT_BLOCK:
2883         case LLOG_ORIGIN_HANDLE_READ_HEADER:
2884         case LLOG_ORIGIN_HANDLE_CLOSE:
2885         case LLOG_ORIGIN_HANDLE_DESTROY:
2886         case LLOG_ORIGIN_HANDLE_PREV_BLOCK:
2887         case LLOG_CATINFO:
2888                 rc = lustre_msg_check_version(msg, LUSTRE_LOG_VERSION);
2889                 if (rc)
2890                         CERROR("bad opc %u version %08x, expecting %08x\n",
2891                                lustre_msg_get_opc(msg),
2892                                lustre_msg_get_version(msg),
2893                                LUSTRE_LOG_VERSION);
2894                 break;
2895         default:
2896                 CERROR("MDS unknown opcode %d\n", lustre_msg_get_opc(msg));
2897                 rc = -ENOTSUPP;
2898         }
2899         return rc;
2900 }
2901
2902 static int mdt_handle0(struct ptlrpc_request *req,
2903                        struct mdt_thread_info *info,
2904                        struct mdt_opc_slice *supported)
2905 {
2906         struct mdt_handler *h;
2907         struct lustre_msg  *msg;
2908         int                 rc;
2909
2910         ENTRY;
2911
2912         if (OBD_FAIL_CHECK_ORSET(OBD_FAIL_MDS_ALL_REQUEST_NET, OBD_FAIL_ONCE))
2913                 RETURN(0);
2914
2915         LASSERT(current->journal_info == NULL);
2916
2917         msg = req->rq_reqmsg;
2918         rc = mdt_msg_check_version(msg);
2919         if (likely(rc == 0)) {
2920                 rc = mdt_recovery(info);
2921                 if (likely(rc == +1)) {
2922                         switch (lustre_msg_get_opc(msg)) {
2923                         case MDS_READPAGE:
2924                                 req->rq_bulk_read = 1;
2925                                 break;
2926                         case MDS_WRITEPAGE:
2927                                 req->rq_bulk_write = 1;
2928                                 break;
2929                         }
2930
2931                         h = mdt_handler_find(lustre_msg_get_opc(msg),
2932                                              supported);
2933                         if (likely(h != NULL)) {
2934                                 rc = mdt_req_handle(info, h, req);
2935                         } else {
2936                                 CERROR("The unsupported opc: 0x%x\n",
2937                                        lustre_msg_get_opc(msg) );
2938                                 req->rq_status = -ENOTSUPP;
2939                                 rc = ptlrpc_error(req);
2940                                 RETURN(rc);
2941                         }
2942                 }
2943         } else
2944                 CERROR(LUSTRE_MDT_NAME" drops mal-formed request\n");
2945         RETURN(rc);
2946 }
2947
2948 /*
2949  * MDT handler function called by ptlrpc service thread when request comes.
2950  *
2951  * XXX common "target" functionality should be factored into separate module
2952  * shared by mdt, ost and stand-alone services like fld.
2953  */
2954 static int mdt_handle_common(struct ptlrpc_request *req,
2955                              struct mdt_opc_slice *supported)
2956 {
2957         struct lu_env          *env;
2958         struct mdt_thread_info *info;
2959         int                     rc;
2960         ENTRY;
2961
2962         env = req->rq_svc_thread->t_env;
2963         LASSERT(env != NULL);
2964         LASSERT(env->le_ses != NULL);
2965         LASSERT(env->le_ctx.lc_thread == req->rq_svc_thread);
2966         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
2967         LASSERT(info != NULL);
2968
2969         mdt_thread_info_init(req, info);
2970
2971         rc = mdt_handle0(req, info, supported);
2972
2973         mdt_thread_info_fini(info);
2974         RETURN(rc);
2975 }
2976
2977 /*
2978  * This is called from recovery code as handler of _all_ RPC types, FLD and SEQ
2979  * as well.
2980  */
2981 int mdt_recovery_handle(struct ptlrpc_request *req)
2982 {
2983         int rc;
2984         ENTRY;
2985
2986         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2987         case FLD_QUERY:
2988                 rc = mdt_handle_common(req, mdt_fld_handlers);
2989                 break;
2990         case SEQ_QUERY:
2991                 rc = mdt_handle_common(req, mdt_seq_handlers);
2992                 break;
2993         default:
2994                 rc = mdt_handle_common(req, mdt_regular_handlers);
2995                 break;
2996         }
2997
2998         RETURN(rc);
2999 }
3000
3001 static int mdt_regular_handle(struct ptlrpc_request *req)
3002 {
3003         return mdt_handle_common(req, mdt_regular_handlers);
3004 }
3005
3006 static int mdt_readpage_handle(struct ptlrpc_request *req)
3007 {
3008         return mdt_handle_common(req, mdt_readpage_handlers);
3009 }
3010
3011 static int mdt_xmds_handle(struct ptlrpc_request *req)
3012 {
3013         return mdt_handle_common(req, mdt_xmds_handlers);
3014 }
3015
3016 static int mdt_mdsc_handle(struct ptlrpc_request *req)
3017 {
3018         return mdt_handle_common(req, mdt_seq_handlers);
3019 }
3020
3021 static int mdt_mdss_handle(struct ptlrpc_request *req)
3022 {
3023         return mdt_handle_common(req, mdt_seq_handlers);
3024 }
3025
3026 static int mdt_dtss_handle(struct ptlrpc_request *req)
3027 {
3028         return mdt_handle_common(req, mdt_seq_handlers);
3029 }
3030
3031 static int mdt_fld_handle(struct ptlrpc_request *req)
3032 {
3033         return mdt_handle_common(req, mdt_fld_handlers);
3034 }
3035
3036 enum mdt_it_code {
3037         MDT_IT_OPEN,
3038         MDT_IT_OCREAT,
3039         MDT_IT_CREATE,
3040         MDT_IT_GETATTR,
3041         MDT_IT_READDIR,
3042         MDT_IT_LOOKUP,
3043         MDT_IT_UNLINK,
3044         MDT_IT_TRUNC,
3045         MDT_IT_GETXATTR,
3046         MDT_IT_NR
3047 };
3048
3049 static int mdt_intent_getattr(enum mdt_it_code opcode,
3050                               struct mdt_thread_info *info,
3051                               struct ldlm_lock **,
3052                               int);
3053 static int mdt_intent_reint(enum mdt_it_code opcode,
3054                             struct mdt_thread_info *info,
3055                             struct ldlm_lock **,
3056                             int);
3057
3058 static struct mdt_it_flavor {
3059         const struct req_format *it_fmt;
3060         __u32                    it_flags;
3061         int                    (*it_act)(enum mdt_it_code ,
3062                                          struct mdt_thread_info *,
3063                                          struct ldlm_lock **,
3064                                          int);
3065         long                     it_reint;
3066 } mdt_it_flavor[] = {
3067         [MDT_IT_OPEN]     = {
3068                 .it_fmt   = &RQF_LDLM_INTENT,
3069                 /*.it_flags = HABEO_REFERO,*/
3070                 .it_flags = 0,
3071                 .it_act   = mdt_intent_reint,
3072                 .it_reint = REINT_OPEN
3073         },
3074         [MDT_IT_OCREAT]   = {
3075                 .it_fmt   = &RQF_LDLM_INTENT,
3076                 .it_flags = MUTABOR,
3077                 .it_act   = mdt_intent_reint,
3078                 .it_reint = REINT_OPEN
3079         },
3080         [MDT_IT_CREATE]   = {
3081                 .it_fmt   = &RQF_LDLM_INTENT,
3082                 .it_flags = MUTABOR,
3083                 .it_act   = mdt_intent_reint,
3084                 .it_reint = REINT_CREATE
3085         },
3086         [MDT_IT_GETATTR]  = {
3087                 .it_fmt   = &RQF_LDLM_INTENT_GETATTR,
3088                 .it_flags = HABEO_REFERO,
3089                 .it_act   = mdt_intent_getattr
3090         },
3091         [MDT_IT_READDIR]  = {
3092                 .it_fmt   = NULL,
3093                 .it_flags = 0,
3094                 .it_act   = NULL
3095         },
3096         [MDT_IT_LOOKUP]   = {
3097                 .it_fmt   = &RQF_LDLM_INTENT_GETATTR,
3098                 .it_flags = HABEO_REFERO,
3099                 .it_act   = mdt_intent_getattr
3100         },
3101         [MDT_IT_UNLINK]   = {
3102                 .it_fmt   = &RQF_LDLM_INTENT_UNLINK,
3103                 .it_flags = MUTABOR,
3104                 .it_act   = NULL,
3105                 .it_reint = REINT_UNLINK
3106         },
3107         [MDT_IT_TRUNC]    = {
3108                 .it_fmt   = NULL,
3109                 .it_flags = MUTABOR,
3110                 .it_act   = NULL
3111         },
3112         [MDT_IT_GETXATTR] = {
3113                 .it_fmt   = NULL,
3114                 .it_flags = 0,
3115                 .it_act   = NULL
3116         }
3117 };
3118
3119 int mdt_intent_lock_replace(struct mdt_thread_info *info,
3120                             struct ldlm_lock **lockp,
3121                             struct ldlm_lock *new_lock,
3122                             struct mdt_lock_handle *lh,
3123                             int flags)
3124 {
3125         struct ptlrpc_request  *req = mdt_info_req(info);
3126         struct ldlm_lock       *lock = *lockp;
3127
3128         /*
3129          * Get new lock only for cases when possible resent did not find any
3130          * lock.
3131          */
3132         if (new_lock == NULL)
3133                 new_lock = ldlm_handle2lock_long(&lh->mlh_reg_lh, 0);
3134
3135         if (new_lock == NULL && (flags & LDLM_FL_INTENT_ONLY)) {
3136                 lh->mlh_reg_lh.cookie = 0;
3137                 RETURN(0);
3138         }
3139
3140         LASSERTF(new_lock != NULL,
3141                  "lockh "LPX64"\n", lh->mlh_reg_lh.cookie);
3142
3143         /*
3144          * If we've already given this lock to a client once, then we should
3145          * have no readers or writers.  Otherwise, we should have one reader
3146          * _or_ writer ref (which will be zeroed below) before returning the
3147          * lock to a client.
3148          */
3149         if (new_lock->l_export == req->rq_export) {
3150                 LASSERT(new_lock->l_readers + new_lock->l_writers == 0);
3151         } else {
3152                 LASSERT(new_lock->l_export == NULL);
3153                 LASSERT(new_lock->l_readers + new_lock->l_writers == 1);
3154         }
3155
3156         *lockp = new_lock;
3157
3158         if (new_lock->l_export == req->rq_export) {
3159                 /*
3160                  * Already gave this to the client, which means that we
3161                  * reconstructed a reply.
3162                  */
3163                 LASSERT(lustre_msg_get_flags(req->rq_reqmsg) &
3164                         MSG_RESENT);
3165                 lh->mlh_reg_lh.cookie = 0;
3166                 RETURN(ELDLM_LOCK_REPLACED);
3167         }
3168
3169         /*
3170          * Fixup the lock to be given to the client.
3171          */
3172         lock_res_and_lock(new_lock);
3173         /* Zero new_lock->l_readers and new_lock->l_writers without triggering
3174          * possible blocking AST. */
3175         while (new_lock->l_readers > 0) {
3176                 lu_ref_del(&new_lock->l_reference, "reader", new_lock);
3177                 lu_ref_del(&new_lock->l_reference, "user", new_lock);
3178                 new_lock->l_readers--;
3179         }
3180         while (new_lock->l_writers > 0) {
3181                 lu_ref_del(&new_lock->l_reference, "writer", new_lock);
3182                 lu_ref_del(&new_lock->l_reference, "user", new_lock);
3183                 new_lock->l_writers--;
3184         }
3185
3186         new_lock->l_export = class_export_lock_get(req->rq_export);
3187         new_lock->l_blocking_ast = lock->l_blocking_ast;
3188         new_lock->l_completion_ast = lock->l_completion_ast;
3189         new_lock->l_remote_handle = lock->l_remote_handle;
3190         new_lock->l_flags &= ~LDLM_FL_LOCAL;
3191
3192         unlock_res_and_lock(new_lock);
3193
3194         lustre_hash_add(new_lock->l_export->exp_lock_hash,
3195                         &new_lock->l_remote_handle,
3196                         &new_lock->l_exp_hash);
3197
3198         LDLM_LOCK_RELEASE(new_lock);
3199         lh->mlh_reg_lh.cookie = 0;
3200
3201         RETURN(ELDLM_LOCK_REPLACED);
3202 }
3203
3204 static void mdt_intent_fixup_resent(struct mdt_thread_info *info,
3205                                     struct ldlm_lock *new_lock,
3206                                     struct ldlm_lock **old_lock,
3207                                     struct mdt_lock_handle *lh)
3208 {
3209         struct ptlrpc_request  *req = mdt_info_req(info);
3210         struct obd_export      *exp = req->rq_export;
3211         struct lustre_handle    remote_hdl;
3212         struct ldlm_request    *dlmreq;
3213         struct ldlm_lock       *lock;
3214
3215         if (!(lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT))
3216                 return;
3217
3218         dlmreq = req_capsule_client_get(info->mti_pill, &RMF_DLM_REQ);
3219         remote_hdl = dlmreq->lock_handle[0];
3220
3221         lock = lustre_hash_lookup(exp->exp_lock_hash, &remote_hdl);
3222         if (lock) {
3223                 if (lock != new_lock) {
3224                         lh->mlh_reg_lh.cookie = lock->l_handle.h_cookie;
3225                         lh->mlh_reg_mode = lock->l_granted_mode;
3226
3227                         LDLM_DEBUG(lock, "Restoring lock cookie");
3228                         DEBUG_REQ(D_DLMTRACE, req,
3229                                   "restoring lock cookie "LPX64,
3230                                   lh->mlh_reg_lh.cookie);
3231                         if (old_lock)
3232                                 *old_lock = LDLM_LOCK_GET(lock);
3233                         lh_put(exp->exp_lock_hash, &lock->l_exp_hash);
3234                         return;
3235                 }
3236
3237                 lh_put(exp->exp_lock_hash, &lock->l_exp_hash);
3238         }
3239
3240         /*
3241          * If the xid matches, then we know this is a resent request, and allow
3242          * it. (It's probably an OPEN, for which we don't send a lock.
3243          */
3244         if (req_xid_is_last(req))
3245                 return;
3246
3247         /*
3248          * This remote handle isn't enqueued, so we never received or processed
3249          * this request.  Clear MSG_RESENT, because it can be handled like any
3250          * normal request now.
3251          */
3252         lustre_msg_clear_flags(req->rq_reqmsg, MSG_RESENT);
3253
3254         DEBUG_REQ(D_DLMTRACE, req, "no existing lock with rhandle "LPX64,
3255                   remote_hdl.cookie);
3256 }
3257
3258 static int mdt_intent_getattr(enum mdt_it_code opcode,
3259                               struct mdt_thread_info *info,
3260                               struct ldlm_lock **lockp,
3261                               int flags)
3262 {
3263         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
3264         struct ldlm_lock       *new_lock = NULL;
3265         __u64                   child_bits;
3266         struct ldlm_reply      *ldlm_rep;
3267         struct ptlrpc_request  *req;
3268         struct mdt_body        *reqbody;
3269         struct mdt_body        *repbody;
3270         int                     rc;
3271         ENTRY;
3272
3273         reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
3274         LASSERT(reqbody);
3275
3276         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
3277         LASSERT(repbody);
3278
3279         info->mti_spec.sp_ck_split = !!(reqbody->valid & OBD_MD_FLCKSPLIT);
3280         info->mti_cross_ref = !!(reqbody->valid & OBD_MD_FLCROSSREF);
3281         repbody->eadatasize = 0;
3282         repbody->aclsize = 0;
3283
3284         switch (opcode) {
3285         case MDT_IT_LOOKUP:
3286                 child_bits = MDS_INODELOCK_LOOKUP;
3287                 break;
3288         case MDT_IT_GETATTR:
3289                 child_bits = MDS_INODELOCK_LOOKUP | MDS_INODELOCK_UPDATE;
3290                 break;
3291         default:
3292                 CERROR("Unhandled till now");
3293                 GOTO(out_shrink, rc = -EINVAL);
3294         }
3295
3296         rc = mdt_init_ucred(info, reqbody);
3297         if (rc)
3298                 GOTO(out_shrink, rc);
3299
3300         req = info->mti_pill->rc_req;
3301         ldlm_rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
3302         mdt_set_disposition(info, ldlm_rep, DISP_IT_EXECD);
3303
3304         /* Get lock from request for possible resent case. */
3305         mdt_intent_fixup_resent(info, *lockp, &new_lock, lhc);
3306
3307         ldlm_rep->lock_policy_res2 =
3308                 mdt_getattr_name_lock(info, lhc, child_bits, ldlm_rep);
3309
3310         if (mdt_get_disposition(ldlm_rep, DISP_LOOKUP_NEG))
3311                 ldlm_rep->lock_policy_res2 = 0;
3312         if (!mdt_get_disposition(ldlm_rep, DISP_LOOKUP_POS) ||
3313             ldlm_rep->lock_policy_res2) {
3314                 lhc->mlh_reg_lh.cookie = 0ull;
3315                 GOTO(out_ucred, rc = ELDLM_LOCK_ABORTED);
3316         }
3317
3318         rc = mdt_intent_lock_replace(info, lockp, new_lock, lhc, flags);
3319         EXIT;
3320 out_ucred:
3321         mdt_exit_ucred(info);
3322 out_shrink:
3323         mdt_shrink_reply(info);
3324         return rc;
3325 }
3326
3327 static int mdt_intent_reint(enum mdt_it_code opcode,
3328                             struct mdt_thread_info *info,
3329                             struct ldlm_lock **lockp,
3330                             int flags)
3331 {
3332         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
3333         struct ldlm_reply      *rep = NULL;
3334         long                    opc;
3335         int                     rc;
3336
3337         static const struct req_format *intent_fmts[REINT_MAX] = {
3338                 [REINT_CREATE]  = &RQF_LDLM_INTENT_CREATE,
3339                 [REINT_OPEN]    = &RQF_LDLM_INTENT_OPEN
3340         };
3341
3342         ENTRY;
3343
3344         opc = mdt_reint_opcode(info, intent_fmts);
3345         if (opc < 0)
3346                 RETURN(opc);
3347
3348         if (mdt_it_flavor[opcode].it_reint != opc) {
3349                 CERROR("Reint code %ld doesn't match intent: %d\n",
3350                        opc, opcode);
3351                 RETURN(err_serious(-EPROTO));
3352         }
3353
3354         /* Get lock from request for possible resent case. */
3355         mdt_intent_fixup_resent(info, *lockp, NULL, lhc);
3356
3357         rc = mdt_reint_internal(info, lhc, opc);
3358
3359         /* Check whether the reply has been packed successfully. */
3360         if (mdt_info_req(info)->rq_repmsg != NULL)
3361                 rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
3362         if (rep == NULL)
3363                 RETURN(err_serious(-EFAULT));
3364
3365         /* MDC expects this in any case */
3366         if (rc != 0)
3367                 mdt_set_disposition(info, rep, DISP_LOOKUP_EXECD);
3368
3369         /* Cross-ref case, the lock should be returned to the client */
3370         if (rc == -EREMOTE) {
3371                 LASSERT(lustre_handle_is_used(&lhc->mlh_reg_lh));
3372                 rep->lock_policy_res2 = 0;
3373                 rc = mdt_intent_lock_replace(info, lockp, NULL, lhc, flags);
3374                 RETURN(rc);
3375         }
3376         rep->lock_policy_res2 = clear_serious(rc);
3377
3378         if (rc == -ENOTCONN || rc == -ENODEV ||
3379             rc == -EOVERFLOW) { /**< if VBR failure then return error */
3380                 /*
3381                  * If it is the disconnect error (ENODEV & ENOCONN), the error
3382                  * will be returned by rq_status, and client at ptlrpc layer
3383                  * will detect this, then disconnect, reconnect the import
3384                  * immediately, instead of impacting the following the rpc.
3385                  */
3386                 lhc->mlh_reg_lh.cookie = 0ull;
3387                 RETURN(rc);
3388         } else {
3389                 /*
3390                  * For other cases, the error will be returned by intent.
3391                  * and client will retrieve the result from intent.
3392                  */
3393                  /*
3394                   * FIXME: when open lock is finished, that should be
3395                   * checked here.
3396                   */
3397                 if (lustre_handle_is_used(&lhc->mlh_reg_lh)) {
3398                         rep->lock_policy_res2 = 0;
3399                         rc = mdt_intent_lock_replace(info, lockp, NULL, lhc, flags);
3400                         RETURN(rc);
3401                 } else {
3402                         lhc->mlh_reg_lh.cookie = 0ull;
3403                         RETURN(ELDLM_LOCK_ABORTED);
3404                 }
3405         }
3406 }
3407
3408 static int mdt_intent_code(long itcode)
3409 {
3410         int rc;
3411
3412         switch(itcode) {
3413         case IT_OPEN:
3414                 rc = MDT_IT_OPEN;
3415                 break;
3416         case IT_OPEN|IT_CREAT:
3417                 rc = MDT_IT_OCREAT;
3418                 break;
3419         case IT_CREAT:
3420                 rc = MDT_IT_CREATE;
3421                 break;
3422         case IT_READDIR:
3423                 rc = MDT_IT_READDIR;
3424                 break;
3425         case IT_GETATTR:
3426                 rc = MDT_IT_GETATTR;
3427                 break;
3428         case IT_LOOKUP:
3429                 rc = MDT_IT_LOOKUP;
3430                 break;
3431         case IT_UNLINK:
3432                 rc = MDT_IT_UNLINK;
3433                 break;
3434         case IT_TRUNC:
3435                 rc = MDT_IT_TRUNC;
3436                 break;
3437         case IT_GETXATTR:
3438                 rc = MDT_IT_GETXATTR;
3439                 break;
3440         default:
3441                 CERROR("Unknown intent opcode: %ld\n", itcode);
3442                 rc = -EINVAL;
3443                 break;
3444         }
3445         return rc;
3446 }
3447
3448 static int mdt_intent_opc(long itopc, struct mdt_thread_info *info,
3449                           struct ldlm_lock **lockp, int flags)
3450 {
3451         struct req_capsule   *pill;
3452         struct mdt_it_flavor *flv;
3453         int opc;
3454         int rc;
3455         ENTRY;
3456
3457         opc = mdt_intent_code(itopc);
3458         if (opc < 0)
3459                 RETURN(-EINVAL);
3460
3461         pill = info->mti_pill;
3462         flv  = &mdt_it_flavor[opc];
3463
3464         if (flv->it_fmt != NULL)
3465                 req_capsule_extend(pill, flv->it_fmt);
3466
3467         rc = mdt_unpack_req_pack_rep(info, flv->it_flags);
3468         if (rc == 0) {
3469                 struct ptlrpc_request *req = mdt_info_req(info);
3470                 if (flv->it_flags & MUTABOR &&
3471                     req->rq_export->exp_connect_flags & OBD_CONNECT_RDONLY)
3472                         RETURN(-EROFS);
3473         }
3474         if (rc == 0 && flv->it_act != NULL) {
3475                 /* execute policy */
3476                 rc = flv->it_act(opc, info, lockp, flags);
3477         } else {
3478                 rc = -EOPNOTSUPP;
3479         }
3480         RETURN(rc);
3481 }
3482
3483 static int mdt_intent_policy(struct ldlm_namespace *ns,
3484                              struct ldlm_lock **lockp, void *req_cookie,
3485                              ldlm_mode_t mode, int flags, void *data)
3486 {
3487         struct mdt_thread_info *info;
3488         struct ptlrpc_request  *req  =  req_cookie;
3489         struct ldlm_intent     *it;
3490         struct req_capsule     *pill;
3491         int rc;
3492
3493         ENTRY;
3494
3495         LASSERT(req != NULL);
3496
3497         info = lu_context_key_get(&req->rq_svc_thread->t_env->le_ctx,
3498                                   &mdt_thread_key);
3499         LASSERT(info != NULL);
3500         pill = info->mti_pill;
3501         LASSERT(pill->rc_req == req);
3502
3503         if (req->rq_reqmsg->lm_bufcount > DLM_INTENT_IT_OFF) {
3504                 req_capsule_extend(pill, &RQF_LDLM_INTENT);
3505                 it = req_capsule_client_get(pill, &RMF_LDLM_INTENT);
3506                 if (it != NULL) {
3507                         const struct ldlm_request *dlmreq;
3508                         __u64 req_bits;
3509
3510                         rc = mdt_intent_opc(it->opc, info, lockp, flags);
3511                         if (rc == 0)
3512                                 rc = ELDLM_OK;
3513
3514                         /*
3515                          * Lock without inodebits makes no sense and will oops
3516                          * later in ldlm. Let's check it now to see if we have
3517                          * wrong lock from client or bits get corrupted
3518                          * somewhere in mdt_intent_opc().
3519                          */
3520                         dlmreq = info->mti_dlm_req;
3521                         req_bits = dlmreq->lock_desc.l_policy_data.l_inodebits.bits;
3522                         LASSERT(req_bits != 0);
3523
3524                 } else
3525                         rc = err_serious(-EFAULT);
3526         } else {
3527                 /* No intent was provided */
3528                 LASSERT(pill->rc_fmt == &RQF_LDLM_ENQUEUE);
3529                 rc = req_capsule_server_pack(pill);
3530                 if (rc)
3531                         rc = err_serious(rc);
3532         }
3533         RETURN(rc);
3534 }
3535
3536 /*
3537  * Seq wrappers
3538  */
3539 static void mdt_seq_adjust(const struct lu_env *env,
3540                           struct mdt_device *m, int lost)
3541 {
3542         struct md_site *ms = mdt_md_site(m);
3543         struct lu_seq_range out;
3544         ENTRY;
3545
3546         LASSERT(ms && ms->ms_server_seq);
3547         LASSERT(lost >= 0);
3548         /* get extra seq from seq_server, moving it's range up */
3549         while (lost-- > 0) {
3550                 seq_server_alloc_meta(ms->ms_server_seq, NULL, &out, env);
3551         }
3552         EXIT;
3553 }
3554
3555 static int mdt_seq_fini(const struct lu_env *env,
3556                         struct mdt_device *m)
3557 {
3558         struct md_site *ms = mdt_md_site(m);
3559         ENTRY;
3560
3561         if (ms != NULL) {
3562                 if (ms->ms_server_seq) {
3563                         seq_server_fini(ms->ms_server_seq, env);
3564                         OBD_FREE_PTR(ms->ms_server_seq);
3565                         ms->ms_server_seq = NULL;
3566         }
3567
3568                 if (ms->ms_control_seq) {
3569                         seq_server_fini(ms->ms_control_seq, env);
3570                         OBD_FREE_PTR(ms->ms_control_seq);
3571                         ms->ms_control_seq = NULL;
3572         }
3573
3574                 if (ms->ms_client_seq) {
3575                         seq_client_fini(ms->ms_client_seq);
3576                         OBD_FREE_PTR(ms->ms_client_seq);
3577                         ms->ms_client_seq = NULL;
3578                 }
3579         }
3580
3581         RETURN(0);
3582 }
3583
3584 static int mdt_seq_init(const struct lu_env *env,
3585                         const char *uuid,
3586                         struct mdt_device *m)
3587 {
3588         struct md_site *ms;
3589         char *prefix;
3590         int rc;
3591         ENTRY;
3592
3593         ms = mdt_md_site(m);
3594
3595         /*
3596          * This is sequence-controller node. Init seq-controller server on local
3597          * MDT.
3598          */
3599         if (ms->ms_node_id == 0) {
3600                 LASSERT(ms->ms_control_seq == NULL);
3601
3602                 OBD_ALLOC_PTR(ms->ms_control_seq);
3603                 if (ms->ms_control_seq == NULL)
3604                         RETURN(-ENOMEM);
3605
3606                 rc = seq_server_init(ms->ms_control_seq,
3607                                      m->mdt_bottom, uuid,
3608                                      LUSTRE_SEQ_CONTROLLER,
3609                                      ms,
3610                                      env);
3611
3612                 if (rc)
3613                         GOTO(out_seq_fini, rc);
3614
3615                 OBD_ALLOC_PTR(ms->ms_client_seq);
3616                 if (ms->ms_client_seq == NULL)
3617                         GOTO(out_seq_fini, rc = -ENOMEM);
3618
3619                 OBD_ALLOC(prefix, MAX_OBD_NAME + 5);
3620                 if (prefix == NULL) {
3621                         OBD_FREE_PTR(ms->ms_client_seq);
3622                         GOTO(out_seq_fini, rc = -ENOMEM);
3623                 }
3624
3625                 snprintf(prefix, MAX_OBD_NAME + 5, "ctl-%s",
3626                          uuid);
3627
3628                 /*
3629                  * Init seq-controller client after seq-controller server is
3630                  * ready. Pass ms->ms_control_seq to it for direct talking.
3631                  */
3632                 rc = seq_client_init(ms->ms_client_seq, NULL,
3633                                      LUSTRE_SEQ_METADATA, prefix,
3634                                      ms->ms_control_seq);
3635                 OBD_FREE(prefix, MAX_OBD_NAME + 5);
3636
3637                 if (rc)
3638                         GOTO(out_seq_fini, rc);
3639         }
3640
3641         /* Init seq-server on local MDT */
3642         LASSERT(ms->ms_server_seq == NULL);
3643
3644         OBD_ALLOC_PTR(ms->ms_server_seq);
3645         if (ms->ms_server_seq == NULL)
3646                 GOTO(out_seq_fini, rc = -ENOMEM);
3647
3648         rc = seq_server_init(ms->ms_server_seq,
3649                              m->mdt_bottom, uuid,
3650                              LUSTRE_SEQ_SERVER,
3651                              ms,
3652                              env);
3653         if (rc)
3654                 GOTO(out_seq_fini, rc = -ENOMEM);
3655
3656         /* Assign seq-controller client to local seq-server. */
3657         if (ms->ms_node_id == 0) {
3658                 LASSERT(ms->ms_client_seq != NULL);
3659
3660                 rc = seq_server_set_cli(ms->ms_server_seq,
3661                                         ms->ms_client_seq,
3662                                         env);
3663         }
3664
3665         EXIT;
3666 out_seq_fini:
3667         if (rc)
3668                 mdt_seq_fini(env, m);
3669
3670         return rc;
3671 }
3672 /*
3673  * Init client sequence manager which is used by local MDS to talk to sequence
3674  * controller on remote node.
3675  */
3676 static int mdt_seq_init_cli(const struct lu_env *env,
3677                             struct mdt_device *m,
3678                             struct lustre_cfg *cfg)
3679 {
3680         struct md_site    *ms = mdt_md_site(m);
3681         struct obd_device *mdc;
3682         struct obd_uuid   *uuidp, *mdcuuidp;
3683         char              *uuid_str, *mdc_uuid_str;
3684         int                rc;
3685         int                index;
3686         struct mdt_thread_info *info;
3687         char *p, *index_string = lustre_cfg_string(cfg, 2);
3688         ENTRY;
3689
3690         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
3691         uuidp = &info->mti_u.uuid[0];
3692         mdcuuidp = &info->mti_u.uuid[1];
3693
3694         LASSERT(index_string);
3695
3696         index = simple_strtol(index_string, &p, 10);
3697         if (*p) {
3698                 CERROR("Invalid index in lustre_cgf, offset 2\n");
3699                 RETURN(-EINVAL);
3700         }
3701
3702         /* check if this is adding the first MDC and controller is not yet
3703          * initialized. */
3704         if (index != 0 || ms->ms_client_seq)
3705                 RETURN(0);
3706
3707         uuid_str = lustre_cfg_string(cfg, 1);
3708         mdc_uuid_str = lustre_cfg_string(cfg, 4);
3709         obd_str2uuid(uuidp, uuid_str);
3710         obd_str2uuid(mdcuuidp, mdc_uuid_str);
3711
3712         mdc = class_find_client_obd(uuidp, LUSTRE_MDC_NAME, mdcuuidp);
3713         if (!mdc) {
3714                 CERROR("can't find controller MDC by uuid %s\n",
3715                        uuid_str);
3716                 rc = -ENOENT;
3717         } else if (!mdc->obd_set_up) {
3718                 CERROR("target %s not set up\n", mdc->obd_name);
3719                 rc = -EINVAL;
3720         } else {
3721                 LASSERT(ms->ms_control_exp);
3722                 OBD_ALLOC_PTR(ms->ms_client_seq);
3723                 if (ms->ms_client_seq != NULL) {
3724                         char *prefix;
3725
3726                         OBD_ALLOC(prefix, MAX_OBD_NAME + 5);
3727                         if (!prefix)
3728                                 RETURN(-ENOMEM);
3729
3730                         snprintf(prefix, MAX_OBD_NAME + 5, "ctl-%s",
3731                                  mdc->obd_name);
3732
3733                         rc = seq_client_init(ms->ms_client_seq,
3734                                              ms->ms_control_exp,
3735                                              LUSTRE_SEQ_METADATA,
3736                                              prefix, NULL);
3737                         OBD_FREE(prefix, MAX_OBD_NAME + 5);
3738                 } else
3739                         rc = -ENOMEM;
3740
3741                 if (rc)
3742                         RETURN(rc);
3743
3744                 LASSERT(ms->ms_server_seq != NULL);
3745                 rc = seq_server_set_cli(ms->ms_server_seq, ms->ms_client_seq,
3746                                         env);
3747         }
3748
3749         RETURN(rc);
3750 }
3751
3752 static void mdt_seq_fini_cli(struct mdt_device *m)
3753 {
3754         struct md_site *ms;
3755
3756         ENTRY;
3757
3758         ms = mdt_md_site(m);
3759
3760         if (ms != NULL) {
3761                 if (ms->ms_server_seq)
3762                         seq_server_set_cli(ms->ms_server_seq,
3763                                    NULL, NULL);
3764
3765                 if (ms->ms_control_exp) {
3766                         class_export_put(ms->ms_control_exp);
3767                         ms->ms_control_exp = NULL;
3768                 }
3769         }
3770         EXIT;
3771 }
3772
3773 /*
3774  * FLD wrappers
3775  */
3776 static int mdt_fld_fini(const struct lu_env *env,
3777                         struct mdt_device *m)
3778 {
3779         struct md_site *ms = mdt_md_site(m);
3780         ENTRY;
3781
3782         if (ms && ms->ms_server_fld) {
3783                 fld_server_fini(ms->ms_server_fld, env);
3784                 OBD_FREE_PTR(ms->ms_server_fld);
3785                 ms->ms_server_fld = NULL;
3786         }
3787
3788         RETURN(0);
3789 }
3790
3791 static int mdt_fld_init(const struct lu_env *env,
3792                         const char *uuid,
3793                         struct mdt_device *m)
3794 {
3795         struct md_site *ms;
3796         int rc;
3797         ENTRY;
3798
3799         ms = mdt_md_site(m);
3800
3801         OBD_ALLOC_PTR(ms->ms_server_fld);
3802         if (ms->ms_server_fld == NULL)
3803                 RETURN(rc = -ENOMEM);
3804
3805         rc = fld_server_init(ms->ms_server_fld,
3806                              m->mdt_bottom, uuid,
3807                              env, ms->ms_node_id);
3808         if (rc) {
3809                 OBD_FREE_PTR(ms->ms_server_fld);
3810                 ms->ms_server_fld = NULL;
3811                 RETURN(rc);
3812         }
3813
3814         RETURN(0);
3815 }
3816
3817 /* device init/fini methods */
3818 static void mdt_stop_ptlrpc_service(struct mdt_device *m)
3819 {
3820         ENTRY;
3821         if (m->mdt_regular_service != NULL) {
3822                 ptlrpc_unregister_service(m->mdt_regular_service);
3823                 m->mdt_regular_service = NULL;
3824         }
3825         if (m->mdt_readpage_service != NULL) {
3826                 ptlrpc_unregister_service(m->mdt_readpage_service);
3827                 m->mdt_readpage_service = NULL;
3828         }
3829         if (m->mdt_xmds_service != NULL) {
3830                 ptlrpc_unregister_service(m->mdt_xmds_service);
3831                 m->mdt_xmds_service = NULL;
3832         }
3833         if (m->mdt_setattr_service != NULL) {
3834                 ptlrpc_unregister_service(m->mdt_setattr_service);
3835                 m->mdt_setattr_service = NULL;
3836         }
3837         if (m->mdt_mdsc_service != NULL) {
3838                 ptlrpc_unregister_service(m->mdt_mdsc_service);
3839                 m->mdt_mdsc_service = NULL;
3840         }
3841         if (m->mdt_mdss_service != NULL) {
3842                 ptlrpc_unregister_service(m->mdt_mdss_service);
3843                 m->mdt_mdss_service = NULL;
3844         }
3845         if (m->mdt_dtss_service != NULL) {
3846                 ptlrpc_unregister_service(m->mdt_dtss_service);
3847                 m->mdt_dtss_service = NULL;
3848         }
3849         if (m->mdt_fld_service != NULL) {
3850                 ptlrpc_unregister_service(m->mdt_fld_service);
3851                 m->mdt_fld_service = NULL;
3852         }
3853         EXIT;
3854 }
3855
3856 static int mdt_start_ptlrpc_service(struct mdt_device *m)
3857 {
3858         int rc;
3859         static struct ptlrpc_service_conf conf;
3860         cfs_proc_dir_entry_t *procfs_entry;
3861         ENTRY;
3862
3863         procfs_entry = m->mdt_md_dev.md_lu_dev.ld_obd->obd_proc_entry;
3864
3865         conf = (typeof(conf)) {
3866                 .psc_nbufs           = MDS_NBUFS,
3867                 .psc_bufsize         = MDS_BUFSIZE,
3868                 .psc_max_req_size    = MDS_MAXREQSIZE,
3869                 .psc_max_reply_size  = MDS_MAXREPSIZE,
3870                 .psc_req_portal      = MDS_REQUEST_PORTAL,
3871                 .psc_rep_portal      = MDC_REPLY_PORTAL,
3872                 .psc_watchdog_factor = MDT_SERVICE_WATCHDOG_FACTOR,
3873                 /*
3874                  * We'd like to have a mechanism to set this on a per-device
3875                  * basis, but alas...
3876                  */
3877                 .psc_min_threads    = min(max(mdt_num_threads, MDT_MIN_THREADS),
3878                                           MDT_MAX_THREADS),
3879                 .psc_max_threads     = MDT_MAX_THREADS,
3880                 .psc_ctx_tags        = LCT_MD_THREAD
3881         };
3882
3883         m->mdt_ldlm_client = &m->mdt_md_dev.md_lu_dev.ld_obd->obd_ldlm_client;
3884         ptlrpc_init_client(LDLM_CB_REQUEST_PORTAL, LDLM_CB_REPLY_PORTAL,
3885                            "mdt_ldlm_client", m->mdt_ldlm_client);
3886
3887         m->mdt_regular_service =
3888                 ptlrpc_init_svc_conf(&conf, mdt_regular_handle, LUSTRE_MDT_NAME,
3889                                      procfs_entry, target_print_req,
3890                                      LUSTRE_MDT_NAME);
3891         if (m->mdt_regular_service == NULL)
3892                 RETURN(-ENOMEM);
3893
3894         rc = ptlrpc_start_threads(NULL, m->mdt_regular_service);
3895         if (rc)
3896                 GOTO(err_mdt_svc, rc);
3897
3898         /*
3899          * readpage service configuration. Parameters have to be adjusted,
3900          * ideally.
3901          */
3902         conf = (typeof(conf)) {
3903                 .psc_nbufs           = MDS_NBUFS,
3904                 .psc_bufsize         = MDS_BUFSIZE,
3905                 .psc_max_req_size    = MDS_MAXREQSIZE,
3906                 .psc_max_reply_size  = MDS_MAXREPSIZE,
3907                 .psc_req_portal      = MDS_READPAGE_PORTAL,
3908                 .psc_rep_portal      = MDC_REPLY_PORTAL,
3909                 .psc_watchdog_factor = MDT_SERVICE_WATCHDOG_FACTOR,
3910                 .psc_min_threads    = min(max(mdt_num_threads, MDT_MIN_THREADS),
3911                                           MDT_MAX_THREADS),
3912                 .psc_max_threads     = MDT_MAX_THREADS,
3913                 .psc_ctx_tags        = LCT_MD_THREAD
3914         };
3915         m->mdt_readpage_service =
3916                 ptlrpc_init_svc_conf(&conf, mdt_readpage_handle,
3917                                      LUSTRE_MDT_NAME "_readpage",
3918                                      procfs_entry, target_print_req,"mdt_rdpg");
3919
3920         if (m->mdt_readpage_service == NULL) {
3921                 CERROR("failed to start readpage service\n");
3922                 GOTO(err_mdt_svc, rc = -ENOMEM);
3923         }
3924
3925         rc = ptlrpc_start_threads(NULL, m->mdt_readpage_service);
3926
3927         /*
3928          * setattr service configuration.
3929          */
3930         conf = (typeof(conf)) {
3931                 .psc_nbufs           = MDS_NBUFS,
3932                 .psc_bufsize         = MDS_BUFSIZE,
3933                 .psc_max_req_size    = MDS_MAXREQSIZE,
3934                 .psc_max_reply_size  = MDS_MAXREPSIZE,
3935                 .psc_req_portal      = MDS_SETATTR_PORTAL,
3936                 .psc_rep_portal      = MDC_REPLY_PORTAL,
3937                 .psc_watchdog_factor = MDT_SERVICE_WATCHDOG_FACTOR,
3938                 .psc_min_threads   = min(max(mdt_num_threads, MDT_MIN_THREADS),
3939                                          MDT_MAX_THREADS),
3940                 .psc_max_threads     = MDT_MAX_THREADS,
3941                 .psc_ctx_tags        = LCT_MD_THREAD
3942         };
3943
3944         m->mdt_setattr_service =
3945                 ptlrpc_init_svc_conf(&conf, mdt_regular_handle,
3946                                      LUSTRE_MDT_NAME "_setattr",
3947                                      procfs_entry, target_print_req,"mdt_attr");
3948
3949         if (!m->mdt_setattr_service) {
3950                 CERROR("failed to start setattr service\n");
3951                 GOTO(err_mdt_svc, rc = -ENOMEM);
3952         }
3953
3954         rc = ptlrpc_start_threads(NULL, m->mdt_setattr_service);
3955         if (rc)
3956                 GOTO(err_mdt_svc, rc);
3957
3958         /*
3959          * sequence controller service configuration
3960          */
3961         conf = (typeof(conf)) {
3962                 .psc_nbufs           = MDS_NBUFS,
3963                 .psc_bufsize         = MDS_BUFSIZE,
3964                 .psc_max_req_size    = SEQ_MAXREQSIZE,
3965                 .psc_max_reply_size  = SEQ_MAXREPSIZE,
3966                 .psc_req_portal      = SEQ_CONTROLLER_PORTAL,
3967                 .psc_rep_portal      = MDC_REPLY_PORTAL,
3968                 .psc_watchdog_factor = MDT_SERVICE_WATCHDOG_FACTOR,
3969                 .psc_min_threads     = SEQ_NUM_THREADS,
3970                 .psc_max_threads     = SEQ_NUM_THREADS,
3971                 .psc_ctx_tags        = LCT_MD_THREAD|LCT_DT_THREAD
3972         };
3973
3974         m->mdt_mdsc_service =
3975                 ptlrpc_init_svc_conf(&conf, mdt_mdsc_handle,
3976                                      LUSTRE_MDT_NAME"_mdsc",
3977                                      procfs_entry, target_print_req,"mdt_mdsc");
3978         if (!m->mdt_mdsc_service) {
3979                 CERROR("failed to start seq controller service\n");
3980                 GOTO(err_mdt_svc, rc = -ENOMEM);
3981         }
3982
3983         rc = ptlrpc_start_threads(NULL, m->mdt_mdsc_service);
3984         if (rc)
3985                 GOTO(err_mdt_svc, rc);
3986
3987         /*
3988          * metadata sequence server service configuration
3989          */
3990         conf = (typeof(conf)) {
3991                 .psc_nbufs           = MDS_NBUFS,
3992                 .psc_bufsize         = MDS_BUFSIZE,
3993                 .psc_max_req_size    = SEQ_MAXREQSIZE,
3994                 .psc_max_reply_size  = SEQ_MAXREPSIZE,
3995                 .psc_req_portal      = SEQ_METADATA_PORTAL,
3996                 .psc_rep_portal      = MDC_REPLY_PORTAL,
3997                 .psc_watchdog_factor = MDT_SERVICE_WATCHDOG_FACTOR,
3998                 .psc_min_threads     = SEQ_NUM_THREADS,
3999                 .psc_max_threads     = SEQ_NUM_THREADS,
4000                 .psc_ctx_tags        = LCT_MD_THREAD|LCT_DT_THREAD
4001         };
4002
4003         m->mdt_mdss_service =
4004                 ptlrpc_init_svc_conf(&conf, mdt_mdss_handle,
4005                                      LUSTRE_MDT_NAME"_mdss",
4006                                      procfs_entry, target_print_req,"mdt_mdss");
4007         if (!m->mdt_mdss_service) {
4008                 CERROR("failed to start metadata seq server service\n");
4009                 GOTO(err_mdt_svc, rc = -ENOMEM);
4010         }
4011
4012         rc = ptlrpc_start_threads(NULL, m->mdt_mdss_service);
4013         if (rc)
4014                 GOTO(err_mdt_svc, rc);
4015
4016
4017         /*
4018          * Data sequence server service configuration. We want to have really
4019          * cluster-wide sequences space. This is why we start only one sequence
4020          * controller which manages space.
4021          */
4022         conf = (typeof(conf)) {
4023                 .psc_nbufs           = MDS_NBUFS,
4024                 .psc_bufsize         = MDS_BUFSIZE,
4025                 .psc_max_req_size    = SEQ_MAXREQSIZE,
4026                 .psc_max_reply_size  = SEQ_MAXREPSIZE,
4027                 .psc_req_portal      = SEQ_DATA_PORTAL,
4028                 .psc_rep_portal      = OSC_REPLY_PORTAL,
4029                 .psc_watchdog_factor = MDT_SERVICE_WATCHDOG_FACTOR,
4030                 .psc_min_threads     = SEQ_NUM_THREADS,
4031                 .psc_max_threads     = SEQ_NUM_THREADS,
4032                 .psc_ctx_tags        = LCT_MD_THREAD|LCT_DT_THREAD
4033         };
4034
4035         m->mdt_dtss_service =
4036                 ptlrpc_init_svc_conf(&conf, mdt_dtss_handle,
4037                                      LUSTRE_MDT_NAME"_dtss",
4038                                      procfs_entry, target_print_req,"mdt_dtss");
4039         if (!m->mdt_dtss_service) {
4040                 CERROR("failed to start data seq server service\n");
4041                 GOTO(err_mdt_svc, rc = -ENOMEM);
4042         }
4043
4044         rc = ptlrpc_start_threads(NULL, m->mdt_dtss_service);
4045         if (rc)
4046                 GOTO(err_mdt_svc, rc);
4047
4048         /* FLD service start */
4049         conf = (typeof(conf)) {
4050                 .psc_nbufs           = MDS_NBUFS,
4051                 .psc_bufsize         = MDS_BUFSIZE,
4052                 .psc_max_req_size    = FLD_MAXREQSIZE,
4053                 .psc_max_reply_size  = FLD_MAXREPSIZE,
4054                 .psc_req_portal      = FLD_REQUEST_PORTAL,
4055                 .psc_rep_portal      = MDC_REPLY_PORTAL,
4056                 .psc_watchdog_factor = MDT_SERVICE_WATCHDOG_FACTOR,
4057                 .psc_min_threads     = FLD_NUM_THREADS,
4058                 .psc_max_threads     = FLD_NUM_THREADS,
4059                 .psc_ctx_tags        = LCT_DT_THREAD|LCT_MD_THREAD
4060         };
4061
4062         m->mdt_fld_service =
4063                 ptlrpc_init_svc_conf(&conf, mdt_fld_handle,
4064                                      LUSTRE_MDT_NAME"_fld",
4065                                      procfs_entry, target_print_req, "mdt_fld");
4066         if (!m->mdt_fld_service) {
4067                 CERROR("failed to start fld service\n");
4068                 GOTO(err_mdt_svc, rc = -ENOMEM);
4069         }
4070
4071         rc = ptlrpc_start_threads(NULL, m->mdt_fld_service);
4072         if (rc)
4073                 GOTO(err_mdt_svc, rc);
4074
4075         /*
4076          * mds-mds service configuration. Separate portal is used to allow
4077          * mds-mds requests be not blocked during recovery.
4078          */
4079         conf = (typeof(conf)) {
4080                 .psc_nbufs           = MDS_NBUFS,
4081                 .psc_bufsize         = MDS_BUFSIZE,
4082                 .psc_max_req_size    = MDS_MAXREQSIZE,
4083                 .psc_max_reply_size  = MDS_MAXREPSIZE,
4084                 .psc_req_portal      = MDS_MDS_PORTAL,
4085                 .psc_rep_portal      = MDC_REPLY_PORTAL,
4086                 .psc_watchdog_factor = MDT_SERVICE_WATCHDOG_FACTOR,
4087                 .psc_min_threads    = min(max(mdt_num_threads, MDT_MIN_THREADS),
4088                                           MDT_MAX_THREADS),
4089                 .psc_max_threads     = MDT_MAX_THREADS,
4090                 .psc_ctx_tags        = LCT_MD_THREAD
4091         };
4092         m->mdt_xmds_service =
4093                 ptlrpc_init_svc_conf(&conf, mdt_xmds_handle,
4094                                      LUSTRE_MDT_NAME "_mds",
4095                                      procfs_entry, target_print_req,"mdt_xmds");
4096
4097         if (m->mdt_xmds_service == NULL) {
4098                 CERROR("failed to start readpage service\n");
4099                 GOTO(err_mdt_svc, rc = -ENOMEM);
4100         }
4101
4102         rc = ptlrpc_start_threads(NULL, m->mdt_xmds_service);
4103         if (rc)
4104                 GOTO(err_mdt_svc, rc);
4105
4106         EXIT;
4107 err_mdt_svc:
4108         if (rc)
4109                 mdt_stop_ptlrpc_service(m);
4110
4111         return rc;
4112 }
4113
4114 static void mdt_stack_fini(const struct lu_env *env,
4115                            struct mdt_device *m, struct lu_device *top)
4116 {
4117         struct obd_device       *obd = mdt2obd_dev(m);
4118         struct lustre_cfg_bufs  *bufs;
4119         struct lustre_cfg       *lcfg;
4120         struct mdt_thread_info  *info;
4121         char flags[3]="";
4122         ENTRY;
4123
4124         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
4125         LASSERT(info != NULL);
4126
4127         bufs = &info->mti_u.bufs;
4128         /* process cleanup, pass mdt obd name to get obd umount flags */
4129         lustre_cfg_bufs_reset(bufs, obd->obd_name);
4130         if (obd->obd_force)
4131                 strcat(flags, "F");
4132         if (obd->obd_fail)
4133                 strcat(flags, "A");
4134         lustre_cfg_bufs_set_string(bufs, 1, flags);
4135         lcfg = lustre_cfg_new(LCFG_CLEANUP, bufs);
4136         if (!lcfg) {
4137                 CERROR("Cannot alloc lcfg!\n");
4138                 return;
4139         }
4140
4141         LASSERT(top);
4142         top->ld_ops->ldo_process_config(env, top, lcfg);
4143         lustre_cfg_free(lcfg);
4144
4145         lu_stack_fini(env, top);
4146         m->mdt_child = NULL;
4147         m->mdt_bottom = NULL;
4148 }
4149
4150 static struct lu_device *mdt_layer_setup(struct lu_env *env,
4151                                          const char *typename,
4152                                          struct lu_device *child,
4153                                          struct lustre_cfg *cfg)
4154 {
4155         const char            *dev = lustre_cfg_string(cfg, 0);
4156         struct obd_type       *type;
4157         struct lu_device_type *ldt;
4158         struct lu_device      *d;
4159         int rc;
4160         ENTRY;
4161
4162         /* find the type */
4163         type = class_get_type(typename);
4164         if (!type) {
4165                 CERROR("Unknown type: '%s'\n", typename);
4166                 GOTO(out, rc = -ENODEV);
4167         }
4168
4169         rc = lu_env_refill((struct lu_env *)env);
4170         if (rc != 0) {
4171                 CERROR("Failure to refill session: '%d'\n", rc);
4172                 GOTO(out_type, rc);
4173         }
4174
4175         ldt = type->typ_lu;
4176         if (ldt == NULL) {
4177                 CERROR("type: '%s'\n", typename);
4178                 GOTO(out_type, rc = -EINVAL);
4179         }
4180
4181         ldt->ldt_obd_type = type;
4182         d = ldt->ldt_ops->ldto_device_alloc(env, ldt, cfg);
4183         if (IS_ERR(d)) {
4184                 CERROR("Cannot allocate device: '%s'\n", typename);
4185                 GOTO(out_type, rc = -ENODEV);
4186         }
4187
4188         LASSERT(child->ld_site);
4189         d->ld_site = child->ld_site;
4190
4191         type->typ_refcnt++;
4192         rc = ldt->ldt_ops->ldto_device_init(env, d, dev, child);
4193         if (rc) {
4194                 CERROR("can't init device '%s', rc %d\n", typename, rc);
4195                 GOTO(out_alloc, rc);
4196         }
4197         lu_device_get(d);
4198         lu_ref_add(&d->ld_reference, "lu-stack", &lu_site_init);
4199
4200         RETURN(d);
4201
4202 out_alloc:
4203         ldt->ldt_ops->ldto_device_free(env, d);
4204         type->typ_refcnt--;
4205 out_type:
4206         class_put_type(type);
4207 out:
4208         return ERR_PTR(rc);
4209 }
4210
4211 static int mdt_stack_init(struct lu_env *env,
4212                           struct mdt_device *m,
4213                           struct lustre_cfg *cfg,
4214                           struct lustre_mount_info  *lmi)
4215 {
4216         struct lu_device  *d = &m->mdt_md_dev.md_lu_dev;
4217         struct lu_device  *tmp;
4218         struct md_device  *md;
4219         struct lu_device  *child_lu_dev;
4220         int rc;
4221         ENTRY;
4222
4223         /* init the stack */
4224         tmp = mdt_layer_setup(env, LUSTRE_OSD_NAME, d, cfg);
4225         if (IS_ERR(tmp)) {
4226                 RETURN(PTR_ERR(tmp));
4227         }
4228         m->mdt_bottom = lu2dt_dev(tmp);
4229         d = tmp;
4230         tmp = mdt_layer_setup(env, LUSTRE_MDD_NAME, d, cfg);
4231         if (IS_ERR(tmp)) {
4232                 GOTO(out, rc = PTR_ERR(tmp));
4233         }
4234         d = tmp;
4235         md = lu2md_dev(d);
4236
4237         tmp = mdt_layer_setup(env, LUSTRE_CMM_NAME, d, cfg);
4238         if (IS_ERR(tmp)) {
4239                 GOTO(out, rc = PTR_ERR(tmp));
4240         }
4241         d = tmp;
4242         /*set mdd upcall device*/
4243         md_upcall_dev_set(md, lu2md_dev(d));
4244
4245         md = lu2md_dev(d);
4246         /*set cmm upcall device*/
4247         md_upcall_dev_set(md, &m->mdt_md_dev);
4248
4249         m->mdt_child = lu2md_dev(d);
4250
4251         /* process setup config */
4252         tmp = &m->mdt_md_dev.md_lu_dev;
4253         rc = tmp->ld_ops->ldo_process_config(env, tmp, cfg);
4254         if (rc)
4255                 GOTO(out, rc);
4256
4257         /* initialize local objects */
4258         child_lu_dev = &m->mdt_child->md_lu_dev;
4259
4260         rc = child_lu_dev->ld_ops->ldo_prepare(env,
4261                                                &m->mdt_md_dev.md_lu_dev,
4262                                                child_lu_dev);
4263 out:
4264         /* fini from last known good lu_device */
4265         if (rc)
4266                 mdt_stack_fini(env, m, d);
4267
4268         return rc;
4269 }
4270
4271 /**
4272  * setup CONFIG_ORIG context, used to access local config log.
4273  * this may need to be rewrite as part of llog rewrite for lu-api.
4274  */
4275 static int mdt_obd_llog_setup(struct obd_device *obd,
4276                               struct lustre_sb_info *lsi)
4277 {
4278         int     rc;
4279
4280         LASSERT(obd->obd_fsops == NULL);
4281
4282         obd->obd_fsops = fsfilt_get_ops(MT_STR(lsi->lsi_ldd));
4283         if (IS_ERR(obd->obd_fsops))
4284                 return PTR_ERR(obd->obd_fsops);
4285
4286         rc = fsfilt_setup(obd, lsi->lsi_srv_mnt->mnt_sb);
4287         if (rc) {
4288                 fsfilt_put_ops(obd->obd_fsops);
4289                 return rc;
4290         }
4291
4292         OBD_SET_CTXT_MAGIC(&obd->obd_lvfs_ctxt);
4293         obd->obd_lvfs_ctxt.pwdmnt = lsi->lsi_srv_mnt;
4294         obd->obd_lvfs_ctxt.pwd = lsi->lsi_srv_mnt->mnt_root;
4295         obd->obd_lvfs_ctxt.fs = get_ds();
4296
4297         rc = llog_setup(obd, &obd->obd_olg, LLOG_CONFIG_ORIG_CTXT, obd,
4298                         0, NULL, &llog_lvfs_ops);
4299         if (rc) {
4300                 CERROR("llog_setup() failed: %d\n", rc);
4301                 fsfilt_put_ops(obd->obd_fsops);
4302         }
4303
4304         return rc;
4305 }
4306
4307 static void mdt_obd_llog_cleanup(struct obd_device *obd)
4308 {
4309         struct llog_ctxt *ctxt;
4310
4311         ctxt = llog_get_context(obd, LLOG_CONFIG_ORIG_CTXT);
4312         if (ctxt)
4313                 llog_cleanup(ctxt);
4314
4315         if (obd->obd_fsops) {
4316                 fsfilt_put_ops(obd->obd_fsops);
4317                 obd->obd_fsops = NULL;
4318         }
4319 }
4320
4321 static void mdt_fini(const struct lu_env *env, struct mdt_device *m)
4322 {
4323         struct md_device  *next = m->mdt_child;
4324         struct lu_device  *d    = &m->mdt_md_dev.md_lu_dev;
4325         struct lu_site    *ls   = d->ld_site;
4326         struct obd_device *obd = mdt2obd_dev(m);
4327         ENTRY;
4328
4329         target_recovery_fini(obd);
4330
4331         ping_evictor_stop();
4332
4333         mdt_stop_ptlrpc_service(m);
4334         mdt_llog_ctxt_unclone(env, m, LLOG_CHANGELOG_ORIG_CTXT);
4335         mdt_obd_llog_cleanup(obd);
4336         obd_exports_barrier(obd);
4337         obd_zombie_barrier();
4338 #ifdef HAVE_QUOTA_SUPPORT
4339         next->md_ops->mdo_quota.mqo_cleanup(env, next);
4340 #endif
4341         lut_fini(env, &m->mdt_lut);
4342         mdt_fs_cleanup(env, m);
4343         upcall_cache_cleanup(m->mdt_identity_cache);
4344         m->mdt_identity_cache = NULL;
4345
4346         if (m->mdt_namespace != NULL) {
4347                 ldlm_namespace_free(m->mdt_namespace, NULL,
4348                                     d->ld_obd->obd_force);
4349                 d->ld_obd->obd_namespace = m->mdt_namespace = NULL;
4350         }
4351
4352         cfs_free_nidlist(&m->mdt_nosquash_nids);
4353         if (m->mdt_nosquash_str) {
4354                 OBD_FREE(m->mdt_nosquash_str, m->mdt_nosquash_strlen);
4355                 m->mdt_nosquash_str = NULL;
4356                 m->mdt_nosquash_strlen = 0;
4357         }
4358
4359         mdt_seq_fini(env, m);
4360         mdt_seq_fini_cli(m);
4361         mdt_fld_fini(env, m);
4362         sptlrpc_rule_set_free(&m->mdt_sptlrpc_rset);
4363
4364         next->md_ops->mdo_init_capa_ctxt(env, next, 0, 0, 0, NULL);
4365         cfs_timer_disarm(&m->mdt_ck_timer);
4366         mdt_ck_thread_stop(m);
4367
4368         /*
4369          * Finish the stack
4370          */
4371         mdt_stack_fini(env, m, md2lu_dev(m->mdt_child));
4372
4373         mdt_procfs_fini(m);
4374         if (obd->obd_proc_exports_entry) {
4375                 lprocfs_remove_proc_entry("clear", obd->obd_proc_exports_entry);
4376                 obd->obd_proc_exports_entry = NULL;
4377         }
4378         lprocfs_free_per_client_stats(obd);
4379         lprocfs_free_obd_stats(obd);
4380         ptlrpc_lprocfs_unregister_obd(obd);
4381         lprocfs_obd_cleanup(obd);
4382
4383         if (ls) {
4384                 struct md_site *mite;
4385
4386                 lu_site_fini(ls);
4387                 mite = lu_site2md(ls);
4388                 OBD_FREE_PTR(mite);
4389                 d->ld_site = NULL;
4390         }
4391         LASSERT(atomic_read(&d->ld_ref) == 0);
4392
4393         EXIT;
4394 }
4395
4396 static int mdt_adapt_sptlrpc_conf(struct obd_device *obd, int initial)
4397 {
4398         struct mdt_device       *m = mdt_dev(obd->obd_lu_dev);
4399         struct sptlrpc_rule_set  tmp_rset;
4400         int                      rc;
4401
4402         sptlrpc_rule_set_init(&tmp_rset);
4403         rc = sptlrpc_conf_target_get_rules(obd, &tmp_rset, initial);
4404         if (rc) {
4405                 CERROR("mdt %s: failed get sptlrpc rules: %d\n",
4406                        obd->obd_name, rc);
4407                 return rc;
4408         }
4409
4410         sptlrpc_target_update_exp_flavor(obd, &tmp_rset);
4411
4412         write_lock(&m->mdt_sptlrpc_lock);
4413         sptlrpc_rule_set_free(&m->mdt_sptlrpc_rset);
4414         m->mdt_sptlrpc_rset = tmp_rset;
4415         write_unlock(&m->mdt_sptlrpc_lock);
4416
4417         return 0;
4418 }
4419
4420 static void fsoptions_to_mdt_flags(struct mdt_device *m, char *options)
4421 {
4422         char *p = options;
4423
4424         m->mdt_opts.mo_mds_capa = 1;
4425         m->mdt_opts.mo_oss_capa = 1;
4426 #ifdef CONFIG_FS_POSIX_ACL
4427         /* ACLs should be enabled by default (b=13829) */
4428         m->mdt_opts.mo_acl = 1;
4429         LCONSOLE_INFO("Enabling ACL\n");
4430 #else
4431         m->mdt_opts.mo_acl = 0;
4432         LCONSOLE_INFO("Disabling ACL\n");
4433 #endif
4434
4435         if (!options)
4436                 return;
4437
4438         while (*options) {
4439                 int len;
4440
4441                 while (*p && *p != ',')
4442                         p++;
4443
4444                 len = p - options;
4445                 if ((len == sizeof("user_xattr") - 1) &&
4446                     (memcmp(options, "user_xattr", len) == 0)) {
4447                         m->mdt_opts.mo_user_xattr = 1;
4448                         LCONSOLE_INFO("Enabling user_xattr\n");
4449                 } else if ((len == sizeof("nouser_xattr") - 1) &&
4450                            (memcmp(options, "nouser_xattr", len) == 0)) {
4451                         m->mdt_opts.mo_user_xattr = 0;
4452                         LCONSOLE_INFO("Disabling user_xattr\n");
4453                 } else if ((len == sizeof("noacl") - 1) &&
4454                            (memcmp(options, "noacl", len) == 0)) {
4455                         m->mdt_opts.mo_acl = 0;
4456                         LCONSOLE_INFO("Disabling ACL\n");
4457                 }
4458
4459                 options = ++p;
4460         }
4461 }
4462
4463 int mdt_postrecov(const struct lu_env *, struct mdt_device *);
4464
4465 static int mdt_init0(const struct lu_env *env, struct mdt_device *m,
4466                      struct lu_device_type *ldt, struct lustre_cfg *cfg)
4467 {
4468         struct lprocfs_static_vars lvars;
4469         struct mdt_thread_info    *info;
4470         struct obd_device         *obd;
4471         const char                *dev = lustre_cfg_string(cfg, 0);
4472         const char                *num = lustre_cfg_string(cfg, 2);
4473         struct lustre_mount_info  *lmi = NULL;
4474         struct lustre_sb_info     *lsi;
4475         struct lustre_disk_data   *ldd;
4476         struct lu_site            *s;
4477         struct md_site            *mite;
4478         const char                *identity_upcall = "NONE";
4479 #ifdef HAVE_QUOTA_SUPPORT
4480         struct md_device          *next;
4481 #endif
4482         int                        rc;
4483         int                        node_id;
4484         ENTRY;
4485
4486         md_device_init(&m->mdt_md_dev, ldt);
4487         /*
4488          * Environment (env) might be missing mdt_thread_key values at that
4489          * point, if device is allocated when mdt_thread_key is in QUIESCENT
4490          * mode.
4491          *
4492          * Usually device allocation path doesn't use module key values, but
4493          * mdt has to do a lot of work here, so allocate key value.
4494          */
4495         rc = lu_env_refill((struct lu_env *)env);
4496         if (rc != 0)
4497                 RETURN(rc);
4498
4499         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
4500         LASSERT(info != NULL);
4501
4502         obd = class_name2obd(dev);
4503         LASSERT(obd != NULL);
4504
4505         spin_lock_init(&m->mdt_transno_lock);
4506
4507         m->mdt_max_mdsize = MAX_MD_SIZE;
4508         m->mdt_max_cookiesize = sizeof(struct llog_cookie);
4509         m->mdt_som_conf = 0;
4510
4511         m->mdt_opts.mo_user_xattr = 0;
4512         m->mdt_opts.mo_acl = 0;
4513         m->mdt_opts.mo_cos = MDT_COS_DEFAULT;
4514         lmi = server_get_mount_2(dev);
4515         if (lmi == NULL) {
4516                 CERROR("Cannot get mount info for %s!\n", dev);
4517                 RETURN(-EFAULT);
4518         } else {
4519                 lsi = s2lsi(lmi->lmi_sb);
4520                 fsoptions_to_mdt_flags(m, lsi->lsi_lmd->lmd_opts);
4521                 /* CMD is supported only in IAM mode */
4522                 ldd = lsi->lsi_ldd;
4523                 LASSERT(num);
4524                 node_id = simple_strtol(num, NULL, 10);
4525                 if (!(ldd->ldd_flags & LDD_F_IAM_DIR) && node_id) {
4526                         CERROR("CMD Operation not allowed in IOP mode\n");
4527                         GOTO(err_lmi, rc = -EINVAL);
4528                 }
4529         }
4530
4531         rwlock_init(&m->mdt_sptlrpc_lock);
4532         sptlrpc_rule_set_init(&m->mdt_sptlrpc_rset);
4533
4534         spin_lock_init(&m->mdt_ioepoch_lock);
4535         m->mdt_opts.mo_compat_resname = 0;
4536         m->mdt_capa_timeout = CAPA_TIMEOUT;
4537         m->mdt_capa_alg = CAPA_HMAC_ALG_SHA1;
4538         m->mdt_ck_timeout = CAPA_KEY_TIMEOUT;
4539         m->mdt_squash_uid = 0;
4540         m->mdt_squash_gid = 0;
4541         CFS_INIT_LIST_HEAD(&m->mdt_nosquash_nids);
4542         m->mdt_nosquash_str = NULL;
4543         m->mdt_nosquash_strlen = 0;
4544         init_rwsem(&m->mdt_squash_sem);
4545
4546         spin_lock_init(&m->mdt_client_bitmap_lock);
4547
4548         OBD_ALLOC_PTR(mite);
4549         if (mite == NULL)
4550                 GOTO(err_lmi, rc = -ENOMEM);
4551
4552         s = &mite->ms_lu;
4553
4554         m->mdt_md_dev.md_lu_dev.ld_ops = &mdt_lu_ops;
4555         m->mdt_md_dev.md_lu_dev.ld_obd = obd;
4556         /* set this lu_device to obd, because error handling need it */
4557         obd->obd_lu_dev = &m->mdt_md_dev.md_lu_dev;
4558
4559         rc = lu_site_init(s, &m->mdt_md_dev.md_lu_dev);
4560         if (rc) {
4561                 CERROR("Can't init lu_site, rc %d\n", rc);
4562                 GOTO(err_free_site, rc);
4563         }
4564
4565         lprocfs_mdt_init_vars(&lvars);
4566         rc = lprocfs_obd_setup(obd, lvars.obd_vars);
4567         if (rc) {
4568                 CERROR("Can't init lprocfs, rc %d\n", rc);
4569                 GOTO(err_fini_site, rc);
4570         }
4571         ptlrpc_lprocfs_register_obd(obd);
4572
4573         rc = mdt_procfs_init(m, dev);
4574         if (rc) {
4575                 CERROR("Can't init MDT lprocfs, rc %d\n", rc);
4576                 GOTO(err_fini_proc, rc);
4577         }
4578
4579         obd->obd_proc_exports_entry = proc_mkdir("exports",
4580                                                  obd->obd_proc_entry);
4581         if (obd->obd_proc_exports_entry)
4582                 lprocfs_add_simple(obd->obd_proc_exports_entry,
4583                                    "clear", lprocfs_nid_stats_clear_read,
4584                                    lprocfs_nid_stats_clear_write, obd, NULL);
4585
4586         /* set server index */
4587         lu_site2md(s)->ms_node_id = node_id;
4588
4589         /* failover is the default
4590          * FIXME: we do not failout mds0/mgs, which may cause some problems.
4591          * assumed whose ms_node_id == 0 XXX
4592          * */
4593         obd->obd_replayable = 1;
4594         /* No connection accepted until configurations will finish */
4595         obd->obd_no_conn = 1;
4596
4597         if (cfg->lcfg_bufcount > 4 && LUSTRE_CFG_BUFLEN(cfg, 4) > 0) {
4598                 char *str = lustre_cfg_string(cfg, 4);
4599                 if (strchr(str, 'n')) {
4600                         CWARN("%s: recovery disabled\n", obd->obd_name);
4601                         obd->obd_replayable = 0;
4602                 }
4603         }
4604
4605         /* init the stack */
4606         rc = mdt_stack_init((struct lu_env *)env, m, cfg, lmi);
4607         if (rc) {
4608                 CERROR("Can't init device stack, rc %d\n", rc);
4609                 GOTO(err_fini_proc, rc);
4610         }
4611
4612         rc = lut_init(env, &m->mdt_lut, obd, m->mdt_bottom);
4613         if (rc)
4614                 GOTO(err_fini_stack, rc);
4615
4616         rc = mdt_fld_init(env, obd->obd_name, m);
4617         if (rc)
4618                 GOTO(err_lut, rc);
4619
4620         rc = mdt_seq_init(env, obd->obd_name, m);
4621         if (rc)
4622                 GOTO(err_fini_fld, rc);
4623
4624         snprintf(info->mti_u.ns_name, sizeof info->mti_u.ns_name,
4625                  LUSTRE_MDT_NAME"-%p", m);
4626         m->mdt_namespace = ldlm_namespace_new(obd, info->mti_u.ns_name,
4627                                               LDLM_NAMESPACE_SERVER,
4628                                               LDLM_NAMESPACE_GREEDY);
4629         if (m->mdt_namespace == NULL)
4630                 GOTO(err_fini_seq, rc = -ENOMEM);
4631
4632         ldlm_register_intent(m->mdt_namespace, mdt_intent_policy);
4633         /* set obd_namespace for compatibility with old code */
4634         obd->obd_namespace = m->mdt_namespace;
4635
4636         /* XXX: to support suppgid for ACL, we enable identity_upcall
4637          * by default, otherwise, maybe got unexpected -EACCESS. */
4638         if (m->mdt_opts.mo_acl)
4639                 identity_upcall = MDT_IDENTITY_UPCALL_PATH;
4640
4641         m->mdt_identity_cache = upcall_cache_init(obd->obd_name, identity_upcall,
4642                                                   &mdt_identity_upcall_cache_ops);
4643         if (IS_ERR(m->mdt_identity_cache)) {
4644                 rc = PTR_ERR(m->mdt_identity_cache);
4645                 m->mdt_identity_cache = NULL;
4646                 GOTO(err_free_ns, rc);
4647         }
4648
4649         cfs_timer_init(&m->mdt_ck_timer, mdt_ck_timer_callback, m);
4650
4651         rc = mdt_ck_thread_start(m);
4652         if (rc)
4653                 GOTO(err_free_ns, rc);
4654
4655         rc = mdt_fs_setup(env, m, obd, lsi);
4656         if (rc)
4657                 GOTO(err_capa, rc);
4658
4659         rc = mdt_obd_llog_setup(obd, lsi);
4660         if (rc)
4661                 GOTO(err_fs_cleanup, rc);
4662
4663         rc = mdt_llog_ctxt_clone(env, m, LLOG_CHANGELOG_ORIG_CTXT);
4664         if (rc)
4665                 GOTO(err_llog_cleanup, rc);
4666
4667         mdt_adapt_sptlrpc_conf(obd, 1);
4668
4669 #ifdef HAVE_QUOTA_SUPPORT
4670         next = m->mdt_child;
4671         rc = next->md_ops->mdo_quota.mqo_setup(env, next, lmi->lmi_mnt);
4672         if (rc)
4673                 GOTO(err_llog_cleanup, rc);
4674 #endif
4675
4676         server_put_mount_2(dev, lmi->lmi_mnt);
4677         lmi = NULL;
4678
4679         target_recovery_init(&m->mdt_lut, mdt_recovery_handle);
4680
4681         rc = mdt_start_ptlrpc_service(m);
4682         if (rc)
4683                 GOTO(err_recovery, rc);
4684
4685         ping_evictor_start();
4686
4687         rc = lu_site_init_finish(s);
4688         if (rc)
4689                 GOTO(err_stop_service, rc);
4690
4691         if (obd->obd_recovering == 0)
4692                 mdt_postrecov(env, m);
4693
4694         mdt_init_capa_ctxt(env, m);
4695
4696         /* Reduce the initial timeout on an MDS because it doesn't need such
4697          * a long timeout as an OST does. Adaptive timeouts will adjust this
4698          * value appropriately. */
4699         if (ldlm_timeout == LDLM_TIMEOUT_DEFAULT)
4700                 ldlm_timeout = MDS_LDLM_TIMEOUT_DEFAULT;
4701
4702         RETURN(0);
4703
4704 err_stop_service:
4705         ping_evictor_stop();
4706         mdt_stop_ptlrpc_service(m);
4707 err_recovery:
4708         target_recovery_fini(obd);
4709 #ifdef HAVE_QUOTA_SUPPORT
4710         next->md_ops->mdo_quota.mqo_cleanup(env, next);
4711 #endif
4712 err_llog_cleanup:
4713         mdt_llog_ctxt_unclone(env, m, LLOG_CHANGELOG_ORIG_CTXT);
4714         mdt_obd_llog_cleanup(obd);
4715 err_fs_cleanup:
4716         mdt_fs_cleanup(env, m);
4717 err_capa:
4718         cfs_timer_disarm(&m->mdt_ck_timer);
4719         mdt_ck_thread_stop(m);
4720 err_free_ns:
4721         upcall_cache_cleanup(m->mdt_identity_cache);
4722         m->mdt_identity_cache = NULL;
4723         ldlm_namespace_free(m->mdt_namespace, NULL, 0);
4724         obd->obd_namespace = m->mdt_namespace = NULL;
4725 err_fini_seq:
4726         mdt_seq_fini(env, m);
4727 err_fini_fld:
4728         mdt_fld_fini(env, m);
4729 err_lut:
4730         lut_fini(env, &m->mdt_lut);
4731 err_fini_stack:
4732         mdt_stack_fini(env, m, md2lu_dev(m->mdt_child));
4733 err_fini_proc:
4734         mdt_procfs_fini(m);
4735         if (obd->obd_proc_exports_entry) {
4736                 lprocfs_remove_proc_entry("clear", obd->obd_proc_exports_entry);
4737                 obd->obd_proc_exports_entry = NULL;
4738         }
4739         ptlrpc_lprocfs_unregister_obd(obd);
4740         lprocfs_obd_cleanup(obd);
4741 err_fini_site:
4742         lu_site_fini(s);
4743 err_free_site:
4744         OBD_FREE_PTR(mite);
4745 err_lmi:
4746         if (lmi)
4747                 server_put_mount_2(dev, lmi->lmi_mnt);
4748         return (rc);
4749 }
4750
4751 /* used by MGS to process specific configurations */
4752 static int mdt_process_config(const struct lu_env *env,
4753                               struct lu_device *d, struct lustre_cfg *cfg)
4754 {
4755         struct mdt_device *m = mdt_dev(d);
4756         struct md_device *md_next = m->mdt_child;
4757         struct lu_device *next = md2lu_dev(md_next);
4758         int rc = 0;
4759         ENTRY;
4760
4761         switch (cfg->lcfg_command) {
4762         case LCFG_PARAM: {
4763                 struct lprocfs_static_vars lvars;
4764                 struct obd_device *obd = d->ld_obd;
4765
4766                 /*
4767                  * For interoperability between 1.8 and 2.0,
4768                  * skip old "mdt.group_upcall" param.
4769                  */
4770                 {
4771                         char *param = lustre_cfg_string(cfg, 1);
4772                         if (param && !strncmp("mdt.group_upcall", param, 16)) {
4773                                 CWARN("For 1.8 interoperability, skip this"
4774                                        " mdt.group_upcall. It is obsolete\n");
4775                                 break;
4776                         }
4777                 }
4778
4779                 lprocfs_mdt_init_vars(&lvars);
4780                 rc = class_process_proc_param(PARAM_MDT, lvars.obd_vars,
4781                                               cfg, obd);
4782                 if (rc > 0 || rc == -ENOSYS)
4783                         /* we don't understand; pass it on */
4784                         rc = next->ld_ops->ldo_process_config(env, next, cfg);
4785                 break;
4786         }
4787         case LCFG_ADD_MDC:
4788                 /*
4789                  * Add mdc hook to get first MDT uuid and connect it to
4790                  * ls->controller to use for seq manager.
4791                  */
4792                 rc = next->ld_ops->ldo_process_config(env, next, cfg);
4793                 if (rc)
4794                         CERROR("Can't add mdc, rc %d\n", rc);
4795                 else
4796                         rc = mdt_seq_init_cli(env, mdt_dev(d), cfg);
4797                 break;
4798         default:
4799                 /* others are passed further */
4800                 rc = next->ld_ops->ldo_process_config(env, next, cfg);
4801                 break;
4802         }
4803         RETURN(rc);
4804 }
4805
4806 static struct lu_object *mdt_object_alloc(const struct lu_env *env,
4807                                           const struct lu_object_header *hdr,
4808                                           struct lu_device *d)
4809 {
4810         struct mdt_object *mo;
4811
4812         ENTRY;
4813
4814         OBD_ALLOC_PTR(mo);
4815         if (mo != NULL) {
4816                 struct lu_object *o;
4817                 struct lu_object_header *h;
4818
4819                 o = &mo->mot_obj.mo_lu;
4820                 h = &mo->mot_header;
4821                 lu_object_header_init(h);
4822                 lu_object_init(o, h, d);
4823                 lu_object_add_top(h, o);
4824                 o->lo_ops = &mdt_obj_ops;
4825                 RETURN(o);
4826         } else
4827                 RETURN(NULL);
4828 }
4829
4830 static int mdt_object_init(const struct lu_env *env, struct lu_object *o,
4831                            const struct lu_object_conf *unused)
4832 {
4833         struct mdt_device *d = mdt_dev(o->lo_dev);
4834         struct lu_device  *under;
4835         struct lu_object  *below;
4836         int                rc = 0;
4837         ENTRY;
4838
4839         CDEBUG(D_INFO, "object init, fid = "DFID"\n",
4840                PFID(lu_object_fid(o)));
4841
4842         under = &d->mdt_child->md_lu_dev;
4843         below = under->ld_ops->ldo_object_alloc(env, o->lo_header, under);
4844         if (below != NULL) {
4845                 lu_object_add(o, below);
4846         } else
4847                 rc = -ENOMEM;
4848
4849         RETURN(rc);
4850 }
4851
4852 static void mdt_object_free(const struct lu_env *env, struct lu_object *o)
4853 {
4854         struct mdt_object *mo = mdt_obj(o);
4855         struct lu_object_header *h;
4856         ENTRY;
4857
4858         h = o->lo_header;
4859         CDEBUG(D_INFO, "object free, fid = "DFID"\n",
4860                PFID(lu_object_fid(o)));
4861
4862         lu_object_fini(o);
4863         lu_object_header_fini(h);
4864         OBD_FREE_PTR(mo);
4865         EXIT;
4866 }
4867
4868 static int mdt_object_print(const struct lu_env *env, void *cookie,
4869                             lu_printer_t p, const struct lu_object *o)
4870 {
4871         struct mdt_object *mdto = mdt_obj((struct lu_object *)o);
4872         return (*p)(env, cookie, LUSTRE_MDT_NAME"-object@%p(ioepoch=%llu "
4873                     "flags=%llx, epochcount=%d, writecount=%d)",
4874                     mdto, mdto->mot_ioepoch, mdto->mot_flags,
4875                     mdto->mot_epochcount, mdto->mot_writecount);
4876 }
4877
4878 static const struct lu_device_operations mdt_lu_ops = {
4879         .ldo_object_alloc   = mdt_object_alloc,
4880         .ldo_process_config = mdt_process_config,
4881 };
4882
4883 static const struct lu_object_operations mdt_obj_ops = {
4884         .loo_object_init    = mdt_object_init,
4885         .loo_object_free    = mdt_object_free,
4886         .loo_object_print   = mdt_object_print
4887 };
4888
4889 static int mdt_obd_set_info_async(struct obd_export *exp,
4890                                   __u32 keylen, void *key,
4891                                   __u32 vallen, void *val,
4892                                   struct ptlrpc_request_set *set)
4893 {
4894         struct obd_device     *obd = exp->exp_obd;
4895         int                    rc;
4896         ENTRY;
4897
4898         LASSERT(obd);
4899
4900         if (KEY_IS(KEY_SPTLRPC_CONF)) {
4901                 rc = mdt_adapt_sptlrpc_conf(obd, 0);
4902                 RETURN(rc);
4903         }
4904
4905         RETURN(0);
4906 }
4907
4908 /* mds_connect_internal */
4909 static int mdt_connect_internal(struct obd_export *exp,
4910                                 struct mdt_device *mdt,
4911                                 struct obd_connect_data *data)
4912 {
4913         if (data != NULL) {
4914                 data->ocd_connect_flags &= MDT_CONNECT_SUPPORTED;
4915                 data->ocd_ibits_known &= MDS_INODELOCK_FULL;
4916
4917                 /* If no known bits (which should not happen, probably,
4918                    as everybody should support LOOKUP and UPDATE bits at least)
4919                    revert to compat mode with plain locks. */
4920                 if (!data->ocd_ibits_known &&
4921                     data->ocd_connect_flags & OBD_CONNECT_IBITS)
4922                         data->ocd_connect_flags &= ~OBD_CONNECT_IBITS;
4923
4924                 if (!mdt->mdt_opts.mo_acl)
4925                         data->ocd_connect_flags &= ~OBD_CONNECT_ACL;
4926
4927                 if (!mdt->mdt_opts.mo_user_xattr)
4928                         data->ocd_connect_flags &= ~OBD_CONNECT_XATTR;
4929
4930                 if (!mdt->mdt_som_conf)
4931                         data->ocd_connect_flags &= ~OBD_CONNECT_SOM;
4932
4933                 spin_lock(&exp->exp_lock);
4934                 exp->exp_connect_flags = data->ocd_connect_flags;
4935                 spin_unlock(&exp->exp_lock);
4936                 data->ocd_version = LUSTRE_VERSION_CODE;
4937                 exp->exp_mdt_data.med_ibits_known = data->ocd_ibits_known;
4938         }
4939
4940 #if 0
4941         if (mdt->mdt_opts.mo_acl &&
4942             ((exp->exp_connect_flags & OBD_CONNECT_ACL) == 0)) {
4943                 CWARN("%s: MDS requires ACL support but client does not\n",
4944                       mdt->mdt_md_dev.md_lu_dev.ld_obd->obd_name);
4945                 return -EBADE;
4946         }
4947 #endif
4948
4949         if ((exp->exp_connect_flags & OBD_CONNECT_FID) == 0) {
4950                 CWARN("%s: MDS requires FID support, but client not\n",
4951                       mdt->mdt_md_dev.md_lu_dev.ld_obd->obd_name);
4952                 return -EBADE;
4953         }
4954
4955         if (mdt->mdt_som_conf &&
4956             !(exp->exp_connect_flags & OBD_CONNECT_MDS_MDS) &&
4957             !(exp->exp_connect_flags & OBD_CONNECT_SOM)) {
4958                 CWARN("%s: MDS has SOM enabled, but client does not support "
4959                       "it\n", mdt->mdt_md_dev.md_lu_dev.ld_obd->obd_name);
4960                 return -EBADE;
4961         }
4962
4963         return 0;
4964 }
4965
4966 static int mdt_connect_check_sptlrpc(struct mdt_device *mdt,
4967                                      struct obd_export *exp,
4968                                      struct ptlrpc_request *req)
4969 {
4970         struct sptlrpc_flavor   flvr;
4971         int                     rc = 0;
4972
4973         if (exp->exp_flvr.sf_rpc == SPTLRPC_FLVR_INVALID) {
4974                 read_lock(&mdt->mdt_sptlrpc_lock);
4975                 sptlrpc_target_choose_flavor(&mdt->mdt_sptlrpc_rset,
4976                                              req->rq_sp_from,
4977                                              req->rq_peer.nid,
4978                                              &flvr);
4979                 read_unlock(&mdt->mdt_sptlrpc_lock);
4980
4981                 spin_lock(&exp->exp_lock);
4982
4983                 exp->exp_sp_peer = req->rq_sp_from;
4984                 exp->exp_flvr = flvr;
4985
4986                 if (exp->exp_flvr.sf_rpc != SPTLRPC_FLVR_ANY &&
4987                     exp->exp_flvr.sf_rpc != req->rq_flvr.sf_rpc) {
4988                         CERROR("unauthorized rpc flavor %x from %s, "
4989                                "expect %x\n", req->rq_flvr.sf_rpc,
4990                                libcfs_nid2str(req->rq_peer.nid),
4991                                exp->exp_flvr.sf_rpc);
4992                         rc = -EACCES;
4993                 }
4994
4995                 spin_unlock(&exp->exp_lock);
4996         } else {
4997                 if (exp->exp_sp_peer != req->rq_sp_from) {
4998                         CERROR("RPC source %s doesn't match %s\n",
4999                                sptlrpc_part2name(req->rq_sp_from),
5000                                sptlrpc_part2name(exp->exp_sp_peer));
5001                         rc = -EACCES;
5002                 } else {
5003                         rc = sptlrpc_target_export_check(exp, req);
5004                 }
5005         }
5006
5007         return rc;
5008 }
5009
5010 /* mds_connect copy */
5011 static int mdt_obd_connect(const struct lu_env *env,
5012                            struct obd_export **exp, struct obd_device *obd,
5013                            struct obd_uuid *cluuid,
5014                            struct obd_connect_data *data,
5015                            void *localdata)
5016 {
5017         struct mdt_thread_info *info;
5018         struct lsd_client_data *lcd;
5019         struct obd_export      *lexp;
5020         struct lustre_handle    conn = { 0 };
5021         struct mdt_device      *mdt;
5022         struct ptlrpc_request  *req;
5023         int                     rc;
5024         ENTRY;
5025
5026         LASSERT(env != NULL);
5027         if (!exp || !obd || !cluuid)
5028                 RETURN(-EINVAL);
5029
5030         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
5031         req = info->mti_pill->rc_req;
5032         mdt = mdt_dev(obd->obd_lu_dev);
5033
5034         rc = class_connect(&conn, obd, cluuid);
5035         if (rc)
5036                 RETURN(rc);
5037
5038         lexp = class_conn2export(&conn);
5039         LASSERT(lexp != NULL);
5040
5041         rc = mdt_connect_check_sptlrpc(mdt, lexp, req);
5042         if (rc)
5043                 GOTO(out, rc);
5044
5045         rc = mdt_connect_internal(lexp, mdt, data);
5046         if (rc == 0) {
5047                 OBD_ALLOC_PTR(lcd);
5048                 if (lcd != NULL) {
5049                         struct mdt_thread_info *mti;
5050                         mti = lu_context_key_get(&env->le_ctx,
5051                                                  &mdt_thread_key);
5052                         LASSERT(mti != NULL);
5053                         mti->mti_exp = lexp;
5054                         memcpy(lcd->lcd_uuid, cluuid, sizeof lcd->lcd_uuid);
5055                         lexp->exp_mdt_data.med_lcd = lcd;
5056                         rc = mdt_client_new(env, mdt);
5057                         if (rc != 0) {
5058                                 OBD_FREE_PTR(lcd);
5059                                 lexp->exp_mdt_data.med_lcd = NULL;
5060                         } else {
5061                                 mdt_export_stats_init(obd, lexp, localdata);
5062                         }
5063                 } else
5064                         rc = -ENOMEM;
5065         }
5066
5067 out:
5068         if (rc != 0)
5069                 class_disconnect(lexp);
5070         else
5071                 *exp = lexp;
5072
5073         RETURN(rc);
5074 }
5075
5076 static int mdt_obd_reconnect(const struct lu_env *env,
5077                              struct obd_export *exp, struct obd_device *obd,
5078                              struct obd_uuid *cluuid,
5079                              struct obd_connect_data *data,
5080                              void *localdata)
5081 {
5082         struct mdt_thread_info *info;
5083         struct mdt_device      *mdt;
5084         struct ptlrpc_request  *req;
5085         int                     rc;
5086         ENTRY;
5087
5088         if (exp == NULL || obd == NULL || cluuid == NULL)
5089                 RETURN(-EINVAL);
5090
5091         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
5092         req = info->mti_pill->rc_req;
5093         mdt = mdt_dev(obd->obd_lu_dev);
5094
5095         rc = mdt_connect_check_sptlrpc(mdt, exp, req);
5096         if (rc)
5097                 RETURN(rc);
5098
5099         rc = mdt_connect_internal(exp, mdt_dev(obd->obd_lu_dev), data);
5100         if (rc == 0)
5101                 mdt_export_stats_init(obd, exp, localdata);
5102
5103         RETURN(rc);
5104 }
5105 static int mdt_mfd_cleanup(struct obd_export *exp)
5106 {
5107         struct mdt_export_data *med = &exp->exp_mdt_data;
5108         struct obd_device      *obd = exp->exp_obd;
5109         struct mdt_device      *mdt;
5110         struct mdt_thread_info *info;
5111         struct lu_env           env;
5112         CFS_LIST_HEAD(closing_list);
5113         struct mdt_file_data *mfd, *n;
5114         int rc = 0;
5115         ENTRY;
5116
5117         spin_lock(&med->med_open_lock);
5118         while (!list_empty(&med->med_open_head)) {
5119                 struct list_head *tmp = med->med_open_head.next;
5120                 mfd = list_entry(tmp, struct mdt_file_data, mfd_list);
5121
5122                 /* Remove mfd handle so it can't be found again.
5123                  * We are consuming the mfd_list reference here. */
5124                 class_handle_unhash(&mfd->mfd_handle);
5125                 list_move_tail(&mfd->mfd_list, &closing_list);
5126         }
5127         spin_unlock(&med->med_open_lock);
5128         mdt = mdt_dev(obd->obd_lu_dev);
5129         LASSERT(mdt != NULL);
5130
5131         rc = lu_env_init(&env, LCT_MD_THREAD);
5132         if (rc)
5133                 RETURN(rc);
5134
5135         info = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
5136         LASSERT(info != NULL);
5137         memset(info, 0, sizeof *info);
5138         info->mti_env = &env;
5139         info->mti_mdt = mdt;
5140         info->mti_exp = exp;
5141
5142         if (!list_empty(&closing_list)) {
5143                 struct md_attr *ma = &info->mti_attr;
5144                 int lmm_size;
5145                 int cookie_size;
5146
5147                 lmm_size = mdt->mdt_max_mdsize;
5148                 OBD_ALLOC(ma->ma_lmm, lmm_size);
5149                 if (ma->ma_lmm == NULL)
5150                         GOTO(out_lmm, rc = -ENOMEM);
5151
5152                 cookie_size = mdt->mdt_max_cookiesize;
5153                 OBD_ALLOC(ma->ma_cookie, cookie_size);
5154                 if (ma->ma_cookie == NULL)
5155                         GOTO(out_cookie, rc = -ENOMEM);
5156
5157                 /* Close any open files (which may also cause orphan unlinking). */
5158                 list_for_each_entry_safe(mfd, n, &closing_list, mfd_list) {
5159                         list_del_init(&mfd->mfd_list);
5160                         memset(&ma->ma_attr, 0, sizeof(ma->ma_attr));
5161                         ma->ma_lmm_size = lmm_size;
5162                         ma->ma_cookie_size = cookie_size;
5163                         ma->ma_need = 0;
5164                         /* It is not for setattr, just tell MDD to send
5165                          * DESTROY RPC to OSS if needed */
5166                         ma->ma_attr_flags = MDS_CLOSE_CLEANUP;
5167                         ma->ma_valid = MA_FLAGS;
5168                         mdt_mfd_close(info, mfd);
5169                 }
5170                 info->mti_mdt = NULL;
5171                 OBD_FREE(ma->ma_cookie, cookie_size);
5172                 ma->ma_cookie = NULL;
5173 out_cookie:
5174                 OBD_FREE(ma->ma_lmm, lmm_size);
5175                 ma->ma_lmm = NULL;
5176         }
5177 out_lmm:
5178         lu_env_fini(&env);
5179
5180         RETURN(rc);
5181 }
5182
5183 static int mdt_obd_disconnect(struct obd_export *exp)
5184 {
5185         struct mdt_device *mdt = mdt_dev(exp->exp_obd->obd_lu_dev);
5186         int rc;
5187         ENTRY;
5188
5189         LASSERT(exp);
5190         class_export_get(exp);
5191
5192         /* Disconnect early so that clients can't keep using export */
5193         rc = class_disconnect(exp);
5194         if (mdt->mdt_namespace != NULL || exp->exp_obd->obd_namespace != NULL)
5195                 ldlm_cancel_locks_for_export(exp);
5196
5197         /* release nid stat refererence */
5198         lprocfs_exp_cleanup(exp);
5199
5200         /* complete all outstanding replies */
5201         spin_lock(&exp->exp_lock);
5202         while (!list_empty(&exp->exp_outstanding_replies)) {
5203                 struct ptlrpc_reply_state *rs =
5204                         list_entry(exp->exp_outstanding_replies.next,
5205                                    struct ptlrpc_reply_state, rs_exp_list);
5206                 struct ptlrpc_service *svc = rs->rs_service;
5207
5208                 spin_lock(&svc->srv_lock);
5209                 list_del_init(&rs->rs_exp_list);
5210                 spin_lock(&rs->rs_lock);
5211                 ptlrpc_schedule_difficult_reply(rs);
5212                 spin_unlock(&rs->rs_lock);
5213                 spin_unlock(&svc->srv_lock);
5214         }
5215         spin_unlock(&exp->exp_lock);
5216         rc = mdt_mfd_cleanup(exp);
5217         class_export_put(exp);
5218         RETURN(rc);
5219 }
5220
5221 /* FIXME: Can we avoid using these two interfaces? */
5222 static int mdt_init_export(struct obd_export *exp)
5223 {
5224         struct mdt_export_data *med = &exp->exp_mdt_data;
5225         int                     rc;
5226         ENTRY;
5227
5228         CFS_INIT_LIST_HEAD(&med->med_open_head);
5229         spin_lock_init(&med->med_open_lock);
5230         sema_init(&med->med_idmap_sem, 1);
5231         med->med_idmap = NULL;
5232         spin_lock(&exp->exp_lock);
5233         exp->exp_connecting = 1;
5234         spin_unlock(&exp->exp_lock);
5235         rc = ldlm_init_export(exp);
5236         if (rc)
5237                 CERROR("Error %d while initializing export\n", rc);
5238         RETURN(rc);
5239 }
5240
5241 static int mdt_destroy_export(struct obd_export *export)
5242 {
5243         struct mdt_export_data *med;
5244         struct obd_device      *obd = export->exp_obd;
5245         struct mdt_device      *mdt;
5246         struct mdt_thread_info *info;
5247         struct lu_env           env;
5248         int rc = 0;
5249         ENTRY;
5250
5251         med = &export->exp_mdt_data;
5252         if (exp_connect_rmtclient(export))
5253                 mdt_cleanup_idmap(med);
5254
5255         target_destroy_export(export);
5256         ldlm_destroy_export(export);
5257
5258         LASSERT(list_empty(&export->exp_outstanding_replies));
5259         LASSERT(list_empty(&med->med_open_head));
5260         if (obd_uuid_equals(&export->exp_client_uuid, &obd->obd_uuid))
5261                 RETURN(0);
5262
5263         mdt = mdt_dev(obd->obd_lu_dev);
5264         LASSERT(mdt != NULL);
5265
5266         rc = lu_env_init(&env, LCT_MD_THREAD);
5267         if (rc)
5268                 RETURN(rc);
5269
5270         info = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
5271         LASSERT(info != NULL);
5272         memset(info, 0, sizeof *info);
5273         info->mti_env = &env;
5274         info->mti_exp = export;
5275         info->mti_mdt = NULL;
5276         mdt_client_del(&env, mdt);
5277
5278         lu_env_fini(&env);
5279         RETURN(rc);
5280 }
5281
5282 static void mdt_allow_cli(struct mdt_device *m, unsigned int flag)
5283 {
5284         if (flag & CONFIG_LOG)
5285                 m->mdt_fl_cfglog = 1;
5286
5287         /* also notify active event */
5288         if (flag & CONFIG_SYNC)
5289                 m->mdt_fl_synced = 1;
5290
5291         if (m->mdt_fl_cfglog && m->mdt_fl_synced)
5292                 /* Open for clients */
5293                 m->mdt_md_dev.md_lu_dev.ld_obd->obd_no_conn = 0;
5294 }
5295
5296 static int mdt_upcall(const struct lu_env *env, struct md_device *md,
5297                       enum md_upcall_event ev, void *data)
5298 {
5299         struct mdt_device *m = mdt_dev(&md->md_lu_dev);
5300         struct md_device  *next  = m->mdt_child;
5301         struct mdt_thread_info *mti;
5302         int rc = 0;
5303         ENTRY;
5304
5305         switch (ev) {
5306                 case MD_LOV_SYNC:
5307                         rc = next->md_ops->mdo_maxsize_get(env, next,
5308                                         &m->mdt_max_mdsize,
5309                                         &m->mdt_max_cookiesize);
5310                         CDEBUG(D_INFO, "get max mdsize %d max cookiesize %d\n",
5311                                      m->mdt_max_mdsize, m->mdt_max_cookiesize);
5312                         mdt_allow_cli(m, CONFIG_SYNC);
5313                         if (data)
5314                                 (*(__u64 *)data) = m->mdt_mount_count;
5315                         break;
5316                 case MD_NO_TRANS:
5317                         mti = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
5318                         mti->mti_no_need_trans = 1;
5319                         CDEBUG(D_INFO, "disable mdt trans for this thread\n");
5320                         break;
5321                 case MD_LOV_CONFIG:
5322                         /* Check that MDT is not yet configured */
5323                         LASSERT(!m->mdt_fl_cfglog);
5324                         break;
5325 #ifdef HAVE_QUOTA_SUPPORT
5326                 case MD_LOV_QUOTA:
5327                         if (md->md_lu_dev.ld_obd->obd_recovering == 0 &&
5328                             likely(md->md_lu_dev.ld_obd->obd_stopping == 0))
5329                                 next->md_ops->mdo_quota.mqo_recovery(env, next);
5330                         break;
5331 #endif
5332                 default:
5333                         CERROR("invalid event\n");
5334                         rc = -EINVAL;
5335                         break;
5336         }
5337         RETURN(rc);
5338 }
5339
5340 static int mdt_obd_notify(struct obd_device *host,
5341                           struct obd_device *watched,
5342                           enum obd_notify_event ev, void *data)
5343 {
5344         struct mdt_device *mdt = mdt_dev(host->obd_lu_dev);
5345 #ifdef HAVE_QUOTA_SUPPORT
5346         struct md_device *next = mdt->mdt_child;
5347 #endif
5348         ENTRY;
5349
5350         switch (ev) {
5351         case OBD_NOTIFY_CONFIG:
5352                 mdt_allow_cli(mdt, (unsigned long)data);
5353
5354 #ifdef HAVE_QUOTA_SUPPORT
5355                /* quota_type has been processed, we can now handle
5356                 * incoming quota requests */
5357                 next->md_ops->mdo_quota.mqo_notify(NULL, next);
5358 #endif
5359                 break;
5360         default:
5361                 CDEBUG(D_INFO, "Unhandled notification %#x\n", ev);
5362         }
5363         RETURN(0);
5364 }
5365
5366 static int mdt_rpc_fid2path(struct mdt_thread_info *info, void *key,
5367                             void *val, int vallen)
5368 {
5369         struct mdt_device *mdt = mdt_dev(info->mti_exp->exp_obd->obd_lu_dev);
5370         struct getinfo_fid2path *fpout, *fpin;
5371         int rc = 0;
5372
5373         fpin = key + size_round(sizeof(KEY_FID2PATH));
5374         fpout = val;
5375
5376         if (lustre_msg_swabbed(mdt_info_req(info)->rq_reqmsg))
5377                 lustre_swab_fid2path(fpin);
5378
5379         memcpy(fpout, fpin, sizeof(*fpin));
5380         if (fpout->gf_pathlen != vallen - sizeof(*fpin))
5381                 RETURN(-EINVAL);
5382
5383         rc = mdt_fid2path(info->mti_env, mdt, fpout);
5384         RETURN(rc);
5385 }
5386
5387 static int mdt_fid2path(const struct lu_env *env, struct mdt_device *mdt,
5388                         struct getinfo_fid2path *fp)
5389 {
5390         struct mdt_object *obj;
5391         int    rc;
5392         ENTRY;
5393
5394         CDEBUG(D_IOCTL, "path get "DFID" from "LPU64" #%d\n",
5395                PFID(&fp->gf_fid), fp->gf_recno, fp->gf_linkno);
5396
5397         if (!fid_is_sane(&fp->gf_fid))
5398                 RETURN(-EINVAL);
5399
5400         obj = mdt_object_find(env, mdt, &fp->gf_fid);
5401         if (obj == NULL || IS_ERR(obj)) {
5402                 CDEBUG(D_IOCTL, "no object "DFID": %ld\n",PFID(&fp->gf_fid),
5403                        PTR_ERR(obj));
5404                 RETURN(-EINVAL);
5405         }
5406
5407         rc = lu_object_exists(&obj->mot_obj.mo_lu);
5408         if (rc <= 0) {
5409                 if (rc == -1)
5410                         rc = -EREMOTE;
5411                 else
5412                         rc = -ENOENT;
5413                 mdt_object_put(env, obj);
5414                 CDEBUG(D_IOCTL, "nonlocal object "DFID": %d\n",
5415                        PFID(&fp->gf_fid), rc);
5416                 RETURN(rc);
5417         }
5418
5419         rc = mo_path(env, md_object_next(&obj->mot_obj), fp->gf_path,
5420                      fp->gf_pathlen, &fp->gf_recno, &fp->gf_linkno);
5421         mdt_object_put(env, obj);
5422
5423         RETURN(rc);
5424 }
5425
5426 static int mdt_get_info(struct mdt_thread_info *info)
5427 {
5428         struct ptlrpc_request *req = mdt_info_req(info);
5429         char *key;
5430         int keylen;
5431         __u32 *vallen;
5432         void *valout;
5433         int rc;
5434         ENTRY;
5435
5436         key = req_capsule_client_get(info->mti_pill, &RMF_GETINFO_KEY);
5437         if (key == NULL) {
5438                 CDEBUG(D_IOCTL, "No GETINFO key");
5439                 RETURN(-EFAULT);
5440         }
5441         keylen = req_capsule_get_size(info->mti_pill, &RMF_GETINFO_KEY,
5442                                       RCL_CLIENT);
5443
5444         vallen = req_capsule_client_get(info->mti_pill, &RMF_GETINFO_VALLEN);
5445         if (vallen == NULL) {
5446                 CDEBUG(D_IOCTL, "Unable to get RMF_GETINFO_VALLEN buffer");
5447                 RETURN(-EFAULT);
5448         }
5449
5450         req_capsule_set_size(info->mti_pill, &RMF_GETINFO_VAL, RCL_SERVER,
5451                              *vallen);
5452         rc = req_capsule_server_pack(info->mti_pill);
5453         valout = req_capsule_server_get(info->mti_pill, &RMF_GETINFO_VAL);
5454         if (valout == NULL) {
5455                 CDEBUG(D_IOCTL, "Unable to get get-info RPC out buffer");
5456                 RETURN(-EFAULT);
5457         }
5458
5459         if (KEY_IS(KEY_FID2PATH))
5460                 rc = mdt_rpc_fid2path(info, key, valout, *vallen);
5461         else
5462                 rc = -EINVAL;
5463
5464         lustre_msg_set_status(req->rq_repmsg, rc);
5465
5466         RETURN(rc);
5467 }
5468
5469 /* Pass the ioc down */
5470 static int mdt_ioc_child(struct lu_env *env, struct mdt_device *mdt,
5471                          unsigned int cmd, int len, void *data)
5472 {
5473         struct lu_context ioctl_session;
5474         struct md_device *next = mdt->mdt_child;
5475         int rc;
5476         ENTRY;
5477
5478         rc = lu_context_init(&ioctl_session, LCT_SESSION);
5479         if (rc)
5480                 RETURN(rc);
5481         ioctl_session.lc_thread = (struct ptlrpc_thread *)cfs_current();
5482         lu_context_enter(&ioctl_session);
5483         env->le_ses = &ioctl_session;
5484
5485         LASSERT(next->md_ops->mdo_iocontrol);
5486         rc = next->md_ops->mdo_iocontrol(env, next, cmd, len, data);
5487
5488         lu_context_exit(&ioctl_session);
5489         lu_context_fini(&ioctl_session);
5490         RETURN(rc);
5491 }
5492
5493 static int mdt_ioc_version_get(struct mdt_thread_info *mti, void *karg)
5494 {
5495         struct obd_ioctl_data *data = karg;
5496         struct lu_fid *fid = (struct lu_fid *)data->ioc_inlbuf1;
5497         __u64 version;
5498         struct mdt_object *obj;
5499         struct mdt_lock_handle  *lh;
5500         int rc;
5501         ENTRY;
5502         CDEBUG(D_IOCTL, "getting version for "DFID"\n", PFID(fid));
5503         if (!fid_is_sane(fid))
5504                 RETURN(-EINVAL);
5505
5506         lh = &mti->mti_lh[MDT_LH_PARENT];
5507         mdt_lock_reg_init(lh, LCK_CR);
5508
5509         obj = mdt_object_find_lock(mti, fid, lh, MDS_INODELOCK_UPDATE);
5510         if (IS_ERR(obj))
5511                 RETURN(PTR_ERR(obj));
5512
5513         rc = mdt_object_exists(obj);
5514         if (rc < 0) {
5515                 rc = -EREMOTE;
5516                 /**
5517                  * before calling version get the correct MDS should be
5518                  * fid, this is error to find remote object here
5519                  */
5520                 CERROR("nonlocal object "DFID"\n", PFID(fid));
5521         } else if (rc == 0) {
5522                 rc = -ENOENT;
5523                 CDEBUG(D_IOCTL, "no such object: "DFID"\n", PFID(fid));
5524         } else {
5525                 version = mo_version_get(mti->mti_env, mdt_object_child(obj));
5526                 if (version < 0) {
5527                         rc = (int)version;
5528                 } else {
5529                         *(__u64 *)data->ioc_inlbuf2 = version;
5530                         rc = 0;
5531                 }
5532         }
5533         mdt_object_unlock_put(mti, obj, lh, 1);
5534         RETURN(rc);
5535 }
5536
5537 /* ioctls on obd dev */
5538 static int mdt_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
5539                          void *karg, void *uarg)
5540 {
5541         struct lu_env      env;
5542         struct obd_device *obd = exp->exp_obd;
5543         struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
5544         struct dt_device  *dt = mdt->mdt_bottom;
5545         int rc;
5546
5547         ENTRY;
5548         CDEBUG(D_IOCTL, "handling ioctl cmd %#x\n", cmd);
5549         rc = lu_env_init(&env, LCT_MD_THREAD);
5550         if (rc)
5551                 RETURN(rc);
5552
5553         switch (cmd) {
5554         case OBD_IOC_SYNC:
5555                 rc = mdt_device_sync(&env, mdt);
5556                 break;
5557         case OBD_IOC_SET_READONLY:
5558                 dt->dd_ops->dt_ro(&env, dt);
5559                 break;
5560         case OBD_IOC_ABORT_RECOVERY:
5561                 CERROR("Aborting recovery for device %s\n", obd->obd_name);
5562                 target_stop_recovery_thread(obd);
5563                 rc = 0;
5564                 break;
5565         case OBD_IOC_CHANGELOG_REG:
5566         case OBD_IOC_CHANGELOG_DEREG:
5567         case OBD_IOC_CHANGELOG_CLEAR:
5568                 rc = mdt_ioc_child(&env, mdt, cmd, len, karg);
5569                 break;
5570         case OBD_IOC_GET_OBJ_VERSION: {
5571                 struct mdt_thread_info *mti;
5572                 mti = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
5573                 memset(mti, 0, sizeof *mti);
5574                 mti->mti_env = &env;
5575                 mti->mti_mdt = mdt;
5576                 mti->mti_exp = exp;
5577
5578                 rc = mdt_ioc_version_get(mti, karg);
5579                 break;
5580         }
5581         default:
5582                 CERROR("Not supported cmd = %d for device %s\n",
5583                        cmd, obd->obd_name);
5584                 rc = -EOPNOTSUPP;
5585         }
5586
5587         lu_env_fini(&env);
5588         RETURN(rc);
5589 }
5590
5591 int mdt_postrecov(const struct lu_env *env, struct mdt_device *mdt)
5592 {
5593         struct lu_device *ld = md2lu_dev(mdt->mdt_child);
5594         struct obd_device *obd = mdt2obd_dev(mdt);
5595 #ifdef HAVE_QUOTA_SUPPORT
5596         struct md_device *next = mdt->mdt_child;
5597 #endif
5598         int rc, lost;
5599         ENTRY;
5600         /* if some clients didn't participate in recovery then we can possibly
5601          * lost sequence. Now we should increase sequence for safe value */
5602         lost = obd->obd_max_recoverable_clients - obd->obd_connected_clients;
5603         mdt_seq_adjust(env, mdt, lost);
5604
5605         rc = ld->ld_ops->ldo_recovery_complete(env, ld);
5606 #ifdef HAVE_QUOTA_SUPPORT
5607         if (likely(obd->obd_stopping == 0))
5608                 next->md_ops->mdo_quota.mqo_recovery(env, next);
5609 #endif
5610         RETURN(rc);
5611 }
5612
5613 int mdt_obd_postrecov(struct obd_device *obd)
5614 {
5615         struct lu_env env;
5616         int rc;
5617
5618         rc = lu_env_init(&env, LCT_MD_THREAD);
5619         if (rc)
5620                 RETURN(rc);
5621         rc = mdt_postrecov(&env, mdt_dev(obd->obd_lu_dev));
5622         lu_env_fini(&env);
5623         return rc;
5624 }
5625
5626 /**
5627  * Send a copytool req to a client
5628  * Note this sends a request RPC from a server (MDT) to a client (MDC),
5629  * backwards of normal comms.
5630  */
5631 int mdt_hsm_copytool_send(struct obd_export *exp)
5632 {
5633         struct lnl_hdr *lh;
5634         struct hsm_action_list *hal;
5635         struct hsm_action_item *hai;
5636         int rc, len;
5637         ENTRY;
5638
5639         CWARN("%s: writing to mdc at %s\n", exp->exp_obd->obd_name,
5640               libcfs_nid2str(exp->exp_connection->c_peer.nid));
5641
5642         len = sizeof(*lh) + sizeof(*hal) + MTI_NAME_MAXLEN +
5643                 /* for mockup below */ 2 * size_round(sizeof(*hai));
5644         OBD_ALLOC(lh, len);
5645         if (lh == NULL)
5646                 RETURN(-ENOMEM);
5647
5648         lh->lnl_magic = LNL_MAGIC;
5649         lh->lnl_transport = LNL_TRANSPORT_HSM;
5650         lh->lnl_msgtype = HMT_ACTION_LIST;
5651         lh->lnl_msglen = len;
5652
5653         hal = (struct hsm_action_list *)(lh + 1);
5654         hal->hal_version = HAL_VERSION;
5655         hal->hal_archive_num = 1;
5656         obd_uuid2fsname(hal->hal_fsname, exp->exp_obd->obd_name,
5657                         MTI_NAME_MAXLEN);
5658
5659         /* mock up an action list */
5660         hal->hal_count = 2;
5661         hai = hai_zero(hal);
5662         hai->hai_action = HSMA_ARCHIVE;
5663         hai->hai_fid.f_oid = 0xA00A;
5664         hai->hai_len = sizeof(*hai);
5665         hai = hai_next(hai);
5666         hai->hai_action = HSMA_RESTORE;
5667         hai->hai_fid.f_oid = 0xB00B;
5668         hai->hai_len = sizeof(*hai);
5669
5670         /* Uses the ldlm reverse import; this rpc will be seen by
5671           the ldlm_callback_handler */
5672         rc = target_set_info_rpc(exp->exp_imp_reverse, LDLM_SET_INFO,
5673                                  sizeof(KEY_HSM_COPYTOOL_SEND),
5674                                  KEY_HSM_COPYTOOL_SEND,
5675                                  len, lh, NULL);
5676
5677         OBD_FREE(lh, len);
5678
5679         RETURN(rc);
5680 }
5681
5682 static struct obd_ops mdt_obd_device_ops = {
5683         .o_owner          = THIS_MODULE,
5684         .o_set_info_async = mdt_obd_set_info_async,
5685         .o_connect        = mdt_obd_connect,
5686         .o_reconnect      = mdt_obd_reconnect,
5687         .o_disconnect     = mdt_obd_disconnect,
5688         .o_init_export    = mdt_init_export,
5689         .o_destroy_export = mdt_destroy_export,
5690         .o_iocontrol      = mdt_iocontrol,
5691         .o_postrecov      = mdt_obd_postrecov,
5692         .o_notify         = mdt_obd_notify
5693 };
5694
5695 static struct lu_device* mdt_device_fini(const struct lu_env *env,
5696                                          struct lu_device *d)
5697 {
5698         struct mdt_device *m = mdt_dev(d);
5699         ENTRY;
5700
5701         mdt_fini(env, m);
5702         RETURN(NULL);
5703 }
5704
5705 static struct lu_device *mdt_device_free(const struct lu_env *env,
5706                                          struct lu_device *d)
5707 {
5708         struct mdt_device *m = mdt_dev(d);
5709         ENTRY;
5710
5711         md_device_fini(&m->mdt_md_dev);
5712         OBD_FREE_PTR(m);
5713         RETURN(NULL);
5714 }
5715
5716 static struct lu_device *mdt_device_alloc(const struct lu_env *env,
5717                                           struct lu_device_type *t,
5718                                           struct lustre_cfg *cfg)
5719 {
5720         struct lu_device  *l;
5721         struct mdt_device *m;
5722
5723         OBD_ALLOC_PTR(m);
5724         if (m != NULL) {
5725                 int rc;
5726
5727                 l = &m->mdt_md_dev.md_lu_dev;
5728                 rc = mdt_init0(env, m, t, cfg);
5729                 if (rc != 0) {
5730                         mdt_device_free(env, l);
5731                         l = ERR_PTR(rc);
5732                         return l;
5733                 }
5734                 md_upcall_init(&m->mdt_md_dev, mdt_upcall);
5735         } else
5736                 l = ERR_PTR(-ENOMEM);
5737         return l;
5738 }
5739
5740 /* context key constructor/destructor: mdt_key_init, mdt_key_fini */
5741 LU_KEY_INIT_FINI(mdt, struct mdt_thread_info);
5742
5743 /* context key: mdt_thread_key */
5744 LU_CONTEXT_KEY_DEFINE(mdt, LCT_MD_THREAD);
5745
5746 /* context key constructor/destructor: mdt_txn_key_init, mdt_txn_key_fini */
5747 LU_KEY_INIT_FINI(mdt_txn, struct mdt_txn_info);
5748
5749 struct lu_context_key mdt_txn_key = {
5750         .lct_tags = LCT_TX_HANDLE,
5751         .lct_init = mdt_txn_key_init,
5752         .lct_fini = mdt_txn_key_fini
5753 };
5754
5755 struct md_ucred *mdt_ucred(const struct mdt_thread_info *info)
5756 {
5757         return md_ucred(info->mti_env);
5758 }
5759
5760 /**
5761  * Enable/disable COS.
5762  *
5763  * Set/Clear the COS flag in mdt options.
5764  *
5765  * \param mdt mdt device
5766  * \param val 0 disables COS, other values enable COS
5767  */
5768 void mdt_enable_cos(struct mdt_device *mdt, int val)
5769 {
5770         struct lu_env env;
5771         int rc;
5772
5773         mdt->mdt_opts.mo_cos = !!val;
5774         rc = lu_env_init(&env, LCT_MD_THREAD);
5775         if (unlikely(rc != 0)) {
5776                 CWARN("lu_env initialization failed with rc = %d,"
5777                       "cannot sync\n", rc);
5778                 return;
5779         }
5780         mdt_device_sync(&env, mdt);
5781         lu_env_fini(&env);
5782 }
5783
5784 /**
5785  * Check COS status.
5786  *
5787  * Return COS flag status/
5788  *
5789  * \param mdt mdt device
5790  */
5791 int mdt_cos_is_enabled(struct mdt_device *mdt)
5792 {
5793         return mdt->mdt_opts.mo_cos != 0;
5794 }
5795
5796 /* type constructor/destructor: mdt_type_init, mdt_type_fini */
5797 LU_TYPE_INIT_FINI(mdt, &mdt_thread_key, &mdt_txn_key);
5798
5799 static struct lu_device_type_operations mdt_device_type_ops = {
5800         .ldto_init = mdt_type_init,
5801         .ldto_fini = mdt_type_fini,
5802
5803         .ldto_start = mdt_type_start,
5804         .ldto_stop  = mdt_type_stop,
5805
5806         .ldto_device_alloc = mdt_device_alloc,
5807         .ldto_device_free  = mdt_device_free,
5808         .ldto_device_fini  = mdt_device_fini
5809 };
5810
5811 static struct lu_device_type mdt_device_type = {
5812         .ldt_tags     = LU_DEVICE_MD,
5813         .ldt_name     = LUSTRE_MDT_NAME,
5814         .ldt_ops      = &mdt_device_type_ops,
5815         .ldt_ctx_tags = LCT_MD_THREAD
5816 };
5817
5818 static struct lu_local_obj_desc mdt_last_recv = {
5819         .llod_name      = LAST_RCVD,
5820         .llod_oid       = MDT_LAST_RECV_OID,
5821         .llod_is_index  = 0,
5822 };
5823
5824 static int __init mdt_mod_init(void)
5825 {
5826         struct lprocfs_static_vars lvars;
5827         int rc;
5828
5829         llo_local_obj_register(&mdt_last_recv);
5830
5831         mdt_num_threads = MDT_NUM_THREADS;
5832         lprocfs_mdt_init_vars(&lvars);
5833         rc = class_register_type(&mdt_obd_device_ops, NULL,
5834                                  lvars.module_vars, LUSTRE_MDT_NAME,
5835                                  &mdt_device_type);
5836
5837         return rc;
5838 }
5839
5840 static void __exit mdt_mod_exit(void)
5841 {
5842         llo_local_obj_unregister(&mdt_last_recv);
5843         class_unregister_type(LUSTRE_MDT_NAME);
5844 }
5845
5846
5847 #define DEF_HNDL(prefix, base, suffix, flags, opc, fn, fmt)             \
5848 [prefix ## _ ## opc - prefix ## _ ## base] = {                          \
5849         .mh_name    = #opc,                                             \
5850         .mh_fail_id = OBD_FAIL_ ## prefix ## _  ## opc ## suffix,       \
5851         .mh_opc     = prefix ## _  ## opc,                              \
5852         .mh_flags   = flags,                                            \
5853         .mh_act     = fn,                                               \
5854         .mh_fmt     = fmt                                               \
5855 }
5856
5857 #define DEF_MDT_HNDL(flags, name, fn, fmt)                                  \
5858         DEF_HNDL(MDS, GETATTR, _NET, flags, name, fn, fmt)
5859
5860 #define DEF_SEQ_HNDL(flags, name, fn, fmt)                      \
5861         DEF_HNDL(SEQ, QUERY, _NET, flags, name, fn, fmt)
5862
5863 #define DEF_FLD_HNDL(flags, name, fn, fmt)                      \
5864         DEF_HNDL(FLD, QUERY, _NET, flags, name, fn, fmt)
5865 /*
5866  * Request with a format known in advance
5867  */
5868 #define DEF_MDT_HNDL_F(flags, name, fn)                                 \
5869         DEF_HNDL(MDS, GETATTR, _NET, flags, name, fn, &RQF_MDS_ ## name)
5870
5871 #define DEF_SEQ_HNDL_F(flags, name, fn)                                 \
5872         DEF_HNDL(SEQ, QUERY, _NET, flags, name, fn, &RQF_SEQ_ ## name)
5873
5874 #define DEF_FLD_HNDL_F(flags, name, fn)                                 \
5875         DEF_HNDL(FLD, QUERY, _NET, flags, name, fn, &RQF_FLD_ ## name)
5876 /*
5877  * Request with a format we do not yet know
5878  */
5879 #define DEF_MDT_HNDL_0(flags, name, fn)                                 \
5880         DEF_HNDL(MDS, GETATTR, _NET, flags, name, fn, NULL)
5881
5882 static struct mdt_handler mdt_mds_ops[] = {
5883 DEF_MDT_HNDL_F(0,                         CONNECT,      mdt_connect),
5884 DEF_MDT_HNDL_F(0,                         DISCONNECT,   mdt_disconnect),
5885 DEF_MDT_HNDL  (0,                         SET_INFO,     mdt_set_info,
5886                                                              &RQF_OBD_SET_INFO),
5887 DEF_MDT_HNDL_F(0,                         GET_INFO,     mdt_get_info),
5888 DEF_MDT_HNDL_F(0           |HABEO_REFERO, GETSTATUS,    mdt_getstatus),
5889 DEF_MDT_HNDL_F(HABEO_CORPUS,              GETATTR,      mdt_getattr),
5890 DEF_MDT_HNDL_F(HABEO_CORPUS|HABEO_REFERO, GETATTR_NAME, mdt_getattr_name),
5891 DEF_MDT_HNDL_F(HABEO_CORPUS,              GETXATTR,     mdt_getxattr),
5892 DEF_MDT_HNDL_F(0           |HABEO_REFERO, STATFS,       mdt_statfs),
5893 DEF_MDT_HNDL_F(0           |MUTABOR,      REINT,        mdt_reint),
5894 DEF_MDT_HNDL_F(HABEO_CORPUS,              CLOSE,        mdt_close),
5895 DEF_MDT_HNDL_F(HABEO_CORPUS,              DONE_WRITING, mdt_done_writing),
5896 DEF_MDT_HNDL_F(0           |HABEO_REFERO, PIN,          mdt_pin),
5897 DEF_MDT_HNDL_0(0,                         SYNC,         mdt_sync),
5898 DEF_MDT_HNDL_F(HABEO_CORPUS|HABEO_REFERO, IS_SUBDIR,    mdt_is_subdir),
5899 #ifdef HAVE_QUOTA_SUPPORT
5900 DEF_MDT_HNDL_F(0,                         QUOTACHECK,   mdt_quotacheck_handle),
5901 DEF_MDT_HNDL_F(0,                         QUOTACTL,     mdt_quotactl_handle)
5902 #endif
5903 };
5904
5905 #define DEF_OBD_HNDL(flags, name, fn)                   \
5906         DEF_HNDL(OBD, PING, _NET, flags, name, fn, NULL)
5907
5908
5909 static struct mdt_handler mdt_obd_ops[] = {
5910         DEF_OBD_HNDL(0, PING,           mdt_obd_ping),
5911         DEF_OBD_HNDL(0, LOG_CANCEL,     mdt_obd_log_cancel),
5912         DEF_OBD_HNDL(0, QC_CALLBACK,    mdt_obd_qc_callback)
5913 };
5914
5915 #define DEF_DLM_HNDL_0(flags, name, fn)                   \
5916         DEF_HNDL(LDLM, ENQUEUE, , flags, name, fn, NULL)
5917 #define DEF_DLM_HNDL_F(flags, name, fn)                   \
5918         DEF_HNDL(LDLM, ENQUEUE, , flags, name, fn, &RQF_LDLM_ ## name)
5919
5920 static struct mdt_handler mdt_dlm_ops[] = {
5921         DEF_DLM_HNDL_F(HABEO_CLAVIS, ENQUEUE,        mdt_enqueue),
5922         DEF_DLM_HNDL_0(HABEO_CLAVIS, CONVERT,        mdt_convert),
5923         DEF_DLM_HNDL_0(0,            BL_CALLBACK,    mdt_bl_callback),
5924         DEF_DLM_HNDL_0(0,            CP_CALLBACK,    mdt_cp_callback)
5925 };
5926
5927 #define DEF_LLOG_HNDL(flags, name, fn)                   \
5928         DEF_HNDL(LLOG, ORIGIN_HANDLE_CREATE, _NET, flags, name, fn, NULL)
5929
5930 static struct mdt_handler mdt_llog_ops[] = {
5931         DEF_LLOG_HNDL(0, ORIGIN_HANDLE_CREATE,      mdt_llog_create),
5932         DEF_LLOG_HNDL(0, ORIGIN_HANDLE_NEXT_BLOCK,  mdt_llog_next_block),
5933         DEF_LLOG_HNDL(0, ORIGIN_HANDLE_READ_HEADER, mdt_llog_read_header),
5934         DEF_LLOG_HNDL(0, ORIGIN_HANDLE_WRITE_REC,   NULL),
5935         DEF_LLOG_HNDL(0, ORIGIN_HANDLE_CLOSE,       NULL),
5936         DEF_LLOG_HNDL(0, ORIGIN_CONNECT,            NULL),
5937         DEF_LLOG_HNDL(0, CATINFO,                   NULL),
5938         DEF_LLOG_HNDL(0, ORIGIN_HANDLE_PREV_BLOCK,  mdt_llog_prev_block),
5939         DEF_LLOG_HNDL(0, ORIGIN_HANDLE_DESTROY,     mdt_llog_destroy),
5940 };
5941
5942 #define DEF_SEC_CTX_HNDL(name, fn)                      \
5943         DEF_HNDL(SEC_CTX, INIT, _NET, 0, name, fn, NULL)
5944
5945 static struct mdt_handler mdt_sec_ctx_ops[] = {
5946         DEF_SEC_CTX_HNDL(INIT,          mdt_sec_ctx_handle),
5947         DEF_SEC_CTX_HNDL(INIT_CONT,     mdt_sec_ctx_handle),
5948         DEF_SEC_CTX_HNDL(FINI,          mdt_sec_ctx_handle)
5949 };
5950
5951 static struct mdt_opc_slice mdt_regular_handlers[] = {
5952         {
5953                 .mos_opc_start = MDS_GETATTR,
5954                 .mos_opc_end   = MDS_LAST_OPC,
5955                 .mos_hs        = mdt_mds_ops
5956         },
5957         {
5958                 .mos_opc_start = OBD_PING,
5959                 .mos_opc_end   = OBD_LAST_OPC,
5960                 .mos_hs        = mdt_obd_ops
5961         },
5962         {
5963                 .mos_opc_start = LDLM_ENQUEUE,
5964                 .mos_opc_end   = LDLM_LAST_OPC,
5965                 .mos_hs        = mdt_dlm_ops
5966         },
5967         {
5968                 .mos_opc_start = LLOG_ORIGIN_HANDLE_CREATE,
5969                 .mos_opc_end   = LLOG_LAST_OPC,
5970                 .mos_hs        = mdt_llog_ops
5971         },
5972         {
5973                 .mos_opc_start = SEC_CTX_INIT,
5974                 .mos_opc_end   = SEC_LAST_OPC,
5975                 .mos_hs        = mdt_sec_ctx_ops
5976         },
5977         {
5978                 .mos_hs        = NULL
5979         }
5980 };
5981
5982 static struct mdt_handler mdt_readpage_ops[] = {
5983         DEF_MDT_HNDL_F(0,                         CONNECT,  mdt_connect),
5984         DEF_MDT_HNDL_F(HABEO_CORPUS|HABEO_REFERO, READPAGE, mdt_readpage),
5985 #ifdef HAVE_SPLIT_SUPPORT
5986         DEF_MDT_HNDL_F(HABEO_CORPUS|HABEO_REFERO, WRITEPAGE, mdt_writepage),
5987 #endif
5988
5989         /*
5990          * XXX: this is ugly and should be fixed one day, see mdc_close() for
5991          * detailed comments. --umka
5992          */
5993         DEF_MDT_HNDL_F(HABEO_CORPUS,              CLOSE,    mdt_close),
5994         DEF_MDT_HNDL_F(HABEO_CORPUS,              DONE_WRITING,    mdt_done_writing),
5995 };
5996
5997 static struct mdt_opc_slice mdt_readpage_handlers[] = {
5998         {
5999                 .mos_opc_start = MDS_GETATTR,
6000                 .mos_opc_end   = MDS_LAST_OPC,
6001                 .mos_hs        = mdt_readpage_ops
6002         },
6003         {
6004                 .mos_hs        = NULL
6005         }
6006 };
6007
6008 static struct mdt_handler mdt_xmds_ops[] = {
6009         DEF_MDT_HNDL_F(0,                         CONNECT,      mdt_connect),
6010         DEF_MDT_HNDL_F(HABEO_CORPUS             , GETATTR,      mdt_getattr),
6011         DEF_MDT_HNDL_F(0 | MUTABOR              , REINT,        mdt_reint),
6012         DEF_MDT_HNDL_F(HABEO_CORPUS|HABEO_REFERO, IS_SUBDIR,    mdt_is_subdir),
6013 };
6014
6015 static struct mdt_opc_slice mdt_xmds_handlers[] = {
6016         {
6017                 .mos_opc_start = MDS_GETATTR,
6018                 .mos_opc_end   = MDS_LAST_OPC,
6019                 .mos_hs        = mdt_xmds_ops
6020         },
6021         {
6022                 .mos_opc_start = OBD_PING,
6023                 .mos_opc_end   = OBD_LAST_OPC,
6024                 .mos_hs        = mdt_obd_ops
6025         },
6026         {
6027                 .mos_opc_start = SEC_CTX_INIT,
6028                 .mos_opc_end   = SEC_LAST_OPC,
6029                 .mos_hs        = mdt_sec_ctx_ops
6030         },
6031         {
6032                 .mos_hs        = NULL
6033         }
6034 };
6035
6036 static struct mdt_handler mdt_seq_ops[] = {
6037         DEF_SEQ_HNDL_F(0, QUERY, (int (*)(struct mdt_thread_info *))seq_query)
6038 };
6039
6040 static struct mdt_opc_slice mdt_seq_handlers[] = {
6041         {
6042                 .mos_opc_start = SEQ_QUERY,
6043                 .mos_opc_end   = SEQ_LAST_OPC,
6044                 .mos_hs        = mdt_seq_ops
6045         },
6046         {
6047                 .mos_hs        = NULL
6048         }
6049 };
6050
6051 static struct mdt_handler mdt_fld_ops[] = {
6052         DEF_FLD_HNDL_F(0, QUERY, (int (*)(struct mdt_thread_info *))fld_query)
6053 };
6054
6055 static struct mdt_opc_slice mdt_fld_handlers[] = {
6056         {
6057                 .mos_opc_start = FLD_QUERY,
6058                 .mos_opc_end   = FLD_LAST_OPC,
6059                 .mos_hs        = mdt_fld_ops
6060         },
6061         {
6062                 .mos_hs        = NULL
6063         }
6064 };
6065
6066 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
6067 MODULE_DESCRIPTION("Lustre Meta-data Target ("LUSTRE_MDT_NAME")");
6068 MODULE_LICENSE("GPL");
6069
6070 CFS_MODULE_PARM(mdt_num_threads, "ul", ulong, 0444,
6071                 "number of mdt service threads to start");
6072
6073 cfs_module(mdt, "0.2.0", mdt_mod_init, mdt_mod_exit);