Whamcloud - gitweb
LU-6085 mdt: return valid attribute only to client
[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) 2010, 2014, Intel Corporation.
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 #include <lustre_ioctl.h>
57 /* struct ptlrpc_request */
58 #include <lustre_net.h>
59 /* struct obd_export */
60 #include <lustre_export.h>
61 /* struct obd_device */
62 #include <obd.h>
63 /* lu2dt_dev() */
64 #include <dt_object.h>
65 #include <lustre_mds.h>
66 #include <lustre_log.h>
67 #include "mdt_internal.h"
68 #include <lustre_acl.h>
69 #include <lustre_param.h>
70 #include <lustre_quota.h>
71 #include <lustre_lfsck.h>
72 #include <lustre_nodemap.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 static struct mdt_device *mdt_dev(struct lu_device *d);
97 static int mdt_unpack_req_pack_rep(struct mdt_thread_info *info, __u32 flags);
98
99 static const struct lu_object_operations mdt_obj_ops;
100
101 /* Slab for MDT object allocation */
102 static struct kmem_cache *mdt_object_kmem;
103
104 /* For HSM restore handles */
105 struct kmem_cache *mdt_hsm_cdt_kmem;
106
107 /* For HSM request handles */
108 struct kmem_cache *mdt_hsm_car_kmem;
109
110 static struct lu_kmem_descr mdt_caches[] = {
111         {
112                 .ckd_cache = &mdt_object_kmem,
113                 .ckd_name  = "mdt_obj",
114                 .ckd_size  = sizeof(struct mdt_object)
115         },
116         {
117                 .ckd_cache      = &mdt_hsm_cdt_kmem,
118                 .ckd_name       = "mdt_cdt_restore_handle",
119                 .ckd_size       = sizeof(struct cdt_restore_handle)
120         },
121         {
122                 .ckd_cache      = &mdt_hsm_car_kmem,
123                 .ckd_name       = "mdt_cdt_agent_req",
124                 .ckd_size       = sizeof(struct cdt_agent_req)
125         },
126         {
127                 .ckd_cache = NULL
128         }
129 };
130
131 int mdt_get_disposition(struct ldlm_reply *rep, int flag)
132 {
133         if (!rep)
134                 return 0;
135         return (rep->lock_policy_res1 & flag);
136 }
137
138 void mdt_clear_disposition(struct mdt_thread_info *info,
139                            struct ldlm_reply *rep, int flag)
140 {
141         if (info) {
142                 info->mti_opdata &= ~flag;
143                 tgt_opdata_clear(info->mti_env, flag);
144         }
145         if (rep)
146                 rep->lock_policy_res1 &= ~flag;
147 }
148
149 void mdt_set_disposition(struct mdt_thread_info *info,
150                          struct ldlm_reply *rep, int flag)
151 {
152         if (info) {
153                 info->mti_opdata |= flag;
154                 tgt_opdata_set(info->mti_env, flag);
155         }
156         if (rep)
157                 rep->lock_policy_res1 |= flag;
158 }
159
160 void mdt_lock_reg_init(struct mdt_lock_handle *lh, ldlm_mode_t lm)
161 {
162         lh->mlh_pdo_hash = 0;
163         lh->mlh_reg_mode = lm;
164         lh->mlh_rreg_mode = lm;
165         lh->mlh_type = MDT_REG_LOCK;
166 }
167
168 void mdt_lock_pdo_init(struct mdt_lock_handle *lh, ldlm_mode_t lock_mode,
169                        const struct lu_name *lname)
170 {
171         lh->mlh_reg_mode = lock_mode;
172         lh->mlh_rreg_mode = lock_mode;
173         lh->mlh_type = MDT_PDO_LOCK;
174
175         if (lu_name_is_valid(lname)) {
176                 lh->mlh_pdo_hash = full_name_hash(lname->ln_name,
177                                                   lname->ln_namelen);
178                 /* XXX Workaround for LU-2856
179                  *
180                  * Zero is a valid return value of full_name_hash, but
181                  * several users of mlh_pdo_hash assume a non-zero
182                  * hash value. We therefore map zero onto an
183                  * arbitrary, but consistent value (1) to avoid
184                  * problems further down the road. */
185                 if (unlikely(lh->mlh_pdo_hash == 0))
186                         lh->mlh_pdo_hash = 1;
187         } else {
188                 lh->mlh_pdo_hash = 0;
189         }
190 }
191
192 static void mdt_lock_pdo_mode(struct mdt_thread_info *info, struct mdt_object *o,
193                               struct mdt_lock_handle *lh)
194 {
195         mdl_mode_t mode;
196         ENTRY;
197
198         /*
199          * Any dir access needs couple of locks:
200          *
201          * 1) on part of dir we gonna take lookup/modify;
202          *
203          * 2) on whole dir to protect it from concurrent splitting and/or to
204          * flush client's cache for readdir().
205          *
206          * so, for a given mode and object this routine decides what lock mode
207          * to use for lock #2:
208          *
209          * 1) if caller's gonna lookup in dir then we need to protect dir from
210          * being splitted only - LCK_CR
211          *
212          * 2) if caller's gonna modify dir then we need to protect dir from
213          * being splitted and to flush cache - LCK_CW
214          *
215          * 3) if caller's gonna modify dir and that dir seems ready for
216          * splitting then we need to protect it from any type of access
217          * (lookup/modify/split) - LCK_EX --bzzz
218          */
219
220         LASSERT(lh->mlh_reg_mode != LCK_MINMODE);
221         LASSERT(lh->mlh_pdo_mode == LCK_MINMODE);
222
223         /*
224          * Ask underlaying level its opinion about preferable PDO lock mode
225          * having access type passed as regular lock mode:
226          *
227          * - MDL_MINMODE means that lower layer does not want to specify lock
228          * mode;
229          *
230          * - MDL_NL means that no PDO lock should be taken. This is used in some
231          * cases. Say, for non-splittable directories no need to use PDO locks
232          * at all.
233          */
234         mode = mdo_lock_mode(info->mti_env, mdt_object_child(o),
235                              mdt_dlm_mode2mdl_mode(lh->mlh_reg_mode));
236
237         if (mode != MDL_MINMODE) {
238                 lh->mlh_pdo_mode = mdt_mdl_mode2dlm_mode(mode);
239         } else {
240                 /*
241                  * Lower layer does not want to specify locking mode. We do it
242                  * our selves. No special protection is needed, just flush
243                  * client's cache on modification and allow concurrent
244                  * mondification.
245                  */
246                 switch (lh->mlh_reg_mode) {
247                 case LCK_EX:
248                         lh->mlh_pdo_mode = LCK_EX;
249                         break;
250                 case LCK_PR:
251                         lh->mlh_pdo_mode = LCK_CR;
252                         break;
253                 case LCK_PW:
254                         lh->mlh_pdo_mode = LCK_CW;
255                         break;
256                 default:
257                         CERROR("Not expected lock type (0x%x)\n",
258                                (int)lh->mlh_reg_mode);
259                         LBUG();
260                 }
261         }
262
263         LASSERT(lh->mlh_pdo_mode != LCK_MINMODE);
264         EXIT;
265 }
266
267 static int mdt_getstatus(struct tgt_session_info *tsi)
268 {
269         struct mdt_thread_info  *info = tsi2mdt_info(tsi);
270         struct mdt_device       *mdt = info->mti_mdt;
271         struct mdt_body         *repbody;
272         int                      rc;
273
274         ENTRY;
275
276         rc = mdt_check_ucred(info);
277         if (rc)
278                 GOTO(out, rc = err_serious(rc));
279
280         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_GETSTATUS_PACK))
281                 GOTO(out, rc = err_serious(-ENOMEM));
282
283         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
284         repbody->mbo_fid1 = mdt->mdt_md_root_fid;
285         repbody->mbo_valid |= OBD_MD_FLID;
286
287         if (tsi->tsi_tgt->lut_mds_capa &&
288             exp_connect_flags(info->mti_exp) & OBD_CONNECT_MDS_CAPA) {
289                 struct mdt_object       *root;
290                 struct lustre_capa      *capa;
291
292                 root = mdt_object_find(info->mti_env, mdt, &repbody->mbo_fid1);
293                 if (IS_ERR(root))
294                         GOTO(out, rc = PTR_ERR(root));
295
296                 capa = req_capsule_server_get(info->mti_pill, &RMF_CAPA1);
297                 LASSERT(capa);
298                 capa->lc_opc = CAPA_OPC_MDS_DEFAULT;
299                 rc = mo_capa_get(info->mti_env, mdt_object_child(root), capa,
300                                  0);
301                 mdt_object_put(info->mti_env, root);
302                 if (rc == 0)
303                         repbody->mbo_valid |= OBD_MD_FLMDSCAPA;
304         }
305         EXIT;
306 out:
307         mdt_thread_info_fini(info);
308         return rc;
309 }
310
311 static int mdt_statfs(struct tgt_session_info *tsi)
312 {
313         struct ptlrpc_request           *req = tgt_ses_req(tsi);
314         struct mdt_thread_info          *info = tsi2mdt_info(tsi);
315         struct md_device                *next = info->mti_mdt->mdt_child;
316         struct ptlrpc_service_part      *svcpt;
317         struct obd_statfs               *osfs;
318         int                             rc;
319
320         ENTRY;
321
322         svcpt = req->rq_rqbd->rqbd_svcpt;
323
324         /* This will trigger a watchdog timeout */
325         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_STATFS_LCW_SLEEP,
326                          (MDT_SERVICE_WATCHDOG_FACTOR *
327                           at_get(&svcpt->scp_at_estimate)) + 1);
328
329         rc = mdt_check_ucred(info);
330         if (rc)
331                 GOTO(out, rc = err_serious(rc));
332
333         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_STATFS_PACK))
334                 GOTO(out, rc = err_serious(-ENOMEM));
335
336         osfs = req_capsule_server_get(info->mti_pill, &RMF_OBD_STATFS);
337         if (!osfs)
338                 GOTO(out, rc = -EPROTO);
339
340         /** statfs information are cached in the mdt_device */
341         if (cfs_time_before_64(info->mti_mdt->mdt_osfs_age,
342                                cfs_time_shift_64(-OBD_STATFS_CACHE_SECONDS))) {
343                 /** statfs data is too old, get up-to-date one */
344                 rc = next->md_ops->mdo_statfs(info->mti_env, next, osfs);
345                 if (rc)
346                         GOTO(out, rc);
347                 spin_lock(&info->mti_mdt->mdt_osfs_lock);
348                 info->mti_mdt->mdt_osfs = *osfs;
349                 info->mti_mdt->mdt_osfs_age = cfs_time_current_64();
350                 spin_unlock(&info->mti_mdt->mdt_osfs_lock);
351         } else {
352                 /** use cached statfs data */
353                 spin_lock(&info->mti_mdt->mdt_osfs_lock);
354                 *osfs = info->mti_mdt->mdt_osfs;
355                 spin_unlock(&info->mti_mdt->mdt_osfs_lock);
356         }
357
358         if (rc == 0)
359                 mdt_counter_incr(req, LPROC_MDT_STATFS);
360 out:
361         mdt_thread_info_fini(info);
362         RETURN(rc);
363 }
364
365 /**
366  * Pack SOM attributes into the reply.
367  * Call under a DLM UPDATE lock.
368  */
369 static void mdt_pack_size2body(struct mdt_thread_info *info,
370                                struct mdt_object *mo)
371 {
372         struct mdt_body *b;
373         struct md_attr *ma = &info->mti_attr;
374
375         LASSERT(ma->ma_attr.la_valid & LA_MODE);
376         b = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
377
378         /* Check if Size-on-MDS is supported, if this is a regular file,
379          * if SOM is enabled on the object and if SOM cache exists and valid.
380          * Otherwise do not pack Size-on-MDS attributes to the reply. */
381         if (!(mdt_conn_flags(info) & OBD_CONNECT_SOM) ||
382             !S_ISREG(ma->ma_attr.la_mode) ||
383             !mdt_object_is_som_enabled(mo) ||
384             !(ma->ma_valid & MA_SOM))
385                 return;
386
387         b->mbo_valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS;
388         b->mbo_size = ma->ma_som->msd_size;
389         b->mbo_blocks = ma->ma_som->msd_blocks;
390 }
391
392 #ifdef CONFIG_FS_POSIX_ACL
393 /*
394  * Pack ACL data into the reply. UIDs/GIDs are mapped and filtered by nodemap.
395  *
396  * \param       info    thread info object
397  * \param       repbody reply to pack ACLs into
398  * \param       o       mdt object of file to examine
399  * \param       nodemap nodemap of client to reply to
400  * \retval      0       success
401  * \retval      -errno  error getting or parsing ACL from disk
402  */
403 int mdt_pack_acl2body(struct mdt_thread_info *info, struct mdt_body *repbody,
404                       struct mdt_object *o, struct lu_nodemap *nodemap)
405 {
406         const struct lu_env     *env = info->mti_env;
407         struct md_object        *next = mdt_object_child(o);
408         struct lu_buf           *buf = &info->mti_buf;
409         int rc;
410
411         buf->lb_buf = req_capsule_server_get(info->mti_pill, &RMF_ACL);
412         buf->lb_len = req_capsule_get_size(info->mti_pill, &RMF_ACL,
413                                            RCL_SERVER);
414         if (buf->lb_len == 0)
415                 return 0;
416
417         rc = mo_xattr_get(env, next, buf, XATTR_NAME_ACL_ACCESS);
418         if (rc < 0) {
419                 if (rc == -ENODATA) {
420                         repbody->mbo_aclsize = 0;
421                         repbody->mbo_valid |= OBD_MD_FLACL;
422                         rc = 0;
423                 } else if (rc == -EOPNOTSUPP) {
424                         rc = 0;
425                 } else {
426                         CERROR("%s: unable to read "DFID" ACL: rc = %d\n",
427                                mdt_obd_name(info->mti_mdt),
428                                PFID(mdt_object_fid(o)), rc);
429                 }
430         } else {
431                 rc = nodemap_map_acl(nodemap, buf->lb_buf,
432                                      rc, NODEMAP_FS_TO_CLIENT);
433                 /* if all ACLs mapped out, rc is still >= 0 */
434                 if (rc < 0) {
435                         CERROR("%s: nodemap_map_acl unable to parse "DFID
436                                " ACL: rc = %d\n", mdt_obd_name(info->mti_mdt),
437                                PFID(mdt_object_fid(o)), rc);
438                 } else {
439                         repbody->mbo_aclsize = rc;
440                         repbody->mbo_valid |= OBD_MD_FLACL;
441                         rc = 0;
442                 }
443         }
444         return rc;
445 }
446 #endif
447
448 void mdt_pack_attr2body(struct mdt_thread_info *info, struct mdt_body *b,
449                         const struct lu_attr *attr, const struct lu_fid *fid)
450 {
451         struct md_attr          *ma = &info->mti_attr;
452         struct obd_export       *exp = info->mti_exp;
453         struct lu_nodemap       *nodemap = exp->exp_target_data.ted_nodemap;
454
455         LASSERT(ma->ma_valid & MA_INODE);
456
457         if (attr->la_valid & LA_ATIME) {
458                 b->mbo_atime = attr->la_atime;
459                 b->mbo_valid |= OBD_MD_FLATIME;
460         }
461         if (attr->la_valid & LA_MTIME) {
462                 b->mbo_mtime = attr->la_mtime;
463                 b->mbo_valid |= OBD_MD_FLMTIME;
464         }
465         if (attr->la_valid & LA_CTIME) {
466                 b->mbo_ctime = attr->la_ctime;
467                 b->mbo_valid |= OBD_MD_FLCTIME;
468         }
469         if (attr->la_valid & LA_FLAGS) {
470                 b->mbo_flags = attr->la_flags;
471                 b->mbo_valid |= OBD_MD_FLFLAGS;
472         }
473         if (attr->la_valid & LA_NLINK) {
474                 b->mbo_nlink = attr->la_nlink;
475                 b->mbo_valid |= OBD_MD_FLNLINK;
476         }
477         if (attr->la_valid & LA_UID) {
478                 b->mbo_uid = nodemap_map_id(nodemap, NODEMAP_UID,
479                                             NODEMAP_FS_TO_CLIENT,
480                                             attr->la_uid);
481                 b->mbo_valid |= OBD_MD_FLUID;
482         }
483         if (attr->la_valid & LA_GID) {
484                 b->mbo_gid = nodemap_map_id(nodemap, NODEMAP_GID,
485                                             NODEMAP_FS_TO_CLIENT,
486                                             attr->la_gid);
487                 b->mbo_valid |= OBD_MD_FLGID;
488         }
489         b->mbo_mode = attr->la_mode;
490         if (attr->la_valid & LA_MODE)
491                 b->mbo_valid |= OBD_MD_FLMODE;
492         if (attr->la_valid & LA_TYPE)
493                 b->mbo_valid |= OBD_MD_FLTYPE;
494
495         if (fid != NULL) {
496                 b->mbo_fid1 = *fid;
497                 b->mbo_valid |= OBD_MD_FLID;
498                 CDEBUG(D_INODE, DFID": nlink=%d, mode=%o, valid="LPX64"\n",
499                        PFID(fid), b->mbo_nlink, b->mbo_mode, b->mbo_valid);
500         }
501
502         if (info != NULL)
503                 mdt_body_reverse_idmap(info, b);
504
505         if (!(attr->la_valid & LA_TYPE))
506                 return;
507
508         b->mbo_rdev   = attr->la_rdev;
509         b->mbo_size   = attr->la_size;
510         b->mbo_blocks = attr->la_blocks;
511
512         if (!S_ISREG(attr->la_mode)) {
513                 b->mbo_valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS | OBD_MD_FLRDEV;
514         } else if (ma->ma_need & MA_LOV && !(ma->ma_valid & MA_LOV)) {
515                 /* means no objects are allocated on osts. */
516                 LASSERT(!(ma->ma_valid & MA_LOV));
517                 /* just ignore blocks occupied by extend attributes on MDS */
518                 b->mbo_blocks = 0;
519                 /* if no object is allocated on osts, the size on mds is valid.
520                  * b=22272 */
521                 b->mbo_valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS;
522         } else if ((ma->ma_valid & MA_LOV) && ma->ma_lmm != NULL &&
523                    ma->ma_lmm->lmm_pattern & LOV_PATTERN_F_RELEASED) {
524                 /* A released file stores its size on MDS. */
525                 /* But return 1 block for released file, unless tools like tar
526                  * will consider it fully sparse. (LU-3864)
527                  */
528                 if (unlikely(b->mbo_size == 0))
529                         b->mbo_blocks = 0;
530                 else
531                         b->mbo_blocks = 1;
532                 b->mbo_valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS;
533         }
534
535         if (fid != NULL && (b->mbo_valid & OBD_MD_FLSIZE))
536                 CDEBUG(D_VFSTRACE, DFID": returning size %llu\n",
537                        PFID(fid), (unsigned long long)b->mbo_size);
538 }
539
540 static inline int mdt_body_has_lov(const struct lu_attr *la,
541                                    const struct mdt_body *body)
542 {
543         return (S_ISREG(la->la_mode) && (body->mbo_valid & OBD_MD_FLEASIZE)) ||
544                (S_ISDIR(la->la_mode) && (body->mbo_valid & OBD_MD_FLDIREA));
545 }
546
547 void mdt_client_compatibility(struct mdt_thread_info *info)
548 {
549         struct mdt_body       *body;
550         struct ptlrpc_request *req = mdt_info_req(info);
551         struct obd_export     *exp = req->rq_export;
552         struct md_attr        *ma = &info->mti_attr;
553         struct lu_attr        *la = &ma->ma_attr;
554         ENTRY;
555
556         if (exp_connect_layout(exp))
557                 /* the client can deal with 16-bit lmm_stripe_count */
558                 RETURN_EXIT;
559
560         body = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
561
562         if (!mdt_body_has_lov(la, body))
563                 RETURN_EXIT;
564
565         /* now we have a reply with a lov for a client not compatible with the
566          * layout lock so we have to clean the layout generation number */
567         if (S_ISREG(la->la_mode))
568                 ma->ma_lmm->lmm_layout_gen = 0;
569         EXIT;
570 }
571
572 static int mdt_attr_get_eabuf_size(struct mdt_thread_info *info,
573                                    struct mdt_object *o)
574 {
575         const struct lu_env *env = info->mti_env;
576         int rc, rc2;
577
578         rc = mo_xattr_get(env, mdt_object_child(o), &LU_BUF_NULL,
579                           XATTR_NAME_LOV);
580
581         if (rc == -ENODATA)
582                 rc = 0;
583
584         if (rc < 0)
585                 goto out;
586
587         /* Is it a directory? Let's check for the LMV as well */
588         if (S_ISDIR(lu_object_attr(&mdt_object_child(o)->mo_lu))) {
589                 rc2 = mo_xattr_get(env, mdt_object_child(o), &LU_BUF_NULL,
590                                    XATTR_NAME_LMV);
591
592                 if (rc2 == -ENODATA)
593                         rc2 = mo_xattr_get(env, mdt_object_child(o),
594                                            &LU_BUF_NULL,
595                                            XATTR_NAME_DEFAULT_LMV);
596
597                 if ((rc2 < 0 && rc2 != -ENODATA) || (rc2 > rc))
598                         rc = rc2;
599         }
600
601 out:
602         return rc;
603 }
604
605 int mdt_big_xattr_get(struct mdt_thread_info *info, struct mdt_object *o,
606                       const char *name)
607 {
608         const struct lu_env *env = info->mti_env;
609         int rc;
610         ENTRY;
611
612         LASSERT(info->mti_big_lmm_used == 0);
613         rc = mo_xattr_get(env, mdt_object_child(o), &LU_BUF_NULL, name);
614         if (rc < 0)
615                 RETURN(rc);
616
617         /* big_lmm may need to be grown */
618         if (info->mti_big_lmmsize < rc) {
619                 int size = size_roundup_power2(rc);
620
621                 if (info->mti_big_lmmsize > 0) {
622                         /* free old buffer */
623                         LASSERT(info->mti_big_lmm);
624                         OBD_FREE_LARGE(info->mti_big_lmm,
625                                        info->mti_big_lmmsize);
626                         info->mti_big_lmm = NULL;
627                         info->mti_big_lmmsize = 0;
628                 }
629
630                 OBD_ALLOC_LARGE(info->mti_big_lmm, size);
631                 if (info->mti_big_lmm == NULL)
632                         RETURN(-ENOMEM);
633                 info->mti_big_lmmsize = size;
634         }
635         LASSERT(info->mti_big_lmmsize >= rc);
636
637         info->mti_buf.lb_buf = info->mti_big_lmm;
638         info->mti_buf.lb_len = info->mti_big_lmmsize;
639         rc = mo_xattr_get(env, mdt_object_child(o), &info->mti_buf, name);
640
641         RETURN(rc);
642 }
643
644 int mdt_stripe_get(struct mdt_thread_info *info, struct mdt_object *o,
645                    struct md_attr *ma, const char *name)
646 {
647         struct md_object *next = mdt_object_child(o);
648         struct lu_buf    *buf = &info->mti_buf;
649         int rc;
650
651         if (strcmp(name, XATTR_NAME_LOV) == 0) {
652                 buf->lb_buf = ma->ma_lmm;
653                 buf->lb_len = ma->ma_lmm_size;
654                 LASSERT(!(ma->ma_valid & MA_LOV));
655         } else if (strcmp(name, XATTR_NAME_LMV) == 0) {
656                 buf->lb_buf = ma->ma_lmv;
657                 buf->lb_len = ma->ma_lmv_size;
658                 LASSERT(!(ma->ma_valid & MA_LMV));
659         } else if (strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0) {
660                 buf->lb_buf = ma->ma_lmv;
661                 buf->lb_len = ma->ma_lmv_size;
662                 LASSERT(!(ma->ma_valid & MA_LMV_DEF));
663         } else {
664                 return -EINVAL;
665         }
666
667         rc = mo_xattr_get(info->mti_env, next, buf, name);
668         if (rc > 0) {
669
670 got:
671                 if (strcmp(name, XATTR_NAME_LOV) == 0) {
672                         if (info->mti_big_lmm_used)
673                                 ma->ma_lmm = info->mti_big_lmm;
674
675                         /* NOT return LOV EA with hole to old client. */
676                         if (unlikely(le32_to_cpu(ma->ma_lmm->lmm_pattern) &
677                                      LOV_PATTERN_F_HOLE) &&
678                             !(exp_connect_flags(info->mti_exp) &
679                               OBD_CONNECT_LFSCK)) {
680                                 return -EIO;
681                         } else {
682                                 ma->ma_lmm_size = rc;
683                                 ma->ma_valid |= MA_LOV;
684                         }
685                 } else if (strcmp(name, XATTR_NAME_LMV) == 0) {
686                         if (info->mti_big_lmm_used)
687                                 ma->ma_lmv = info->mti_big_lmm;
688
689                         ma->ma_lmv_size = rc;
690                         ma->ma_valid |= MA_LMV;
691                 } else if (strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0) {
692                         ma->ma_lmv_size = rc;
693                         ma->ma_valid |= MA_LMV_DEF;
694                 }
695
696                 /* Update mdt_max_mdsize so all clients will be aware that */
697                 if (info->mti_mdt->mdt_max_mdsize < rc)
698                         info->mti_mdt->mdt_max_mdsize = rc;
699
700                 rc = 0;
701         } else if (rc == -ENODATA) {
702                 /* no LOV EA */
703                 rc = 0;
704         } else if (rc == -ERANGE) {
705                 /* Default LMV has fixed size, so it must be able to fit
706                  * in the original buffer */
707                 if (strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0)
708                         return rc;
709                 rc = mdt_big_xattr_get(info, o, name);
710                 if (rc > 0) {
711                         info->mti_big_lmm_used = 1;
712                         goto got;
713                 }
714         }
715
716         return rc;
717 }
718
719 static int mdt_attr_get_pfid(struct mdt_thread_info *info,
720                              struct mdt_object *o, struct lu_fid *pfid)
721 {
722         struct lu_buf           *buf = &info->mti_buf;
723         struct link_ea_header   *leh;
724         struct link_ea_entry    *lee;
725         int                      rc;
726         ENTRY;
727
728         buf->lb_buf = info->mti_big_lmm;
729         buf->lb_len = info->mti_big_lmmsize;
730         rc = mo_xattr_get(info->mti_env, mdt_object_child(o),
731                           buf, XATTR_NAME_LINK);
732         /* ignore errors, MA_PFID won't be set and it is
733          * up to the caller to treat this as an error */
734         if (rc == -ERANGE || buf->lb_len == 0) {
735                 rc = mdt_big_xattr_get(info, o, XATTR_NAME_LINK);
736                 buf->lb_buf = info->mti_big_lmm;
737                 buf->lb_len = info->mti_big_lmmsize;
738         }
739
740         if (rc < 0)
741                 RETURN(rc);
742         if (rc < sizeof(*leh)) {
743                 CERROR("short LinkEA on "DFID": rc = %d\n",
744                        PFID(mdt_object_fid(o)), rc);
745                 RETURN(-ENODATA);
746         }
747
748         leh = (struct link_ea_header *) buf->lb_buf;
749         lee = (struct link_ea_entry *)(leh + 1);
750         if (leh->leh_magic == __swab32(LINK_EA_MAGIC)) {
751                 leh->leh_magic = LINK_EA_MAGIC;
752                 leh->leh_reccount = __swab32(leh->leh_reccount);
753                 leh->leh_len = __swab64(leh->leh_len);
754         }
755         if (leh->leh_magic != LINK_EA_MAGIC)
756                 RETURN(-EINVAL);
757         if (leh->leh_reccount == 0)
758                 RETURN(-ENODATA);
759
760         memcpy(pfid, &lee->lee_parent_fid, sizeof(*pfid));
761         fid_be_to_cpu(pfid, pfid);
762
763         RETURN(0);
764 }
765
766 int mdt_attr_get_complex(struct mdt_thread_info *info,
767                          struct mdt_object *o, struct md_attr *ma)
768 {
769         const struct lu_env *env = info->mti_env;
770         struct md_object    *next = mdt_object_child(o);
771         struct lu_buf       *buf = &info->mti_buf;
772         int                  need = ma->ma_need;
773         int                  rc = 0, rc2;
774         u32                  mode;
775         ENTRY;
776
777         ma->ma_valid = 0;
778
779         if (mdt_object_exists(o) == 0)
780                 GOTO(out, rc = -ENOENT);
781         mode = lu_object_attr(&next->mo_lu);
782
783         if (need & MA_INODE) {
784                 ma->ma_need = MA_INODE;
785                 rc = mo_attr_get(env, next, ma);
786                 if (rc)
787                         GOTO(out, rc);
788                 ma->ma_valid |= MA_INODE;
789         }
790
791         if (need & MA_PFID) {
792                 rc = mdt_attr_get_pfid(info, o, &ma->ma_pfid);
793                 if (rc == 0)
794                         ma->ma_valid |= MA_PFID;
795                 /* ignore this error, parent fid is not mandatory */
796                 rc = 0;
797         }
798
799         if (need & MA_LOV && (S_ISREG(mode) || S_ISDIR(mode))) {
800                 rc = mdt_stripe_get(info, o, ma, XATTR_NAME_LOV);
801                 if (rc)
802                         GOTO(out, rc);
803         }
804
805         if (need & MA_LMV && S_ISDIR(mode)) {
806                 rc = mdt_stripe_get(info, o, ma, XATTR_NAME_LMV);
807                 if (rc != 0)
808                         GOTO(out, rc);
809         }
810
811         if (need & MA_LMV_DEF && S_ISDIR(mode)) {
812                 rc = mdt_stripe_get(info, o, ma, XATTR_NAME_DEFAULT_LMV);
813                 if (rc != 0)
814                         GOTO(out, rc);
815         }
816
817         if (need & MA_SOM && S_ISREG(mode)) {
818                 buf->lb_buf = info->mti_xattr_buf;
819                 buf->lb_len = sizeof(info->mti_xattr_buf);
820                 CLASSERT(sizeof(struct som_attrs) <=
821                          sizeof(info->mti_xattr_buf));
822                 rc2 = mo_xattr_get(info->mti_env, next, buf, XATTR_NAME_SOM);
823                 rc2 = lustre_buf2som(info->mti_xattr_buf, rc2, ma->ma_som);
824                 if (rc2 == 0)
825                         ma->ma_valid |= MA_SOM;
826                 else if (rc2 < 0 && rc2 != -ENODATA)
827                         GOTO(out, rc = rc2);
828         }
829
830         if (need & MA_HSM && S_ISREG(mode)) {
831                 buf->lb_buf = info->mti_xattr_buf;
832                 buf->lb_len = sizeof(info->mti_xattr_buf);
833                 CLASSERT(sizeof(struct hsm_attrs) <=
834                          sizeof(info->mti_xattr_buf));
835                 rc2 = mo_xattr_get(info->mti_env, next, buf, XATTR_NAME_HSM);
836                 rc2 = lustre_buf2hsm(info->mti_xattr_buf, rc2, &ma->ma_hsm);
837                 if (rc2 == 0)
838                         ma->ma_valid |= MA_HSM;
839                 else if (rc2 < 0 && rc2 != -ENODATA)
840                         GOTO(out, rc = rc2);
841         }
842
843 #ifdef CONFIG_FS_POSIX_ACL
844         if (need & MA_ACL_DEF && S_ISDIR(mode)) {
845                 buf->lb_buf = ma->ma_acl;
846                 buf->lb_len = ma->ma_acl_size;
847                 rc2 = mo_xattr_get(env, next, buf, XATTR_NAME_ACL_DEFAULT);
848                 if (rc2 > 0) {
849                         ma->ma_acl_size = rc2;
850                         ma->ma_valid |= MA_ACL_DEF;
851                 } else if (rc2 == -ENODATA) {
852                         /* no ACLs */
853                         ma->ma_acl_size = 0;
854                 } else
855                         GOTO(out, rc = rc2);
856         }
857 #endif
858 out:
859         ma->ma_need = need;
860         CDEBUG(D_INODE, "after getattr rc = %d, ma_valid = "LPX64" ma_lmm=%p\n",
861                rc, ma->ma_valid, ma->ma_lmm);
862         RETURN(rc);
863 }
864
865 static int mdt_getattr_internal(struct mdt_thread_info *info,
866                                 struct mdt_object *o, int ma_need)
867 {
868         struct md_object        *next = mdt_object_child(o);
869         const struct mdt_body   *reqbody = info->mti_body;
870         struct ptlrpc_request   *req = mdt_info_req(info);
871         struct md_attr          *ma = &info->mti_attr;
872         struct lu_attr          *la = &ma->ma_attr;
873         struct req_capsule      *pill = info->mti_pill;
874         const struct lu_env     *env = info->mti_env;
875         struct mdt_body         *repbody;
876         struct lu_buf           *buffer = &info->mti_buf;
877         struct obd_export       *exp = info->mti_exp;
878         struct lu_nodemap       *nodemap = exp->exp_target_data.ted_nodemap;
879         int                      rc;
880         int                      is_root;
881         ENTRY;
882
883         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_GETATTR_PACK))
884                 RETURN(err_serious(-ENOMEM));
885
886         repbody = req_capsule_server_get(pill, &RMF_MDT_BODY);
887
888         ma->ma_valid = 0;
889
890         if (mdt_object_remote(o)) {
891                 /* This object is located on remote node.*/
892                 /* Return -ENOTSUPP for old client */
893                 if (!mdt_is_dne_client(req->rq_export))
894                         GOTO(out, rc = -ENOTSUPP);
895
896                 repbody->mbo_fid1 = *mdt_object_fid(o);
897                 repbody->mbo_valid = OBD_MD_FLID | OBD_MD_MDS;
898                 GOTO(out, rc = 0);
899         }
900
901         if (reqbody->mbo_eadatasize > 0) {
902                 buffer->lb_buf = req_capsule_server_get(pill, &RMF_MDT_MD);
903                 if (buffer->lb_buf == NULL)
904                         GOTO(out, rc = -EPROTO);
905                 buffer->lb_len = req_capsule_get_size(pill, &RMF_MDT_MD,
906                                                       RCL_SERVER);
907         } else {
908                 buffer->lb_buf = NULL;
909                 buffer->lb_len = 0;
910                 ma_need &= ~(MA_LOV | MA_LMV);
911                 CDEBUG(D_INFO, "%s: RPC from %s: does not need LOVEA.\n",
912                        mdt_obd_name(info->mti_mdt),
913                        req->rq_export->exp_client_uuid.uuid);
914         }
915
916         /* If it is dir object and client require MEA, then we got MEA */
917         if (S_ISDIR(lu_object_attr(&next->mo_lu)) &&
918             (reqbody->mbo_valid & (OBD_MD_MEA | OBD_MD_DEFAULT_MEA))) {
919                 /* Assumption: MDT_MD size is enough for lmv size. */
920                 ma->ma_lmv = buffer->lb_buf;
921                 ma->ma_lmv_size = buffer->lb_len;
922                 ma->ma_need = MA_INODE;
923                 if (ma->ma_lmv_size > 0) {
924                         if (reqbody->mbo_valid & OBD_MD_MEA)
925                                 ma->ma_need |= MA_LMV;
926                         else if (reqbody->mbo_valid & OBD_MD_DEFAULT_MEA)
927                                 ma->ma_need |= MA_LMV_DEF;
928                 }
929         } else {
930                 ma->ma_lmm = buffer->lb_buf;
931                 ma->ma_lmm_size = buffer->lb_len;
932                 ma->ma_need = MA_INODE | MA_HSM;
933                 if (ma->ma_lmm_size > 0)
934                         ma->ma_need |= MA_LOV;
935         }
936
937         if (S_ISDIR(lu_object_attr(&next->mo_lu)) &&
938             reqbody->mbo_valid & OBD_MD_FLDIREA  &&
939             lustre_msg_get_opc(req->rq_reqmsg) == MDS_GETATTR) {
940                 /* get default stripe info for this dir. */
941                 ma->ma_need |= MA_LOV_DEF;
942         }
943         ma->ma_need |= ma_need;
944         if (ma->ma_need & MA_SOM)
945                 ma->ma_som = &info->mti_u.som.data;
946
947         rc = mdt_attr_get_complex(info, o, ma);
948         if (unlikely(rc)) {
949                 CERROR("%s: getattr error for "DFID": rc = %d\n",
950                        mdt_obd_name(info->mti_mdt),
951                        PFID(mdt_object_fid(o)), rc);
952                 RETURN(rc);
953         }
954
955         /* if file is released, check if a restore is running */
956         if ((ma->ma_valid & MA_HSM) && (ma->ma_hsm.mh_flags & HS_RELEASED) &&
957             mdt_hsm_restore_is_running(info, mdt_object_fid(o))) {
958                 repbody->mbo_t_state = MS_RESTORE;
959                 repbody->mbo_valid |= OBD_MD_TSTATE;
960         }
961
962         is_root = lu_fid_eq(mdt_object_fid(o), &info->mti_mdt->mdt_md_root_fid);
963
964         /* the Lustre protocol supposes to return default striping
965          * on the user-visible root if explicitly requested */
966         if ((ma->ma_valid & MA_LOV) == 0 && S_ISDIR(la->la_mode) &&
967             (ma->ma_need & MA_LOV_DEF && is_root) && ma->ma_need & MA_LOV) {
968                 struct lu_fid      rootfid;
969                 struct mdt_object *root;
970                 struct mdt_device *mdt = info->mti_mdt;
971
972                 rc = dt_root_get(env, mdt->mdt_bottom, &rootfid);
973                 if (rc)
974                         RETURN(rc);
975                 root = mdt_object_find(env, mdt, &rootfid);
976                 if (IS_ERR(root))
977                         RETURN(PTR_ERR(root));
978                 rc = mdt_stripe_get(info, root, ma, XATTR_NAME_LOV);
979                 mdt_object_put(info->mti_env, root);
980                 if (unlikely(rc)) {
981                         CERROR("%s: getattr error for "DFID": rc = %d\n",
982                                mdt_obd_name(info->mti_mdt),
983                                PFID(mdt_object_fid(o)), rc);
984                         RETURN(rc);
985                 }
986         }
987
988         if (likely(ma->ma_valid & MA_INODE))
989                 mdt_pack_attr2body(info, repbody, la, mdt_object_fid(o));
990         else
991                 RETURN(-EFAULT);
992
993         if (mdt_body_has_lov(la, reqbody)) {
994                 if (ma->ma_valid & MA_LOV) {
995                         LASSERT(ma->ma_lmm_size);
996                         repbody->mbo_eadatasize = ma->ma_lmm_size;
997                         if (S_ISDIR(la->la_mode))
998                                 repbody->mbo_valid |= OBD_MD_FLDIREA;
999                         else
1000                                 repbody->mbo_valid |= OBD_MD_FLEASIZE;
1001                         mdt_dump_lmm(D_INFO, ma->ma_lmm, repbody->mbo_valid);
1002                 }
1003                 if (ma->ma_valid & MA_LMV) {
1004                         /* Return -ENOTSUPP for old client */
1005                         if (!mdt_is_striped_client(req->rq_export))
1006                                 RETURN(-ENOTSUPP);
1007
1008                         LASSERT(S_ISDIR(la->la_mode));
1009                         mdt_dump_lmv(D_INFO, ma->ma_lmv);
1010                         repbody->mbo_eadatasize = ma->ma_lmv_size;
1011                         repbody->mbo_valid |= (OBD_MD_FLDIREA|OBD_MD_MEA);
1012                 }
1013                 if (ma->ma_valid & MA_LMV_DEF) {
1014                         /* Return -ENOTSUPP for old client */
1015                         if (!mdt_is_striped_client(req->rq_export))
1016                                 RETURN(-ENOTSUPP);
1017                         LASSERT(S_ISDIR(la->la_mode));
1018                         repbody->mbo_eadatasize = ma->ma_lmv_size;
1019                         repbody->mbo_valid |= (OBD_MD_FLDIREA |
1020                                                OBD_MD_DEFAULT_MEA);
1021                 }
1022         } else if (S_ISLNK(la->la_mode) &&
1023                    reqbody->mbo_valid & OBD_MD_LINKNAME) {
1024                 buffer->lb_buf = ma->ma_lmm;
1025                 /* eadatasize from client includes NULL-terminator, so
1026                  * there is no need to read it */
1027                 buffer->lb_len = reqbody->mbo_eadatasize - 1;
1028                 rc = mo_readlink(env, next, buffer);
1029                 if (unlikely(rc <= 0)) {
1030                         CERROR("%s: readlink failed for "DFID": rc = %d\n",
1031                                mdt_obd_name(info->mti_mdt),
1032                                PFID(mdt_object_fid(o)), rc);
1033                         rc = -EFAULT;
1034                 } else {
1035                         int print_limit = min_t(int, PAGE_CACHE_SIZE - 128, rc);
1036
1037                         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_READLINK_EPROTO))
1038                                 rc -= 2;
1039                         repbody->mbo_valid |= OBD_MD_LINKNAME;
1040                         /* we need to report back size with NULL-terminator
1041                          * because client expects that */
1042                         repbody->mbo_eadatasize = rc + 1;
1043                         if (repbody->mbo_eadatasize != reqbody->mbo_eadatasize)
1044                                 CDEBUG(D_INODE, "%s: Read shorter symlink %d "
1045                                        "on "DFID ", expected %d\n",
1046                                        mdt_obd_name(info->mti_mdt),
1047                                        rc, PFID(mdt_object_fid(o)),
1048                                        reqbody->mbo_eadatasize - 1);
1049                         /* NULL terminate */
1050                         ((char *)ma->ma_lmm)[rc] = 0;
1051
1052                         /* If the total CDEBUG() size is larger than a page, it
1053                          * will print a warning to the console, avoid this by
1054                          * printing just the last part of the symlink. */
1055                         CDEBUG(D_INODE, "symlink dest %s%.*s, len = %d\n",
1056                                print_limit < rc ? "..." : "", print_limit,
1057                                (char *)ma->ma_lmm + rc - print_limit, rc);
1058                         rc = 0;
1059                 }
1060         }
1061
1062         if (reqbody->mbo_valid & OBD_MD_FLMODEASIZE) {
1063                 repbody->mbo_max_cookiesize = 0;
1064                 repbody->mbo_max_mdsize = info->mti_mdt->mdt_max_mdsize;
1065                 repbody->mbo_valid |= OBD_MD_FLMODEASIZE;
1066                 CDEBUG(D_INODE, "I am going to change the MAX_MD_SIZE & "
1067                        "MAX_COOKIE to : %d:%d\n", repbody->mbo_max_mdsize,
1068                        repbody->mbo_max_cookiesize);
1069         }
1070
1071         if (exp_connect_rmtclient(info->mti_exp) &&
1072             reqbody->mbo_valid & OBD_MD_FLRMTPERM) {
1073                 void *buf = req_capsule_server_get(pill, &RMF_ACL);
1074
1075                 /* mdt_getattr_lock only */
1076                 rc = mdt_pack_remote_perm(info, o, buf);
1077                 if (rc) {
1078                         repbody->mbo_valid &= ~OBD_MD_FLRMTPERM;
1079                         repbody->mbo_aclsize = 0;
1080                         RETURN(rc);
1081                 } else {
1082                         repbody->mbo_valid |= OBD_MD_FLRMTPERM;
1083                         repbody->mbo_aclsize = sizeof(struct mdt_remote_perm);
1084                 }
1085         }
1086 #ifdef CONFIG_FS_POSIX_ACL
1087         else if ((exp_connect_flags(req->rq_export) & OBD_CONNECT_ACL) &&
1088                  (reqbody->mbo_valid & OBD_MD_FLACL))
1089                 rc = mdt_pack_acl2body(info, repbody, o, nodemap);
1090 #endif
1091
1092         if (reqbody->mbo_valid & OBD_MD_FLMDSCAPA &&
1093             info->mti_mdt->mdt_lut.lut_mds_capa &&
1094             exp_connect_flags(info->mti_exp) & OBD_CONNECT_MDS_CAPA) {
1095                 struct lustre_capa *capa;
1096
1097                 capa = req_capsule_server_get(pill, &RMF_CAPA1);
1098                 LASSERT(capa);
1099                 capa->lc_opc = CAPA_OPC_MDS_DEFAULT;
1100                 rc = mo_capa_get(env, next, capa, 0);
1101                 if (rc)
1102                         RETURN(rc);
1103                 repbody->mbo_valid |= OBD_MD_FLMDSCAPA;
1104         }
1105
1106 out:
1107         if (rc == 0)
1108                 mdt_counter_incr(req, LPROC_MDT_GETATTR);
1109
1110         RETURN(rc);
1111 }
1112
1113 static int mdt_renew_capa(struct mdt_thread_info *info)
1114 {
1115         struct mdt_object  *obj = info->mti_object;
1116         struct mdt_body    *body;
1117         struct lustre_capa *capa, *c;
1118         int rc;
1119         ENTRY;
1120
1121         /* if object doesn't exist, or server has disabled capability,
1122          * return directly, client will find body->valid OBD_MD_FLOSSCAPA
1123          * flag not set.
1124          */
1125         if (!obj || !info->mti_mdt->mdt_lut.lut_oss_capa ||
1126             !(exp_connect_flags(info->mti_exp) & OBD_CONNECT_OSS_CAPA))
1127                 RETURN(0);
1128
1129         body = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
1130         LASSERT(body != NULL);
1131
1132         c = req_capsule_client_get(info->mti_pill, &RMF_CAPA1);
1133         LASSERT(c);
1134
1135         capa = req_capsule_server_get(info->mti_pill, &RMF_CAPA2);
1136         LASSERT(capa);
1137
1138         *capa = *c;
1139         rc = mo_capa_get(info->mti_env, mdt_object_child(obj), capa, 1);
1140         if (rc == 0)
1141                 body->mbo_valid |= OBD_MD_FLOSSCAPA;
1142         RETURN(rc);
1143 }
1144
1145 static int mdt_getattr(struct tgt_session_info *tsi)
1146 {
1147         struct mdt_thread_info  *info = tsi2mdt_info(tsi);
1148         struct mdt_object       *obj = info->mti_object;
1149         struct req_capsule      *pill = info->mti_pill;
1150         struct mdt_body         *reqbody;
1151         struct mdt_body         *repbody;
1152         int rc, rc2;
1153         ENTRY;
1154
1155         reqbody = req_capsule_client_get(pill, &RMF_MDT_BODY);
1156         LASSERT(reqbody);
1157
1158         if (reqbody->mbo_valid & OBD_MD_FLOSSCAPA) {
1159                 rc = req_capsule_server_pack(pill);
1160                 if (unlikely(rc))
1161                         RETURN(err_serious(rc));
1162                 rc = mdt_renew_capa(info);
1163                 GOTO(out_shrink, rc);
1164         }
1165
1166         LASSERT(obj != NULL);
1167         LASSERT(lu_object_assert_exists(&obj->mot_obj));
1168
1169         /* Unlike intent case where we need to pre-fill out buffers early on
1170          * in intent policy for ldlm reasons, here we can have a much better
1171          * guess at EA size by just reading it from disk.
1172          * Exceptions are readdir and (missing) directory striping */
1173         /* Readlink */
1174         if (reqbody->mbo_valid & OBD_MD_LINKNAME) {
1175                 /* No easy way to know how long is the symlink, but it cannot
1176                  * be more than PATH_MAX, so we allocate +1 */
1177                 rc = PATH_MAX + 1;
1178
1179         /* A special case for fs ROOT: getattr there might fetch
1180          * default EA for entire fs, not just for this dir!
1181          */
1182         } else if (lu_fid_eq(mdt_object_fid(obj),
1183                              &info->mti_mdt->mdt_md_root_fid) &&
1184                    (reqbody->mbo_valid & OBD_MD_FLDIREA) &&
1185                    (lustre_msg_get_opc(mdt_info_req(info)->rq_reqmsg) ==
1186                                                                  MDS_GETATTR)) {
1187                 /* Should the default strping be bigger, mdt_fix_reply
1188                  * will reallocate */
1189                 rc = DEF_REP_MD_SIZE;
1190         } else {
1191                 /* Read the actual EA size from disk */
1192                 rc = mdt_attr_get_eabuf_size(info, obj);
1193         }
1194
1195         if (rc < 0)
1196                 GOTO(out, rc = err_serious(rc));
1197
1198         req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER, rc);
1199
1200         rc = req_capsule_server_pack(pill);
1201         if (unlikely(rc != 0))
1202                 GOTO(out, rc = err_serious(rc));
1203
1204         repbody = req_capsule_server_get(pill, &RMF_MDT_BODY);
1205         LASSERT(repbody != NULL);
1206         repbody->mbo_eadatasize = 0;
1207         repbody->mbo_aclsize = 0;
1208
1209         if (reqbody->mbo_valid & OBD_MD_FLRMTPERM)
1210                 rc = mdt_init_ucred(info, reqbody);
1211         else
1212                 rc = mdt_check_ucred(info);
1213         if (unlikely(rc))
1214                 GOTO(out_shrink, rc);
1215
1216         info->mti_cross_ref = !!(reqbody->mbo_valid & OBD_MD_FLCROSSREF);
1217
1218         /*
1219          * Don't check capability at all, because rename might getattr for
1220          * remote obj, and at that time no capability is available.
1221          */
1222         mdt_set_capainfo(info, 1, &reqbody->mbo_fid1, BYPASS_CAPA);
1223         rc = mdt_getattr_internal(info, obj, 0);
1224         if (reqbody->mbo_valid & OBD_MD_FLRMTPERM)
1225                 mdt_exit_ucred(info);
1226         EXIT;
1227 out_shrink:
1228         mdt_client_compatibility(info);
1229         rc2 = mdt_fix_reply(info);
1230         if (rc == 0)
1231                 rc = rc2;
1232 out:
1233         mdt_thread_info_fini(info);
1234         return rc;
1235 }
1236
1237 static int mdt_swap_layouts(struct tgt_session_info *tsi)
1238 {
1239         struct mdt_thread_info  *info;
1240         struct ptlrpc_request   *req = tgt_ses_req(tsi);
1241         struct obd_export       *exp = req->rq_export;
1242         struct mdt_object       *o1, *o2, *o;
1243         struct mdt_lock_handle  *lh1, *lh2;
1244         struct mdc_swap_layouts *msl;
1245         int                      rc;
1246         ENTRY;
1247
1248         /* client does not support layout lock, so layout swaping
1249          * is disabled.
1250          * FIXME: there is a problem for old clients which don't support
1251          * layout lock yet. If those clients have already opened the file
1252          * they won't be notified at all so that old layout may still be
1253          * used to do IO. This can be fixed after file release is landed by
1254          * doing exclusive open and taking full EX ibits lock. - Jinshan */
1255         if (!exp_connect_layout(exp))
1256                 RETURN(-EOPNOTSUPP);
1257
1258         info = tsi2mdt_info(tsi);
1259
1260         if (info->mti_dlm_req != NULL)
1261                 ldlm_request_cancel(req, info->mti_dlm_req, 0, LATF_SKIP);
1262
1263         if (req_capsule_get_size(info->mti_pill, &RMF_CAPA1, RCL_CLIENT))
1264                 mdt_set_capainfo(info, 0, &info->mti_body->mbo_fid1,
1265                                  req_capsule_client_get(info->mti_pill,
1266                                                         &RMF_CAPA1));
1267
1268         if (req_capsule_get_size(info->mti_pill, &RMF_CAPA2, RCL_CLIENT))
1269                 mdt_set_capainfo(info, 1, &info->mti_body->mbo_fid2,
1270                                  req_capsule_client_get(info->mti_pill,
1271                                                         &RMF_CAPA2));
1272
1273         o1 = info->mti_object;
1274         o = o2 = mdt_object_find(info->mti_env, info->mti_mdt,
1275                                 &info->mti_body->mbo_fid2);
1276         if (IS_ERR(o))
1277                 GOTO(out, rc = PTR_ERR(o));
1278
1279         if (mdt_object_remote(o) || !mdt_object_exists(o)) /* remote object */
1280                 GOTO(put, rc = -ENOENT);
1281
1282         rc = lu_fid_cmp(&info->mti_body->mbo_fid1, &info->mti_body->mbo_fid2);
1283         if (unlikely(rc == 0)) /* same file, you kidding me? no-op. */
1284                 GOTO(put, rc);
1285
1286         if (rc < 0)
1287                 swap(o1, o2);
1288
1289         /* permission check. Make sure the calling process having permission
1290          * to write both files. */
1291         rc = mo_permission(info->mti_env, NULL, mdt_object_child(o1), NULL,
1292                                 MAY_WRITE);
1293         if (rc < 0)
1294                 GOTO(put, rc);
1295
1296         rc = mo_permission(info->mti_env, NULL, mdt_object_child(o2), NULL,
1297                                 MAY_WRITE);
1298         if (rc < 0)
1299                 GOTO(put, rc);
1300
1301         msl = req_capsule_client_get(info->mti_pill, &RMF_SWAP_LAYOUTS);
1302         if (msl == NULL)
1303                 GOTO(put, rc = -EPROTO);
1304
1305         lh1 = &info->mti_lh[MDT_LH_NEW];
1306         mdt_lock_reg_init(lh1, LCK_EX);
1307         lh2 = &info->mti_lh[MDT_LH_OLD];
1308         mdt_lock_reg_init(lh2, LCK_EX);
1309
1310         rc = mdt_object_lock(info, o1, lh1, MDS_INODELOCK_LAYOUT |
1311                              MDS_INODELOCK_XATTR, MDT_LOCAL_LOCK);
1312         if (rc < 0)
1313                 GOTO(put, rc);
1314
1315         rc = mdt_object_lock(info, o2, lh2, MDS_INODELOCK_LAYOUT |
1316                              MDS_INODELOCK_XATTR, MDT_LOCAL_LOCK);
1317         if (rc < 0)
1318                 GOTO(unlock1, rc);
1319
1320         rc = mo_swap_layouts(info->mti_env, mdt_object_child(o1),
1321                              mdt_object_child(o2), msl->msl_flags);
1322         GOTO(unlock2, rc);
1323 unlock2:
1324         mdt_object_unlock(info, o2, lh2, rc);
1325 unlock1:
1326         mdt_object_unlock(info, o1, lh1, rc);
1327 put:
1328         mdt_object_put(info->mti_env, o);
1329 out:
1330         mdt_thread_info_fini(info);
1331         RETURN(rc);
1332 }
1333
1334 static int mdt_raw_lookup(struct mdt_thread_info *info,
1335                           struct mdt_object *parent,
1336                           const struct lu_name *lname,
1337                           struct ldlm_reply *ldlm_rep)
1338 {
1339         struct lu_fid   *child_fid = &info->mti_tmp_fid1;
1340         int              rc;
1341         ENTRY;
1342
1343         LASSERT(!info->mti_cross_ref);
1344
1345         /* Only got the fid of this obj by name */
1346         fid_zero(child_fid);
1347         rc = mdo_lookup(info->mti_env, mdt_object_child(info->mti_object),
1348                         lname, child_fid, &info->mti_spec);
1349         if (rc == 0) {
1350                 struct mdt_body *repbody;
1351
1352                 repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
1353                 repbody->mbo_fid1 = *child_fid;
1354                 repbody->mbo_valid = OBD_MD_FLID;
1355                 mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_POS);
1356         } else if (rc == -ENOENT) {
1357                 mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_NEG);
1358         }
1359
1360         RETURN(rc);
1361 }
1362
1363 /*
1364  * UPDATE lock should be taken against parent, and be release before exit;
1365  * child_bits lock should be taken against child, and be returned back:
1366  *            (1)normal request should release the child lock;
1367  *            (2)intent request will grant the lock to client.
1368  */
1369 static int mdt_getattr_name_lock(struct mdt_thread_info *info,
1370                                  struct mdt_lock_handle *lhc,
1371                                  __u64 child_bits,
1372                                  struct ldlm_reply *ldlm_rep)
1373 {
1374         struct ptlrpc_request  *req       = mdt_info_req(info);
1375         struct mdt_body        *reqbody   = NULL;
1376         struct mdt_object      *parent    = info->mti_object;
1377         struct mdt_object      *child;
1378         struct lu_fid          *child_fid = &info->mti_tmp_fid1;
1379         struct lu_name         *lname     = NULL;
1380         struct mdt_lock_handle *lhp       = NULL;
1381         struct ldlm_lock       *lock;
1382         bool                    is_resent;
1383         bool                    try_layout;
1384         int                     ma_need = 0;
1385         int                     rc;
1386         ENTRY;
1387
1388         is_resent = lustre_handle_is_used(&lhc->mlh_reg_lh);
1389         LASSERT(ergo(is_resent,
1390                      lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT));
1391
1392         if (parent == NULL)
1393                 RETURN(-ENOENT);
1394
1395         if (info->mti_cross_ref) {
1396                 /* Only getattr on the child. Parent is on another node. */
1397                 mdt_set_disposition(info, ldlm_rep,
1398                                     DISP_LOOKUP_EXECD | DISP_LOOKUP_POS);
1399                 child = parent;
1400                 CDEBUG(D_INODE, "partial getattr_name child_fid = "DFID", "
1401                        "ldlm_rep = %p\n",
1402                        PFID(mdt_object_fid(child)), ldlm_rep);
1403
1404                 rc = mdt_check_resent_lock(info, child, lhc);
1405                 if (rc < 0) {
1406                         RETURN(rc);
1407                 } else if (rc > 0) {
1408                         mdt_lock_handle_init(lhc);
1409                         mdt_lock_reg_init(lhc, LCK_PR);
1410
1411                         /*
1412                          * Object's name is on another MDS, no lookup or layout
1413                          * lock is needed here but update lock is.
1414                          */
1415                         child_bits &= ~(MDS_INODELOCK_LOOKUP |
1416                                         MDS_INODELOCK_LAYOUT);
1417                         child_bits |= MDS_INODELOCK_PERM | MDS_INODELOCK_UPDATE;
1418
1419                         rc = mdt_object_lock(info, child, lhc, child_bits,
1420                                              MDT_LOCAL_LOCK);
1421                         if (rc < 0)
1422                                 RETURN(rc);
1423                 }
1424
1425                 /* Finally, we can get attr for child. */
1426                 if (!mdt_object_exists(child)) {
1427                         LU_OBJECT_DEBUG(D_INFO, info->mti_env,
1428                                         &child->mot_obj,
1429                                         "remote object doesn't exist.\n");
1430                         mdt_object_unlock(info, child, lhc, 1);
1431                         RETURN(-ENOENT);
1432                 }
1433
1434                 mdt_set_capainfo(info, 0, mdt_object_fid(child), BYPASS_CAPA);
1435                 rc = mdt_getattr_internal(info, child, 0);
1436                 if (unlikely(rc != 0))
1437                         mdt_object_unlock(info, child, lhc, 1);
1438
1439                 RETURN(rc);
1440         }
1441
1442         lname = &info->mti_name;
1443         mdt_name_unpack(info->mti_pill, &RMF_NAME, lname, MNF_FIX_ANON);
1444
1445         if (lu_name_is_valid(lname)) {
1446                 CDEBUG(D_INODE, "getattr with lock for "DFID"/"DNAME", "
1447                        "ldlm_rep = %p\n", PFID(mdt_object_fid(parent)),
1448                        PNAME(lname), ldlm_rep);
1449         } else {
1450                 reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
1451                 if (unlikely(reqbody == NULL))
1452                         RETURN(err_serious(-EPROTO));
1453
1454                 *child_fid = reqbody->mbo_fid2;
1455
1456                 if (unlikely(!fid_is_sane(child_fid)))
1457                         RETURN(err_serious(-EINVAL));
1458
1459                 CDEBUG(D_INODE, "getattr with lock for "DFID"/"DFID", "
1460                        "ldlm_rep = %p\n",
1461                        PFID(mdt_object_fid(parent)),
1462                        PFID(&reqbody->mbo_fid2), ldlm_rep);
1463         }
1464
1465         mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_EXECD);
1466
1467         if (unlikely(!mdt_object_exists(parent)) && lu_name_is_valid(lname)) {
1468                 LU_OBJECT_DEBUG(D_INODE, info->mti_env,
1469                                 &parent->mot_obj,
1470                                 "Parent doesn't exist!\n");
1471                 RETURN(-ESTALE);
1472         }
1473
1474         if (mdt_object_remote(parent)) {
1475                 CERROR("%s: parent "DFID" is on remote target\n",
1476                        mdt_obd_name(info->mti_mdt),
1477                        PFID(mdt_object_fid(parent)));
1478                 RETURN(-EIO);
1479         }
1480
1481         if (lu_name_is_valid(lname)) {
1482                 /* Always allow to lookup ".." */
1483                 if (unlikely(lname->ln_namelen == 2 &&
1484                              lname->ln_name[0] == '.' &&
1485                              lname->ln_name[1] == '.'))
1486                         info->mti_spec.sp_permitted = 1;
1487
1488                 if (info->mti_body->mbo_valid == OBD_MD_FLID) {
1489                         rc = mdt_raw_lookup(info, parent, lname, ldlm_rep);
1490
1491                         RETURN(rc);
1492                 }
1493
1494                 /* step 1: lock parent only if parent is a directory */
1495                 if (S_ISDIR(lu_object_attr(&parent->mot_obj))) {
1496                         lhp = &info->mti_lh[MDT_LH_PARENT];
1497                         mdt_lock_pdo_init(lhp, LCK_PR, lname);
1498                         rc = mdt_object_lock(info, parent, lhp,
1499                                              MDS_INODELOCK_UPDATE,
1500                                              MDT_LOCAL_LOCK);
1501                         if (unlikely(rc != 0))
1502                                 RETURN(rc);
1503                 }
1504
1505                 /* step 2: lookup child's fid by name */
1506                 fid_zero(child_fid);
1507                 rc = mdo_lookup(info->mti_env, mdt_object_child(parent), lname,
1508                                 child_fid, &info->mti_spec);
1509                 if (rc == -ENOENT)
1510                         mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_NEG);
1511
1512                 if (rc != 0)
1513                         GOTO(out_parent, rc);
1514         }
1515
1516         mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_POS);
1517
1518         /*
1519          *step 3: find the child object by fid & lock it.
1520          *        regardless if it is local or remote.
1521          *
1522          *Note: LU-3240 (commit 762f2114d282a98ebfa4dbbeea9298a8088ad24e)
1523          *      set parent dir fid the same as child fid in getattr by fid case
1524          *      we should not lu_object_find() the object again, could lead
1525          *      to hung if there is a concurrent unlink destroyed the object.
1526          */
1527         if (lu_fid_eq(mdt_object_fid(parent), child_fid)) {
1528                 mdt_object_get(info->mti_env, parent);
1529                 child = parent;
1530         } else {
1531                 child = mdt_object_find(info->mti_env, info->mti_mdt,
1532                                         child_fid);
1533         }
1534
1535         if (unlikely(IS_ERR(child)))
1536                 GOTO(out_parent, rc = PTR_ERR(child));
1537
1538         rc = mdt_check_resent_lock(info, child, lhc);
1539         if (rc < 0) {
1540                 GOTO(out_child, rc);
1541         } else if (rc > 0) {
1542                 OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_RESEND, obd_timeout*2);
1543                 mdt_lock_handle_init(lhc);
1544                 mdt_lock_reg_init(lhc, LCK_PR);
1545                 try_layout = false;
1546
1547                 if (!mdt_object_exists(child)) {
1548                         LU_OBJECT_DEBUG(D_INODE, info->mti_env,
1549                                         &child->mot_obj,
1550                                         "Object doesn't exist!\n");
1551                         GOTO(out_child, rc = -ENOENT);
1552                 }
1553
1554                 if (!(child_bits & MDS_INODELOCK_UPDATE) &&
1555                       mdt_object_exists(child) && !mdt_object_remote(child)) {
1556                         struct md_attr *ma = &info->mti_attr;
1557
1558                         ma->ma_valid = 0;
1559                         ma->ma_need = MA_INODE;
1560                         rc = mdt_attr_get_complex(info, child, ma);
1561                         if (unlikely(rc != 0))
1562                                 GOTO(out_child, rc);
1563
1564                         /* If the file has not been changed for some time, we
1565                          * return not only a LOOKUP lock, but also an UPDATE
1566                          * lock and this might save us RPC on later STAT. For
1567                          * directories, it also let negative dentry cache start
1568                          * working for this dir. */
1569                         if (ma->ma_valid & MA_INODE &&
1570                             ma->ma_attr.la_valid & LA_CTIME &&
1571                             info->mti_mdt->mdt_namespace->ns_ctime_age_limit +
1572                                 ma->ma_attr.la_ctime < cfs_time_current_sec())
1573                                 child_bits |= MDS_INODELOCK_UPDATE;
1574                 }
1575
1576                 /* layout lock must be granted in a best-effort way
1577                  * for IT operations */
1578                 LASSERT(!(child_bits & MDS_INODELOCK_LAYOUT));
1579                 if (!OBD_FAIL_CHECK(OBD_FAIL_MDS_NO_LL_GETATTR) &&
1580                     exp_connect_layout(info->mti_exp) &&
1581                     S_ISREG(lu_object_attr(&child->mot_obj)) &&
1582                     !mdt_object_remote(child) && ldlm_rep != NULL) {
1583                         /* try to grant layout lock for regular file. */
1584                         try_layout = true;
1585                 }
1586
1587                 rc = 0;
1588                 if (try_layout) {
1589                         child_bits |= MDS_INODELOCK_LAYOUT;
1590                         /* try layout lock, it may fail to be granted due to
1591                          * contention at LOOKUP or UPDATE */
1592                         if (!mdt_object_lock_try(info, child, lhc, child_bits,
1593                                                  MDT_CROSS_LOCK)) {
1594                                 child_bits &= ~MDS_INODELOCK_LAYOUT;
1595                                 LASSERT(child_bits != 0);
1596                                 rc = mdt_object_lock(info, child, lhc,
1597                                                 child_bits, MDT_CROSS_LOCK);
1598                         } else {
1599                                 ma_need |= MA_LOV;
1600                         }
1601                 } else {
1602                         /* Do not enqueue the UPDATE lock from MDT(cross-MDT),
1603                          * client will enqueue the lock to the remote MDT */
1604                         if (mdt_object_remote(child))
1605                                 child_bits &= ~MDS_INODELOCK_UPDATE;
1606                         rc = mdt_object_lock(info, child, lhc, child_bits,
1607                                                 MDT_CROSS_LOCK);
1608                 }
1609                 if (unlikely(rc != 0))
1610                         GOTO(out_child, rc);
1611         }
1612
1613         lock = ldlm_handle2lock(&lhc->mlh_reg_lh);
1614         /* Get MA_SOM attributes if update lock is given. */
1615         if (lock &&
1616             lock->l_policy_data.l_inodebits.bits & MDS_INODELOCK_UPDATE &&
1617             S_ISREG(lu_object_attr(&mdt_object_child(child)->mo_lu)))
1618                 ma_need |= MA_SOM;
1619
1620         /* finally, we can get attr for child. */
1621         mdt_set_capainfo(info, 1, child_fid, BYPASS_CAPA);
1622         rc = mdt_getattr_internal(info, child, ma_need);
1623         if (unlikely(rc != 0)) {
1624                 mdt_object_unlock(info, child, lhc, 1);
1625         } else if (lock) {
1626                 /* Debugging code. */
1627                 LDLM_DEBUG(lock, "Returning lock to client");
1628                 LASSERTF(fid_res_name_eq(mdt_object_fid(child),
1629                                          &lock->l_resource->lr_name),
1630                          "Lock res_id: "DLDLMRES", fid: "DFID"\n",
1631                          PLDLMRES(lock->l_resource),
1632                          PFID(mdt_object_fid(child)));
1633                 if (mdt_object_exists(child) && !mdt_object_remote(child))
1634                         mdt_pack_size2body(info, child);
1635         }
1636         if (lock)
1637                 LDLM_LOCK_PUT(lock);
1638
1639         EXIT;
1640 out_child:
1641         mdt_object_put(info->mti_env, child);
1642 out_parent:
1643         if (lhp)
1644                 mdt_object_unlock(info, parent, lhp, 1);
1645         return rc;
1646 }
1647
1648 /* normal handler: should release the child lock */
1649 static int mdt_getattr_name(struct tgt_session_info *tsi)
1650 {
1651         struct mdt_thread_info  *info = tsi2mdt_info(tsi);
1652         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_CHILD];
1653         struct mdt_body        *reqbody;
1654         struct mdt_body        *repbody;
1655         int rc, rc2;
1656         ENTRY;
1657
1658         reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
1659         LASSERT(reqbody != NULL);
1660         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
1661         LASSERT(repbody != NULL);
1662
1663         info->mti_cross_ref = !!(reqbody->mbo_valid & OBD_MD_FLCROSSREF);
1664         repbody->mbo_eadatasize = 0;
1665         repbody->mbo_aclsize = 0;
1666
1667         rc = mdt_init_ucred(info, reqbody);
1668         if (unlikely(rc))
1669                 GOTO(out_shrink, rc);
1670
1671         rc = mdt_getattr_name_lock(info, lhc, MDS_INODELOCK_UPDATE, NULL);
1672         if (lustre_handle_is_used(&lhc->mlh_reg_lh)) {
1673                 ldlm_lock_decref(&lhc->mlh_reg_lh, lhc->mlh_reg_mode);
1674                 lhc->mlh_reg_lh.cookie = 0;
1675         }
1676         mdt_exit_ucred(info);
1677         EXIT;
1678 out_shrink:
1679         mdt_client_compatibility(info);
1680         rc2 = mdt_fix_reply(info);
1681         if (rc == 0)
1682                 rc = rc2;
1683         mdt_thread_info_fini(info);
1684         return rc;
1685 }
1686
1687 static int mdt_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
1688                          void *karg, void *uarg);
1689
1690 static int mdt_set_info(struct tgt_session_info *tsi)
1691 {
1692         struct ptlrpc_request   *req = tgt_ses_req(tsi);
1693         char                    *key;
1694         void                    *val;
1695         int                      keylen, vallen, rc = 0;
1696
1697         ENTRY;
1698
1699         key = req_capsule_client_get(tsi->tsi_pill, &RMF_SETINFO_KEY);
1700         if (key == NULL) {
1701                 DEBUG_REQ(D_HA, req, "no set_info key");
1702                 RETURN(err_serious(-EFAULT));
1703         }
1704
1705         keylen = req_capsule_get_size(tsi->tsi_pill, &RMF_SETINFO_KEY,
1706                                       RCL_CLIENT);
1707
1708         val = req_capsule_client_get(tsi->tsi_pill, &RMF_SETINFO_VAL);
1709         if (val == NULL) {
1710                 DEBUG_REQ(D_HA, req, "no set_info val");
1711                 RETURN(err_serious(-EFAULT));
1712         }
1713
1714         vallen = req_capsule_get_size(tsi->tsi_pill, &RMF_SETINFO_VAL,
1715                                       RCL_CLIENT);
1716
1717         /* Swab any part of val you need to here */
1718         if (KEY_IS(KEY_READ_ONLY)) {
1719                 spin_lock(&req->rq_export->exp_lock);
1720                 if (*(__u32 *)val)
1721                         *exp_connect_flags_ptr(req->rq_export) |=
1722                                 OBD_CONNECT_RDONLY;
1723                 else
1724                         *exp_connect_flags_ptr(req->rq_export) &=
1725                                 ~OBD_CONNECT_RDONLY;
1726                 spin_unlock(&req->rq_export->exp_lock);
1727         } else if (KEY_IS(KEY_CHANGELOG_CLEAR)) {
1728                 struct changelog_setinfo *cs = val;
1729
1730                 if (vallen != sizeof(*cs)) {
1731                         CERROR("%s: bad changelog_clear setinfo size %d\n",
1732                                tgt_name(tsi->tsi_tgt), vallen);
1733                         RETURN(-EINVAL);
1734                 }
1735                 if (ptlrpc_req_need_swab(req)) {
1736                         __swab64s(&cs->cs_recno);
1737                         __swab32s(&cs->cs_id);
1738                 }
1739
1740                 rc = mdt_iocontrol(OBD_IOC_CHANGELOG_CLEAR, req->rq_export,
1741                                    vallen, val, NULL);
1742         } else {
1743                 RETURN(-EINVAL);
1744         }
1745         RETURN(rc);
1746 }
1747
1748 static int mdt_readpage(struct tgt_session_info *tsi)
1749 {
1750         struct mdt_thread_info  *info = mdt_th_info(tsi->tsi_env);
1751         struct mdt_object       *object = mdt_obj(tsi->tsi_corpus);
1752         struct lu_rdpg          *rdpg = &info->mti_u.rdpg.mti_rdpg;
1753         const struct mdt_body   *reqbody = tsi->tsi_mdt_body;
1754         struct mdt_body         *repbody;
1755         int                      rc;
1756         int                      i;
1757
1758         ENTRY;
1759
1760         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_READPAGE_PACK))
1761                 RETURN(err_serious(-ENOMEM));
1762
1763         repbody = req_capsule_server_get(tsi->tsi_pill, &RMF_MDT_BODY);
1764         if (repbody == NULL || reqbody == NULL)
1765                 RETURN(err_serious(-EFAULT));
1766
1767         /*
1768          * prepare @rdpg before calling lower layers and transfer itself. Here
1769          * reqbody->size contains offset of where to start to read and
1770          * reqbody->nlink contains number bytes to read.
1771          */
1772         rdpg->rp_hash = reqbody->mbo_size;
1773         if (rdpg->rp_hash != reqbody->mbo_size) {
1774                 CERROR("Invalid hash: "LPX64" != "LPX64"\n",
1775                        rdpg->rp_hash, reqbody->mbo_size);
1776                 RETURN(-EFAULT);
1777         }
1778
1779         rdpg->rp_attrs = reqbody->mbo_mode;
1780         if (exp_connect_flags(tsi->tsi_exp) & OBD_CONNECT_64BITHASH)
1781                 rdpg->rp_attrs |= LUDA_64BITHASH;
1782         rdpg->rp_count  = min_t(unsigned int, reqbody->mbo_nlink,
1783                                 exp_max_brw_size(tsi->tsi_exp));
1784         rdpg->rp_npages = (rdpg->rp_count + PAGE_CACHE_SIZE - 1) >>
1785                           PAGE_CACHE_SHIFT;
1786         OBD_ALLOC(rdpg->rp_pages, rdpg->rp_npages * sizeof rdpg->rp_pages[0]);
1787         if (rdpg->rp_pages == NULL)
1788                 RETURN(-ENOMEM);
1789
1790         for (i = 0; i < rdpg->rp_npages; ++i) {
1791                 rdpg->rp_pages[i] = alloc_page(GFP_IOFS);
1792                 if (rdpg->rp_pages[i] == NULL)
1793                         GOTO(free_rdpg, rc = -ENOMEM);
1794         }
1795
1796         /* call lower layers to fill allocated pages with directory data */
1797         rc = mo_readpage(tsi->tsi_env, mdt_object_child(object), rdpg);
1798         if (rc < 0)
1799                 GOTO(free_rdpg, rc);
1800
1801         /* send pages to client */
1802         rc = tgt_sendpage(tsi, rdpg, rc);
1803
1804         EXIT;
1805 free_rdpg:
1806
1807         for (i = 0; i < rdpg->rp_npages; i++)
1808                 if (rdpg->rp_pages[i] != NULL)
1809                         __free_page(rdpg->rp_pages[i]);
1810         OBD_FREE(rdpg->rp_pages, rdpg->rp_npages * sizeof rdpg->rp_pages[0]);
1811
1812         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_SENDPAGE))
1813                 RETURN(0);
1814
1815         return rc;
1816 }
1817
1818 static int mdt_reint_internal(struct mdt_thread_info *info,
1819                               struct mdt_lock_handle *lhc,
1820                               __u32 op)
1821 {
1822         struct req_capsule      *pill = info->mti_pill;
1823         struct mdt_body         *repbody;
1824         int                      rc = 0, rc2;
1825
1826         ENTRY;
1827
1828         rc = mdt_reint_unpack(info, op);
1829         if (rc != 0) {
1830                 CERROR("Can't unpack reint, rc %d\n", rc);
1831                 RETURN(err_serious(rc));
1832         }
1833
1834         /* for replay (no_create) lmm is not needed, client has it already */
1835         if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
1836                 req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER,
1837                                      DEF_REP_MD_SIZE);
1838
1839         /* llog cookies are always 0, the field is kept for compatibility */
1840         if (req_capsule_has_field(pill, &RMF_LOGCOOKIES, RCL_SERVER))
1841                 req_capsule_set_size(pill, &RMF_LOGCOOKIES, RCL_SERVER, 0);
1842
1843         rc = req_capsule_server_pack(pill);
1844         if (rc != 0) {
1845                 CERROR("Can't pack response, rc %d\n", rc);
1846                 RETURN(err_serious(rc));
1847         }
1848
1849         if (req_capsule_has_field(pill, &RMF_MDT_BODY, RCL_SERVER)) {
1850                 repbody = req_capsule_server_get(pill, &RMF_MDT_BODY);
1851                 LASSERT(repbody);
1852                 repbody->mbo_eadatasize = 0;
1853                 repbody->mbo_aclsize = 0;
1854         }
1855
1856         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_REINT_DELAY, 10);
1857
1858         /* for replay no cookkie / lmm need, because client have this already */
1859         if (info->mti_spec.no_create)
1860                 if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
1861                         req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER, 0);
1862
1863         rc = mdt_init_ucred_reint(info);
1864         if (rc)
1865                 GOTO(out_shrink, rc);
1866
1867         rc = mdt_fix_attr_ucred(info, op);
1868         if (rc != 0)
1869                 GOTO(out_ucred, rc = err_serious(rc));
1870
1871         if (mdt_check_resent(info, mdt_reconstruct, lhc)) {
1872                 DEBUG_REQ(D_INODE, mdt_info_req(info), "resent opt.");
1873                 rc = lustre_msg_get_status(mdt_info_req(info)->rq_repmsg);
1874                 GOTO(out_ucred, rc);
1875         }
1876         rc = mdt_reint_rec(info, lhc);
1877         EXIT;
1878 out_ucred:
1879         mdt_exit_ucred(info);
1880 out_shrink:
1881         mdt_client_compatibility(info);
1882         rc2 = mdt_fix_reply(info);
1883         if (rc == 0)
1884                 rc = rc2;
1885         return rc;
1886 }
1887
1888 static long mdt_reint_opcode(struct ptlrpc_request *req,
1889                              const struct req_format **fmt)
1890 {
1891         struct mdt_device       *mdt;
1892         struct mdt_rec_reint    *rec;
1893         long                     opc;
1894
1895         rec = req_capsule_client_get(&req->rq_pill, &RMF_REC_REINT);
1896         if (rec != NULL) {
1897                 opc = rec->rr_opcode;
1898                 DEBUG_REQ(D_INODE, req, "reint opt = %ld", opc);
1899                 if (opc < REINT_MAX && fmt[opc] != NULL)
1900                         req_capsule_extend(&req->rq_pill, fmt[opc]);
1901                 else {
1902                         mdt = mdt_exp2dev(req->rq_export);
1903                         CERROR("%s: Unsupported opcode '%ld' from client '%s':"
1904                                " rc = %d\n", req->rq_export->exp_obd->obd_name,
1905                                opc, mdt->mdt_ldlm_client->cli_name, -EFAULT);
1906                         opc = err_serious(-EFAULT);
1907                 }
1908         } else {
1909                 opc = err_serious(-EFAULT);
1910         }
1911         return opc;
1912 }
1913
1914 static int mdt_reint(struct tgt_session_info *tsi)
1915 {
1916         long opc;
1917         int  rc;
1918         static const struct req_format *reint_fmts[REINT_MAX] = {
1919                 [REINT_SETATTR]  = &RQF_MDS_REINT_SETATTR,
1920                 [REINT_CREATE]   = &RQF_MDS_REINT_CREATE,
1921                 [REINT_LINK]     = &RQF_MDS_REINT_LINK,
1922                 [REINT_UNLINK]   = &RQF_MDS_REINT_UNLINK,
1923                 [REINT_RENAME]   = &RQF_MDS_REINT_RENAME,
1924                 [REINT_OPEN]     = &RQF_MDS_REINT_OPEN,
1925                 [REINT_SETXATTR] = &RQF_MDS_REINT_SETXATTR,
1926                 [REINT_RMENTRY]  = &RQF_MDS_REINT_UNLINK,
1927                 [REINT_MIGRATE]  = &RQF_MDS_REINT_RENAME
1928         };
1929
1930         ENTRY;
1931
1932         opc = mdt_reint_opcode(tgt_ses_req(tsi), reint_fmts);
1933         if (opc >= 0) {
1934                 struct mdt_thread_info *info = tsi2mdt_info(tsi);
1935                 /*
1936                  * No lock possible here from client to pass it to reint code
1937                  * path.
1938                  */
1939                 rc = mdt_reint_internal(info, NULL, opc);
1940                 mdt_thread_info_fini(info);
1941         } else {
1942                 rc = opc;
1943         }
1944
1945         tsi->tsi_reply_fail_id = OBD_FAIL_MDS_REINT_NET_REP;
1946         RETURN(rc);
1947 }
1948
1949 /* this should sync the whole device */
1950 static int mdt_device_sync(const struct lu_env *env, struct mdt_device *mdt)
1951 {
1952         struct dt_device *dt = mdt->mdt_bottom;
1953         int rc;
1954         ENTRY;
1955
1956         rc = dt->dd_ops->dt_sync(env, dt);
1957         RETURN(rc);
1958 }
1959
1960 /* this should sync this object */
1961 static int mdt_object_sync(struct mdt_thread_info *info)
1962 {
1963         struct md_object *next;
1964         int rc;
1965         ENTRY;
1966
1967         if (!mdt_object_exists(info->mti_object)) {
1968                 CWARN("%s: non existing object "DFID": rc = %d\n",
1969                       mdt_obd_name(info->mti_mdt),
1970                       PFID(mdt_object_fid(info->mti_object)), -ESTALE);
1971                 RETURN(-ESTALE);
1972         }
1973         next = mdt_object_child(info->mti_object);
1974         rc = mo_object_sync(info->mti_env, next);
1975
1976         RETURN(rc);
1977 }
1978
1979 static int mdt_sync(struct tgt_session_info *tsi)
1980 {
1981         struct ptlrpc_request   *req = tgt_ses_req(tsi);
1982         struct req_capsule      *pill = tsi->tsi_pill;
1983         struct mdt_body         *body;
1984         int                      rc;
1985
1986         ENTRY;
1987
1988         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_SYNC_PACK))
1989                 RETURN(err_serious(-ENOMEM));
1990
1991         if (fid_seq(&tsi->tsi_mdt_body->mbo_fid1) == 0) {
1992                 rc = mdt_device_sync(tsi->tsi_env, mdt_exp2dev(tsi->tsi_exp));
1993         } else {
1994                 struct mdt_thread_info *info = tsi2mdt_info(tsi);
1995
1996                 /* sync an object */
1997                 rc = mdt_object_sync(info);
1998                 if (rc == 0) {
1999                         const struct lu_fid *fid;
2000                         struct lu_attr *la = &info->mti_attr.ma_attr;
2001
2002                         info->mti_attr.ma_need = MA_INODE;
2003                         info->mti_attr.ma_valid = 0;
2004                         rc = mdt_attr_get_complex(info, info->mti_object,
2005                                                   &info->mti_attr);
2006                         if (rc == 0) {
2007                                 body = req_capsule_server_get(pill,
2008                                                               &RMF_MDT_BODY);
2009                                 fid = mdt_object_fid(info->mti_object);
2010                                 mdt_pack_attr2body(info, body, la, fid);
2011                         }
2012                 }
2013                 mdt_thread_info_fini(info);
2014         }
2015         if (rc == 0)
2016                 mdt_counter_incr(req, LPROC_MDT_SYNC);
2017
2018         RETURN(rc);
2019 }
2020
2021 /*
2022  * Handle quota control requests to consult current usage/limit, but also
2023  * to configure quota enforcement
2024  */
2025 static int mdt_quotactl(struct tgt_session_info *tsi)
2026 {
2027         struct obd_export       *exp  = tsi->tsi_exp;
2028         struct req_capsule      *pill = tsi->tsi_pill;
2029         struct obd_quotactl     *oqctl, *repoqc;
2030         int                      id, rc;
2031         struct mdt_device       *mdt = mdt_exp2dev(exp);
2032         struct lu_device        *qmt = mdt->mdt_qmt_dev;
2033         struct lu_nodemap       *nodemap = exp->exp_target_data.ted_nodemap;
2034         ENTRY;
2035
2036         oqctl = req_capsule_client_get(pill, &RMF_OBD_QUOTACTL);
2037         if (oqctl == NULL)
2038                 RETURN(err_serious(-EPROTO));
2039
2040         rc = req_capsule_server_pack(pill);
2041         if (rc)
2042                 RETURN(err_serious(rc));
2043
2044         switch (oqctl->qc_cmd) {
2045         case Q_QUOTACHECK:
2046         case LUSTRE_Q_INVALIDATE:
2047         case LUSTRE_Q_FINVALIDATE:
2048         case Q_QUOTAON:
2049         case Q_QUOTAOFF:
2050         case Q_INITQUOTA:
2051                 /* deprecated, not used any more */
2052                 RETURN(-EOPNOTSUPP);
2053                 /* master quotactl */
2054         case Q_SETINFO:
2055         case Q_SETQUOTA:
2056                 if (!nodemap_can_setquota(nodemap))
2057                         RETURN(-EPERM);
2058         case Q_GETINFO:
2059         case Q_GETQUOTA:
2060                 if (qmt == NULL)
2061                         RETURN(-EOPNOTSUPP);
2062                 /* slave quotactl */
2063         case Q_GETOINFO:
2064         case Q_GETOQUOTA:
2065                 break;
2066         default:
2067                 CERROR("Unsupported quotactl command: %d\n", oqctl->qc_cmd);
2068                 RETURN(-EFAULT);
2069         }
2070
2071         /* map uid/gid for remote client */
2072         id = oqctl->qc_id;
2073         if (exp_connect_rmtclient(exp)) {
2074                 struct lustre_idmap_table *idmap;
2075
2076                 idmap = exp->exp_mdt_data.med_idmap;
2077
2078                 if (unlikely(oqctl->qc_cmd != Q_GETQUOTA &&
2079                              oqctl->qc_cmd != Q_GETINFO))
2080                         RETURN(-EPERM);
2081
2082                 if (oqctl->qc_type == USRQUOTA)
2083                         id = lustre_idmap_lookup_uid(NULL, idmap, 0,
2084                                                      oqctl->qc_id);
2085                 else if (oqctl->qc_type == GRPQUOTA)
2086                         id = lustre_idmap_lookup_gid(NULL, idmap, 0,
2087                                                      oqctl->qc_id);
2088                 else
2089                         RETURN(-EINVAL);
2090
2091                 if (id == CFS_IDMAP_NOTFOUND) {
2092                         CDEBUG(D_QUOTA, "no mapping for id %u\n", oqctl->qc_id);
2093                         RETURN(-EACCES);
2094                 }
2095         }
2096
2097         if (oqctl->qc_type == USRQUOTA)
2098                 id = nodemap_map_id(nodemap, NODEMAP_UID,
2099                                     NODEMAP_CLIENT_TO_FS, id);
2100         else if (oqctl->qc_type == GRPQUOTA)
2101                 id = nodemap_map_id(nodemap, NODEMAP_UID,
2102                                     NODEMAP_CLIENT_TO_FS, id);
2103
2104         repoqc = req_capsule_server_get(pill, &RMF_OBD_QUOTACTL);
2105         if (repoqc == NULL)
2106                 RETURN(err_serious(-EFAULT));
2107
2108         if (oqctl->qc_id != id)
2109                 swap(oqctl->qc_id, id);
2110
2111         switch (oqctl->qc_cmd) {
2112
2113         case Q_GETINFO:
2114         case Q_SETINFO:
2115         case Q_SETQUOTA:
2116         case Q_GETQUOTA:
2117                 /* forward quotactl request to QMT */
2118                 rc = qmt_hdls.qmth_quotactl(tsi->tsi_env, qmt, oqctl);
2119                 break;
2120
2121         case Q_GETOINFO:
2122         case Q_GETOQUOTA:
2123                 /* slave quotactl */
2124                 rc = lquotactl_slv(tsi->tsi_env, tsi->tsi_tgt->lut_bottom,
2125                                    oqctl);
2126                 break;
2127
2128         default:
2129                 CERROR("Unsupported quotactl command: %d\n", oqctl->qc_cmd);
2130                 RETURN(-EFAULT);
2131         }
2132
2133         if (oqctl->qc_id != id)
2134                 swap(oqctl->qc_id, id);
2135
2136         *repoqc = *oqctl;
2137         RETURN(rc);
2138 }
2139
2140 /** clone llog ctxt from child (mdd)
2141  * This allows remote llog (replicator) access.
2142  * We can either pass all llog RPCs (eg mdt_llog_create) on to child where the
2143  * context was originally set up, or we can handle them directly.
2144  * I choose the latter, but that means I need any llog
2145  * contexts set up by child to be accessable by the mdt.  So we clone the
2146  * context into our context list here.
2147  */
2148 static int mdt_llog_ctxt_clone(const struct lu_env *env, struct mdt_device *mdt,
2149                                int idx)
2150 {
2151         struct md_device  *next = mdt->mdt_child;
2152         struct llog_ctxt *ctxt;
2153         int rc;
2154
2155         if (!llog_ctxt_null(mdt2obd_dev(mdt), idx))
2156                 return 0;
2157
2158         rc = next->md_ops->mdo_llog_ctxt_get(env, next, idx, (void **)&ctxt);
2159         if (rc || ctxt == NULL) {
2160                 return 0;
2161         }
2162
2163         rc = llog_group_set_ctxt(&mdt2obd_dev(mdt)->obd_olg, ctxt, idx);
2164         if (rc)
2165                 CERROR("Can't set mdt ctxt %d\n", rc);
2166
2167         return rc;
2168 }
2169
2170 static int mdt_llog_ctxt_unclone(const struct lu_env *env,
2171                                  struct mdt_device *mdt, int idx)
2172 {
2173         struct llog_ctxt *ctxt;
2174
2175         ctxt = llog_get_context(mdt2obd_dev(mdt), idx);
2176         if (ctxt == NULL)
2177                 return 0;
2178         /* Put once for the get we just did, and once for the clone */
2179         llog_ctxt_put(ctxt);
2180         llog_ctxt_put(ctxt);
2181         return 0;
2182 }
2183
2184 /*
2185  * sec context handlers
2186  */
2187 static int mdt_sec_ctx_handle(struct tgt_session_info *tsi)
2188 {
2189         int rc;
2190
2191         rc = mdt_handle_idmap(tsi);
2192         if (unlikely(rc)) {
2193                 struct ptlrpc_request   *req = tgt_ses_req(tsi);
2194                 __u32                    opc;
2195
2196                 opc = lustre_msg_get_opc(req->rq_reqmsg);
2197                 if (opc == SEC_CTX_INIT || opc == SEC_CTX_INIT_CONT)
2198                         sptlrpc_svc_ctx_invalidate(req);
2199         }
2200
2201         CFS_FAIL_TIMEOUT(OBD_FAIL_SEC_CTX_HDL_PAUSE, cfs_fail_val);
2202
2203         return rc;
2204 }
2205
2206 /*
2207  * quota request handlers
2208  */
2209 static int mdt_quota_dqacq(struct tgt_session_info *tsi)
2210 {
2211         struct mdt_device       *mdt = mdt_exp2dev(tsi->tsi_exp);
2212         struct lu_device        *qmt = mdt->mdt_qmt_dev;
2213         int                      rc;
2214         ENTRY;
2215
2216         if (qmt == NULL)
2217                 RETURN(err_serious(-EOPNOTSUPP));
2218
2219         rc = qmt_hdls.qmth_dqacq(tsi->tsi_env, qmt, tgt_ses_req(tsi));
2220         RETURN(rc);
2221 }
2222
2223 struct mdt_object *mdt_object_new(const struct lu_env *env,
2224                                   struct mdt_device *d,
2225                                   const struct lu_fid *f)
2226 {
2227         struct lu_object_conf conf = { .loc_flags = LOC_F_NEW };
2228         struct lu_object *o;
2229         struct mdt_object *m;
2230         ENTRY;
2231
2232         CDEBUG(D_INFO, "Allocate object for "DFID"\n", PFID(f));
2233         o = lu_object_find(env, &d->mdt_lu_dev, f, &conf);
2234         if (unlikely(IS_ERR(o)))
2235                 m = (struct mdt_object *)o;
2236         else
2237                 m = mdt_obj(o);
2238         RETURN(m);
2239 }
2240
2241 struct mdt_object *mdt_object_find(const struct lu_env *env,
2242                                    struct mdt_device *d,
2243                                    const struct lu_fid *f)
2244 {
2245         struct lu_object *o;
2246         struct mdt_object *m;
2247         ENTRY;
2248
2249         CDEBUG(D_INFO, "Find object for "DFID"\n", PFID(f));
2250         o = lu_object_find(env, &d->mdt_lu_dev, f, NULL);
2251         if (unlikely(IS_ERR(o)))
2252                 m = (struct mdt_object *)o;
2253         else
2254                 m = mdt_obj(o);
2255
2256         RETURN(m);
2257 }
2258
2259 /**
2260  * Asyncronous commit for mdt device.
2261  *
2262  * Pass asynchonous commit call down the MDS stack.
2263  *
2264  * \param env environment
2265  * \param mdt the mdt device
2266  */
2267 static void mdt_device_commit_async(const struct lu_env *env,
2268                                     struct mdt_device *mdt)
2269 {
2270         struct dt_device *dt = mdt->mdt_bottom;
2271         int rc;
2272
2273         rc = dt->dd_ops->dt_commit_async(env, dt);
2274         if (unlikely(rc != 0))
2275                 CWARN("%s: async commit start failed: rc = %d\n",
2276                       mdt_obd_name(mdt), rc);
2277 }
2278
2279 /**
2280  * Mark the lock as "synchonous".
2281  *
2282  * Mark the lock to deffer transaction commit to the unlock time.
2283  *
2284  * \param lock the lock to mark as "synchonous"
2285  *
2286  * \see mdt_is_lock_sync
2287  * \see mdt_save_lock
2288  */
2289 static inline void mdt_set_lock_sync(struct ldlm_lock *lock)
2290 {
2291         lock->l_ast_data = (void*)1;
2292 }
2293
2294 /**
2295  * Check whehter the lock "synchonous" or not.
2296  *
2297  * \param lock the lock to check
2298  * \retval 1 the lock is "synchonous"
2299  * \retval 0 the lock isn't "synchronous"
2300  *
2301  * \see mdt_set_lock_sync
2302  * \see mdt_save_lock
2303  */
2304 static inline int mdt_is_lock_sync(struct ldlm_lock *lock)
2305 {
2306         return lock->l_ast_data != NULL;
2307 }
2308
2309 /**
2310  * Blocking AST for mdt locks.
2311  *
2312  * Starts transaction commit if in case of COS lock conflict or
2313  * deffers such a commit to the mdt_save_lock.
2314  *
2315  * \param lock the lock which blocks a request or cancelling lock
2316  * \param desc unused
2317  * \param data unused
2318  * \param flag indicates whether this cancelling or blocking callback
2319  * \retval 0
2320  * \see ldlm_blocking_ast_nocheck
2321  */
2322 int mdt_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
2323                      void *data, int flag)
2324 {
2325         struct obd_device *obd = ldlm_lock_to_ns(lock)->ns_obd;
2326         struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
2327         int rc;
2328         ENTRY;
2329
2330         if (flag == LDLM_CB_CANCELING)
2331                 RETURN(0);
2332         lock_res_and_lock(lock);
2333         if (lock->l_blocking_ast != mdt_blocking_ast) {
2334                 unlock_res_and_lock(lock);
2335                 RETURN(0);
2336         }
2337         if (mdt_cos_is_enabled(mdt) &&
2338             lock->l_req_mode & (LCK_PW | LCK_EX) &&
2339             lock->l_blocking_lock != NULL &&
2340             lock->l_client_cookie != lock->l_blocking_lock->l_client_cookie) {
2341                 mdt_set_lock_sync(lock);
2342         }
2343         rc = ldlm_blocking_ast_nocheck(lock);
2344
2345         /* There is no lock conflict if l_blocking_lock == NULL,
2346          * it indicates a blocking ast sent from ldlm_lock_decref_internal
2347          * when the last reference to a local lock was released */
2348         if (lock->l_req_mode == LCK_COS && lock->l_blocking_lock != NULL) {
2349                 struct lu_env env;
2350
2351                 rc = lu_env_init(&env, LCT_LOCAL);
2352                 if (unlikely(rc != 0))
2353                         CWARN("%s: lu_env initialization failed, cannot "
2354                               "start asynchronous commit: rc = %d\n",
2355                               obd->obd_name, rc);
2356                 else
2357                         mdt_device_commit_async(&env, mdt);
2358                 lu_env_fini(&env);
2359         }
2360         RETURN(rc);
2361 }
2362
2363 /* Used for cross-MDT lock */
2364 int mdt_remote_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
2365                             void *data, int flag)
2366 {
2367         struct lustre_handle lockh;
2368         int               rc;
2369
2370         switch (flag) {
2371         case LDLM_CB_BLOCKING:
2372                 ldlm_lock2handle(lock, &lockh);
2373                 rc = ldlm_cli_cancel(&lockh, LCF_ASYNC);
2374                 if (rc < 0) {
2375                         CDEBUG(D_INODE, "ldlm_cli_cancel: %d\n", rc);
2376                         RETURN(rc);
2377                 }
2378                 break;
2379         case LDLM_CB_CANCELING:
2380                 LDLM_DEBUG(lock, "Revoke remote lock\n");
2381                 break;
2382         default:
2383                 LBUG();
2384         }
2385         RETURN(0);
2386 }
2387
2388 int mdt_check_resent_lock(struct mdt_thread_info *info,
2389                           struct mdt_object *mo,
2390                           struct mdt_lock_handle *lhc)
2391 {
2392         /* the lock might already be gotten in ldlm_handle_enqueue() */
2393         if (unlikely(lustre_handle_is_used(&lhc->mlh_reg_lh))) {
2394                 struct ptlrpc_request *req = mdt_info_req(info);
2395                 struct ldlm_lock      *lock;
2396
2397                 lock = ldlm_handle2lock(&lhc->mlh_reg_lh);
2398                 LASSERT(lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT);
2399                 if (lock == NULL) {
2400                         /* Lock is pinned by ldlm_handle_enqueue0() as it is
2401                          * a resend case, however, it could be already destroyed
2402                          * due to client eviction or a raced cancel RPC. */
2403                         LDLM_DEBUG_NOLOCK("Invalid lock handle "LPX64"\n",
2404                                           lhc->mlh_reg_lh.cookie);
2405                         RETURN(-ESTALE);
2406                 }
2407
2408                 if (!fid_res_name_eq(mdt_object_fid(mo),
2409                                      &lock->l_resource->lr_name)) {
2410                         CWARN("%s: Although resent, but still not "
2411                               "get child lock:"DFID"\n",
2412                               info->mti_exp->exp_obd->obd_name,
2413                               PFID(mdt_object_fid(mo)));
2414                         LDLM_LOCK_PUT(lock);
2415                         RETURN(-EPROTO);
2416                 }
2417                 LDLM_LOCK_PUT(lock);
2418                 return 0;
2419         }
2420         return 1;
2421 }
2422
2423 int mdt_remote_object_lock(struct mdt_thread_info *mti,
2424                            struct mdt_object *o, const struct lu_fid *fid,
2425                            struct lustre_handle *lh, ldlm_mode_t mode,
2426                            __u64 ibits)
2427 {
2428         struct ldlm_enqueue_info *einfo = &mti->mti_einfo;
2429         ldlm_policy_data_t *policy = &mti->mti_policy;
2430         struct ldlm_res_id *res_id = &mti->mti_res_id;
2431         int rc = 0;
2432         ENTRY;
2433
2434         LASSERT(mdt_object_remote(o));
2435
2436         LASSERT(ibits == MDS_INODELOCK_UPDATE);
2437
2438         fid_build_reg_res_name(fid, res_id);
2439
2440         memset(einfo, 0, sizeof(*einfo));
2441         einfo->ei_type = LDLM_IBITS;
2442         einfo->ei_mode = mode;
2443         einfo->ei_cb_bl = mdt_remote_blocking_ast;
2444         einfo->ei_cb_cp = ldlm_completion_ast;
2445         einfo->ei_enq_slave = 0;
2446         einfo->ei_res_id = res_id;
2447
2448         memset(policy, 0, sizeof(*policy));
2449         policy->l_inodebits.bits = ibits;
2450
2451         rc = mo_object_lock(mti->mti_env, mdt_object_child(o), lh, einfo,
2452                             policy);
2453         RETURN(rc);
2454 }
2455
2456 static int mdt_object_local_lock(struct mdt_thread_info *info,
2457                                  struct mdt_object *o,
2458                                  struct mdt_lock_handle *lh, __u64 ibits,
2459                                  bool nonblock, int locality)
2460 {
2461         struct ldlm_namespace *ns = info->mti_mdt->mdt_namespace;
2462         ldlm_policy_data_t *policy = &info->mti_policy;
2463         struct ldlm_res_id *res_id = &info->mti_res_id;
2464         __u64 dlmflags;
2465         int rc;
2466         ENTRY;
2467
2468         LASSERT(!lustre_handle_is_used(&lh->mlh_reg_lh));
2469         LASSERT(!lustre_handle_is_used(&lh->mlh_pdo_lh));
2470         LASSERT(lh->mlh_reg_mode != LCK_MINMODE);
2471         LASSERT(lh->mlh_type != MDT_NUL_LOCK);
2472
2473         /* Only enqueue LOOKUP lock for remote object */
2474         if (mdt_object_remote(o))
2475                 LASSERT(ibits == MDS_INODELOCK_LOOKUP);
2476
2477         if (lh->mlh_type == MDT_PDO_LOCK) {
2478                 /* check for exists after object is locked */
2479                 if (mdt_object_exists(o) == 0) {
2480                         /* Non-existent object shouldn't have PDO lock */
2481                         RETURN(-ESTALE);
2482                 } else {
2483                         /* Non-dir object shouldn't have PDO lock */
2484                         if (!S_ISDIR(lu_object_attr(&o->mot_obj)))
2485                                 RETURN(-ENOTDIR);
2486                 }
2487         }
2488
2489         memset(policy, 0, sizeof(*policy));
2490         fid_build_reg_res_name(mdt_object_fid(o), res_id);
2491
2492         dlmflags = LDLM_FL_ATOMIC_CB;
2493         if (nonblock)
2494                 dlmflags |= LDLM_FL_BLOCK_NOWAIT;
2495
2496         /*
2497          * Take PDO lock on whole directory and build correct @res_id for lock
2498          * on part of directory.
2499          */
2500         if (lh->mlh_pdo_hash != 0) {
2501                 LASSERT(lh->mlh_type == MDT_PDO_LOCK);
2502                 mdt_lock_pdo_mode(info, o, lh);
2503                 if (lh->mlh_pdo_mode != LCK_NL) {
2504                         /*
2505                          * Do not use LDLM_FL_LOCAL_ONLY for parallel lock, it
2506                          * is never going to be sent to client and we do not
2507                          * want it slowed down due to possible cancels.
2508                          */
2509                         policy->l_inodebits.bits = MDS_INODELOCK_UPDATE;
2510                         rc = mdt_fid_lock(ns, &lh->mlh_pdo_lh, lh->mlh_pdo_mode,
2511                                           policy, res_id, dlmflags,
2512                                           info->mti_exp == NULL ? NULL :
2513                                           &info->mti_exp->exp_handle.h_cookie);
2514                         if (unlikely(rc != 0))
2515                                 GOTO(out_unlock, rc);
2516                 }
2517
2518                 /*
2519                  * Finish res_id initializing by name hash marking part of
2520                  * directory which is taking modification.
2521                  */
2522                 res_id->name[LUSTRE_RES_ID_HSH_OFF] = lh->mlh_pdo_hash;
2523         }
2524
2525         policy->l_inodebits.bits = ibits;
2526
2527         /*
2528          * Use LDLM_FL_LOCAL_ONLY for this lock. We do not know yet if it is
2529          * going to be sent to client. If it is - mdt_intent_policy() path will
2530          * fix it up and turn FL_LOCAL flag off.
2531          */
2532         rc = mdt_fid_lock(ns, &lh->mlh_reg_lh, lh->mlh_reg_mode, policy,
2533                           res_id, LDLM_FL_LOCAL_ONLY | dlmflags,
2534                           info->mti_exp == NULL ? NULL :
2535                           &info->mti_exp->exp_handle.h_cookie);
2536 out_unlock:
2537         if (rc != 0)
2538                 mdt_object_unlock(info, o, lh, 1);
2539         else if (unlikely(OBD_FAIL_PRECHECK(OBD_FAIL_MDS_PDO_LOCK)) &&
2540                    lh->mlh_pdo_hash != 0 &&
2541                    (lh->mlh_reg_mode == LCK_PW || lh->mlh_reg_mode == LCK_EX))
2542                 OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_PDO_LOCK, 15);
2543
2544         RETURN(rc);
2545 }
2546
2547 static int
2548 mdt_object_lock_internal(struct mdt_thread_info *info, struct mdt_object *o,
2549                          struct mdt_lock_handle *lh, __u64 ibits,
2550                          bool nonblock, int locality)
2551 {
2552         int rc;
2553         ENTRY;
2554
2555         if (!mdt_object_remote(o))
2556                 return mdt_object_local_lock(info, o, lh, ibits, nonblock,
2557                                              locality);
2558
2559         if (locality == MDT_LOCAL_LOCK) {
2560                 CERROR("%s: try to get local lock for remote object"
2561                        DFID".\n", mdt_obd_name(info->mti_mdt),
2562                        PFID(mdt_object_fid(o)));
2563                 RETURN(-EPROTO);
2564         }
2565
2566         /* XXX do not support PERM/LAYOUT/XATTR lock for remote object yet */
2567         ibits &= ~(MDS_INODELOCK_PERM | MDS_INODELOCK_LAYOUT |
2568                    MDS_INODELOCK_XATTR);
2569         if (ibits & MDS_INODELOCK_UPDATE) {
2570                 /* Sigh, PDO needs to enqueue 2 locks right now, but
2571                  * enqueue RPC can only request 1 lock, to avoid extra
2572                  * RPC, so it will instead enqueue EX lock for remote
2573                  * object anyway XXX*/
2574                 if (lh->mlh_type == MDT_PDO_LOCK &&
2575                     lh->mlh_pdo_hash != 0) {
2576                         CDEBUG(D_INFO, "%s: "DFID" convert PDO lock to"
2577                                "EX lock.\n", mdt_obd_name(info->mti_mdt),
2578                                PFID(mdt_object_fid(o)));
2579                         lh->mlh_pdo_hash = 0;
2580                         lh->mlh_rreg_mode = LCK_EX;
2581                         lh->mlh_type = MDT_REG_LOCK;
2582                 }
2583                 rc = mdt_remote_object_lock(info, o, mdt_object_fid(o),
2584                                             &lh->mlh_rreg_lh,
2585                                             lh->mlh_rreg_mode,
2586                                             MDS_INODELOCK_UPDATE);
2587                 if (rc != ELDLM_OK)
2588                         RETURN(rc);
2589         }
2590
2591         /* Only enqueue LOOKUP lock for remote object */
2592         if (ibits & MDS_INODELOCK_LOOKUP) {
2593                 rc = mdt_object_local_lock(info, o, lh,
2594                                            MDS_INODELOCK_LOOKUP,
2595                                            nonblock, locality);
2596                 if (rc != ELDLM_OK)
2597                         RETURN(rc);
2598         }
2599
2600         RETURN(0);
2601 }
2602
2603 int mdt_object_lock(struct mdt_thread_info *info, struct mdt_object *o,
2604                     struct mdt_lock_handle *lh, __u64 ibits, int locality)
2605 {
2606         return mdt_object_lock_internal(info, o, lh, ibits, false, locality);
2607 }
2608
2609 int mdt_object_lock_try(struct mdt_thread_info *info, struct mdt_object *o,
2610                         struct mdt_lock_handle *lh, __u64 ibits, int locality)
2611 {
2612         struct mdt_lock_handle tmp = *lh;
2613         int rc;
2614
2615         rc = mdt_object_lock_internal(info, o, &tmp, ibits, true, locality);
2616         if (rc == 0)
2617                 *lh = tmp;
2618
2619         return rc == 0;
2620 }
2621
2622 /**
2623  * Save a lock within request object.
2624  *
2625  * Keep the lock referenced until whether client ACK or transaction
2626  * commit happens or release the lock immediately depending on input
2627  * parameters. If COS is ON, a write lock is converted to COS lock
2628  * before saving.
2629  *
2630  * \param info thead info object
2631  * \param h lock handle
2632  * \param mode lock mode
2633  * \param decref force immediate lock releasing
2634  */
2635 static
2636 void mdt_save_lock(struct mdt_thread_info *info, struct lustre_handle *h,
2637                    ldlm_mode_t mode, int decref)
2638 {
2639         ENTRY;
2640
2641         if (lustre_handle_is_used(h)) {
2642                 if (decref || !info->mti_has_trans ||
2643                     !(mode & (LCK_PW | LCK_EX))){
2644                         mdt_fid_unlock(h, mode);
2645                 } else {
2646                         struct mdt_device *mdt = info->mti_mdt;
2647                         struct ldlm_lock *lock = ldlm_handle2lock(h);
2648                         struct ptlrpc_request *req = mdt_info_req(info);
2649                         int no_ack = 0;
2650
2651                         LASSERTF(lock != NULL, "no lock for cookie "LPX64"\n",
2652                                  h->cookie);
2653                         /* there is no request if mdt_object_unlock() is called
2654                          * from mdt_export_cleanup()->mdt_add_dirty_flag() */
2655                         if (likely(req != NULL)) {
2656                                 CDEBUG(D_HA, "request = %p reply state = %p"
2657                                        " transno = "LPD64"\n", req,
2658                                        req->rq_reply_state, req->rq_transno);
2659                                 if (mdt_cos_is_enabled(mdt)) {
2660                                         no_ack = 1;
2661                                         ldlm_lock_downgrade(lock, LCK_COS);
2662                                         mode = LCK_COS;
2663                                 }
2664                                 ptlrpc_save_lock(req, h, mode, no_ack);
2665                         } else {
2666                                 ldlm_lock_decref(h, mode);
2667                         }
2668                         if (mdt_is_lock_sync(lock)) {
2669                                 CDEBUG(D_HA, "found sync-lock,"
2670                                        " async commit started\n");
2671                                 mdt_device_commit_async(info->mti_env,
2672                                                         mdt);
2673                         }
2674                         LDLM_LOCK_PUT(lock);
2675                 }
2676                 h->cookie = 0ull;
2677         }
2678
2679         EXIT;
2680 }
2681
2682 /**
2683  * Unlock mdt object.
2684  *
2685  * Immeditely release the regular lock and the PDO lock or save the
2686  * lock in reqeuest and keep them referenced until client ACK or
2687  * transaction commit.
2688  *
2689  * \param info thread info object
2690  * \param o mdt object
2691  * \param lh mdt lock handle referencing regular and PDO locks
2692  * \param decref force immediate lock releasing
2693  */
2694 void mdt_object_unlock(struct mdt_thread_info *info, struct mdt_object *o,
2695                        struct mdt_lock_handle *lh, int decref)
2696 {
2697         ENTRY;
2698
2699         mdt_save_lock(info, &lh->mlh_pdo_lh, lh->mlh_pdo_mode, decref);
2700         mdt_save_lock(info, &lh->mlh_reg_lh, lh->mlh_reg_mode, decref);
2701
2702         if (lustre_handle_is_used(&lh->mlh_rreg_lh))
2703                 ldlm_lock_decref(&lh->mlh_rreg_lh, lh->mlh_rreg_mode);
2704
2705         EXIT;
2706 }
2707
2708 struct mdt_object *mdt_object_find_lock(struct mdt_thread_info *info,
2709                                         const struct lu_fid *f,
2710                                         struct mdt_lock_handle *lh,
2711                                         __u64 ibits)
2712 {
2713         struct mdt_object *o;
2714
2715         o = mdt_object_find(info->mti_env, info->mti_mdt, f);
2716         if (!IS_ERR(o)) {
2717                 int rc;
2718
2719                 rc = mdt_object_lock(info, o, lh, ibits,
2720                                      MDT_LOCAL_LOCK);
2721                 if (rc != 0) {
2722                         mdt_object_put(info->mti_env, o);
2723                         o = ERR_PTR(rc);
2724                 }
2725         }
2726         return o;
2727 }
2728
2729 void mdt_object_unlock_put(struct mdt_thread_info * info,
2730                            struct mdt_object * o,
2731                            struct mdt_lock_handle *lh,
2732                            int decref)
2733 {
2734         mdt_object_unlock(info, o, lh, decref);
2735         mdt_object_put(info->mti_env, o);
2736 }
2737
2738 /*
2739  * Generic code handling requests that have struct mdt_body passed in:
2740  *
2741  *  - extract mdt_body from request and save it in @info, if present;
2742  *
2743  *  - create lu_object, corresponding to the fid in mdt_body, and save it in
2744  *  @info;
2745  *
2746  *  - if HABEO_CORPUS flag is set for this request type check whether object
2747  *  actually exists on storage (lu_object_exists()).
2748  *
2749  */
2750 static int mdt_body_unpack(struct mdt_thread_info *info, __u32 flags)
2751 {
2752         const struct mdt_body    *body;
2753         struct mdt_object        *obj;
2754         const struct lu_env      *env;
2755         struct req_capsule       *pill;
2756         int                       rc;
2757         ENTRY;
2758
2759         env = info->mti_env;
2760         pill = info->mti_pill;
2761
2762         body = info->mti_body = req_capsule_client_get(pill, &RMF_MDT_BODY);
2763         if (body == NULL)
2764                 RETURN(-EFAULT);
2765
2766         if (!(body->mbo_valid & OBD_MD_FLID))
2767                 RETURN(0);
2768
2769         if (!fid_is_sane(&body->mbo_fid1)) {
2770                 CERROR("Invalid fid: "DFID"\n", PFID(&body->mbo_fid1));
2771                 RETURN(-EINVAL);
2772         }
2773
2774         /*
2775          * Do not get size or any capa fields before we check that request
2776          * contains capa actually. There are some requests which do not, for
2777          * instance MDS_IS_SUBDIR.
2778          */
2779         if (req_capsule_has_field(pill, &RMF_CAPA1, RCL_CLIENT) &&
2780             req_capsule_get_size(pill, &RMF_CAPA1, RCL_CLIENT))
2781                 mdt_set_capainfo(info, 0, &body->mbo_fid1,
2782                                  req_capsule_client_get(pill, &RMF_CAPA1));
2783
2784         obj = mdt_object_find(env, info->mti_mdt, &body->mbo_fid1);
2785         if (!IS_ERR(obj)) {
2786                 if ((flags & HABEO_CORPUS) &&
2787                     !mdt_object_exists(obj)) {
2788                         mdt_object_put(env, obj);
2789                         /* for capability renew ENOENT will be handled in
2790                          * mdt_renew_capa */
2791                         if (body->mbo_valid & OBD_MD_FLOSSCAPA)
2792                                 rc = 0;
2793                         else
2794                                 rc = -ENOENT;
2795                 } else {
2796                         info->mti_object = obj;
2797                         rc = 0;
2798                 }
2799         } else
2800                 rc = PTR_ERR(obj);
2801
2802         RETURN(rc);
2803 }
2804
2805 static int mdt_unpack_req_pack_rep(struct mdt_thread_info *info, __u32 flags)
2806 {
2807         struct req_capsule *pill = info->mti_pill;
2808         int rc;
2809         ENTRY;
2810
2811         if (req_capsule_has_field(pill, &RMF_MDT_BODY, RCL_CLIENT))
2812                 rc = mdt_body_unpack(info, flags);
2813         else
2814                 rc = 0;
2815
2816         if (rc == 0 && (flags & HABEO_REFERO)) {
2817                 /* Pack reply. */
2818                 if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
2819                         req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER,
2820                                              DEF_REP_MD_SIZE);
2821                 if (req_capsule_has_field(pill, &RMF_LOGCOOKIES, RCL_SERVER))
2822                         req_capsule_set_size(pill, &RMF_LOGCOOKIES,
2823                                              RCL_SERVER, 0);
2824
2825                 rc = req_capsule_server_pack(pill);
2826         }
2827         RETURN(rc);
2828 }
2829
2830 static int mdt_init_capa_ctxt(const struct lu_env *env, struct mdt_device *m)
2831 {
2832         struct md_device *next = m->mdt_child;
2833
2834         return next->md_ops->mdo_init_capa_ctxt(env, next,
2835                                                 m->mdt_lut.lut_mds_capa,
2836                                                 m->mdt_capa_timeout,
2837                                                 m->mdt_capa_alg,
2838                                                 m->mdt_capa_keys);
2839 }
2840
2841 void mdt_lock_handle_init(struct mdt_lock_handle *lh)
2842 {
2843         lh->mlh_type = MDT_NUL_LOCK;
2844         lh->mlh_reg_lh.cookie = 0ull;
2845         lh->mlh_reg_mode = LCK_MINMODE;
2846         lh->mlh_pdo_lh.cookie = 0ull;
2847         lh->mlh_pdo_mode = LCK_MINMODE;
2848         lh->mlh_rreg_lh.cookie = 0ull;
2849         lh->mlh_rreg_mode = LCK_MINMODE;
2850 }
2851
2852 void mdt_lock_handle_fini(struct mdt_lock_handle *lh)
2853 {
2854         LASSERT(!lustre_handle_is_used(&lh->mlh_reg_lh));
2855         LASSERT(!lustre_handle_is_used(&lh->mlh_pdo_lh));
2856 }
2857
2858 /*
2859  * Initialize fields of struct mdt_thread_info. Other fields are left in
2860  * uninitialized state, because it's too expensive to zero out whole
2861  * mdt_thread_info (> 1K) on each request arrival.
2862  */
2863 void mdt_thread_info_init(struct ptlrpc_request *req,
2864                           struct mdt_thread_info *info)
2865 {
2866         int i;
2867
2868         info->mti_pill = &req->rq_pill;
2869
2870         /* lock handle */
2871         for (i = 0; i < ARRAY_SIZE(info->mti_lh); i++)
2872                 mdt_lock_handle_init(&info->mti_lh[i]);
2873
2874         /* mdt device: it can be NULL while CONNECT */
2875         if (req->rq_export) {
2876                 info->mti_mdt = mdt_dev(req->rq_export->exp_obd->obd_lu_dev);
2877                 info->mti_exp = req->rq_export;
2878         } else
2879                 info->mti_mdt = NULL;
2880         info->mti_env = req->rq_svc_thread->t_env;
2881         info->mti_transno = lustre_msg_get_transno(req->rq_reqmsg);
2882
2883         memset(&info->mti_attr, 0, sizeof(info->mti_attr));
2884         info->mti_big_buf = LU_BUF_NULL;
2885         info->mti_body = NULL;
2886         info->mti_object = NULL;
2887         info->mti_dlm_req = NULL;
2888         info->mti_has_trans = 0;
2889         info->mti_cross_ref = 0;
2890         info->mti_opdata = 0;
2891         info->mti_big_lmm_used = 0;
2892
2893         info->mti_spec.no_create = 0;
2894         info->mti_spec.sp_rm_entry = 0;
2895         info->mti_spec.sp_permitted = 0;
2896
2897         info->mti_spec.u.sp_ea.eadata = NULL;
2898         info->mti_spec.u.sp_ea.eadatalen = 0;
2899 }
2900
2901 void mdt_thread_info_fini(struct mdt_thread_info *info)
2902 {
2903         int i;
2904
2905         if (info->mti_object != NULL) {
2906                 mdt_object_put(info->mti_env, info->mti_object);
2907                 info->mti_object = NULL;
2908         }
2909
2910         for (i = 0; i < ARRAY_SIZE(info->mti_lh); i++)
2911                 mdt_lock_handle_fini(&info->mti_lh[i]);
2912         info->mti_env = NULL;
2913         info->mti_pill = NULL;
2914         info->mti_exp = NULL;
2915
2916         if (unlikely(info->mti_big_buf.lb_buf != NULL))
2917                 lu_buf_free(&info->mti_big_buf);
2918 }
2919
2920 struct mdt_thread_info *tsi2mdt_info(struct tgt_session_info *tsi)
2921 {
2922         struct mdt_thread_info  *mti;
2923         struct lustre_capa      *lc;
2924
2925         mti = mdt_th_info(tsi->tsi_env);
2926         LASSERT(mti != NULL);
2927
2928         mdt_thread_info_init(tgt_ses_req(tsi), mti);
2929         if (tsi->tsi_corpus != NULL) {
2930                 struct req_capsule *pill = tsi->tsi_pill;
2931
2932                 mti->mti_object = mdt_obj(tsi->tsi_corpus);
2933                 lu_object_get(tsi->tsi_corpus);
2934
2935                 /*
2936                  * XXX: must be part of tgt_mdt_body_unpack but moved here
2937                  * due to mdt_set_capainfo().
2938                  */
2939                 if (req_capsule_has_field(pill, &RMF_CAPA1, RCL_CLIENT) &&
2940                     req_capsule_get_size(pill, &RMF_CAPA1, RCL_CLIENT) > 0) {
2941                         lc = req_capsule_client_get(pill, &RMF_CAPA1);
2942                         mdt_set_capainfo(mti, 0, &tsi->tsi_mdt_body->mbo_fid1,
2943                                          lc);
2944                 }
2945         }
2946         mti->mti_body = tsi->tsi_mdt_body;
2947         mti->mti_dlm_req = tsi->tsi_dlm_req;
2948
2949         return mti;
2950 }
2951
2952 static int mdt_tgt_connect(struct tgt_session_info *tsi)
2953 {
2954         struct ptlrpc_request   *req = tgt_ses_req(tsi);
2955         int                      rc;
2956
2957         ENTRY;
2958
2959         if (OBD_FAIL_CHECK(OBD_FAIL_TGT_DELAY_CONDITIONAL) &&
2960             cfs_fail_val ==
2961             tsi2mdt_info(tsi)->mti_mdt->mdt_seq_site.ss_node_id)
2962                 schedule_timeout_and_set_state(TASK_UNINTERRUPTIBLE,
2963                         msecs_to_jiffies(3 * MSEC_PER_SEC));
2964
2965         rc = tgt_connect(tsi);
2966         if (rc != 0)
2967                 RETURN(rc);
2968
2969         rc = mdt_init_idmap(tsi);
2970         if (rc != 0)
2971                 GOTO(err, rc);
2972         RETURN(0);
2973 err:
2974         obd_disconnect(class_export_get(req->rq_export));
2975         return rc;
2976 }
2977
2978 enum mdt_it_code {
2979         MDT_IT_OPEN,
2980         MDT_IT_OCREAT,
2981         MDT_IT_CREATE,
2982         MDT_IT_GETATTR,
2983         MDT_IT_READDIR,
2984         MDT_IT_LOOKUP,
2985         MDT_IT_UNLINK,
2986         MDT_IT_TRUNC,
2987         MDT_IT_GETXATTR,
2988         MDT_IT_LAYOUT,
2989         MDT_IT_QUOTA,
2990         MDT_IT_NR
2991 };
2992
2993 static int mdt_intent_getattr(enum mdt_it_code opcode,
2994                               struct mdt_thread_info *info,
2995                               struct ldlm_lock **,
2996                               __u64);
2997
2998 static int mdt_intent_getxattr(enum mdt_it_code opcode,
2999                                 struct mdt_thread_info *info,
3000                                 struct ldlm_lock **lockp,
3001                                 __u64 flags);
3002
3003 static int mdt_intent_layout(enum mdt_it_code opcode,
3004                              struct mdt_thread_info *info,
3005                              struct ldlm_lock **,
3006                              __u64);
3007 static int mdt_intent_reint(enum mdt_it_code opcode,
3008                             struct mdt_thread_info *info,
3009                             struct ldlm_lock **,
3010                             __u64);
3011
3012 static struct mdt_it_flavor {
3013         const struct req_format *it_fmt;
3014         __u32                    it_flags;
3015         int                    (*it_act)(enum mdt_it_code ,
3016                                          struct mdt_thread_info *,
3017                                          struct ldlm_lock **,
3018                                          __u64);
3019         long                     it_reint;
3020 } mdt_it_flavor[] = {
3021         [MDT_IT_OPEN]     = {
3022                 .it_fmt   = &RQF_LDLM_INTENT,
3023                 /*.it_flags = HABEO_REFERO,*/
3024                 .it_flags = 0,
3025                 .it_act   = mdt_intent_reint,
3026                 .it_reint = REINT_OPEN
3027         },
3028         [MDT_IT_OCREAT]   = {
3029                 .it_fmt   = &RQF_LDLM_INTENT,
3030                 /*
3031                  * OCREAT is not a MUTABOR request as if the file
3032                  * already exists.
3033                  * We do the extra check of OBD_CONNECT_RDONLY in
3034                  * mdt_reint_open() when we really need to create
3035                  * the object.
3036                  */
3037                 .it_flags = 0,
3038                 .it_act   = mdt_intent_reint,
3039                 .it_reint = REINT_OPEN
3040         },
3041         [MDT_IT_CREATE]   = {
3042                 .it_fmt   = &RQF_LDLM_INTENT,
3043                 .it_flags = MUTABOR,
3044                 .it_act   = mdt_intent_reint,
3045                 .it_reint = REINT_CREATE
3046         },
3047         [MDT_IT_GETATTR]  = {
3048                 .it_fmt   = &RQF_LDLM_INTENT_GETATTR,
3049                 .it_flags = HABEO_REFERO,
3050                 .it_act   = mdt_intent_getattr
3051         },
3052         [MDT_IT_READDIR]  = {
3053                 .it_fmt   = NULL,
3054                 .it_flags = 0,
3055                 .it_act   = NULL
3056         },
3057         [MDT_IT_LOOKUP]   = {
3058                 .it_fmt   = &RQF_LDLM_INTENT_GETATTR,
3059                 .it_flags = HABEO_REFERO,
3060                 .it_act   = mdt_intent_getattr
3061         },
3062         [MDT_IT_UNLINK]   = {
3063                 .it_fmt   = &RQF_LDLM_INTENT_UNLINK,
3064                 .it_flags = MUTABOR,
3065                 .it_act   = NULL,
3066                 .it_reint = REINT_UNLINK
3067         },
3068         [MDT_IT_TRUNC]    = {
3069                 .it_fmt   = NULL,
3070                 .it_flags = MUTABOR,
3071                 .it_act   = NULL
3072         },
3073         [MDT_IT_GETXATTR] = {
3074                 .it_fmt   = &RQF_LDLM_INTENT_GETXATTR,
3075                 .it_flags = HABEO_CORPUS,
3076                 .it_act   = mdt_intent_getxattr
3077         },
3078         [MDT_IT_LAYOUT] = {
3079                 .it_fmt   = &RQF_LDLM_INTENT_LAYOUT,
3080                 .it_flags = 0,
3081                 .it_act   = mdt_intent_layout
3082         }
3083 };
3084
3085 static int
3086 mdt_intent_lock_replace(struct mdt_thread_info *info,
3087                         struct ldlm_lock **lockp,
3088                         struct mdt_lock_handle *lh,
3089                         __u64 flags)
3090 {
3091         struct ptlrpc_request  *req = mdt_info_req(info);
3092         struct ldlm_lock       *lock = *lockp;
3093         struct ldlm_lock       *new_lock;
3094
3095         /* If possible resent found a lock, @lh is set to its handle */
3096         new_lock = ldlm_handle2lock_long(&lh->mlh_reg_lh, 0);
3097
3098         if (new_lock == NULL && (flags & LDLM_FL_INTENT_ONLY)) {
3099                 lh->mlh_reg_lh.cookie = 0;
3100                 RETURN(0);
3101         }
3102
3103         LASSERTF(new_lock != NULL,
3104                  "lockh "LPX64"\n", lh->mlh_reg_lh.cookie);
3105
3106         /*
3107          * If we've already given this lock to a client once, then we should
3108          * have no readers or writers.  Otherwise, we should have one reader
3109          * _or_ writer ref (which will be zeroed below) before returning the
3110          * lock to a client.
3111          */
3112         if (new_lock->l_export == req->rq_export) {
3113                 LASSERT(new_lock->l_readers + new_lock->l_writers == 0);
3114         } else {
3115                 LASSERT(new_lock->l_export == NULL);
3116                 LASSERT(new_lock->l_readers + new_lock->l_writers == 1);
3117         }
3118
3119         *lockp = new_lock;
3120
3121         if (new_lock->l_export == req->rq_export) {
3122                 /*
3123                  * Already gave this to the client, which means that we
3124                  * reconstructed a reply.
3125                  */
3126                 LASSERT(lustre_msg_get_flags(req->rq_reqmsg) &
3127                         MSG_RESENT);
3128
3129                 LDLM_LOCK_RELEASE(new_lock);
3130                 lh->mlh_reg_lh.cookie = 0;
3131                 RETURN(ELDLM_LOCK_REPLACED);
3132         }
3133
3134         /*
3135          * Fixup the lock to be given to the client.
3136          */
3137         lock_res_and_lock(new_lock);
3138         /* Zero new_lock->l_readers and new_lock->l_writers without triggering
3139          * possible blocking AST. */
3140         while (new_lock->l_readers > 0) {
3141                 lu_ref_del(&new_lock->l_reference, "reader", new_lock);
3142                 lu_ref_del(&new_lock->l_reference, "user", new_lock);
3143                 new_lock->l_readers--;
3144         }
3145         while (new_lock->l_writers > 0) {
3146                 lu_ref_del(&new_lock->l_reference, "writer", new_lock);
3147                 lu_ref_del(&new_lock->l_reference, "user", new_lock);
3148                 new_lock->l_writers--;
3149         }
3150
3151         new_lock->l_export = class_export_lock_get(req->rq_export, new_lock);
3152         new_lock->l_blocking_ast = lock->l_blocking_ast;
3153         new_lock->l_completion_ast = lock->l_completion_ast;
3154         new_lock->l_remote_handle = lock->l_remote_handle;
3155         new_lock->l_flags &= ~LDLM_FL_LOCAL;
3156
3157         unlock_res_and_lock(new_lock);
3158
3159         cfs_hash_add(new_lock->l_export->exp_lock_hash,
3160                      &new_lock->l_remote_handle,
3161                      &new_lock->l_exp_hash);
3162
3163         LDLM_LOCK_RELEASE(new_lock);
3164         lh->mlh_reg_lh.cookie = 0;
3165
3166         RETURN(ELDLM_LOCK_REPLACED);
3167 }
3168
3169 static void mdt_intent_fixup_resent(struct mdt_thread_info *info,
3170                                     struct ldlm_lock *new_lock,
3171                                     struct mdt_lock_handle *lh,
3172                                     __u64 flags)
3173 {
3174         struct ptlrpc_request  *req = mdt_info_req(info);
3175         struct ldlm_request    *dlmreq;
3176
3177         if (!(lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT))
3178                 return;
3179
3180         dlmreq = req_capsule_client_get(info->mti_pill, &RMF_DLM_REQ);
3181
3182         /* Check if this is a resend case (MSG_RESENT is set on RPC) and a
3183          * lock was found by ldlm_handle_enqueue(); if so @lh must be
3184          * initialized. */
3185         if (flags & LDLM_FL_RESENT) {
3186                 lh->mlh_reg_lh.cookie = new_lock->l_handle.h_cookie;
3187                 lh->mlh_reg_mode = new_lock->l_granted_mode;
3188
3189                 LDLM_DEBUG(new_lock, "Restoring lock cookie");
3190                 DEBUG_REQ(D_DLMTRACE, req, "restoring lock cookie "LPX64,
3191                           lh->mlh_reg_lh.cookie);
3192                 return;
3193         }
3194
3195         /*
3196          * If the xid matches, then we know this is a resent request, and allow
3197          * it. (It's probably an OPEN, for which we don't send a lock.
3198          */
3199         if (req_xid_is_last(req))
3200                 return;
3201
3202         /*
3203          * This remote handle isn't enqueued, so we never received or processed
3204          * this request.  Clear MSG_RESENT, because it can be handled like any
3205          * normal request now.
3206          */
3207         lustre_msg_clear_flags(req->rq_reqmsg, MSG_RESENT);
3208
3209         DEBUG_REQ(D_DLMTRACE, req, "no existing lock with rhandle "LPX64,
3210                   dlmreq->lock_handle[0].cookie);
3211 }
3212
3213 static int mdt_intent_getxattr(enum mdt_it_code opcode,
3214                                 struct mdt_thread_info *info,
3215                                 struct ldlm_lock **lockp,
3216                                 __u64 flags)
3217 {
3218         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
3219         struct ldlm_reply      *ldlm_rep = NULL;
3220         int rc, grc;
3221
3222         /*
3223          * Initialize lhc->mlh_reg_lh either from a previously granted lock
3224          * (for the resend case) or a new lock. Below we will use it to
3225          * replace the original lock.
3226          */
3227         mdt_intent_fixup_resent(info, *lockp, lhc, flags);
3228         if (!lustre_handle_is_used(&lhc->mlh_reg_lh)) {
3229                 mdt_lock_reg_init(lhc, (*lockp)->l_req_mode);
3230                 rc = mdt_object_lock(info, info->mti_object, lhc,
3231                                         MDS_INODELOCK_XATTR,
3232                                         MDT_LOCAL_LOCK);
3233                 if (rc)
3234                         return rc;
3235         }
3236
3237         grc = mdt_getxattr(info);
3238
3239         rc = mdt_intent_lock_replace(info, lockp, lhc, flags);
3240
3241         if (mdt_info_req(info)->rq_repmsg != NULL)
3242                 ldlm_rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
3243         if (ldlm_rep == NULL)
3244                 RETURN(err_serious(-EFAULT));
3245
3246         ldlm_rep->lock_policy_res2 = grc;
3247
3248         return rc;
3249 }
3250
3251 static int mdt_intent_getattr(enum mdt_it_code opcode,
3252                               struct mdt_thread_info *info,
3253                               struct ldlm_lock **lockp,
3254                               __u64 flags)
3255 {
3256         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
3257         __u64                   child_bits;
3258         struct ldlm_reply      *ldlm_rep;
3259         struct mdt_body        *reqbody;
3260         struct mdt_body        *repbody;
3261         int                     rc, rc2;
3262         ENTRY;
3263
3264         reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
3265         LASSERT(reqbody);
3266
3267         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
3268         LASSERT(repbody);
3269
3270         info->mti_cross_ref = !!(reqbody->mbo_valid & OBD_MD_FLCROSSREF);
3271         repbody->mbo_eadatasize = 0;
3272         repbody->mbo_aclsize = 0;
3273
3274         switch (opcode) {
3275         case MDT_IT_LOOKUP:
3276                 child_bits = MDS_INODELOCK_LOOKUP | MDS_INODELOCK_PERM;
3277                 break;
3278         case MDT_IT_GETATTR:
3279                 child_bits = MDS_INODELOCK_LOOKUP | MDS_INODELOCK_UPDATE |
3280                              MDS_INODELOCK_PERM;
3281                 break;
3282         default:
3283                 CERROR("Unsupported intent (%d)\n", opcode);
3284                 GOTO(out_shrink, rc = -EINVAL);
3285         }
3286
3287         rc = mdt_init_ucred(info, reqbody);
3288         if (rc)
3289                 GOTO(out_shrink, rc);
3290
3291         ldlm_rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
3292         mdt_set_disposition(info, ldlm_rep, DISP_IT_EXECD);
3293
3294         /* Get lock from request for possible resent case. */
3295         mdt_intent_fixup_resent(info, *lockp, lhc, flags);
3296
3297         rc = mdt_getattr_name_lock(info, lhc, child_bits, ldlm_rep);
3298         ldlm_rep->lock_policy_res2 = clear_serious(rc);
3299
3300         if (mdt_get_disposition(ldlm_rep, DISP_LOOKUP_NEG))
3301                 ldlm_rep->lock_policy_res2 = 0;
3302         if (!mdt_get_disposition(ldlm_rep, DISP_LOOKUP_POS) ||
3303             ldlm_rep->lock_policy_res2) {
3304                 lhc->mlh_reg_lh.cookie = 0ull;
3305                 GOTO(out_ucred, rc = ELDLM_LOCK_ABORTED);
3306         }
3307
3308         rc = mdt_intent_lock_replace(info, lockp, lhc, flags);
3309         EXIT;
3310 out_ucred:
3311         mdt_exit_ucred(info);
3312 out_shrink:
3313         mdt_client_compatibility(info);
3314         rc2 = mdt_fix_reply(info);
3315         if (rc == 0)
3316                 rc = rc2;
3317         return rc;
3318 }
3319
3320 static int mdt_intent_layout(enum mdt_it_code opcode,
3321                              struct mdt_thread_info *info,
3322                              struct ldlm_lock **lockp,
3323                              __u64 flags)
3324 {
3325         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_LAYOUT];
3326         struct layout_intent *layout;
3327         struct lu_fid *fid;
3328         struct mdt_object *obj = NULL;
3329         int rc = 0;
3330         ENTRY;
3331
3332         if (opcode != MDT_IT_LAYOUT) {
3333                 CERROR("%s: Unknown intent (%d)\n", mdt_obd_name(info->mti_mdt),
3334                         opcode);
3335                 RETURN(-EINVAL);
3336         }
3337
3338         fid = &info->mti_tmp_fid2;
3339         fid_extract_from_res_name(fid, &(*lockp)->l_resource->lr_name);
3340
3341         /* Get lock from request for possible resent case. */
3342         mdt_intent_fixup_resent(info, *lockp, lhc, flags);
3343
3344         obj = mdt_object_find(info->mti_env, info->mti_mdt, fid);
3345         if (IS_ERR(obj))
3346                 RETURN(PTR_ERR(obj));
3347
3348         if (mdt_object_exists(obj) && !mdt_object_remote(obj)) {
3349                 /* get the length of lsm */
3350                 rc = mdt_attr_get_eabuf_size(info, obj);
3351                 if (rc < 0) {
3352                         mdt_object_put(info->mti_env, obj);
3353                         RETURN(rc);
3354                 }
3355
3356                 if (rc > info->mti_mdt->mdt_max_mdsize)
3357                         info->mti_mdt->mdt_max_mdsize = rc;
3358         }
3359
3360         mdt_object_put(info->mti_env, obj);
3361
3362         (*lockp)->l_lvb_type = LVB_T_LAYOUT;
3363         req_capsule_set_size(info->mti_pill, &RMF_DLM_LVB, RCL_SERVER, rc);
3364         rc = req_capsule_server_pack(info->mti_pill);
3365         if (rc != 0)
3366                 RETURN(-EINVAL);
3367
3368         if (lustre_handle_is_used(&lhc->mlh_reg_lh))
3369                 rc = mdt_intent_lock_replace(info, lockp, lhc, flags);
3370
3371         layout = req_capsule_client_get(info->mti_pill, &RMF_LAYOUT_INTENT);
3372         LASSERT(layout != NULL);
3373         if (layout->li_opc == LAYOUT_INTENT_ACCESS)
3374                 /* return to normal/resent ldlm handling */
3375                 RETURN(rc);
3376
3377         CERROR("%s: Unsupported layout intent (%d)\n",
3378                 mdt_obd_name(info->mti_mdt), layout->li_opc);
3379         RETURN(-EINVAL);
3380 }
3381
3382 static int mdt_intent_reint(enum mdt_it_code opcode,
3383                             struct mdt_thread_info *info,
3384                             struct ldlm_lock **lockp,
3385                             __u64 flags)
3386 {
3387         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
3388         struct ldlm_reply      *rep = NULL;
3389         long                    opc;
3390         int                     rc;
3391
3392         static const struct req_format *intent_fmts[REINT_MAX] = {
3393                 [REINT_CREATE]  = &RQF_LDLM_INTENT_CREATE,
3394                 [REINT_OPEN]    = &RQF_LDLM_INTENT_OPEN
3395         };
3396
3397         ENTRY;
3398
3399         opc = mdt_reint_opcode(mdt_info_req(info), intent_fmts);
3400         if (opc < 0)
3401                 RETURN(opc);
3402
3403         if (mdt_it_flavor[opcode].it_reint != opc) {
3404                 CERROR("Reint code %ld doesn't match intent: %d\n",
3405                        opc, opcode);
3406                 RETURN(err_serious(-EPROTO));
3407         }
3408
3409         /* Get lock from request for possible resent case. */
3410         mdt_intent_fixup_resent(info, *lockp, lhc, flags);
3411
3412         rc = mdt_reint_internal(info, lhc, opc);
3413
3414         /* Check whether the reply has been packed successfully. */
3415         if (mdt_info_req(info)->rq_repmsg != NULL)
3416                 rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
3417         if (rep == NULL)
3418                 RETURN(err_serious(-EFAULT));
3419
3420         /* MDC expects this in any case */
3421         if (rc != 0)
3422                 mdt_set_disposition(info, rep, DISP_LOOKUP_EXECD);
3423
3424         /* the open lock or the lock for cross-ref object should be
3425          * returned to the client */
3426         if (lustre_handle_is_used(&lhc->mlh_reg_lh) &&
3427             (rc == 0 || rc == -MDT_EREMOTE_OPEN)) {
3428                 rep->lock_policy_res2 = 0;
3429                 rc = mdt_intent_lock_replace(info, lockp, lhc, flags);
3430                 RETURN(rc);
3431         }
3432
3433         rep->lock_policy_res2 = clear_serious(rc);
3434
3435         if (rep->lock_policy_res2 == -ENOENT &&
3436             mdt_get_disposition(rep, DISP_LOOKUP_NEG))
3437                 rep->lock_policy_res2 = 0;
3438
3439         lhc->mlh_reg_lh.cookie = 0ull;
3440         if (rc == -ENOTCONN || rc == -ENODEV ||
3441             rc == -EOVERFLOW) { /**< if VBR failure then return error */
3442                 /*
3443                  * If it is the disconnect error (ENODEV & ENOCONN), the error
3444                  * will be returned by rq_status, and client at ptlrpc layer
3445                  * will detect this, then disconnect, reconnect the import
3446                  * immediately, instead of impacting the following the rpc.
3447                  */
3448                 RETURN(rc);
3449         }
3450         /*
3451          * For other cases, the error will be returned by intent, and client
3452          * will retrieve the result from intent.
3453          */
3454         RETURN(ELDLM_LOCK_ABORTED);
3455 }
3456
3457 static int mdt_intent_code(long itcode)
3458 {
3459         int rc;
3460
3461         switch(itcode) {
3462         case IT_OPEN:
3463                 rc = MDT_IT_OPEN;
3464                 break;
3465         case IT_OPEN|IT_CREAT:
3466                 rc = MDT_IT_OCREAT;
3467                 break;
3468         case IT_CREAT:
3469                 rc = MDT_IT_CREATE;
3470                 break;
3471         case IT_READDIR:
3472                 rc = MDT_IT_READDIR;
3473                 break;
3474         case IT_GETATTR:
3475                 rc = MDT_IT_GETATTR;
3476                 break;
3477         case IT_LOOKUP:
3478                 rc = MDT_IT_LOOKUP;
3479                 break;
3480         case IT_UNLINK:
3481                 rc = MDT_IT_UNLINK;
3482                 break;
3483         case IT_TRUNC:
3484                 rc = MDT_IT_TRUNC;
3485                 break;
3486         case IT_GETXATTR:
3487                 rc = MDT_IT_GETXATTR;
3488                 break;
3489         case IT_LAYOUT:
3490                 rc = MDT_IT_LAYOUT;
3491                 break;
3492         case IT_QUOTA_DQACQ:
3493         case IT_QUOTA_CONN:
3494                 rc = MDT_IT_QUOTA;
3495                 break;
3496         default:
3497                 CERROR("Unknown intent opcode: %ld\n", itcode);
3498                 rc = -EINVAL;
3499                 break;
3500         }
3501         return rc;
3502 }
3503
3504 static int mdt_intent_opc(long itopc, struct mdt_thread_info *info,
3505                           struct ldlm_lock **lockp, __u64 flags)
3506 {
3507         struct req_capsule      *pill = info->mti_pill;
3508         struct ptlrpc_request   *req = mdt_info_req(info);
3509         struct mdt_it_flavor    *flv;
3510         int opc;
3511         int rc;
3512         ENTRY;
3513
3514         opc = mdt_intent_code(itopc);
3515         if (opc < 0)
3516                 RETURN(-EINVAL);
3517
3518         if (opc == MDT_IT_QUOTA) {
3519                 struct lu_device *qmt = info->mti_mdt->mdt_qmt_dev;
3520
3521                 if (qmt == NULL)
3522                         RETURN(-EOPNOTSUPP);
3523
3524                 (*lockp)->l_lvb_type = LVB_T_LQUOTA;
3525                 /* pass the request to quota master */
3526                 rc = qmt_hdls.qmth_intent_policy(info->mti_env, qmt,
3527                                                  mdt_info_req(info), lockp,
3528                                                  flags);
3529                 RETURN(rc);
3530         }
3531
3532         flv = &mdt_it_flavor[opc];
3533         if (flv->it_fmt != NULL)
3534                 req_capsule_extend(pill, flv->it_fmt);
3535
3536         rc = mdt_unpack_req_pack_rep(info, flv->it_flags);
3537         if (rc < 0)
3538                 RETURN(rc);
3539
3540         if (flv->it_flags & MUTABOR &&
3541             exp_connect_flags(req->rq_export) & OBD_CONNECT_RDONLY)
3542                 RETURN(-EROFS);
3543
3544         if (flv->it_act != NULL) {
3545                 struct ldlm_reply *rep;
3546
3547                 /* execute policy */
3548                 rc = flv->it_act(opc, info, lockp, flags);
3549
3550                 /* Check whether the reply has been packed successfully. */
3551                 if (req->rq_repmsg != NULL) {
3552                         rep = req_capsule_server_get(info->mti_pill,
3553                                                      &RMF_DLM_REP);
3554                         rep->lock_policy_res2 =
3555                                 ptlrpc_status_hton(rep->lock_policy_res2);
3556                 }
3557         }
3558
3559         RETURN(rc);
3560 }
3561
3562 static int mdt_intent_policy(struct ldlm_namespace *ns,
3563                              struct ldlm_lock **lockp, void *req_cookie,
3564                              ldlm_mode_t mode, __u64 flags, void *data)
3565 {
3566         struct tgt_session_info *tsi;
3567         struct mdt_thread_info  *info;
3568         struct ptlrpc_request   *req  =  req_cookie;
3569         struct ldlm_intent      *it;
3570         struct req_capsule      *pill;
3571         int rc;
3572
3573         ENTRY;
3574
3575         LASSERT(req != NULL);
3576
3577         tsi = tgt_ses_info(req->rq_svc_thread->t_env);
3578
3579         info = tsi2mdt_info(tsi);
3580         LASSERT(info != NULL);
3581         pill = info->mti_pill;
3582         LASSERT(pill->rc_req == req);
3583
3584         if (req->rq_reqmsg->lm_bufcount > DLM_INTENT_IT_OFF) {
3585                 req_capsule_extend(pill, &RQF_LDLM_INTENT_BASIC);
3586                 it = req_capsule_client_get(pill, &RMF_LDLM_INTENT);
3587                 if (it != NULL) {
3588                         rc = mdt_intent_opc(it->opc, info, lockp, flags);
3589                         if (rc == 0)
3590                                 rc = ELDLM_OK;
3591
3592                         /* Lock without inodebits makes no sense and will oops
3593                          * later in ldlm. Let's check it now to see if we have
3594                          * ibits corrupted somewhere in mdt_intent_opc().
3595                          * The case for client miss to set ibits has been
3596                          * processed by others. */
3597                         LASSERT(ergo(info->mti_dlm_req->lock_desc.l_resource.\
3598                                         lr_type == LDLM_IBITS,
3599                                      info->mti_dlm_req->lock_desc.\
3600                                         l_policy_data.l_inodebits.bits != 0));
3601                 } else
3602                         rc = err_serious(-EFAULT);
3603         } else {
3604                 /* No intent was provided */
3605                 LASSERT(pill->rc_fmt == &RQF_LDLM_ENQUEUE);
3606                 req_capsule_set_size(pill, &RMF_DLM_LVB, RCL_SERVER, 0);
3607                 rc = req_capsule_server_pack(pill);
3608                 if (rc)
3609                         rc = err_serious(rc);
3610         }
3611         mdt_thread_info_fini(info);
3612         RETURN(rc);
3613 }
3614
3615 static void mdt_deregister_seq_exp(struct mdt_device *mdt)
3616 {
3617         struct seq_server_site  *ss = mdt_seq_site(mdt);
3618
3619         if (ss->ss_node_id == 0)
3620                 return;
3621
3622         if (ss->ss_client_seq != NULL) {
3623                 lustre_deregister_lwp_item(&ss->ss_client_seq->lcs_exp);
3624                 ss->ss_client_seq->lcs_exp = NULL;
3625         }
3626
3627         if (ss->ss_server_fld != NULL) {
3628                 lustre_deregister_lwp_item(&ss->ss_server_fld->lsf_control_exp);
3629                 ss->ss_server_fld->lsf_control_exp = NULL;
3630         }
3631 }
3632
3633 static void mdt_seq_fini_cli(struct mdt_device *mdt)
3634 {
3635         struct seq_server_site *ss = mdt_seq_site(mdt);
3636
3637         if (ss == NULL)
3638                 return;
3639
3640         if (ss->ss_server_seq != NULL)
3641                 seq_server_set_cli(NULL, ss->ss_server_seq, NULL);
3642 }
3643
3644 static int mdt_seq_fini(const struct lu_env *env, struct mdt_device *mdt)
3645 {
3646         mdt_seq_fini_cli(mdt);
3647         mdt_deregister_seq_exp(mdt);
3648
3649         return seq_site_fini(env, mdt_seq_site(mdt));
3650 }
3651
3652 /**
3653  * It will retrieve its FLDB entries from MDT0, and it only happens
3654  * when upgrading existent FS to 2.6 or when local FLDB is corrupted,
3655  * and it needs to refresh FLDB from the MDT0.
3656  **/
3657 static int mdt_register_lwp_callback(void *data)
3658 {
3659         struct lu_env           env;
3660         struct mdt_device       *mdt = data;
3661         struct lu_server_fld    *fld = mdt_seq_site(mdt)->ss_server_fld;
3662         int                     rc;
3663         ENTRY;
3664
3665         LASSERT(mdt_seq_site(mdt)->ss_node_id != 0);
3666
3667         if (!likely(fld->lsf_new))
3668                 RETURN(0);
3669
3670         rc = lu_env_init(&env, LCT_MD_THREAD);
3671         if (rc) {
3672                 CERROR("%s: cannot init env: rc = %d\n", mdt_obd_name(mdt), rc);
3673                 RETURN(rc);
3674         }
3675
3676         rc = fld_update_from_controller(&env, fld);
3677         if (rc != 0) {
3678                 CERROR("%s: cannot update controller: rc = %d\n",
3679                        mdt_obd_name(mdt), rc);
3680                 GOTO(out, rc);
3681         }
3682 out:
3683         lu_env_fini(&env);
3684         RETURN(rc);
3685 }
3686
3687 static int mdt_register_seq_exp(struct mdt_device *mdt)
3688 {
3689         struct seq_server_site  *ss = mdt_seq_site(mdt);
3690         char                    *lwp_name = NULL;
3691         int                     rc;
3692
3693         if (ss->ss_node_id == 0)
3694                 return 0;
3695
3696         OBD_ALLOC(lwp_name, MAX_OBD_NAME);
3697         if (lwp_name == NULL)
3698                 GOTO(out_free, rc = -ENOMEM);
3699
3700         rc = tgt_name2lwp_name(mdt_obd_name(mdt), lwp_name, MAX_OBD_NAME, 0);
3701         if (rc != 0)
3702                 GOTO(out_free, rc);
3703
3704         rc = lustre_register_lwp_item(lwp_name, &ss->ss_client_seq->lcs_exp,
3705                                       NULL, NULL);
3706         if (rc != 0)
3707                 GOTO(out_free, rc);
3708
3709         rc = lustre_register_lwp_item(lwp_name,
3710                                       &ss->ss_server_fld->lsf_control_exp,
3711                                       mdt_register_lwp_callback, mdt);
3712         if (rc != 0) {
3713                 lustre_deregister_lwp_item(&ss->ss_client_seq->lcs_exp);
3714                 ss->ss_client_seq->lcs_exp = NULL;
3715                 GOTO(out_free, rc);
3716         }
3717 out_free:
3718         if (lwp_name != NULL)
3719                 OBD_FREE(lwp_name, MAX_OBD_NAME);
3720
3721         return rc;
3722 }
3723
3724 /*
3725  * Init client sequence manager which is used by local MDS to talk to sequence
3726  * controller on remote node.
3727  */
3728 static int mdt_seq_init_cli(const struct lu_env *env, struct mdt_device *mdt)
3729 {
3730         struct seq_server_site  *ss = mdt_seq_site(mdt);
3731         int                     rc;
3732         char                    *prefix;
3733         ENTRY;
3734
3735         /* check if this is adding the first MDC and controller is not yet
3736          * initialized. */
3737         OBD_ALLOC_PTR(ss->ss_client_seq);
3738         if (ss->ss_client_seq == NULL)
3739                 RETURN(-ENOMEM);
3740
3741         OBD_ALLOC(prefix, MAX_OBD_NAME + 5);
3742         if (prefix == NULL) {
3743                 OBD_FREE_PTR(ss->ss_client_seq);
3744                 ss->ss_client_seq = NULL;
3745                 RETURN(-ENOMEM);
3746         }
3747
3748         /* Note: seq_client_fini will be called in seq_site_fini */
3749         snprintf(prefix, MAX_OBD_NAME + 5, "ctl-%s", mdt_obd_name(mdt));
3750         rc = seq_client_init(ss->ss_client_seq, NULL, LUSTRE_SEQ_METADATA,
3751                              prefix, ss->ss_node_id == 0 ?  ss->ss_control_seq :
3752                                                             NULL);
3753         OBD_FREE(prefix, MAX_OBD_NAME + 5);
3754         if (rc != 0) {
3755                 OBD_FREE_PTR(ss->ss_client_seq);
3756                 ss->ss_client_seq = NULL;
3757                 RETURN(rc);
3758         }
3759
3760         rc = seq_server_set_cli(env, ss->ss_server_seq, ss->ss_client_seq);
3761
3762         RETURN(rc);
3763 }
3764
3765 static int mdt_seq_init(const struct lu_env *env, struct mdt_device *mdt)
3766 {
3767         struct seq_server_site  *ss;
3768         int                     rc;
3769         ENTRY;
3770
3771         ss = mdt_seq_site(mdt);
3772         /* init sequence controller server(MDT0) */
3773         if (ss->ss_node_id == 0) {
3774                 OBD_ALLOC_PTR(ss->ss_control_seq);
3775                 if (ss->ss_control_seq == NULL)
3776                         RETURN(-ENOMEM);
3777
3778                 rc = seq_server_init(env, ss->ss_control_seq, mdt->mdt_bottom,
3779                                      mdt_obd_name(mdt), LUSTRE_SEQ_CONTROLLER,
3780                                      ss);
3781                 if (rc)
3782                         GOTO(out_seq_fini, rc);
3783         }
3784
3785         /* Init normal sequence server */
3786         OBD_ALLOC_PTR(ss->ss_server_seq);
3787         if (ss->ss_server_seq == NULL)
3788                 GOTO(out_seq_fini, rc = -ENOMEM);
3789
3790         rc = seq_server_init(env, ss->ss_server_seq, mdt->mdt_bottom,
3791                              mdt_obd_name(mdt), LUSTRE_SEQ_SERVER, ss);
3792         if (rc)
3793                 GOTO(out_seq_fini, rc);
3794
3795         /* init seq client for seq server to talk to seq controller(MDT0) */
3796         rc = mdt_seq_init_cli(env, mdt);
3797         if (rc != 0)
3798                 GOTO(out_seq_fini, rc);
3799
3800         if (ss->ss_node_id != 0)
3801                 /* register controler export through lwp */
3802                 rc = mdt_register_seq_exp(mdt);
3803
3804         EXIT;
3805 out_seq_fini:
3806         if (rc)
3807                 mdt_seq_fini(env, mdt);
3808
3809         return rc;
3810 }
3811
3812 /*
3813  * FLD wrappers
3814  */
3815 static int mdt_fld_fini(const struct lu_env *env,
3816                         struct mdt_device *m)
3817 {
3818         struct seq_server_site *ss = mdt_seq_site(m);
3819         ENTRY;
3820
3821         if (ss && ss->ss_server_fld) {
3822                 fld_server_fini(env, ss->ss_server_fld);
3823                 OBD_FREE_PTR(ss->ss_server_fld);
3824                 ss->ss_server_fld = NULL;
3825         }
3826
3827         RETURN(0);
3828 }
3829
3830 static int mdt_fld_init(const struct lu_env *env,
3831                         const char *uuid,
3832                         struct mdt_device *m)
3833 {
3834         struct seq_server_site *ss;
3835         int rc;
3836         ENTRY;
3837
3838         ss = mdt_seq_site(m);
3839
3840         OBD_ALLOC_PTR(ss->ss_server_fld);
3841         if (ss->ss_server_fld == NULL)
3842                 RETURN(rc = -ENOMEM);
3843
3844         rc = fld_server_init(env, ss->ss_server_fld, m->mdt_bottom, uuid,
3845                              LU_SEQ_RANGE_MDT);
3846         if (rc) {
3847                 OBD_FREE_PTR(ss->ss_server_fld);
3848                 ss->ss_server_fld = NULL;
3849                 RETURN(rc);
3850         }
3851
3852         RETURN(0);
3853 }
3854
3855 static void mdt_stack_pre_fini(const struct lu_env *env,
3856                            struct mdt_device *m, struct lu_device *top)
3857 {
3858         struct lustre_cfg_bufs  *bufs;
3859         struct lustre_cfg       *lcfg;
3860         struct mdt_thread_info  *info;
3861         ENTRY;
3862
3863         LASSERT(top);
3864
3865         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
3866         LASSERT(info != NULL);
3867
3868         bufs = &info->mti_u.bufs;
3869
3870         LASSERT(m->mdt_child_exp);
3871         LASSERT(m->mdt_child_exp->exp_obd);
3872
3873         /* process cleanup, pass mdt obd name to get obd umount flags */
3874         /* XXX: this is needed because all layers are referenced by
3875          * objects (some of them are pinned by osd, for example *
3876          * the proper solution should be a model where object used
3877          * by osd only doesn't have mdt/mdd slices -bzzz */
3878         lustre_cfg_bufs_reset(bufs, mdt_obd_name(m));
3879         lustre_cfg_bufs_set_string(bufs, 1, NULL);
3880         lcfg = lustre_cfg_new(LCFG_PRE_CLEANUP, bufs);
3881         if (lcfg == NULL)
3882                 RETURN_EXIT;
3883
3884         top->ld_ops->ldo_process_config(env, top, lcfg);
3885         lustre_cfg_free(lcfg);
3886         EXIT;
3887 }
3888
3889 static void mdt_stack_fini(const struct lu_env *env,
3890                            struct mdt_device *m, struct lu_device *top)
3891 {
3892         struct obd_device       *obd = mdt2obd_dev(m);
3893         struct lustre_cfg_bufs  *bufs;
3894         struct lustre_cfg       *lcfg;
3895         struct mdt_thread_info  *info;
3896         char                     flags[3] = "";
3897         ENTRY;
3898
3899         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
3900         LASSERT(info != NULL);
3901
3902         lu_dev_del_linkage(top->ld_site, top);
3903
3904         lu_site_purge(env, top->ld_site, -1);
3905
3906         bufs = &info->mti_u.bufs;
3907         /* process cleanup, pass mdt obd name to get obd umount flags */
3908         /* another purpose is to let all layers to release their objects */
3909         lustre_cfg_bufs_reset(bufs, mdt_obd_name(m));
3910         if (obd->obd_force)
3911                 strcat(flags, "F");
3912         if (obd->obd_fail)
3913                 strcat(flags, "A");
3914         lustre_cfg_bufs_set_string(bufs, 1, flags);
3915         lcfg = lustre_cfg_new(LCFG_CLEANUP, bufs);
3916         if (lcfg == NULL)
3917                 RETURN_EXIT;
3918
3919         LASSERT(top);
3920         top->ld_ops->ldo_process_config(env, top, lcfg);
3921         lustre_cfg_free(lcfg);
3922
3923         lu_site_purge(env, top->ld_site, -1);
3924
3925         m->mdt_child = NULL;
3926         m->mdt_bottom = NULL;
3927
3928         obd_disconnect(m->mdt_child_exp);
3929         m->mdt_child_exp = NULL;
3930
3931         obd_disconnect(m->mdt_bottom_exp);
3932         m->mdt_child_exp = NULL;
3933 }
3934
3935 static int mdt_connect_to_next(const struct lu_env *env, struct mdt_device *m,
3936                                const char *next, struct obd_export **exp)
3937 {
3938         struct obd_connect_data *data = NULL;
3939         struct obd_device       *obd;
3940         int                      rc;
3941         ENTRY;
3942
3943         OBD_ALLOC_PTR(data);
3944         if (data == NULL)
3945                 GOTO(out, rc = -ENOMEM);
3946
3947         obd = class_name2obd(next);
3948         if (obd == NULL) {
3949                 CERROR("%s: can't locate next device: %s\n",
3950                        mdt_obd_name(m), next);
3951                 GOTO(out, rc = -ENOTCONN);
3952         }
3953
3954         data->ocd_connect_flags = OBD_CONNECT_VERSION;
3955         data->ocd_version = LUSTRE_VERSION_CODE;
3956
3957         rc = obd_connect(NULL, exp, obd, &obd->obd_uuid, data, NULL);
3958         if (rc) {
3959                 CERROR("%s: cannot connect to next dev %s (%d)\n",
3960                        mdt_obd_name(m), next, rc);
3961                 GOTO(out, rc);
3962         }
3963
3964 out:
3965         if (data)
3966                 OBD_FREE_PTR(data);
3967         RETURN(rc);
3968 }
3969
3970 static int mdt_stack_init(const struct lu_env *env, struct mdt_device *mdt,
3971                           struct lustre_cfg *cfg)
3972 {
3973         char                   *dev = lustre_cfg_string(cfg, 0);
3974         int                     rc, name_size, uuid_size;
3975         char                   *name, *uuid, *p;
3976         struct lustre_cfg_bufs *bufs;
3977         struct lustre_cfg      *lcfg;
3978         struct obd_device      *obd;
3979         struct lustre_profile  *lprof;
3980         struct lu_site         *site;
3981         ENTRY;
3982
3983         /* in 1.8 we had the only device in the stack - MDS.
3984          * 2.0 introduces MDT, MDD, OSD; MDT starts others internally.
3985          * in 2.3 OSD is instantiated by obd_mount.c, so we need
3986          * to generate names and setup MDT, MDD. MDT will be using
3987          * generated name to connect to MDD. for MDD the next device
3988          * will be LOD with name taken from so called "profile" which
3989          * is generated by mount_option line
3990          *
3991          * 1.8 MGS generates config. commands like this:
3992          *   #06 (104)mount_option 0:  1:lustre-MDT0000  2:lustre-mdtlov
3993          *   #08 (120)setup   0:lustre-MDT0000  1:dev 2:type 3:lustre-MDT0000
3994          * 2.0 MGS generates config. commands like this:
3995          *   #07 (112)mount_option 0:  1:lustre-MDT0000  2:lustre-MDT0000-mdtlov
3996          *   #08 (160)setup   0:lustre-MDT0000  1:lustre-MDT0000_UUID  2:0
3997          *                    3:lustre-MDT0000-mdtlov  4:f
3998          *
3999          * we generate MDD name from MDT one, just replacing T with D
4000          *
4001          * after all the preparations, the logical equivalent will be
4002          *   #01 (160)setup   0:lustre-MDD0000  1:lustre-MDD0000_UUID  2:0
4003          *                    3:lustre-MDT0000-mdtlov  4:f
4004          *   #02 (160)setup   0:lustre-MDT0000  1:lustre-MDT0000_UUID  2:0
4005          *                    3:lustre-MDD0000  4:f
4006          *
4007          *  notice we build the stack from down to top: MDD first, then MDT */
4008
4009         name_size = MAX_OBD_NAME;
4010         uuid_size = MAX_OBD_NAME;
4011
4012         OBD_ALLOC(name, name_size);
4013         OBD_ALLOC(uuid, uuid_size);
4014         if (name == NULL || uuid == NULL)
4015                 GOTO(cleanup_mem, rc = -ENOMEM);
4016
4017         OBD_ALLOC_PTR(bufs);
4018         if (!bufs)
4019                 GOTO(cleanup_mem, rc = -ENOMEM);
4020
4021         strcpy(name, dev);
4022         p = strstr(name, "-MDT");
4023         if (p == NULL)
4024                 GOTO(free_bufs, rc = -ENOMEM);
4025         p[3] = 'D';
4026
4027         snprintf(uuid, MAX_OBD_NAME, "%s_UUID", name);
4028
4029         lprof = class_get_profile(lustre_cfg_string(cfg, 0));
4030         if (lprof == NULL || lprof->lp_dt == NULL) {
4031                 CERROR("can't find the profile: %s\n",
4032                        lustre_cfg_string(cfg, 0));
4033                 GOTO(free_bufs, rc = -EINVAL);
4034         }
4035
4036         lustre_cfg_bufs_reset(bufs, name);
4037         lustre_cfg_bufs_set_string(bufs, 1, LUSTRE_MDD_NAME);
4038         lustre_cfg_bufs_set_string(bufs, 2, uuid);
4039         lustre_cfg_bufs_set_string(bufs, 3, lprof->lp_dt);
4040
4041         lcfg = lustre_cfg_new(LCFG_ATTACH, bufs);
4042         if (lcfg == NULL)
4043                 GOTO(free_bufs, rc = -ENOMEM);
4044
4045         rc = class_attach(lcfg);
4046         if (rc)
4047                 GOTO(lcfg_cleanup, rc);
4048
4049         obd = class_name2obd(name);
4050         if (!obd) {
4051                 CERROR("Can not find obd %s (%s in config)\n",
4052                        MDD_OBD_NAME, lustre_cfg_string(cfg, 0));
4053                 GOTO(lcfg_cleanup, rc = -EINVAL);
4054         }
4055
4056         lustre_cfg_free(lcfg);
4057
4058         lustre_cfg_bufs_reset(bufs, name);
4059         lustre_cfg_bufs_set_string(bufs, 1, uuid);
4060         lustre_cfg_bufs_set_string(bufs, 2, dev);
4061         lustre_cfg_bufs_set_string(bufs, 3, lprof->lp_dt);
4062
4063         lcfg = lustre_cfg_new(LCFG_SETUP, bufs);
4064         if (lcfg == NULL)
4065                 GOTO(class_detach, rc = -ENOMEM);
4066
4067         rc = class_setup(obd, lcfg);
4068         if (rc)
4069                 GOTO(class_detach, rc);
4070
4071         /* connect to MDD we just setup */
4072         rc = mdt_connect_to_next(env, mdt, name, &mdt->mdt_child_exp);
4073         if (rc)
4074                 GOTO(class_detach, rc);
4075
4076         site = mdt->mdt_child_exp->exp_obd->obd_lu_dev->ld_site;
4077         LASSERT(site);
4078         LASSERT(mdt_lu_site(mdt) == NULL);
4079         mdt->mdt_lu_dev.ld_site = site;
4080         site->ls_top_dev = &mdt->mdt_lu_dev;
4081         mdt->mdt_child = lu2md_dev(mdt->mdt_child_exp->exp_obd->obd_lu_dev);
4082
4083         /* now connect to bottom OSD */
4084         snprintf(name, MAX_OBD_NAME, "%s-osd", dev);
4085         rc = mdt_connect_to_next(env, mdt, name, &mdt->mdt_bottom_exp);
4086         if (rc)
4087                 GOTO(class_detach, rc);
4088         mdt->mdt_bottom =
4089                 lu2dt_dev(mdt->mdt_bottom_exp->exp_obd->obd_lu_dev);
4090
4091         rc = lu_env_refill((struct lu_env *)env);
4092         if (rc != 0)
4093                 CERROR("Failure to refill session: '%d'\n", rc);
4094
4095         lu_dev_add_linkage(site, &mdt->mdt_lu_dev);
4096
4097         EXIT;
4098 class_detach:
4099         if (rc)
4100                 class_detach(obd, lcfg);
4101 lcfg_cleanup:
4102         lustre_cfg_free(lcfg);
4103 free_bufs:
4104         OBD_FREE_PTR(bufs);
4105 cleanup_mem:
4106         if (name)
4107                 OBD_FREE(name, name_size);
4108         if (uuid)
4109                 OBD_FREE(uuid, uuid_size);
4110         RETURN(rc);
4111 }
4112
4113 /* setup quota master target on MDT0 */
4114 static int mdt_quota_init(const struct lu_env *env, struct mdt_device *mdt,
4115                           struct lustre_cfg *cfg)
4116 {
4117         struct obd_device       *obd;
4118         char                    *dev = lustre_cfg_string(cfg, 0);
4119         char                    *qmtname, *uuid, *p;
4120         struct lustre_cfg_bufs  *bufs;
4121         struct lustre_cfg       *lcfg;
4122         struct lustre_profile   *lprof;
4123         struct obd_connect_data *data;
4124         int                      rc;
4125         ENTRY;
4126
4127         LASSERT(mdt->mdt_qmt_exp == NULL);
4128         LASSERT(mdt->mdt_qmt_dev == NULL);
4129
4130         /* quota master is on MDT0 only for now */
4131         if (mdt->mdt_seq_site.ss_node_id != 0)
4132                 RETURN(0);
4133
4134         /* MGS generates config commands which look as follows:
4135          *   #01 (160)setup   0:lustre-MDT0000  1:lustre-MDT0000_UUID  2:0
4136          *                    3:lustre-MDT0000-mdtlov  4:f
4137          *
4138          * We generate the QMT name from the MDT one, just replacing MD with QM
4139          * after all the preparations, the logical equivalent will be:
4140          *   #01 (160)setup   0:lustre-QMT0000  1:lustre-QMT0000_UUID  2:0
4141          *                    3:lustre-MDT0000-osd  4:f */
4142         OBD_ALLOC(qmtname, MAX_OBD_NAME);
4143         OBD_ALLOC(uuid, UUID_MAX);
4144         OBD_ALLOC_PTR(bufs);
4145         OBD_ALLOC_PTR(data);
4146         if (qmtname == NULL || uuid == NULL || bufs == NULL || data == NULL)
4147                 GOTO(cleanup_mem, rc = -ENOMEM);
4148
4149         strcpy(qmtname, dev);
4150         p = strstr(qmtname, "-MDT");
4151         if (p == NULL)
4152                 GOTO(cleanup_mem, rc = -ENOMEM);
4153         /* replace MD with QM */
4154         p[1] = 'Q';
4155         p[2] = 'M';
4156
4157         snprintf(uuid, UUID_MAX, "%s_UUID", qmtname);
4158
4159         lprof = class_get_profile(lustre_cfg_string(cfg, 0));
4160         if (lprof == NULL || lprof->lp_dt == NULL) {
4161                 CERROR("can't find profile for %s\n",
4162                        lustre_cfg_string(cfg, 0));
4163                 GOTO(cleanup_mem, rc = -EINVAL);
4164         }
4165
4166         lustre_cfg_bufs_reset(bufs, qmtname);
4167         lustre_cfg_bufs_set_string(bufs, 1, LUSTRE_QMT_NAME);
4168         lustre_cfg_bufs_set_string(bufs, 2, uuid);
4169         lustre_cfg_bufs_set_string(bufs, 3, lprof->lp_dt);
4170
4171         lcfg = lustre_cfg_new(LCFG_ATTACH, bufs);
4172         if (lcfg == NULL)
4173                 GOTO(cleanup_mem, rc = -ENOMEM);
4174
4175         rc = class_attach(lcfg);
4176         if (rc)
4177                 GOTO(lcfg_cleanup, rc);
4178
4179         obd = class_name2obd(qmtname);
4180         if (!obd) {
4181                 CERROR("Can not find obd %s (%s in config)\n", qmtname,
4182                        lustre_cfg_string(cfg, 0));
4183                 GOTO(lcfg_cleanup, rc = -EINVAL);
4184         }
4185
4186         lustre_cfg_free(lcfg);
4187
4188         lustre_cfg_bufs_reset(bufs, qmtname);
4189         lustre_cfg_bufs_set_string(bufs, 1, uuid);
4190         lustre_cfg_bufs_set_string(bufs, 2, dev);
4191
4192         /* for quota, the next device should be the OSD device */
4193         lustre_cfg_bufs_set_string(bufs, 3,
4194                                    mdt->mdt_bottom->dd_lu_dev.ld_obd->obd_name);
4195
4196         lcfg = lustre_cfg_new(LCFG_SETUP, bufs);
4197         if (lcfg == NULL)
4198                 GOTO(class_detach, rc = -ENOMEM);
4199
4200         rc = class_setup(obd, lcfg);
4201         if (rc)
4202                 GOTO(class_detach, rc);
4203
4204         mdt->mdt_qmt_dev = obd->obd_lu_dev;
4205
4206         /* configure local quota objects */
4207         rc = mdt->mdt_qmt_dev->ld_ops->ldo_prepare(env,
4208                                                    &mdt->mdt_lu_dev,
4209                                                    mdt->mdt_qmt_dev);
4210         if (rc)
4211                 GOTO(class_cleanup, rc);
4212
4213         /* connect to quota master target */
4214         data->ocd_connect_flags = OBD_CONNECT_VERSION;
4215         data->ocd_version = LUSTRE_VERSION_CODE;
4216         rc = obd_connect(NULL, &mdt->mdt_qmt_exp, obd, &obd->obd_uuid,
4217                          data, NULL);
4218         if (rc) {
4219                 CERROR("cannot connect to quota master device %s (%d)\n",
4220                        qmtname, rc);
4221                 GOTO(class_cleanup, rc);
4222         }
4223
4224         EXIT;
4225 class_cleanup:
4226         if (rc) {
4227                 class_manual_cleanup(obd);
4228                 mdt->mdt_qmt_dev = NULL;
4229         }
4230 class_detach:
4231         if (rc)
4232                 class_detach(obd, lcfg);
4233 lcfg_cleanup:
4234         lustre_cfg_free(lcfg);
4235 cleanup_mem:
4236         if (bufs)
4237                 OBD_FREE_PTR(bufs);
4238         if (qmtname)
4239                 OBD_FREE(qmtname, MAX_OBD_NAME);
4240         if (uuid)
4241                 OBD_FREE(uuid, UUID_MAX);
4242         if (data)
4243                 OBD_FREE_PTR(data);
4244         return rc;
4245 }
4246
4247 /* Shutdown quota master target associated with mdt */
4248 static void mdt_quota_fini(const struct lu_env *env, struct mdt_device *mdt)
4249 {
4250         ENTRY;
4251
4252         if (mdt->mdt_qmt_exp == NULL)
4253                 RETURN_EXIT;
4254         LASSERT(mdt->mdt_qmt_dev != NULL);
4255
4256         /* the qmt automatically shuts down when the mdt disconnects */
4257         obd_disconnect(mdt->mdt_qmt_exp);
4258         mdt->mdt_qmt_exp = NULL;
4259         mdt->mdt_qmt_dev = NULL;
4260         EXIT;
4261 }
4262
4263 /* mdt_getxattr() is used from mdt_intent_getxattr(), use this wrapper
4264  * for now. This will be removed along with converting rest of MDT code
4265  * to use tgt_session_info */
4266 static int mdt_tgt_getxattr(struct tgt_session_info *tsi)
4267 {
4268         struct mdt_thread_info  *info = tsi2mdt_info(tsi);
4269         int                      rc;
4270
4271         rc = mdt_getxattr(info);
4272
4273         mdt_thread_info_fini(info);
4274         return rc;
4275 }
4276
4277 static struct tgt_handler mdt_tgt_handlers[] = {
4278 TGT_RPC_HANDLER(MDS_FIRST_OPC,
4279                 0,                      MDS_CONNECT,    mdt_tgt_connect,
4280                 &RQF_CONNECT, LUSTRE_OBD_VERSION),
4281 TGT_RPC_HANDLER(MDS_FIRST_OPC,
4282                 0,                      MDS_DISCONNECT, tgt_disconnect,
4283                 &RQF_MDS_DISCONNECT, LUSTRE_OBD_VERSION),
4284 TGT_RPC_HANDLER(MDS_FIRST_OPC,
4285                 HABEO_REFERO,           MDS_SET_INFO,   mdt_set_info,
4286                 &RQF_OBD_SET_INFO, LUSTRE_MDS_VERSION),
4287 TGT_MDT_HDL(0,                          MDS_GET_INFO,   mdt_get_info),
4288 TGT_MDT_HDL(0           | HABEO_REFERO, MDS_GETSTATUS,  mdt_getstatus),
4289 TGT_MDT_HDL(HABEO_CORPUS,               MDS_GETATTR,    mdt_getattr),
4290 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO, MDS_GETATTR_NAME,
4291                                                         mdt_getattr_name),
4292 TGT_MDT_HDL(HABEO_CORPUS,               MDS_GETXATTR,   mdt_tgt_getxattr),
4293 TGT_MDT_HDL(0           | HABEO_REFERO, MDS_STATFS,     mdt_statfs),
4294 TGT_MDT_HDL(0           | MUTABOR,      MDS_REINT,      mdt_reint),
4295 TGT_MDT_HDL(HABEO_CORPUS,               MDS_CLOSE,      mdt_close),
4296 TGT_MDT_HDL(HABEO_CORPUS,               MDS_DONE_WRITING,
4297                                                         mdt_done_writing),
4298 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO, MDS_READPAGE,   mdt_readpage),
4299 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO, MDS_SYNC,       mdt_sync),
4300 TGT_MDT_HDL(0,                          MDS_QUOTACTL,   mdt_quotactl),
4301 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO | MUTABOR, MDS_HSM_PROGRESS,
4302                                                         mdt_hsm_progress),
4303 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO | MUTABOR, MDS_HSM_CT_REGISTER,
4304                                                         mdt_hsm_ct_register),
4305 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO | MUTABOR, MDS_HSM_CT_UNREGISTER,
4306                                                         mdt_hsm_ct_unregister),
4307 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO, MDS_HSM_STATE_GET,
4308                                                         mdt_hsm_state_get),
4309 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO | MUTABOR, MDS_HSM_STATE_SET,
4310                                                         mdt_hsm_state_set),
4311 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO, MDS_HSM_ACTION, mdt_hsm_action),
4312 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO, MDS_HSM_REQUEST,
4313                                                         mdt_hsm_request),
4314 TGT_MDT_HDL(HABEO_CLAVIS | HABEO_CORPUS | HABEO_REFERO | MUTABOR,
4315             MDS_SWAP_LAYOUTS,
4316             mdt_swap_layouts),
4317 };
4318
4319 static struct tgt_handler mdt_sec_ctx_ops[] = {
4320 TGT_SEC_HDL_VAR(0,                      SEC_CTX_INIT,     mdt_sec_ctx_handle),
4321 TGT_SEC_HDL_VAR(0,                      SEC_CTX_INIT_CONT,mdt_sec_ctx_handle),
4322 TGT_SEC_HDL_VAR(0,                      SEC_CTX_FINI,     mdt_sec_ctx_handle)
4323 };
4324
4325 static struct tgt_handler mdt_quota_ops[] = {
4326 TGT_QUOTA_HDL(HABEO_REFERO,             QUOTA_DQACQ,      mdt_quota_dqacq),
4327 };
4328
4329 static struct tgt_opc_slice mdt_common_slice[] = {
4330         {
4331                 .tos_opc_start  = MDS_FIRST_OPC,
4332                 .tos_opc_end    = MDS_LAST_OPC,
4333                 .tos_hs         = mdt_tgt_handlers
4334         },
4335         {
4336                 .tos_opc_start  = OBD_FIRST_OPC,
4337                 .tos_opc_end    = OBD_LAST_OPC,
4338                 .tos_hs         = tgt_obd_handlers
4339         },
4340         {
4341                 .tos_opc_start  = LDLM_FIRST_OPC,
4342                 .tos_opc_end    = LDLM_LAST_OPC,
4343                 .tos_hs         = tgt_dlm_handlers
4344         },
4345         {
4346                 .tos_opc_start  = SEC_FIRST_OPC,
4347                 .tos_opc_end    = SEC_LAST_OPC,
4348                 .tos_hs         = mdt_sec_ctx_ops
4349         },
4350         {
4351                 .tos_opc_start  = OUT_UPDATE_FIRST_OPC,
4352                 .tos_opc_end    = OUT_UPDATE_LAST_OPC,
4353                 .tos_hs         = tgt_out_handlers
4354         },
4355         {
4356                 .tos_opc_start  = FLD_FIRST_OPC,
4357                 .tos_opc_end    = FLD_LAST_OPC,
4358                 .tos_hs         = fld_handlers
4359         },
4360         {
4361                 .tos_opc_start  = SEQ_FIRST_OPC,
4362                 .tos_opc_end    = SEQ_LAST_OPC,
4363                 .tos_hs         = seq_handlers
4364         },
4365         {
4366                 .tos_opc_start  = QUOTA_DQACQ,
4367                 .tos_opc_end    = QUOTA_LAST_OPC,
4368                 .tos_hs         = mdt_quota_ops
4369         },
4370         {
4371                 .tos_opc_start  = LLOG_FIRST_OPC,
4372                 .tos_opc_end    = LLOG_LAST_OPC,
4373                 .tos_hs         = tgt_llog_handlers
4374         },
4375         {
4376                 .tos_opc_start  = LFSCK_FIRST_OPC,
4377                 .tos_opc_end    = LFSCK_LAST_OPC,
4378                 .tos_hs         = tgt_lfsck_handlers
4379         },
4380
4381         {
4382                 .tos_hs         = NULL
4383         }
4384 };
4385
4386 static void mdt_fini(const struct lu_env *env, struct mdt_device *m)
4387 {
4388         struct md_device        *next = m->mdt_child;
4389         struct lu_device        *d    = &m->mdt_lu_dev;
4390         struct obd_device       *obd  = mdt2obd_dev(m);
4391         struct lfsck_stop        stop;
4392         ENTRY;
4393
4394         stop.ls_status = LS_PAUSED;
4395         stop.ls_flags = 0;
4396         next->md_ops->mdo_iocontrol(env, next, OBD_IOC_STOP_LFSCK, 0, &stop);
4397
4398         target_recovery_fini(obd);
4399         ping_evictor_stop();
4400         mdt_stack_pre_fini(env, m, md2lu_dev(m->mdt_child));
4401
4402         if (m->mdt_opts.mo_coordinator)
4403                 mdt_hsm_cdt_stop(m);
4404
4405         mdt_hsm_cdt_fini(m);
4406
4407         mdt_llog_ctxt_unclone(env, m, LLOG_AGENT_ORIG_CTXT);
4408         mdt_llog_ctxt_unclone(env, m, LLOG_CHANGELOG_ORIG_CTXT);
4409         obd_exports_barrier(obd);
4410         obd_zombie_barrier();
4411
4412         mdt_procfs_fini(m);
4413
4414         tgt_fini(env, &m->mdt_lut);
4415         mdt_fs_cleanup(env, m);
4416         upcall_cache_cleanup(m->mdt_identity_cache);
4417         m->mdt_identity_cache = NULL;
4418
4419         if (m->mdt_namespace != NULL) {
4420                 ldlm_namespace_free(m->mdt_namespace, NULL,
4421                                     d->ld_obd->obd_force);
4422                 d->ld_obd->obd_namespace = m->mdt_namespace = NULL;
4423         }
4424
4425         mdt_quota_fini(env, m);
4426
4427         cfs_free_nidlist(&m->mdt_squash.rsi_nosquash_nids);
4428
4429         mdt_seq_fini(env, m);
4430         mdt_fld_fini(env, m);
4431
4432         next->md_ops->mdo_init_capa_ctxt(env, next, 0, 0, 0, NULL);
4433         cfs_timer_disarm(&m->mdt_ck_timer);
4434         mdt_ck_thread_stop(m);
4435
4436         /*
4437          * Finish the stack
4438          */
4439         mdt_stack_fini(env, m, md2lu_dev(m->mdt_child));
4440
4441         LASSERT(atomic_read(&d->ld_ref) == 0);
4442
4443         server_put_mount(mdt_obd_name(m), true);
4444
4445         EXIT;
4446 }
4447
4448 static int mdt_postrecov(const struct lu_env *, struct mdt_device *);
4449
4450 static int mdt_init0(const struct lu_env *env, struct mdt_device *m,
4451                      struct lu_device_type *ldt, struct lustre_cfg *cfg)
4452 {
4453         struct mdt_thread_info    *info;
4454         struct obd_device         *obd;
4455         const char                *dev = lustre_cfg_string(cfg, 0);
4456         const char                *num = lustre_cfg_string(cfg, 2);
4457         struct lustre_mount_info  *lmi = NULL;
4458         struct lustre_sb_info     *lsi;
4459         struct lu_site            *s;
4460         struct seq_server_site    *ss_site;
4461         const char                *identity_upcall = "NONE";
4462         struct md_device          *next;
4463         int                        rc;
4464         long                       node_id;
4465         mntopt_t                   mntopts;
4466         ENTRY;
4467
4468         lu_device_init(&m->mdt_lu_dev, ldt);
4469         /*
4470          * Environment (env) might be missing mdt_thread_key values at that
4471          * point, if device is allocated when mdt_thread_key is in QUIESCENT
4472          * mode.
4473          *
4474          * Usually device allocation path doesn't use module key values, but
4475          * mdt has to do a lot of work here, so allocate key value.
4476          */
4477         rc = lu_env_refill((struct lu_env *)env);
4478         if (rc != 0)
4479                 RETURN(rc);
4480
4481         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
4482         LASSERT(info != NULL);
4483
4484         obd = class_name2obd(dev);
4485         LASSERT(obd != NULL);
4486
4487         m->mdt_max_mdsize = MAX_MD_SIZE; /* 4 stripes */
4488
4489         m->mdt_som_conf = 0;
4490
4491         m->mdt_opts.mo_cos = MDT_COS_DEFAULT;
4492
4493         /* default is coordinator off, it is started through conf_param
4494          * or /proc */
4495         m->mdt_opts.mo_coordinator = 0;
4496
4497         lmi = server_get_mount(dev);
4498         if (lmi == NULL) {
4499                 CERROR("Cannot get mount info for %s!\n", dev);
4500                 RETURN(-EFAULT);
4501         } else {
4502                 lsi = s2lsi(lmi->lmi_sb);
4503                 /* CMD is supported only in IAM mode */
4504                 LASSERT(num);
4505                 node_id = simple_strtol(num, NULL, 10);
4506                 obd->u.obt.obt_magic = OBT_MAGIC;
4507         }
4508
4509         spin_lock_init(&m->mdt_ioepoch_lock);
4510         m->mdt_capa_timeout = CAPA_TIMEOUT;
4511         m->mdt_capa_alg = CAPA_HMAC_ALG_SHA1;
4512         m->mdt_ck_timeout = CAPA_KEY_TIMEOUT;
4513         m->mdt_squash.rsi_uid = 0;
4514         m->mdt_squash.rsi_gid = 0;
4515         INIT_LIST_HEAD(&m->mdt_squash.rsi_nosquash_nids);
4516         init_rwsem(&m->mdt_squash.rsi_sem);
4517         spin_lock_init(&m->mdt_osfs_lock);
4518         m->mdt_osfs_age = cfs_time_shift_64(-1000);
4519         m->mdt_enable_remote_dir = 0;
4520         m->mdt_enable_remote_dir_gid = 0;
4521
4522         m->mdt_lu_dev.ld_ops = &mdt_lu_ops;
4523         m->mdt_lu_dev.ld_obd = obd;
4524         /* Set this lu_device to obd for error handling purposes. */
4525         obd->obd_lu_dev = &m->mdt_lu_dev;
4526
4527         /* init the stack */
4528         rc = mdt_stack_init((struct lu_env *)env, m, cfg);
4529         if (rc) {
4530                 CERROR("%s: Can't init device stack, rc %d\n",
4531                        mdt_obd_name(m), rc);
4532                 GOTO(err_lmi, rc);
4533         }
4534
4535         s = mdt_lu_site(m);
4536         ss_site = mdt_seq_site(m);
4537         s->ld_seq_site = ss_site;
4538         ss_site->ss_lu = s;
4539
4540         /* set server index */
4541         ss_site->ss_node_id = node_id;
4542
4543         /* failover is the default
4544          * FIXME: we do not failout mds0/mgs, which may cause some problems.
4545          * assumed whose ss_node_id == 0 XXX
4546          * */
4547         obd->obd_replayable = 1;
4548         /* No connection accepted until configurations will finish */
4549         obd->obd_no_conn = 1;
4550
4551         if (cfg->lcfg_bufcount > 4 && LUSTRE_CFG_BUFLEN(cfg, 4) > 0) {
4552                 char *str = lustre_cfg_string(cfg, 4);
4553                 if (strchr(str, 'n')) {
4554                         CWARN("%s: recovery disabled\n", mdt_obd_name(m));
4555                         obd->obd_replayable = 0;
4556                 }
4557         }
4558
4559         rc = mdt_fld_init(env, mdt_obd_name(m), m);
4560         if (rc)
4561                 GOTO(err_fini_stack, rc);
4562
4563         rc = mdt_seq_init(env, m);
4564         if (rc)
4565                 GOTO(err_fini_fld, rc);
4566
4567         snprintf(info->mti_u.ns_name, sizeof(info->mti_u.ns_name), "%s-%s",
4568                  LUSTRE_MDT_NAME, obd->obd_uuid.uuid);
4569         m->mdt_namespace = ldlm_namespace_new(obd, info->mti_u.ns_name,
4570                                               LDLM_NAMESPACE_SERVER,
4571                                               LDLM_NAMESPACE_GREEDY,
4572                                               LDLM_NS_TYPE_MDT);
4573         if (m->mdt_namespace == NULL)
4574                 GOTO(err_fini_seq, rc = -ENOMEM);
4575
4576         m->mdt_namespace->ns_lvbp = m;
4577         m->mdt_namespace->ns_lvbo = &mdt_lvbo;
4578
4579         ldlm_register_intent(m->mdt_namespace, mdt_intent_policy);
4580         /* set obd_namespace for compatibility with old code */
4581         obd->obd_namespace = m->mdt_namespace;
4582
4583         cfs_timer_init(&m->mdt_ck_timer, mdt_ck_timer_callback, m);
4584
4585         rc = mdt_hsm_cdt_init(m);
4586         if (rc != 0) {
4587                 CERROR("%s: error initializing coordinator, rc %d\n",
4588                        mdt_obd_name(m), rc);
4589                 GOTO(err_free_ns, rc);
4590         }
4591
4592         rc = mdt_ck_thread_start(m);
4593         if (rc)
4594                 GOTO(err_free_hsm, rc);
4595
4596         rc = tgt_init(env, &m->mdt_lut, obd, m->mdt_bottom, mdt_common_slice,
4597                       OBD_FAIL_MDS_ALL_REQUEST_NET,
4598                       OBD_FAIL_MDS_ALL_REPLY_NET);
4599         if (rc)
4600                 GOTO(err_capa, rc);
4601
4602         rc = mdt_fs_setup(env, m, obd, lsi);
4603         if (rc)
4604                 GOTO(err_tgt, rc);
4605
4606         tgt_adapt_sptlrpc_conf(&m->mdt_lut, 1);
4607
4608         next = m->mdt_child;
4609         rc = next->md_ops->mdo_iocontrol(env, next, OBD_IOC_GET_MNTOPT, 0,
4610                                          &mntopts);
4611         if (rc)
4612                 GOTO(err_fs_cleanup, rc);
4613
4614         if (mntopts & MNTOPT_USERXATTR)
4615                 m->mdt_opts.mo_user_xattr = 1;
4616         else
4617                 m->mdt_opts.mo_user_xattr = 0;
4618
4619         rc = next->md_ops->mdo_maxeasize_get(env, next, &m->mdt_max_ea_size);
4620         if (rc)
4621                 GOTO(err_fs_cleanup, rc);
4622
4623         if (mntopts & MNTOPT_ACL)
4624                 m->mdt_opts.mo_acl = 1;
4625         else
4626                 m->mdt_opts.mo_acl = 0;
4627
4628         /* XXX: to support suppgid for ACL, we enable identity_upcall
4629          * by default, otherwise, maybe got unexpected -EACCESS. */
4630         if (m->mdt_opts.mo_acl)
4631                 identity_upcall = MDT_IDENTITY_UPCALL_PATH;
4632
4633         m->mdt_identity_cache = upcall_cache_init(mdt_obd_name(m),
4634                                                 identity_upcall,
4635                                                 &mdt_identity_upcall_cache_ops);
4636         if (IS_ERR(m->mdt_identity_cache)) {
4637                 rc = PTR_ERR(m->mdt_identity_cache);
4638                 m->mdt_identity_cache = NULL;
4639                 GOTO(err_fs_cleanup, rc);
4640         }
4641
4642         rc = mdt_procfs_init(m, dev);
4643         if (rc) {
4644                 CERROR("Can't init MDT lprocfs, rc %d\n", rc);
4645                 GOTO(err_recovery, rc);
4646         }
4647
4648         rc = mdt_quota_init(env, m, cfg);
4649         if (rc)
4650                 GOTO(err_procfs, rc);
4651
4652         m->mdt_ldlm_client = &mdt2obd_dev(m)->obd_ldlm_client;
4653         ptlrpc_init_client(LDLM_CB_REQUEST_PORTAL, LDLM_CB_REPLY_PORTAL,
4654                            "mdt_ldlm_client", m->mdt_ldlm_client);
4655
4656         ping_evictor_start();
4657
4658         /* recovery will be started upon mdt_prepare()
4659          * when the whole stack is complete and ready
4660          * to serve the requests */
4661
4662         mdt_init_capa_ctxt(env, m);
4663
4664         /* Reduce the initial timeout on an MDS because it doesn't need such
4665          * a long timeout as an OST does. Adaptive timeouts will adjust this
4666          * value appropriately. */
4667         if (ldlm_timeout == LDLM_TIMEOUT_DEFAULT)
4668                 ldlm_timeout = MDS_LDLM_TIMEOUT_DEFAULT;
4669
4670         RETURN(0);
4671 err_procfs:
4672         mdt_procfs_fini(m);
4673 err_recovery:
4674         target_recovery_fini(obd);
4675         upcall_cache_cleanup(m->mdt_identity_cache);
4676         m->mdt_identity_cache = NULL;
4677 err_fs_cleanup:
4678         mdt_fs_cleanup(env, m);
4679 err_tgt:
4680         tgt_fini(env, &m->mdt_lut);
4681 err_capa:
4682         cfs_timer_disarm(&m->mdt_ck_timer);
4683         mdt_ck_thread_stop(m);
4684 err_free_hsm:
4685         mdt_hsm_cdt_fini(m);
4686 err_free_ns:
4687         ldlm_namespace_free(m->mdt_namespace, NULL, 0);
4688         obd->obd_namespace = m->mdt_namespace = NULL;
4689 err_fini_seq:
4690         mdt_seq_fini(env, m);
4691 err_fini_fld:
4692         mdt_fld_fini(env, m);
4693 err_fini_stack:
4694         mdt_stack_fini(env, m, md2lu_dev(m->mdt_child));
4695 err_lmi:
4696         if (lmi)
4697                 server_put_mount(dev, true);
4698         return(rc);
4699 }
4700
4701 /* For interoperability, the left element is old parameter, the right one
4702  * is the new version of the parameter, if some parameter is deprecated,
4703  * the new version should be set as NULL. */
4704 static struct cfg_interop_param mdt_interop_param[] = {
4705         { "mdt.group_upcall",   NULL },
4706         { "mdt.quota_type",     NULL },
4707         { "mdd.quota_type",     NULL },
4708         { "mdt.rootsquash",     "mdt.root_squash" },
4709         { "mdt.nosquash_nid",   "mdt.nosquash_nids" },
4710         { NULL }
4711 };
4712
4713 /* used by MGS to process specific configurations */
4714 static int mdt_process_config(const struct lu_env *env,
4715                               struct lu_device *d, struct lustre_cfg *cfg)
4716 {
4717         struct mdt_device *m = mdt_dev(d);
4718         struct md_device *md_next = m->mdt_child;
4719         struct lu_device *next = md2lu_dev(md_next);
4720         int rc;
4721         ENTRY;
4722
4723         switch (cfg->lcfg_command) {
4724         case LCFG_PARAM: {
4725                 struct obd_device          *obd = d->ld_obd;
4726
4727                 /* For interoperability */
4728                 struct cfg_interop_param   *ptr = NULL;
4729                 struct lustre_cfg          *old_cfg = NULL;
4730                 char                       *param = NULL;
4731
4732                 param = lustre_cfg_string(cfg, 1);
4733                 if (param == NULL) {
4734                         CERROR("param is empty\n");
4735                         rc = -EINVAL;
4736                         break;
4737                 }
4738
4739                 ptr = class_find_old_param(param, mdt_interop_param);
4740                 if (ptr != NULL) {
4741                         if (ptr->new_param == NULL) {
4742                                 rc = 0;
4743                                 CWARN("For interoperability, skip this %s."
4744                                       " It is obsolete.\n", ptr->old_param);
4745                                 break;
4746                         }
4747
4748                         CWARN("Found old param %s, changed it to %s.\n",
4749                               ptr->old_param, ptr->new_param);
4750
4751                         old_cfg = cfg;
4752                         cfg = lustre_cfg_rename(old_cfg, ptr->new_param);
4753                         if (IS_ERR(cfg)) {
4754                                 rc = PTR_ERR(cfg);
4755                                 break;
4756                         }
4757                 }
4758
4759                 rc = class_process_proc_param(PARAM_MDT, obd->obd_vars,
4760                                               cfg, obd);
4761                 if (rc > 0 || rc == -ENOSYS) {
4762                         /* is it an HSM var ? */
4763                         rc = class_process_proc_param(PARAM_HSM,
4764                                                       hsm_cdt_get_proc_vars(),
4765                                                       cfg, obd);
4766                         if (rc > 0 || rc == -ENOSYS)
4767                                 /* we don't understand; pass it on */
4768                                 rc = next->ld_ops->ldo_process_config(env, next,
4769                                                                       cfg);
4770                 }
4771
4772                 if (old_cfg != NULL)
4773                         lustre_cfg_free(cfg);
4774
4775                 break;
4776         }
4777         default:
4778                 /* others are passed further */
4779                 rc = next->ld_ops->ldo_process_config(env, next, cfg);
4780                 break;
4781         }
4782         RETURN(rc);
4783 }
4784
4785 static struct lu_object *mdt_object_alloc(const struct lu_env *env,
4786                                           const struct lu_object_header *hdr,
4787                                           struct lu_device *d)
4788 {
4789         struct mdt_object *mo;
4790
4791         ENTRY;
4792
4793         OBD_SLAB_ALLOC_PTR_GFP(mo, mdt_object_kmem, GFP_NOFS);
4794         if (mo != NULL) {
4795                 struct lu_object *o;
4796                 struct lu_object_header *h;
4797
4798                 o = &mo->mot_obj;
4799                 h = &mo->mot_header;
4800                 lu_object_header_init(h);
4801                 lu_object_init(o, h, d);
4802                 lu_object_add_top(h, o);
4803                 o->lo_ops = &mdt_obj_ops;
4804                 mutex_init(&mo->mot_ioepoch_mutex);
4805                 mutex_init(&mo->mot_lov_mutex);
4806                 init_rwsem(&mo->mot_open_sem);
4807                 RETURN(o);
4808         }
4809         RETURN(NULL);
4810 }
4811
4812 static int mdt_object_init(const struct lu_env *env, struct lu_object *o,
4813                            const struct lu_object_conf *unused)
4814 {
4815         struct mdt_device *d = mdt_dev(o->lo_dev);
4816         struct lu_device  *under;
4817         struct lu_object  *below;
4818         int                rc = 0;
4819         ENTRY;
4820
4821         CDEBUG(D_INFO, "object init, fid = "DFID"\n",
4822                PFID(lu_object_fid(o)));
4823
4824         under = &d->mdt_child->md_lu_dev;
4825         below = under->ld_ops->ldo_object_alloc(env, o->lo_header, under);
4826         if (below != NULL) {
4827                 lu_object_add(o, below);
4828         } else
4829                 rc = -ENOMEM;
4830
4831         RETURN(rc);
4832 }
4833
4834 static void mdt_object_free(const struct lu_env *env, struct lu_object *o)
4835 {
4836         struct mdt_object *mo = mdt_obj(o);
4837         struct lu_object_header *h;
4838         ENTRY;
4839
4840         h = o->lo_header;
4841         CDEBUG(D_INFO, "object free, fid = "DFID"\n",
4842                PFID(lu_object_fid(o)));
4843
4844         LASSERT(atomic_read(&mo->mot_open_count) == 0);
4845         LASSERT(atomic_read(&mo->mot_lease_count) == 0);
4846
4847         lu_object_fini(o);
4848         lu_object_header_fini(h);
4849         OBD_SLAB_FREE_PTR(mo, mdt_object_kmem);
4850
4851         EXIT;
4852 }
4853
4854 static int mdt_object_print(const struct lu_env *env, void *cookie,
4855                             lu_printer_t p, const struct lu_object *o)
4856 {
4857         struct mdt_object *mdto = mdt_obj((struct lu_object *)o);
4858         return (*p)(env, cookie, LUSTRE_MDT_NAME"-object@%p(ioepoch="LPU64" "
4859                     "flags="LPX64", epochcount=%d, writecount=%d)",
4860                     mdto, mdto->mot_ioepoch, mdto->mot_flags,
4861                     mdto->mot_ioepoch_count, mdto->mot_writecount);
4862 }
4863
4864 static int mdt_prepare(const struct lu_env *env,
4865                 struct lu_device *pdev,
4866                 struct lu_device *cdev)
4867 {
4868         struct mdt_device *mdt = mdt_dev(cdev);
4869         struct lu_device *next = &mdt->mdt_child->md_lu_dev;
4870         struct obd_device *obd = cdev->ld_obd;
4871         int rc;
4872
4873         ENTRY;
4874
4875         LASSERT(obd);
4876
4877         rc = next->ld_ops->ldo_prepare(env, cdev, next);
4878         if (rc)
4879                 RETURN(rc);
4880
4881         rc = mdt_llog_ctxt_clone(env, mdt, LLOG_CHANGELOG_ORIG_CTXT);
4882         if (rc)
4883                 RETURN(rc);
4884
4885         rc = mdt_llog_ctxt_clone(env, mdt, LLOG_AGENT_ORIG_CTXT);
4886         if (rc)
4887                 RETURN(rc);
4888
4889         rc = lfsck_register_namespace(env, mdt->mdt_bottom, mdt->mdt_namespace);
4890         /* The LFSCK instance is registered just now, so it must be there when
4891          * register the namespace to such instance. */
4892         LASSERTF(rc == 0, "register namespace failed: rc = %d\n", rc);
4893
4894         if (mdt->mdt_seq_site.ss_node_id == 0) {
4895                 rc = mdt->mdt_child->md_ops->mdo_root_get(env, mdt->mdt_child,
4896                                                          &mdt->mdt_md_root_fid);
4897                 if (rc)
4898                         RETURN(rc);
4899         }
4900
4901         LASSERT(!test_bit(MDT_FL_CFGLOG, &mdt->mdt_state));
4902         target_recovery_init(&mdt->mdt_lut, tgt_request_handle);
4903         set_bit(MDT_FL_CFGLOG, &mdt->mdt_state);
4904         LASSERT(obd->obd_no_conn);
4905         spin_lock(&obd->obd_dev_lock);
4906         obd->obd_no_conn = 0;
4907         spin_unlock(&obd->obd_dev_lock);
4908
4909         if (obd->obd_recovering == 0)
4910                 mdt_postrecov(env, mdt);
4911
4912         RETURN(rc);
4913 }
4914
4915 const struct lu_device_operations mdt_lu_ops = {
4916         .ldo_object_alloc   = mdt_object_alloc,
4917         .ldo_process_config = mdt_process_config,
4918         .ldo_prepare        = mdt_prepare,
4919 };
4920
4921 static const struct lu_object_operations mdt_obj_ops = {
4922         .loo_object_init    = mdt_object_init,
4923         .loo_object_free    = mdt_object_free,
4924         .loo_object_print   = mdt_object_print
4925 };
4926
4927 static int mdt_obd_set_info_async(const struct lu_env *env,
4928                                   struct obd_export *exp,
4929                                   __u32 keylen, void *key,
4930                                   __u32 vallen, void *val,
4931                                   struct ptlrpc_request_set *set)
4932 {
4933         int rc;
4934
4935         ENTRY;
4936
4937         if (KEY_IS(KEY_SPTLRPC_CONF)) {
4938                 rc = tgt_adapt_sptlrpc_conf(class_exp2tgt(exp), 0);
4939                 RETURN(rc);
4940         }
4941
4942         RETURN(0);
4943 }
4944
4945 /**
4946  * Match client and server connection feature flags.
4947  *
4948  * Compute the compatibility flags for a connection request based on
4949  * features mutually supported by client and server.
4950  *
4951  * The obd_export::exp_connect_data.ocd_connect_flags field in \a exp
4952  * must not be updated here, otherwise a partially initialized value may
4953  * be exposed. After the connection request is successfully processed,
4954  * the top-level MDT connect request handler atomically updates the export
4955  * connect flags from the obd_connect_data::ocd_connect_flags field of the
4956  * reply. \see mdt_connect().
4957  *
4958  * \param exp   the obd_export associated with this client/target pair
4959  * \param mdt   the target device for the connection
4960  * \param data  stores data for this connect request
4961  *
4962  * \retval 0       success
4963  * \retval -EPROTO \a data unexpectedly has zero obd_connect_data::ocd_brw_size
4964  * \retval -EBADE  client and server feature requirements are incompatible
4965  */
4966 static int mdt_connect_internal(struct obd_export *exp,
4967                                 struct mdt_device *mdt,
4968                                 struct obd_connect_data *data)
4969 {
4970         LASSERT(data != NULL);
4971
4972         data->ocd_connect_flags &= MDT_CONNECT_SUPPORTED;
4973         data->ocd_ibits_known &= MDS_INODELOCK_FULL;
4974
4975         if (!(data->ocd_connect_flags & OBD_CONNECT_MDS_MDS) &&
4976             !(data->ocd_connect_flags & OBD_CONNECT_IBITS)) {
4977                 CWARN("%s: client %s does not support ibits lock, either "
4978                       "very old or an invalid client: flags "LPX64"\n",
4979                       mdt_obd_name(mdt), exp->exp_client_uuid.uuid,
4980                       data->ocd_connect_flags);
4981                 return -EBADE;
4982         }
4983
4984         if (!mdt->mdt_opts.mo_acl)
4985                 data->ocd_connect_flags &= ~OBD_CONNECT_ACL;
4986
4987         if (!mdt->mdt_opts.mo_user_xattr)
4988                 data->ocd_connect_flags &= ~OBD_CONNECT_XATTR;
4989
4990         if (!mdt->mdt_som_conf)
4991                 data->ocd_connect_flags &= ~OBD_CONNECT_SOM;
4992
4993         if (data->ocd_connect_flags & OBD_CONNECT_BRW_SIZE) {
4994                 data->ocd_brw_size = min(data->ocd_brw_size,
4995                                          (__u32)MD_MAX_BRW_SIZE);
4996                 if (data->ocd_brw_size == 0) {
4997                         CERROR("%s: cli %s/%p ocd_connect_flags: "LPX64
4998                                " ocd_version: %x ocd_grant: %d "
4999                                "ocd_index: %u ocd_brw_size is "
5000                                "unexpectedly zero, network data "
5001                                "corruption? Refusing connection of this"
5002                                " client\n",
5003                                mdt_obd_name(mdt),
5004                                exp->exp_client_uuid.uuid,
5005                                exp, data->ocd_connect_flags, data->ocd_version,
5006                                data->ocd_grant, data->ocd_index);
5007                         return -EPROTO;
5008                 }
5009         }
5010
5011         /* NB: Disregard the rule against updating
5012          * exp_connect_data.ocd_connect_flags in this case, since
5013          * tgt_client_new() needs to know if this is a lightweight
5014          * connection, and it is safe to expose this flag before
5015          * connection processing completes. */
5016         if (data->ocd_connect_flags & OBD_CONNECT_LIGHTWEIGHT) {
5017                 spin_lock(&exp->exp_lock);
5018                 *exp_connect_flags_ptr(exp) |= OBD_CONNECT_LIGHTWEIGHT;
5019                 spin_unlock(&exp->exp_lock);
5020         }
5021
5022         data->ocd_version = LUSTRE_VERSION_CODE;
5023
5024         if ((data->ocd_connect_flags & OBD_CONNECT_FID) == 0) {
5025                 CWARN("%s: MDS requires FID support, but client not\n",
5026                       mdt_obd_name(mdt));
5027                 return -EBADE;
5028         }
5029
5030         if (mdt->mdt_som_conf &&
5031             !(data->ocd_connect_flags & (OBD_CONNECT_LIGHTWEIGHT |
5032                                          OBD_CONNECT_MDS_MDS |
5033                                          OBD_CONNECT_SOM))) {
5034                 CWARN("%s: MDS has SOM enabled, but client does not support "
5035                       "it\n", mdt_obd_name(mdt));
5036                 return -EBADE;
5037         }
5038
5039         if (OCD_HAS_FLAG(data, PINGLESS)) {
5040                 if (ptlrpc_pinger_suppress_pings()) {
5041                         spin_lock(&exp->exp_obd->obd_dev_lock);
5042                         list_del_init(&exp->exp_obd_chain_timed);
5043                         spin_unlock(&exp->exp_obd->obd_dev_lock);
5044                 } else {
5045                         data->ocd_connect_flags &= ~OBD_CONNECT_PINGLESS;
5046                 }
5047         }
5048
5049         data->ocd_max_easize = mdt->mdt_max_ea_size;
5050
5051         return 0;
5052 }
5053
5054 static int mdt_ctxt_add_dirty_flag(struct lu_env *env,
5055                                    struct mdt_thread_info *info,
5056                                    struct mdt_file_data *mfd)
5057 {
5058         struct lu_context ses;
5059         int rc;
5060         ENTRY;
5061
5062         rc = lu_context_init(&ses, LCT_SERVER_SESSION);
5063         if (rc)
5064                 RETURN(rc);
5065
5066         env->le_ses = &ses;
5067         lu_context_enter(&ses);
5068
5069         mdt_ucred(info)->uc_valid = UCRED_OLD;
5070         rc = mdt_add_dirty_flag(info, mfd->mfd_object, &info->mti_attr);
5071
5072         lu_context_exit(&ses);
5073         lu_context_fini(&ses);
5074         env->le_ses = NULL;
5075
5076         RETURN(rc);
5077 }
5078
5079 static int mdt_export_cleanup(struct obd_export *exp)
5080 {
5081         struct list_head         closing_list;
5082         struct mdt_export_data  *med = &exp->exp_mdt_data;
5083         struct obd_device       *obd = exp->exp_obd;
5084         struct mdt_device       *mdt;
5085         struct mdt_thread_info  *info;
5086         struct lu_env            env;
5087         struct mdt_file_data    *mfd, *n;
5088         int rc = 0;
5089         ENTRY;
5090
5091         INIT_LIST_HEAD(&closing_list);
5092         spin_lock(&med->med_open_lock);
5093         while (!list_empty(&med->med_open_head)) {
5094                 struct list_head *tmp = med->med_open_head.next;
5095                 mfd = list_entry(tmp, struct mdt_file_data, mfd_list);
5096
5097                 /* Remove mfd handle so it can't be found again.
5098                  * We are consuming the mfd_list reference here. */
5099                 class_handle_unhash(&mfd->mfd_handle);
5100                 list_move_tail(&mfd->mfd_list, &closing_list);
5101         }
5102         spin_unlock(&med->med_open_lock);
5103         mdt = mdt_dev(obd->obd_lu_dev);
5104         LASSERT(mdt != NULL);
5105
5106         rc = lu_env_init(&env, LCT_MD_THREAD);
5107         if (rc)
5108                 RETURN(rc);
5109
5110         info = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
5111         LASSERT(info != NULL);
5112         memset(info, 0, sizeof *info);
5113         info->mti_env = &env;
5114         info->mti_mdt = mdt;
5115         info->mti_exp = exp;
5116
5117         if (!list_empty(&closing_list)) {
5118                 struct md_attr *ma = &info->mti_attr;
5119
5120                 /* Close any open files (which may also cause orphan
5121                  * unlinking). */
5122                 list_for_each_entry_safe(mfd, n, &closing_list, mfd_list) {
5123                         list_del_init(&mfd->mfd_list);
5124                         ma->ma_need = ma->ma_valid = 0;
5125
5126                         /* This file is being closed due to an eviction, it
5127                          * could have been modified and now dirty regarding to
5128                          * HSM archive, check this!
5129                          * The logic here is to mark a file dirty if there's a
5130                          * chance it was dirtied before the client was evicted,
5131                          * so that we don't have to wait for a release attempt
5132                          * before finding out the file was actually dirty and
5133                          * fail the release. Aggressively marking it dirty here
5134                          * will cause the policy engine to attempt to
5135                          * re-archive it; when rearchiving, we can compare the
5136                          * current version to the HSM data_version and make the
5137                          * archive request into a noop if it's not actually
5138                          * dirty.
5139                          */
5140                         if (mfd->mfd_mode & (FMODE_WRITE|MDS_FMODE_TRUNC))
5141                                 rc = mdt_ctxt_add_dirty_flag(&env, info, mfd);
5142
5143                         /* Don't unlink orphan on failover umount, LU-184 */
5144                         if (exp->exp_flags & OBD_OPT_FAILOVER) {
5145                                 ma->ma_valid = MA_FLAGS;
5146                                 ma->ma_attr_flags |= MDS_KEEP_ORPHAN;
5147                         }
5148                         mdt_mfd_close(info, mfd);
5149                 }
5150         }
5151         info->mti_mdt = NULL;
5152         /* cleanup client slot early */
5153         /* Do not erase record for recoverable client. */
5154         if (!(exp->exp_flags & OBD_OPT_FAILOVER) || exp->exp_failed)
5155                 tgt_client_del(&env, exp);
5156         lu_env_fini(&env);
5157
5158         RETURN(rc);
5159 }
5160
5161 static int mdt_obd_disconnect(struct obd_export *exp)
5162 {
5163         int rc;
5164         ENTRY;
5165
5166         LASSERT(exp);
5167         class_export_get(exp);
5168
5169         nodemap_del_member(exp);
5170         rc = server_disconnect_export(exp);
5171         if (rc != 0)
5172                 CDEBUG(D_IOCTL, "server disconnect error: rc = %d\n", rc);
5173
5174         rc = mdt_export_cleanup(exp);
5175         class_export_put(exp);
5176         RETURN(rc);
5177 }
5178
5179 /* mds_connect copy */
5180 static int mdt_obd_connect(const struct lu_env *env,
5181                            struct obd_export **exp, struct obd_device *obd,
5182                            struct obd_uuid *cluuid,
5183                            struct obd_connect_data *data,
5184                            void *localdata)
5185 {
5186         struct obd_export       *lexp;
5187         struct lustre_handle    conn = { 0 };
5188         struct mdt_device       *mdt;
5189         int                      rc;
5190         lnet_nid_t              *client_nid = localdata;
5191         ENTRY;
5192
5193         LASSERT(env != NULL);
5194         if (!exp || !obd || !cluuid)
5195                 RETURN(-EINVAL);
5196
5197         mdt = mdt_dev(obd->obd_lu_dev);
5198
5199         /*
5200          * first, check whether the stack is ready to handle requests
5201          * XXX: probably not very appropriate method is used now
5202          *      at some point we should find a better one
5203          */
5204         if (!test_bit(MDT_FL_SYNCED, &mdt->mdt_state) && data != NULL &&
5205             !(data->ocd_connect_flags & OBD_CONNECT_LIGHTWEIGHT)) {
5206                 rc = obd_get_info(env, mdt->mdt_child_exp,
5207                                   sizeof(KEY_OSP_CONNECTED),
5208                                   KEY_OSP_CONNECTED, NULL, NULL, NULL);
5209                 if (rc)
5210                         RETURN(-EAGAIN);
5211                 set_bit(MDT_FL_SYNCED, &mdt->mdt_state);
5212         }
5213
5214         rc = class_connect(&conn, obd, cluuid);
5215         if (rc)
5216                 RETURN(rc);
5217
5218         lexp = class_conn2export(&conn);
5219         LASSERT(lexp != NULL);
5220
5221         rc = mdt_connect_internal(lexp, mdt, data);
5222         if (rc == 0) {
5223                 struct lsd_client_data *lcd = lexp->exp_target_data.ted_lcd;
5224
5225                 LASSERT(lcd);
5226                 memcpy(lcd->lcd_uuid, cluuid, sizeof lcd->lcd_uuid);
5227                 rc = tgt_client_new(env, lexp);
5228                 if (rc == 0) {
5229                         rc = nodemap_add_member(*client_nid, lexp);
5230                         if (rc != 0 && rc != -EEXIST)
5231                                 goto out;
5232
5233                         mdt_export_stats_init(obd, lexp, localdata);
5234                 }
5235
5236                 /* For phase I, sync for cross-ref operation. */
5237                 spin_lock(&lexp->exp_lock);
5238                 lexp->exp_keep_sync = 1;
5239                 spin_unlock(&lexp->exp_lock);
5240         }
5241 out:
5242         if (rc != 0) {
5243                 class_disconnect(lexp);
5244                 *exp = NULL;
5245         } else {
5246                 *exp = lexp;
5247         }
5248
5249         RETURN(rc);
5250 }
5251
5252 static int mdt_obd_reconnect(const struct lu_env *env,
5253                              struct obd_export *exp, struct obd_device *obd,
5254                              struct obd_uuid *cluuid,
5255                              struct obd_connect_data *data,
5256                              void *localdata)
5257 {
5258         lnet_nid_t             *client_nid = localdata;
5259         int                     rc;
5260         ENTRY;
5261
5262         if (exp == NULL || obd == NULL || cluuid == NULL)
5263                 RETURN(-EINVAL);
5264
5265         rc = mdt_connect_internal(exp, mdt_dev(obd->obd_lu_dev), data);
5266         if (rc == 0) {
5267                 rc = nodemap_add_member(*client_nid, exp);
5268                 if (rc == 0 || rc == -EEXIST)
5269                         mdt_export_stats_init(obd, exp, localdata);
5270         }
5271
5272         RETURN(rc);
5273 }
5274
5275 /* FIXME: Can we avoid using these two interfaces? */
5276 static int mdt_init_export(struct obd_export *exp)
5277 {
5278         struct mdt_export_data *med = &exp->exp_mdt_data;
5279         int                     rc;
5280         ENTRY;
5281
5282         INIT_LIST_HEAD(&med->med_open_head);
5283         spin_lock_init(&med->med_open_lock);
5284         mutex_init(&med->med_idmap_mutex);
5285         med->med_idmap = NULL;
5286         spin_lock(&exp->exp_lock);
5287         exp->exp_connecting = 1;
5288         spin_unlock(&exp->exp_lock);
5289
5290         /* self-export doesn't need client data and ldlm initialization */
5291         if (unlikely(obd_uuid_equals(&exp->exp_obd->obd_uuid,
5292                                      &exp->exp_client_uuid)))
5293                 RETURN(0);
5294
5295         rc = tgt_client_alloc(exp);
5296         if (rc)
5297                 GOTO(err, rc);
5298
5299         rc = ldlm_init_export(exp);
5300         if (rc)
5301                 GOTO(err_free, rc);
5302
5303         RETURN(rc);
5304
5305 err_free:
5306         tgt_client_free(exp);
5307 err:
5308         CERROR("%s: Failed to initialize export: rc = %d\n",
5309                exp->exp_obd->obd_name, rc);
5310         return rc;
5311 }
5312
5313 static int mdt_destroy_export(struct obd_export *exp)
5314 {
5315         ENTRY;
5316
5317         if (exp_connect_rmtclient(exp))
5318                 mdt_cleanup_idmap(&exp->exp_mdt_data);
5319
5320         target_destroy_export(exp);
5321         /* destroy can be called from failed obd_setup, so
5322          * checking uuid is safer than obd_self_export */
5323         if (unlikely(obd_uuid_equals(&exp->exp_obd->obd_uuid,
5324                                      &exp->exp_client_uuid)))
5325                 RETURN(0);
5326
5327         ldlm_destroy_export(exp);
5328         tgt_client_free(exp);
5329
5330         LASSERT(list_empty(&exp->exp_outstanding_replies));
5331         LASSERT(list_empty(&exp->exp_mdt_data.med_open_head));
5332
5333         RETURN(0);
5334 }
5335
5336 int mdt_links_read(struct mdt_thread_info *info, struct mdt_object *mdt_obj,
5337                    struct linkea_data *ldata)
5338 {
5339         int rc;
5340
5341         LASSERT(ldata->ld_buf->lb_buf != NULL);
5342
5343         if (!mdt_object_exists(mdt_obj))
5344                 return -ENODATA;
5345
5346         rc = mo_xattr_get(info->mti_env, mdt_object_child(mdt_obj),
5347                           ldata->ld_buf, XATTR_NAME_LINK);
5348         if (rc == -ERANGE) {
5349                 /* Buf was too small, figure out what we need. */
5350                 lu_buf_free(ldata->ld_buf);
5351                 rc = mo_xattr_get(info->mti_env, mdt_object_child(mdt_obj),
5352                                   ldata->ld_buf, XATTR_NAME_LINK);
5353                 if (rc < 0)
5354                         return rc;
5355                 ldata->ld_buf = lu_buf_check_and_alloc(ldata->ld_buf, rc);
5356                 if (ldata->ld_buf->lb_buf == NULL)
5357                         return -ENOMEM;
5358                 rc = mo_xattr_get(info->mti_env, mdt_object_child(mdt_obj),
5359                                   ldata->ld_buf, XATTR_NAME_LINK);
5360         }
5361         if (rc < 0)
5362                 return rc;
5363
5364         return linkea_init(ldata);
5365 }
5366
5367 /**
5368  * Given an MDT object, try to look up the full path to the object.
5369  * Part of the MDT layer implementation of lfs fid2path.
5370  *
5371  * \param[in]     info  Per-thread common data shared by MDT level handlers.
5372  * \param[in]     obj   Object to do path lookup of
5373  * \param[in,out] fp    User-provided struct to store path information
5374  *
5375  * \retval 0 Lookup successful, path information stored in fp
5376  * \retval -EAGAIN Lookup failed, usually because object is being moved
5377  * \retval negative errno if there was a problem
5378  */
5379 static int mdt_path_current(struct mdt_thread_info *info,
5380                             struct mdt_object *obj,
5381                             struct getinfo_fid2path *fp)
5382 {
5383         struct mdt_device       *mdt = info->mti_mdt;
5384         struct mdt_object       *mdt_obj;
5385         struct link_ea_header   *leh;
5386         struct link_ea_entry    *lee;
5387         struct lu_name          *tmpname = &info->mti_name;
5388         struct lu_fid           *tmpfid = &info->mti_tmp_fid1;
5389         struct lu_buf           *buf = &info->mti_big_buf;
5390         char                    *ptr;
5391         int                     reclen;
5392         struct linkea_data      ldata = { NULL };
5393         int                     rc = 0;
5394         bool                    first = true;
5395         ENTRY;
5396
5397         /* temp buffer for path element, the buffer will be finally freed
5398          * in mdt_thread_info_fini */
5399         buf = lu_buf_check_and_alloc(buf, PATH_MAX);
5400         if (buf->lb_buf == NULL)
5401                 RETURN(-ENOMEM);
5402
5403         ldata.ld_buf = buf;
5404         ptr = fp->gf_path + fp->gf_pathlen - 1;
5405         *ptr = 0;
5406         --ptr;
5407         *tmpfid = fp->gf_fid = *mdt_object_fid(obj);
5408
5409         /* root FID only exists on MDT0, and fid2path should also ends at MDT0,
5410          * so checking root_fid can only happen on MDT0. */
5411         while (!lu_fid_eq(&mdt->mdt_md_root_fid, &fp->gf_fid)) {
5412                 struct lu_buf           lmv_buf;
5413
5414                 mdt_obj = mdt_object_find(info->mti_env, mdt, tmpfid);
5415                 if (IS_ERR(mdt_obj))
5416                         GOTO(out, rc = PTR_ERR(mdt_obj));
5417
5418                 if (!mdt_object_exists(mdt_obj)) {
5419                         mdt_object_put(info->mti_env, mdt_obj);
5420                         GOTO(out, rc = -ENOENT);
5421                 }
5422
5423                 if (mdt_object_remote(mdt_obj)) {
5424                         mdt_object_put(info->mti_env, mdt_obj);
5425                         GOTO(remote_out, rc = -EREMOTE);
5426                 }
5427
5428                 rc = mdt_links_read(info, mdt_obj, &ldata);
5429                 if (rc != 0) {
5430                         mdt_object_put(info->mti_env, mdt_obj);
5431                         GOTO(out, rc);
5432                 }
5433
5434                 leh = buf->lb_buf;
5435                 lee = (struct link_ea_entry *)(leh + 1); /* link #0 */
5436                 linkea_entry_unpack(lee, &reclen, tmpname, tmpfid);
5437                 /* If set, use link #linkno for path lookup, otherwise use
5438                    link #0.  Only do this for the final path element. */
5439                 if (first && fp->gf_linkno < leh->leh_reccount) {
5440                         int count;
5441                         for (count = 0; count < fp->gf_linkno; count++) {
5442                                 lee = (struct link_ea_entry *)
5443                                      ((char *)lee + reclen);
5444                                 linkea_entry_unpack(lee, &reclen, tmpname,
5445                                                     tmpfid);
5446                         }
5447                         if (fp->gf_linkno < leh->leh_reccount - 1)
5448                                 /* indicate to user there are more links */
5449                                 fp->gf_linkno++;
5450                 }
5451
5452                 lmv_buf.lb_buf = info->mti_xattr_buf;
5453                 lmv_buf.lb_len = sizeof(info->mti_xattr_buf);
5454                 /* Check if it is slave stripes */
5455                 rc = mo_xattr_get(info->mti_env, mdt_object_child(mdt_obj),
5456                                   &lmv_buf, XATTR_NAME_LMV);
5457                 mdt_object_put(info->mti_env, mdt_obj);
5458                 if (rc > 0) {
5459                         union lmv_mds_md *lmm = lmv_buf.lb_buf;
5460
5461                         /* For slave stripes, get its master */
5462                         if (le32_to_cpu(lmm->lmv_magic) == LMV_MAGIC_STRIPE) {
5463                                 fp->gf_fid = *tmpfid;
5464                                 continue;
5465                         }
5466                 } else if (rc < 0 && rc != -ENODATA) {
5467                         GOTO(out, rc);
5468                 }
5469
5470                 rc = 0;
5471
5472                 /* Pack the name in the end of the buffer */
5473                 ptr -= tmpname->ln_namelen;
5474                 if (ptr - 1 <= fp->gf_path)
5475                         GOTO(out, rc = -EOVERFLOW);
5476                 strncpy(ptr, tmpname->ln_name, tmpname->ln_namelen);
5477                 *(--ptr) = '/';
5478
5479                 /* keep the last resolved fid to the client, so the
5480                  * client will build the left path on another MDT for
5481                  * remote object */
5482                 fp->gf_fid = *tmpfid;
5483
5484                 first = false;
5485         }
5486
5487 remote_out:
5488         ptr++; /* skip leading / */
5489         memmove(fp->gf_path, ptr, fp->gf_path + fp->gf_pathlen - ptr);
5490
5491 out:
5492         RETURN(rc);
5493 }
5494
5495 /**
5496  * Given an MDT object, use mdt_path_current to get the path.
5497  * Essentially a wrapper to retry mdt_path_current a set number of times
5498  * if -EAGAIN is returned (usually because an object is being moved).
5499  *
5500  * Part of the MDT layer implementation of lfs fid2path.
5501  *
5502  * \param[in]     info  Per-thread common data shared by mdt level handlers.
5503  * \param[in]     obj   Object to do path lookup of
5504  * \param[in,out] fp    User-provided struct for arguments and to store path
5505  *                      information
5506  *
5507  * \retval 0 Lookup successful, path information stored in fp
5508  * \retval negative errno if there was a problem
5509  */
5510 static int mdt_path(struct mdt_thread_info *info, struct mdt_object *obj,
5511                     struct getinfo_fid2path *fp)
5512 {
5513         struct mdt_device       *mdt = info->mti_mdt;
5514         int                     tries = 3;
5515         int                     rc = -EAGAIN;
5516         ENTRY;
5517
5518         if (fp->gf_pathlen < 3)
5519                 RETURN(-EOVERFLOW);
5520
5521         if (lu_fid_eq(&mdt->mdt_md_root_fid, mdt_object_fid(obj))) {
5522                 fp->gf_path[0] = '\0';
5523                 RETURN(0);
5524         }
5525
5526         /* Retry multiple times in case file is being moved */
5527         while (tries-- && rc == -EAGAIN)
5528                 rc = mdt_path_current(info, obj, fp);
5529
5530         RETURN(rc);
5531 }
5532
5533 /**
5534  * Get the full path of the provided FID, as of changelog record recno.
5535  *
5536  * This checks sanity and looks up object for user provided FID
5537  * before calling the actual path lookup code.
5538  *
5539  * Part of the MDT layer implementation of lfs fid2path.
5540  *
5541  * \param[in]     info  Per-thread common data shared by mdt level handlers.
5542  * \param[in,out] fp    User-provided struct for arguments and to store path
5543  *                      information
5544  *
5545  * \retval 0 Lookup successful, path information and recno stored in fp
5546  * \retval -ENOENT, object does not exist
5547  * \retval negative errno if there was a problem
5548  */
5549 static int mdt_fid2path(struct mdt_thread_info *info,
5550                         struct getinfo_fid2path *fp)
5551 {
5552         struct mdt_device *mdt = info->mti_mdt;
5553         struct mdt_object *obj;
5554         int    rc;
5555         ENTRY;
5556
5557         CDEBUG(D_IOCTL, "path get "DFID" from "LPU64" #%d\n",
5558                 PFID(&fp->gf_fid), fp->gf_recno, fp->gf_linkno);
5559
5560         if (!fid_is_sane(&fp->gf_fid))
5561                 RETURN(-EINVAL);
5562
5563         if (!fid_is_namespace_visible(&fp->gf_fid)) {
5564                 CWARN("%s: "DFID" is invalid, sequence should be "
5565                       ">= "LPX64"\n", mdt_obd_name(mdt),
5566                       PFID(&fp->gf_fid), (__u64)FID_SEQ_NORMAL);
5567                 RETURN(-EINVAL);
5568         }
5569
5570         obj = mdt_object_find(info->mti_env, mdt, &fp->gf_fid);
5571         if (obj == NULL || IS_ERR(obj)) {
5572                 CDEBUG(D_IOCTL, "no object "DFID": %ld\n", PFID(&fp->gf_fid),
5573                        PTR_ERR(obj));
5574                 RETURN(-EINVAL);
5575         }
5576
5577         if (mdt_object_remote(obj))
5578                 rc = -EREMOTE;
5579         else if (!mdt_object_exists(obj))
5580                 rc = -ENOENT;
5581         else
5582                 rc = 0;
5583
5584         if (rc < 0) {
5585                 mdt_object_put(info->mti_env, obj);
5586                 CDEBUG(D_IOCTL, "nonlocal object "DFID": rc = %d\n",
5587                        PFID(&fp->gf_fid), rc);
5588                 RETURN(rc);
5589         }
5590
5591         rc = mdt_path(info, obj, fp);
5592
5593         CDEBUG(D_INFO, "fid "DFID", path %s recno "LPX64" linkno %u\n",
5594                PFID(&fp->gf_fid), fp->gf_path, fp->gf_recno, fp->gf_linkno);
5595
5596         mdt_object_put(info->mti_env, obj);
5597
5598         RETURN(rc);
5599 }
5600
5601 static int mdt_rpc_fid2path(struct mdt_thread_info *info, void *key,
5602                             void *val, int vallen)
5603 {
5604         struct getinfo_fid2path *fpout, *fpin;
5605         int rc = 0;
5606
5607         fpin = key + cfs_size_round(sizeof(KEY_FID2PATH));
5608         fpout = val;
5609
5610         if (ptlrpc_req_need_swab(info->mti_pill->rc_req))
5611                 lustre_swab_fid2path(fpin);
5612
5613         memcpy(fpout, fpin, sizeof(*fpin));
5614         if (fpout->gf_pathlen != vallen - sizeof(*fpin))
5615                 RETURN(-EINVAL);
5616
5617         rc = mdt_fid2path(info, fpout);
5618         RETURN(rc);
5619 }
5620
5621 int mdt_get_info(struct tgt_session_info *tsi)
5622 {
5623         char    *key;
5624         int      keylen;
5625         __u32   *vallen;
5626         void    *valout;
5627         int      rc;
5628
5629         ENTRY;
5630
5631         key = req_capsule_client_get(tsi->tsi_pill, &RMF_GETINFO_KEY);
5632         if (key == NULL) {
5633                 CDEBUG(D_IOCTL, "No GETINFO key\n");
5634                 RETURN(err_serious(-EFAULT));
5635         }
5636         keylen = req_capsule_get_size(tsi->tsi_pill, &RMF_GETINFO_KEY,
5637                                       RCL_CLIENT);
5638
5639         vallen = req_capsule_client_get(tsi->tsi_pill, &RMF_GETINFO_VALLEN);
5640         if (vallen == NULL) {
5641                 CDEBUG(D_IOCTL, "%s: cannot get RMF_GETINFO_VALLEN buffer\n",
5642                                 tgt_name(tsi->tsi_tgt));
5643                 RETURN(err_serious(-EFAULT));
5644         }
5645
5646         req_capsule_set_size(tsi->tsi_pill, &RMF_GETINFO_VAL, RCL_SERVER,
5647                              *vallen);
5648         rc = req_capsule_server_pack(tsi->tsi_pill);
5649         if (rc)
5650                 RETURN(err_serious(rc));
5651
5652         valout = req_capsule_server_get(tsi->tsi_pill, &RMF_GETINFO_VAL);
5653         if (valout == NULL) {
5654                 CDEBUG(D_IOCTL, "%s: cannot get get-info RPC out buffer\n",
5655                                 tgt_name(tsi->tsi_tgt));
5656                 RETURN(err_serious(-EFAULT));
5657         }
5658
5659         if (KEY_IS(KEY_FID2PATH)) {
5660                 struct mdt_thread_info  *info = tsi2mdt_info(tsi);
5661
5662                 rc = mdt_rpc_fid2path(info, key, valout, *vallen);
5663                 mdt_thread_info_fini(info);
5664         } else {
5665                 rc = -EINVAL;
5666         }
5667         RETURN(rc);
5668 }
5669
5670 /* Pass the ioc down */
5671 static int mdt_ioc_child(struct lu_env *env, struct mdt_device *mdt,
5672                          unsigned int cmd, int len, void *data)
5673 {
5674         struct lu_context ioctl_session;
5675         struct md_device *next = mdt->mdt_child;
5676         int rc;
5677         ENTRY;
5678
5679         rc = lu_context_init(&ioctl_session, LCT_SERVER_SESSION);
5680         if (rc)
5681                 RETURN(rc);
5682         ioctl_session.lc_thread = (struct ptlrpc_thread *)current;
5683         lu_context_enter(&ioctl_session);
5684         env->le_ses = &ioctl_session;
5685
5686         LASSERT(next->md_ops->mdo_iocontrol);
5687         rc = next->md_ops->mdo_iocontrol(env, next, cmd, len, data);
5688
5689         lu_context_exit(&ioctl_session);
5690         lu_context_fini(&ioctl_session);
5691         RETURN(rc);
5692 }
5693
5694 static int mdt_ioc_version_get(struct mdt_thread_info *mti, void *karg)
5695 {
5696         struct obd_ioctl_data *data = karg;
5697         struct lu_fid *fid;
5698         __u64 version;
5699         struct mdt_object *obj;
5700         struct mdt_lock_handle  *lh;
5701         int rc;
5702         ENTRY;
5703
5704         if (data->ioc_inlbuf1 == NULL || data->ioc_inllen1 != sizeof(*fid) ||
5705             data->ioc_inlbuf2 == NULL || data->ioc_inllen2 != sizeof(version))
5706                 RETURN(-EINVAL);
5707
5708         fid = (struct lu_fid *)data->ioc_inlbuf1;
5709
5710         if (!fid_is_sane(fid))
5711                 RETURN(-EINVAL);
5712
5713         CDEBUG(D_IOCTL, "getting version for "DFID"\n", PFID(fid));
5714
5715         lh = &mti->mti_lh[MDT_LH_PARENT];
5716         mdt_lock_reg_init(lh, LCK_CR);
5717
5718         obj = mdt_object_find_lock(mti, fid, lh, MDS_INODELOCK_UPDATE);
5719         if (IS_ERR(obj))
5720                 RETURN(PTR_ERR(obj));
5721
5722         if (mdt_object_remote(obj)) {
5723                 rc = -EREMOTE;
5724                 /**
5725                  * before calling version get the correct MDS should be
5726                  * fid, this is error to find remote object here
5727                  */
5728                 CERROR("nonlocal object "DFID"\n", PFID(fid));
5729         } else if (!mdt_object_exists(obj)) {
5730                 *(__u64 *)data->ioc_inlbuf2 = ENOENT_VERSION;
5731                 rc = -ENOENT;
5732         } else {
5733                 version = dt_version_get(mti->mti_env, mdt_obj2dt(obj));
5734                *(__u64 *)data->ioc_inlbuf2 = version;
5735                 rc = 0;
5736         }
5737         mdt_object_unlock_put(mti, obj, lh, 1);
5738         RETURN(rc);
5739 }
5740
5741 /* ioctls on obd dev */
5742 static int mdt_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
5743                          void *karg, void *uarg)
5744 {
5745         struct lu_env      env;
5746         struct obd_device *obd = exp->exp_obd;
5747         struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
5748         struct dt_device  *dt = mdt->mdt_bottom;
5749         int rc;
5750
5751         ENTRY;
5752         CDEBUG(D_IOCTL, "handling ioctl cmd %#x\n", cmd);
5753         rc = lu_env_init(&env, LCT_MD_THREAD);
5754         if (rc)
5755                 RETURN(rc);
5756
5757         switch (cmd) {
5758         case OBD_IOC_SYNC:
5759                 rc = mdt_device_sync(&env, mdt);
5760                 break;
5761         case OBD_IOC_SET_READONLY:
5762                 rc = dt->dd_ops->dt_ro(&env, dt);
5763                 break;
5764         case OBD_IOC_ABORT_RECOVERY:
5765                 CERROR("%s: Aborting recovery for device\n", mdt_obd_name(mdt));
5766                 target_stop_recovery_thread(obd);
5767                 rc = 0;
5768                 break;
5769         case OBD_IOC_CHANGELOG_REG:
5770         case OBD_IOC_CHANGELOG_DEREG:
5771         case OBD_IOC_CHANGELOG_CLEAR:
5772                 rc = mdt_ioc_child(&env, mdt, cmd, len, karg);
5773                 break;
5774         case OBD_IOC_START_LFSCK: {
5775                 struct md_device *next = mdt->mdt_child;
5776                 struct obd_ioctl_data *data = karg;
5777                 struct lfsck_start_param lsp;
5778
5779                 if (unlikely(data == NULL)) {
5780                         rc = -EINVAL;
5781                         break;
5782                 }
5783
5784                 lsp.lsp_start = (struct lfsck_start *)(data->ioc_inlbuf1);
5785                 lsp.lsp_index_valid = 0;
5786                 rc = next->md_ops->mdo_iocontrol(&env, next, cmd, 0, &lsp);
5787                 break;
5788         }
5789         case OBD_IOC_STOP_LFSCK: {
5790                 struct md_device        *next = mdt->mdt_child;
5791                 struct obd_ioctl_data   *data = karg;
5792                 struct lfsck_stop        stop;
5793
5794                 stop.ls_status = LS_STOPPED;
5795                 /* Old lfsck utils may pass NULL @stop. */
5796                 if (data->ioc_inlbuf1 == NULL)
5797                         stop.ls_flags = 0;
5798                 else
5799                         stop.ls_flags =
5800                         ((struct lfsck_stop *)(data->ioc_inlbuf1))->ls_flags;
5801
5802                 rc = next->md_ops->mdo_iocontrol(&env, next, cmd, 0, &stop);
5803                 break;
5804         }
5805         case OBD_IOC_GET_OBJ_VERSION: {
5806                 struct mdt_thread_info *mti;
5807                 mti = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
5808                 memset(mti, 0, sizeof *mti);
5809                 mti->mti_env = &env;
5810                 mti->mti_mdt = mdt;
5811                 mti->mti_exp = exp;
5812
5813                 rc = mdt_ioc_version_get(mti, karg);
5814                 break;
5815         }
5816         case OBD_IOC_CATLOGLIST: {
5817                 struct mdt_thread_info *mti;
5818
5819                 mti = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
5820                 lu_local_obj_fid(&mti->mti_tmp_fid1, LLOG_CATALOGS_OID);
5821                 rc = llog_catalog_list(&env, mdt->mdt_bottom, 0, karg,
5822                                        &mti->mti_tmp_fid1);
5823                 break;
5824          }
5825         default:
5826                 rc = -EOPNOTSUPP;
5827                 CERROR("%s: Not supported cmd = %d, rc = %d\n",
5828                         mdt_obd_name(mdt), cmd, rc);
5829         }
5830
5831         lu_env_fini(&env);
5832         RETURN(rc);
5833 }
5834
5835 static int mdt_postrecov(const struct lu_env *env, struct mdt_device *mdt)
5836 {
5837         struct lu_device *ld = md2lu_dev(mdt->mdt_child);
5838         struct lfsck_start_param lsp;
5839         int rc;
5840         ENTRY;
5841
5842         lsp.lsp_start = NULL;
5843         lsp.lsp_index_valid = 0;
5844         rc = mdt->mdt_child->md_ops->mdo_iocontrol(env, mdt->mdt_child,
5845                                                    OBD_IOC_START_LFSCK,
5846                                                    0, &lsp);
5847         if (rc != 0 && rc != -EALREADY)
5848                 CWARN("%s: auto trigger paused LFSCK failed: rc = %d\n",
5849                       mdt_obd_name(mdt), rc);
5850
5851         rc = ld->ld_ops->ldo_recovery_complete(env, ld);
5852         RETURN(rc);
5853 }
5854
5855 static int mdt_obd_postrecov(struct obd_device *obd)
5856 {
5857         struct lu_env env;
5858         int rc;
5859
5860         rc = lu_env_init(&env, LCT_MD_THREAD);
5861         if (rc)
5862                 RETURN(rc);
5863         rc = mdt_postrecov(&env, mdt_dev(obd->obd_lu_dev));
5864         lu_env_fini(&env);
5865         return rc;
5866 }
5867
5868 static struct obd_ops mdt_obd_device_ops = {
5869         .o_owner          = THIS_MODULE,
5870         .o_set_info_async = mdt_obd_set_info_async,
5871         .o_connect        = mdt_obd_connect,
5872         .o_reconnect      = mdt_obd_reconnect,
5873         .o_disconnect     = mdt_obd_disconnect,
5874         .o_init_export    = mdt_init_export,
5875         .o_destroy_export = mdt_destroy_export,
5876         .o_iocontrol      = mdt_iocontrol,
5877         .o_postrecov      = mdt_obd_postrecov,
5878 };
5879
5880 static struct lu_device* mdt_device_fini(const struct lu_env *env,
5881                                          struct lu_device *d)
5882 {
5883         struct mdt_device *m = mdt_dev(d);
5884         ENTRY;
5885
5886         mdt_fini(env, m);
5887         RETURN(NULL);
5888 }
5889
5890 static struct lu_device *mdt_device_free(const struct lu_env *env,
5891                                          struct lu_device *d)
5892 {
5893         struct mdt_device *m = mdt_dev(d);
5894         ENTRY;
5895
5896         lu_device_fini(&m->mdt_lu_dev);
5897         OBD_FREE_PTR(m);
5898
5899         RETURN(NULL);
5900 }
5901
5902 static struct lu_device *mdt_device_alloc(const struct lu_env *env,
5903                                           struct lu_device_type *t,
5904                                           struct lustre_cfg *cfg)
5905 {
5906         struct lu_device  *l;
5907         struct mdt_device *m;
5908
5909         OBD_ALLOC_PTR(m);
5910         if (m != NULL) {
5911                 int rc;
5912
5913                 l = &m->mdt_lu_dev;
5914                 rc = mdt_init0(env, m, t, cfg);
5915                 if (rc != 0) {
5916                         mdt_device_free(env, l);
5917                         l = ERR_PTR(rc);
5918                         return l;
5919                 }
5920         } else
5921                 l = ERR_PTR(-ENOMEM);
5922         return l;
5923 }
5924
5925 /* context key constructor/destructor: mdt_key_init, mdt_key_fini */
5926 LU_KEY_INIT(mdt, struct mdt_thread_info);
5927
5928 static void mdt_key_fini(const struct lu_context *ctx,
5929                          struct lu_context_key *key, void* data)
5930 {
5931         struct mdt_thread_info *info = data;
5932
5933         if (info->mti_big_lmm) {
5934                 OBD_FREE_LARGE(info->mti_big_lmm, info->mti_big_lmmsize);
5935                 info->mti_big_lmm = NULL;
5936                 info->mti_big_lmmsize = 0;
5937         }
5938         OBD_FREE_PTR(info);
5939 }
5940
5941 /* context key: mdt_thread_key */
5942 LU_CONTEXT_KEY_DEFINE(mdt, LCT_MD_THREAD);
5943
5944 struct lu_ucred *mdt_ucred(const struct mdt_thread_info *info)
5945 {
5946         return lu_ucred(info->mti_env);
5947 }
5948
5949 struct lu_ucred *mdt_ucred_check(const struct mdt_thread_info *info)
5950 {
5951         return lu_ucred_check(info->mti_env);
5952 }
5953
5954 /**
5955  * Enable/disable COS (Commit On Sharing).
5956  *
5957  * Set/Clear the COS flag in mdt options.
5958  *
5959  * \param mdt mdt device
5960  * \param val 0 disables COS, other values enable COS
5961  */
5962 void mdt_enable_cos(struct mdt_device *mdt, int val)
5963 {
5964         struct lu_env env;
5965         int rc;
5966
5967         mdt->mdt_opts.mo_cos = !!val;
5968         rc = lu_env_init(&env, LCT_LOCAL);
5969         if (unlikely(rc != 0)) {
5970                 CWARN("%s: lu_env initialization failed, cannot "
5971                       "sync: rc = %d\n", mdt_obd_name(mdt), rc);
5972                 return;
5973         }
5974         mdt_device_sync(&env, mdt);
5975         lu_env_fini(&env);
5976 }
5977
5978 /**
5979  * Check COS (Commit On Sharing) status.
5980  *
5981  * Return COS flag status.
5982  *
5983  * \param mdt mdt device
5984  */
5985 int mdt_cos_is_enabled(struct mdt_device *mdt)
5986 {
5987         return mdt->mdt_opts.mo_cos != 0;
5988 }
5989
5990 static struct lu_device_type_operations mdt_device_type_ops = {
5991         .ldto_device_alloc = mdt_device_alloc,
5992         .ldto_device_free  = mdt_device_free,
5993         .ldto_device_fini  = mdt_device_fini
5994 };
5995
5996 static struct lu_device_type mdt_device_type = {
5997         .ldt_tags     = LU_DEVICE_MD,
5998         .ldt_name     = LUSTRE_MDT_NAME,
5999         .ldt_ops      = &mdt_device_type_ops,
6000         .ldt_ctx_tags = LCT_MD_THREAD
6001 };
6002
6003 static int __init mdt_mod_init(void)
6004 {
6005         int rc;
6006
6007         CLASSERT(sizeof("0x0123456789ABCDEF:0x01234567:0x01234567") ==
6008                  FID_NOBRACE_LEN + 1);
6009         CLASSERT(sizeof("[0x0123456789ABCDEF:0x01234567:0x01234567]") ==
6010                  FID_LEN + 1);
6011         rc = lu_kmem_init(mdt_caches);
6012         if (rc)
6013                 return rc;
6014
6015         rc = mds_mod_init();
6016         if (rc)
6017                 GOTO(lu_fini, rc);
6018
6019         rc = class_register_type(&mdt_obd_device_ops, NULL, true, NULL,
6020                                  LUSTRE_MDT_NAME, &mdt_device_type);
6021         if (rc)
6022                 GOTO(mds_fini, rc);
6023 lu_fini:
6024         if (rc)
6025                 lu_kmem_fini(mdt_caches);
6026 mds_fini:
6027         if (rc)
6028                 mds_mod_exit();
6029         return rc;
6030 }
6031
6032 static void __exit mdt_mod_exit(void)
6033 {
6034         class_unregister_type(LUSTRE_MDT_NAME);
6035         mds_mod_exit();
6036         lu_kmem_fini(mdt_caches);
6037 }
6038
6039 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
6040 MODULE_DESCRIPTION("Lustre Metadata Target ("LUSTRE_MDT_NAME")");
6041 MODULE_LICENSE("GPL");
6042
6043 cfs_module(mdt, LUSTRE_VERSION_STRING, mdt_mod_init, mdt_mod_exit);