Whamcloud - gitweb
LU-9771 mdt: revise layout_change() to take md_layout_change
[fs/lustre-release.git] / lustre / mdt / mdt_handler.c
index 9c69c54..c2533e4 100644 (file)
  *
  * You should have received a copy of the GNU General Public License
  * version 2 along with this program; If not, see
- * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
- *
- * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * http://www.gnu.org/licenses/gpl-2.0.html
  *
  * GPL HEADER END
  */
@@ -27,7 +23,7 @@
  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
  * Use is subject to license terms.
  *
- * Copyright (c) 2010, 2014, Intel Corporation.
+ * Copyright (c) 2010, 2016, Intel Corporation.
  */
 /*
  * This file is part of Lustre, http://www.lustre.org/
 #define DEBUG_SUBSYSTEM S_MDS
 
 #include <linux/module.h>
-/*
- * struct OBD_{ALLOC,FREE}*()
- */
-#include <obd_support.h>
-#include <lustre_ioctl.h>
-/* struct ptlrpc_request */
-#include <lustre_net.h>
-/* struct obd_export */
-#include <lustre_export.h>
-/* struct obd_device */
-#include <obd.h>
-/* lu2dt_dev() */
+#include <linux/pagemap.h>
+
 #include <dt_object.h>
-#include <lustre_mds.h>
-#include <lustre_log.h>
-#include "mdt_internal.h"
 #include <lustre_acl.h>
-#include <lustre_param.h>
-#include <lustre_quota.h>
+#include <lustre_export.h>
+#include <uapi/linux/lustre/lustre_ioctl.h>
 #include <lustre_lfsck.h>
+#include <lustre_log.h>
 #include <lustre_nodemap.h>
+#include <lustre_mds.h>
+#include <uapi/linux/lustre/lustre_param.h>
+#include <lustre_quota.h>
+#include <lustre_swab.h>
+#include <obd.h>
+#include <obd_support.h>
+#include <lustre_barrier.h>
+#include <obd_cksum.h>
+#include <llog_swab.h>
+
+#include "mdt_internal.h"
+
 
 static unsigned int max_mod_rpcs_per_client = 8;
