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