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