-CFS_MODULE_PARM(max_mod_rpcs_per_client, "i", uint, 0644,
-               "maximum number of modify RPCs in flight allowed per client");
+module_param(max_mod_rpcs_per_client, uint, 0644);
+MODULE_PARM_DESC(max_mod_rpcs_per_client, "maximum number of modify RPCs in flight allowed per client");
 
 mdl_mode_t mdt_mdl_lock_modes[] = {
         [LCK_MINMODE] = MDL_MINMODE,
@@ -86,15 +82,15 @@ mdl_mode_t mdt_mdl_lock_modes[] = {
         [LCK_GROUP]   = MDL_GROUP
 };
 
-ldlm_mode_t mdt_dlm_lock_modes[] = {
-        [MDL_MINMODE] = LCK_MINMODE,
-        [MDL_EX]      = LCK_EX,
-        [MDL_PW]      = LCK_PW,
-        [MDL_PR]      = LCK_PR,
-        [MDL_CW]      = LCK_CW,
-        [MDL_CR]      = LCK_CR,
-        [MDL_NL]      = LCK_NL,
-        [MDL_GROUP]   = LCK_GROUP
+enum ldlm_mode mdt_dlm_lock_modes[] = {
+       [MDL_MINMODE]   = LCK_MINMODE,
+       [MDL_EX]        = LCK_EX,
+       [MDL_PW]        = LCK_PW,
+       [MDL_PR]        = LCK_PR,
+       [MDL_CW]        = LCK_CW,
+       [MDL_CR]        = LCK_CR,
+       [MDL_NL]        = LCK_NL,
+       [MDL_GROUP]     = LCK_GROUP
 };
 
 static struct mdt_device *mdt_dev(struct lu_device *d);
@@ -161,24 +157,25 @@ void mdt_set_disposition(struct mdt_thread_info *info,
                rep->lock_policy_res1 |= op_flag;
 }
 
-void mdt_lock_reg_init(struct mdt_lock_handle *lh, ldlm_mode_t lm)
+void mdt_lock_reg_init(struct mdt_lock_handle *lh, enum ldlm_mode lm)
 {
-        lh->mlh_pdo_hash = 0;
-        lh->mlh_reg_mode = lm;
+       lh->mlh_pdo_hash = 0;
+       lh->mlh_reg_mode = lm;
        lh->mlh_rreg_mode = lm;
-        lh->mlh_type = MDT_REG_LOCK;
+       lh->mlh_type = MDT_REG_LOCK;
 }
 
-void mdt_lock_pdo_init(struct mdt_lock_handle *lh, ldlm_mode_t lock_mode,
+void mdt_lock_pdo_init(struct mdt_lock_handle *lh, enum ldlm_mode lock_mode,
                       const struct lu_name *lname)
 {
        lh->mlh_reg_mode = lock_mode;
+       lh->mlh_pdo_mode = LCK_MINMODE;
        lh->mlh_rreg_mode = lock_mode;
        lh->mlh_type = MDT_PDO_LOCK;
 
        if (lu_name_is_valid(lname)) {
-               lh->mlh_pdo_hash = full_name_hash(lname->ln_name,
-                                                 lname->ln_namelen);
+               lh->mlh_pdo_hash = ll_full_name_hash(NULL, lname->ln_name,
+                                                    lname->ln_namelen);
                /* XXX Workaround for LU-2856
                 *
                 * Zero is a valid return value of full_name_hash, but
@@ -268,12 +265,98 @@ static void mdt_lock_pdo_mode(struct mdt_thread_info *info, struct mdt_object *o
         EXIT;
 }
 
-static int mdt_getstatus(struct tgt_session_info *tsi)
+static int mdt_lookup_fileset(struct mdt_thread_info *info, const char *fileset,
+                             struct lu_fid *fid)
+{
+       struct mdt_device *mdt = info->mti_mdt;
+       struct lu_name *lname = &info->mti_name;
+       char *name = NULL;
+       struct mdt_object *parent;
+       u32 mode;
+       int rc = 0;
+
+       LASSERT(!info->mti_cross_ref);
+
+       OBD_ALLOC(name, NAME_MAX + 1);
+       if (name == NULL)
+               return -ENOMEM;
+       lname->ln_name = name;
+
+       /*
+        * We may want to allow this to mount a completely separate
+        * fileset from the MDT in the future, but keeping it to
+        * ROOT/ only for now avoid potential security issues.
+        */
+       *fid = mdt->mdt_md_root_fid;
+
+       while (rc == 0 && fileset != NULL && *fileset != '\0') {
+               const char *s1 = fileset;
+               const char *s2;
+
+               while (*++s1 == '/')
+                       ;
+               s2 = s1;
+               while (*s2 != '/' && *s2 != '\0')
+                       s2++;
+
+               if (s2 == s1)
+                       break;
+
+               fileset = s2;
+
+               lname->ln_namelen = s2 - s1;
+               if (lname->ln_namelen > NAME_MAX) {
+                       rc = -EINVAL;
+                       break;
+               }
+
+               /* reject .. as a path component */
+               if (lname->ln_namelen == 2 &&
+                   strncmp(s1, "..", 2) == 0) {
+                       rc = -EINVAL;
+                       break;
+               }
+
+               strncpy(name, s1, lname->ln_namelen);
+               name[lname->ln_namelen] = '\0';
+
+               parent = mdt_object_find(info->mti_env, mdt, fid);
+               if (IS_ERR(parent)) {
+                       rc = PTR_ERR(parent);
+                       break;
+               }
+               /* Only got the fid of this obj by name */
+               fid_zero(fid);
+               rc = mdo_lookup(info->mti_env, mdt_object_child(parent), lname,
+                               fid, &info->mti_spec);
+               mdt_object_put(info->mti_env, parent);
+       }
+       if (!rc) {
+               parent = mdt_object_find(info->mti_env, mdt, fid);
+               if (IS_ERR(parent))
+                       rc = PTR_ERR(parent);
+               else {
+                       mode = lu_object_attr(&parent->mot_obj);
+                       mdt_object_put(info->mti_env, parent);
+                       if (!S_ISDIR(mode))
+                               rc = -ENOTDIR;
+               }
+       }
+
+       OBD_FREE(name, NAME_MAX + 1);
+
+       return rc;
+}
+
+static int mdt_get_root(struct tgt_session_info *tsi)
 {
        struct mdt_thread_info  *info = tsi2mdt_info(tsi);
        struct mdt_device       *mdt = info->mti_mdt;
        struct mdt_body         *repbody;
+       char                    *fileset = NULL, *buffer = NULL;
        int                      rc;
+       struct obd_export       *exp = info->mti_exp;
+       char                    *nodemap_fileset;
 
        ENTRY;
 
@@ -281,16 +364,50 @@ static int mdt_getstatus(struct tgt_session_info *tsi)
        if (rc)
                GOTO(out, rc = err_serious(rc));
 
-       if (OBD_FAIL_CHECK(OBD_FAIL_MDS_GETSTATUS_PACK))
+       if (OBD_FAIL_CHECK(OBD_FAIL_MDS_GET_ROOT_PACK))
                GOTO(out, rc = err_serious(-ENOMEM));
 
        repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
-       repbody->mbo_fid1 = mdt->mdt_md_root_fid;
+       if (req_capsule_get_size(info->mti_pill, &RMF_NAME, RCL_CLIENT) > 0) {
+               fileset = req_capsule_client_get(info->mti_pill, &RMF_NAME);
+               if (fileset == NULL)
+                       GOTO(out, rc = err_serious(-EFAULT));
+       }
+
+       nodemap_fileset = nodemap_get_fileset(exp->exp_target_data.ted_nodemap);
+       if (nodemap_fileset && nodemap_fileset[0]) {
+               CDEBUG(D_INFO, "nodemap fileset is %s\n", nodemap_fileset);
+               if (fileset) {
+                       /* consider fileset from client as a sub-fileset
+                        * of the nodemap one */
+                       OBD_ALLOC(buffer, PATH_MAX + 1);
+                       if (buffer == NULL)
+                               GOTO(out, rc = err_serious(-ENOMEM));
+                       if (snprintf(buffer, PATH_MAX + 1, "%s/%s",
+                                    nodemap_fileset, fileset) >= PATH_MAX + 1)
+                               GOTO(out, rc = err_serious(-EINVAL));
+                       fileset = buffer;
+               } else {
+                       /* enforce fileset as specified in the nodemap */
+                       fileset = nodemap_fileset;
+               }
+       }
+
+       if (fileset) {
+               CDEBUG(D_INFO, "Getting fileset %s\n", fileset);
+               rc = mdt_lookup_fileset(info, fileset, &repbody->mbo_fid1);
+               if (rc < 0)
+                       GOTO(out, rc = err_serious(rc));
+       } else {
+               repbody->mbo_fid1 = mdt->mdt_md_root_fid;
+       }
        repbody->mbo_valid |= OBD_MD_FLID;
 
        EXIT;
 out:
        mdt_thread_info_fini(info);
+       if (buffer)
+               OBD_FREE(buffer, PATH_MAX+1);
        return rc;
 }
 
@@ -298,7 +415,8 @@ static int mdt_statfs(struct tgt_session_info *tsi)
 {
        struct ptlrpc_request           *req = tgt_ses_req(tsi);
        struct mdt_thread_info          *info = tsi2mdt_info(tsi);
-       struct md_device                *next = info->mti_mdt->mdt_child;
+       struct mdt_device               *mdt = info->mti_mdt;
+       struct tg_grants_data           *tgd = &mdt->mdt_lut.lut_tgd;
        struct ptlrpc_service_part      *svcpt;
        struct obd_statfs               *osfs;
        int                             rc;
@@ -323,24 +441,44 @@ static int mdt_statfs(struct tgt_session_info *tsi)
        if (!osfs)
                GOTO(out, rc = -EPROTO);
 
-       /** statfs information are cached in the mdt_device */
-       if (cfs_time_before_64(info->mti_mdt->mdt_osfs_age,
-                              cfs_time_shift_64(-OBD_STATFS_CACHE_SECONDS))) {
-               /** statfs data is too old, get up-to-date one */
-               rc = next->md_ops->mdo_statfs(info->mti_env, next, osfs);
-               if (rc)
-                       GOTO(out, rc);
-               spin_lock(&info->mti_mdt->mdt_osfs_lock);
-               info->mti_mdt->mdt_osfs = *osfs;
-               info->mti_mdt->mdt_osfs_age = cfs_time_current_64();
-               spin_unlock(&info->mti_mdt->mdt_osfs_lock);
-       } else {
-               /** use cached statfs data */
-               spin_lock(&info->mti_mdt->mdt_osfs_lock);
-               *osfs = info->mti_mdt->mdt_osfs;
-               spin_unlock(&info->mti_mdt->mdt_osfs_lock);
-       }
+       rc = tgt_statfs_internal(tsi->tsi_env, &mdt->mdt_lut, osfs,
+                                cfs_time_shift_64(-OBD_STATFS_CACHE_SECONDS),
+                                NULL);
+       if (unlikely(rc))
+               GOTO(out, rc);
 
+       /* at least try to account for cached pages.  its still racy and
+        * might be under-reporting if clients haven't announced their
+        * caches with brw recently */
+       CDEBUG(D_SUPER | D_CACHE, "blocks cached %llu granted %llu"
+              " pending %llu free %llu avail %llu\n",
+              tgd->tgd_tot_dirty, tgd->tgd_tot_granted,
+              tgd->tgd_tot_pending,
+              osfs->os_bfree << tgd->tgd_blockbits,
+              osfs->os_bavail << tgd->tgd_blockbits);
+
+       osfs->os_bavail -= min_t(u64, osfs->os_bavail,
+                                ((tgd->tgd_tot_dirty + tgd->tgd_tot_pending +
+                                  osfs->os_bsize - 1) >> tgd->tgd_blockbits));
+
+       tgt_grant_sanity_check(mdt->mdt_lu_dev.ld_obd, __func__);
+       CDEBUG(D_CACHE, "%llu blocks: %llu free, %llu avail; "
+              "%llu objects: %llu free; state %x\n",
+              osfs->os_blocks, osfs->os_bfree, osfs->os_bavail,
+              osfs->os_files, osfs->os_ffree, osfs->os_state);
+
+       if (!exp_grant_param_supp(tsi->tsi_exp) &&
+           tgd->tgd_blockbits > COMPAT_BSIZE_SHIFT) {
+               /* clients which don't support OBD_CONNECT_GRANT_PARAM
+                * should not see a block size > page size, otherwise
+                * cl_lost_grant goes mad. Therefore, we emulate a 4KB (=2^12)
+                * block size which is the biggest block size known to work
+                * with all client's page size. */
+               osfs->os_blocks <<= tgd->tgd_blockbits - COMPAT_BSIZE_SHIFT;
+               osfs->os_bfree  <<= tgd->tgd_blockbits - COMPAT_BSIZE_SHIFT;
+               osfs->os_bavail <<= tgd->tgd_blockbits - COMPAT_BSIZE_SHIFT;
+               osfs->os_bsize = 1 << COMPAT_BSIZE_SHIFT;
+       }
        if (rc == 0)
                mdt_counter_incr(req, LPROC_MDT_STATFS);
 out:
@@ -348,6 +486,41 @@ out:
        RETURN(rc);
 }
 
+/**
+ * Pack size attributes into the reply.
+ */
+int mdt_pack_size2body(struct mdt_thread_info *info,
+                       const struct lu_fid *fid, bool dom_lock)
+{
+       struct mdt_body *b;
+       struct md_attr *ma = &info->mti_attr;
+       int dom_stripe;
+
+       ENTRY;
+
+       LASSERT(ma->ma_attr.la_valid & LA_MODE);
+
+       if (!S_ISREG(ma->ma_attr.la_mode) ||
+           !(ma->ma_valid & MA_LOV && ma->ma_lmm != NULL))
+               RETURN(-ENODATA);
+
+       dom_stripe = mdt_lmm_dom_entry(ma->ma_lmm);
+       /* no DoM stripe, no size in reply */
+       if (dom_stripe == LMM_NO_DOM)
+               RETURN(-ENOENT);
+
+       /* no DoM lock, no size in reply */
+       if (!dom_lock)
+               RETURN(0);
+
+       /* Either DoM lock exists or LMM has only DoM stripe then
+        * return size on body. */
+       b = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
+
+       mdt_dom_object_size(info->mti_env, info->mti_mdt, fid, b, dom_lock);
+       RETURN(0);
+}
+
 #ifdef CONFIG_FS_POSIX_ACL
 /*
  * Pack ACL data into the reply. UIDs/GIDs are mapped and filtered by nodemap.
@@ -365,14 +538,18 @@ int mdt_pack_acl2body(struct mdt_thread_info *info, struct mdt_body *repbody,
        const struct lu_env     *env = info->mti_env;
        struct md_object        *next = mdt_object_child(o);
        struct lu_buf           *buf = &info->mti_buf;
+       struct mdt_device       *mdt = info->mti_mdt;
        int rc;
 
+       ENTRY;
+
        buf->lb_buf = req_capsule_server_get(info->mti_pill, &RMF_ACL);
        buf->lb_len = req_capsule_get_size(info->mti_pill, &RMF_ACL,
                                           RCL_SERVER);
        if (buf->lb_len == 0)
-               return 0;
+               RETURN(0);
 
+again:
        rc = mo_xattr_get(env, next, buf, XATTR_NAME_ACL_ACCESS);
        if (rc < 0) {
                if (rc == -ENODATA) {
@@ -382,17 +559,49 @@ int mdt_pack_acl2body(struct mdt_thread_info *info, struct mdt_body *repbody,
                } else if (rc == -EOPNOTSUPP) {
                        rc = 0;
                } else {
+                       if (rc == -ERANGE &&
+                           exp_connect_large_acl(info->mti_exp) &&
+                           buf->lb_buf != info->mti_big_acl) {
+                               if (info->mti_big_acl == NULL) {
+                                       OBD_ALLOC_LARGE(info->mti_big_acl,
+                                                       mdt->mdt_max_ea_size);
+                                       if (info->mti_big_acl == NULL) {
+                                               CERROR("%s: unable to grow "
+                                                      DFID" ACL buffer\n",
+                                                      mdt_obd_name(mdt),
+                                                      PFID(mdt_object_fid(o)));
+                                               RETURN(-ENOMEM);
+                                       }
+
+                                       info->mti_big_aclsize =
+                                                       mdt->mdt_max_ea_size;
+                               }
+
+                               CDEBUG(D_INODE, "%s: grow the "DFID
+                                      " ACL buffer to size %d\n",
+                                      mdt_obd_name(mdt),
+                                      PFID(mdt_object_fid(o)),
+                                      mdt->mdt_max_ea_size);
+
+                               buf->lb_buf = info->mti_big_acl;
+                               buf->lb_len = info->mti_big_aclsize;
+
+                               goto again;
+                       }
+
                        CERROR("%s: unable to read "DFID" ACL: rc = %d\n",
-                              mdt_obd_name(info->mti_mdt),
-                              PFID(mdt_object_fid(o)), rc);
+                              mdt_obd_name(mdt), PFID(mdt_object_fid(o)), rc);
                }
        } else {
+               if (buf->lb_buf == info->mti_big_acl)
+                       info->mti_big_acl_used = 1;
+
                rc = nodemap_map_acl(nodemap, buf->lb_buf,
                                     rc, NODEMAP_FS_TO_CLIENT);
                /* if all ACLs mapped out, rc is still >= 0 */
                if (rc < 0) {
                        CERROR("%s: nodemap_map_acl unable to parse "DFID
-                              " ACL: rc = %d\n", mdt_obd_name(info->mti_mdt),
+                              " ACL: rc = %d\n", mdt_obd_name(mdt),
                               PFID(mdt_object_fid(o)), rc);
                } else {
                        repbody->mbo_aclsize = rc;
@@ -400,16 +609,41 @@ int mdt_pack_acl2body(struct mdt_thread_info *info, struct mdt_body *repbody,
                        rc = 0;
                }
        }
-       return rc;
+
+       RETURN(rc);
 }
 #endif
 
+/* XXX Look into layout in MDT layer. */
+static inline bool mdt_hsm_is_released(struct lov_mds_md *lmm)
+{
+       struct lov_comp_md_v1   *comp_v1;
+       struct lov_mds_md       *v1;
+       int                      i;
+
+       if (lmm->lmm_magic == LOV_MAGIC_COMP_V1) {
+               comp_v1 = (struct lov_comp_md_v1 *)lmm;
+
+               for (i = 0; i < comp_v1->lcm_entry_count; i++) {
+                       v1 = (struct lov_mds_md *)((char *)comp_v1 +
+                               comp_v1->lcm_entries[i].lcme_offset);
+                       /* We don't support partial release for now */
+                       if (!(v1->lmm_pattern & LOV_PATTERN_F_RELEASED))
+                               return false;
+               }
+               return true;
+       } else {
+               return (lmm->lmm_pattern & LOV_PATTERN_F_RELEASED) ?
+                       true : false;
+       }
+}
+
 void mdt_pack_attr2body(struct mdt_thread_info *info, struct mdt_body *b,
                         const struct lu_attr *attr, const struct lu_fid *fid)
 {
-       struct md_attr          *ma = &info->mti_attr;
-       struct obd_export       *exp = info->mti_exp;
-       struct lu_nodemap       *nodemap = exp->exp_target_data.ted_nodemap;
+       struct md_attr *ma = &info->mti_attr;
+       struct obd_export *exp = info->mti_exp;
+       struct lu_nodemap *nodemap = NULL;
 
        LASSERT(ma->ma_valid & MA_INODE);
 
@@ -433,6 +667,11 @@ void mdt_pack_attr2body(struct mdt_thread_info *info, struct mdt_body *b,
                b->mbo_nlink = attr->la_nlink;
                b->mbo_valid |= OBD_MD_FLNLINK;
        }
+       if (attr->la_valid & (LA_UID|LA_GID)) {
+               nodemap = nodemap_get_from_exp(exp);
+               if (IS_ERR(nodemap))
+                       goto out;
+       }
        if (attr->la_valid & LA_UID) {
                b->mbo_uid = nodemap_map_id(nodemap, NODEMAP_UID,
                                            NODEMAP_FS_TO_CLIENT,
@@ -445,6 +684,13 @@ void mdt_pack_attr2body(struct mdt_thread_info *info, struct mdt_body *b,
                                            attr->la_gid);
                b->mbo_valid |= OBD_MD_FLGID;
        }
+
+       if (attr->la_valid & LA_PROJID) {
+               /* TODO, nodemap for project id */
+               b->mbo_projid = attr->la_projid;
+               b->mbo_valid |= OBD_MD_FLPROJID;
+       }
+
        b->mbo_mode = attr->la_mode;
        if (attr->la_valid & LA_MODE)
                b->mbo_valid |= OBD_MD_FLMODE;
@@ -454,13 +700,10 @@ void mdt_pack_attr2body(struct mdt_thread_info *info, struct mdt_body *b,
        if (fid != NULL) {
                b->mbo_fid1 = *fid;
                b->mbo_valid |= OBD_MD_FLID;
-               CDEBUG(D_INODE, DFID": nlink=%d, mode=%o, valid="LPX64"\n",
+               CDEBUG(D_INODE, DFID": nlink=%d, mode=%o, valid=%#llx\n",
                       PFID(fid), b->mbo_nlink, b->mbo_mode, b->mbo_valid);
        }
 
-       if (info != NULL)
-               mdt_body_reverse_idmap(info, b);
-
        if (!(attr->la_valid & LA_TYPE))
                return;
 
@@ -478,22 +721,29 @@ void mdt_pack_attr2body(struct mdt_thread_info *info, struct mdt_body *b,
                /* if no object is allocated on osts, the size on mds is valid.
                 * b=22272 */
                b->mbo_valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS;
-       } else if ((ma->ma_valid & MA_LOV) && ma->ma_lmm != NULL &&
-                  ma->ma_lmm->lmm_pattern & LOV_PATTERN_F_RELEASED) {
-               /* A released file stores its size on MDS. */
-               /* But return 1 block for released file, unless tools like tar
-                * will consider it fully sparse. (LU-3864)
-                */
-               if (unlikely(b->mbo_size == 0))
-                       b->mbo_blocks = 0;
-               else
-                       b->mbo_blocks = 1;
-               b->mbo_valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS;
+       } else if ((ma->ma_valid & MA_LOV) && ma->ma_lmm != NULL) {
+               if (mdt_hsm_is_released(ma->ma_lmm)) {
+                       /* A released file stores its size on MDS. */
+                       /* But return 1 block for released file, unless tools
+                        * like tar will consider it fully sparse. (LU-3864)
+                        */
+                       if (unlikely(b->mbo_size == 0))
+                               b->mbo_blocks = 0;
+                       else
+                               b->mbo_blocks = 1;
+                       b->mbo_valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS;
+               } else if (info->mti_som_valid) { /* som is valid */
+                       b->mbo_valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS;
+               }
        }
 
        if (fid != NULL && (b->mbo_valid & OBD_MD_FLSIZE))
                CDEBUG(D_VFSTRACE, DFID": returning size %llu\n",
                       PFID(fid), (unsigned long long)b->mbo_size);
+
+out:
+       if (!IS_ERR_OR_NULL(nodemap))
+               nodemap_putref(nodemap);
 }
 
 static inline int mdt_body_has_lov(const struct lu_attr *la,
@@ -744,6 +994,9 @@ int mdt_attr_get_complex(struct mdt_thread_info *info,
                rc = mo_attr_get(env, next, ma);
                if (rc)
                        GOTO(out, rc);
+
+               if (S_ISREG(mode))
+                       (void) mdt_get_som(info, o, &ma->ma_attr);
                ma->ma_valid |= MA_INODE;
        }
 
@@ -803,7 +1056,7 @@ int mdt_attr_get_complex(struct mdt_thread_info *info,
 #endif
 out:
        ma->ma_need = need;
-       CDEBUG(D_INODE, "after getattr rc = %d, ma_valid = "LPX64" ma_lmm=%p\n",
+       CDEBUG(D_INODE, "after getattr rc = %d, ma_valid = %#llx ma_lmm=%p\n",
               rc, ma->ma_valid, ma->ma_lmm);
        RETURN(rc);
 }
@@ -821,9 +1074,7 @@ static int mdt_getattr_internal(struct mdt_thread_info *info,
        struct mdt_body         *repbody;
        struct lu_buf           *buffer = &info->mti_buf;
        struct obd_export       *exp = info->mti_exp;
-       struct lu_nodemap       *nodemap = exp->exp_target_data.ted_nodemap;
        int                      rc;
-       int                      is_root;
        ENTRY;
 
        if (OBD_FAIL_CHECK(OBD_FAIL_MDS_GETATTR_PACK))
@@ -890,7 +1141,8 @@ static int mdt_getattr_internal(struct mdt_thread_info *info,
 
        rc = mdt_attr_get_complex(info, o, ma);
        if (unlikely(rc)) {
-               CERROR("%s: getattr error for "DFID": rc = %d\n",
+               CDEBUG(rc == -ENOENT ? D_OTHER : D_ERROR,
+                      "%s: getattr error for "DFID": rc = %d\n",
                       mdt_obd_name(info->mti_mdt),
                       PFID(mdt_object_fid(o)), rc);
                RETURN(rc);
@@ -904,32 +1156,6 @@ static int mdt_getattr_internal(struct mdt_thread_info *info,
                        repbody->mbo_t_state = MS_RESTORE;
        }
 
-       is_root = lu_fid_eq(mdt_object_fid(o), &info->mti_mdt->mdt_md_root_fid);
-
-       /* the Lustre protocol supposes to return default striping
-        * on the user-visible root if explicitly requested */
-       if ((ma->ma_valid & MA_LOV) == 0 && S_ISDIR(la->la_mode) &&
-           (ma->ma_need & MA_LOV_DEF && is_root) && ma->ma_need & MA_LOV) {
-               struct lu_fid      rootfid;
-               struct mdt_object *root;
-               struct mdt_device *mdt = info->mti_mdt;
-
-               rc = dt_root_get(env, mdt->mdt_bottom, &rootfid);
-               if (rc)
-                       RETURN(rc);
-               root = mdt_object_find(env, mdt, &rootfid);
-               if (IS_ERR(root))
-                       RETURN(PTR_ERR(root));
-               rc = mdt_stripe_get(info, root, ma, XATTR_NAME_LOV);
-               mdt_object_put(info->mti_env, root);
-               if (unlikely(rc)) {
-                       CERROR("%s: getattr error for "DFID": rc = %d\n",
-                              mdt_obd_name(info->mti_mdt),
-                              PFID(mdt_object_fid(o)), rc);
-                       RETURN(rc);
-               }
-       }
-
         if (likely(ma->ma_valid & MA_INODE))
                 mdt_pack_attr2body(info, repbody, la, mdt_object_fid(o));
         else
@@ -960,6 +1186,7 @@ static int mdt_getattr_internal(struct mdt_thread_info *info,
                        if (!mdt_is_striped_client(req->rq_export))
                                RETURN(-ENOTSUPP);
                        LASSERT(S_ISDIR(la->la_mode));
+                       mdt_dump_lmv(D_INFO, ma->ma_lmv);
                        repbody->mbo_eadatasize = ma->ma_lmv_size;
                        repbody->mbo_valid |= (OBD_MD_FLDIREA |
                                               OBD_MD_DEFAULT_MEA);
@@ -977,7 +1204,7 @@ static int mdt_getattr_internal(struct mdt_thread_info *info,
                               PFID(mdt_object_fid(o)), rc);
                        rc = -EFAULT;
                } else {
-                       int print_limit = min_t(int, PAGE_CACHE_SIZE - 128, rc);
+                       int print_limit = min_t(int, PAGE_SIZE - 128, rc);
 
                        if (OBD_FAIL_CHECK(OBD_FAIL_MDS_READLINK_EPROTO))
                                rc -= 2;
@@ -1011,25 +1238,16 @@ static int mdt_getattr_internal(struct mdt_thread_info *info,
                       repbody->mbo_max_mdsize);
        }
 
-       if (exp_connect_rmtclient(info->mti_exp) &&
-           reqbody->mbo_valid & OBD_MD_FLRMTPERM) {
-               void *buf = req_capsule_server_get(pill, &RMF_ACL);
-
-               /* mdt_getattr_lock only */
-               rc = mdt_pack_remote_perm(info, o, buf);
-               if (rc) {
-                       repbody->mbo_valid &= ~OBD_MD_FLRMTPERM;
-                       repbody->mbo_aclsize = 0;
-                       RETURN(rc);
-               } else {
-                       repbody->mbo_valid |= OBD_MD_FLRMTPERM;
-                       repbody->mbo_aclsize = sizeof(struct mdt_remote_perm);
-               }
-       }
 #ifdef CONFIG_FS_POSIX_ACL
-       else if ((exp_connect_flags(req->rq_export) & OBD_CONNECT_ACL) &&
-                (reqbody->mbo_valid & OBD_MD_FLACL))
+       if ((exp_connect_flags(req->rq_export) & OBD_CONNECT_ACL) &&
+                (reqbody->mbo_valid & OBD_MD_FLACL)) {
+               struct lu_nodemap *nodemap = nodemap_get_from_exp(exp);
+               if (IS_ERR(nodemap))
+                       RETURN(PTR_ERR(nodemap));
+
                rc = mdt_pack_acl2body(info, repbody, o, nodemap);
+               nodemap_putref(nodemap);
+       }
 #endif
 
 out:
@@ -1085,6 +1303,12 @@ static int mdt_getattr(struct tgt_session_info *tsi)
 
        req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER, rc);
 
+       /* Set ACL reply buffer size as LUSTRE_POSIX_ACL_MAX_SIZE_OLD
+        * by default. If the target object has more ACL entries, then
+        * enlarge the buffer when necessary. */
+       req_capsule_set_size(pill, &RMF_ACL, RCL_SERVER,
+                            LUSTRE_POSIX_ACL_MAX_SIZE_OLD);
+
        rc = req_capsule_server_pack(pill);
        if (unlikely(rc != 0))
                GOTO(out, rc = err_serious(rc));
@@ -1094,18 +1318,13 @@ static int mdt_getattr(struct tgt_session_info *tsi)
        repbody->mbo_eadatasize = 0;
        repbody->mbo_aclsize = 0;
 
-       if (reqbody->mbo_valid & OBD_MD_FLRMTPERM)
-               rc = mdt_init_ucred(info, reqbody);
-       else
-               rc = mdt_check_ucred(info);
+       rc = mdt_check_ucred(info);
        if (unlikely(rc))
                GOTO(out_shrink, rc);
 
        info->mti_cross_ref = !!(reqbody->mbo_valid & OBD_MD_FLCROSSREF);
 
        rc = mdt_getattr_internal(info, obj, 0);
-       if (reqbody->mbo_valid & OBD_MD_FLRMTPERM)
-                mdt_exit_ucred(info);
         EXIT;
 out_shrink:
         mdt_client_compatibility(info);
@@ -1118,6 +1337,59 @@ out:
 }
 
 /**
+ * Handler of layout intent RPC requiring the layout modification
+ *
+ * \param[in] info     thread environment
+ * \param[in] obj      object
+ * \param[in] layout   layout change descriptor
+ *
+ * \retval 0   on success
+ * \retval < 0 error code
+ */
+static int mdt_layout_change(struct mdt_thread_info *info,
+                            struct mdt_object *obj,
+                            struct md_layout_change *layout)
+{
+       struct mdt_lock_handle *lh = &info->mti_lh[MDT_LH_LOCAL];
+       struct layout_intent *intent = layout->mlc_intent;
+       int rc;
+       ENTRY;
+
+       CDEBUG(D_INFO, "got layout change request from client: "
+              "opc:%u flags:%#x extent "DEXT"\n",
+              intent->li_opc, intent->li_flags, PEXT(&intent->li_extent));
+
+       if (intent->li_extent.e_start >= intent->li_extent.e_end) {
+               CERROR(DFID ":invalid range of layout change "DEXT"\n",
+                      PFID(mdt_object_fid(obj)), PEXT(&intent->li_extent));
+               RETURN(-EINVAL);
+       }
+
+       if (!mdt_object_exists(obj))
+               GOTO(out, rc = -ENOENT);
+
+       if (!S_ISREG(lu_object_attr(&obj->mot_obj)))
+               GOTO(out, rc = -EINVAL);
+
+       rc = mo_permission(info->mti_env, NULL, mdt_object_child(obj), NULL,
+                          MAY_WRITE);
+       if (rc)
+               GOTO(out, rc);
+
+       /* take layout lock to prepare layout change */
+       mdt_lock_reg_init(lh, LCK_EX);
+       rc = mdt_object_lock(info, obj, lh, MDS_INODELOCK_LAYOUT);
+       if (rc)
+               GOTO(out, rc);
+
+       rc = mo_layout_change(info->mti_env, mdt_object_child(obj), layout);
+
+       mdt_object_unlock(info, obj, lh, 1);
+out:
+       RETURN(rc);
+}
+
+/**
  * Exchange MOF_LOV_CREATED flags between two objects after a
  * layout swap. No assumption is made on whether o1 or o2 have
  * created objects or not.
@@ -1127,17 +1399,13 @@ out:
  */
 static void mdt_swap_lov_flag(struct mdt_object *o1, struct mdt_object *o2)
 {
-       __u64   o1_flags;
+       unsigned int o1_lov_created = o1->mot_lov_created;
 
        mutex_lock(&o1->mot_lov_mutex);
        mutex_lock(&o2->mot_lov_mutex);
 
-       o1_flags = o1->mot_flags;
-       o1->mot_flags = (o1->mot_flags & ~MOF_LOV_CREATED) |
-                       (o2->mot_flags & MOF_LOV_CREATED);
-
-       o2->mot_flags = (o2->mot_flags & ~MOF_LOV_CREATED) |
-                       (o1_flags & MOF_LOV_CREATED);
+       o1->mot_lov_created = o2->mot_lov_created;
+       o2->mot_lov_created = o1_lov_created;
 
        mutex_unlock(&o2->mot_lov_mutex);
        mutex_unlock(&o1->mot_lov_mutex);
@@ -1274,18 +1542,19 @@ static int mdt_getattr_name_lock(struct mdt_thread_info *info,
                                  __u64 child_bits,
                                  struct ldlm_reply *ldlm_rep)
 {
-        struct ptlrpc_request  *req       = mdt_info_req(info);
-        struct mdt_body        *reqbody   = NULL;
-        struct mdt_object      *parent    = info->mti_object;
-        struct mdt_object      *child;
-        struct lu_fid          *child_fid = &info->mti_tmp_fid1;
-        struct lu_name         *lname     = NULL;
-        struct mdt_lock_handle *lhp       = NULL;
-        struct ldlm_lock       *lock;
-       bool                    is_resent;
-       bool                    try_layout;
-       int                     ma_need = 0;
-       int                     rc;
+       struct ptlrpc_request  *req = mdt_info_req(info);
+       struct mdt_body        *reqbody = NULL;
+       struct mdt_object      *parent = info->mti_object;
+       struct mdt_object      *child;
+       struct lu_fid          *child_fid = &info->mti_tmp_fid1;
+       struct lu_name         *lname = NULL;
+       struct mdt_lock_handle *lhp = NULL;
+       struct ldlm_lock       *lock;
+       __u64 try_bits = 0;
+       bool is_resent;
+       int ma_need = 0;
+       int rc;
+
        ENTRY;
 
        is_resent = lustre_handle_is_used(&lhc->mlh_reg_lh);
@@ -1328,7 +1597,7 @@ static int mdt_getattr_name_lock(struct mdt_thread_info *info,
                if (!mdt_object_exists(child)) {
                        LU_OBJECT_DEBUG(D_INFO, info->mti_env,
                                        &child->mot_obj,
-                                       "remote object doesn't exist.\n");
+                                       "remote object doesn't exist.");
                        mdt_object_unlock(info, child, lhc, 1);
                        RETURN(-ENOENT);
                }
@@ -1368,7 +1637,7 @@ static int mdt_getattr_name_lock(struct mdt_thread_info *info,
        if (unlikely(!mdt_object_exists(parent)) && lu_name_is_valid(lname)) {
                LU_OBJECT_DEBUG(D_INODE, info->mti_env,
                                &parent->mot_obj,
-                               "Parent doesn't exist!\n");
+                               "Parent doesn't exist!");
                RETURN(-ESTALE);
        }
 
@@ -1436,30 +1705,29 @@ static int mdt_getattr_name_lock(struct mdt_thread_info *info,
                GOTO(out_parent, rc = PTR_ERR(child));
 
        OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_RESEND, obd_timeout * 2);
+       if (!mdt_object_exists(child)) {
+               LU_OBJECT_DEBUG(D_INODE, info->mti_env,
+                               &child->mot_obj,
+                               "Object doesn't exist!");
+               GOTO(out_child, rc = -ENOENT);
+       }
+
        rc = mdt_check_resent_lock(info, child, lhc);
        if (rc < 0) {
                GOTO(out_child, rc);
        } else if (rc > 0) {
-                mdt_lock_handle_init(lhc);
+               mdt_lock_handle_init(lhc);
                mdt_lock_reg_init(lhc, LCK_PR);
-               try_layout = false;
-
-               if (!mdt_object_exists(child)) {
-                       LU_OBJECT_DEBUG(D_INODE, info->mti_env,
-                                       &child->mot_obj,
-                                       "Object doesn't exist!\n");
-                       GOTO(out_child, rc = -ENOENT);
-               }
 
                if (!(child_bits & MDS_INODELOCK_UPDATE) &&
                      mdt_object_exists(child) && !mdt_object_remote(child)) {
-                        struct md_attr *ma = &info->mti_attr;
+                       struct md_attr *ma = &info->mti_attr;
 
-                        ma->ma_valid = 0;
-                        ma->ma_need = MA_INODE;
+                       ma->ma_valid = 0;
+                       ma->ma_need = MA_INODE;
                        rc = mdt_attr_get_complex(info, child, ma);
-                        if (unlikely(rc != 0))
-                                GOTO(out_child, rc);
+                       if (unlikely(rc != 0))
+                               GOTO(out_child, rc);
 
                        /* If the file has not been changed for some time, we
                         * return not only a LOOKUP lock, but also an UPDATE
@@ -1476,28 +1744,25 @@ static int mdt_getattr_name_lock(struct mdt_thread_info *info,
                /* layout lock must be granted in a best-effort way
                 * for IT operations */
                LASSERT(!(child_bits & MDS_INODELOCK_LAYOUT));
-               if (!OBD_FAIL_CHECK(OBD_FAIL_MDS_NO_LL_GETATTR) &&
-                   exp_connect_layout(info->mti_exp) &&
-                   S_ISREG(lu_object_attr(&child->mot_obj)) &&
+               if (S_ISREG(lu_object_attr(&child->mot_obj)) &&
                    !mdt_object_remote(child) && ldlm_rep != NULL) {
-                       /* try to grant layout lock for regular file. */
-                       try_layout = true;
+                       if (!OBD_FAIL_CHECK(OBD_FAIL_MDS_NO_LL_GETATTR) &&
+                           exp_connect_layout(info->mti_exp)) {
+                               /* try to grant layout lock for regular file. */
+                               try_bits = MDS_INODELOCK_LAYOUT;
+                       }
+                       /* Acquire DOM lock in advance for data-on-mdt file */
+                       if (child != parent)
+                               try_bits |= MDS_INODELOCK_DOM;
                }
 
-               rc = 0;
-               if (try_layout) {
-                       child_bits |= MDS_INODELOCK_LAYOUT;
+               if (try_bits != 0) {
                        /* try layout lock, it may fail to be granted due to
                         * contention at LOOKUP or UPDATE */
-                       if (!mdt_object_lock_try(info, child, lhc,
-                                                child_bits)) {
-                               child_bits &= ~MDS_INODELOCK_LAYOUT;
-                               LASSERT(child_bits != 0);
-                               rc = mdt_object_lock(info, child, lhc,
-                                                    child_bits);
-                       } else {
+                       rc = mdt_object_lock_try(info, child, lhc, &child_bits,
+                                                try_bits, false);
+                       if (child_bits & MDS_INODELOCK_LAYOUT)
                                ma_need |= MA_LOV;
-                       }
                } else {
                        /* Do not enqueue the UPDATE lock from MDT(cross-MDT),
                         * client will enqueue the lock to the remote MDT */
@@ -1523,6 +1788,27 @@ static int mdt_getattr_name_lock(struct mdt_thread_info *info,
                         "Lock res_id: "DLDLMRES", fid: "DFID"\n",
                         PLDLMRES(lock->l_resource),
                         PFID(mdt_object_fid(child)));
+
+               if (S_ISREG(lu_object_attr(&child->mot_obj)) &&
+                   mdt_object_exists(child) && !mdt_object_remote(child) &&
+                   child != parent) {
+                       LDLM_LOCK_PUT(lock);
+                       mdt_object_put(info->mti_env, child);
+                       /* NB: call the mdt_pack_size2body always after
+                        * mdt_object_put(), that is why this speacial
+                        * exit path is used. */
+                       rc = mdt_pack_size2body(info, child_fid,
+                                               child_bits & MDS_INODELOCK_DOM);
+                       if (rc != 0 && child_bits & MDS_INODELOCK_DOM) {
+                               /* DOM lock was taken in advance but this is
+                                * not DoM file. Drop the lock. */
+                               lock_res_and_lock(lock);
+                               ldlm_inodebits_drop(lock, MDS_INODELOCK_DOM);
+                               unlock_res_and_lock(lock);
+                       }
+
+                       GOTO(out_parent, rc = 0);
+               }
         }
         if (lock)
                 LDLM_LOCK_PUT(lock);
@@ -1555,7 +1841,7 @@ static int mdt_getattr_name(struct tgt_session_info *tsi)
        repbody->mbo_eadatasize = 0;
        repbody->mbo_aclsize = 0;
 
-        rc = mdt_init_ucred(info, reqbody);
+        rc = mdt_init_ucred_intent_getattr(info, reqbody);
         if (unlikely(rc))
                 GOTO(out_shrink, rc);
 
@@ -1576,7 +1862,7 @@ out_shrink:
 }
 
 static int mdt_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
-                         void *karg, void *uarg);
+                        void *karg, void __user *uarg);
 
 static int mdt_set_info(struct tgt_session_info *tsi)
 {
@@ -1630,6 +1916,9 @@ static int mdt_set_info(struct tgt_session_info *tsi)
 
                rc = mdt_iocontrol(OBD_IOC_CHANGELOG_CLEAR, req->rq_export,
                                   vallen, val, NULL);
+       } else if (KEY_IS(KEY_EVICT_BY_NID)) {
+               if (vallen > 0)
+                       obd_export_evict_by_nid(req->rq_export->exp_obd, val);
        } else {
                RETURN(-EINVAL);
        }
@@ -1662,7 +1951,7 @@ static int mdt_readpage(struct tgt_session_info *tsi)
          */
        rdpg->rp_hash = reqbody->mbo_size;
        if (rdpg->rp_hash != reqbody->mbo_size) {
-               CERROR("Invalid hash: "LPX64" != "LPX64"\n",
+               CERROR("Invalid hash: %#llx != %#llx\n",
                       rdpg->rp_hash, reqbody->mbo_size);
                RETURN(-EFAULT);
        }
@@ -1672,14 +1961,14 @@ static int mdt_readpage(struct tgt_session_info *tsi)
                rdpg->rp_attrs |= LUDA_64BITHASH;
        rdpg->rp_count  = min_t(unsigned int, reqbody->mbo_nlink,
                                exp_max_brw_size(tsi->tsi_exp));
-       rdpg->rp_npages = (rdpg->rp_count + PAGE_CACHE_SIZE - 1) >>
-                         PAGE_CACHE_SHIFT;
+       rdpg->rp_npages = (rdpg->rp_count + PAGE_SIZE - 1) >>
+                         PAGE_SHIFT;
         OBD_ALLOC(rdpg->rp_pages, rdpg->rp_npages * sizeof rdpg->rp_pages[0]);
         if (rdpg->rp_pages == NULL)
                 RETURN(-ENOMEM);
 
         for (i = 0; i < rdpg->rp_npages; ++i) {
-               rdpg->rp_pages[i] = alloc_page(GFP_IOFS);
+               rdpg->rp_pages[i] = alloc_page(GFP_NOFS);
                 if (rdpg->rp_pages[i] == NULL)
                         GOTO(free_rdpg, rc = -ENOMEM);
         }
@@ -1706,6 +1995,26 @@ free_rdpg:
        return rc;
 }
 
+static int mdt_fix_attr_ucred(struct mdt_thread_info *info, __u32 op)
+{
+       struct lu_ucred *uc = mdt_ucred_check(info);
+       struct lu_attr *attr = &info->mti_attr.ma_attr;
+
+       if (uc == NULL)
+               return -EINVAL;
+
+       if (op != REINT_SETATTR) {
+               if ((attr->la_valid & LA_UID) && (attr->la_uid != -1))
+                       attr->la_uid = uc->uc_fsuid;
+               /* for S_ISGID, inherit gid from his parent, such work will be
+                * done in cmm/mdd layer, here set all cases as uc->uc_fsgid. */
+               if ((attr->la_valid & LA_GID) && (attr->la_gid != -1))
+                       attr->la_gid = uc->uc_fsgid;
+       }
+
+       return 0;
+}
+
 static int mdt_reint_internal(struct mdt_thread_info *info,
                               struct mdt_lock_handle *lhc,
                               __u32 op)
@@ -1731,6 +2040,13 @@ static int mdt_reint_internal(struct mdt_thread_info *info,
         if (req_capsule_has_field(pill, &RMF_LOGCOOKIES, RCL_SERVER))
                req_capsule_set_size(pill, &RMF_LOGCOOKIES, RCL_SERVER, 0);
 
+       /* Set ACL reply buffer size as LUSTRE_POSIX_ACL_MAX_SIZE_OLD
+        * by default. If the target object has more ACL entries, then
+        * enlarge the buffer when necessary. */
+       if (req_capsule_has_field(pill, &RMF_ACL, RCL_SERVER))
+               req_capsule_set_size(pill, &RMF_ACL, RCL_SERVER,
+                                    LUSTRE_POSIX_ACL_MAX_SIZE_OLD);
+
         rc = req_capsule_server_pack(pill);
         if (rc != 0) {
                 CERROR("Can't pack response, rc %d\n", rc);
@@ -1852,20 +2168,21 @@ static int mdt_device_sync(const struct lu_env *env, struct mdt_device *mdt)
 }
 
 /* this should sync this object */
-static int mdt_object_sync(struct mdt_thread_info *info)
+static int mdt_object_sync(const struct lu_env *env, struct obd_export *exp,
+                          struct mdt_object *mo)
 {
-       struct md_object *next;
        int rc;
+
        ENTRY;
 
-       if (!mdt_object_exists(info->mti_object)) {
+       if (!mdt_object_exists(mo)) {
                CWARN("%s: non existing object "DFID": rc = %d\n",
-                     mdt_obd_name(info->mti_mdt),
-                     PFID(mdt_object_fid(info->mti_object)), -ESTALE);
+                     exp->exp_obd->obd_name, PFID(mdt_object_fid(mo)),
+                     -ESTALE);
                RETURN(-ESTALE);
        }
-       next = mdt_object_child(info->mti_object);
-       rc = mo_object_sync(info->mti_env, next);
+
+       rc = mo_object_sync(env, mdt_object_child(mo));
 
        RETURN(rc);
 }
@@ -1888,7 +2205,8 @@ static int mdt_sync(struct tgt_session_info *tsi)
                struct mdt_thread_info *info = tsi2mdt_info(tsi);
 
                /* sync an object */
-               rc = mdt_object_sync(info);
+               rc = mdt_object_sync(tsi->tsi_env, tsi->tsi_exp,
+                                    info->mti_object);
                if (rc == 0) {
                        const struct lu_fid *fid;
                        struct lu_attr *la = &info->mti_attr.ma_attr;
@@ -1912,6 +2230,54 @@ static int mdt_sync(struct tgt_session_info *tsi)
        RETURN(rc);
 }
 
+static int mdt_data_sync(struct tgt_session_info *tsi)
+{
+       struct mdt_thread_info *info;
+       struct mdt_device *mdt = mdt_exp2dev(tsi->tsi_exp);
+       struct ost_body *body = tsi->tsi_ost_body;
+       struct ost_body *repbody;
+       struct mdt_object *mo = NULL;
+       struct md_attr *ma;
+       int rc = 0;
+
+       ENTRY;
+
+       repbody = req_capsule_server_get(tsi->tsi_pill, &RMF_OST_BODY);
+
+       /* if no fid is specified then do nothing,
+        * device sync is done via MDS_SYNC */
+       if (fid_is_zero(&tsi->tsi_fid))
+               RETURN(0);
+
+       mo = mdt_object_find(tsi->tsi_env, mdt, &tsi->tsi_fid);
+       if (IS_ERR(mo))
+               RETURN(PTR_ERR(mo));
+
+       rc = mdt_object_sync(tsi->tsi_env, tsi->tsi_exp, mo);
+       if (rc)
+               GOTO(put, rc);
+
+       repbody->oa.o_oi = body->oa.o_oi;
+       repbody->oa.o_valid = OBD_MD_FLID | OBD_MD_FLGROUP;
+
+       info = tsi2mdt_info(tsi);
+       ma = &info->mti_attr;
+       ma->ma_need = MA_INODE;
+       ma->ma_valid = 0;
+       rc = mdt_attr_get_complex(info, mo, ma);
+       if (rc == 0)
+               obdo_from_la(&repbody->oa, &ma->ma_attr, VALID_FLAGS);
+       else
+               rc = 0;
+       mdt_thread_info_fini(info);
+
+       EXIT;
+put:
+       if (mo != NULL)
+               mdt_object_put(tsi->tsi_env, mo);
+       return rc;
+}
+
 /*
  * Handle quota control requests to consult current usage/limit, but also
  * to configure quota enforcement
@@ -1924,7 +2290,7 @@ static int mdt_quotactl(struct tgt_session_info *tsi)
        int                      id, rc;
        struct mdt_device       *mdt = mdt_exp2dev(exp);
        struct lu_device        *qmt = mdt->mdt_qmt_dev;
-       struct lu_nodemap       *nodemap = exp->exp_target_data.ted_nodemap;
+       struct lu_nodemap       *nodemap;
        ENTRY;
 
        oqctl = req_capsule_client_get(pill, &RMF_OBD_QUOTACTL);
@@ -1935,65 +2301,61 @@ static int mdt_quotactl(struct tgt_session_info *tsi)
        if (rc)
                RETURN(err_serious(rc));
 
+       nodemap = nodemap_get_from_exp(exp);
+       if (IS_ERR(nodemap))
+               RETURN(PTR_ERR(nodemap));
+
        switch (oqctl->qc_cmd) {
                /* master quotactl */
        case Q_SETINFO:
        case Q_SETQUOTA:
                if (!nodemap_can_setquota(nodemap))
-                       RETURN(-EPERM);
+                       GOTO(out_nodemap, rc = -EPERM);
        case Q_GETINFO:
        case Q_GETQUOTA:
                if (qmt == NULL)
-                       RETURN(-EOPNOTSUPP);
+                       GOTO(out_nodemap, rc = -EOPNOTSUPP);
                /* slave quotactl */
        case Q_GETOINFO:
        case Q_GETOQUOTA:
                break;
        default:
                CERROR("Unsupported quotactl command: %d\n", oqctl->qc_cmd);
-               RETURN(-EFAULT);
+               GOTO(out_nodemap, rc = -EFAULT);
        }
 
-       /* map uid/gid for remote client */
        id = oqctl->qc_id;
-       if (exp_connect_rmtclient(exp)) {
-               struct lustre_idmap_table *idmap;
-
-               idmap = exp->exp_mdt_data.med_idmap;
-
-               if (unlikely(oqctl->qc_cmd != Q_GETQUOTA &&
-                            oqctl->qc_cmd != Q_GETINFO))
-                       RETURN(-EPERM);
-
-               if (oqctl->qc_type == USRQUOTA)
-                       id = lustre_idmap_lookup_uid(NULL, idmap, 0,
-                                                    oqctl->qc_id);
-               else if (oqctl->qc_type == GRPQUOTA)
-                       id = lustre_idmap_lookup_gid(NULL, idmap, 0,
-                                                    oqctl->qc_id);
-               else
-                       RETURN(-EINVAL);
-
-               if (id == CFS_IDMAP_NOTFOUND) {
-                       CDEBUG(D_QUOTA, "no mapping for id %u\n", oqctl->qc_id);
-                       RETURN(-EACCES);
-               }
-       }
-
-       if (oqctl->qc_type == USRQUOTA)
+       switch (oqctl->qc_type) {
+       case USRQUOTA:
                id = nodemap_map_id(nodemap, NODEMAP_UID,
                                    NODEMAP_CLIENT_TO_FS, id);
-       else if (oqctl->qc_type == GRPQUOTA)
-               id = nodemap_map_id(nodemap, NODEMAP_UID,
+               break;
+       case GRPQUOTA:
+               id = nodemap_map_id(nodemap, NODEMAP_GID,
                                    NODEMAP_CLIENT_TO_FS, id);
-
+               break;
+       case PRJQUOTA:
+               /* todo: check/map project id */
+               id = oqctl->qc_id;
+               break;
+       default:
+               GOTO(out_nodemap, rc = -EOPNOTSUPP);
+       }
        repoqc = req_capsule_server_get(pill, &RMF_OBD_QUOTACTL);
        if (repoqc == NULL)
-               RETURN(err_serious(-EFAULT));
+               GOTO(out_nodemap, rc = err_serious(-EFAULT));
+
+       if (oqctl->qc_cmd == Q_SETINFO || oqctl->qc_cmd == Q_SETQUOTA)
+               barrier_exit(tsi->tsi_tgt->lut_bottom);
 
        if (oqctl->qc_id != id)
                swap(oqctl->qc_id, id);
 
+       if (oqctl->qc_cmd == Q_SETINFO || oqctl->qc_cmd == Q_SETQUOTA) {
+               if (unlikely(!barrier_entry(tsi->tsi_tgt->lut_bottom)))
+                       RETURN(-EINPROGRESS);
+       }
+
        switch (oqctl->qc_cmd) {
 
        case Q_GETINFO:
@@ -2013,14 +2375,20 @@ static int mdt_quotactl(struct tgt_session_info *tsi)
 
        default:
                CERROR("Unsupported quotactl command: %d\n", oqctl->qc_cmd);
-               RETURN(-EFAULT);
+               GOTO(out_nodemap, rc = -EFAULT);
        }
 
        if (oqctl->qc_id != id)
                swap(oqctl->qc_id, id);
 
        *repoqc = *oqctl;
-       RETURN(rc);
+
+       EXIT;
+
+out_nodemap:
+       nodemap_putref(nodemap);
+
+       return rc;
 }
 
 /** clone llog ctxt from child (mdd)
@@ -2072,21 +2440,9 @@ static int mdt_llog_ctxt_unclone(const struct lu_env *env,
  */
 static int mdt_sec_ctx_handle(struct tgt_session_info *tsi)
 {
-       int rc;
-
-       rc = mdt_handle_idmap(tsi);
-       if (unlikely(rc)) {
-               struct ptlrpc_request   *req = tgt_ses_req(tsi);
-               __u32                    opc;
-
-               opc = lustre_msg_get_opc(req->rq_reqmsg);
-               if (opc == SEC_CTX_INIT || opc == SEC_CTX_INIT_CONT)
-                       sptlrpc_svc_ctx_invalidate(req);
-       }
-
        CFS_FAIL_TIMEOUT(OBD_FAIL_SEC_CTX_HDL_PAUSE, cfs_fail_val);
 
-       return rc;
+       return 0;
 }
 
 /*
@@ -2155,11 +2511,14 @@ static void mdt_device_commit_async(const struct lu_env *env,
 {
        struct dt_device *dt = mdt->mdt_bottom;
        int rc;
+       ENTRY;
 
        rc = dt->dd_ops->dt_commit_async(env, dt);
        if (unlikely(rc != 0))
                CWARN("%s: async commit start failed: rc = %d\n",
                      mdt_obd_name(mdt), rc);
+       atomic_inc(&mdt->mdt_async_commit_count);
+       EXIT;
 }
 
 /**
@@ -2206,69 +2565,139 @@ static inline int mdt_is_lock_sync(struct ldlm_lock *lock)
  * \see ldlm_blocking_ast_nocheck
  */
 int mdt_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
-                     void *data, int flag)
+                    void *data, int flag)
 {
-        struct obd_device *obd = ldlm_lock_to_ns(lock)->ns_obd;
-        struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
-        int rc;
-        ENTRY;
+       struct obd_device *obd = ldlm_lock_to_ns(lock)->ns_obd;
+       struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
+       bool commit_async = false;
+       int rc;
+       ENTRY;
 
-        if (flag == LDLM_CB_CANCELING)
-                RETURN(0);
-        lock_res_and_lock(lock);
-        if (lock->l_blocking_ast != mdt_blocking_ast) {
-                unlock_res_and_lock(lock);
-                RETURN(0);
-        }
-        if (mdt_cos_is_enabled(mdt) &&
-            lock->l_req_mode & (LCK_PW | LCK_EX) &&
-            lock->l_blocking_lock != NULL &&
-            lock->l_client_cookie != lock->l_blocking_lock->l_client_cookie) {
-                mdt_set_lock_sync(lock);
-        }
-        rc = ldlm_blocking_ast_nocheck(lock);
+       if (flag == LDLM_CB_CANCELING)
+               RETURN(0);
+
+       lock_res_and_lock(lock);
+       if (lock->l_blocking_ast != mdt_blocking_ast) {
+               unlock_res_and_lock(lock);
+               RETURN(0);
+       }
+       /* There is no lock conflict if l_blocking_lock == NULL,
+        * it indicates a blocking ast sent from ldlm_lock_decref_internal
+        * when the last reference to a local lock was released */
+       if (lock->l_req_mode & (LCK_PW | LCK_EX) &&
+           lock->l_blocking_lock != NULL) {
+               if (mdt_cos_is_enabled(mdt)) {
+                       if (lock->l_client_cookie !=
+                           lock->l_blocking_lock->l_client_cookie)
+                               mdt_set_lock_sync(lock);
+               } else if (mdt_slc_is_enabled(mdt) &&
+                          ldlm_is_cos_incompat(lock->l_blocking_lock)) {
+                       mdt_set_lock_sync(lock);
+                       /*
+                        * we may do extra commit here, but there is a small
+                        * window to miss a commit: lock was unlocked (saved),
+                        * then a conflict lock queued and we come here, but
+                        * REP-ACK not received, so lock was not converted to
+                        * COS mode yet.
+                        * Fortunately this window is quite small, so the
+                        * extra commit should be rare (not to say distributed
+                        * operation is rare too).
+                        */
+                       commit_async = true;
+               }
+       } else if (lock->l_req_mode == LCK_COS &&
+                  lock->l_blocking_lock != NULL) {
+               commit_async = true;
+       }
 
-        /* There is no lock conflict if l_blocking_lock == NULL,
-         * it indicates a blocking ast sent from ldlm_lock_decref_internal
-         * when the last reference to a local lock was released */
-        if (lock->l_req_mode == LCK_COS && lock->l_blocking_lock != NULL) {
-                struct lu_env env;
+       rc = ldlm_blocking_ast_nocheck(lock);
+
+       if (commit_async) {
+               struct lu_env env;
 
                rc = lu_env_init(&env, LCT_LOCAL);
                if (unlikely(rc != 0))
                        CWARN("%s: lu_env initialization failed, cannot "
                              "start asynchronous commit: rc = %d\n",
                              obd->obd_name, rc);
-                else
-                        mdt_device_commit_async(&env, mdt);
-                lu_env_fini(&env);
-        }
-        RETURN(rc);
+               else
+                       mdt_device_commit_async(&env, mdt);
+               lu_env_fini(&env);
+       }
+       RETURN(rc);
 }
 
-/* Used for cross-MDT lock */
+/*
+ * Blocking AST for cross-MDT lock
+ *
+ * Discard lock from uncommitted_slc_locks and cancel it.
+ *
+ * \param lock the lock which blocks a request or cancelling lock
+ * \param desc unused
+ * \param data unused
+ * \param flag indicates whether this cancelling or blocking callback
+ * \retval     0 on success
+ * \retval     negative number on error
+ */
 int mdt_remote_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
                            void *data, int flag)
 {
-       struct lustre_handle lockh;
-       int               rc;
+       int rc = 0;
+       ENTRY;
 
        switch (flag) {
-       case LDLM_CB_BLOCKING:
+       case LDLM_CB_BLOCKING: {
+               struct lustre_handle lockh;
+
                ldlm_lock2handle(lock, &lockh);
-               rc = ldlm_cli_cancel(&lockh, LCF_ASYNC);
+               rc = ldlm_cli_cancel(&lockh,
+                       ldlm_is_atomic_cb(lock) ? 0 : LCF_ASYNC);
                if (rc < 0) {
                        CDEBUG(D_INODE, "ldlm_cli_cancel: %d\n", rc);
                        RETURN(rc);
                }
                break;
-       case LDLM_CB_CANCELING:
+       }
+       case LDLM_CB_CANCELING: {
+               struct obd_device *obd = ldlm_lock_to_ns(lock)->ns_obd;
+               struct mdt_device *mdt =
+                               mdt_dev(obd->obd_lu_dev->ld_site->ls_top_dev);
+
                LDLM_DEBUG(lock, "Revoke remote lock\n");
+
+               /* discard slc lock here so that it can be cleaned anytime,
+                * especially for cleanup_resource() */
+               tgt_discard_slc_lock(&mdt->mdt_lut, lock);
+
+               /* once we cache lock, l_ast_data is set to mdt_object */
+               if (lock->l_ast_data != NULL) {
+                       struct mdt_object *mo = lock->l_ast_data;
+                       struct lu_env env;
+
+                       rc = lu_env_init(&env, LCT_MD_THREAD);
+                       if (unlikely(rc != 0)) {
+                               CWARN("%s: lu_env initialization failed, object"
+                                     "%p "DFID" is leaked!\n",
+                                     obd->obd_name, mo,
+                                     PFID(mdt_object_fid(mo)));
+                               RETURN(rc);
+                       }
+
+                       if (lock->l_policy_data.l_inodebits.bits &
+                           (MDS_INODELOCK_XATTR | MDS_INODELOCK_UPDATE)) {
+                               rc = mo_invalidate(&env, mdt_object_child(mo));
+                               mo->mot_cache_attr = 0;
+                       }
+                       mdt_object_put(&env, mo);
+                       lu_env_fini(&env);
+               }
                break;
+       }
        default:
                LBUG();
        }
-       RETURN(0);
+
+       RETURN(rc);
 }
 
 int mdt_check_resent_lock(struct mdt_thread_info *info,
@@ -2286,7 +2715,7 @@ int mdt_check_resent_lock(struct mdt_thread_info *info,
                        /* Lock is pinned by ldlm_handle_enqueue0() as it is
                         * a resend case, however, it could be already destroyed
                         * due to client eviction or a raced cancel RPC. */
-                       LDLM_DEBUG_NOLOCK("Invalid lock handle "LPX64"\n",
+                       LDLM_DEBUG_NOLOCK("Invalid lock handle %#llx",
                                          lhc->mlh_reg_lh.cookie);
                        RETURN(-ESTALE);
                }
@@ -2306,13 +2735,13 @@ int mdt_check_resent_lock(struct mdt_thread_info *info,
        return 1;
 }
 
-int mdt_remote_object_lock(struct mdt_thread_info *mti,
-                          struct mdt_object *o, const struct lu_fid *fid,
-                          struct lustre_handle *lh, ldlm_mode_t mode,
-                          __u64 ibits, bool nonblock)
+int mdt_remote_object_lock_try(struct mdt_thread_info *mti,
+                              struct mdt_object *o, const struct lu_fid *fid,
+                              struct lustre_handle *lh, enum ldlm_mode mode,
+                              __u64 *ibits, __u64 trybits, bool cache)
 {
        struct ldlm_enqueue_info *einfo = &mti->mti_einfo;
-       ldlm_policy_data_t *policy = &mti->mti_policy;
+       union ldlm_policy_data *policy = &mti->mti_policy;
        struct ldlm_res_id *res_id = &mti->mti_res_id;
        int rc = 0;
        ENTRY;
@@ -2328,37 +2757,76 @@ int mdt_remote_object_lock(struct mdt_thread_info *mti,
        einfo->ei_cb_cp = ldlm_completion_ast;
        einfo->ei_enq_slave = 0;
        einfo->ei_res_id = res_id;
-       if (nonblock)
-               einfo->ei_nonblock = 1;
+
+       if (cache) {
+               /*
+                * if we cache lock, couple lock with mdt_object, so that object
+                * can be easily found in lock ASTs.
+                */
+               mdt_object_get(mti->mti_env, o);
+               einfo->ei_cbdata = o;
+       }
+
 
        memset(policy, 0, sizeof(*policy));
-       policy->l_inodebits.bits = ibits;
+       policy->l_inodebits.bits = *ibits;
+       policy->l_inodebits.try_bits = trybits;
 
        rc = mo_object_lock(mti->mti_env, mdt_object_child(o), lh, einfo,
                            policy);
+       if (rc < 0 && cache) {
+               mdt_object_put(mti->mti_env, o);
+               einfo->ei_cbdata = NULL;
+       }
+
+       /* Return successfully acquired bits to a caller */
+       if (rc == 0) {
+               struct ldlm_lock *lock = ldlm_handle2lock(lh);
+
+               LASSERT(lock);
+               *ibits = lock->l_policy_data.l_inodebits.bits;
+               LDLM_LOCK_PUT(lock);
+       }
        RETURN(rc);
 }
 
+int mdt_remote_object_lock(struct mdt_thread_info *mti, struct mdt_object *o,
+                          const struct lu_fid *fid, struct lustre_handle *lh,
+                          enum ldlm_mode mode, __u64 ibits, bool cache)
+{
+       return mdt_remote_object_lock_try(mti, o, fid, lh, mode, &ibits, 0,
+                                         cache);
+}
+
 static int mdt_object_local_lock(struct mdt_thread_info *info,
                                 struct mdt_object *o,
-                                struct mdt_lock_handle *lh, __u64 ibits,
-                                bool nonblock)
+                                struct mdt_lock_handle *lh, __u64 *ibits,
+                                __u64 trybits, bool cos_incompat)
 {
-        struct ldlm_namespace *ns = info->mti_mdt->mdt_namespace;
-        ldlm_policy_data_t *policy = &info->mti_policy;
-        struct ldlm_res_id *res_id = &info->mti_res_id;
-       __u64 dlmflags;
-        int rc;
-        ENTRY;
+       struct ldlm_namespace *ns = info->mti_mdt->mdt_namespace;
+       union ldlm_policy_data *policy = &info->mti_policy;
+       struct ldlm_res_id *res_id = &info->mti_res_id;
+       __u64 dlmflags = 0;
+       int rc;
+       ENTRY;
 
         LASSERT(!lustre_handle_is_used(&lh->mlh_reg_lh));
         LASSERT(!lustre_handle_is_used(&lh->mlh_pdo_lh));
         LASSERT(lh->mlh_reg_mode != LCK_MINMODE);
         LASSERT(lh->mlh_type != MDT_NUL_LOCK);
 
+       if (cos_incompat) {
+               LASSERT(lh->mlh_reg_mode == LCK_PW ||
+                       lh->mlh_reg_mode == LCK_EX);
+               dlmflags |= LDLM_FL_COS_INCOMPAT;
+       } else if (mdt_cos_is_enabled(info->mti_mdt)) {
+               dlmflags |= LDLM_FL_COS_ENABLED;
+       }
+
        /* Only enqueue LOOKUP lock for remote object */
-       if (mdt_object_remote(o))
-               LASSERT(ibits == MDS_INODELOCK_LOOKUP);
+       if (mdt_object_remote(o)) {
+               LASSERT(*ibits == MDS_INODELOCK_LOOKUP);
+       }
 
        if (lh->mlh_type == MDT_PDO_LOCK) {
                 /* check for exists after object is locked */
@@ -2369,30 +2837,28 @@ static int mdt_object_local_lock(struct mdt_thread_info *info,
                         /* Non-dir object shouldn't have PDO lock */
                        if (!S_ISDIR(lu_object_attr(&o->mot_obj)))
                                RETURN(-ENOTDIR);
-                }
-        }
+               }
+       }
 
-        memset(policy, 0, sizeof(*policy));
-        fid_build_reg_res_name(mdt_object_fid(o), res_id);
 
-       dlmflags = LDLM_FL_ATOMIC_CB;
-       if (nonblock)
-               dlmflags |= LDLM_FL_BLOCK_NOWAIT;
+       fid_build_reg_res_name(mdt_object_fid(o), res_id);
+       dlmflags |= LDLM_FL_ATOMIC_CB;
 
-        /*
-         * Take PDO lock on whole directory and build correct @res_id for lock
-         * on part of directory.
-         */
-        if (lh->mlh_pdo_hash != 0) {
-                LASSERT(lh->mlh_type == MDT_PDO_LOCK);
-                mdt_lock_pdo_mode(info, o, lh);
-                if (lh->mlh_pdo_mode != LCK_NL) {
-                        /*
-                         * Do not use LDLM_FL_LOCAL_ONLY for parallel lock, it
-                         * is never going to be sent to client and we do not
-                         * want it slowed down due to possible cancels.
-                         */
-                        policy->l_inodebits.bits = MDS_INODELOCK_UPDATE;
+       /*
+        * Take PDO lock on whole directory and build correct @res_id for lock
+        * on part of directory.
+        */
+       if (lh->mlh_pdo_hash != 0) {
+               LASSERT(lh->mlh_type == MDT_PDO_LOCK);
+               mdt_lock_pdo_mode(info, o, lh);
+               if (lh->mlh_pdo_mode != LCK_NL) {
+                       /*
+                        * Do not use LDLM_FL_LOCAL_ONLY for parallel lock, it
+                        * is never going to be sent to client and we do not
+                        * want it slowed down due to possible cancels.
+                        */
+                       policy->l_inodebits.bits = MDS_INODELOCK_UPDATE;
+                       policy->l_inodebits.try_bits = 0;
                        rc = mdt_fid_lock(ns, &lh->mlh_pdo_lh, lh->mlh_pdo_mode,
                                          policy, res_id, dlmflags,
                                          info->mti_exp == NULL ? NULL :
@@ -2408,7 +2874,8 @@ static int mdt_object_local_lock(struct mdt_thread_info *info,
                 res_id->name[LUSTRE_RES_ID_HSH_OFF] = lh->mlh_pdo_hash;
         }
 
-        policy->l_inodebits.bits = ibits;
+       policy->l_inodebits.bits = *ibits;
+       policy->l_inodebits.try_bits = trybits;
 
         /*
          * Use LDLM_FL_LOCAL_ONLY for this lock. We do not know yet if it is
@@ -2427,37 +2894,49 @@ out_unlock:
                   (lh->mlh_reg_mode == LCK_PW || lh->mlh_reg_mode == LCK_EX))
                OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_PDO_LOCK, 15);
 
+       /* Return successfully acquired bits to a caller */
+       if (rc == 0) {
+               struct ldlm_lock *lock = ldlm_handle2lock(&lh->mlh_reg_lh);
+
+               LASSERT(lock);
+               *ibits = lock->l_policy_data.l_inodebits.bits;
+               LDLM_LOCK_PUT(lock);
+       }
        RETURN(rc);
 }
 
 static int
 mdt_object_lock_internal(struct mdt_thread_info *info, struct mdt_object *o,
-                        struct mdt_lock_handle *lh, __u64 ibits,
-                        bool nonblock)
+                        struct mdt_lock_handle *lh, __u64 *ibits,
+                        __u64 trybits, bool cos_incompat)
 {
        struct mdt_lock_handle *local_lh = NULL;
        int rc;
        ENTRY;
 
-       if (!mdt_object_remote(o))
-               return mdt_object_local_lock(info, o, lh, ibits, nonblock);
+       if (!mdt_object_remote(o)) {
+               rc = mdt_object_local_lock(info, o, lh, ibits, trybits,
+                                          cos_incompat);
+               RETURN(rc);
+       }
 
        /* XXX do not support PERM/LAYOUT/XATTR lock for remote object yet */
-       ibits &= ~(MDS_INODELOCK_PERM | MDS_INODELOCK_LAYOUT |
-                  MDS_INODELOCK_XATTR);
+       *ibits &= ~(MDS_INODELOCK_PERM | MDS_INODELOCK_LAYOUT |
+                   MDS_INODELOCK_XATTR);
 
        /* Only enqueue LOOKUP lock for remote object */
-       if (ibits & MDS_INODELOCK_LOOKUP) {
-               rc = mdt_object_local_lock(info, o, lh,
-                                          MDS_INODELOCK_LOOKUP,
-                                          nonblock);
+       if (*ibits & MDS_INODELOCK_LOOKUP) {
+               __u64 local = MDS_INODELOCK_LOOKUP;
+
+               rc = mdt_object_local_lock(info, o, lh, &local, 0,
+                                          cos_incompat);
                if (rc != ELDLM_OK)
                        RETURN(rc);
 
                local_lh = lh;
        }
 
-       if (ibits & MDS_INODELOCK_UPDATE) {
+       if ((*ibits | trybits) & MDS_INODELOCK_UPDATE) {
                /* Sigh, PDO needs to enqueue 2 locks right now, but
                 * enqueue RPC can only request 1 lock, to avoid extra
                 * RPC, so it will instead enqueue EX lock for remote
@@ -2471,10 +2950,11 @@ mdt_object_lock_internal(struct mdt_thread_info *info, struct mdt_object *o,
                        lh->mlh_rreg_mode = LCK_EX;
                        lh->mlh_type = MDT_REG_LOCK;
                }
-               rc = mdt_remote_object_lock(info, o, mdt_object_fid(o),
-                                           &lh->mlh_rreg_lh,
-                                           lh->mlh_rreg_mode,
-                                           MDS_INODELOCK_UPDATE, nonblock);
+
+               rc = mdt_remote_object_lock_try(info, o, mdt_object_fid(o),
+                                               &lh->mlh_rreg_lh,
+                                               lh->mlh_rreg_mode,
+                                               ibits, trybits, false);
                if (rc != ELDLM_OK) {
                        if (local_lh != NULL)
                                mdt_object_unlock(info, o, local_lh, rc);
@@ -2488,20 +2968,24 @@ mdt_object_lock_internal(struct mdt_thread_info *info, struct mdt_object *o,
 int mdt_object_lock(struct mdt_thread_info *info, struct mdt_object *o,
                    struct mdt_lock_handle *lh, __u64 ibits)
 {
-       return mdt_object_lock_internal(info, o, lh, ibits, false);
+       return mdt_object_lock_internal(info, o, lh, &ibits, 0, false);
 }
 
-int mdt_object_lock_try(struct mdt_thread_info *info, struct mdt_object *o,
-                       struct mdt_lock_handle *lh, __u64 ibits)
+int mdt_reint_object_lock(struct mdt_thread_info *info, struct mdt_object *o,
+                         struct mdt_lock_handle *lh, __u64 ibits,
+                         bool cos_incompat)
 {
-       struct mdt_lock_handle tmp = *lh;
-       int rc;
-
-       rc = mdt_object_lock_internal(info, o, &tmp, ibits, true);
-       if (rc == 0)
-               *lh = tmp;
+       LASSERT(lh->mlh_reg_mode == LCK_PW || lh->mlh_reg_mode == LCK_EX);
+       return mdt_object_lock_internal(info, o, lh, &ibits, 0,
+                                       cos_incompat);
+}
 
-       return rc == 0;
+int mdt_object_lock_try(struct mdt_thread_info *info, struct mdt_object *o,
+                       struct mdt_lock_handle *lh, __u64 *ibits,
+                       __u64 trybits, bool cos_incompat)
+{
+       return mdt_object_lock_internal(info, o, lh, ibits, trybits,
+                                       cos_incompat);
 }
 
 /**
@@ -2517,38 +3001,42 @@ int mdt_object_lock_try(struct mdt_thread_info *info, struct mdt_object *o,
  * \param mode lock mode
  * \param decref force immediate lock releasing
  */
-static
 void mdt_save_lock(struct mdt_thread_info *info, struct lustre_handle *h,
-                   ldlm_mode_t mode, int decref)
+                  enum ldlm_mode mode, int decref)
 {
-        ENTRY;
+       ENTRY;
 
-        if (lustre_handle_is_used(h)) {
-                if (decref || !info->mti_has_trans ||
-                    !(mode & (LCK_PW | LCK_EX))){
-                        mdt_fid_unlock(h, mode);
-                } else {
-                        struct mdt_device *mdt = info->mti_mdt;
-                        struct ldlm_lock *lock = ldlm_handle2lock(h);
-                        struct ptlrpc_request *req = mdt_info_req(info);
-                        int no_ack = 0;
+       if (lustre_handle_is_used(h)) {
+               if (decref || !info->mti_has_trans ||
+                   !(mode & (LCK_PW | LCK_EX))) {
+                       mdt_fid_unlock(h, mode);
+               } else {
+                       struct mdt_device *mdt = info->mti_mdt;
+                       struct ldlm_lock *lock = ldlm_handle2lock(h);
+                       struct ptlrpc_request *req = mdt_info_req(info);
+                       bool cos = mdt_cos_is_enabled(mdt);
+                       bool convert_lock = !cos && mdt_slc_is_enabled(mdt);
+
+                       LASSERTF(lock != NULL, "no lock for cookie %#llx\n",
+                                h->cookie);
 
-                        LASSERTF(lock != NULL, "no lock for cookie "LPX64"\n",
-                                 h->cookie);
                        /* there is no request if mdt_object_unlock() is called
                         * from mdt_export_cleanup()->mdt_add_dirty_flag() */
                        if (likely(req != NULL)) {
-                               CDEBUG(D_HA, "request = %p reply state = %p"
-                                      " transno = "LPD64"\n", req,
-                                      req->rq_reply_state, req->rq_transno);
-                               if (mdt_cos_is_enabled(mdt)) {
-                                       no_ack = 1;
+                               LDLM_DEBUG(lock, "save lock request %p reply "
+                                       "state %p transno %lld\n", req,
+                                       req->rq_reply_state, req->rq_transno);
+                               if (cos) {
                                        ldlm_lock_downgrade(lock, LCK_COS);
                                        mode = LCK_COS;
                                }
-                               ptlrpc_save_lock(req, h, mode, no_ack);
+                               if (req->rq_export->exp_disconnected)
+                                       mdt_fid_unlock(h, mode);
+                               else
+                                       ptlrpc_save_lock(req, h, mode, cos,
+                                                        convert_lock);
                        } else {
-                               ldlm_lock_decref(h, mode);
+                               mdt_fid_unlock(h, mode);
                        }
                         if (mdt_is_lock_sync(lock)) {
                                 CDEBUG(D_HA, "found sync-lock,"
@@ -2565,6 +3053,49 @@ void mdt_save_lock(struct mdt_thread_info *info, struct lustre_handle *h,
 }
 
 /**
+ * Save cross-MDT lock in uncommitted_slc_locks
+ *
+ * Keep the lock referenced until transaction commit happens or release the lock
+ * immediately depending on input parameters.
+ *
+ * \param info thead info object
+ * \param h lock handle
+ * \param mode lock mode
+ * \param decref force immediate lock releasing
+ */
+static void mdt_save_remote_lock(struct mdt_thread_info *info,
+                                struct mdt_object *o, struct lustre_handle *h,
+                                enum ldlm_mode mode, int decref)
+{
+       ENTRY;
+
+       if (lustre_handle_is_used(h)) {
+               struct ldlm_lock *lock = ldlm_handle2lock(h);
+
+               if (o != NULL &&
+                   (lock->l_policy_data.l_inodebits.bits &
+                    (MDS_INODELOCK_XATTR | MDS_INODELOCK_UPDATE)))
+                       mo_invalidate(info->mti_env, mdt_object_child(o));
+
+               if (decref || !info->mti_has_trans ||
+                   !(mode & (LCK_PW | LCK_EX))) {
+                       ldlm_lock_decref_and_cancel(h, mode);
+                       LDLM_LOCK_PUT(lock);
+               } else {
+                       struct ptlrpc_request *req = mdt_info_req(info);
+
+                       LASSERT(req != NULL);
+                       tgt_save_slc_lock(&info->mti_mdt->mdt_lut, lock,
+                                         req->rq_transno);
+                       ldlm_lock_decref(h, mode);
+               }
+               h->cookie = 0ull;
+       }
+
+       EXIT;
+}
+
+/**
  * Unlock mdt object.
  *
  * Immeditely release the regular lock and the PDO lock or save the
@@ -2575,19 +3106,20 @@ void mdt_save_lock(struct mdt_thread_info *info, struct lustre_handle *h,
  * \param o mdt object
  * \param lh mdt lock handle referencing regular and PDO locks
  * \param decref force immediate lock releasing
+ *
+ * XXX o is not used and may be NULL, see hsm_cdt_request_completed().
  */
 void mdt_object_unlock(struct mdt_thread_info *info, struct mdt_object *o,
-                       struct mdt_lock_handle *lh, int decref)
+                      struct mdt_lock_handle *lh, int decref)
 {
-        ENTRY;
-
-        mdt_save_lock(info, &lh->mlh_pdo_lh, lh->mlh_pdo_mode, decref);
-        mdt_save_lock(info, &lh->mlh_reg_lh, lh->mlh_reg_mode, decref);
+       ENTRY;
 
-       if (lustre_handle_is_used(&lh->mlh_rreg_lh))
-               ldlm_lock_decref(&lh->mlh_rreg_lh, lh->mlh_rreg_mode);
+       mdt_save_lock(info, &lh->mlh_pdo_lh, lh->mlh_pdo_mode, decref);
+       mdt_save_lock(info, &lh->mlh_reg_lh, lh->mlh_reg_mode, decref);
+       mdt_save_remote_lock(info, o, &lh->mlh_rreg_lh, lh->mlh_rreg_mode,
+                            decref);
 
-        EXIT;
+       EXIT;
 }
 
 struct mdt_object *mdt_object_find_lock(struct mdt_thread_info *info,
@@ -2690,6 +3222,13 @@ static int mdt_unpack_req_pack_rep(struct mdt_thread_info *info, __u32 flags)
                        req_capsule_set_size(pill, &RMF_LOGCOOKIES,
                                             RCL_SERVER, 0);
 
+               /* Set ACL reply buffer size as LUSTRE_POSIX_ACL_MAX_SIZE_OLD
+                * by default. If the target object has more ACL entries, then
+                * enlarge the buffer when necessary. */
+               if (req_capsule_has_field(pill, &RMF_ACL, RCL_SERVER))
+                       req_capsule_set_size(pill, &RMF_ACL, RCL_SERVER,
+                                            LUSTRE_POSIX_ACL_MAX_SIZE_OLD);
+
                 rc = req_capsule_server_pack(pill);
         }
         RETURN(rc);
@@ -2746,6 +3285,8 @@ void mdt_thread_info_init(struct ptlrpc_request *req,
         info->mti_cross_ref = 0;
         info->mti_opdata = 0;
        info->mti_big_lmm_used = 0;
+       info->mti_big_acl_used = 0;
+       info->mti_som_valid = 0;
 
         info->mti_spec.no_create = 0;
        info->mti_spec.sp_rm_entry = 0;
@@ -2795,11 +3336,6 @@ struct mdt_thread_info *tsi2mdt_info(struct tgt_session_info *tsi)
 
 static int mdt_tgt_connect(struct tgt_session_info *tsi)
 {
-       struct ptlrpc_request   *req = tgt_ses_req(tsi);
-       int                      rc;
-
-       ENTRY;
-
        if (OBD_FAIL_CHECK(OBD_FAIL_TGT_DELAY_CONDITIONAL) &&
            cfs_fail_val ==
            tsi2mdt_info(tsi)->mti_mdt->mdt_seq_site.ss_node_id) {
@@ -2807,17 +3343,7 @@ static int mdt_tgt_connect(struct tgt_session_info *tsi)
                schedule_timeout(msecs_to_jiffies(3 * MSEC_PER_SEC));
        }
 
-       rc = tgt_connect(tsi);
-       if (rc != 0)
-               RETURN(rc);
-
-       rc = mdt_init_idmap(tsi);
-       if (rc != 0)
-               GOTO(err, rc);
-       RETURN(0);
-err:
-       obd_disconnect(class_export_get(req->rq_export));
-       return rc;
+       return tgt_connect(tsi);
 }
 
 enum mdt_it_code {
@@ -2832,13 +3358,14 @@ enum mdt_it_code {
         MDT_IT_GETXATTR,
         MDT_IT_LAYOUT,
        MDT_IT_QUOTA,
-        MDT_IT_NR
+       MDT_IT_GLIMPSE,
+       MDT_IT_BRW,
+       MDT_IT_NR
 };
 
 static int mdt_intent_getattr(enum mdt_it_code opcode,
-                              struct mdt_thread_info *info,
-                              struct ldlm_lock **,
-                             __u64);
+                             struct mdt_thread_info *info,
+                             struct ldlm_lock **, __u64);
 
 static int mdt_intent_getxattr(enum mdt_it_code opcode,
                                struct mdt_thread_info *info,
@@ -2853,6 +3380,20 @@ static int mdt_intent_reint(enum mdt_it_code opcode,
                             struct mdt_thread_info *info,
                             struct ldlm_lock **,
                            __u64);
+static int mdt_intent_glimpse(enum mdt_it_code opcode,
+                             struct mdt_thread_info *info,
+                             struct ldlm_lock **lockp, __u64 flags)
+{
+       return mdt_glimpse_enqueue(info, info->mti_mdt->mdt_namespace,
+                                  lockp, flags);
+}
+static int mdt_intent_brw(enum mdt_it_code opcode,
+                         struct mdt_thread_info *info,
+                         struct ldlm_lock **lockp, __u64 flags)
+{
+       return mdt_brw_enqueue(info, info->mti_mdt->mdt_namespace,
+                              lockp, flags);
+}
 
 static struct mdt_it_flavor {
         const struct req_format *it_fmt;
@@ -2924,14 +3465,24 @@ static struct mdt_it_flavor {
                .it_fmt   = &RQF_LDLM_INTENT_LAYOUT,
                .it_flags = 0,
                .it_act   = mdt_intent_layout
-       }
+       },
+       [MDT_IT_GLIMPSE] = {
+               .it_fmt = &RQF_LDLM_INTENT,
+               .it_flags = 0,
+               .it_act = mdt_intent_glimpse,
+       },
+       [MDT_IT_BRW] = {
+               .it_fmt = &RQF_LDLM_INTENT,
+               .it_flags = 0,
+               .it_act = mdt_intent_brw,
+       },
+
 };
 
-static int
-mdt_intent_lock_replace(struct mdt_thread_info *info,
-                       struct ldlm_lock **lockp,
-                       struct mdt_lock_handle *lh,
-                       __u64 flags)
+int mdt_intent_lock_replace(struct mdt_thread_info *info,
+                           struct ldlm_lock **lockp,
+                           struct mdt_lock_handle *lh,
+                           __u64 flags, int result)
 {
         struct ptlrpc_request  *req = mdt_info_req(info);
         struct ldlm_lock       *lock = *lockp;
@@ -2945,8 +3496,19 @@ mdt_intent_lock_replace(struct mdt_thread_info *info,
                 RETURN(0);
         }
 
-        LASSERTF(new_lock != NULL,
-                 "lockh "LPX64"\n", lh->mlh_reg_lh.cookie);
+       if (new_lock == NULL && (flags & LDLM_FL_RESENT)) {
+               /* Lock is pinned by ldlm_handle_enqueue0() as it is
+                * a resend case, however, it could be already destroyed
+                * due to client eviction or a raced cancel RPC. */
+               LDLM_DEBUG_NOLOCK("Invalid lock handle %#llx\n",
+                                 lh->mlh_reg_lh.cookie);
+               lh->mlh_reg_lh.cookie = 0;
+               RETURN(-ESTALE);
+       }
+
+       LASSERTF(new_lock != NULL,
+                "lockh %#llx flags %#llx : rc = %d\n",
+                lh->mlh_reg_lh.cookie, flags, result);
 
         /*
          * If we've already given this lock to a client once, then we should
@@ -2996,6 +3558,8 @@ mdt_intent_lock_replace(struct mdt_thread_info *info,
         new_lock->l_export = class_export_lock_get(req->rq_export, new_lock);
         new_lock->l_blocking_ast = lock->l_blocking_ast;
         new_lock->l_completion_ast = lock->l_completion_ast;
+       if (ldlm_has_dom(new_lock))
+               new_lock->l_glimpse_ast = ldlm_server_glimpse_ast;
         new_lock->l_remote_handle = lock->l_remote_handle;
         new_lock->l_flags &= ~LDLM_FL_LOCAL;
 
@@ -3011,10 +3575,9 @@ mdt_intent_lock_replace(struct mdt_thread_info *info,
         RETURN(ELDLM_LOCK_REPLACED);
 }
 
-static void mdt_intent_fixup_resent(struct mdt_thread_info *info,
-                                   struct ldlm_lock *new_lock,
-                                   struct mdt_lock_handle *lh,
-                                   __u64 flags)
+void mdt_intent_fixup_resent(struct mdt_thread_info *info,
+                            struct ldlm_lock *new_lock,
+                            struct mdt_lock_handle *lh, __u64 flags)
 {
         struct ptlrpc_request  *req = mdt_info_req(info);
         struct ldlm_request    *dlmreq;
@@ -3032,7 +3595,7 @@ static void mdt_intent_fixup_resent(struct mdt_thread_info *info,
                lh->mlh_reg_mode = new_lock->l_granted_mode;
 
                LDLM_DEBUG(new_lock, "Restoring lock cookie");
-               DEBUG_REQ(D_DLMTRACE, req, "restoring lock cookie "LPX64,
+               DEBUG_REQ(D_DLMTRACE, req, "restoring lock cookie %#llx",
                          lh->mlh_reg_lh.cookie);
                return;
        }
@@ -3051,7 +3614,7 @@ static void mdt_intent_fixup_resent(struct mdt_thread_info *info,
          */
         lustre_msg_clear_flags(req->rq_reqmsg, MSG_RESENT);
 
-       DEBUG_REQ(D_DLMTRACE, req, "no existing lock with rhandle "LPX64,
+       DEBUG_REQ(D_DLMTRACE, req, "no existing lock with rhandle %#llx",
                  dlmreq->lock_handle[0].cookie);
 }
 
@@ -3062,7 +3625,8 @@ static int mdt_intent_getxattr(enum mdt_it_code opcode,
 {
        struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
        struct ldlm_reply      *ldlm_rep = NULL;
-       int rc, grc;
+       int rc;
+       ENTRY;
 
        /*
         * Initialize lhc->mlh_reg_lh either from a previously granted lock
@@ -3078,18 +3642,30 @@ static int mdt_intent_getxattr(enum mdt_it_code opcode,
                        return rc;
        }
 
-       grc = mdt_getxattr(info);
-
-       rc = mdt_intent_lock_replace(info, lockp, lhc, flags);
+       rc = mdt_getxattr(info);
 
        if (mdt_info_req(info)->rq_repmsg != NULL)
                ldlm_rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
-       if (ldlm_rep == NULL)
+
+       if (ldlm_rep == NULL ||
+           OBD_FAIL_CHECK(OBD_FAIL_MDS_XATTR_REP)) {
+               mdt_object_unlock(info,  info->mti_object, lhc, 1);
                RETURN(err_serious(-EFAULT));
+       }
 
-       ldlm_rep->lock_policy_res2 = grc;
+       ldlm_rep->lock_policy_res2 = clear_serious(rc);
 
-       return rc;
+       /* This is left for interop instead of adding a new interop flag.
+        * LU-7433 */
+#if LUSTRE_VERSION_CODE > OBD_OCD_VERSION(3, 0, 0, 0)
+       if (ldlm_rep->lock_policy_res2) {
+               mdt_object_unlock(info, info->mti_object, lhc, 1);
+               RETURN(ELDLM_LOCK_ABORTED);
+       }
+#endif
+
+       rc = mdt_intent_lock_replace(info, lockp, lhc, flags, rc);
+       RETURN(rc);
 }
 
 static int mdt_intent_getattr(enum mdt_it_code opcode,
@@ -3149,7 +3725,7 @@ static int mdt_intent_getattr(enum mdt_it_code opcode,
                 GOTO(out_ucred, rc = ELDLM_LOCK_ABORTED);
         }
 
-       rc = mdt_intent_lock_replace(info, lockp, lhc, flags);
+       rc = mdt_intent_lock_replace(info, lockp, lhc, flags, rc);
         EXIT;
 out_ucred:
         mdt_exit_ucred(info);
@@ -3167,9 +3743,11 @@ static int mdt_intent_layout(enum mdt_it_code opcode,
                             __u64 flags)
 {
        struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_LAYOUT];
-       struct layout_intent *layout;
+       struct md_layout_change layout = { .mlc_opc = MD_LAYOUT_NOP };
+       struct layout_intent *intent;
        struct lu_fid *fid;
        struct mdt_object *obj = NULL;
+       int layout_size = 0;
        int rc = 0;
        ENTRY;
 
@@ -3179,6 +3757,35 @@ static int mdt_intent_layout(enum mdt_it_code opcode,
                RETURN(-EINVAL);
        }
 
+       intent = req_capsule_client_get(info->mti_pill, &RMF_LAYOUT_INTENT);
+       if (intent == NULL)
+               RETURN(-EPROTO);
+
+       switch (intent->li_opc) {
+       case LAYOUT_INTENT_TRUNC:
+       case LAYOUT_INTENT_WRITE:
+               layout.mlc_opc = MD_LAYOUT_WRITE;
+               layout.mlc_intent = intent;
+               break;
+       case LAYOUT_INTENT_ACCESS:
+               break;
+       case LAYOUT_INTENT_READ:
+       case LAYOUT_INTENT_GLIMPSE:
+       case LAYOUT_INTENT_RELEASE:
+       case LAYOUT_INTENT_RESTORE:
+               CERROR("%s: Unsupported layout intent opc %d\n",
+                      mdt_obd_name(info->mti_mdt), intent->li_opc);
+               rc = -ENOTSUPP;
+               break;
+       default:
+               CERROR("%s: Unknown layout intent opc %d\n",
+                      mdt_obd_name(info->mti_mdt), intent->li_opc);
+               rc = -EINVAL;
+               break;
+       }
+       if (rc < 0)
+               RETURN(rc);
+
        fid = &info->mti_tmp_fid2;
        fid_extract_from_res_name(fid, &(*lockp)->l_resource->lr_name);
 
@@ -3187,40 +3794,88 @@ static int mdt_intent_layout(enum mdt_it_code opcode,
 
        obj = mdt_object_find(info->mti_env, info->mti_mdt, fid);
        if (IS_ERR(obj))
-               RETURN(PTR_ERR(obj));
+               GOTO(out, rc = PTR_ERR(obj));
 
        if (mdt_object_exists(obj) && !mdt_object_remote(obj)) {
-               /* get the length of lsm */
-               rc = mdt_attr_get_eabuf_size(info, obj);
-               if (rc < 0) {
-                       mdt_object_put(info->mti_env, obj);
-                       RETURN(rc);
-               }
+               layout_size = mdt_attr_get_eabuf_size(info, obj);
+               if (layout_size < 0)
+                       GOTO(out_obj, rc = layout_size);
 
-               if (rc > info->mti_mdt->mdt_max_mdsize)
-                       info->mti_mdt->mdt_max_mdsize = rc;
+               if (layout_size > info->mti_mdt->mdt_max_mdsize)
+                       info->mti_mdt->mdt_max_mdsize = layout_size;
        }
 
-       mdt_object_put(info->mti_env, obj);
-
+       /*
+        * set reply buffer size, so that ldlm_handle_enqueue0()->
+        * ldlm_lvbo_fill() will fill the reply buffer with lovea.
+        */
        (*lockp)->l_lvb_type = LVB_T_LAYOUT;
-       req_capsule_set_size(info->mti_pill, &RMF_DLM_LVB, RCL_SERVER, rc);
+       req_capsule_set_size(info->mti_pill, &RMF_DLM_LVB, RCL_SERVER,
+                            layout_size);
        rc = req_capsule_server_pack(info->mti_pill);
-       if (rc != 0)
-               RETURN(-EINVAL);
+       if (rc)
+               GOTO(out_obj, rc);
 
-       if (lustre_handle_is_used(&lhc->mlh_reg_lh))
-               rc = mdt_intent_lock_replace(info, lockp, lhc, flags);
 
-       layout = req_capsule_client_get(info->mti_pill, &RMF_LAYOUT_INTENT);
-       LASSERT(layout != NULL);
-       if (layout->li_opc == LAYOUT_INTENT_ACCESS)
-               /* return to normal/resent ldlm handling */
-               RETURN(rc);
+       if (layout.mlc_opc != MD_LAYOUT_NOP) {
+               struct lu_buf *buf = &layout.mlc_buf;
+
+               /**
+                * mdt_layout_change is a reint operation, when the request
+                * is resent, layout write shouldn't reprocess it again.
+                */
+               rc = mdt_check_resent(info, mdt_reconstruct_generic, lhc);
+               if (rc)
+                       GOTO(out_obj, rc = rc < 0 ? rc : 0);
+
+               /**
+                * There is another resent case: the client's job has been
+                * done by another client, referring lod_declare_layout_change
+                * -EALREADY case, and it became a operation w/o transaction,
+                * so we should not do the layout change, otherwise
+                * mdt_layout_change() will try to cancel the granted server
+                * CR lock whose remote counterpart is still in hold on the
+                * client, and a deadlock ensues.
+                */
+               rc = mdt_check_resent_lock(info, obj, lhc);
+               if (rc <= 0)
+                       GOTO(out_obj, rc);
+
+               buf->lb_buf = NULL;
+               buf->lb_len = 0;
+               if (unlikely(req_is_replay(mdt_info_req(info)))) {
+                       buf->lb_buf = req_capsule_client_get(info->mti_pill,
+                                       &RMF_EADATA);
+                       buf->lb_len = req_capsule_get_size(info->mti_pill,
+                                       &RMF_EADATA, RCL_CLIENT);
+                       /*
+                        * If it's a replay of layout write intent RPC, the
+                        * client has saved the extended lovea when
+                        * it get reply then.
+                        */
+                       if (buf->lb_len > 0)
+                               mdt_fix_lov_magic(info, buf->lb_buf);
+               }
+
+               /*
+                * Instantiate some layout components, if @buf contains
+                * lovea, then it's a replay of the layout intent write
+                * RPC.
+                */
+               rc = mdt_layout_change(info, obj, &layout);
+               if (rc)
+                       GOTO(out_obj, rc);
+       }
+out_obj:
+       mdt_object_put(info->mti_env, obj);
+
+       if (rc == 0 && lustre_handle_is_used(&lhc->mlh_reg_lh))
+               rc = mdt_intent_lock_replace(info, lockp, lhc, flags, rc);
+
+out:
+       lhc->mlh_reg_lh.cookie = 0;
 
-       CERROR("%s: Unsupported layout intent (%d)\n",
-               mdt_obd_name(info->mti_mdt), layout->li_opc);
-       RETURN(-EINVAL);
+       return rc;
 }
 
 static int mdt_intent_reint(enum mdt_it_code opcode,
@@ -3270,15 +3925,16 @@ static int mdt_intent_reint(enum mdt_it_code opcode,
        if (lustre_handle_is_used(&lhc->mlh_reg_lh) &&
            (rc == 0 || rc == -MDT_EREMOTE_OPEN)) {
                rep->lock_policy_res2 = 0;
-               rc = mdt_intent_lock_replace(info, lockp, lhc, flags);
+               rc = mdt_intent_lock_replace(info, lockp, lhc, flags, rc);
                RETURN(rc);
        }
 
        rep->lock_policy_res2 = clear_serious(rc);
 
         if (rep->lock_policy_res2 == -ENOENT &&
-            mdt_get_disposition(rep, DISP_LOOKUP_NEG))
-                rep->lock_policy_res2 = 0;
+           mdt_get_disposition(rep, DISP_LOOKUP_NEG) &&
+           !mdt_get_disposition(rep, DISP_OPEN_CREATE))
+               rep->lock_policy_res2 = 0;
 
        lhc->mlh_reg_lh.cookie = 0ull;
         if (rc == -ENOTCONN || rc == -ENODEV ||
@@ -3298,54 +3954,61 @@ static int mdt_intent_reint(enum mdt_it_code opcode,
        RETURN(ELDLM_LOCK_ABORTED);
 }
 
-static int mdt_intent_code(long itcode)
+static int mdt_intent_code(enum ldlm_intent_flags itcode)
 {
-        int rc;
+       int rc;
 
-        switch(itcode) {
-        case IT_OPEN:
-                rc = MDT_IT_OPEN;
-                break;
-        case IT_OPEN|IT_CREAT:
-                rc = MDT_IT_OCREAT;
-                break;
-        case IT_CREAT:
-                rc = MDT_IT_CREATE;
-                break;
-        case IT_READDIR:
-                rc = MDT_IT_READDIR;
-                break;
-        case IT_GETATTR:
-                rc = MDT_IT_GETATTR;
-                break;
-        case IT_LOOKUP:
-                rc = MDT_IT_LOOKUP;
-                break;
-        case IT_UNLINK:
-                rc = MDT_IT_UNLINK;
-                break;
-        case IT_TRUNC:
-                rc = MDT_IT_TRUNC;
-                break;
-        case IT_GETXATTR:
-                rc = MDT_IT_GETXATTR;
-                break;
-        case IT_LAYOUT:
-                rc = MDT_IT_LAYOUT;
-                break;
+       switch (itcode) {
+       case IT_OPEN:
+               rc = MDT_IT_OPEN;
+               break;
+       case IT_OPEN|IT_CREAT:
+               rc = MDT_IT_OCREAT;
+               break;
+       case IT_CREAT:
+               rc = MDT_IT_CREATE;
+               break;
+       case IT_READDIR:
+               rc = MDT_IT_READDIR;
+               break;
+       case IT_GETATTR:
+               rc = MDT_IT_GETATTR;
+               break;
+       case IT_LOOKUP:
+               rc = MDT_IT_LOOKUP;
+               break;
+       case IT_UNLINK:
+               rc = MDT_IT_UNLINK;
+               break;
+       case IT_TRUNC:
+               rc = MDT_IT_TRUNC;
+               break;
+       case IT_GETXATTR:
+               rc = MDT_IT_GETXATTR;
+               break;
+       case IT_LAYOUT:
+               rc = MDT_IT_LAYOUT;
+               break;
        case IT_QUOTA_DQACQ:
        case IT_QUOTA_CONN:
                rc = MDT_IT_QUOTA;
                break;
-        default:
-                CERROR("Unknown intent opcode: %ld\n", itcode);
-                rc = -EINVAL;
-                break;
-        }
-        return rc;
+       case IT_GLIMPSE:
+               rc = MDT_IT_GLIMPSE;
+               break;
+       case IT_BRW:
+               rc = MDT_IT_BRW;
+               break;
+       default:
+               CERROR("Unknown intent opcode: 0x%08x\n", itcode);
+               rc = -EINVAL;
+               break;
+       }
+       return rc;
 }
 
-static int mdt_intent_opc(long itopc, struct mdt_thread_info *info,
+static int mdt_intent_opc(enum ldlm_intent_flags itopc,
+                         struct mdt_thread_info *info,
                          struct ldlm_lock **lockp, __u64 flags)
 {
        struct req_capsule      *pill = info->mti_pill;
@@ -3365,6 +4028,9 @@ static int mdt_intent_opc(long itopc, struct mdt_thread_info *info,
                if (qmt == NULL)
                        RETURN(-EOPNOTSUPP);
 
+               if (mdt_rdonly(req->rq_export))
+                       RETURN(-EROFS);
+
                (*lockp)->l_lvb_type = LVB_T_LQUOTA;
                /* pass the request to quota master */
                rc = qmt_hdls.qmth_intent_policy(info->mti_env, qmt,
@@ -3381,13 +4047,14 @@ static int mdt_intent_opc(long itopc, struct mdt_thread_info *info,
        if (rc < 0)
                RETURN(rc);
 
-       if (flv->it_flags & MUTABOR &&
-           exp_connect_flags(req->rq_export) & OBD_CONNECT_RDONLY)
+       if (flv->it_flags & MUTABOR && mdt_rdonly(req->rq_export))
                RETURN(-EROFS);
 
        if (flv->it_act != NULL) {
                struct ldlm_reply *rep;
 
+               OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_INTENT_DELAY, 10);
+
                /* execute policy */
                rc = flv->it_act(opc, info, lockp, flags);
 
@@ -3403,15 +4070,28 @@ static int mdt_intent_opc(long itopc, struct mdt_thread_info *info,
        RETURN(rc);
 }
 
+static void mdt_ptlrpc_stats_update(struct ptlrpc_request *req,
+                                   enum ldlm_intent_flags it_opc)
+{
+       struct lprocfs_stats *srv_stats = ptlrpc_req2svc(req)->srv_stats;
+
+       /* update stats when IT code is known */
+       if (srv_stats != NULL)
+               lprocfs_counter_incr(srv_stats,
+                               PTLRPC_LAST_CNTR + (it_opc == IT_GLIMPSE ?
+                               LDLM_GLIMPSE_ENQUEUE : LDLM_IBITS_ENQUEUE));
+}
+
 static int mdt_intent_policy(struct ldlm_namespace *ns,
-                             struct ldlm_lock **lockp, void *req_cookie,
-                            ldlm_mode_t mode, __u64 flags, void *data)
+                            struct ldlm_lock **lockp, void *req_cookie,
+                            enum ldlm_mode mode, __u64 flags, void *data)
 {
        struct tgt_session_info *tsi;
        struct mdt_thread_info  *info;
        struct ptlrpc_request   *req  =  req_cookie;
        struct ldlm_intent      *it;
        struct req_capsule      *pill;
+       const struct ldlm_lock_desc *ldesc;
        int rc;
 
        ENTRY;
@@ -3421,37 +4101,37 @@ static int mdt_intent_policy(struct ldlm_namespace *ns,
        tsi = tgt_ses_info(req->rq_svc_thread->t_env);
 
        info = tsi2mdt_info(tsi);
-        LASSERT(info != NULL);
-        pill = info->mti_pill;
-        LASSERT(pill->rc_req == req);
+       LASSERT(info != NULL);
+       pill = info->mti_pill;
+       LASSERT(pill->rc_req == req);
+       ldesc = &info->mti_dlm_req->lock_desc;
 
-        if (req->rq_reqmsg->lm_bufcount > DLM_INTENT_IT_OFF) {
+       if (req->rq_reqmsg->lm_bufcount > DLM_INTENT_IT_OFF) {
                req_capsule_extend(pill, &RQF_LDLM_INTENT_BASIC);
-                it = req_capsule_client_get(pill, &RMF_LDLM_INTENT);
-                if (it != NULL) {
-                        rc = mdt_intent_opc(it->opc, info, lockp, flags);
-                        if (rc == 0)
-                                rc = ELDLM_OK;
-
-                        /* Lock without inodebits makes no sense and will oops
-                         * later in ldlm. Let's check it now to see if we have
-                         * ibits corrupted somewhere in mdt_intent_opc().
-                         * The case for client miss to set ibits has been
-                         * processed by others. */
-                        LASSERT(ergo(info->mti_dlm_req->lock_desc.l_resource.\
-                                        lr_type == LDLM_IBITS,
-                                     info->mti_dlm_req->lock_desc.\
-                                        l_policy_data.l_inodebits.bits != 0));
-                } else
-                        rc = err_serious(-EFAULT);
-        } else {
-                /* No intent was provided */
-                LASSERT(pill->rc_fmt == &RQF_LDLM_ENQUEUE);
+               it = req_capsule_client_get(pill, &RMF_LDLM_INTENT);
+               if (it != NULL) {
+                       mdt_ptlrpc_stats_update(req, it->opc);
+                       rc = mdt_intent_opc(it->opc, info, lockp, flags);
+                       if (rc == 0)
+                               rc = ELDLM_OK;
+
+                       /* Lock without inodebits makes no sense and will oops
+                        * later in ldlm. Let's check it now to see if we have
+                        * ibits corrupted somewhere in mdt_intent_opc().
+                        * The case for client miss to set ibits has been
+                        * processed by others. */
+                       LASSERT(ergo(ldesc->l_resource.lr_type == LDLM_IBITS,
+                               ldesc->l_policy_data.l_inodebits.bits != 0));
+               } else {
+                       rc = err_serious(-EFAULT);
+               }
+       } else {
+               /* No intent was provided */
                req_capsule_set_size(pill, &RMF_DLM_LVB, RCL_SERVER, 0);
-                rc = req_capsule_server_pack(pill);
-                if (rc)
-                        rc = err_serious(rc);
-        }
+               rc = req_capsule_server_pack(pill);
+               if (rc)
+                       rc = err_serious(rc);
+       }
        mdt_thread_info_fini(info);
        RETURN(rc);
 }
@@ -3727,12 +4407,13 @@ static void mdt_stack_pre_fini(const struct lu_env *env,
         * by osd only doesn't have mdt/mdd slices -bzzz */
        lustre_cfg_bufs_reset(bufs, mdt_obd_name(m));
        lustre_cfg_bufs_set_string(bufs, 1, NULL);
-       lcfg = lustre_cfg_new(LCFG_PRE_CLEANUP, bufs);
-       if (lcfg == NULL)
+       OBD_ALLOC(lcfg, lustre_cfg_len(bufs->lcfg_bufcount, bufs->lcfg_buflen));
+       if (!lcfg)
                RETURN_EXIT;
+       lustre_cfg_init(lcfg, LCFG_PRE_CLEANUP, bufs);
 
        top->ld_ops->ldo_process_config(env, top, lcfg);
-       lustre_cfg_free(lcfg);
+       OBD_FREE(lcfg, lustre_cfg_len(lcfg->lcfg_bufcount, lcfg->lcfg_buflens));
        EXIT;
 }
 
@@ -3762,13 +4443,14 @@ static void mdt_stack_fini(const struct lu_env *env,
        if (obd->obd_fail)
                strcat(flags, "A");
        lustre_cfg_bufs_set_string(bufs, 1, flags);
-       lcfg = lustre_cfg_new(LCFG_CLEANUP, bufs);
-       if (lcfg == NULL)
+       OBD_ALLOC(lcfg, lustre_cfg_len(bufs->lcfg_bufcount, bufs->lcfg_buflen));
+       if (!lcfg)
                RETURN_EXIT;
+       lustre_cfg_init(lcfg, LCFG_CLEANUP, bufs);
 
        LASSERT(top);
        top->ld_ops->ldo_process_config(env, top, lcfg);
-       lustre_cfg_free(lcfg);
+       OBD_FREE(lcfg, lustre_cfg_len(lcfg->lcfg_bufcount, lcfg->lcfg_buflens));
 
        lu_site_purge(env, top->ld_site, -1);
 
@@ -3888,9 +4570,10 @@ static int mdt_stack_init(const struct lu_env *env, struct mdt_device *mdt,
        lustre_cfg_bufs_set_string(bufs, 2, uuid);
        lustre_cfg_bufs_set_string(bufs, 3, lprof->lp_dt);
 
-       lcfg = lustre_cfg_new(LCFG_ATTACH, bufs);
-       if (lcfg == NULL)
-               GOTO(free_bufs, rc = -ENOMEM);
+       OBD_ALLOC(lcfg, lustre_cfg_len(bufs->lcfg_bufcount, bufs->lcfg_buflen));
+       if (!lcfg)
+               GOTO(put_profile, rc = -ENOMEM);
+       lustre_cfg_init(lcfg, LCFG_ATTACH, bufs);
 
        rc = class_attach(lcfg);
        if (rc)
@@ -3903,16 +4586,17 @@ static int mdt_stack_init(const struct lu_env *env, struct mdt_device *mdt,
                GOTO(lcfg_cleanup, rc = -EINVAL);
        }
 
-       lustre_cfg_free(lcfg);
+       OBD_FREE(lcfg, lustre_cfg_len(lcfg->lcfg_bufcount, lcfg->lcfg_buflens));
 
        lustre_cfg_bufs_reset(bufs, name);
        lustre_cfg_bufs_set_string(bufs, 1, uuid);
        lustre_cfg_bufs_set_string(bufs, 2, dev);
        lustre_cfg_bufs_set_string(bufs, 3, lprof->lp_dt);
 
-       lcfg = lustre_cfg_new(LCFG_SETUP, bufs);
-       if (lcfg == NULL)
+       OBD_ALLOC(lcfg, lustre_cfg_len(bufs->lcfg_bufcount, bufs->lcfg_buflen));
+       if (!lcfg)
                GOTO(class_detach, rc = -ENOMEM);
+       lustre_cfg_init(lcfg, LCFG_SETUP, bufs);
 
        rc = class_setup(obd, lcfg);
        if (rc)
@@ -3949,7 +4633,9 @@ class_detach:
        if (rc)
                class_detach(obd, lcfg);
 lcfg_cleanup:
-       lustre_cfg_free(lcfg);
+       OBD_FREE(lcfg, lustre_cfg_len(lcfg->lcfg_bufcount, lcfg->lcfg_buflens));
+put_profile:
+       class_put_profile(lprof);
 free_bufs:
        OBD_FREE_PTR(bufs);
 cleanup_mem:
@@ -4018,9 +4704,10 @@ static int mdt_quota_init(const struct lu_env *env, struct mdt_device *mdt,
        lustre_cfg_bufs_set_string(bufs, 2, uuid);
        lustre_cfg_bufs_set_string(bufs, 3, lprof->lp_dt);
 
-       lcfg = lustre_cfg_new(LCFG_ATTACH, bufs);
-       if (lcfg == NULL)
-               GOTO(cleanup_mem, rc = -ENOMEM);
+       OBD_ALLOC(lcfg, lustre_cfg_len(bufs->lcfg_bufcount, bufs->lcfg_buflen));
+       if (!lcfg)
+               GOTO(put_profile, rc = -ENOMEM);
+       lustre_cfg_init(lcfg, LCFG_ATTACH, bufs);
 
        rc = class_attach(lcfg);
        if (rc)
@@ -4033,7 +4720,7 @@ static int mdt_quota_init(const struct lu_env *env, struct mdt_device *mdt,
                GOTO(lcfg_cleanup, rc = -EINVAL);
        }
 
-       lustre_cfg_free(lcfg);
+       OBD_FREE(lcfg, lustre_cfg_len(lcfg->lcfg_bufcount, lcfg->lcfg_buflens));
 
        lustre_cfg_bufs_reset(bufs, qmtname);
        lustre_cfg_bufs_set_string(bufs, 1, uuid);
@@ -4043,9 +4730,10 @@ static int mdt_quota_init(const struct lu_env *env, struct mdt_device *mdt,
        lustre_cfg_bufs_set_string(bufs, 3,
                                   mdt->mdt_bottom->dd_lu_dev.ld_obd->obd_name);
 
-       lcfg = lustre_cfg_new(LCFG_SETUP, bufs);
-       if (lcfg == NULL)
+       OBD_ALLOC(lcfg, lustre_cfg_len(bufs->lcfg_bufcount, bufs->lcfg_buflen));
+       if (!lcfg)
                GOTO(class_detach, rc = -ENOMEM);
+       lustre_cfg_init(lcfg, LCFG_SETUP, bufs);
 
        rc = class_setup(obd, lcfg);
        if (rc)
@@ -4081,7 +4769,9 @@ class_detach:
        if (rc)
                class_detach(obd, lcfg);
 lcfg_cleanup:
-       lustre_cfg_free(lcfg);
+       OBD_FREE(lcfg, lustre_cfg_len(lcfg->lcfg_bufcount, lcfg->lcfg_buflens));
+put_profile:
+       class_put_profile(lprof);
 cleanup_mem:
        if (bufs)
                OBD_FREE_PTR(bufs);
@@ -4124,6 +4814,11 @@ static int mdt_tgt_getxattr(struct tgt_session_info *tsi)
        return rc;
 }
 
+#define OBD_FAIL_OST_READ_NET  OBD_FAIL_OST_BRW_NET
+#define OBD_FAIL_OST_WRITE_NET OBD_FAIL_OST_BRW_NET
+#define OST_BRW_READ   OST_READ
+#define OST_BRW_WRITE  OST_WRITE
+
 static struct tgt_handler mdt_tgt_handlers[] = {
 TGT_RPC_HANDLER(MDS_FIRST_OPC,
                0,                      MDS_CONNECT,    mdt_tgt_connect,
@@ -4135,7 +4830,7 @@ TGT_RPC_HANDLER(MDS_FIRST_OPC,
                HABEO_REFERO,           MDS_SET_INFO,   mdt_set_info,
                &RQF_OBD_SET_INFO, LUSTRE_MDS_VERSION),
 TGT_MDT_HDL(0,                         MDS_GET_INFO,   mdt_get_info),
-TGT_MDT_HDL(0          | HABEO_REFERO, MDS_GETSTATUS,  mdt_getstatus),
+TGT_MDT_HDL(0          | HABEO_REFERO, MDS_GET_ROOT,   mdt_get_root),
 TGT_MDT_HDL(HABEO_CORPUS,              MDS_GETATTR,    mdt_getattr),
 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO,        MDS_GETATTR_NAME,
                                                        mdt_getattr_name),
@@ -4164,6 +4859,14 @@ TGT_MDT_HDL(HABEO_CLAVIS | HABEO_CORPUS | HABEO_REFERO | MUTABOR,
            mdt_swap_layouts),
 };
 
+static struct tgt_handler mdt_io_ops[] = {
+TGT_OST_HDL(HABEO_CORPUS | HABEO_REFERO, OST_BRW_READ, tgt_brw_read),
+TGT_OST_HDL(HABEO_CORPUS | MUTABOR,     OST_BRW_WRITE, tgt_brw_write),
+TGT_OST_HDL(HABEO_CORPUS | HABEO_REFERO | MUTABOR,
+                                        OST_PUNCH,     mdt_punch_hdl),
+TGT_OST_HDL(HABEO_CORPUS | HABEO_REFERO, OST_SYNC,     mdt_data_sync),
+};
+
 static struct tgt_handler mdt_sec_ctx_ops[] = {
 TGT_SEC_HDL_VAR(0,                     SEC_CTX_INIT,     mdt_sec_ctx_handle),
 TGT_SEC_HDL_VAR(0,                     SEC_CTX_INIT_CONT,mdt_sec_ctx_handle),
@@ -4225,7 +4928,11 @@ static struct tgt_opc_slice mdt_common_slice[] = {
                .tos_opc_end    = LFSCK_LAST_OPC,
                .tos_hs         = tgt_lfsck_handlers
        },
-
+       {
+               .tos_opc_start  = OST_FIRST_OPC,
+               .tos_opc_end    = OST_LAST_OPC,
+               .tos_hs         = mdt_io_ops
+       },
        {
                .tos_hs         = NULL
        }
@@ -4233,53 +4940,66 @@ static struct tgt_opc_slice mdt_common_slice[] = {
 
 static void mdt_fini(const struct lu_env *env, struct mdt_device *m)
 {
-       struct md_device        *next = m->mdt_child;
-       struct lu_device        *d    = &m->mdt_lu_dev;
-       struct obd_device       *obd  = mdt2obd_dev(m);
-       struct lfsck_stop        stop;
-       ENTRY;
+       struct md_device *next = m->mdt_child;
+       struct lu_device *d = &m->mdt_lu_dev;
+       struct obd_device *obd = mdt2obd_dev(m);
+       struct lfsck_stop stop;
 
+       ENTRY;
        stop.ls_status = LS_PAUSED;
        stop.ls_flags = 0;
        next->md_ops->mdo_iocontrol(env, next, OBD_IOC_STOP_LFSCK, 0, &stop);
 
        mdt_stack_pre_fini(env, m, md2lu_dev(m->mdt_child));
-       target_recovery_fini(obd);
        ping_evictor_stop();
 
-       if (m->mdt_opts.mo_coordinator)
-               mdt_hsm_cdt_stop(m);
-
-       mdt_hsm_cdt_fini(m);
+       /* Remove the HSM /proc entry so the coordinator cannot be
+        * restarted by a user while it's shutting down. */
+       hsm_cdt_procfs_fini(m);
+       mdt_hsm_cdt_stop(m);
 
        mdt_llog_ctxt_unclone(env, m, LLOG_AGENT_ORIG_CTXT);
-        mdt_llog_ctxt_unclone(env, m, LLOG_CHANGELOG_ORIG_CTXT);
+       mdt_llog_ctxt_unclone(env, m, LLOG_CHANGELOG_ORIG_CTXT);
 
        if (m->mdt_namespace != NULL)
                ldlm_namespace_free_prior(m->mdt_namespace, NULL,
                                          d->ld_obd->obd_force);
 
-        obd_exports_barrier(obd);
-        obd_zombie_barrier();
+       obd_exports_barrier(obd);
+       obd_zombie_barrier();
+
+       mdt_quota_fini(env, m);
+
+       cfs_free_nidlist(&m->mdt_squash.rsi_nosquash_nids);
+
+       /* Calling the cleanup functions in the same order as in the mdt_init0
+        * error path
+        */
+       mdt_procfs_fini(m);
+
+       target_recovery_fini(obd);
+       upcall_cache_cleanup(m->mdt_identity_cache);
+       m->mdt_identity_cache = NULL;
+
+       mdt_fs_cleanup(env, m);
 
-        mdt_procfs_fini(m);
+       tgt_fini(env, &m->mdt_lut);
 
-        tgt_fini(env, &m->mdt_lut);
-        mdt_fs_cleanup(env, m);
-        upcall_cache_cleanup(m->mdt_identity_cache);
-        m->mdt_identity_cache = NULL;
+       mdt_hsm_cdt_fini(m);
 
        if (m->mdt_namespace != NULL) {
                ldlm_namespace_free_post(m->mdt_namespace);
                d->ld_obd->obd_namespace = m->mdt_namespace = NULL;
        }
 
-       mdt_quota_fini(env, m);
+       if (m->mdt_md_root != NULL) {
+               mdt_object_put(env, m->mdt_md_root);
+               m->mdt_md_root = NULL;
+       }
 
-       cfs_free_nidlist(&m->mdt_squash.rsi_nosquash_nids);
+       mdt_seq_fini(env, m);
 
-        mdt_seq_fini(env, m);
-        mdt_fld_fini(env, m);
+       mdt_fld_fini(env, m);
 
        /*
         * Finish the stack
@@ -4296,71 +5016,77 @@ static void mdt_fini(const struct lu_env *env, struct mdt_device *m)
 static int mdt_postrecov(const struct lu_env *, struct mdt_device *);
 
 static int mdt_init0(const struct lu_env *env, struct mdt_device *m,
-                     struct lu_device_type *ldt, struct lustre_cfg *cfg)
-{
-        struct mdt_thread_info    *info;
-        struct obd_device         *obd;
-        const char                *dev = lustre_cfg_string(cfg, 0);
-        const char                *num = lustre_cfg_string(cfg, 2);
-        struct lustre_mount_info  *lmi = NULL;
-        struct lustre_sb_info     *lsi;
-        struct lu_site            *s;
-       struct seq_server_site    *ss_site;
-        const char                *identity_upcall = "NONE";
-        struct md_device          *next;
-        int                        rc;
-       long                       node_id;
-        mntopt_t                   mntopts;
-        ENTRY;
+                    struct lu_device_type *ldt, struct lustre_cfg *cfg)
+{
+       const struct dt_device_param *dt_conf;
+       struct mdt_thread_info *info;
+       struct obd_device *obd;
+       const char *dev = lustre_cfg_string(cfg, 0);
+       const char *num = lustre_cfg_string(cfg, 2);
+       struct tg_grants_data *tgd = &m->mdt_lut.lut_tgd;
+       struct lustre_mount_info *lmi = NULL;
+       struct lustre_sb_info *lsi;
+       struct lu_site *s;
+       struct seq_server_site *ss_site;
+       const char *identity_upcall = "NONE";
+       struct md_device *next;
+       int rc;
+       long node_id;
+       mntopt_t mntopts;
+       ENTRY;
 
        lu_device_init(&m->mdt_lu_dev, ldt);
-        /*
-         * Environment (env) might be missing mdt_thread_key values at that
-         * point, if device is allocated when mdt_thread_key is in QUIESCENT
-         * mode.
-         *
-         * Usually device allocation path doesn't use module key values, but
-         * mdt has to do a lot of work here, so allocate key value.
-         */
-        rc = lu_env_refill((struct lu_env *)env);
-        if (rc != 0)
-                RETURN(rc);
-
-        info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
-        LASSERT(info != NULL);
-
-        obd = class_name2obd(dev);
-        LASSERT(obd != NULL);
+       /*
+        * Environment (env) might be missing mdt_thread_key values at that
+        * point, if device is allocated when mdt_thread_key is in QUIESCENT
+        * mode.
+        *
+        * Usually device allocation path doesn't use module key values, but
+        * mdt has to do a lot of work here, so allocate key value.
+        */
+       rc = lu_env_refill((struct lu_env *)env);
+       if (rc != 0)
+               RETURN(rc);
 
-        m->mdt_max_mdsize = MAX_MD_SIZE; /* 4 stripes */
+       info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
+       LASSERT(info != NULL);
 
-        m->mdt_opts.mo_cos = MDT_COS_DEFAULT;
+       obd = class_name2obd(dev);
+       LASSERT(obd != NULL);
 
-       /* default is coordinator off, it is started through conf_param
-        * or /proc */
-       m->mdt_opts.mo_coordinator = 0;
+       m->mdt_max_mdsize = MAX_MD_SIZE; /* 4 stripes */
+       m->mdt_opts.mo_evict_tgt_nids = 1;
+       m->mdt_opts.mo_cos = MDT_COS_DEFAULT;
 
        lmi = server_get_mount(dev);
-        if (lmi == NULL) {
-                CERROR("Cannot get mount info for %s!\n", dev);
-                RETURN(-EFAULT);
-        } else {
-                lsi = s2lsi(lmi->lmi_sb);
-                /* CMD is supported only in IAM mode */
-                LASSERT(num);
-                node_id = simple_strtol(num, NULL, 10);
+       if (lmi == NULL) {
+               CERROR("Cannot get mount info for %s!\n", dev);
+               RETURN(-EFAULT);
+       } else {
+               lsi = s2lsi(lmi->lmi_sb);
+               /* CMD is supported only in IAM mode */
+               LASSERT(num);
+               node_id = simple_strtol(num, NULL, 10);
                obd->u.obt.obt_magic = OBT_MAGIC;
+               if (lsi->lsi_lmd != NULL &&
+                   lsi->lsi_lmd->lmd_flags & LMD_FLG_SKIP_LFSCK)
+                       m->mdt_skip_lfsck = 1;
        }
 
+       /* DoM files get IO lock at open by default */
+       m->mdt_opts.mo_dom_lock = 1;
+
        m->mdt_squash.rsi_uid = 0;
        m->mdt_squash.rsi_gid = 0;
        INIT_LIST_HEAD(&m->mdt_squash.rsi_nosquash_nids);
        init_rwsem(&m->mdt_squash.rsi_sem);
-       spin_lock_init(&m->mdt_osfs_lock);
-       m->mdt_osfs_age = cfs_time_shift_64(-1000);
+       spin_lock_init(&m->mdt_lock);
        m->mdt_enable_remote_dir = 0;
        m->mdt_enable_remote_dir_gid = 0;
 
+       atomic_set(&m->mdt_mds_mds_conns, 0);
+       atomic_set(&m->mdt_async_commit_count, 0);
+
        m->mdt_lu_dev.ld_ops = &mdt_lu_ops;
        m->mdt_lu_dev.ld_obd = obd;
        /* Set this lu_device to obd for error handling purposes. */
@@ -4379,16 +5105,16 @@ static int mdt_init0(const struct lu_env *env, struct mdt_device *m,
        s->ld_seq_site = ss_site;
        ss_site->ss_lu = s;
 
-        /* set server index */
+       /* set server index */
        ss_site->ss_node_id = node_id;
 
        /* failover is the default
         * FIXME: we do not failout mds0/mgs, which may cause some problems.
         * assumed whose ss_node_id == 0 XXX
         * */
-        obd->obd_replayable = 1;
-        /* No connection accepted until configurations will finish */
-        obd->obd_no_conn = 1;
+       obd->obd_replayable = 1;
+       /* No connection accepted until configurations will finish */
+       obd->obd_no_conn = 1;
 
        if (cfg->lcfg_bufcount > 4 && LUSTRE_CFG_BUFLEN(cfg, 4) > 0) {
                char *str = lustre_cfg_string(cfg, 4);
@@ -4408,25 +5134,25 @@ static int mdt_init0(const struct lu_env *env, struct mdt_device *m,
 
        snprintf(info->mti_u.ns_name, sizeof(info->mti_u.ns_name), "%s-%s",
                 LUSTRE_MDT_NAME, obd->obd_uuid.uuid);
-        m->mdt_namespace = ldlm_namespace_new(obd, info->mti_u.ns_name,
-                                              LDLM_NAMESPACE_SERVER,
-                                              LDLM_NAMESPACE_GREEDY,
-                                              LDLM_NS_TYPE_MDT);
-        if (m->mdt_namespace == NULL)
-                GOTO(err_fini_seq, rc = -ENOMEM);
+       m->mdt_namespace = ldlm_namespace_new(obd, info->mti_u.ns_name,
+                                             LDLM_NAMESPACE_SERVER,
+                                             LDLM_NAMESPACE_GREEDY,
+                                             LDLM_NS_TYPE_MDT);
+       if (m->mdt_namespace == NULL)
+               GOTO(err_fini_seq, rc = -ENOMEM);
 
        m->mdt_namespace->ns_lvbp = m;
        m->mdt_namespace->ns_lvbo = &mdt_lvbo;
 
-        ldlm_register_intent(m->mdt_namespace, mdt_intent_policy);
-        /* set obd_namespace for compatibility with old code */
-        obd->obd_namespace = m->mdt_namespace;
+       ldlm_register_intent(m->mdt_namespace, mdt_intent_policy);
+       /* set obd_namespace for compatibility with old code */
+       obd->obd_namespace = m->mdt_namespace;
 
        rc = mdt_hsm_cdt_init(m);
        if (rc != 0) {
                CERROR("%s: error initializing coordinator, rc %d\n",
                       mdt_obd_name(m), rc);
-                GOTO(err_free_ns, rc);
+               GOTO(err_free_ns, rc);
        }
 
        rc = tgt_init(env, &m->mdt_lut, obd, m->mdt_bottom, mdt_common_slice,
@@ -4435,31 +5161,37 @@ static int mdt_init0(const struct lu_env *env, struct mdt_device *m,
        if (rc)
                GOTO(err_free_hsm, rc);
 
+       /* Amount of available space excluded from granting and reserved
+        * for metadata. It is in percentage and 50% is default value. */
+       tgd->tgd_reserved_pcnt = 50;
+
+       if (ONE_MB_BRW_SIZE < (1U << tgd->tgd_blockbits))
+               m->mdt_brw_size = 1U << tgd->tgd_blockbits;
+       else
+               m->mdt_brw_size = ONE_MB_BRW_SIZE;
+
        rc = mdt_fs_setup(env, m, obd, lsi);
        if (rc)
                GOTO(err_tgt, rc);
 
-       tgt_adapt_sptlrpc_conf(&m->mdt_lut, 1);
+       tgt_adapt_sptlrpc_conf(&m->mdt_lut);
 
-        next = m->mdt_child;
-        rc = next->md_ops->mdo_iocontrol(env, next, OBD_IOC_GET_MNTOPT, 0,
-                                         &mntopts);
-        if (rc)
-               GOTO(err_fs_cleanup, rc);
+       next = m->mdt_child;
+       dt_conf = next->md_ops->mdo_dtconf_get(env, next);
 
-        if (mntopts & MNTOPT_USERXATTR)
-                m->mdt_opts.mo_user_xattr = 1;
-        else
-                m->mdt_opts.mo_user_xattr = 0;
+       mntopts = dt_conf->ddp_mntopts;
 
-       rc = next->md_ops->mdo_maxeasize_get(env, next, &m->mdt_max_ea_size);
-       if (rc)
-               GOTO(err_fs_cleanup, rc);
+       if (mntopts & MNTOPT_USERXATTR)
+               m->mdt_opts.mo_user_xattr = 1;
+       else
+               m->mdt_opts.mo_user_xattr = 0;
 
-        if (mntopts & MNTOPT_ACL)
-                m->mdt_opts.mo_acl = 1;
-        else
-                m->mdt_opts.mo_acl = 0;
+       m->mdt_max_ea_size = dt_conf->ddp_max_ea_size;
+
+       if (mntopts & MNTOPT_ACL)
+               m->mdt_opts.mo_acl = 1;
+       else
+               m->mdt_opts.mo_acl = 0;
 
        /* XXX: to support suppgid for ACL, we enable identity_upcall
         * by default, otherwise, maybe got unexpected -EACCESS. */
@@ -4475,11 +5207,11 @@ static int mdt_init0(const struct lu_env *env, struct mdt_device *m,
                GOTO(err_fs_cleanup, rc);
        }
 
-        rc = mdt_procfs_init(m, dev);
-        if (rc) {
-                CERROR("Can't init MDT lprocfs, rc %d\n", rc);
-                GOTO(err_recovery, rc);
-        }
+       rc = mdt_procfs_init(m, dev);
+       if (rc) {
+               CERROR("Can't init MDT lprocfs, rc %d\n", rc);
+               GOTO(err_recovery, rc);
+       }
 
        rc = mdt_quota_init(env, m, cfg);
        if (rc)
@@ -4495,13 +5227,13 @@ static int mdt_init0(const struct lu_env *env, struct mdt_device *m,
         * when the whole stack is complete and ready
         * to serve the requests */
 
-        /* Reduce the initial timeout on an MDS because it doesn't need such
-         * a long timeout as an OST does. Adaptive timeouts will adjust this
-         * value appropriately. */
-        if (ldlm_timeout == LDLM_TIMEOUT_DEFAULT)
-                ldlm_timeout = MDS_LDLM_TIMEOUT_DEFAULT;
+       /* Reduce the initial timeout on an MDS because it doesn't need such
+        * a long timeout as an OST does. Adaptive timeouts will adjust this
+        * value appropriately. */
+       if (ldlm_timeout == LDLM_TIMEOUT_DEFAULT)
+               ldlm_timeout = MDS_LDLM_TIMEOUT_DEFAULT;
 
-        RETURN(0);
+       RETURN(0);
 err_procfs:
        mdt_procfs_fini(m);
 err_recovery:
@@ -4536,6 +5268,7 @@ static struct cfg_interop_param mdt_interop_param[] = {
        { "mdt.group_upcall",   NULL },
        { "mdt.quota_type",     NULL },
        { "mdd.quota_type",     NULL },
+       { "mdt.som",            NULL },
        { "mdt.rootsquash",     "mdt.root_squash" },
        { "mdt.nosquash_nid",   "mdt.nosquash_nids" },
        { NULL }
@@ -4600,9 +5333,9 @@ static int mdt_process_config(const struct lu_env *env,
                                                                      cfg);
                }
 
-               if (old_cfg != NULL)
-                       lustre_cfg_free(cfg);
-
+               if (old_cfg)
+                       OBD_FREE(cfg, lustre_cfg_len(cfg->lcfg_bufcount,
+                                                    cfg->lcfg_buflens));
                break;
        }
         default:
@@ -4634,7 +5367,9 @@ static struct lu_object *mdt_object_alloc(const struct lu_env *env,
                o->lo_ops = &mdt_obj_ops;
                spin_lock_init(&mo->mot_write_lock);
                mutex_init(&mo->mot_lov_mutex);
+               init_rwsem(&mo->mot_dom_sem);
                init_rwsem(&mo->mot_open_sem);
+               atomic_set(&mo->mot_open_count, 0);
                RETURN(o);
        }
        RETURN(NULL);
@@ -4688,8 +5423,10 @@ static int mdt_object_print(const struct lu_env *env, void *cookie,
        struct mdt_object *mdto = mdt_obj((struct lu_object *)o);
 
        return (*p)(env, cookie,
-                   LUSTRE_MDT_NAME"-object@%p(flags=%d, writecount=%d)",
-                   mdto, mdto->mot_flags, mdto->mot_write_count);
+                   LUSTRE_MDT_NAME"-object@%p(%s %s, writecount=%d)",
+                   mdto, mdto->mot_lov_created ? "lov_created" : "",
+                   mdto->mot_cache_attr ? "cache_attr" : "",
+                   mdto->mot_write_count);
 }
 
 static int mdt_prepare(const struct lu_env *env,
@@ -4767,7 +5504,7 @@ static int mdt_obd_set_info_async(const struct lu_env *env,
        ENTRY;
 
        if (KEY_IS(KEY_SPTLRPC_CONF)) {
-               rc = tgt_adapt_sptlrpc_conf(class_exp2tgt(exp), 0);
+               rc = tgt_adapt_sptlrpc_conf(class_exp2tgt(exp));
                RETURN(rc);
        }
 
@@ -4787,6 +5524,10 @@ static int mdt_obd_set_info_async(const struct lu_env *env,
  * connect flags from the obd_connect_data::ocd_connect_flags field of the
  * reply. \see mdt_connect().
  *
+ * Before 2.7.50 clients will send a struct obd_connect_data_v1 rather than a
+ * full struct obd_connect_data. So care must be taken when accessing fields
+ * that are not present in struct obd_connect_data_v1. See LU-16.
+ *
  * \param exp   the obd_export associated with this client/target pair
  * \param mdt   the target device for the connection
  * \param data  stores data for this connect request
@@ -4795,19 +5536,29 @@ static int mdt_obd_set_info_async(const struct lu_env *env,
  * \retval -EPROTO \a data unexpectedly has zero obd_connect_data::ocd_brw_size
  * \retval -EBADE  client and server feature requirements are incompatible
  */
-static int mdt_connect_internal(struct obd_export *exp,
+static int mdt_connect_internal(const struct lu_env *env,
+                               struct obd_export *exp,
                                struct mdt_device *mdt,
-                               struct obd_connect_data *data)
+                               struct obd_connect_data *data, bool reconnect)
 {
        LASSERT(data != NULL);
 
        data->ocd_connect_flags &= MDT_CONNECT_SUPPORTED;
+
+       if (mdt->mdt_bottom->dd_rdonly &&
+           !(data->ocd_connect_flags & OBD_CONNECT_MDS_MDS) &&
+           !(data->ocd_connect_flags & OBD_CONNECT_RDONLY))
+               RETURN(-EACCES);
+
+       if (data->ocd_connect_flags & OBD_CONNECT_FLAGS2)
+               data->ocd_connect_flags2 &= MDT_CONNECT_SUPPORTED2;
+
        data->ocd_ibits_known &= MDS_INODELOCK_FULL;
 
        if (!(data->ocd_connect_flags & OBD_CONNECT_MDS_MDS) &&
            !(data->ocd_connect_flags & OBD_CONNECT_IBITS)) {
                CWARN("%s: client %s does not support ibits lock, either "
-                     "very old or an invalid client: flags "LPX64"\n",
+                     "very old or an invalid client: flags %#llx\n",
                      mdt_obd_name(mdt), exp->exp_client_uuid.uuid,
                      data->ocd_connect_flags);
                return -EBADE;
@@ -4819,16 +5570,14 @@ static int mdt_connect_internal(struct obd_export *exp,
        if (!mdt->mdt_opts.mo_user_xattr)
                data->ocd_connect_flags &= ~OBD_CONNECT_XATTR;
 
-       if (data->ocd_connect_flags & OBD_CONNECT_BRW_SIZE) {
+       if (OCD_HAS_FLAG(data, BRW_SIZE)) {
                data->ocd_brw_size = min(data->ocd_brw_size,
-                                        (__u32)MD_MAX_BRW_SIZE);
+                                        mdt->mdt_brw_size);
                if (data->ocd_brw_size == 0) {
-                       CERROR("%s: cli %s/%p ocd_connect_flags: "LPX64
-                              " ocd_version: %x ocd_grant: %d "
-                              "ocd_index: %u ocd_brw_size is "
-                              "unexpectedly zero, network data "
-                              "corruption? Refusing connection of this"
-                              " client\n",
+                       CERROR("%s: cli %s/%p ocd_connect_flags: %#llx "
+                              "ocd_version: %x ocd_grant: %d ocd_index: %u "
+                              "ocd_brw_size unexpectedly zero, network data "
+                              "corruption? Refusing to connect this client\n",
                               mdt_obd_name(mdt),
                               exp->exp_client_uuid.uuid,
                               exp, data->ocd_connect_flags, data->ocd_version,
@@ -4837,6 +5586,30 @@ static int mdt_connect_internal(struct obd_export *exp,
                }
        }
 
+       if (OCD_HAS_FLAG(data, GRANT_PARAM)) {
+               struct dt_device_param *ddp = &mdt->mdt_lut.lut_dt_conf;
+
+               /* client is reporting its page size, for future use */
+               exp->exp_target_data.ted_pagebits = data->ocd_grant_blkbits;
+               data->ocd_grant_blkbits  = mdt->mdt_lut.lut_tgd.tgd_blockbits;
+               /* ddp_inodespace may not be power-of-two value, eg. for ldiskfs
+                * it's LDISKFS_DIR_REC_LEN(20) = 28. */
+               data->ocd_grant_inobits = fls(ddp->ddp_inodespace - 1);
+               /* ocd_grant_tax_kb is in 1K byte blocks */
+               data->ocd_grant_tax_kb = ddp->ddp_extent_tax >> 10;
+               data->ocd_grant_max_blks = ddp->ddp_max_extent_blks;
+       }
+
+       if (OCD_HAS_FLAG(data, GRANT)) {
+               /* Save connect_data we have so far because tgt_grant_connect()
+                * uses it to calculate grant. */
+               exp->exp_connect_data = *data;
+               tgt_grant_connect(env, exp, data, !reconnect);
+       }
+
+       if (OCD_HAS_FLAG(data, MAXBYTES))
+               data->ocd_maxbytes = mdt->mdt_lut.lut_dt_conf.ddp_maxbytes;
+
        /* NB: Disregard the rule against updating
         * exp_connect_data.ocd_connect_flags in this case, since
         * tgt_client_new() needs to know if this is a lightweight
@@ -4880,6 +5653,32 @@ static int mdt_connect_internal(struct obd_export *exp,
                spin_unlock(&exp->exp_lock);
        }
 
+       if (OCD_HAS_FLAG(data, CKSUM)) {
+               __u32 cksum_types = data->ocd_cksum_types;
+
+               /* The client set in ocd_cksum_types the checksum types it
+                * supports. We have to mask off the algorithms that we don't
+                * support */
+               data->ocd_cksum_types &= cksum_types_supported_server();
+
+               if (unlikely(data->ocd_cksum_types == 0)) {
+                       CERROR("%s: Connect with checksum support but no "
+                              "ocd_cksum_types is set\n",
+                              exp->exp_obd->obd_name);
+                       RETURN(-EPROTO);
+               }
+
+               CDEBUG(D_RPCTRACE, "%s: cli %s supports cksum type %x, return "
+                      "%x\n", exp->exp_obd->obd_name, obd_export_nid2str(exp),
+                      cksum_types, data->ocd_cksum_types);
+       } else {
+               /* This client does not support OBD_CONNECT_CKSUM
+                * fall back to CRC32 */
+               CDEBUG(D_RPCTRACE, "%s: cli %s does not support "
+                      "OBD_CONNECT_CKSUM, CRC32 will be used\n",
+                      exp->exp_obd->obd_name, obd_export_nid2str(exp));
+       }
+
        return 0;
 }
 
@@ -4990,20 +5789,46 @@ static int mdt_export_cleanup(struct obd_export *exp)
         RETURN(rc);
 }
 
+static inline void mdt_enable_slc(struct mdt_device *mdt)
+{
+       if (mdt->mdt_lut.lut_sync_lock_cancel == NEVER_SYNC_ON_CANCEL)
+               mdt->mdt_lut.lut_sync_lock_cancel = BLOCKING_SYNC_ON_CANCEL;
+}
+
+static inline void mdt_disable_slc(struct mdt_device *mdt)
+{
+       if (mdt->mdt_lut.lut_sync_lock_cancel == BLOCKING_SYNC_ON_CANCEL)
+               mdt->mdt_lut.lut_sync_lock_cancel = NEVER_SYNC_ON_CANCEL;
+}
+
 static int mdt_obd_disconnect(struct obd_export *exp)
 {
-        int rc;
-        ENTRY;
+       int rc;
+
+       ENTRY;
 
-        LASSERT(exp);
-        class_export_get(exp);
+       LASSERT(exp);
+       class_export_get(exp);
+
+       if (!(exp->exp_flags & OBD_OPT_FORCE))
+               tgt_grant_sanity_check(exp->exp_obd, __func__);
+
+       if ((exp_connect_flags(exp) & OBD_CONNECT_MDS_MDS) &&
+           !(exp_connect_flags(exp) & OBD_CONNECT_LIGHTWEIGHT)) {
+               struct mdt_device *mdt = mdt_dev(exp->exp_obd->obd_lu_dev);
+
+               if (atomic_dec_and_test(&mdt->mdt_mds_mds_conns))
+                       mdt_disable_slc(mdt);
+       }
 
-       nodemap_del_member(exp);
        rc = server_disconnect_export(exp);
        if (rc != 0)
                CDEBUG(D_IOCTL, "server disconnect error: rc = %d\n", rc);
 
+       tgt_grant_discard(exp);
+
        rc = mdt_export_cleanup(exp);
+       nodemap_del_member(exp);
        class_export_put(exp);
        RETURN(rc);
 }
@@ -5023,17 +5848,25 @@ static int mdt_obd_connect(const struct lu_env *env,
        ENTRY;
 
        LASSERT(env != NULL);
+       LASSERT(data != NULL);
+
        if (!exp || !obd || !cluuid)
                RETURN(-EINVAL);
 
        mdt = mdt_dev(obd->obd_lu_dev);
 
+       if ((data->ocd_connect_flags & OBD_CONNECT_MDS_MDS) &&
+           !(data->ocd_connect_flags & OBD_CONNECT_LIGHTWEIGHT)) {
+               atomic_inc(&mdt->mdt_mds_mds_conns);
+               mdt_enable_slc(mdt);
+       }
+
        /*
         * first, check whether the stack is ready to handle requests
         * XXX: probably not very appropriate method is used now
         *      at some point we should find a better one
         */
-       if (!test_bit(MDT_FL_SYNCED, &mdt->mdt_state) && data != NULL &&
+       if (!test_bit(MDT_FL_SYNCED, &mdt->mdt_state) &&
            !(data->ocd_connect_flags & OBD_CONNECT_LIGHTWEIGHT) &&
            !(data->ocd_connect_flags & OBD_CONNECT_MDS_MDS)) {
                rc = obd_get_info(env, mdt->mdt_child_exp,
@@ -5051,27 +5884,34 @@ static int mdt_obd_connect(const struct lu_env *env,
        lexp = class_conn2export(&conn);
        LASSERT(lexp != NULL);
 
-       rc = mdt_connect_internal(lexp, mdt, data);
+       rc = nodemap_add_member(*client_nid, lexp);
+       if (rc != 0 && rc != -EEXIST)
+               GOTO(out, rc);
+
+       rc = mdt_connect_internal(env, lexp, mdt, data, false);
        if (rc == 0) {
                struct lsd_client_data *lcd = lexp->exp_target_data.ted_lcd;
 
                LASSERT(lcd);
                memcpy(lcd->lcd_uuid, cluuid, sizeof lcd->lcd_uuid);
                rc = tgt_client_new(env, lexp);
-               if (rc == 0) {
-                       rc = nodemap_add_member(*client_nid, lexp);
-                       if (rc != 0 && rc != -EEXIST)
-                               goto out;
-
+               if (rc == 0)
                        mdt_export_stats_init(obd, lexp, localdata);
-               }
        }
 out:
        if (rc != 0) {
                class_disconnect(lexp);
+               nodemap_del_member(lexp);
                *exp = NULL;
        } else {
                *exp = lexp;
+               /* Because we do not want this export to be evicted by pinger,
+                * let's not add this export to the timed chain list. */
+               if (data->ocd_connect_flags & OBD_CONNECT_MDS_MDS) {
+                       spin_lock(&lexp->exp_obd->obd_dev_lock);
+                       list_del_init(&lexp->exp_obd_chain_timed);
+                       spin_unlock(&lexp->exp_obd->obd_dev_lock);
+               }
        }
 
        RETURN(rc);
@@ -5090,12 +5930,16 @@ static int mdt_obd_reconnect(const struct lu_env *env,
        if (exp == NULL || obd == NULL || cluuid == NULL)
                RETURN(-EINVAL);
 
-       rc = mdt_connect_internal(exp, mdt_dev(obd->obd_lu_dev), data);
-       if (rc == 0) {
-               rc = nodemap_add_member(*client_nid, exp);
-               if (rc == 0 || rc == -EEXIST)
-                       mdt_export_stats_init(obd, exp, localdata);
-       }
+       rc = nodemap_add_member(*client_nid, exp);
+       if (rc != 0 && rc != -EEXIST)
+               RETURN(rc);
+
+       rc = mdt_connect_internal(env, exp, mdt_dev(obd->obd_lu_dev), data,
+                                 true);
+       if (rc == 0)
+               mdt_export_stats_init(obd, exp, localdata);
+       else
+               nodemap_del_member(exp);
 
        RETURN(rc);
 }
@@ -5109,8 +5953,6 @@ static int mdt_init_export(struct obd_export *exp)
 
        INIT_LIST_HEAD(&med->med_open_head);
        spin_lock_init(&med->med_open_lock);
-       mutex_init(&med->med_idmap_mutex);
-       med->med_idmap = NULL;
        spin_lock(&exp->exp_lock);
        exp->exp_connecting = 1;
        spin_unlock(&exp->exp_lock);
@@ -5142,9 +5984,6 @@ static int mdt_destroy_export(struct obd_export *exp)
 {
         ENTRY;
 
-        if (exp_connect_rmtclient(exp))
-                mdt_cleanup_idmap(&exp->exp_mdt_data);
-
         target_destroy_export(exp);
         /* destroy can be called from failed obd_setup, so
          * checking uuid is safer than obd_self_export */
@@ -5158,6 +5997,17 @@ static int mdt_destroy_export(struct obd_export *exp)
        LASSERT(list_empty(&exp->exp_outstanding_replies));
        LASSERT(list_empty(&exp->exp_mdt_data.med_open_head));
 
+       /*
+        * discard grants once we're sure no more
+        * interaction with the client is possible
+        */
+       tgt_grant_discard(exp);
+       if (exp_connect_flags(exp) & OBD_CONNECT_GRANT)
+               exp->exp_obd->u.obt.obt_lut->lut_tgd.tgd_tot_granted_clients--;
+
+       if (!(exp->exp_flags & OBD_OPT_FORCE))
+               tgt_grant_sanity_check(exp->exp_obd, __func__);
+
        RETURN(0);
 }
 
@@ -5189,7 +6039,7 @@ int mdt_links_read(struct mdt_thread_info *info, struct mdt_object *mdt_obj,
        if (rc < 0)
                return rc;
 
-       return linkea_init(ldata);
+       return linkea_init_with_rec(ldata);
 }
 
 /**
@@ -5199,6 +6049,7 @@ int mdt_links_read(struct mdt_thread_info *info, struct mdt_object *mdt_obj,
  * \param[in]     info  Per-thread common data shared by MDT level handlers.
  * \param[in]     obj   Object to do path lookup of
  * \param[in,out] fp    User-provided struct to store path information
+ * \param[in]     root_fid Root FID of current path should reach
  *
  * \retval 0 Lookup successful, path information stored in fp
  * \retval -EAGAIN Lookup failed, usually because object is being moved
@@ -5206,7 +6057,8 @@ int mdt_links_read(struct mdt_thread_info *info, struct mdt_object *mdt_obj,
  */
 static int mdt_path_current(struct mdt_thread_info *info,
                            struct mdt_object *obj,
-                           struct getinfo_fid2path *fp)
+                           struct getinfo_fid2path *fp,
+                           struct lu_fid *root_fid)
 {
        struct mdt_device       *mdt = info->mti_mdt;
        struct mdt_object       *mdt_obj;
@@ -5229,19 +6081,26 @@ static int mdt_path_current(struct mdt_thread_info *info,
                RETURN(-ENOMEM);
 
        ldata.ld_buf = buf;
-       ptr = fp->gf_path + fp->gf_pathlen - 1;
+       ptr = fp->gf_u.gf_path + fp->gf_pathlen - 1;
        *ptr = 0;
        --ptr;
        *tmpfid = fp->gf_fid = *mdt_object_fid(obj);
 
-       /* root FID only exists on MDT0, and fid2path should also ends at MDT0,
-        * so checking root_fid can only happen on MDT0. */
-       while (!lu_fid_eq(&mdt->mdt_md_root_fid, &fp->gf_fid)) {
+       while (!lu_fid_eq(root_fid, &fp->gf_fid)) {
                struct lu_buf           lmv_buf;
 
-               mdt_obj = mdt_object_find(info->mti_env, mdt, tmpfid);
-               if (IS_ERR(mdt_obj))
-                       GOTO(out, rc = PTR_ERR(mdt_obj));
+               if (!lu_fid_eq(root_fid, &mdt->mdt_md_root_fid) &&
+                   lu_fid_eq(&mdt->mdt_md_root_fid, &fp->gf_fid))
+                       GOTO(out, rc = -ENOENT);
+
+               if (lu_fid_eq(mdt_object_fid(obj), tmpfid)) {
+                       mdt_obj = obj;
+                       mdt_object_get(info->mti_env, mdt_obj);
+               } else {
+                       mdt_obj = mdt_object_find(info->mti_env, mdt, tmpfid);
+                       if (IS_ERR(mdt_obj))
+                               GOTO(out, rc = PTR_ERR(mdt_obj));
+               }
 
                if (!mdt_object_exists(mdt_obj)) {
                        mdt_object_put(info->mti_env, mdt_obj);
@@ -5299,7 +6158,7 @@ static int mdt_path_current(struct mdt_thread_info *info,
 
                /* Pack the name in the end of the buffer */
                ptr -= tmpname->ln_namelen;
-               if (ptr - 1 <= fp->gf_path)
+               if (ptr - 1 <= fp->gf_u.gf_path)
                        GOTO(out, rc = -EOVERFLOW);
                strncpy(ptr, tmpname->ln_name, tmpname->ln_namelen);
                *(--ptr) = '/';
@@ -5314,7 +6173,8 @@ static int mdt_path_current(struct mdt_thread_info *info,
 
 remote_out:
        ptr++; /* skip leading / */
-       memmove(fp->gf_path, ptr, fp->gf_path + fp->gf_pathlen - ptr);
+       memmove(fp->gf_u.gf_path, ptr,
+               fp->gf_u.gf_path + fp->gf_pathlen - ptr);
 
 out:
        RETURN(rc);
@@ -5336,7 +6196,7 @@ out:
  * \retval negative errno if there was a problem
  */
 static int mdt_path(struct mdt_thread_info *info, struct mdt_object *obj,
-                   struct getinfo_fid2path *fp)
+                   struct getinfo_fid2path *fp, struct lu_fid *root_fid)
 {
        struct mdt_device       *mdt = info->mti_mdt;
        int                     tries = 3;
@@ -5346,14 +6206,17 @@ static int mdt_path(struct mdt_thread_info *info, struct mdt_object *obj,
        if (fp->gf_pathlen < 3)
                RETURN(-EOVERFLOW);
 
-       if (lu_fid_eq(&mdt->mdt_md_root_fid, mdt_object_fid(obj))) {
-               fp->gf_path[0] = '\0';
+       if (root_fid == NULL)
+               root_fid = &mdt->mdt_md_root_fid;
+
+       if (lu_fid_eq(root_fid, mdt_object_fid(obj))) {
+               fp->gf_u.gf_path[0] = '\0';
                RETURN(0);
        }
 
        /* Retry multiple times in case file is being moved */
        while (tries-- && rc == -EAGAIN)
-               rc = mdt_path_current(info, obj, fp);
+               rc = mdt_path_current(info, obj, fp, root_fid);
 
        RETURN(rc);
 }
@@ -5375,6 +6238,7 @@ static int mdt_path(struct mdt_thread_info *info, struct mdt_object *obj,
  * \retval negative errno if there was a problem
  */
 static int mdt_fid2path(struct mdt_thread_info *info,
+                       struct lu_fid *root_fid,
                        struct getinfo_fid2path *fp)
 {
        struct mdt_device *mdt = info->mti_mdt;
@@ -5382,16 +6246,16 @@ static int mdt_fid2path(struct mdt_thread_info *info,
        int    rc;
        ENTRY;
 
-       CDEBUG(D_IOCTL, "path get "DFID" from "LPU64" #%d\n",
+       CDEBUG(D_IOCTL, "path get "DFID" from %llu #%d\n",
                PFID(&fp->gf_fid), fp->gf_recno, fp->gf_linkno);
 
        if (!fid_is_sane(&fp->gf_fid))
                RETURN(-EINVAL);
 
        if (!fid_is_namespace_visible(&fp->gf_fid)) {
-               CWARN("%s: "DFID" is invalid, sequence should be "
-                     ">= "LPX64"\n", mdt_obd_name(mdt),
-                     PFID(&fp->gf_fid), (__u64)FID_SEQ_NORMAL);
+               CDEBUG(D_INFO, "%s: "DFID" is invalid, f_seq should be >= %#llx"
+                      ", or f_oid != 0, or f_ver == 0\n", mdt_obd_name(mdt),
+                      PFID(&fp->gf_fid), (__u64)FID_SEQ_NORMAL);
                RETURN(-EINVAL);
        }
 
@@ -5417,20 +6281,22 @@ static int mdt_fid2path(struct mdt_thread_info *info,
                RETURN(rc);
        }
 
-       rc = mdt_path(info, obj, fp);
+       rc = mdt_path(info, obj, fp, root_fid);
 
-       CDEBUG(D_INFO, "fid "DFID", path %s recno "LPX64" linkno %u\n",
-              PFID(&fp->gf_fid), fp->gf_path, fp->gf_recno, fp->gf_linkno);
+       CDEBUG(D_INFO, "fid "DFID", path %s recno %#llx linkno %u\n",
+              PFID(&fp->gf_fid), fp->gf_u.gf_path,
+              fp->gf_recno, fp->gf_linkno);
 
        mdt_object_put(info->mti_env, obj);
 
        RETURN(rc);
 }
 
-static int mdt_rpc_fid2path(struct mdt_thread_info *info, void *key,
+static int mdt_rpc_fid2path(struct mdt_thread_info *info, void *key, int keylen,
                            void *val, int vallen)
 {
        struct getinfo_fid2path *fpout, *fpin;
+       struct lu_fid *root_fid = NULL;
        int rc = 0;
 
        fpin = key + cfs_size_round(sizeof(KEY_FID2PATH));
@@ -5443,7 +6309,18 @@ static int mdt_rpc_fid2path(struct mdt_thread_info *info, void *key,
        if (fpout->gf_pathlen != vallen - sizeof(*fpin))
                RETURN(-EINVAL);
 
-       rc = mdt_fid2path(info, fpout);
+       if (keylen >= cfs_size_round(sizeof(KEY_FID2PATH)) + sizeof(*fpin) +
+                     sizeof(struct lu_fid)) {
+               /* client sent its root FID, which is normally fileset FID */
+               root_fid = fpin->gf_u.gf_root_fid;
+               if (ptlrpc_req_need_swab(info->mti_pill->rc_req))
+                       lustre_swab_lu_fid(root_fid);
+
+               if (root_fid != NULL && !fid_is_sane(root_fid))
+                       RETURN(-EINVAL);
+       }
+
+       rc = mdt_fid2path(info, root_fid, fpout);
        RETURN(rc);
 }
 
@@ -5488,7 +6365,7 @@ int mdt_get_info(struct tgt_session_info *tsi)
        if (KEY_IS(KEY_FID2PATH)) {
                struct mdt_thread_info  *info = tsi2mdt_info(tsi);
 
-               rc = mdt_rpc_fid2path(info, key, valout, *vallen);
+               rc = mdt_rpc_fid2path(info, key, keylen, valout, *vallen);
                mdt_thread_info_fini(info);
        } else {
                rc = -EINVAL;
@@ -5496,30 +6373,6 @@ int mdt_get_info(struct tgt_session_info *tsi)
        RETURN(rc);
 }
 
-/* Pass the ioc down */
-static int mdt_ioc_child(struct lu_env *env, struct mdt_device *mdt,
-                        unsigned int cmd, int len, void *data)
-{
-       struct lu_context ioctl_session;
-       struct md_device *next = mdt->mdt_child;
-       int rc;
-       ENTRY;
-
-        rc = lu_context_init(&ioctl_session, LCT_SERVER_SESSION);
-       if (rc)
-               RETURN(rc);
-       ioctl_session.lc_thread = (struct ptlrpc_thread *)current;
-       lu_context_enter(&ioctl_session);
-       env->le_ses = &ioctl_session;
-
-       LASSERT(next->md_ops->mdo_iocontrol);
-       rc = next->md_ops->mdo_iocontrol(env, next, cmd, len, data);
-
-       lu_context_exit(&ioctl_session);
-       lu_context_fini(&ioctl_session);
-       RETURN(rc);
-}
-
 static int mdt_ioc_version_get(struct mdt_thread_info *mti, void *karg)
 {
        struct obd_ioctl_data *data = karg;
@@ -5569,7 +6422,7 @@ static int mdt_ioc_version_get(struct mdt_thread_info *mti, void *karg)
 
 /* ioctls on obd dev */
 static int mdt_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
-                         void *karg, void *uarg)
+                        void *karg, void __user *uarg)
 {
         struct lu_env      env;
         struct obd_device *obd = exp->exp_obd;
@@ -5583,23 +6436,27 @@ static int mdt_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
         if (rc)
                 RETURN(rc);
 
-        switch (cmd) {
-        case OBD_IOC_SYNC:
-                rc = mdt_device_sync(&env, mdt);
-                break;
-        case OBD_IOC_SET_READONLY:
-                rc = dt->dd_ops->dt_ro(&env, dt);
-                break;
+       switch (cmd) {
+       case OBD_IOC_SYNC:
+               rc = mdt_device_sync(&env, mdt);
+               break;
+       case OBD_IOC_SET_READONLY:
+               rc = dt_sync(&env, dt);
+               if (rc == 0)
+                       rc = dt_ro(&env, dt);
+               break;
        case OBD_IOC_ABORT_RECOVERY:
                CERROR("%s: Aborting recovery for device\n", mdt_obd_name(mdt));
-               obd->obd_force_abort_recovery = 1;
+               obd->obd_abort_recovery = 1;
                target_stop_recovery_thread(obd);
                rc = 0;
                break;
         case OBD_IOC_CHANGELOG_REG:
         case OBD_IOC_CHANGELOG_DEREG:
         case OBD_IOC_CHANGELOG_CLEAR:
-                rc = mdt_ioc_child(&env, mdt, cmd, len, karg);
+               rc = mdt->mdt_child->md_ops->mdo_iocontrol(&env,
+                                                          mdt->mdt_child,
+                                                          cmd, len, karg);
                 break;
        case OBD_IOC_START_LFSCK: {
                struct md_device *next = mdt->mdt_child;
@@ -5632,6 +6489,14 @@ static int mdt_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
                rc = next->md_ops->mdo_iocontrol(&env, next, cmd, 0, &stop);
                break;
        }
+       case OBD_IOC_QUERY_LFSCK: {
+               struct md_device        *next = mdt->mdt_child;
+               struct obd_ioctl_data   *data = karg;
+
+               rc = next->md_ops->mdo_iocontrol(&env, next, cmd, 0,
+                                                data->ioc_inlbuf1);
+               break;
+       }
         case OBD_IOC_GET_OBJ_VERSION: {
                 struct mdt_thread_info *mti;
                 mti = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
@@ -5665,18 +6530,21 @@ static int mdt_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
 static int mdt_postrecov(const struct lu_env *env, struct mdt_device *mdt)
 {
        struct lu_device *ld = md2lu_dev(mdt->mdt_child);
-       struct lfsck_start_param lsp;
        int rc;
        ENTRY;
 
-       lsp.lsp_start = NULL;
-       lsp.lsp_index_valid = 0;
-       rc = mdt->mdt_child->md_ops->mdo_iocontrol(env, mdt->mdt_child,
-                                                  OBD_IOC_START_LFSCK,
-                                                  0, &lsp);
-       if (rc != 0 && rc != -EALREADY)
-               CWARN("%s: auto trigger paused LFSCK failed: rc = %d\n",
-                     mdt_obd_name(mdt), rc);
+       if (!mdt->mdt_skip_lfsck && !mdt->mdt_bottom->dd_rdonly) {
+               struct lfsck_start_param lsp;
+
+               lsp.lsp_start = NULL;
+               lsp.lsp_index_valid = 0;
+               rc = mdt->mdt_child->md_ops->mdo_iocontrol(env, mdt->mdt_child,
+                                                          OBD_IOC_START_LFSCK,
+                                                          0, &lsp);
+               if (rc != 0 && rc != -EALREADY)
+                       CWARN("%s: auto trigger paused LFSCK failed: rc = %d\n",
+                             mdt_obd_name(mdt), rc);
+       }
 
        rc = ld->ld_ops->ldo_recovery_complete(env, ld);
        RETURN(rc);
@@ -5705,6 +6573,9 @@ static struct obd_ops mdt_obd_device_ops = {
         .o_destroy_export = mdt_destroy_export,
         .o_iocontrol      = mdt_iocontrol,
         .o_postrecov      = mdt_obd_postrecov,
+       /* Data-on-MDT IO methods */
+       .o_preprw         = mdt_obd_preprw,
+       .o_commitrw       = mdt_obd_commitrw,
 };
 
 static struct lu_device* mdt_device_fini(const struct lu_env *env,
@@ -5765,6 +6636,13 @@ static void mdt_key_fini(const struct lu_context *ctx,
                info->mti_big_lmm = NULL;
                info->mti_big_lmmsize = 0;
        }
+
+       if (info->mti_big_acl) {
+               OBD_FREE_LARGE(info->mti_big_acl, info->mti_big_aclsize);
+               info->mti_big_acl = NULL;
+               info->mti_big_aclsize = 0;
+       }
+
        OBD_FREE_PTR(info);
 }
 
@@ -5830,7 +6708,7 @@ static struct lu_device_type mdt_device_type = {
         .ldt_ctx_tags = LCT_MD_THREAD
 };
 
-static int __init mdt_mod_init(void)
+static int __init mdt_init(void)
 {
        int rc;
 
@@ -5859,17 +6737,17 @@ mds_fini:
        return rc;
 }
 
-static void __exit mdt_mod_exit(void)
+static void __exit mdt_exit(void)
 {
        class_unregister_type(LUSTRE_MDT_NAME);
        mds_mod_exit();
        lu_kmem_fini(mdt_caches);
 }
 
-MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
+MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
 MODULE_DESCRIPTION("Lustre Metadata Target ("LUSTRE_MDT_NAME")");
 MODULE_VERSION(LUSTRE_VERSION_STRING);
 MODULE_LICENSE("GPL");
 
-module_init(mdt_mod_init);
-module_exit(mdt_mod_exit);
+module_init(mdt_init);
+module_exit(mdt_exit);