Whamcloud - gitweb
LU-14487 modules: remove references to Sun Trademark.
[fs/lustre-release.git] / lustre / mdt / mdt_handler.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2010, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * lustre/mdt/mdt_handler.c
32  *
33  * Lustre Metadata Target (mdt) request handler
34  *
35  * Author: Peter Braam <braam@clusterfs.com>
36  * Author: Andreas Dilger <adilger@clusterfs.com>
37  * Author: Phil Schwan <phil@clusterfs.com>
38  * Author: Mike Shaver <shaver@clusterfs.com>
39  * Author: Nikita Danilov <nikita@clusterfs.com>
40  * Author: Huang Hua <huanghua@clusterfs.com>
41  * Author: Yury Umanets <umka@clusterfs.com>
42  */
43
44 #define DEBUG_SUBSYSTEM S_MDS
45
46 #include <linux/module.h>
47 #include <linux/pagemap.h>
48
49 #include <dt_object.h>
50 #include <lustre_acl.h>
51 #include <lustre_export.h>
52 #include <uapi/linux/lustre/lustre_ioctl.h>
53 #include <lustre_lfsck.h>
54 #include <lustre_log.h>
55 #include <lustre_nodemap.h>
56 #include <lustre_mds.h>
57 #include <uapi/linux/lustre/lustre_param.h>
58 #include <lustre_quota.h>
59 #include <lustre_swab.h>
60 #include <lustre_lmv.h>
61 #include <obd.h>
62 #include <obd_support.h>
63 #include <lustre_barrier.h>
64 #include <obd_cksum.h>
65 #include <llog_swab.h>
66
67 #include "mdt_internal.h"
68
69 static unsigned int max_mod_rpcs_per_client = 8;
70 module_param(max_mod_rpcs_per_client, uint, 0644);
71 MODULE_PARM_DESC(max_mod_rpcs_per_client, "maximum number of modify RPCs in flight allowed per client");
72
73 mdl_mode_t mdt_mdl_lock_modes[] = {
74         [LCK_MINMODE] = MDL_MINMODE,
75         [LCK_EX]      = MDL_EX,
76         [LCK_PW]      = MDL_PW,
77         [LCK_PR]      = MDL_PR,
78         [LCK_CW]      = MDL_CW,
79         [LCK_CR]      = MDL_CR,
80         [LCK_NL]      = MDL_NL,
81         [LCK_GROUP]   = MDL_GROUP
82 };
83
84 enum ldlm_mode mdt_dlm_lock_modes[] = {
85         [MDL_MINMODE]   = LCK_MINMODE,
86         [MDL_EX]        = LCK_EX,
87         [MDL_PW]        = LCK_PW,
88         [MDL_PR]        = LCK_PR,
89         [MDL_CW]        = LCK_CW,
90         [MDL_CR]        = LCK_CR,
91         [MDL_NL]        = LCK_NL,
92         [MDL_GROUP]     = LCK_GROUP
93 };
94
95 static struct mdt_device *mdt_dev(struct lu_device *d);
96
97 static const struct lu_object_operations mdt_obj_ops;
98
99 /* Slab for MDT object allocation */
100 static struct kmem_cache *mdt_object_kmem;
101
102 /* For HSM restore handles */
103 struct kmem_cache *mdt_hsm_cdt_kmem;
104
105 /* For HSM request handles */
106 struct kmem_cache *mdt_hsm_car_kmem;
107
108 static struct lu_kmem_descr mdt_caches[] = {
109         {
110                 .ckd_cache = &mdt_object_kmem,
111                 .ckd_name  = "mdt_obj",
112                 .ckd_size  = sizeof(struct mdt_object)
113         },
114         {
115                 .ckd_cache      = &mdt_hsm_cdt_kmem,
116                 .ckd_name       = "mdt_cdt_restore_handle",
117                 .ckd_size       = sizeof(struct cdt_restore_handle)
118         },
119         {
120                 .ckd_cache      = &mdt_hsm_car_kmem,
121                 .ckd_name       = "mdt_cdt_agent_req",
122                 .ckd_size       = sizeof(struct cdt_agent_req)
123         },
124         {
125                 .ckd_cache = NULL
126         }
127 };
128
129 __u64 mdt_get_disposition(struct ldlm_reply *rep, __u64 op_flag)
130 {
131         if (!rep)
132                 return 0;
133         return rep->lock_policy_res1 & op_flag;
134 }
135
136 void mdt_clear_disposition(struct mdt_thread_info *info,
137                            struct ldlm_reply *rep, __u64 op_flag)
138 {
139         if (info) {
140                 info->mti_opdata &= ~op_flag;
141                 tgt_opdata_clear(info->mti_env, op_flag);
142         }
143         if (rep)
144                 rep->lock_policy_res1 &= ~op_flag;
145 }
146
147 void mdt_set_disposition(struct mdt_thread_info *info,
148                          struct ldlm_reply *rep, __u64 op_flag)
149 {
150         if (info) {
151                 info->mti_opdata |= op_flag;
152                 tgt_opdata_set(info->mti_env, op_flag);
153         }
154         if (rep)
155                 rep->lock_policy_res1 |= op_flag;
156 }
157
158 void mdt_lock_reg_init(struct mdt_lock_handle *lh, enum ldlm_mode lm)
159 {
160         lh->mlh_pdo_hash = 0;
161         lh->mlh_reg_mode = lm;
162         lh->mlh_rreg_mode = lm;
163         lh->mlh_type = MDT_REG_LOCK;
164 }
165
166 void mdt_lh_reg_init(struct mdt_lock_handle *lh, struct ldlm_lock *lock)
167 {
168         mdt_lock_reg_init(lh, lock->l_req_mode);
169         if (lock->l_req_mode == LCK_GROUP)
170                 lh->mlh_gid = lock->l_policy_data.l_inodebits.li_gid;
171 }
172
173 void mdt_lock_pdo_init(struct mdt_lock_handle *lh, enum ldlm_mode lock_mode,
174                        const struct lu_name *lname)
175 {
176         lh->mlh_reg_mode = lock_mode;
177         lh->mlh_pdo_mode = LCK_MINMODE;
178         lh->mlh_rreg_mode = lock_mode;
179         lh->mlh_type = MDT_PDO_LOCK;
180
181         if (lu_name_is_valid(lname)) {
182                 lh->mlh_pdo_hash = ll_full_name_hash(NULL, lname->ln_name,
183                                                      lname->ln_namelen);
184                 /* XXX Workaround for LU-2856
185                  *
186                  * Zero is a valid return value of full_name_hash, but
187                  * several users of mlh_pdo_hash assume a non-zero
188                  * hash value. We therefore map zero onto an
189                  * arbitrary, but consistent value (1) to avoid
190                  * problems further down the road. */
191                 if (unlikely(lh->mlh_pdo_hash == 0))
192                         lh->mlh_pdo_hash = 1;
193         } else {
194                 lh->mlh_pdo_hash = 0;
195         }
196 }
197
198 static void mdt_lock_pdo_mode(struct mdt_thread_info *info, struct mdt_object *o,
199                               struct mdt_lock_handle *lh)
200 {
201         mdl_mode_t mode;
202         ENTRY;
203
204         /*
205          * Any dir access needs couple of locks:
206          *
207          * 1) on part of dir we gonna take lookup/modify;
208          *
209          * 2) on whole dir to protect it from concurrent splitting and/or to
210          * flush client's cache for readdir().
211          *
212          * so, for a given mode and object this routine decides what lock mode
213          * to use for lock #2:
214          *
215          * 1) if caller's gonna lookup in dir then we need to protect dir from
216          * being splitted only - LCK_CR
217          *
218          * 2) if caller's gonna modify dir then we need to protect dir from
219          * being splitted and to flush cache - LCK_CW
220          *
221          * 3) if caller's gonna modify dir and that dir seems ready for
222          * splitting then we need to protect it from any type of access
223          * (lookup/modify/split) - LCK_EX --bzzz
224          */
225
226         LASSERT(lh->mlh_reg_mode != LCK_MINMODE);
227         LASSERT(lh->mlh_pdo_mode == LCK_MINMODE);
228
229         /*
230          * Ask underlaying level its opinion about preferable PDO lock mode
231          * having access type passed as regular lock mode:
232          *
233          * - MDL_MINMODE means that lower layer does not want to specify lock
234          * mode;
235          *
236          * - MDL_NL means that no PDO lock should be taken. This is used in some
237          * cases. Say, for non-splittable directories no need to use PDO locks
238          * at all.
239          */
240         mode = mdo_lock_mode(info->mti_env, mdt_object_child(o),
241                              mdt_dlm_mode2mdl_mode(lh->mlh_reg_mode));
242
243         if (mode != MDL_MINMODE) {
244                 lh->mlh_pdo_mode = mdt_mdl_mode2dlm_mode(mode);
245         } else {
246                 /*
247                  * Lower layer does not want to specify locking mode. We do it
248                  * our selves. No special protection is needed, just flush
249                  * client's cache on modification and allow concurrent
250                  * mondification.
251                  */
252                 switch (lh->mlh_reg_mode) {
253                 case LCK_EX:
254                         lh->mlh_pdo_mode = LCK_EX;
255                         break;
256                 case LCK_PR:
257                         lh->mlh_pdo_mode = LCK_CR;
258                         break;
259                 case LCK_PW:
260                         lh->mlh_pdo_mode = LCK_CW;
261                         break;
262                 default:
263                         CERROR("Not expected lock type (0x%x)\n",
264                                (int)lh->mlh_reg_mode);
265                         LBUG();
266                 }
267         }
268
269         LASSERT(lh->mlh_pdo_mode != LCK_MINMODE);
270         EXIT;
271 }
272
273 static int mdt_lookup_fileset(struct mdt_thread_info *info, const char *fileset,
274                               struct lu_fid *fid)
275 {
276         struct mdt_device *mdt = info->mti_mdt;
277         struct lu_name *lname = &info->mti_name;
278         const char *start = fileset;
279         char *filename = info->mti_filename;
280         struct mdt_object *parent;
281         u32 mode;
282         int rc = 0;
283
284         LASSERT(!info->mti_cross_ref);
285
286         /*
287          * We may want to allow this to mount a completely separate
288          * fileset from the MDT in the future, but keeping it to
289          * ROOT/ only for now avoid potential security issues.
290          */
291         *fid = mdt->mdt_md_root_fid;
292
293         while (rc == 0 && start != NULL && *start != '\0') {
294                 const char *s1 = start;
295                 const char *s2;
296
297                 while (*++s1 == '/')
298                         ;
299                 s2 = s1;
300                 while (*s2 != '/' && *s2 != '\0')
301                         s2++;
302
303                 if (s2 == s1)
304                         break;
305
306                 start = s2;
307
308                 lname->ln_namelen = s2 - s1;
309                 if (lname->ln_namelen > NAME_MAX) {
310                         rc = -EINVAL;
311                         break;
312                 }
313
314                 /* reject .. as a path component */
315                 if (lname->ln_namelen == 2 &&
316                     strncmp(s1, "..", 2) == 0) {
317                         rc = -EINVAL;
318                         break;
319                 }
320
321                 strncpy(filename, s1, lname->ln_namelen);
322                 filename[lname->ln_namelen] = '\0';
323                 lname->ln_name = filename;
324
325                 parent = mdt_object_find(info->mti_env, mdt, fid);
326                 if (IS_ERR(parent)) {
327                         rc = PTR_ERR(parent);
328                         break;
329                 }
330                 /* Only got the fid of this obj by name */
331                 fid_zero(fid);
332                 rc = mdo_lookup(info->mti_env, mdt_object_child(parent), lname,
333                                 fid, &info->mti_spec);
334                 mdt_object_put(info->mti_env, parent);
335         }
336         if (!rc) {
337                 parent = mdt_object_find(info->mti_env, mdt, fid);
338                 if (IS_ERR(parent))
339                         rc = PTR_ERR(parent);
340                 else {
341                         mode = lu_object_attr(&parent->mot_obj);
342                         if (!S_ISDIR(mode)) {
343                                 rc = -ENOTDIR;
344                         } else if (mdt_is_remote_object(info, parent, parent)) {
345                                 if (!mdt->mdt_enable_remote_subdir_mount) {
346                                         rc = -EREMOTE;
347                                         LCONSOLE_WARN("%s: subdir mount '%s' refused because 'enable_remote_subdir_mount=0': rc = %d\n",
348                                                       mdt_obd_name(mdt),
349                                                       fileset, rc);
350                                 } else {
351                                         LCONSOLE_INFO("%s: subdir mount '%s' is remote and may be slow\n",
352                                                       mdt_obd_name(mdt),
353                                                       fileset);
354                                 }
355                         }
356                         mdt_object_put(info->mti_env, parent);
357                 }
358         }
359
360         return rc;
361 }
362
363 static int mdt_get_root(struct tgt_session_info *tsi)
364 {
365         struct mdt_thread_info  *info = tsi2mdt_info(tsi);
366         struct mdt_device       *mdt = info->mti_mdt;
367         struct mdt_body         *repbody;
368         char                    *fileset = NULL, *buffer = NULL;
369         int                      rc;
370         struct obd_export       *exp = info->mti_exp;
371         char                    *nodemap_fileset;
372
373         ENTRY;
374
375         rc = mdt_check_ucred(info);
376         if (rc)
377                 GOTO(out, rc = err_serious(rc));
378
379         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_GET_ROOT_PACK))
380                 GOTO(out, rc = err_serious(-ENOMEM));
381
382         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
383         if (req_capsule_get_size(info->mti_pill, &RMF_NAME, RCL_CLIENT) > 0) {
384                 fileset = req_capsule_client_get(info->mti_pill, &RMF_NAME);
385                 if (fileset == NULL)
386                         GOTO(out, rc = err_serious(-EFAULT));
387         }
388
389         nodemap_fileset = nodemap_get_fileset(exp->exp_target_data.ted_nodemap);
390         if (nodemap_fileset && nodemap_fileset[0]) {
391                 CDEBUG(D_INFO, "nodemap fileset is %s\n", nodemap_fileset);
392                 if (fileset) {
393                         /* consider fileset from client as a sub-fileset
394                          * of the nodemap one */
395                         OBD_ALLOC(buffer, PATH_MAX + 1);
396                         if (buffer == NULL)
397                                 GOTO(out, rc = err_serious(-ENOMEM));
398                         if (snprintf(buffer, PATH_MAX + 1, "%s/%s",
399                                      nodemap_fileset, fileset) >= PATH_MAX + 1)
400                                 GOTO(out, rc = err_serious(-EINVAL));
401                         fileset = buffer;
402                 } else {
403                         /* enforce fileset as specified in the nodemap */
404                         fileset = nodemap_fileset;
405                 }
406         }
407
408         if (fileset) {
409                 CDEBUG(D_INFO, "Getting fileset %s\n", fileset);
410                 rc = mdt_lookup_fileset(info, fileset, &repbody->mbo_fid1);
411                 if (rc < 0)
412                         GOTO(out, rc = err_serious(rc));
413         } else {
414                 repbody->mbo_fid1 = mdt->mdt_md_root_fid;
415         }
416         repbody->mbo_valid |= OBD_MD_FLID;
417
418         EXIT;
419 out:
420         mdt_thread_info_fini(info);
421         if (buffer)
422                 OBD_FREE(buffer, PATH_MAX+1);
423         return rc;
424 }
425
426 static int mdt_statfs(struct tgt_session_info *tsi)
427 {
428         struct ptlrpc_request *req = tgt_ses_req(tsi);
429         struct mdt_thread_info *info = tsi2mdt_info(tsi);
430         struct mdt_device *mdt = info->mti_mdt;
431         struct tg_grants_data *tgd = &mdt->mdt_lut.lut_tgd;
432         struct md_device *next = mdt->mdt_child;
433         struct ptlrpc_service_part *svcpt;
434         struct obd_statfs *osfs;
435         struct mdt_body *reqbody = NULL;
436         struct mdt_statfs_cache *msf;
437         ktime_t kstart = ktime_get();
438         int rc;
439
440         ENTRY;
441
442         svcpt = req->rq_rqbd->rqbd_svcpt;
443
444         /* This will trigger a watchdog timeout */
445         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_STATFS_LCW_SLEEP,
446                          (MDT_SERVICE_WATCHDOG_FACTOR *
447                           at_get(&svcpt->scp_at_estimate)) + 1);
448
449         rc = mdt_check_ucred(info);
450         if (rc)
451                 GOTO(out, rc = err_serious(rc));
452
453         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_STATFS_PACK))
454                 GOTO(out, rc = err_serious(-ENOMEM));
455
456         osfs = req_capsule_server_get(info->mti_pill, &RMF_OBD_STATFS);
457         if (!osfs)
458                 GOTO(out, rc = -EPROTO);
459
460         if (mdt_is_sum_statfs_client(req->rq_export) &&
461                 lustre_packed_msg_size(req->rq_reqmsg) ==
462                 req_capsule_fmt_size(req->rq_reqmsg->lm_magic,
463                                      &RQF_MDS_STATFS_NEW, RCL_CLIENT)) {
464                 req_capsule_extend(info->mti_pill, &RQF_MDS_STATFS_NEW);
465                 reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
466         }
467
468         if (reqbody && reqbody->mbo_valid & OBD_MD_FLAGSTATFS)
469                 msf = &mdt->mdt_sum_osfs;
470         else
471                 msf = &mdt->mdt_osfs;
472
473         if (msf->msf_age + OBD_STATFS_CACHE_SECONDS <= ktime_get_seconds()) {
474                         /** statfs data is too old, get up-to-date one */
475                         if (reqbody && reqbody->mbo_valid & OBD_MD_FLAGSTATFS)
476                                 rc = next->md_ops->mdo_statfs(info->mti_env,
477                                                               next, osfs);
478                         else
479                                 rc = dt_statfs(info->mti_env, mdt->mdt_bottom,
480                                                osfs);
481                         if (rc)
482                                 GOTO(out, rc);
483                         spin_lock(&mdt->mdt_lock);
484                         msf->msf_osfs = *osfs;
485                         msf->msf_age = ktime_get_seconds();
486                         spin_unlock(&mdt->mdt_lock);
487         } else {
488                         /** use cached statfs data */
489                         spin_lock(&mdt->mdt_lock);
490                         *osfs = msf->msf_osfs;
491                         spin_unlock(&mdt->mdt_lock);
492         }
493
494         /* at least try to account for cached pages.  its still racy and
495          * might be under-reporting if clients haven't announced their
496          * caches with brw recently */
497         CDEBUG(D_SUPER | D_CACHE, "blocks cached %llu granted %llu"
498                " pending %llu free %llu avail %llu\n",
499                tgd->tgd_tot_dirty, tgd->tgd_tot_granted,
500                tgd->tgd_tot_pending,
501                osfs->os_bfree << tgd->tgd_blockbits,
502                osfs->os_bavail << tgd->tgd_blockbits);
503
504         osfs->os_bavail -= min_t(u64, osfs->os_bavail,
505                                  ((tgd->tgd_tot_dirty + tgd->tgd_tot_pending +
506                                    osfs->os_bsize - 1) >> tgd->tgd_blockbits));
507
508         tgt_grant_sanity_check(mdt->mdt_lu_dev.ld_obd, __func__);
509         CDEBUG(D_CACHE, "%llu blocks: %llu free, %llu avail; "
510                "%llu objects: %llu free; state %x\n",
511                osfs->os_blocks, osfs->os_bfree, osfs->os_bavail,
512                osfs->os_files, osfs->os_ffree, osfs->os_state);
513
514         if (!exp_grant_param_supp(tsi->tsi_exp) &&
515             tgd->tgd_blockbits > COMPAT_BSIZE_SHIFT) {
516                 /* clients which don't support OBD_CONNECT_GRANT_PARAM
517                  * should not see a block size > page size, otherwise
518                  * cl_lost_grant goes mad. Therefore, we emulate a 4KB (=2^12)
519                  * block size which is the biggest block size known to work
520                  * with all client's page size. */
521                 osfs->os_blocks <<= tgd->tgd_blockbits - COMPAT_BSIZE_SHIFT;
522                 osfs->os_bfree  <<= tgd->tgd_blockbits - COMPAT_BSIZE_SHIFT;
523                 osfs->os_bavail <<= tgd->tgd_blockbits - COMPAT_BSIZE_SHIFT;
524                 osfs->os_bsize = 1 << COMPAT_BSIZE_SHIFT;
525         }
526         if (rc == 0)
527                 mdt_counter_incr(req, LPROC_MDT_STATFS,
528                                  ktime_us_delta(ktime_get(), kstart));
529 out:
530         mdt_thread_info_fini(info);
531         RETURN(rc);
532 }
533
534 __u32 mdt_lmm_dom_entry_check(struct lov_mds_md *lmm, int *is_dom_only)
535 {
536         struct lov_comp_md_v1 *comp_v1;
537         struct lov_mds_md *v1;
538         __u32 off;
539         __u32 dom_stripesize = 0;
540         int i;
541         bool has_ost_stripes = false;
542
543         ENTRY;
544
545         if (is_dom_only)
546                 *is_dom_only = 0;
547
548         if (le32_to_cpu(lmm->lmm_magic) != LOV_MAGIC_COMP_V1)
549                 RETURN(0);
550
551         comp_v1 = (struct lov_comp_md_v1 *)lmm;
552         off = le32_to_cpu(comp_v1->lcm_entries[0].lcme_offset);
553         v1 = (struct lov_mds_md *)((char *)comp_v1 + off);
554
555         /* Fast check for DoM entry with no mirroring, should be the first */
556         if (le16_to_cpu(comp_v1->lcm_mirror_count) == 0 &&
557             lov_pattern(le32_to_cpu(v1->lmm_pattern)) != LOV_PATTERN_MDT)
558                 RETURN(0);
559
560         /* check all entries otherwise */
561         for (i = 0; i < le16_to_cpu(comp_v1->lcm_entry_count); i++) {
562                 struct lov_comp_md_entry_v1 *lcme;
563
564                 lcme = &comp_v1->lcm_entries[i];
565                 if (!(le32_to_cpu(lcme->lcme_flags) & LCME_FL_INIT))
566                         continue;
567
568                 off = le32_to_cpu(lcme->lcme_offset);
569                 v1 = (struct lov_mds_md *)((char *)comp_v1 + off);
570
571                 if (lov_pattern(le32_to_cpu(v1->lmm_pattern)) ==
572                     LOV_PATTERN_MDT)
573                         dom_stripesize = le32_to_cpu(v1->lmm_stripe_size);
574                 else
575                         has_ost_stripes = true;
576
577                 if (dom_stripesize && has_ost_stripes)
578                         RETURN(dom_stripesize);
579         }
580         /* DoM-only case exits here */
581         if (is_dom_only && dom_stripesize)
582                 *is_dom_only = 1;
583         RETURN(dom_stripesize);
584 }
585
586 /**
587  * Pack size attributes into the reply.
588  */
589 int mdt_pack_size2body(struct mdt_thread_info *info,
590                         const struct lu_fid *fid, struct lustre_handle *lh)
591 {
592         struct mdt_body *b;
593         struct md_attr *ma = &info->mti_attr;
594         __u32 dom_stripe;
595         bool dom_lock = false;
596
597         ENTRY;
598
599         LASSERT(ma->ma_attr.la_valid & LA_MODE);
600
601         if (!S_ISREG(ma->ma_attr.la_mode) ||
602             !(ma->ma_valid & MA_LOV && ma->ma_lmm != NULL))
603                 RETURN(-ENODATA);
604
605         dom_stripe = mdt_lmm_dom_stripesize(ma->ma_lmm);
606         /* no DoM stripe, no size in reply */
607         if (!dom_stripe)
608                 RETURN(-ENOENT);
609
610         if (lustre_handle_is_used(lh)) {
611                 struct ldlm_lock *lock;
612
613                 lock = ldlm_handle2lock(lh);
614                 if (lock != NULL) {
615                         dom_lock = ldlm_has_dom(lock);
616                         LDLM_LOCK_PUT(lock);
617                 }
618         }
619
620         /* no DoM lock, no size in reply */
621         if (!dom_lock)
622                 RETURN(0);
623
624         /* Either DoM lock exists or LMM has only DoM stripe then
625          * return size on body. */
626         b = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
627
628         mdt_dom_object_size(info->mti_env, info->mti_mdt, fid, b, dom_lock);
629         RETURN(0);
630 }
631
632 #ifdef CONFIG_LUSTRE_FS_POSIX_ACL
633 /*
634  * Pack ACL data into the reply. UIDs/GIDs are mapped and filtered by nodemap.
635  *
636  * \param       info    thread info object
637  * \param       repbody reply to pack ACLs into
638  * \param       o       mdt object of file to examine
639  * \param       nodemap nodemap of client to reply to
640  * \retval      0       success
641  * \retval      -errno  error getting or parsing ACL from disk
642  */
643 int mdt_pack_acl2body(struct mdt_thread_info *info, struct mdt_body *repbody,
644                       struct mdt_object *o, struct lu_nodemap *nodemap)
645 {
646         const struct lu_env     *env = info->mti_env;
647         struct md_object        *next = mdt_object_child(o);
648         struct lu_buf           *buf = &info->mti_buf;
649         struct mdt_device       *mdt = info->mti_mdt;
650         struct req_capsule *pill = info->mti_pill;
651         int rc;
652
653         ENTRY;
654
655         buf->lb_buf = req_capsule_server_get(pill, &RMF_ACL);
656         buf->lb_len = req_capsule_get_size(pill, &RMF_ACL, RCL_SERVER);
657         if (buf->lb_len == 0)
658                 RETURN(0);
659
660 again:
661         rc = mo_xattr_get(env, next, buf, XATTR_NAME_ACL_ACCESS);
662         if (rc < 0) {
663                 if (rc == -ENODATA) {
664                         repbody->mbo_aclsize = 0;
665                         repbody->mbo_valid |= OBD_MD_FLACL;
666                         rc = 0;
667                 } else if (rc == -EOPNOTSUPP) {
668                         rc = 0;
669                 } else {
670                         if (rc == -ERANGE &&
671                             exp_connect_large_acl(info->mti_exp) &&
672                             buf->lb_buf != info->mti_big_acl) {
673                                 if (info->mti_big_acl == NULL) {
674                                         info->mti_big_aclsize =
675                                                         min_t(unsigned int,
676                                                               mdt->mdt_max_ea_size,
677                                                               XATTR_SIZE_MAX);
678                                         OBD_ALLOC_LARGE(info->mti_big_acl,
679                                                         info->mti_big_aclsize);
680                                         if (info->mti_big_acl == NULL) {
681                                                 info->mti_big_aclsize = 0;
682                                                 CERROR("%s: unable to grow "
683                                                        DFID" ACL buffer\n",
684                                                        mdt_obd_name(mdt),
685                                                        PFID(mdt_object_fid(o)));
686                                                 RETURN(-ENOMEM);
687                                         }
688                                 }
689
690                                 CDEBUG(D_INODE, "%s: grow the "DFID
691                                        " ACL buffer to size %d\n",
692                                        mdt_obd_name(mdt),
693                                        PFID(mdt_object_fid(o)),
694                                        info->mti_big_aclsize);
695
696                                 buf->lb_buf = info->mti_big_acl;
697                                 buf->lb_len = info->mti_big_aclsize;
698
699                                 goto again;
700                         }
701
702                         CERROR("%s: unable to read "DFID" ACL: rc = %d\n",
703                                mdt_obd_name(mdt), PFID(mdt_object_fid(o)), rc);
704                 }
705         } else {
706                 int client;
707                 int server;
708                 int acl_buflen;
709                 int lmm_buflen = 0;
710                 int lmmsize = 0;
711
712                 acl_buflen = req_capsule_get_size(pill, &RMF_ACL, RCL_SERVER);
713                 if (acl_buflen >= rc)
714                         goto map;
715
716                 /* If LOV/LMA EA is small, we can reuse part of their buffer */
717                 client = ptlrpc_req_get_repsize(pill->rc_req);
718                 server = lustre_packed_msg_size(pill->rc_req->rq_repmsg);
719                 if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER)) {
720                         lmm_buflen = req_capsule_get_size(pill, &RMF_MDT_MD,
721                                                           RCL_SERVER);
722                         lmmsize = repbody->mbo_eadatasize;
723                 }
724
725                 if (client < server - acl_buflen - lmm_buflen + rc + lmmsize) {
726                         CDEBUG(D_INODE, "%s: client prepared buffer size %d "
727                                "is not big enough with the ACL size %d (%d)\n",
728                                mdt_obd_name(mdt), client, rc,
729                                server - acl_buflen - lmm_buflen + rc + lmmsize);
730                         repbody->mbo_aclsize = 0;
731                         repbody->mbo_valid &= ~OBD_MD_FLACL;
732                         RETURN(-ERANGE);
733                 }
734
735 map:
736                 if (buf->lb_buf == info->mti_big_acl)
737                         info->mti_big_acl_used = 1;
738
739                 rc = nodemap_map_acl(nodemap, buf->lb_buf,
740                                      rc, NODEMAP_FS_TO_CLIENT);
741                 /* if all ACLs mapped out, rc is still >= 0 */
742                 if (rc < 0) {
743                         CERROR("%s: nodemap_map_acl unable to parse "DFID
744                                " ACL: rc = %d\n", mdt_obd_name(mdt),
745                                PFID(mdt_object_fid(o)), rc);
746                         repbody->mbo_aclsize = 0;
747                         repbody->mbo_valid &= ~OBD_MD_FLACL;
748                 } else {
749                         repbody->mbo_aclsize = rc;
750                         repbody->mbo_valid |= OBD_MD_FLACL;
751                         rc = 0;
752                 }
753         }
754
755         RETURN(rc);
756 }
757 #endif
758
759 /* XXX Look into layout in MDT layer. */
760 static inline bool mdt_hsm_is_released(struct lov_mds_md *lmm)
761 {
762         struct lov_comp_md_v1   *comp_v1;
763         struct lov_mds_md       *v1;
764         int                      i;
765
766         if (lmm->lmm_magic == LOV_MAGIC_COMP_V1) {
767                 comp_v1 = (struct lov_comp_md_v1 *)lmm;
768
769                 for (i = 0; i < comp_v1->lcm_entry_count; i++) {
770                         v1 = (struct lov_mds_md *)((char *)comp_v1 +
771                                 comp_v1->lcm_entries[i].lcme_offset);
772                         /* We don't support partial release for now */
773                         if (!(v1->lmm_pattern & LOV_PATTERN_F_RELEASED))
774                                 return false;
775                 }
776                 return true;
777         } else {
778                 return (lmm->lmm_pattern & LOV_PATTERN_F_RELEASED) ?
779                         true : false;
780         }
781 }
782
783 void mdt_pack_attr2body(struct mdt_thread_info *info, struct mdt_body *b,
784                         const struct lu_attr *attr, const struct lu_fid *fid)
785 {
786         struct md_attr *ma = &info->mti_attr;
787         struct obd_export *exp = info->mti_exp;
788         struct lu_nodemap *nodemap = NULL;
789
790         LASSERT(ma->ma_valid & MA_INODE);
791
792         if (attr->la_valid & LA_ATIME) {
793                 b->mbo_atime = attr->la_atime;
794                 b->mbo_valid |= OBD_MD_FLATIME;
795         }
796         if (attr->la_valid & LA_MTIME) {
797                 b->mbo_mtime = attr->la_mtime;
798                 b->mbo_valid |= OBD_MD_FLMTIME;
799         }
800         if (attr->la_valid & LA_CTIME) {
801                 b->mbo_ctime = attr->la_ctime;
802                 b->mbo_valid |= OBD_MD_FLCTIME;
803         }
804         if (attr->la_valid & LA_BTIME) {
805                 b->mbo_btime = attr->la_btime;
806                 b->mbo_valid |= OBD_MD_FLBTIME;
807         }
808         if (attr->la_valid & LA_FLAGS) {
809                 b->mbo_flags = attr->la_flags;
810                 b->mbo_valid |= OBD_MD_FLFLAGS;
811         }
812         if (attr->la_valid & LA_NLINK) {
813                 b->mbo_nlink = attr->la_nlink;
814                 b->mbo_valid |= OBD_MD_FLNLINK;
815         }
816         if (attr->la_valid & (LA_UID|LA_GID)) {
817                 nodemap = nodemap_get_from_exp(exp);
818                 if (IS_ERR(nodemap))
819                         goto out;
820         }
821         if (attr->la_valid & LA_UID) {
822                 b->mbo_uid = nodemap_map_id(nodemap, NODEMAP_UID,
823                                             NODEMAP_FS_TO_CLIENT,
824                                             attr->la_uid);
825                 b->mbo_valid |= OBD_MD_FLUID;
826         }
827         if (attr->la_valid & LA_GID) {
828                 b->mbo_gid = nodemap_map_id(nodemap, NODEMAP_GID,
829                                             NODEMAP_FS_TO_CLIENT,
830                                             attr->la_gid);
831                 b->mbo_valid |= OBD_MD_FLGID;
832         }
833
834         if (attr->la_valid & LA_PROJID) {
835                 /* TODO, nodemap for project id */
836                 b->mbo_projid = attr->la_projid;
837                 b->mbo_valid |= OBD_MD_FLPROJID;
838         }
839
840         b->mbo_mode = attr->la_mode;
841         if (attr->la_valid & LA_MODE)
842                 b->mbo_valid |= OBD_MD_FLMODE;
843         if (attr->la_valid & LA_TYPE)
844                 b->mbo_valid |= OBD_MD_FLTYPE;
845
846         if (fid != NULL) {
847                 b->mbo_fid1 = *fid;
848                 b->mbo_valid |= OBD_MD_FLID;
849                 CDEBUG(D_INODE, DFID": nlink=%d, mode=%o, valid=%#llx\n",
850                        PFID(fid), b->mbo_nlink, b->mbo_mode, b->mbo_valid);
851         }
852
853         if (!(attr->la_valid & LA_TYPE))
854                 return;
855
856         b->mbo_rdev   = attr->la_rdev;
857         b->mbo_size   = attr->la_size;
858         b->mbo_blocks = attr->la_blocks;
859
860         if (!S_ISREG(attr->la_mode)) {
861                 b->mbo_valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS | OBD_MD_FLRDEV;
862         } else if (ma->ma_need & MA_LOV && !(ma->ma_valid & MA_LOV)) {
863                 /* means no objects are allocated on osts. */
864                 LASSERT(!(ma->ma_valid & MA_LOV));
865                 /* just ignore blocks occupied by extend attributes on MDS */
866                 b->mbo_blocks = 0;
867                 /* if no object is allocated on osts, the size on mds is valid.
868                  * b=22272 */
869                 b->mbo_valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS;
870         } else if ((ma->ma_valid & MA_LOV) && ma->ma_lmm != NULL) {
871                 if (mdt_hsm_is_released(ma->ma_lmm)) {
872                         /* A released file stores its size on MDS. */
873                         /* But return 1 block for released file, unless tools
874                          * like tar will consider it fully sparse. (LU-3864)
875                          */
876                         if (unlikely(b->mbo_size == 0))
877                                 b->mbo_blocks = 0;
878                         else
879                                 b->mbo_blocks = 1;
880                         b->mbo_valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS;
881                 } else if (info->mti_som_valid) { /* som is valid */
882                         b->mbo_valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS;
883                 } else if (ma->ma_valid & MA_SOM) { /* lsom is valid */
884                         b->mbo_valid |= OBD_MD_FLLAZYSIZE | OBD_MD_FLLAZYBLOCKS;
885                         b->mbo_size = ma->ma_som.ms_size;
886                         b->mbo_blocks = ma->ma_som.ms_blocks;
887                 }
888         }
889
890         if (fid != NULL && (b->mbo_valid & OBD_MD_FLSIZE ||
891                             b->mbo_valid & OBD_MD_FLLAZYSIZE))
892                 CDEBUG(D_VFSTRACE, DFID": returning size %llu\n",
893                        PFID(fid), (unsigned long long)b->mbo_size);
894
895 out:
896         if (!IS_ERR_OR_NULL(nodemap))
897                 nodemap_putref(nodemap);
898 }
899
900 static inline int mdt_body_has_lov(const struct lu_attr *la,
901                                    const struct mdt_body *body)
902 {
903         return (S_ISREG(la->la_mode) && (body->mbo_valid & OBD_MD_FLEASIZE)) ||
904                (S_ISDIR(la->la_mode) && (body->mbo_valid & OBD_MD_FLDIREA));
905 }
906
907 void mdt_client_compatibility(struct mdt_thread_info *info)
908 {
909         struct mdt_body       *body;
910         struct ptlrpc_request *req = mdt_info_req(info);
911         struct obd_export     *exp = req->rq_export;
912         struct md_attr        *ma = &info->mti_attr;
913         struct lu_attr        *la = &ma->ma_attr;
914         ENTRY;
915
916         if (exp_connect_layout(exp))
917                 /* the client can deal with 16-bit lmm_stripe_count */
918                 RETURN_EXIT;
919
920         body = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
921
922         if (!mdt_body_has_lov(la, body))
923                 RETURN_EXIT;
924
925         /* now we have a reply with a lov for a client not compatible with the
926          * layout lock so we have to clean the layout generation number */
927         if (S_ISREG(la->la_mode))
928                 ma->ma_lmm->lmm_layout_gen = 0;
929         EXIT;
930 }
931
932 static int mdt_attr_get_eabuf_size(struct mdt_thread_info *info,
933                                    struct mdt_object *o)
934 {
935         const struct lu_env *env = info->mti_env;
936         int rc, rc2;
937
938         rc = mo_xattr_get(env, mdt_object_child(o), &LU_BUF_NULL,
939                           XATTR_NAME_LOV);
940
941         if (rc == -ENODATA)
942                 rc = 0;
943
944         if (rc < 0)
945                 goto out;
946
947         /* Is it a directory? Let's check for the LMV as well */
948         if (S_ISDIR(lu_object_attr(&mdt_object_child(o)->mo_lu))) {
949                 rc2 = mo_xattr_get(env, mdt_object_child(o), &LU_BUF_NULL,
950                                    XATTR_NAME_LMV);
951
952                 if (rc2 == -ENODATA)
953                         rc2 = mo_xattr_get(env, mdt_object_child(o),
954                                            &LU_BUF_NULL,
955                                            XATTR_NAME_DEFAULT_LMV);
956
957                 if ((rc2 < 0 && rc2 != -ENODATA) || (rc2 > rc))
958                         rc = rc2;
959         }
960
961 out:
962         return rc;
963 }
964
965 int mdt_big_xattr_get(struct mdt_thread_info *info, struct mdt_object *o,
966                       const char *name)
967 {
968         const struct lu_env *env = info->mti_env;
969         int rc;
970         ENTRY;
971
972         LASSERT(info->mti_big_lmm_used == 0);
973         rc = mo_xattr_get(env, mdt_object_child(o), &LU_BUF_NULL, name);
974         if (rc < 0)
975                 RETURN(rc);
976
977         /* big_lmm may need to be grown */
978         if (info->mti_big_lmmsize < rc) {
979                 int size = size_roundup_power2(rc);
980
981                 if (info->mti_big_lmmsize > 0) {
982                         /* free old buffer */
983                         LASSERT(info->mti_big_lmm);
984                         OBD_FREE_LARGE(info->mti_big_lmm,
985                                        info->mti_big_lmmsize);
986                         info->mti_big_lmm = NULL;
987                         info->mti_big_lmmsize = 0;
988                 }
989
990                 OBD_ALLOC_LARGE(info->mti_big_lmm, size);
991                 if (info->mti_big_lmm == NULL)
992                         RETURN(-ENOMEM);
993                 info->mti_big_lmmsize = size;
994         }
995         LASSERT(info->mti_big_lmmsize >= rc);
996
997         info->mti_buf.lb_buf = info->mti_big_lmm;
998         info->mti_buf.lb_len = info->mti_big_lmmsize;
999         rc = mo_xattr_get(env, mdt_object_child(o), &info->mti_buf, name);
1000
1001         RETURN(rc);
1002 }
1003
1004 int __mdt_stripe_get(struct mdt_thread_info *info, struct mdt_object *o,
1005                      struct md_attr *ma, const char *name)
1006 {
1007         struct md_object *next = mdt_object_child(o);
1008         struct lu_buf    *buf = &info->mti_buf;
1009         int rc;
1010
1011         if (strcmp(name, XATTR_NAME_LOV) == 0) {
1012                 buf->lb_buf = ma->ma_lmm;
1013                 buf->lb_len = ma->ma_lmm_size;
1014                 LASSERT(!(ma->ma_valid & MA_LOV));
1015         } else if (strcmp(name, XATTR_NAME_LMV) == 0) {
1016                 buf->lb_buf = ma->ma_lmv;
1017                 buf->lb_len = ma->ma_lmv_size;
1018                 LASSERT(!(ma->ma_valid & MA_LMV));
1019         } else if (strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0) {
1020                 buf->lb_buf = ma->ma_default_lmv;
1021                 buf->lb_len = ma->ma_default_lmv_size;
1022                 LASSERT(!(ma->ma_valid & MA_LMV_DEF));
1023         } else {
1024                 return -EINVAL;
1025         }
1026
1027         LASSERT(buf->lb_buf);
1028
1029         rc = mo_xattr_get(info->mti_env, next, buf, name);
1030         if (rc > 0) {
1031
1032 got:
1033                 if (strcmp(name, XATTR_NAME_LOV) == 0) {
1034                         if (info->mti_big_lmm_used)
1035                                 ma->ma_lmm = info->mti_big_lmm;
1036
1037                         /* NOT return LOV EA with hole to old client. */
1038                         if (unlikely(le32_to_cpu(ma->ma_lmm->lmm_pattern) &
1039                                      LOV_PATTERN_F_HOLE) &&
1040                             !(exp_connect_flags(info->mti_exp) &
1041                               OBD_CONNECT_LFSCK)) {
1042                                 return -EIO;
1043                         } else {
1044                                 ma->ma_lmm_size = rc;
1045                                 ma->ma_valid |= MA_LOV;
1046                         }
1047                 } else if (strcmp(name, XATTR_NAME_LMV) == 0) {
1048                         if (info->mti_big_lmm_used)
1049                                 ma->ma_lmv = info->mti_big_lmm;
1050
1051                         ma->ma_lmv_size = rc;
1052                         ma->ma_valid |= MA_LMV;
1053                 } else if (strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0) {
1054                         ma->ma_default_lmv_size = rc;
1055                         ma->ma_valid |= MA_LMV_DEF;
1056                 }
1057
1058                 /* Update mdt_max_mdsize so all clients will be aware that */
1059                 if (info->mti_mdt->mdt_max_mdsize < rc)
1060                         info->mti_mdt->mdt_max_mdsize = rc;
1061
1062                 rc = 0;
1063         } else if (rc == -ENODATA) {
1064                 /* no LOV EA */
1065                 rc = 0;
1066         } else if (rc == -ERANGE) {
1067                 /* Default LMV has fixed size, so it must be able to fit
1068                  * in the original buffer */
1069                 if (strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0)
1070                         return rc;
1071                 rc = mdt_big_xattr_get(info, o, name);
1072                 if (rc > 0) {
1073                         info->mti_big_lmm_used = 1;
1074                         goto got;
1075                 }
1076         }
1077
1078         return rc;
1079 }
1080
1081 int mdt_stripe_get(struct mdt_thread_info *info, struct mdt_object *o,
1082                    struct md_attr *ma, const char *name)
1083 {
1084         int rc;
1085
1086         if (!info->mti_big_lmm) {
1087                 OBD_ALLOC(info->mti_big_lmm, PAGE_SIZE);
1088                 if (!info->mti_big_lmm)
1089                         return -ENOMEM;
1090                 info->mti_big_lmmsize = PAGE_SIZE;
1091         }
1092
1093         if (strcmp(name, XATTR_NAME_LOV) == 0) {
1094                 ma->ma_lmm = info->mti_big_lmm;
1095                 ma->ma_lmm_size = info->mti_big_lmmsize;
1096                 ma->ma_valid &= ~MA_LOV;
1097         } else if (strcmp(name, XATTR_NAME_LMV) == 0) {
1098                 ma->ma_lmv = info->mti_big_lmm;
1099                 ma->ma_lmv_size = info->mti_big_lmmsize;
1100                 ma->ma_valid &= ~MA_LMV;
1101         } else {
1102                 LBUG();
1103         }
1104
1105         LASSERT(!info->mti_big_lmm_used);
1106         rc = __mdt_stripe_get(info, o, ma, name);
1107         /* since big_lmm is always used here, clear 'used' flag to avoid
1108          * assertion in mdt_big_xattr_get().
1109          */
1110         info->mti_big_lmm_used = 0;
1111
1112         return rc;
1113 }
1114
1115 int mdt_attr_get_pfid(struct mdt_thread_info *info, struct mdt_object *o,
1116                       struct lu_fid *pfid)
1117 {
1118         struct lu_buf           *buf = &info->mti_buf;
1119         struct link_ea_header   *leh;
1120         struct link_ea_entry    *lee;
1121         int                      rc;
1122         ENTRY;
1123
1124         buf->lb_buf = info->mti_big_lmm;
1125         buf->lb_len = info->mti_big_lmmsize;
1126         rc = mo_xattr_get(info->mti_env, mdt_object_child(o),
1127                           buf, XATTR_NAME_LINK);
1128         /* ignore errors, MA_PFID won't be set and it is
1129          * up to the caller to treat this as an error */
1130         if (rc == -ERANGE || buf->lb_len == 0) {
1131                 rc = mdt_big_xattr_get(info, o, XATTR_NAME_LINK);
1132                 buf->lb_buf = info->mti_big_lmm;
1133                 buf->lb_len = info->mti_big_lmmsize;
1134         }
1135
1136         if (rc < 0)
1137                 RETURN(rc);
1138         if (rc < sizeof(*leh)) {
1139                 CERROR("short LinkEA on "DFID": rc = %d\n",
1140                        PFID(mdt_object_fid(o)), rc);
1141                 RETURN(-ENODATA);
1142         }
1143
1144         leh = (struct link_ea_header *) buf->lb_buf;
1145         lee = (struct link_ea_entry *)(leh + 1);
1146         if (leh->leh_magic == __swab32(LINK_EA_MAGIC)) {
1147                 leh->leh_magic = LINK_EA_MAGIC;
1148                 leh->leh_reccount = __swab32(leh->leh_reccount);
1149                 leh->leh_len = __swab64(leh->leh_len);
1150         }
1151         if (leh->leh_magic != LINK_EA_MAGIC)
1152                 RETURN(-EINVAL);
1153         if (leh->leh_reccount == 0)
1154                 RETURN(-ENODATA);
1155
1156         memcpy(pfid, &lee->lee_parent_fid, sizeof(*pfid));
1157         fid_be_to_cpu(pfid, pfid);
1158
1159         RETURN(0);
1160 }
1161
1162 int mdt_attr_get_pfid_name(struct mdt_thread_info *info, struct mdt_object *o,
1163                            struct lu_fid *pfid, struct lu_name *lname)
1164 {
1165         struct lu_buf *buf = &info->mti_buf;
1166         struct link_ea_header *leh;
1167         struct link_ea_entry *lee;
1168         int reclen;
1169         int rc;
1170
1171         buf->lb_buf = info->mti_xattr_buf;
1172         buf->lb_len = sizeof(info->mti_xattr_buf);
1173         rc = mo_xattr_get(info->mti_env, mdt_object_child(o), buf,
1174                           XATTR_NAME_LINK);
1175         if (rc == -ERANGE) {
1176                 rc = mdt_big_xattr_get(info, o, XATTR_NAME_LINK);
1177                 buf->lb_buf = info->mti_big_lmm;
1178                 buf->lb_len = info->mti_big_lmmsize;
1179         }
1180         if (rc < 0)
1181                 return rc;
1182
1183         if (rc < sizeof(*leh)) {
1184                 CERROR("short LinkEA on "DFID": rc = %d\n",
1185                        PFID(mdt_object_fid(o)), rc);
1186                 return -ENODATA;
1187         }
1188
1189         leh = (struct link_ea_header *)buf->lb_buf;
1190         lee = (struct link_ea_entry *)(leh + 1);
1191         if (leh->leh_magic == __swab32(LINK_EA_MAGIC)) {
1192                 leh->leh_magic = LINK_EA_MAGIC;
1193                 leh->leh_reccount = __swab32(leh->leh_reccount);
1194                 leh->leh_len = __swab64(leh->leh_len);
1195         }
1196         if (leh->leh_magic != LINK_EA_MAGIC)
1197                 return -EINVAL;
1198
1199         if (leh->leh_reccount == 0)
1200                 return -ENODATA;
1201
1202         linkea_entry_unpack(lee, &reclen, lname, pfid);
1203
1204         return 0;
1205 }
1206
1207 int mdt_attr_get_complex(struct mdt_thread_info *info,
1208                          struct mdt_object *o, struct md_attr *ma)
1209 {
1210         const struct lu_env *env = info->mti_env;
1211         struct md_object    *next = mdt_object_child(o);
1212         struct lu_buf       *buf = &info->mti_buf;
1213         int                  need = ma->ma_need;
1214         int                  rc = 0, rc2;
1215         u32                  mode;
1216         ENTRY;
1217
1218         ma->ma_valid = 0;
1219
1220         if (mdt_object_exists(o) == 0)
1221                 GOTO(out, rc = -ENOENT);
1222         mode = lu_object_attr(&next->mo_lu);
1223
1224         if (need & MA_INODE) {
1225                 ma->ma_need = MA_INODE;
1226                 rc = mo_attr_get(env, next, ma);
1227                 if (rc)
1228                         GOTO(out, rc);
1229
1230                 if (S_ISREG(mode))
1231                         (void) mdt_get_som(info, o, ma);
1232                 ma->ma_valid |= MA_INODE;
1233         }
1234
1235         if (need & MA_PFID) {
1236                 rc = mdt_attr_get_pfid(info, o, &ma->ma_pfid);
1237                 if (rc == 0)
1238                         ma->ma_valid |= MA_PFID;
1239                 /* ignore this error, parent fid is not mandatory */
1240                 rc = 0;
1241         }
1242
1243         if (need & MA_LOV && (S_ISREG(mode) || S_ISDIR(mode))) {
1244                 rc = __mdt_stripe_get(info, o, ma, XATTR_NAME_LOV);
1245                 if (rc)
1246                         GOTO(out, rc);
1247         }
1248
1249         if (need & MA_LMV && S_ISDIR(mode)) {
1250                 rc = __mdt_stripe_get(info, o, ma, XATTR_NAME_LMV);
1251                 if (rc != 0)
1252                         GOTO(out, rc);
1253         }
1254
1255         if (need & MA_LMV_DEF && S_ISDIR(mode)) {
1256                 rc = __mdt_stripe_get(info, o, ma, XATTR_NAME_DEFAULT_LMV);
1257                 if (rc != 0)
1258                         GOTO(out, rc);
1259         }
1260
1261         /*
1262          * In the handle of MA_INODE, we may already get the SOM attr.
1263          */
1264         if (need & MA_SOM && S_ISREG(mode) && !(ma->ma_valid & MA_SOM)) {
1265                 rc = mdt_get_som(info, o, ma);
1266                 if (rc != 0)
1267                         GOTO(out, rc);
1268         }
1269
1270         if (need & MA_HSM && S_ISREG(mode)) {
1271                 buf->lb_buf = info->mti_xattr_buf;
1272                 buf->lb_len = sizeof(info->mti_xattr_buf);
1273                 BUILD_BUG_ON(sizeof(struct hsm_attrs) >
1274                              sizeof(info->mti_xattr_buf));
1275                 rc2 = mo_xattr_get(info->mti_env, next, buf, XATTR_NAME_HSM);
1276                 rc2 = lustre_buf2hsm(info->mti_xattr_buf, rc2, &ma->ma_hsm);
1277                 if (rc2 == 0)
1278                         ma->ma_valid |= MA_HSM;
1279                 else if (rc2 < 0 && rc2 != -ENODATA)
1280                         GOTO(out, rc = rc2);
1281         }
1282
1283 #ifdef CONFIG_LUSTRE_FS_POSIX_ACL
1284         if (need & MA_ACL_DEF && S_ISDIR(mode)) {
1285                 buf->lb_buf = ma->ma_acl;
1286                 buf->lb_len = ma->ma_acl_size;
1287                 rc2 = mo_xattr_get(env, next, buf, XATTR_NAME_ACL_DEFAULT);
1288                 if (rc2 > 0) {
1289                         ma->ma_acl_size = rc2;
1290                         ma->ma_valid |= MA_ACL_DEF;
1291                 } else if (rc2 == -ENODATA) {
1292                         /* no ACLs */
1293                         ma->ma_acl_size = 0;
1294                 } else
1295                         GOTO(out, rc = rc2);
1296         }
1297 #endif
1298 out:
1299         ma->ma_need = need;
1300         CDEBUG(D_INODE, "after getattr rc = %d, ma_valid = %#llx ma_lmm=%p\n",
1301                rc, ma->ma_valid, ma->ma_lmm);
1302         RETURN(rc);
1303 }
1304
1305 static int mdt_getattr_internal(struct mdt_thread_info *info,
1306                                 struct mdt_object *o, int ma_need)
1307 {
1308         struct mdt_device *mdt = info->mti_mdt;
1309         struct md_object *next = mdt_object_child(o);
1310         const struct mdt_body *reqbody = info->mti_body;
1311         struct ptlrpc_request *req = mdt_info_req(info);
1312         struct md_attr *ma = &info->mti_attr;
1313         struct lu_attr *la = &ma->ma_attr;
1314         struct req_capsule *pill = info->mti_pill;
1315         const struct lu_env *env = info->mti_env;
1316         struct mdt_body *repbody;
1317         struct lu_buf *buffer = &info->mti_buf;
1318         struct obd_export *exp = info->mti_exp;
1319         ktime_t kstart = ktime_get();
1320         int rc;
1321
1322         ENTRY;
1323
1324         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_GETATTR_PACK))
1325                 RETURN(err_serious(-ENOMEM));
1326
1327         repbody = req_capsule_server_get(pill, &RMF_MDT_BODY);
1328
1329         ma->ma_valid = 0;
1330
1331         if (mdt_object_remote(o)) {
1332                 /* This object is located on remote node.*/
1333                 /* Return -ENOTSUPP for old client */
1334                 if (!mdt_is_dne_client(req->rq_export))
1335                         GOTO(out, rc = -ENOTSUPP);
1336
1337                 repbody->mbo_fid1 = *mdt_object_fid(o);
1338                 repbody->mbo_valid = OBD_MD_FLID | OBD_MD_MDS;
1339                 GOTO(out, rc = 0);
1340         }
1341
1342         if (reqbody->mbo_eadatasize > 0) {
1343                 buffer->lb_buf = req_capsule_server_get(pill, &RMF_MDT_MD);
1344                 if (buffer->lb_buf == NULL)
1345                         GOTO(out, rc = -EPROTO);
1346                 buffer->lb_len = req_capsule_get_size(pill, &RMF_MDT_MD,
1347                                                       RCL_SERVER);
1348         } else {
1349                 buffer->lb_buf = NULL;
1350                 buffer->lb_len = 0;
1351                 ma_need &= ~(MA_LOV | MA_LMV);
1352                 CDEBUG(D_INFO, "%s: RPC from %s: does not need LOVEA.\n",
1353                        mdt_obd_name(info->mti_mdt),
1354                        req->rq_export->exp_client_uuid.uuid);
1355         }
1356
1357         /* from 2.12.58 intent_getattr pack default LMV in reply */
1358         if (S_ISDIR(lu_object_attr(&next->mo_lu)) &&
1359             ((reqbody->mbo_valid & (OBD_MD_MEA | OBD_MD_DEFAULT_MEA)) ==
1360                     (OBD_MD_MEA | OBD_MD_DEFAULT_MEA)) &&
1361             req_capsule_has_field(&req->rq_pill, &RMF_DEFAULT_MDT_MD,
1362                                   RCL_SERVER)) {
1363                 ma->ma_lmv = buffer->lb_buf;
1364                 ma->ma_lmv_size = buffer->lb_len;
1365                 ma->ma_default_lmv = req_capsule_server_get(pill,
1366                                                 &RMF_DEFAULT_MDT_MD);
1367                 ma->ma_default_lmv_size = req_capsule_get_size(pill,
1368                                                 &RMF_DEFAULT_MDT_MD,
1369                                                 RCL_SERVER);
1370                 ma->ma_need = MA_INODE;
1371                 if (ma->ma_lmv_size > 0)
1372                         ma->ma_need |= MA_LMV;
1373                 if (ma->ma_default_lmv_size > 0)
1374                         ma->ma_need |= MA_LMV_DEF;
1375         } else if (S_ISDIR(lu_object_attr(&next->mo_lu)) &&
1376                    (reqbody->mbo_valid & (OBD_MD_MEA | OBD_MD_DEFAULT_MEA))) {
1377                 /* If it is dir and client require MEA, then we got MEA */
1378                 /* Assumption: MDT_MD size is enough for lmv size. */
1379                 ma->ma_lmv = buffer->lb_buf;
1380                 ma->ma_lmv_size = buffer->lb_len;
1381                 ma->ma_need = MA_INODE;
1382                 if (ma->ma_lmv_size > 0) {
1383                         if (reqbody->mbo_valid & OBD_MD_MEA) {
1384                                 ma->ma_need |= MA_LMV;
1385                         } else if (reqbody->mbo_valid & OBD_MD_DEFAULT_MEA) {
1386                                 ma->ma_need |= MA_LMV_DEF;
1387                                 ma->ma_default_lmv = buffer->lb_buf;
1388                                 ma->ma_lmv = NULL;
1389                                 ma->ma_default_lmv_size = buffer->lb_len;
1390                                 ma->ma_lmv_size = 0;
1391                         }
1392                 }
1393         } else {
1394                 ma->ma_lmm = buffer->lb_buf;
1395                 ma->ma_lmm_size = buffer->lb_len;
1396                 ma->ma_need = MA_INODE | MA_HSM;
1397                 if (ma->ma_lmm_size > 0) {
1398                         ma->ma_need |= MA_LOV;
1399                         /* Older clients may crash if they getattr overstriped
1400                          * files
1401                          */
1402                         if (!exp_connect_overstriping(exp) &&
1403                             mdt_lmm_is_overstriping(ma->ma_lmm))
1404                                 RETURN(-EOPNOTSUPP);
1405                 }
1406         }
1407
1408         if (S_ISDIR(lu_object_attr(&next->mo_lu)) &&
1409             reqbody->mbo_valid & OBD_MD_FLDIREA  &&
1410             lustre_msg_get_opc(req->rq_reqmsg) == MDS_GETATTR) {
1411                 /* get default stripe info for this dir. */
1412                 ma->ma_need |= MA_LOV_DEF;
1413         }
1414         ma->ma_need |= ma_need;
1415
1416         rc = mdt_attr_get_complex(info, o, ma);
1417         if (unlikely(rc)) {
1418                 CDEBUG_LIMIT(rc == -ENOENT ? D_OTHER : D_ERROR,
1419                              "%s: getattr error for "DFID": rc = %d\n",
1420                              mdt_obd_name(info->mti_mdt),
1421                              PFID(mdt_object_fid(o)), rc);
1422                 RETURN(rc);
1423         }
1424
1425         /* if file is released, check if a restore is running */
1426         if (ma->ma_valid & MA_HSM) {
1427                 repbody->mbo_valid |= OBD_MD_TSTATE;
1428                 if ((ma->ma_hsm.mh_flags & HS_RELEASED) &&
1429                     mdt_hsm_restore_is_running(info, mdt_object_fid(o)))
1430                         repbody->mbo_t_state = MS_RESTORE;
1431         }
1432
1433         if (unlikely(!(ma->ma_valid & MA_INODE)))
1434                 RETURN(-EFAULT);
1435
1436         mdt_pack_attr2body(info, repbody, la, mdt_object_fid(o));
1437
1438         if (mdt_body_has_lov(la, reqbody)) {
1439                 u32 stripe_count = 1;
1440
1441                 if (ma->ma_valid & MA_LOV) {
1442                         LASSERT(ma->ma_lmm_size);
1443                         repbody->mbo_eadatasize = ma->ma_lmm_size;
1444                         if (S_ISDIR(la->la_mode))
1445                                 repbody->mbo_valid |= OBD_MD_FLDIREA;
1446                         else
1447                                 repbody->mbo_valid |= OBD_MD_FLEASIZE;
1448                         mdt_dump_lmm(D_INFO, ma->ma_lmm, repbody->mbo_valid);
1449                 }
1450                 if (ma->ma_valid & MA_LMV) {
1451                         struct lmv_mds_md_v1 *lmv = &ma->ma_lmv->lmv_md_v1;
1452                         u32 magic = le32_to_cpu(lmv->lmv_magic);
1453
1454                         /* Return -ENOTSUPP for old client */
1455                         if (!mdt_is_striped_client(req->rq_export))
1456                                 RETURN(-ENOTSUPP);
1457
1458                         LASSERT(S_ISDIR(la->la_mode));
1459                         mdt_dump_lmv(D_INFO, ma->ma_lmv);
1460                         repbody->mbo_eadatasize = ma->ma_lmv_size;
1461                         repbody->mbo_valid |= (OBD_MD_FLDIREA|OBD_MD_MEA);
1462
1463                         stripe_count = le32_to_cpu(lmv->lmv_stripe_count);
1464                         if (magic == LMV_MAGIC_STRIPE && lmv_is_restriping(lmv))
1465                                 mdt_restripe_migrate_add(info, o);
1466                         else if (magic == LMV_MAGIC_V1 &&
1467                                  lmv_is_restriping(lmv))
1468                                 mdt_restripe_update_add(info, o);
1469                 }
1470                 if (ma->ma_valid & MA_LMV_DEF) {
1471                         /* Return -ENOTSUPP for old client */
1472                         if (!mdt_is_striped_client(req->rq_export))
1473                                 RETURN(-ENOTSUPP);
1474                         LASSERT(S_ISDIR(la->la_mode));
1475                         /*
1476                          * when ll_dir_getstripe() gets default LMV, it
1477                          * checks mbo_eadatasize.
1478                          */
1479                         if (!(ma->ma_valid & MA_LMV))
1480                                 repbody->mbo_eadatasize =
1481                                         ma->ma_default_lmv_size;
1482                         repbody->mbo_valid |= (OBD_MD_FLDIREA |
1483                                                OBD_MD_DEFAULT_MEA);
1484                 }
1485                 CDEBUG(D_VFSTRACE,
1486                        "dirent count %llu stripe count %u MDT count %d\n",
1487                        ma->ma_attr.la_dirent_count, stripe_count,
1488                        atomic_read(&mdt->mdt_mds_mds_conns) + 1);
1489                 if (ma->ma_attr.la_dirent_count != LU_DIRENT_COUNT_UNSET &&
1490                     ma->ma_attr.la_dirent_count >
1491                         mdt->mdt_restriper.mdr_dir_split_count &&
1492                     !fid_is_root(mdt_object_fid(o)) &&
1493                     mdt->mdt_enable_dir_auto_split &&
1494                     !o->mot_restriping &&
1495                     stripe_count < atomic_read(&mdt->mdt_mds_mds_conns) + 1)
1496                         mdt_auto_split_add(info, o);
1497         } else if (S_ISLNK(la->la_mode) &&
1498                    reqbody->mbo_valid & OBD_MD_LINKNAME) {
1499                 buffer->lb_buf = ma->ma_lmm;
1500                 /* eadatasize from client includes NULL-terminator, so
1501                  * there is no need to read it */
1502                 buffer->lb_len = reqbody->mbo_eadatasize - 1;
1503                 rc = mo_readlink(env, next, buffer);
1504                 if (unlikely(rc <= 0)) {
1505                         CERROR("%s: readlink failed for "DFID": rc = %d\n",
1506                                mdt_obd_name(info->mti_mdt),
1507                                PFID(mdt_object_fid(o)), rc);
1508                         rc = -EFAULT;
1509                 } else {
1510                         int print_limit = min_t(int, PAGE_SIZE - 128, rc);
1511
1512                         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_READLINK_EPROTO))
1513                                 rc -= 2;
1514                         repbody->mbo_valid |= OBD_MD_LINKNAME;
1515                         /* we need to report back size with NULL-terminator
1516                          * because client expects that */
1517                         repbody->mbo_eadatasize = rc + 1;
1518                         if (repbody->mbo_eadatasize != reqbody->mbo_eadatasize)
1519                                 CDEBUG(D_INODE, "%s: Read shorter symlink %d "
1520                                        "on "DFID ", expected %d\n",
1521                                        mdt_obd_name(info->mti_mdt),
1522                                        rc, PFID(mdt_object_fid(o)),
1523                                        reqbody->mbo_eadatasize - 1);
1524                         /* NULL terminate */
1525                         ((char *)ma->ma_lmm)[rc] = 0;
1526
1527                         /* If the total CDEBUG() size is larger than a page, it
1528                          * will print a warning to the console, avoid this by
1529                          * printing just the last part of the symlink. */
1530                         CDEBUG(D_INODE, "symlink dest %s%.*s, len = %d\n",
1531                                print_limit < rc ? "..." : "", print_limit,
1532                                (char *)ma->ma_lmm + rc - print_limit, rc);
1533                         rc = 0;
1534                 }
1535         }
1536
1537         if (reqbody->mbo_valid & OBD_MD_FLMODEASIZE) {
1538                 repbody->mbo_max_mdsize = info->mti_mdt->mdt_max_mdsize;
1539                 repbody->mbo_valid |= OBD_MD_FLMODEASIZE;
1540                 CDEBUG(D_INODE, "changing the max MD size to %u\n",
1541                        repbody->mbo_max_mdsize);
1542         }
1543
1544 #ifdef CONFIG_LUSTRE_FS_POSIX_ACL
1545         if ((exp_connect_flags(req->rq_export) & OBD_CONNECT_ACL) &&
1546                  (reqbody->mbo_valid & OBD_MD_FLACL)) {
1547                 struct lu_nodemap *nodemap = nodemap_get_from_exp(exp);
1548                 if (IS_ERR(nodemap))
1549                         RETURN(PTR_ERR(nodemap));
1550
1551                 rc = mdt_pack_acl2body(info, repbody, o, nodemap);
1552                 nodemap_putref(nodemap);
1553         }
1554 #endif
1555
1556 out:
1557         if (rc == 0)
1558                 mdt_counter_incr(req, LPROC_MDT_GETATTR,
1559                                  ktime_us_delta(ktime_get(), kstart));
1560
1561         RETURN(rc);
1562 }
1563
1564 static int mdt_getattr(struct tgt_session_info *tsi)
1565 {
1566         struct mdt_thread_info  *info = tsi2mdt_info(tsi);
1567         struct mdt_object       *obj = info->mti_object;
1568         struct req_capsule      *pill = info->mti_pill;
1569         struct mdt_body         *reqbody;
1570         struct mdt_body         *repbody;
1571         int rc, rc2;
1572         ENTRY;
1573
1574         if (unlikely(info->mti_object == NULL))
1575                 RETURN(-EPROTO);
1576
1577         reqbody = req_capsule_client_get(pill, &RMF_MDT_BODY);
1578         LASSERT(reqbody);
1579         LASSERT(lu_object_assert_exists(&obj->mot_obj));
1580
1581         /* Special case for Data-on-MDT files to get data version */
1582         if (unlikely(reqbody->mbo_valid & OBD_MD_FLDATAVERSION)) {
1583                 rc = mdt_data_version_get(tsi);
1584                 GOTO(out, rc);
1585         }
1586
1587         /* Unlike intent case where we need to pre-fill out buffers early on
1588          * in intent policy for ldlm reasons, here we can have a much better
1589          * guess at EA size by just reading it from disk.
1590          * Exceptions are readdir and (missing) directory striping */
1591         /* Readlink */
1592         if (reqbody->mbo_valid & OBD_MD_LINKNAME) {
1593                 /* No easy way to know how long is the symlink, but it cannot
1594                  * be more than PATH_MAX, so we allocate +1 */
1595                 rc = PATH_MAX + 1;
1596         /* A special case for fs ROOT: getattr there might fetch
1597          * default EA for entire fs, not just for this dir!
1598          */
1599         } else if (lu_fid_eq(mdt_object_fid(obj),
1600                              &info->mti_mdt->mdt_md_root_fid) &&
1601                    (reqbody->mbo_valid & OBD_MD_FLDIREA) &&
1602                    (lustre_msg_get_opc(mdt_info_req(info)->rq_reqmsg) ==
1603                                                                  MDS_GETATTR)) {
1604                 /* Should the default strping be bigger, mdt_fix_reply
1605                  * will reallocate */
1606                 rc = DEF_REP_MD_SIZE;
1607         } else {
1608                 /* Read the actual EA size from disk */
1609                 rc = mdt_attr_get_eabuf_size(info, obj);
1610         }
1611
1612         if (rc < 0)
1613                 GOTO(out, rc = err_serious(rc));
1614
1615         req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER, rc);
1616
1617         /* Set ACL reply buffer size as LUSTRE_POSIX_ACL_MAX_SIZE_OLD
1618          * by default. If the target object has more ACL entries, then
1619          * enlarge the buffer when necessary. */
1620         req_capsule_set_size(pill, &RMF_ACL, RCL_SERVER,
1621                              LUSTRE_POSIX_ACL_MAX_SIZE_OLD);
1622
1623         rc = req_capsule_server_pack(pill);
1624         if (unlikely(rc != 0))
1625                 GOTO(out, rc = err_serious(rc));
1626
1627         repbody = req_capsule_server_get(pill, &RMF_MDT_BODY);
1628         LASSERT(repbody != NULL);
1629         repbody->mbo_eadatasize = 0;
1630         repbody->mbo_aclsize = 0;
1631
1632         rc = mdt_check_ucred(info);
1633         if (unlikely(rc))
1634                 GOTO(out_shrink, rc);
1635
1636         info->mti_cross_ref = !!(reqbody->mbo_valid & OBD_MD_FLCROSSREF);
1637
1638         rc = mdt_getattr_internal(info, obj, 0);
1639         EXIT;
1640 out_shrink:
1641         mdt_client_compatibility(info);
1642         rc2 = mdt_fix_reply(info);
1643         if (rc == 0)
1644                 rc = rc2;
1645 out:
1646         mdt_thread_info_fini(info);
1647         return rc;
1648 }
1649
1650 /**
1651  * Handler of layout intent RPC requiring the layout modification
1652  *
1653  * \param[in]  info     thread environment
1654  * \param[in]  obj      object
1655  * \param[out] lhc      object ldlm lock handle
1656  * \param[in]  layout   layout change descriptor
1657  *
1658  * \retval 0    on success
1659  * \retval < 0  error code
1660  */
1661 int mdt_layout_change(struct mdt_thread_info *info, struct mdt_object *obj,
1662                       struct mdt_lock_handle *lhc,
1663                       struct md_layout_change *layout)
1664 {
1665         int rc;
1666
1667         ENTRY;
1668
1669         if (!mdt_object_exists(obj))
1670                 RETURN(-ENOENT);
1671
1672         if (!S_ISREG(lu_object_attr(&obj->mot_obj)))
1673                 RETURN(-EINVAL);
1674
1675         rc = mo_permission(info->mti_env, NULL, mdt_object_child(obj), NULL,
1676                            MAY_WRITE);
1677         if (rc)
1678                 RETURN(rc);
1679
1680         rc = mdt_check_resent_lock(info, obj, lhc);
1681         if (rc < 0)
1682                 RETURN(rc);
1683
1684         if (rc > 0) {
1685                 /* not resent */
1686                 __u64 lockpart = MDS_INODELOCK_LAYOUT;
1687
1688                 /* take layout lock to prepare layout change */
1689                 if (layout->mlc_opc == MD_LAYOUT_WRITE)
1690                         lockpart |= MDS_INODELOCK_UPDATE;
1691
1692                 mdt_lock_handle_init(lhc);
1693                 mdt_lock_reg_init(lhc, LCK_EX);
1694                 rc = mdt_reint_object_lock(info, obj, lhc, lockpart, false);
1695                 if (rc)
1696                         RETURN(rc);
1697         }
1698
1699         mutex_lock(&obj->mot_som_mutex);
1700         rc = mo_layout_change(info->mti_env, mdt_object_child(obj), layout);
1701         mutex_unlock(&obj->mot_som_mutex);
1702
1703         if (rc)
1704                 mdt_object_unlock(info, obj, lhc, 1);
1705
1706         RETURN(rc);
1707 }
1708
1709 /**
1710  * Exchange MOF_LOV_CREATED flags between two objects after a
1711  * layout swap. No assumption is made on whether o1 or o2 have
1712  * created objects or not.
1713  *
1714  * \param[in,out] o1    First swap layout object
1715  * \param[in,out] o2    Second swap layout object
1716  */
1717 static void mdt_swap_lov_flag(struct mdt_object *o1, struct mdt_object *o2)
1718 {
1719         unsigned int o1_lov_created = o1->mot_lov_created;
1720
1721         mutex_lock(&o1->mot_lov_mutex);
1722         mutex_lock(&o2->mot_lov_mutex);
1723
1724         o1->mot_lov_created = o2->mot_lov_created;
1725         o2->mot_lov_created = o1_lov_created;
1726
1727         mutex_unlock(&o2->mot_lov_mutex);
1728         mutex_unlock(&o1->mot_lov_mutex);
1729 }
1730
1731 static int mdt_swap_layouts(struct tgt_session_info *tsi)
1732 {
1733         struct mdt_thread_info  *info;
1734         struct ptlrpc_request   *req = tgt_ses_req(tsi);
1735         struct obd_export       *exp = req->rq_export;
1736         struct mdt_object       *o1, *o2, *o;
1737         struct mdt_lock_handle  *lh1, *lh2;
1738         struct mdc_swap_layouts *msl;
1739         int                      rc;
1740         ENTRY;
1741
1742         /* client does not support layout lock, so layout swaping
1743          * is disabled.
1744          * FIXME: there is a problem for old clients which don't support
1745          * layout lock yet. If those clients have already opened the file
1746          * they won't be notified at all so that old layout may still be
1747          * used to do IO. This can be fixed after file release is landed by
1748          * doing exclusive open and taking full EX ibits lock. - Jinshan */
1749         if (!exp_connect_layout(exp))
1750                 RETURN(-EOPNOTSUPP);
1751
1752         info = tsi2mdt_info(tsi);
1753         if (unlikely(info->mti_object == NULL))
1754                 RETURN(-EPROTO);
1755
1756         if (info->mti_dlm_req != NULL)
1757                 ldlm_request_cancel(req, info->mti_dlm_req, 0, LATF_SKIP);
1758
1759         o1 = info->mti_object;
1760         o = o2 = mdt_object_find(info->mti_env, info->mti_mdt,
1761                                 &info->mti_body->mbo_fid2);
1762         if (IS_ERR(o))
1763                 GOTO(out, rc = PTR_ERR(o));
1764
1765         if (mdt_object_remote(o) || !mdt_object_exists(o)) /* remote object */
1766                 GOTO(put, rc = -ENOENT);
1767
1768         rc = lu_fid_cmp(&info->mti_body->mbo_fid1, &info->mti_body->mbo_fid2);
1769         if (unlikely(rc == 0)) /* same file, you kidding me? no-op. */
1770                 GOTO(put, rc);
1771
1772         if (rc < 0)
1773                 swap(o1, o2);
1774
1775         /* permission check. Make sure the calling process having permission
1776          * to write both files. */
1777         rc = mo_permission(info->mti_env, NULL, mdt_object_child(o1), NULL,
1778                            MAY_WRITE);
1779         if (rc < 0)
1780                 GOTO(put, rc);
1781
1782         rc = mo_permission(info->mti_env, NULL, mdt_object_child(o2), NULL,
1783                            MAY_WRITE);
1784         if (rc < 0)
1785                 GOTO(put, rc);
1786
1787         msl = req_capsule_client_get(info->mti_pill, &RMF_SWAP_LAYOUTS);
1788         if (msl == NULL)
1789                 GOTO(put, rc = -EPROTO);
1790
1791         lh1 = &info->mti_lh[MDT_LH_NEW];
1792         mdt_lock_reg_init(lh1, LCK_EX);
1793         lh2 = &info->mti_lh[MDT_LH_OLD];
1794         mdt_lock_reg_init(lh2, LCK_EX);
1795
1796         rc = mdt_object_lock(info, o1, lh1, MDS_INODELOCK_LAYOUT |
1797                              MDS_INODELOCK_XATTR);
1798         if (rc < 0)
1799                 GOTO(put, rc);
1800
1801         rc = mdt_object_lock(info, o2, lh2, MDS_INODELOCK_LAYOUT |
1802                              MDS_INODELOCK_XATTR);
1803         if (rc < 0)
1804                 GOTO(unlock1, rc);
1805
1806         rc = mo_swap_layouts(info->mti_env, mdt_object_child(o1),
1807                              mdt_object_child(o2), msl->msl_flags);
1808         if (rc < 0)
1809                 GOTO(unlock2, rc);
1810
1811         mdt_swap_lov_flag(o1, o2);
1812
1813 unlock2:
1814         mdt_object_unlock(info, o2, lh2, rc);
1815 unlock1:
1816         mdt_object_unlock(info, o1, lh1, rc);
1817 put:
1818         mdt_object_put(info->mti_env, o);
1819 out:
1820         mdt_thread_info_fini(info);
1821         RETURN(rc);
1822 }
1823
1824 static int mdt_raw_lookup(struct mdt_thread_info *info,
1825                           struct mdt_object *parent,
1826                           const struct lu_name *lname,
1827                           struct ldlm_reply *ldlm_rep)
1828 {
1829         struct lu_fid   *child_fid = &info->mti_tmp_fid1;
1830         int              rc;
1831         ENTRY;
1832
1833         LASSERT(!info->mti_cross_ref);
1834
1835         /* Only got the fid of this obj by name */
1836         fid_zero(child_fid);
1837         rc = mdo_lookup(info->mti_env, mdt_object_child(info->mti_object),
1838                         lname, child_fid, &info->mti_spec);
1839         if (rc == 0) {
1840                 struct mdt_body *repbody;
1841
1842                 repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
1843                 repbody->mbo_fid1 = *child_fid;
1844                 repbody->mbo_valid = OBD_MD_FLID;
1845                 mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_POS);
1846         } else if (rc == -ENOENT) {
1847                 mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_NEG);
1848         }
1849
1850         RETURN(rc);
1851 }
1852
1853 /*
1854  * UPDATE lock should be taken against parent, and be released before exit;
1855  * child_bits lock should be taken against child, and be returned back:
1856  *            (1)normal request should release the child lock;
1857  *            (2)intent request will grant the lock to client.
1858  */
1859 static int mdt_getattr_name_lock(struct mdt_thread_info *info,
1860                                  struct mdt_lock_handle *lhc,
1861                                  __u64 child_bits,
1862                                  struct ldlm_reply *ldlm_rep)
1863 {
1864         struct ptlrpc_request *req = mdt_info_req(info);
1865         struct mdt_body *reqbody = NULL;
1866         struct mdt_object *parent = info->mti_object;
1867         struct mdt_object *child = NULL;
1868         struct lu_fid *child_fid = &info->mti_tmp_fid1;
1869         struct lu_name *lname = NULL;
1870         struct mdt_lock_handle *lhp = NULL;
1871         struct ldlm_lock *lock;
1872         struct req_capsule *pill = info->mti_pill;
1873         __u64 try_bits = 0;
1874         bool is_resent;
1875         int ma_need = 0;
1876         int rc;
1877
1878         ENTRY;
1879
1880         is_resent = lustre_handle_is_used(&lhc->mlh_reg_lh);
1881         LASSERT(ergo(is_resent,
1882                      lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT));
1883
1884         if (parent == NULL)
1885                 RETURN(-ENOENT);
1886
1887         if (info->mti_cross_ref) {
1888                 /* Only getattr on the child. Parent is on another node. */
1889                 mdt_set_disposition(info, ldlm_rep,
1890                                     DISP_LOOKUP_EXECD | DISP_LOOKUP_POS);
1891                 child = parent;
1892                 CDEBUG(D_INODE, "partial getattr_name child_fid = "DFID", "
1893                        "ldlm_rep = %p\n",
1894                        PFID(mdt_object_fid(child)), ldlm_rep);
1895
1896                 rc = mdt_check_resent_lock(info, child, lhc);
1897                 if (rc < 0) {
1898                         RETURN(rc);
1899                 } else if (rc > 0) {
1900                         mdt_lock_handle_init(lhc);
1901                         mdt_lock_reg_init(lhc, LCK_PR);
1902
1903                         /*
1904                          * Object's name entry is on another MDS, it will
1905                          * request PERM lock only because LOOKUP lock is owned
1906                          * by the MDS where name entry resides.
1907                          *
1908                          * TODO: it should try layout lock too. - Jinshan
1909                          */
1910                         child_bits &= ~(MDS_INODELOCK_LOOKUP |
1911                                         MDS_INODELOCK_LAYOUT);
1912                         child_bits |= MDS_INODELOCK_PERM;
1913
1914                         rc = mdt_object_lock(info, child, lhc, child_bits);
1915                         if (rc < 0)
1916                                 RETURN(rc);
1917                 }
1918
1919                 /* Finally, we can get attr for child. */
1920                 if (!mdt_object_exists(child)) {
1921                         LU_OBJECT_DEBUG(D_INFO, info->mti_env,
1922                                         &child->mot_obj,
1923                                         "remote object doesn't exist.");
1924                         mdt_object_unlock(info, child, lhc, 1);
1925                         RETURN(-ENOENT);
1926                 }
1927
1928                 rc = mdt_getattr_internal(info, child, 0);
1929                 if (unlikely(rc != 0)) {
1930                         mdt_object_unlock(info, child, lhc, 1);
1931                         RETURN(rc);
1932                 }
1933
1934                 rc = mdt_pack_secctx_in_reply(info, child);
1935                 if (unlikely(rc)) {
1936                         mdt_object_unlock(info, child, lhc, 1);
1937                         RETURN(rc);
1938                 }
1939
1940                 rc = mdt_pack_encctx_in_reply(info, child);
1941                 if (unlikely(rc))
1942                         mdt_object_unlock(info, child, lhc, 1);
1943                 RETURN(rc);
1944         }
1945
1946         lname = &info->mti_name;
1947         mdt_name_unpack(pill, &RMF_NAME, lname, MNF_FIX_ANON);
1948
1949         if (lu_name_is_valid(lname)) {
1950                 if (mdt_object_remote(parent)) {
1951                         CERROR("%s: parent "DFID" is on remote target\n",
1952                                mdt_obd_name(info->mti_mdt),
1953                                PFID(mdt_object_fid(parent)));
1954                         RETURN(-EPROTO);
1955                 }
1956
1957                 CDEBUG(D_INODE, "getattr with lock for "DFID"/"DNAME", "
1958                        "ldlm_rep = %p\n", PFID(mdt_object_fid(parent)),
1959                        PNAME(lname), ldlm_rep);
1960         } else {
1961                 reqbody = req_capsule_client_get(pill, &RMF_MDT_BODY);
1962                 if (unlikely(reqbody == NULL))
1963                         RETURN(err_serious(-EPROTO));
1964
1965                 *child_fid = reqbody->mbo_fid2;
1966                 if (unlikely(!fid_is_sane(child_fid)))
1967                         RETURN(err_serious(-EINVAL));
1968
1969                 if (lu_fid_eq(mdt_object_fid(parent), child_fid)) {
1970                         mdt_object_get(info->mti_env, parent);
1971                         child = parent;
1972                 } else {
1973                         child = mdt_object_find(info->mti_env, info->mti_mdt,
1974                                                 child_fid);
1975                         if (IS_ERR(child))
1976                                 RETURN(PTR_ERR(child));
1977                 }
1978
1979                 if (mdt_object_remote(child)) {
1980                         CERROR("%s: child "DFID" is on remote target\n",
1981                                mdt_obd_name(info->mti_mdt),
1982                                PFID(mdt_object_fid(child)));
1983                         GOTO(out_child, rc = -EPROTO);
1984                 }
1985
1986                 /* don't fetch LOOKUP lock if it's remote object */
1987                 rc = mdt_is_remote_object(info, parent, child);
1988                 if (rc < 0)
1989                         GOTO(out_child, rc);
1990                 if (rc)
1991                         child_bits &= ~MDS_INODELOCK_LOOKUP;
1992
1993                 CDEBUG(D_INODE, "getattr with lock for "DFID"/"DFID", "
1994                        "ldlm_rep = %p\n",
1995                        PFID(mdt_object_fid(parent)),
1996                        PFID(&reqbody->mbo_fid2), ldlm_rep);
1997         }
1998
1999         mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_EXECD);
2000
2001         if (unlikely(!mdt_object_exists(parent)) && lu_name_is_valid(lname)) {
2002                 LU_OBJECT_DEBUG(D_INODE, info->mti_env,
2003                                 &parent->mot_obj,
2004                                 "Parent doesn't exist!");
2005                 GOTO(out_child, rc = -ESTALE);
2006         }
2007
2008         if (lu_name_is_valid(lname)) {
2009                 /* Always allow to lookup ".." */
2010                 if (unlikely(lname->ln_namelen == 2 &&
2011                              lname->ln_name[0] == '.' &&
2012                              lname->ln_name[1] == '.'))
2013                         info->mti_spec.sp_permitted = 1;
2014
2015                 if (info->mti_body->mbo_valid == OBD_MD_FLID) {
2016                         rc = mdt_raw_lookup(info, parent, lname, ldlm_rep);
2017
2018                         RETURN(rc);
2019                 }
2020
2021                 /* step 1: lock parent only if parent is a directory */
2022                 if (S_ISDIR(lu_object_attr(&parent->mot_obj))) {
2023                         lhp = &info->mti_lh[MDT_LH_PARENT];
2024                         mdt_lock_pdo_init(lhp, LCK_PR, lname);
2025                         rc = mdt_object_lock(info, parent, lhp,
2026                                              MDS_INODELOCK_UPDATE);
2027                         if (unlikely(rc != 0))
2028                                 RETURN(rc);
2029                 }
2030
2031                 /* step 2: lookup child's fid by name */
2032                 fid_zero(child_fid);
2033                 rc = mdo_lookup(info->mti_env, mdt_object_child(parent), lname,
2034                                 child_fid, &info->mti_spec);
2035                 if (rc == -ENOENT)
2036                         mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_NEG);
2037
2038                 if (rc != 0)
2039                         GOTO(unlock_parent, rc);
2040
2041                 child = mdt_object_find(info->mti_env, info->mti_mdt,
2042                                         child_fid);
2043                 if (unlikely(IS_ERR(child)))
2044                         GOTO(unlock_parent, rc = PTR_ERR(child));
2045         }
2046
2047         mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_POS);
2048
2049         /* step 3: lock child regardless if it is local or remote. */
2050         LASSERT(child);
2051
2052         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_RESEND, obd_timeout * 2);
2053         if (!mdt_object_exists(child)) {
2054                 LU_OBJECT_DEBUG(D_INODE, info->mti_env,
2055                                 &child->mot_obj,
2056                                 "Object doesn't exist!");
2057                 GOTO(out_child, rc = -ENOENT);
2058         }
2059
2060         rc = mdt_check_resent_lock(info, child, lhc);
2061         if (rc < 0) {
2062                 GOTO(out_child, rc);
2063         } else if (rc > 0) {
2064                 mdt_lock_handle_init(lhc);
2065                 mdt_lock_reg_init(lhc, LCK_PR);
2066
2067                 if (!(child_bits & MDS_INODELOCK_UPDATE) &&
2068                     !mdt_object_remote(child)) {
2069                         struct md_attr *ma = &info->mti_attr;
2070
2071                         ma->ma_valid = 0;
2072                         ma->ma_need = MA_INODE;
2073                         rc = mdt_attr_get_complex(info, child, ma);
2074                         if (unlikely(rc != 0))
2075                                 GOTO(out_child, rc);
2076
2077                         /* If the file has not been changed for some time, we
2078                          * return not only a LOOKUP lock, but also an UPDATE
2079                          * lock and this might save us RPC on later STAT. For
2080                          * directories, it also let negative dentry cache start
2081                          * working for this dir. */
2082                         if (ma->ma_valid & MA_INODE &&
2083                             ma->ma_attr.la_valid & LA_CTIME &&
2084                             info->mti_mdt->mdt_namespace->ns_ctime_age_limit +
2085                             ma->ma_attr.la_ctime < ktime_get_real_seconds())
2086                                 child_bits |= MDS_INODELOCK_UPDATE;
2087                 }
2088
2089                 /* layout lock must be granted in a best-effort way
2090                  * for IT operations */
2091                 LASSERT(!(child_bits & MDS_INODELOCK_LAYOUT));
2092                 if (S_ISREG(lu_object_attr(&child->mot_obj)) &&
2093                     !mdt_object_remote(child) && ldlm_rep != NULL) {
2094                         if (!OBD_FAIL_CHECK(OBD_FAIL_MDS_NO_LL_GETATTR) &&
2095                             exp_connect_layout(info->mti_exp)) {
2096                                 /* try to grant layout lock for regular file. */
2097                                 try_bits = MDS_INODELOCK_LAYOUT;
2098                         }
2099                         /* Acquire DOM lock in advance for data-on-mdt file */
2100                         if (child != parent)
2101                                 try_bits |= MDS_INODELOCK_DOM;
2102                 }
2103
2104                 if (try_bits != 0) {
2105                         /* try layout lock, it may fail to be granted due to
2106                          * contention at LOOKUP or UPDATE */
2107                         rc = mdt_object_lock_try(info, child, lhc, &child_bits,
2108                                                  try_bits, false);
2109                         if (child_bits & MDS_INODELOCK_LAYOUT)
2110                                 ma_need |= MA_LOV;
2111                 } else {
2112                         /* Do not enqueue the UPDATE lock from MDT(cross-MDT),
2113                          * client will enqueue the lock to the remote MDT */
2114                         if (mdt_object_remote(child))
2115                                 child_bits &= ~MDS_INODELOCK_UPDATE;
2116                         rc = mdt_object_lock(info, child, lhc, child_bits);
2117                 }
2118                 if (unlikely(rc != 0))
2119                         GOTO(out_child, rc);
2120         }
2121
2122         /* finally, we can get attr for child. */
2123         rc = mdt_getattr_internal(info, child, ma_need);
2124         if (unlikely(rc != 0)) {
2125                 mdt_object_unlock(info, child, lhc, 1);
2126                 GOTO(out_child, rc);
2127         }
2128
2129         rc = mdt_pack_secctx_in_reply(info, child);
2130         if (unlikely(rc)) {
2131                 mdt_object_unlock(info, child, lhc, 1);
2132                 GOTO(out_child, rc);
2133         }
2134
2135         rc = mdt_pack_encctx_in_reply(info, child);
2136         if (unlikely(rc)) {
2137                 mdt_object_unlock(info, child, lhc, 1);
2138                 GOTO(out_child, rc);
2139         }
2140
2141         lock = ldlm_handle2lock(&lhc->mlh_reg_lh);
2142         if (lock) {
2143                 /* Debugging code. */
2144                 LDLM_DEBUG(lock, "Returning lock to client");
2145                 LASSERTF(fid_res_name_eq(mdt_object_fid(child),
2146                                          &lock->l_resource->lr_name),
2147                          "Lock res_id: "DLDLMRES", fid: "DFID"\n",
2148                          PLDLMRES(lock->l_resource),
2149                          PFID(mdt_object_fid(child)));
2150
2151                 if (S_ISREG(lu_object_attr(&child->mot_obj)) &&
2152                     !mdt_object_remote(child) && child != parent) {
2153                         mdt_object_put(info->mti_env, child);
2154                         rc = mdt_pack_size2body(info, child_fid,
2155                                                 &lhc->mlh_reg_lh);
2156                         if (rc != 0 && child_bits & MDS_INODELOCK_DOM) {
2157                                 /* DOM lock was taken in advance but this is
2158                                  * not DoM file. Drop the lock.
2159                                  */
2160                                 lock_res_and_lock(lock);
2161                                 ldlm_inodebits_drop(lock, MDS_INODELOCK_DOM);
2162                                 unlock_res_and_lock(lock);
2163                         }
2164                         LDLM_LOCK_PUT(lock);
2165                         GOTO(unlock_parent, rc = 0);
2166                 }
2167                 LDLM_LOCK_PUT(lock);
2168         }
2169
2170         EXIT;
2171 out_child:
2172         if (child)
2173                 mdt_object_put(info->mti_env, child);
2174 unlock_parent:
2175         if (lhp)
2176                 mdt_object_unlock(info, parent, lhp, 1);
2177         return rc;
2178 }
2179
2180 /* normal handler: should release the child lock */
2181 static int mdt_getattr_name(struct tgt_session_info *tsi)
2182 {
2183         struct mdt_thread_info  *info = tsi2mdt_info(tsi);
2184         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_CHILD];
2185         struct mdt_body *reqbody;
2186         struct mdt_body *repbody;
2187         int rc, rc2;
2188
2189         ENTRY;
2190
2191         reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
2192         LASSERT(reqbody != NULL);
2193         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
2194         LASSERT(repbody != NULL);
2195
2196         info->mti_cross_ref = !!(reqbody->mbo_valid & OBD_MD_FLCROSSREF);
2197         repbody->mbo_eadatasize = 0;
2198         repbody->mbo_aclsize = 0;
2199
2200         rc = mdt_init_ucred(info, reqbody);
2201         if (unlikely(rc))
2202                 GOTO(out_shrink, rc);
2203
2204         rc = mdt_getattr_name_lock(info, lhc, MDS_INODELOCK_UPDATE, NULL);
2205         if (lustre_handle_is_used(&lhc->mlh_reg_lh)) {
2206                 ldlm_lock_decref(&lhc->mlh_reg_lh, lhc->mlh_reg_mode);
2207                 lhc->mlh_reg_lh.cookie = 0;
2208         }
2209         mdt_exit_ucred(info);
2210         EXIT;
2211 out_shrink:
2212         mdt_client_compatibility(info);
2213         rc2 = mdt_fix_reply(info);
2214         if (rc == 0)
2215                 rc = rc2;
2216         mdt_thread_info_fini(info);
2217         return rc;
2218 }
2219
2220 static int mdt_rmfid_unlink(struct mdt_thread_info *info,
2221                             const struct lu_fid *pfid,
2222                             const struct lu_name *name,
2223                             struct mdt_object *obj, s64 ctime)
2224 {
2225         struct lu_fid *child_fid = &info->mti_tmp_fid1;
2226         struct ldlm_enqueue_info *einfo = &info->mti_einfo[0];
2227         struct mdt_device *mdt = info->mti_mdt;
2228         struct md_attr *ma = &info->mti_attr;
2229         struct mdt_lock_handle *parent_lh;
2230         struct mdt_lock_handle *child_lh;
2231         struct mdt_object *pobj;
2232         bool cos_incompat = false;
2233         int rc;
2234         ENTRY;
2235
2236         pobj = mdt_object_find(info->mti_env, mdt, pfid);
2237         if (IS_ERR(pobj))
2238                 GOTO(out, rc = PTR_ERR(pobj));
2239
2240         parent_lh = &info->mti_lh[MDT_LH_PARENT];
2241         mdt_lock_pdo_init(parent_lh, LCK_PW, name);
2242         rc = mdt_object_lock(info, pobj, parent_lh, MDS_INODELOCK_UPDATE);
2243         if (rc != 0)
2244                 GOTO(put_parent, rc);
2245
2246         if (mdt_object_remote(pobj))
2247                 cos_incompat = true;
2248
2249         rc = mdo_lookup(info->mti_env, mdt_object_child(pobj),
2250                         name, child_fid, &info->mti_spec);
2251         if (rc != 0)
2252                 GOTO(unlock_parent, rc);
2253
2254         if (!lu_fid_eq(child_fid, mdt_object_fid(obj)))
2255                 GOTO(unlock_parent, rc = -EREMCHG);
2256
2257         child_lh = &info->mti_lh[MDT_LH_CHILD];
2258         mdt_lock_reg_init(child_lh, LCK_EX);
2259         rc = mdt_reint_striped_lock(info, obj, child_lh,
2260                                     MDS_INODELOCK_LOOKUP | MDS_INODELOCK_UPDATE,
2261                                     einfo, cos_incompat);
2262         if (rc != 0)
2263                 GOTO(unlock_parent, rc);
2264
2265         if (atomic_read(&obj->mot_open_count)) {
2266                 CDEBUG(D_OTHER, "object "DFID" open, skip\n",
2267                        PFID(mdt_object_fid(obj)));
2268                 GOTO(unlock_child, rc = -EBUSY);
2269         }
2270
2271         ma->ma_need = 0;
2272         ma->ma_valid = MA_INODE;
2273         ma->ma_attr.la_valid = LA_CTIME;
2274         ma->ma_attr.la_ctime = ctime;
2275
2276         mutex_lock(&obj->mot_lov_mutex);
2277
2278         rc = mdo_unlink(info->mti_env, mdt_object_child(pobj),
2279                         mdt_object_child(obj), name, ma, 0);
2280
2281         mutex_unlock(&obj->mot_lov_mutex);
2282
2283 unlock_child:
2284         mdt_reint_striped_unlock(info, obj, child_lh, einfo, 1);
2285 unlock_parent:
2286         mdt_object_unlock(info, pobj, parent_lh, 1);
2287 put_parent:
2288         mdt_object_put(info->mti_env, pobj);
2289 out:
2290         RETURN(rc);
2291 }
2292
2293 static int mdt_rmfid_check_permission(struct mdt_thread_info *info,
2294                                         struct mdt_object *obj)
2295 {
2296         struct lu_ucred *uc = lu_ucred(info->mti_env);
2297         struct md_attr *ma = &info->mti_attr;
2298         struct lu_attr *la = &ma->ma_attr;
2299         int rc = 0;
2300         ENTRY;
2301
2302         ma->ma_need = MA_INODE;
2303         rc = mo_attr_get(info->mti_env, mdt_object_child(obj), ma);
2304         if (rc)
2305                 GOTO(out, rc);
2306
2307         if (la->la_flags & LUSTRE_IMMUTABLE_FL)
2308                         rc = -EACCES;
2309
2310         if (md_capable(uc, CAP_DAC_OVERRIDE))
2311                 RETURN(0);
2312         if (uc->uc_fsuid == la->la_uid) {
2313                 if ((la->la_mode & S_IWUSR) == 0)
2314                         rc = -EACCES;
2315         } else if (uc->uc_fsgid == la->la_gid) {
2316                 if ((la->la_mode & S_IWGRP) == 0)
2317                         rc = -EACCES;
2318         } else if ((la->la_mode & S_IWOTH) == 0) {
2319                         rc = -EACCES;
2320         }
2321
2322 out:
2323         RETURN(rc);
2324 }
2325
2326 static int mdt_rmfid_one(struct mdt_thread_info *info, struct lu_fid *fid,
2327                          s64 ctime)
2328 {
2329         struct mdt_device *mdt = info->mti_mdt;
2330         struct mdt_object *obj = NULL;
2331         struct linkea_data ldata = { NULL };
2332         struct lu_buf *buf = &info->mti_big_buf;
2333         struct lu_name *name = &info->mti_name;
2334         struct lu_fid *pfid = &info->mti_tmp_fid1;
2335         struct link_ea_header *leh;
2336         struct link_ea_entry *lee;
2337         int reclen, count, rc = 0;
2338         ENTRY;
2339
2340         if (!fid_is_sane(fid))
2341                 GOTO(out, rc = -EINVAL);
2342
2343         if (!fid_is_namespace_visible(fid))
2344                 GOTO(out, rc = -EINVAL);
2345
2346         obj = mdt_object_find(info->mti_env, mdt, fid);
2347         if (IS_ERR(obj))
2348                 GOTO(out, rc = PTR_ERR(obj));
2349
2350         if (mdt_object_remote(obj))
2351                 GOTO(out, rc = -EREMOTE);
2352         if (!mdt_object_exists(obj) || lu_object_is_dying(&obj->mot_header))
2353                 GOTO(out, rc = -ENOENT);
2354
2355         rc = mdt_rmfid_check_permission(info, obj);
2356         if (rc)
2357                 GOTO(out, rc);
2358
2359         /* take LinkEA */
2360         buf = lu_buf_check_and_alloc(buf, PATH_MAX);
2361         if (!buf->lb_buf)
2362                 GOTO(out, rc = -ENOMEM);
2363
2364         ldata.ld_buf = buf;
2365         rc = mdt_links_read(info, obj, &ldata);
2366         if (rc)
2367                 GOTO(out, rc);
2368
2369         leh = buf->lb_buf;
2370         lee = (struct link_ea_entry *)(leh + 1);
2371         for (count = 0; count < leh->leh_reccount; count++) {
2372                 /* remove every hardlink */
2373                 linkea_entry_unpack(lee, &reclen, name, pfid);
2374                 lee = (struct link_ea_entry *) ((char *)lee + reclen);
2375                 rc = mdt_rmfid_unlink(info, pfid, name, obj, ctime);
2376                 if (rc)
2377                         break;
2378         }
2379
2380 out:
2381         if (obj && !IS_ERR(obj))
2382                 mdt_object_put(info->mti_env, obj);
2383         if (info->mti_big_buf.lb_buf)
2384                 lu_buf_free(&info->mti_big_buf);
2385
2386         RETURN(rc);
2387 }
2388
2389 static int mdt_rmfid(struct tgt_session_info *tsi)
2390 {
2391         struct mdt_thread_info *mti = tsi2mdt_info(tsi);
2392         struct mdt_body *reqbody;
2393         struct lu_fid *fids, *rfids;
2394         int bufsize, rc;
2395         __u32 *rcs;
2396         int i, nr;
2397         ENTRY;
2398
2399         reqbody = req_capsule_client_get(tsi->tsi_pill, &RMF_MDT_BODY);
2400         if (reqbody == NULL)
2401                 RETURN(-EPROTO);
2402         bufsize = req_capsule_get_size(tsi->tsi_pill, &RMF_FID_ARRAY,
2403                                        RCL_CLIENT);
2404         nr = bufsize / sizeof(struct lu_fid);
2405         if (nr * sizeof(struct lu_fid) != bufsize)
2406                 RETURN(-EINVAL);
2407         req_capsule_set_size(tsi->tsi_pill, &RMF_RCS,
2408                              RCL_SERVER, nr * sizeof(__u32));
2409         req_capsule_set_size(tsi->tsi_pill, &RMF_FID_ARRAY,
2410                              RCL_SERVER, nr * sizeof(struct lu_fid));
2411         rc = req_capsule_server_pack(tsi->tsi_pill);
2412         if (rc)
2413                 GOTO(out, rc = err_serious(rc));
2414         fids = req_capsule_client_get(tsi->tsi_pill, &RMF_FID_ARRAY);
2415         if (fids == NULL)
2416                 RETURN(-EPROTO);
2417         rcs = req_capsule_server_get(tsi->tsi_pill, &RMF_RCS);
2418         LASSERT(rcs);
2419         rfids = req_capsule_server_get(tsi->tsi_pill, &RMF_FID_ARRAY);
2420         LASSERT(rfids);
2421
2422         mdt_init_ucred(mti, reqbody);
2423         for (i = 0; i < nr; i++) {
2424                 rfids[i] = fids[i];
2425                 rcs[i] = mdt_rmfid_one(mti, fids + i, reqbody->mbo_ctime);
2426         }
2427         mdt_exit_ucred(mti);
2428
2429 out:
2430         RETURN(rc);
2431 }
2432
2433 static int mdt_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
2434                          void *karg, void __user *uarg);
2435
2436 static int mdt_set_info(struct tgt_session_info *tsi)
2437 {
2438         struct ptlrpc_request   *req = tgt_ses_req(tsi);
2439         char                    *key;
2440         void                    *val;
2441         int                      keylen, vallen, rc = 0;
2442
2443         ENTRY;
2444
2445         key = req_capsule_client_get(tsi->tsi_pill, &RMF_SETINFO_KEY);
2446         if (key == NULL) {
2447                 DEBUG_REQ(D_HA, req, "no set_info key");
2448                 RETURN(err_serious(-EFAULT));
2449         }
2450
2451         keylen = req_capsule_get_size(tsi->tsi_pill, &RMF_SETINFO_KEY,
2452                                       RCL_CLIENT);
2453
2454         val = req_capsule_client_get(tsi->tsi_pill, &RMF_SETINFO_VAL);
2455         if (val == NULL) {
2456                 DEBUG_REQ(D_HA, req, "no set_info val");
2457                 RETURN(err_serious(-EFAULT));
2458         }
2459
2460         vallen = req_capsule_get_size(tsi->tsi_pill, &RMF_SETINFO_VAL,
2461                                       RCL_CLIENT);
2462
2463         /* Swab any part of val you need to here */
2464         if (KEY_IS(KEY_READ_ONLY)) {
2465                 spin_lock(&req->rq_export->exp_lock);
2466                 if (*(__u32 *)val)
2467                         *exp_connect_flags_ptr(req->rq_export) |=
2468                                 OBD_CONNECT_RDONLY;
2469                 else
2470                         *exp_connect_flags_ptr(req->rq_export) &=
2471                                 ~OBD_CONNECT_RDONLY;
2472                 spin_unlock(&req->rq_export->exp_lock);
2473         } else if (KEY_IS(KEY_CHANGELOG_CLEAR)) {
2474                 struct changelog_setinfo *cs = val;
2475
2476                 if (vallen != sizeof(*cs)) {
2477                         CERROR("%s: bad changelog_clear setinfo size %d\n",
2478                                tgt_name(tsi->tsi_tgt), vallen);
2479                         RETURN(-EINVAL);
2480                 }
2481                 if (ptlrpc_req_need_swab(req)) {
2482                         __swab64s(&cs->cs_recno);
2483                         __swab32s(&cs->cs_id);
2484                 }
2485
2486                 if (!mdt_is_rootadmin(tsi2mdt_info(tsi)))
2487                         RETURN(-EACCES);
2488                 rc = mdt_iocontrol(OBD_IOC_CHANGELOG_CLEAR, req->rq_export,
2489                                    vallen, val, NULL);
2490         } else if (KEY_IS(KEY_EVICT_BY_NID)) {
2491                 if (vallen > 0)
2492                         obd_export_evict_by_nid(req->rq_export->exp_obd, val);
2493         } else {
2494                 RETURN(-EINVAL);
2495         }
2496         RETURN(rc);
2497 }
2498
2499 static int mdt_readpage(struct tgt_session_info *tsi)
2500 {
2501         struct mdt_thread_info  *info = mdt_th_info(tsi->tsi_env);
2502         struct mdt_object       *object = mdt_obj(tsi->tsi_corpus);
2503         struct lu_rdpg          *rdpg = &info->mti_u.rdpg.mti_rdpg;
2504         const struct mdt_body   *reqbody = tsi->tsi_mdt_body;
2505         struct mdt_body         *repbody;
2506         int                      rc;
2507         int                      i;
2508
2509         ENTRY;
2510
2511         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_READPAGE_PACK))
2512                 RETURN(err_serious(-ENOMEM));
2513
2514         repbody = req_capsule_server_get(tsi->tsi_pill, &RMF_MDT_BODY);
2515         if (repbody == NULL || reqbody == NULL)
2516                 RETURN(err_serious(-EFAULT));
2517
2518         /*
2519          * prepare @rdpg before calling lower layers and transfer itself. Here
2520          * reqbody->size contains offset of where to start to read and
2521          * reqbody->nlink contains number bytes to read.
2522          */
2523         rdpg->rp_hash = reqbody->mbo_size;
2524         if (rdpg->rp_hash != reqbody->mbo_size) {
2525                 CERROR("Invalid hash: %#llx != %#llx\n",
2526                        rdpg->rp_hash, reqbody->mbo_size);
2527                 RETURN(-EFAULT);
2528         }
2529
2530         rdpg->rp_attrs = reqbody->mbo_mode;
2531         if (exp_connect_flags(tsi->tsi_exp) & OBD_CONNECT_64BITHASH)
2532                 rdpg->rp_attrs |= LUDA_64BITHASH;
2533         rdpg->rp_count  = min_t(unsigned int, reqbody->mbo_nlink,
2534                                 exp_max_brw_size(tsi->tsi_exp));
2535         rdpg->rp_npages = (rdpg->rp_count + PAGE_SIZE - 1) >>
2536                           PAGE_SHIFT;
2537         OBD_ALLOC_PTR_ARRAY_LARGE(rdpg->rp_pages, rdpg->rp_npages);
2538         if (rdpg->rp_pages == NULL)
2539                 RETURN(-ENOMEM);
2540
2541         for (i = 0; i < rdpg->rp_npages; ++i) {
2542                 rdpg->rp_pages[i] = alloc_page(GFP_NOFS);
2543                 if (rdpg->rp_pages[i] == NULL)
2544                         GOTO(free_rdpg, rc = -ENOMEM);
2545         }
2546
2547         /* call lower layers to fill allocated pages with directory data */
2548         rc = mo_readpage(tsi->tsi_env, mdt_object_child(object), rdpg);
2549         if (rc < 0)
2550                 GOTO(free_rdpg, rc);
2551
2552         /* send pages to client */
2553         rc = tgt_sendpage(tsi, rdpg, rc);
2554
2555         EXIT;
2556 free_rdpg:
2557
2558         for (i = 0; i < rdpg->rp_npages; i++)
2559                 if (rdpg->rp_pages[i] != NULL)
2560                         __free_page(rdpg->rp_pages[i]);
2561         OBD_FREE_PTR_ARRAY_LARGE(rdpg->rp_pages, rdpg->rp_npages);
2562
2563         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_SENDPAGE))
2564                 RETURN(0);
2565
2566         return rc;
2567 }
2568
2569 static int mdt_fix_attr_ucred(struct mdt_thread_info *info, __u32 op)
2570 {
2571         struct lu_ucred *uc = mdt_ucred_check(info);
2572         struct lu_attr *attr = &info->mti_attr.ma_attr;
2573
2574         if (uc == NULL)
2575                 return -EINVAL;
2576
2577         if (op != REINT_SETATTR) {
2578                 if ((attr->la_valid & LA_UID) && (attr->la_uid != -1))
2579                         attr->la_uid = uc->uc_fsuid;
2580                 /* for S_ISGID, inherit gid from his parent, such work will be
2581                  * done in cmm/mdd layer, here set all cases as uc->uc_fsgid. */
2582                 if ((attr->la_valid & LA_GID) && (attr->la_gid != -1))
2583                         attr->la_gid = uc->uc_fsgid;
2584         }
2585
2586         return 0;
2587 }
2588
2589 static inline bool mdt_is_readonly_open(struct mdt_thread_info *info, __u32 op)
2590 {
2591         return op == REINT_OPEN &&
2592              !(info->mti_spec.sp_cr_flags & (MDS_FMODE_WRITE | MDS_OPEN_CREAT));
2593 }
2594
2595 static void mdt_preset_secctx_size(struct mdt_thread_info *info)
2596 {
2597         struct req_capsule *pill = info->mti_pill;
2598
2599         if (req_capsule_has_field(pill, &RMF_FILE_SECCTX,
2600                                   RCL_SERVER) &&
2601             req_capsule_has_field(pill, &RMF_FILE_SECCTX_NAME,
2602                                   RCL_CLIENT)) {
2603                 if (req_capsule_get_size(pill, &RMF_FILE_SECCTX_NAME,
2604                                          RCL_CLIENT) != 0)
2605                         /* pre-set size in server part with max size */
2606                         req_capsule_set_size(pill, &RMF_FILE_SECCTX,
2607                                              RCL_SERVER,
2608                                              OBD_MAX_DEFAULT_EA_SIZE);
2609                 else
2610                         req_capsule_set_size(pill, &RMF_FILE_SECCTX,
2611                                              RCL_SERVER, 0);
2612         }
2613 }
2614
2615 static void mdt_preset_encctx_size(struct mdt_thread_info *info)
2616 {
2617         struct req_capsule *pill = info->mti_pill;
2618
2619         if (req_capsule_has_field(pill, &RMF_FILE_ENCCTX,
2620                                   RCL_SERVER))
2621                 /* pre-set size in server part with max size */
2622                 req_capsule_set_size(pill, &RMF_FILE_ENCCTX,
2623                                      RCL_SERVER,
2624                                      info->mti_mdt->mdt_max_mdsize);
2625 }
2626
2627 static int mdt_reint_internal(struct mdt_thread_info *info,
2628                               struct mdt_lock_handle *lhc,
2629                               __u32 op)
2630 {
2631         struct req_capsule      *pill = info->mti_pill;
2632         struct mdt_body         *repbody;
2633         int                      rc = 0, rc2;
2634
2635         ENTRY;
2636
2637         rc = mdt_reint_unpack(info, op);
2638         if (rc != 0) {
2639                 CERROR("Can't unpack reint, rc %d\n", rc);
2640                 RETURN(err_serious(rc));
2641         }
2642
2643
2644         /* check if the file system is set to readonly. O_RDONLY open
2645          * is still allowed even the file system is set to readonly mode */
2646         if (mdt_rdonly(info->mti_exp) && !mdt_is_readonly_open(info, op))
2647                 RETURN(err_serious(-EROFS));
2648
2649         /* for replay (no_create) lmm is not needed, client has it already */
2650         if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
2651                 req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER,
2652                                      DEF_REP_MD_SIZE);
2653
2654         /* llog cookies are always 0, the field is kept for compatibility */
2655         if (req_capsule_has_field(pill, &RMF_LOGCOOKIES, RCL_SERVER))
2656                 req_capsule_set_size(pill, &RMF_LOGCOOKIES, RCL_SERVER, 0);
2657
2658         /* Set ACL reply buffer size as LUSTRE_POSIX_ACL_MAX_SIZE_OLD
2659          * by default. If the target object has more ACL entries, then
2660          * enlarge the buffer when necessary. */
2661         if (req_capsule_has_field(pill, &RMF_ACL, RCL_SERVER))
2662                 req_capsule_set_size(pill, &RMF_ACL, RCL_SERVER,
2663                                      LUSTRE_POSIX_ACL_MAX_SIZE_OLD);
2664
2665         mdt_preset_secctx_size(info);
2666         mdt_preset_encctx_size(info);
2667
2668         rc = req_capsule_server_pack(pill);
2669         if (rc != 0) {
2670                 CERROR("Can't pack response, rc %d\n", rc);
2671                 RETURN(err_serious(rc));
2672         }
2673
2674         if (req_capsule_has_field(pill, &RMF_MDT_BODY, RCL_SERVER)) {
2675                 repbody = req_capsule_server_get(pill, &RMF_MDT_BODY);
2676                 LASSERT(repbody);
2677                 repbody->mbo_eadatasize = 0;
2678                 repbody->mbo_aclsize = 0;
2679         }
2680
2681         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_REINT_DELAY, 10);
2682
2683         /* for replay no cookkie / lmm need, because client have this already */
2684         if (info->mti_spec.no_create)
2685                 if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
2686                         req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER, 0);
2687
2688         rc = mdt_init_ucred_reint(info);
2689         if (rc)
2690                 GOTO(out_shrink, rc);
2691
2692         rc = mdt_fix_attr_ucred(info, op);
2693         if (rc != 0)
2694                 GOTO(out_ucred, rc = err_serious(rc));
2695
2696         rc = mdt_check_resent(info, mdt_reconstruct, lhc);
2697         if (rc < 0) {
2698                 GOTO(out_ucred, rc);
2699         } else if (rc == 1) {
2700                 DEBUG_REQ(D_INODE, mdt_info_req(info), "resent opt");
2701                 rc = lustre_msg_get_status(mdt_info_req(info)->rq_repmsg);
2702                 GOTO(out_ucred, rc);
2703         }
2704         rc = mdt_reint_rec(info, lhc);
2705         EXIT;
2706 out_ucred:
2707         mdt_exit_ucred(info);
2708 out_shrink:
2709         mdt_client_compatibility(info);
2710
2711         rc2 = mdt_fix_reply(info);
2712         if (rc == 0)
2713                 rc = rc2;
2714
2715         /*
2716          * Data-on-MDT optimization - read data along with OPEN and return it
2717          * in reply when possible.
2718          */
2719         if (rc == 0 && op == REINT_OPEN && !req_is_replay(pill->rc_req))
2720                 rc = mdt_dom_read_on_open(info, info->mti_mdt,
2721                                           &lhc->mlh_reg_lh);
2722
2723         return rc;
2724 }
2725
2726 static long mdt_reint_opcode(struct ptlrpc_request *req,
2727                              const struct req_format **fmt)
2728 {
2729         struct mdt_device       *mdt;
2730         struct mdt_rec_reint    *rec;
2731         long                     opc;
2732
2733         rec = req_capsule_client_get(&req->rq_pill, &RMF_REC_REINT);
2734         if (rec != NULL) {
2735                 opc = rec->rr_opcode;
2736                 DEBUG_REQ(D_INODE, req, "reint opt = %ld", opc);
2737                 if (opc < REINT_MAX && fmt[opc] != NULL)
2738                         req_capsule_extend(&req->rq_pill, fmt[opc]);
2739                 else {
2740                         mdt = mdt_exp2dev(req->rq_export);
2741                         CERROR("%s: Unsupported opcode '%ld' from client '%s':"
2742                                " rc = %d\n", req->rq_export->exp_obd->obd_name,
2743                                opc, mdt->mdt_ldlm_client->cli_name, -EFAULT);
2744                         opc = err_serious(-EFAULT);
2745                 }
2746         } else {
2747                 opc = err_serious(-EFAULT);
2748         }
2749         return opc;
2750 }
2751
2752 static int mdt_reint(struct tgt_session_info *tsi)
2753 {
2754         long opc;
2755         int  rc;
2756         static const struct req_format *reint_fmts[REINT_MAX] = {
2757                 [REINT_SETATTR]  = &RQF_MDS_REINT_SETATTR,
2758                 [REINT_CREATE]   = &RQF_MDS_REINT_CREATE,
2759                 [REINT_LINK]     = &RQF_MDS_REINT_LINK,
2760                 [REINT_UNLINK]   = &RQF_MDS_REINT_UNLINK,
2761                 [REINT_RENAME]   = &RQF_MDS_REINT_RENAME,
2762                 [REINT_OPEN]     = &RQF_MDS_REINT_OPEN,
2763                 [REINT_SETXATTR] = &RQF_MDS_REINT_SETXATTR,
2764                 [REINT_RMENTRY]  = &RQF_MDS_REINT_UNLINK,
2765                 [REINT_MIGRATE]  = &RQF_MDS_REINT_MIGRATE,
2766                 [REINT_RESYNC]   = &RQF_MDS_REINT_RESYNC,
2767         };
2768
2769         ENTRY;
2770
2771         opc = mdt_reint_opcode(tgt_ses_req(tsi), reint_fmts);
2772         if (opc >= 0) {
2773                 struct mdt_thread_info *info = tsi2mdt_info(tsi);
2774                 /*
2775                  * No lock possible here from client to pass it to reint code
2776                  * path.
2777                  */
2778                 rc = mdt_reint_internal(info, NULL, opc);
2779                 mdt_thread_info_fini(info);
2780         } else {
2781                 rc = opc;
2782         }
2783
2784         tsi->tsi_reply_fail_id = OBD_FAIL_MDS_REINT_NET_REP;
2785         RETURN(rc);
2786 }
2787
2788 /* this should sync the whole device */
2789 int mdt_device_sync(const struct lu_env *env, struct mdt_device *mdt)
2790 {
2791         struct dt_device *dt = mdt->mdt_bottom;
2792         int rc;
2793         ENTRY;
2794
2795         rc = dt->dd_ops->dt_sync(env, dt);
2796         RETURN(rc);
2797 }
2798
2799 /* this should sync this object */
2800 static int mdt_object_sync(const struct lu_env *env, struct obd_export *exp,
2801                            struct mdt_object *mo)
2802 {
2803         int rc = 0;
2804
2805         ENTRY;
2806
2807         if (!mdt_object_exists(mo)) {
2808                 CWARN("%s: non existing object "DFID": rc = %d\n",
2809                       exp->exp_obd->obd_name, PFID(mdt_object_fid(mo)),
2810                       -ESTALE);
2811                 RETURN(-ESTALE);
2812         }
2813
2814         if (S_ISREG(lu_object_attr(&mo->mot_obj))) {
2815                 struct lu_target *tgt = tgt_ses_info(env)->tsi_tgt;
2816                 dt_obj_version_t version;
2817
2818                 version = dt_version_get(env, mdt_obj2dt(mo));
2819                 if (version > tgt->lut_obd->obd_last_committed)
2820                         rc = mo_object_sync(env, mdt_object_child(mo));
2821         } else {
2822                 rc = mo_object_sync(env, mdt_object_child(mo));
2823         }
2824
2825         RETURN(rc);
2826 }
2827
2828 static int mdt_sync(struct tgt_session_info *tsi)
2829 {
2830         struct ptlrpc_request   *req = tgt_ses_req(tsi);
2831         struct req_capsule      *pill = tsi->tsi_pill;
2832         struct mdt_body         *body;
2833         ktime_t                  kstart = ktime_get();
2834         int                      rc;
2835
2836         ENTRY;
2837
2838         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_SYNC_PACK))
2839                 RETURN(err_serious(-ENOMEM));
2840
2841         if (fid_seq(&tsi->tsi_mdt_body->mbo_fid1) == 0) {
2842                 rc = mdt_device_sync(tsi->tsi_env, mdt_exp2dev(tsi->tsi_exp));
2843         } else {
2844                 struct mdt_thread_info *info = tsi2mdt_info(tsi);
2845
2846                 if (unlikely(info->mti_object == NULL))
2847                         RETURN(-EPROTO);
2848
2849                 /* sync an object */
2850                 rc = mdt_object_sync(tsi->tsi_env, tsi->tsi_exp,
2851                                      info->mti_object);
2852                 if (rc == 0) {
2853                         const struct lu_fid *fid;
2854                         struct lu_attr *la = &info->mti_attr.ma_attr;
2855
2856                         info->mti_attr.ma_need = MA_INODE;
2857                         info->mti_attr.ma_valid = 0;
2858                         rc = mdt_attr_get_complex(info, info->mti_object,
2859                                                   &info->mti_attr);
2860                         if (rc == 0) {
2861                                 body = req_capsule_server_get(pill,
2862                                                               &RMF_MDT_BODY);
2863                                 fid = mdt_object_fid(info->mti_object);
2864                                 mdt_pack_attr2body(info, body, la, fid);
2865                         }
2866                 }
2867                 mdt_thread_info_fini(info);
2868         }
2869         if (rc == 0)
2870                 mdt_counter_incr(req, LPROC_MDT_SYNC,
2871                                  ktime_us_delta(ktime_get(), kstart));
2872
2873         RETURN(rc);
2874 }
2875
2876 static int mdt_data_sync(struct tgt_session_info *tsi)
2877 {
2878         struct mdt_thread_info *info;
2879         struct mdt_device *mdt = mdt_exp2dev(tsi->tsi_exp);
2880         struct ost_body *body = tsi->tsi_ost_body;
2881         struct ost_body *repbody;
2882         struct mdt_object *mo = NULL;
2883         struct md_attr *ma;
2884         int rc = 0;
2885
2886         ENTRY;
2887
2888         repbody = req_capsule_server_get(tsi->tsi_pill, &RMF_OST_BODY);
2889
2890         /* if no fid is specified then do nothing,
2891          * device sync is done via MDS_SYNC */
2892         if (fid_is_zero(&tsi->tsi_fid))
2893                 RETURN(0);
2894
2895         mo = mdt_object_find(tsi->tsi_env, mdt, &tsi->tsi_fid);
2896         if (IS_ERR(mo))
2897                 RETURN(PTR_ERR(mo));
2898
2899         rc = mdt_object_sync(tsi->tsi_env, tsi->tsi_exp, mo);
2900         if (rc)
2901                 GOTO(put, rc);
2902
2903         repbody->oa.o_oi = body->oa.o_oi;
2904         repbody->oa.o_valid = OBD_MD_FLID | OBD_MD_FLGROUP;
2905
2906         info = tsi2mdt_info(tsi);
2907         ma = &info->mti_attr;
2908         ma->ma_need = MA_INODE;
2909         ma->ma_valid = 0;
2910         rc = mdt_attr_get_complex(info, mo, ma);
2911         if (rc == 0)
2912                 obdo_from_la(&repbody->oa, &ma->ma_attr, VALID_FLAGS);
2913         else
2914                 rc = 0;
2915         mdt_thread_info_fini(info);
2916
2917         EXIT;
2918 put:
2919         if (mo != NULL)
2920                 mdt_object_put(tsi->tsi_env, mo);
2921         return rc;
2922 }
2923
2924 /*
2925  * Handle quota control requests to consult current usage/limit, but also
2926  * to configure quota enforcement
2927  */
2928 static int mdt_quotactl(struct tgt_session_info *tsi)
2929 {
2930         struct obd_export *exp  = tsi->tsi_exp;
2931         struct req_capsule *pill = tsi->tsi_pill;
2932         struct obd_quotactl *oqctl, *repoqc;
2933         int id, rc;
2934         struct mdt_device *mdt = mdt_exp2dev(exp);
2935         struct lu_device *qmt = mdt->mdt_qmt_dev;
2936         struct lu_nodemap *nodemap;
2937         ENTRY;
2938
2939         oqctl = req_capsule_client_get(pill, &RMF_OBD_QUOTACTL);
2940         if (!oqctl)
2941                 RETURN(err_serious(-EPROTO));
2942
2943         rc = req_capsule_server_pack(pill);
2944         if (rc)
2945                 RETURN(err_serious(rc));
2946
2947         nodemap = nodemap_get_from_exp(exp);
2948         if (IS_ERR(nodemap))
2949                 RETURN(PTR_ERR(nodemap));
2950
2951         switch (oqctl->qc_cmd) {
2952                 /* master quotactl */
2953         case Q_SETINFO:
2954         case Q_SETQUOTA:
2955         case LUSTRE_Q_SETDEFAULT:
2956         case LUSTRE_Q_SETQUOTAPOOL:
2957         case LUSTRE_Q_SETINFOPOOL:
2958                 if (!nodemap_can_setquota(nodemap))
2959                         GOTO(out_nodemap, rc = -EPERM);
2960                 /* fallthrough */
2961         case Q_GETINFO:
2962         case Q_GETQUOTA:
2963         case LUSTRE_Q_GETDEFAULT:
2964         case LUSTRE_Q_GETQUOTAPOOL:
2965         case LUSTRE_Q_GETINFOPOOL:
2966                 if (qmt == NULL)
2967                         GOTO(out_nodemap, rc = -EOPNOTSUPP);
2968                 /* slave quotactl */
2969                 /* fallthrough */
2970         case Q_GETOINFO:
2971         case Q_GETOQUOTA:
2972                 break;
2973         default:
2974                 rc = -EFAULT;
2975                 CERROR("%s: unsupported quotactl command %d: rc = %d\n",
2976                        mdt_obd_name(mdt), oqctl->qc_cmd, rc);
2977                 GOTO(out_nodemap, rc);
2978         }
2979
2980         id = oqctl->qc_id;
2981         switch (oqctl->qc_type) {
2982         case USRQUOTA:
2983                 id = nodemap_map_id(nodemap, NODEMAP_UID,
2984                                     NODEMAP_CLIENT_TO_FS, id);
2985                 break;
2986         case GRPQUOTA:
2987                 id = nodemap_map_id(nodemap, NODEMAP_GID,
2988                                     NODEMAP_CLIENT_TO_FS, id);
2989                 break;
2990         case PRJQUOTA:
2991                 /* todo: check/map project id */
2992                 id = oqctl->qc_id;
2993                 break;
2994         default:
2995                 GOTO(out_nodemap, rc = -EOPNOTSUPP);
2996         }
2997         repoqc = req_capsule_server_get(pill, &RMF_OBD_QUOTACTL);
2998         if (repoqc == NULL)
2999                 GOTO(out_nodemap, rc = err_serious(-EFAULT));
3000
3001         if (oqctl->qc_cmd == Q_SETINFO || oqctl->qc_cmd == Q_SETQUOTA)
3002                 barrier_exit(tsi->tsi_tgt->lut_bottom);
3003
3004         if (oqctl->qc_id != id)
3005                 swap(oqctl->qc_id, id);
3006
3007         if (oqctl->qc_cmd == Q_SETINFO || oqctl->qc_cmd == Q_SETQUOTA) {
3008                 if (unlikely(!barrier_entry(tsi->tsi_tgt->lut_bottom)))
3009                         RETURN(-EINPROGRESS);
3010         }
3011
3012         switch (oqctl->qc_cmd) {
3013
3014         case Q_GETINFO:
3015         case Q_SETINFO:
3016         case Q_SETQUOTA:
3017         case Q_GETQUOTA:
3018         case LUSTRE_Q_SETDEFAULT:
3019         case LUSTRE_Q_GETDEFAULT:
3020         case LUSTRE_Q_SETQUOTAPOOL:
3021         case LUSTRE_Q_GETQUOTAPOOL:
3022         case LUSTRE_Q_SETINFOPOOL:
3023         case LUSTRE_Q_GETINFOPOOL:
3024                 /* forward quotactl request to QMT */
3025                 rc = qmt_hdls.qmth_quotactl(tsi->tsi_env, qmt, oqctl);
3026                 break;
3027
3028         case Q_GETOINFO:
3029         case Q_GETOQUOTA:
3030                 /* slave quotactl */
3031                 rc = lquotactl_slv(tsi->tsi_env, tsi->tsi_tgt->lut_bottom,
3032                                    oqctl);
3033                 break;
3034
3035         default:
3036                 CERROR("Unsupported quotactl command: %d\n", oqctl->qc_cmd);
3037                 GOTO(out_nodemap, rc = -EFAULT);
3038         }
3039
3040         if (oqctl->qc_id != id)
3041                 swap(oqctl->qc_id, id);
3042
3043         QCTL_COPY(repoqc, oqctl);
3044         EXIT;
3045
3046 out_nodemap:
3047         nodemap_putref(nodemap);
3048
3049         return rc;
3050 }
3051
3052 /** clone llog ctxt from child (mdd)
3053  * This allows remote llog (replicator) access.
3054  * We can either pass all llog RPCs (eg mdt_llog_create) on to child where the
3055  * context was originally set up, or we can handle them directly.
3056  * I choose the latter, but that means I need any llog
3057  * contexts set up by child to be accessable by the mdt.  So we clone the
3058  * context into our context list here.
3059  */
3060 static int mdt_llog_ctxt_clone(const struct lu_env *env, struct mdt_device *mdt,
3061                                int idx)
3062 {
3063         struct md_device  *next = mdt->mdt_child;
3064         struct llog_ctxt *ctxt;
3065         int rc;
3066
3067         if (!llog_ctxt_null(mdt2obd_dev(mdt), idx))
3068                 return 0;
3069
3070         rc = next->md_ops->mdo_llog_ctxt_get(env, next, idx, (void **)&ctxt);
3071         if (rc || ctxt == NULL) {
3072                 return 0;
3073         }
3074
3075         rc = llog_group_set_ctxt(&mdt2obd_dev(mdt)->obd_olg, ctxt, idx);
3076         if (rc)
3077                 CERROR("Can't set mdt ctxt %d\n", rc);
3078
3079         return rc;
3080 }
3081
3082 static int mdt_llog_ctxt_unclone(const struct lu_env *env,
3083                                  struct mdt_device *mdt, int idx)
3084 {
3085         struct llog_ctxt *ctxt;
3086
3087         ctxt = llog_get_context(mdt2obd_dev(mdt), idx);
3088         if (ctxt == NULL)
3089                 return 0;
3090         /* Put once for the get we just did, and once for the clone */
3091         llog_ctxt_put(ctxt);
3092         llog_ctxt_put(ctxt);
3093         return 0;
3094 }
3095
3096 /*
3097  * sec context handlers
3098  */
3099 static int mdt_sec_ctx_handle(struct tgt_session_info *tsi)
3100 {
3101         CFS_FAIL_TIMEOUT(OBD_FAIL_SEC_CTX_HDL_PAUSE, cfs_fail_val);
3102
3103         return 0;
3104 }
3105
3106 /*
3107  * quota request handlers
3108  */
3109 static int mdt_quota_dqacq(struct tgt_session_info *tsi)
3110 {
3111         struct mdt_device       *mdt = mdt_exp2dev(tsi->tsi_exp);
3112         struct lu_device        *qmt = mdt->mdt_qmt_dev;
3113         int                      rc;
3114         ENTRY;
3115
3116         if (qmt == NULL)
3117                 RETURN(err_serious(-EOPNOTSUPP));
3118
3119         rc = qmt_hdls.qmth_dqacq(tsi->tsi_env, qmt, tgt_ses_req(tsi));
3120         RETURN(rc);
3121 }
3122
3123 struct mdt_object *mdt_object_new(const struct lu_env *env,
3124                                   struct mdt_device *d,
3125                                   const struct lu_fid *f)
3126 {
3127         struct lu_object_conf conf = { .loc_flags = LOC_F_NEW };
3128         struct lu_object *o;
3129         struct mdt_object *m;
3130         ENTRY;
3131
3132         CDEBUG(D_INFO, "Allocate object for "DFID"\n", PFID(f));
3133         o = lu_object_find(env, &d->mdt_lu_dev, f, &conf);
3134         if (unlikely(IS_ERR(o)))
3135                 m = (struct mdt_object *)o;
3136         else
3137                 m = mdt_obj(o);
3138         RETURN(m);
3139 }
3140
3141 struct mdt_object *mdt_object_find(const struct lu_env *env,
3142                                    struct mdt_device *d,
3143                                    const struct lu_fid *f)
3144 {
3145         struct lu_object *o;
3146         struct mdt_object *m;
3147         ENTRY;
3148
3149         CDEBUG(D_INFO, "Find object for "DFID"\n", PFID(f));
3150         o = lu_object_find(env, &d->mdt_lu_dev, f, NULL);
3151         if (unlikely(IS_ERR(o)))
3152                 m = (struct mdt_object *)o;
3153         else
3154                 m = mdt_obj(o);
3155
3156         RETURN(m);
3157 }
3158
3159 /**
3160  * Asyncronous commit for mdt device.
3161  *
3162  * Pass asynchonous commit call down the MDS stack.
3163  *
3164  * \param env environment
3165  * \param mdt the mdt device
3166  */
3167 static void mdt_device_commit_async(const struct lu_env *env,
3168                                     struct mdt_device *mdt)
3169 {
3170         struct dt_device *dt = mdt->mdt_bottom;
3171         int rc;
3172         ENTRY;
3173
3174         rc = dt->dd_ops->dt_commit_async(env, dt);
3175         if (unlikely(rc != 0))
3176                 CWARN("%s: async commit start failed: rc = %d\n",
3177                       mdt_obd_name(mdt), rc);
3178         atomic_inc(&mdt->mdt_async_commit_count);
3179         EXIT;
3180 }
3181
3182 /**
3183  * Mark the lock as "synchonous".
3184  *
3185  * Mark the lock to deffer transaction commit to the unlock time.
3186  *
3187  * \param lock the lock to mark as "synchonous"
3188  *
3189  * \see mdt_is_lock_sync
3190  * \see mdt_save_lock
3191  */
3192 static inline void mdt_set_lock_sync(struct ldlm_lock *lock)
3193 {
3194         lock->l_ast_data = (void*)1;
3195 }
3196
3197 /**
3198  * Check whehter the lock "synchonous" or not.
3199  *
3200  * \param lock the lock to check
3201  * \retval 1 the lock is "synchonous"
3202  * \retval 0 the lock isn't "synchronous"
3203  *
3204  * \see mdt_set_lock_sync
3205  * \see mdt_save_lock
3206  */
3207 static inline int mdt_is_lock_sync(struct ldlm_lock *lock)
3208 {
3209         return lock->l_ast_data != NULL;
3210 }
3211
3212 /**
3213  * Blocking AST for mdt locks.
3214  *
3215  * Starts transaction commit if in case of COS lock conflict or
3216  * deffers such a commit to the mdt_save_lock.
3217  *
3218  * \param lock the lock which blocks a request or cancelling lock
3219  * \param desc unused
3220  * \param data unused
3221  * \param flag indicates whether this cancelling or blocking callback
3222  * \retval 0
3223  * \see ldlm_blocking_ast_nocheck
3224  */
3225 int mdt_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
3226                      void *data, int flag)
3227 {
3228         struct obd_device *obd = ldlm_lock_to_ns(lock)->ns_obd;
3229         struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
3230         struct ldlm_cb_set_arg *arg = data;
3231         bool commit_async = false;
3232         int rc;
3233         ENTRY;
3234
3235         if (flag == LDLM_CB_CANCELING)
3236                 RETURN(0);
3237
3238         lock_res_and_lock(lock);
3239         if (lock->l_blocking_ast != mdt_blocking_ast) {
3240                 unlock_res_and_lock(lock);
3241                 RETURN(0);
3242         }
3243
3244         /* A blocking ast may be sent from ldlm_lock_decref_internal
3245          * when the last reference to a local lock was released and
3246          * during blocking event from ldlm_work_bl_ast_lock().
3247          * The 'data' parameter is l_ast_data in the first case and
3248          * callback arguments in the second one. Distinguish them by that.
3249          */
3250         if (!data || data == lock->l_ast_data || !arg->bl_desc)
3251                 goto skip_cos_checks;
3252
3253         if (lock->l_req_mode & (LCK_PW | LCK_EX)) {
3254                 if (mdt_cos_is_enabled(mdt)) {
3255                         if (!arg->bl_desc->bl_same_client)
3256                                 mdt_set_lock_sync(lock);
3257                 } else if (mdt_slc_is_enabled(mdt) &&
3258                            arg->bl_desc->bl_cos_incompat) {
3259                         mdt_set_lock_sync(lock);
3260                         /*
3261                          * we may do extra commit here, but there is a small
3262                          * window to miss a commit: lock was unlocked (saved),
3263                          * then a conflict lock queued and we come here, but
3264                          * REP-ACK not received, so lock was not converted to
3265                          * COS mode yet.
3266                          * Fortunately this window is quite small, so the
3267                          * extra commit should be rare (not to say distributed
3268                          * operation is rare too).
3269                          */
3270                         commit_async = true;
3271                 }
3272         } else if (lock->l_req_mode == LCK_COS) {
3273                 commit_async = true;
3274         }
3275
3276 skip_cos_checks:
3277         rc = ldlm_blocking_ast_nocheck(lock);
3278
3279         if (commit_async) {
3280                 struct lu_env env;
3281
3282                 rc = lu_env_init(&env, LCT_LOCAL);
3283                 if (unlikely(rc != 0))
3284                         CWARN("%s: lu_env initialization failed, cannot "
3285                               "start asynchronous commit: rc = %d\n",
3286                               obd->obd_name, rc);
3287                 else
3288                         mdt_device_commit_async(&env, mdt);
3289                 lu_env_fini(&env);
3290         }
3291         RETURN(rc);
3292 }
3293
3294 /*
3295  * Blocking AST for cross-MDT lock
3296  *
3297  * Discard lock from uncommitted_slc_locks and cancel it.
3298  *
3299  * \param lock  the lock which blocks a request or cancelling lock
3300  * \param desc  unused
3301  * \param data  unused
3302  * \param flag  indicates whether this cancelling or blocking callback
3303  * \retval      0 on success
3304  * \retval      negative number on error
3305  */
3306 int mdt_remote_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
3307                             void *data, int flag)
3308 {
3309         int rc = 0;
3310         ENTRY;
3311
3312         switch (flag) {
3313         case LDLM_CB_BLOCKING: {
3314                 struct lustre_handle lockh;
3315
3316                 ldlm_lock2handle(lock, &lockh);
3317                 rc = ldlm_cli_cancel(&lockh,
3318                         ldlm_is_atomic_cb(lock) ? 0 : LCF_ASYNC);
3319                 if (rc < 0) {
3320                         CDEBUG(D_INODE, "ldlm_cli_cancel: %d\n", rc);
3321                         RETURN(rc);
3322                 }
3323                 break;
3324         }
3325         case LDLM_CB_CANCELING: {
3326                 struct obd_device *obd = ldlm_lock_to_ns(lock)->ns_obd;
3327                 struct mdt_device *mdt =
3328                                 mdt_dev(obd->obd_lu_dev->ld_site->ls_top_dev);
3329
3330                 LDLM_DEBUG(lock, "Revoke remote lock\n");
3331
3332                 /* discard slc lock here so that it can be cleaned anytime,
3333                  * especially for cleanup_resource() */
3334                 tgt_discard_slc_lock(&mdt->mdt_lut, lock);
3335
3336                 /* once we cache lock, l_ast_data is set to mdt_object */
3337                 if (lock->l_ast_data != NULL) {
3338                         struct mdt_object *mo = lock->l_ast_data;
3339                         struct lu_env env;
3340
3341                         rc = lu_env_init(&env, LCT_MD_THREAD);
3342                         if (unlikely(rc != 0)) {
3343                                 CWARN("%s: lu_env initialization failed, object %p "DFID" is leaked!: rc = %d\n",
3344                                       obd->obd_name, mo,
3345                                       PFID(mdt_object_fid(mo)), rc);
3346                                 RETURN(rc);
3347                         }
3348
3349                         if (lock->l_policy_data.l_inodebits.bits &
3350                             (MDS_INODELOCK_XATTR | MDS_INODELOCK_UPDATE)) {
3351                                 rc = mo_invalidate(&env, mdt_object_child(mo));
3352                                 mo->mot_cache_attr = 0;
3353                         }
3354                         mdt_object_put(&env, mo);
3355                         lu_env_fini(&env);
3356                 }
3357                 break;
3358         }
3359         default:
3360                 LBUG();
3361         }
3362
3363         RETURN(rc);
3364 }
3365
3366 int mdt_check_resent_lock(struct mdt_thread_info *info,
3367                           struct mdt_object *mo,
3368                           struct mdt_lock_handle *lhc)
3369 {
3370         /* the lock might already be gotten in ldlm_handle_enqueue() */
3371         if (unlikely(lustre_handle_is_used(&lhc->mlh_reg_lh))) {
3372                 struct ptlrpc_request *req = mdt_info_req(info);
3373                 struct ldlm_lock      *lock;
3374
3375                 lock = ldlm_handle2lock(&lhc->mlh_reg_lh);
3376                 LASSERT(lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT);
3377                 if (lock == NULL) {
3378                         /* Lock is pinned by ldlm_handle_enqueue0() as it is
3379                          * a resend case, however, it could be already destroyed
3380                          * due to client eviction or a raced cancel RPC. */
3381                         LDLM_DEBUG_NOLOCK("Invalid lock handle %#llx",
3382                                           lhc->mlh_reg_lh.cookie);
3383                         RETURN(-ESTALE);
3384                 }
3385
3386                 if (!fid_res_name_eq(mdt_object_fid(mo),
3387                                      &lock->l_resource->lr_name)) {
3388                         CWARN("%s: Although resent, but still not "
3389                               "get child lock:"DFID"\n",
3390                               info->mti_exp->exp_obd->obd_name,
3391                               PFID(mdt_object_fid(mo)));
3392                         LDLM_LOCK_PUT(lock);
3393                         RETURN(-EPROTO);
3394                 }
3395                 LDLM_LOCK_PUT(lock);
3396                 return 0;
3397         }
3398         return 1;
3399 }
3400
3401 static void mdt_remote_object_lock_created_cb(struct ldlm_lock *lock)
3402 {
3403         mdt_object_get(NULL, lock->l_ast_data);
3404 }
3405
3406 int mdt_remote_object_lock_try(struct mdt_thread_info *mti,
3407                                struct mdt_object *o, const struct lu_fid *fid,
3408                                struct lustre_handle *lh, enum ldlm_mode mode,
3409                                __u64 *ibits, __u64 trybits, bool cache)
3410 {
3411         struct ldlm_enqueue_info *einfo = &mti->mti_remote_einfo;
3412         union ldlm_policy_data *policy = &mti->mti_policy;
3413         struct ldlm_res_id *res_id = &mti->mti_res_id;
3414         int rc = 0;
3415         ENTRY;
3416
3417         LASSERT(mdt_object_remote(o));
3418
3419         fid_build_reg_res_name(fid, res_id);
3420
3421         memset(einfo, 0, sizeof(*einfo));
3422         einfo->ei_type = LDLM_IBITS;
3423         einfo->ei_mode = mode;
3424         einfo->ei_cb_bl = mdt_remote_blocking_ast;
3425         einfo->ei_cb_cp = ldlm_completion_ast;
3426         einfo->ei_enq_slave = 0;
3427         einfo->ei_res_id = res_id;
3428
3429         if (cache) {
3430                 /*
3431                  * if we cache lock, couple lock with mdt_object, so that object
3432                  * can be easily found in lock ASTs.
3433                  */
3434                 einfo->ei_cbdata = o;
3435                 einfo->ei_cb_created = mdt_remote_object_lock_created_cb;
3436         }
3437
3438         memset(policy, 0, sizeof(*policy));
3439         policy->l_inodebits.bits = *ibits;
3440         policy->l_inodebits.try_bits = trybits;
3441
3442         rc = mo_object_lock(mti->mti_env, mdt_object_child(o), lh, einfo,
3443                             policy);
3444
3445         /* Return successfully acquired bits to a caller */
3446         if (rc == 0) {
3447                 struct ldlm_lock *lock = ldlm_handle2lock(lh);
3448
3449                 LASSERT(lock);
3450                 *ibits = lock->l_policy_data.l_inodebits.bits;
3451                 LDLM_LOCK_PUT(lock);
3452         }
3453         RETURN(rc);
3454 }
3455
3456 int mdt_remote_object_lock(struct mdt_thread_info *mti, struct mdt_object *o,
3457                            const struct lu_fid *fid, struct lustre_handle *lh,
3458                            enum ldlm_mode mode, __u64 ibits, bool cache)
3459 {
3460         return mdt_remote_object_lock_try(mti, o, fid, lh, mode, &ibits, 0,
3461                                           cache);
3462 }
3463
3464 int mdt_object_local_lock(struct mdt_thread_info *info, struct mdt_object *o,
3465                           struct mdt_lock_handle *lh, __u64 *ibits,
3466                           __u64 trybits, bool cos_incompat)
3467 {
3468         struct ldlm_namespace *ns = info->mti_mdt->mdt_namespace;
3469         union ldlm_policy_data *policy = &info->mti_policy;
3470         struct ldlm_res_id *res_id = &info->mti_res_id;
3471         __u64 dlmflags = 0, *cookie = NULL;
3472         int rc;
3473         ENTRY;
3474
3475         LASSERT(!lustre_handle_is_used(&lh->mlh_reg_lh));
3476         LASSERT(!lustre_handle_is_used(&lh->mlh_pdo_lh));
3477         LASSERT(lh->mlh_reg_mode != LCK_MINMODE);
3478         LASSERT(lh->mlh_type != MDT_NUL_LOCK);
3479
3480         if (cos_incompat) {
3481                 LASSERT(lh->mlh_reg_mode == LCK_PW ||
3482                         lh->mlh_reg_mode == LCK_EX);
3483                 dlmflags |= LDLM_FL_COS_INCOMPAT;
3484         } else if (mdt_cos_is_enabled(info->mti_mdt)) {
3485                 dlmflags |= LDLM_FL_COS_ENABLED;
3486         }
3487
3488         /* Only enqueue LOOKUP lock for remote object */
3489         LASSERT(ergo(mdt_object_remote(o), *ibits == MDS_INODELOCK_LOOKUP));
3490
3491         /* Lease lock are granted with LDLM_FL_CANCEL_ON_BLOCK */
3492         if (lh->mlh_type == MDT_REG_LOCK && lh->mlh_reg_mode == LCK_EX &&
3493             *ibits == MDS_INODELOCK_OPEN)
3494                 dlmflags |= LDLM_FL_CANCEL_ON_BLOCK;
3495
3496         if (lh->mlh_type == MDT_PDO_LOCK) {
3497                 /* check for exists after object is locked */
3498                 if (mdt_object_exists(o) == 0) {
3499                         /* Non-existent object shouldn't have PDO lock */
3500                         RETURN(-ESTALE);
3501                 } else {
3502                         /* Non-dir object shouldn't have PDO lock */
3503                         if (!S_ISDIR(lu_object_attr(&o->mot_obj)))
3504                                 RETURN(-ENOTDIR);
3505                 }
3506         }
3507
3508         fid_build_reg_res_name(mdt_object_fid(o), res_id);
3509         dlmflags |= LDLM_FL_ATOMIC_CB;
3510
3511         if (info->mti_exp)
3512                 cookie = &info->mti_exp->exp_handle.h_cookie;
3513
3514         /*
3515          * Take PDO lock on whole directory and build correct @res_id for lock
3516          * on part of directory.
3517          */
3518         if (lh->mlh_pdo_hash != 0) {
3519                 LASSERT(lh->mlh_type == MDT_PDO_LOCK);
3520                 mdt_lock_pdo_mode(info, o, lh);
3521                 if (lh->mlh_pdo_mode != LCK_NL) {
3522                         /*
3523                          * Do not use LDLM_FL_LOCAL_ONLY for parallel lock, it
3524                          * is never going to be sent to client and we do not
3525                          * want it slowed down due to possible cancels.
3526                          */
3527                         policy->l_inodebits.bits =
3528                                 *ibits & MDS_INODELOCK_UPDATE;
3529                         policy->l_inodebits.try_bits =
3530                                 trybits & MDS_INODELOCK_UPDATE;
3531                         /* at least one of them should be set */
3532                         LASSERT(policy->l_inodebits.bits |
3533                                 policy->l_inodebits.try_bits);
3534                         rc = mdt_fid_lock(info->mti_env, ns, &lh->mlh_pdo_lh,
3535                                           lh->mlh_pdo_mode, policy, res_id,
3536                                           dlmflags, cookie);
3537                         if (unlikely(rc != 0))
3538                                 GOTO(out_unlock, rc);
3539                 }
3540
3541                 /*
3542                  * Finish res_id initializing by name hash marking part of
3543                  * directory which is taking modification.
3544                  */
3545                 res_id->name[LUSTRE_RES_ID_HSH_OFF] = lh->mlh_pdo_hash;
3546         }
3547
3548         policy->l_inodebits.bits = *ibits;
3549         policy->l_inodebits.try_bits = trybits;
3550         policy->l_inodebits.li_gid = lh->mlh_gid;
3551
3552         /*
3553          * Use LDLM_FL_LOCAL_ONLY for this lock. We do not know yet if it is
3554          * going to be sent to client. If it is - mdt_intent_policy() path will
3555          * fix it up and turn FL_LOCAL flag off.
3556          */
3557         rc = mdt_fid_lock(info->mti_env, ns, &lh->mlh_reg_lh, lh->mlh_reg_mode,
3558                           policy, res_id, LDLM_FL_LOCAL_ONLY | dlmflags,
3559                           cookie);
3560 out_unlock:
3561         if (rc != 0)
3562                 mdt_object_unlock(info, o, lh, 1);
3563         else if (unlikely(OBD_FAIL_PRECHECK(OBD_FAIL_MDS_PDO_LOCK)) &&
3564                    lh->mlh_pdo_hash != 0 &&
3565                    (lh->mlh_reg_mode == LCK_PW || lh->mlh_reg_mode == LCK_EX))
3566                 OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_PDO_LOCK, 15);
3567
3568         /* Return successfully acquired bits to a caller */
3569         if (rc == 0) {
3570                 struct ldlm_lock *lock = ldlm_handle2lock(&lh->mlh_reg_lh);
3571
3572                 LASSERT(lock);
3573                 *ibits = lock->l_policy_data.l_inodebits.bits;
3574                 LDLM_LOCK_PUT(lock);
3575         }
3576         RETURN(rc);
3577 }
3578
3579 static int
3580 mdt_object_lock_internal(struct mdt_thread_info *info, struct mdt_object *o,
3581                          struct mdt_lock_handle *lh, __u64 *ibits,
3582                          __u64 trybits, bool cos_incompat)
3583 {
3584         struct mdt_lock_handle *local_lh = NULL;
3585         int rc;
3586         ENTRY;
3587
3588         if (!mdt_object_remote(o)) {
3589                 rc = mdt_object_local_lock(info, o, lh, ibits, trybits,
3590                                            cos_incompat);
3591                 RETURN(rc);
3592         }
3593
3594         /* XXX do not support PERM/LAYOUT/XATTR lock for remote object yet */
3595         *ibits &= ~(MDS_INODELOCK_PERM | MDS_INODELOCK_LAYOUT |
3596                     MDS_INODELOCK_XATTR);
3597
3598         /* Only enqueue LOOKUP lock for remote object */
3599         if (*ibits & MDS_INODELOCK_LOOKUP) {
3600                 __u64 local = MDS_INODELOCK_LOOKUP;
3601
3602                 rc = mdt_object_local_lock(info, o, lh, &local, 0,
3603                                            cos_incompat);
3604                 if (rc != ELDLM_OK)
3605                         RETURN(rc);
3606
3607                 local_lh = lh;
3608         }
3609
3610         if ((*ibits | trybits) & MDS_INODELOCK_UPDATE) {
3611                 /* Sigh, PDO needs to enqueue 2 locks right now, but
3612                  * enqueue RPC can only request 1 lock, to avoid extra
3613                  * RPC, so it will instead enqueue EX lock for remote
3614                  * object anyway XXX*/
3615                 if (lh->mlh_type == MDT_PDO_LOCK &&
3616                     lh->mlh_pdo_hash != 0) {
3617                         CDEBUG(D_INFO,
3618                                "%s: "DFID" convert PDO lock to EX lock.\n",
3619                                mdt_obd_name(info->mti_mdt),
3620                                PFID(mdt_object_fid(o)));
3621                         lh->mlh_pdo_hash = 0;
3622                         lh->mlh_rreg_mode = LCK_EX;
3623                         lh->mlh_type = MDT_REG_LOCK;
3624                 }
3625
3626                 rc = mdt_remote_object_lock_try(info, o, mdt_object_fid(o),
3627                                                 &lh->mlh_rreg_lh,
3628                                                 lh->mlh_rreg_mode,
3629                                                 ibits, trybits, false);
3630                 if (rc != ELDLM_OK) {
3631                         if (local_lh != NULL)
3632                                 mdt_object_unlock(info, o, local_lh, rc);
3633                         RETURN(rc);
3634                 }
3635         }
3636
3637         /* other components like LFSCK can use lockless access
3638          * and populate cache, so we better invalidate it */
3639         mo_invalidate(info->mti_env, mdt_object_child(o));
3640
3641         RETURN(0);
3642 }
3643
3644 int mdt_object_lock(struct mdt_thread_info *info, struct mdt_object *o,
3645                     struct mdt_lock_handle *lh, __u64 ibits)
3646 {
3647         return mdt_object_lock_internal(info, o, lh, &ibits, 0, false);
3648 }
3649
3650 int mdt_reint_object_lock(struct mdt_thread_info *info, struct mdt_object *o,
3651                           struct mdt_lock_handle *lh, __u64 ibits,
3652                           bool cos_incompat)
3653 {
3654         LASSERT(lh->mlh_reg_mode == LCK_PW || lh->mlh_reg_mode == LCK_EX);
3655         return mdt_object_lock_internal(info, o, lh, &ibits, 0,
3656                                         cos_incompat);
3657 }
3658
3659 int mdt_object_lock_try(struct mdt_thread_info *info, struct mdt_object *o,
3660                         struct mdt_lock_handle *lh, __u64 *ibits,
3661                         __u64 trybits, bool cos_incompat)
3662 {
3663         bool trylock_only = *ibits == 0;
3664         int rc;
3665
3666         LASSERT(!(*ibits & trybits));
3667         rc = mdt_object_lock_internal(info, o, lh, ibits, trybits,
3668                                       cos_incompat);
3669         if (rc && trylock_only) { /* clear error for try ibits lock only */
3670                 LASSERT(*ibits == 0);
3671                 rc = 0;
3672         }
3673         return rc;
3674 }
3675
3676 /**
3677  * Save a lock within request object.
3678  *
3679  * Keep the lock referenced until whether client ACK or transaction
3680  * commit happens or release the lock immediately depending on input
3681  * parameters. If COS is ON, a write lock is converted to COS lock
3682  * before saving.
3683  *
3684  * \param info thead info object
3685  * \param h lock handle
3686  * \param mode lock mode
3687  * \param decref force immediate lock releasing
3688  */
3689 void mdt_save_lock(struct mdt_thread_info *info, struct lustre_handle *h,
3690                    enum ldlm_mode mode, int decref)
3691 {
3692         ENTRY;
3693
3694         if (lustre_handle_is_used(h)) {
3695                 if (decref || !info->mti_has_trans ||
3696                     !(mode & (LCK_PW | LCK_EX))) {
3697                         mdt_fid_unlock(h, mode);
3698                 } else {
3699                         struct mdt_device *mdt = info->mti_mdt;
3700                         struct ldlm_lock *lock = ldlm_handle2lock(h);
3701                         struct ptlrpc_request *req = mdt_info_req(info);
3702                         bool cos = mdt_cos_is_enabled(mdt);
3703                         bool convert_lock = !cos && mdt_slc_is_enabled(mdt);
3704
3705                         LASSERTF(lock != NULL, "no lock for cookie %#llx\n",
3706                                  h->cookie);
3707
3708                         /* there is no request if mdt_object_unlock() is called
3709                          * from mdt_export_cleanup()->mdt_add_dirty_flag() */
3710                         if (likely(req != NULL)) {
3711                                 LDLM_DEBUG(lock, "save lock request %p reply "
3712                                         "state %p transno %lld\n", req,
3713                                         req->rq_reply_state, req->rq_transno);
3714                                 if (cos) {
3715                                         ldlm_lock_mode_downgrade(lock, LCK_COS);
3716                                         mode = LCK_COS;
3717                                 }
3718                                 if (req->rq_export->exp_disconnected)
3719                                         mdt_fid_unlock(h, mode);
3720                                 else
3721                                         ptlrpc_save_lock(req, h, mode, cos,
3722                                                          convert_lock);
3723                         } else {
3724                                 mdt_fid_unlock(h, mode);
3725                         }
3726                         if (mdt_is_lock_sync(lock)) {
3727                                 CDEBUG(D_HA, "found sync-lock,"
3728                                        " async commit started\n");
3729                                 mdt_device_commit_async(info->mti_env,
3730                                                         mdt);
3731                         }
3732                         LDLM_LOCK_PUT(lock);
3733                 }
3734                 h->cookie = 0ull;
3735         }
3736
3737         EXIT;
3738 }
3739
3740 /**
3741  * Save cross-MDT lock in uncommitted_slc_locks
3742  *
3743  * Keep the lock referenced until transaction commit happens or release the lock
3744  * immediately depending on input parameters.
3745  *
3746  * \param info thead info object
3747  * \param h lock handle
3748  * \param mode lock mode
3749  * \param decref force immediate lock releasing
3750  */
3751 static void mdt_save_remote_lock(struct mdt_thread_info *info,
3752                                  struct mdt_object *o, struct lustre_handle *h,
3753                                  enum ldlm_mode mode, int decref)
3754 {
3755         ENTRY;
3756
3757         if (lustre_handle_is_used(h)) {
3758                 struct ldlm_lock *lock = ldlm_handle2lock(h);
3759                 struct ptlrpc_request *req = mdt_info_req(info);
3760
3761                 if (o != NULL &&
3762                     (lock->l_policy_data.l_inodebits.bits &
3763                      (MDS_INODELOCK_XATTR | MDS_INODELOCK_UPDATE)))
3764                         mo_invalidate(info->mti_env, mdt_object_child(o));
3765
3766                 if (decref || !info->mti_has_trans || !req ||
3767                     !(mode & (LCK_PW | LCK_EX))) {
3768                         ldlm_lock_decref_and_cancel(h, mode);
3769                         LDLM_LOCK_PUT(lock);
3770                 } else {
3771                         tgt_save_slc_lock(&info->mti_mdt->mdt_lut, lock,
3772                                           req->rq_transno);
3773                         ldlm_lock_decref(h, mode);
3774                 }
3775                 h->cookie = 0ull;
3776         }
3777
3778         EXIT;
3779 }
3780
3781 /**
3782  * Unlock mdt object.
3783  *
3784  * Immeditely release the regular lock and the PDO lock or save the
3785  * lock in request and keep them referenced until client ACK or
3786  * transaction commit.
3787  *
3788  * \param info thread info object
3789  * \param o mdt object
3790  * \param lh mdt lock handle referencing regular and PDO locks
3791  * \param decref force immediate lock releasing
3792  *
3793  * XXX o is not used and may be NULL, see hsm_cdt_request_completed().
3794  */
3795 void mdt_object_unlock(struct mdt_thread_info *info, struct mdt_object *o,
3796                        struct mdt_lock_handle *lh, int decref)
3797 {
3798         ENTRY;
3799
3800         mdt_save_lock(info, &lh->mlh_pdo_lh, lh->mlh_pdo_mode, decref);
3801         mdt_save_lock(info, &lh->mlh_reg_lh, lh->mlh_reg_mode, decref);
3802         mdt_save_remote_lock(info, o, &lh->mlh_rreg_lh, lh->mlh_rreg_mode,
3803                              decref);
3804
3805         EXIT;
3806 }
3807
3808 struct mdt_object *mdt_object_find_lock(struct mdt_thread_info *info,
3809                                         const struct lu_fid *f,
3810                                         struct mdt_lock_handle *lh,
3811                                         __u64 ibits)
3812 {
3813         struct mdt_object *o;
3814
3815         o = mdt_object_find(info->mti_env, info->mti_mdt, f);
3816         if (!IS_ERR(o)) {
3817                 int rc;
3818
3819                 rc = mdt_object_lock(info, o, lh, ibits);
3820                 if (rc != 0) {
3821                         mdt_object_put(info->mti_env, o);
3822                         o = ERR_PTR(rc);
3823                 }
3824         }
3825         return o;
3826 }
3827
3828 void mdt_object_unlock_put(struct mdt_thread_info * info,
3829                            struct mdt_object * o,
3830                            struct mdt_lock_handle *lh,
3831                            int decref)
3832 {
3833         mdt_object_unlock(info, o, lh, decref);
3834         mdt_object_put(info->mti_env, o);
3835 }
3836
3837 /*
3838  * Generic code handling requests that have struct mdt_body passed in:
3839  *
3840  *  - extract mdt_body from request and save it in @info, if present;
3841  *
3842  *  - create lu_object, corresponding to the fid in mdt_body, and save it in
3843  *  @info;
3844  *
3845  *  - if HAS_BODY flag is set for this request type check whether object
3846  *  actually exists on storage (lu_object_exists()).
3847  *
3848  */
3849 static int mdt_body_unpack(struct mdt_thread_info *info,
3850                            enum tgt_handler_flags flags)
3851 {
3852         const struct mdt_body    *body;
3853         struct mdt_object        *obj;
3854         const struct lu_env      *env;
3855         struct req_capsule       *pill;
3856         int                       rc;
3857         ENTRY;
3858
3859         env = info->mti_env;
3860         pill = info->mti_pill;
3861
3862         body = info->mti_body = req_capsule_client_get(pill, &RMF_MDT_BODY);
3863         if (body == NULL)
3864                 RETURN(-EFAULT);
3865
3866         if (!(body->mbo_valid & OBD_MD_FLID))
3867                 RETURN(0);
3868
3869         if (!fid_is_sane(&body->mbo_fid1)) {
3870                 CERROR("Invalid fid: "DFID"\n", PFID(&body->mbo_fid1));
3871                 RETURN(-EINVAL);
3872         }
3873
3874         obj = mdt_object_find(env, info->mti_mdt, &body->mbo_fid1);
3875         if (!IS_ERR(obj)) {
3876                 if ((flags & HAS_BODY) && !mdt_object_exists(obj)) {
3877                         mdt_object_put(env, obj);
3878                         rc = -ENOENT;
3879                 } else {
3880                         info->mti_object = obj;
3881                         rc = 0;
3882                 }
3883         } else
3884                 rc = PTR_ERR(obj);
3885
3886         RETURN(rc);
3887 }
3888
3889 static int mdt_unpack_req_pack_rep(struct mdt_thread_info *info,
3890                                    enum tgt_handler_flags flags)
3891 {
3892         struct req_capsule *pill = info->mti_pill;
3893         int rc;
3894
3895         ENTRY;
3896
3897         if (req_capsule_has_field(pill, &RMF_MDT_BODY, RCL_CLIENT))
3898                 rc = mdt_body_unpack(info, flags);
3899         else
3900                 rc = 0;
3901
3902         if (rc == 0 && (flags & HAS_REPLY)) {
3903                 /* Pack reply. */
3904                 if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
3905                         req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER,
3906                                              DEF_REP_MD_SIZE);
3907                 if (req_capsule_has_field(pill, &RMF_LOGCOOKIES, RCL_SERVER))
3908                         req_capsule_set_size(pill, &RMF_LOGCOOKIES,
3909                                              RCL_SERVER, 0);
3910
3911                 /* Set ACL reply buffer size as LUSTRE_POSIX_ACL_MAX_SIZE_OLD
3912                  * by default. If the target object has more ACL entries, then
3913                  * enlarge the buffer when necessary. */
3914                 if (req_capsule_has_field(pill, &RMF_ACL, RCL_SERVER))
3915                         req_capsule_set_size(pill, &RMF_ACL, RCL_SERVER,
3916                                              LUSTRE_POSIX_ACL_MAX_SIZE_OLD);
3917
3918                 mdt_preset_secctx_size(info);
3919                 mdt_preset_encctx_size(info);
3920
3921                 rc = req_capsule_server_pack(pill);
3922                 if (rc)
3923                         CWARN("%s: cannot pack response: rc = %d\n",
3924                                       mdt_obd_name(info->mti_mdt), rc);
3925         }
3926         RETURN(rc);
3927 }
3928
3929 void mdt_lock_handle_init(struct mdt_lock_handle *lh)
3930 {
3931         lh->mlh_type = MDT_NUL_LOCK;
3932         lh->mlh_reg_lh.cookie = 0ull;
3933         lh->mlh_reg_mode = LCK_MINMODE;
3934         lh->mlh_pdo_lh.cookie = 0ull;
3935         lh->mlh_pdo_mode = LCK_MINMODE;
3936         lh->mlh_rreg_lh.cookie = 0ull;
3937         lh->mlh_rreg_mode = LCK_MINMODE;
3938 }
3939
3940 void mdt_lock_handle_fini(struct mdt_lock_handle *lh)
3941 {
3942         LASSERT(!lustre_handle_is_used(&lh->mlh_reg_lh));
3943         LASSERT(!lustre_handle_is_used(&lh->mlh_pdo_lh));
3944 }
3945
3946 /*
3947  * Initialize fields of struct mdt_thread_info. Other fields are left in
3948  * uninitialized state, because it's too expensive to zero out whole
3949  * mdt_thread_info (> 1K) on each request arrival.
3950  */
3951 void mdt_thread_info_init(struct ptlrpc_request *req,
3952                           struct mdt_thread_info *info)
3953 {
3954         int i;
3955
3956         info->mti_pill = &req->rq_pill;
3957
3958         /* lock handle */
3959         for (i = 0; i < ARRAY_SIZE(info->mti_lh); i++)
3960                 mdt_lock_handle_init(&info->mti_lh[i]);
3961
3962         /* mdt device: it can be NULL while CONNECT */
3963         if (req->rq_export) {
3964                 info->mti_mdt = mdt_dev(req->rq_export->exp_obd->obd_lu_dev);
3965                 info->mti_exp = req->rq_export;
3966         } else
3967                 info->mti_mdt = NULL;
3968         info->mti_env = req->rq_svc_thread->t_env;
3969         info->mti_transno = lustre_msg_get_transno(req->rq_reqmsg);
3970
3971         memset(&info->mti_attr, 0, sizeof(info->mti_attr));
3972         info->mti_big_buf = LU_BUF_NULL;
3973         info->mti_body = NULL;
3974         info->mti_object = NULL;
3975         info->mti_dlm_req = NULL;
3976         info->mti_has_trans = 0;
3977         info->mti_cross_ref = 0;
3978         info->mti_opdata = 0;
3979         info->mti_big_lmm_used = 0;
3980         info->mti_big_acl_used = 0;
3981         info->mti_som_valid = 0;
3982
3983         info->mti_spec.no_create = 0;
3984         info->mti_spec.sp_rm_entry = 0;
3985         info->mti_spec.sp_permitted = 0;
3986
3987         info->mti_spec.u.sp_ea.eadata = NULL;
3988         info->mti_spec.u.sp_ea.eadatalen = 0;
3989 }
3990
3991 void mdt_thread_info_fini(struct mdt_thread_info *info)
3992 {
3993         int i;
3994
3995         if (info->mti_object != NULL) {
3996                 mdt_object_put(info->mti_env, info->mti_object);
3997                 info->mti_object = NULL;
3998         }
3999
4000         for (i = 0; i < ARRAY_SIZE(info->mti_lh); i++)
4001                 mdt_lock_handle_fini(&info->mti_lh[i]);
4002         info->mti_env = NULL;
4003         info->mti_pill = NULL;
4004         info->mti_exp = NULL;
4005         info->mti_mdt = NULL;
4006
4007         if (unlikely(info->mti_big_buf.lb_buf != NULL))
4008                 lu_buf_free(&info->mti_big_buf);
4009 }
4010
4011 struct mdt_thread_info *tsi2mdt_info(struct tgt_session_info *tsi)
4012 {
4013         struct mdt_thread_info  *mti;
4014
4015         mti = mdt_th_info(tsi->tsi_env);
4016         LASSERT(mti != NULL);
4017
4018         mdt_thread_info_init(tgt_ses_req(tsi), mti);
4019         if (tsi->tsi_corpus != NULL) {
4020                 mti->mti_object = mdt_obj(tsi->tsi_corpus);
4021                 lu_object_get(tsi->tsi_corpus);
4022         }
4023         mti->mti_body = tsi->tsi_mdt_body;
4024         mti->mti_dlm_req = tsi->tsi_dlm_req;
4025
4026         return mti;
4027 }
4028
4029 static int mdt_tgt_connect(struct tgt_session_info *tsi)
4030 {
4031         if (OBD_FAIL_CHECK(OBD_FAIL_TGT_DELAY_CONDITIONAL) &&
4032             cfs_fail_val ==
4033             tsi2mdt_info(tsi)->mti_mdt->mdt_seq_site.ss_node_id)
4034                 schedule_timeout_uninterruptible(cfs_time_seconds(3));
4035
4036         return tgt_connect(tsi);
4037 }
4038
4039 static int mdt_intent_glimpse(enum ldlm_intent_flags it_opc,
4040                               struct mdt_thread_info *info,
4041                               struct ldlm_lock **lockp, __u64 flags)
4042 {
4043         return mdt_glimpse_enqueue(info, info->mti_mdt->mdt_namespace,
4044                                    lockp, flags);
4045 }
4046 static int mdt_intent_brw(enum ldlm_intent_flags it_opc,
4047                           struct mdt_thread_info *info,
4048                           struct ldlm_lock **lockp, __u64 flags)
4049 {
4050         return mdt_brw_enqueue(info, info->mti_mdt->mdt_namespace,
4051                                lockp, flags);
4052 }
4053
4054 int mdt_intent_lock_replace(struct mdt_thread_info *info,
4055                             struct ldlm_lock **lockp,
4056                             struct mdt_lock_handle *lh,
4057                             __u64 flags, int result)
4058 {
4059         struct ptlrpc_request  *req = mdt_info_req(info);
4060         struct ldlm_lock       *lock = *lockp;
4061         struct ldlm_lock       *new_lock;
4062
4063         /* If possible resent found a lock, @lh is set to its handle */
4064         new_lock = ldlm_handle2lock_long(&lh->mlh_reg_lh, 0);
4065
4066         if (new_lock == NULL && (flags & LDLM_FL_INTENT_ONLY)) {
4067                 lh->mlh_reg_lh.cookie = 0;
4068                 RETURN(0);
4069         }
4070
4071         if (new_lock == NULL && (flags & LDLM_FL_RESENT)) {
4072                 /* Lock is pinned by ldlm_handle_enqueue0() as it is
4073                  * a resend case, however, it could be already destroyed
4074                  * due to client eviction or a raced cancel RPC. */
4075                 LDLM_DEBUG_NOLOCK("Invalid lock handle %#llx\n",
4076                                   lh->mlh_reg_lh.cookie);
4077                 lh->mlh_reg_lh.cookie = 0;
4078                 RETURN(-ESTALE);
4079         }
4080
4081         LASSERTF(new_lock != NULL,
4082                  "lockh %#llx flags %#llx : rc = %d\n",
4083                  lh->mlh_reg_lh.cookie, flags, result);
4084
4085         /*
4086          * If we've already given this lock to a client once, then we should
4087          * have no readers or writers.  Otherwise, we should have one reader
4088          * _or_ writer ref (which will be zeroed below) before returning the
4089          * lock to a client.
4090          */
4091         if (new_lock->l_export == req->rq_export) {
4092                 LASSERT(new_lock->l_readers + new_lock->l_writers == 0);
4093         } else {
4094                 LASSERT(new_lock->l_export == NULL);
4095                 LASSERT(new_lock->l_readers + new_lock->l_writers == 1);
4096         }
4097
4098         *lockp = new_lock;
4099
4100         if (new_lock->l_export == req->rq_export) {
4101                 /*
4102                  * Already gave this to the client, which means that we
4103                  * reconstructed a reply.
4104                  */
4105                 LASSERT(lustre_msg_get_flags(req->rq_reqmsg) &
4106                         MSG_RESENT);
4107
4108                 LDLM_LOCK_RELEASE(new_lock);
4109                 lh->mlh_reg_lh.cookie = 0;
4110                 RETURN(ELDLM_LOCK_REPLACED);
4111         }
4112
4113         /*
4114          * Fixup the lock to be given to the client.
4115          */
4116         lock_res_and_lock(new_lock);
4117         /* Zero new_lock->l_readers and new_lock->l_writers without triggering
4118          * possible blocking AST. */
4119         while (new_lock->l_readers > 0) {
4120                 lu_ref_del(&new_lock->l_reference, "reader", new_lock);
4121                 lu_ref_del(&new_lock->l_reference, "user", new_lock);
4122                 new_lock->l_readers--;
4123         }
4124         while (new_lock->l_writers > 0) {
4125                 lu_ref_del(&new_lock->l_reference, "writer", new_lock);
4126                 lu_ref_del(&new_lock->l_reference, "user", new_lock);
4127                 new_lock->l_writers--;
4128         }
4129
4130         new_lock->l_export = class_export_lock_get(req->rq_export, new_lock);
4131         new_lock->l_blocking_ast = lock->l_blocking_ast;
4132         new_lock->l_completion_ast = lock->l_completion_ast;
4133         if (ldlm_has_dom(new_lock))
4134                 new_lock->l_glimpse_ast = ldlm_server_glimpse_ast;
4135         new_lock->l_remote_handle = lock->l_remote_handle;
4136         new_lock->l_flags &= ~LDLM_FL_LOCAL;
4137
4138         unlock_res_and_lock(new_lock);
4139
4140         cfs_hash_add(new_lock->l_export->exp_lock_hash,
4141                      &new_lock->l_remote_handle,
4142                      &new_lock->l_exp_hash);
4143
4144         LDLM_LOCK_RELEASE(new_lock);
4145         lh->mlh_reg_lh.cookie = 0;
4146
4147         RETURN(ELDLM_LOCK_REPLACED);
4148 }
4149
4150 void mdt_intent_fixup_resent(struct mdt_thread_info *info,
4151                              struct ldlm_lock *new_lock,
4152                              struct mdt_lock_handle *lh, __u64 flags)
4153 {
4154         struct ptlrpc_request  *req = mdt_info_req(info);
4155         struct ldlm_request    *dlmreq;
4156
4157         if (!(lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT))
4158                 return;
4159
4160         dlmreq = req_capsule_client_get(info->mti_pill, &RMF_DLM_REQ);
4161
4162         /* Check if this is a resend case (MSG_RESENT is set on RPC) and a
4163          * lock was found by ldlm_handle_enqueue(); if so @lh must be
4164          * initialized. */
4165         if (flags & LDLM_FL_RESENT) {
4166                 lh->mlh_reg_lh.cookie = new_lock->l_handle.h_cookie;
4167                 lh->mlh_reg_mode = new_lock->l_granted_mode;
4168
4169                 LDLM_DEBUG(new_lock, "Restoring lock cookie");
4170                 DEBUG_REQ(D_DLMTRACE, req, "restoring lock cookie %#llx",
4171                           lh->mlh_reg_lh.cookie);
4172                 return;
4173         }
4174
4175         /*
4176          * If the xid matches, then we know this is a resent request, and allow
4177          * it. (It's probably an OPEN, for which we don't send a lock.
4178          */
4179         if (req_can_reconstruct(req, NULL) != 0)
4180                 return;
4181
4182         /*
4183          * This remote handle isn't enqueued, so we never received or processed
4184          * this request.  Clear MSG_RESENT, because it can be handled like any
4185          * normal request now.
4186          */
4187         lustre_msg_clear_flags(req->rq_reqmsg, MSG_RESENT);
4188
4189         DEBUG_REQ(D_DLMTRACE, req, "no existing lock with rhandle %#llx",
4190                   dlmreq->lock_handle[0].cookie);
4191 }
4192
4193 static int mdt_intent_getxattr(enum ldlm_intent_flags it_opc,
4194                                struct mdt_thread_info *info,
4195                                struct ldlm_lock **lockp,
4196                                __u64 flags)
4197 {
4198         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
4199         struct ldlm_reply      *ldlm_rep = NULL;
4200         int rc;
4201         ENTRY;
4202
4203         /*
4204          * Initialize lhc->mlh_reg_lh either from a previously granted lock
4205          * (for the resend case) or a new lock. Below we will use it to
4206          * replace the original lock.
4207          */
4208         mdt_intent_fixup_resent(info, *lockp, lhc, flags);
4209         if (!lustre_handle_is_used(&lhc->mlh_reg_lh)) {
4210                 mdt_lock_reg_init(lhc, (*lockp)->l_req_mode);
4211                 rc = mdt_object_lock(info, info->mti_object, lhc,
4212                                      MDS_INODELOCK_XATTR);
4213                 if (rc)
4214                         return rc;
4215         }
4216
4217         rc = mdt_getxattr(info);
4218
4219         if (mdt_info_req(info)->rq_repmsg != NULL)
4220                 ldlm_rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
4221
4222         if (ldlm_rep == NULL ||
4223             OBD_FAIL_CHECK(OBD_FAIL_MDS_XATTR_REP)) {
4224                 mdt_object_unlock(info,  info->mti_object, lhc, 1);
4225                 if (is_serious(rc))
4226                         RETURN(rc);
4227                 else
4228                         RETURN(err_serious(-EFAULT));
4229         }
4230
4231         ldlm_rep->lock_policy_res2 = clear_serious(rc);
4232
4233         /* This is left for interop instead of adding a new interop flag.
4234          * LU-7433 */
4235 #if LUSTRE_VERSION_CODE > OBD_OCD_VERSION(3, 0, 0, 0)
4236         if (ldlm_rep->lock_policy_res2) {
4237                 mdt_object_unlock(info, info->mti_object, lhc, 1);
4238                 RETURN(ELDLM_LOCK_ABORTED);
4239         }
4240 #endif
4241
4242         rc = mdt_intent_lock_replace(info, lockp, lhc, flags, rc);
4243         RETURN(rc);
4244 }
4245
4246 static int mdt_intent_getattr(enum ldlm_intent_flags it_opc,
4247                               struct mdt_thread_info *info,
4248                               struct ldlm_lock **lockp,
4249                               __u64 flags)
4250 {
4251         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
4252         __u64                   child_bits;
4253         struct ldlm_reply      *ldlm_rep;
4254         struct mdt_body        *reqbody;
4255         struct mdt_body        *repbody;
4256         int                     rc, rc2;
4257         ENTRY;
4258
4259         reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
4260         LASSERT(reqbody);
4261
4262         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
4263         LASSERT(repbody);
4264
4265         info->mti_cross_ref = !!(reqbody->mbo_valid & OBD_MD_FLCROSSREF);
4266         repbody->mbo_eadatasize = 0;
4267         repbody->mbo_aclsize = 0;
4268
4269         switch (it_opc) {
4270         case IT_LOOKUP:
4271                 child_bits = MDS_INODELOCK_LOOKUP | MDS_INODELOCK_PERM;
4272                 break;
4273         case IT_GETATTR:
4274                 child_bits = MDS_INODELOCK_LOOKUP | MDS_INODELOCK_UPDATE |
4275                              MDS_INODELOCK_PERM;
4276                 break;
4277         default:
4278                 CERROR("%s: unsupported intent %#x\n",
4279                        mdt_obd_name(info->mti_mdt), (unsigned int)it_opc);
4280                 GOTO(out_shrink, rc = -EINVAL);
4281         }
4282
4283         rc = mdt_init_ucred(info, reqbody);
4284         if (rc)
4285                 GOTO(out_shrink, rc);
4286
4287         ldlm_rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
4288         mdt_set_disposition(info, ldlm_rep, DISP_IT_EXECD);
4289
4290         /* Get lock from request for possible resent case. */
4291         mdt_intent_fixup_resent(info, *lockp, lhc, flags);
4292
4293         rc = mdt_getattr_name_lock(info, lhc, child_bits, ldlm_rep);
4294         ldlm_rep->lock_policy_res2 = clear_serious(rc);
4295
4296         if (mdt_get_disposition(ldlm_rep, DISP_LOOKUP_NEG))
4297                 ldlm_rep->lock_policy_res2 = 0;
4298         if (!mdt_get_disposition(ldlm_rep, DISP_LOOKUP_POS) ||
4299             ldlm_rep->lock_policy_res2) {
4300                 lhc->mlh_reg_lh.cookie = 0ull;
4301                 GOTO(out_ucred, rc = ELDLM_LOCK_ABORTED);
4302         }
4303
4304         rc = mdt_intent_lock_replace(info, lockp, lhc, flags, rc);
4305         EXIT;
4306 out_ucred:
4307         mdt_exit_ucred(info);
4308 out_shrink:
4309         mdt_client_compatibility(info);
4310         rc2 = mdt_fix_reply(info);
4311         if (rc == 0)
4312                 rc = rc2;
4313         return rc;
4314 }
4315
4316 static int mdt_intent_layout(enum ldlm_intent_flags it_opc,
4317                              struct mdt_thread_info *info,
4318                              struct ldlm_lock **lockp,
4319                              __u64 flags)
4320 {
4321         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
4322         struct md_layout_change layout = { .mlc_opc = MD_LAYOUT_NOP };
4323         struct layout_intent *intent;
4324         struct ldlm_reply *ldlm_rep;
4325         struct lu_fid *fid = &info->mti_tmp_fid2;
4326         struct mdt_object *obj = NULL;
4327         int layout_size = 0;
4328         struct lu_buf *buf = &layout.mlc_buf;
4329         int rc = 0;
4330
4331         ENTRY;
4332
4333         fid_extract_from_res_name(fid, &(*lockp)->l_resource->lr_name);
4334
4335         intent = req_capsule_client_get(info->mti_pill, &RMF_LAYOUT_INTENT);
4336         if (intent == NULL)
4337                 RETURN(-EPROTO);
4338
4339         CDEBUG(D_INFO, DFID "got layout change request from client: "
4340                "opc:%u flags:%#x extent "DEXT"\n",
4341                PFID(fid), intent->li_opc, intent->li_flags,
4342                PEXT(&intent->li_extent));
4343
4344         switch (intent->li_opc) {
4345         case LAYOUT_INTENT_TRUNC:
4346         case LAYOUT_INTENT_WRITE:
4347                 layout.mlc_opc = MD_LAYOUT_WRITE;
4348                 layout.mlc_intent = intent;
4349                 break;
4350         case LAYOUT_INTENT_ACCESS:
4351                 break;
4352         case LAYOUT_INTENT_READ:
4353         case LAYOUT_INTENT_GLIMPSE:
4354         case LAYOUT_INTENT_RELEASE:
4355         case LAYOUT_INTENT_RESTORE:
4356                 CERROR("%s: Unsupported layout intent opc %d\n",
4357                        mdt_obd_name(info->mti_mdt), intent->li_opc);
4358                 RETURN(-ENOTSUPP);
4359         default:
4360                 CERROR("%s: Unknown layout intent opc %d\n",
4361                        mdt_obd_name(info->mti_mdt), intent->li_opc);
4362                 RETURN(-EINVAL);
4363         }
4364
4365         obj = mdt_object_find(info->mti_env, info->mti_mdt, fid);
4366         if (IS_ERR(obj))
4367                 RETURN(PTR_ERR(obj));
4368
4369         if (mdt_object_exists(obj) && !mdt_object_remote(obj)) {
4370                 /* if layout is going to be changed don't use the current EA
4371                  * size but the maximum one. That buffer will be shrinked
4372                  * to the actual size in req_capsule_shrink() before reply.
4373                  */
4374                 if (layout.mlc_opc == MD_LAYOUT_WRITE) {
4375                         layout_size = info->mti_mdt->mdt_max_mdsize;
4376                 } else {
4377                         layout_size = mdt_attr_get_eabuf_size(info, obj);
4378                         if (layout_size < 0)
4379                                 GOTO(out, rc = layout_size);
4380
4381                         if (layout_size > info->mti_mdt->mdt_max_mdsize)
4382                                 info->mti_mdt->mdt_max_mdsize = layout_size;
4383                 }
4384                 CDEBUG(D_INFO, "%s: layout_size %d\n",
4385                        mdt_obd_name(info->mti_mdt), layout_size);
4386         }
4387
4388         /*
4389          * set reply buffer size, so that ldlm_handle_enqueue0()->
4390          * ldlm_lvbo_fill() will fill the reply buffer with lovea.
4391          */
4392         req_capsule_set_size(info->mti_pill, &RMF_DLM_LVB, RCL_SERVER,
4393                              layout_size);
4394         rc = req_capsule_server_pack(info->mti_pill);
4395         if (rc)
4396                 GOTO(out, rc);
4397
4398         ldlm_rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
4399         if (!ldlm_rep)
4400                 GOTO(out, rc = -EPROTO);
4401
4402         mdt_set_disposition(info, ldlm_rep, DISP_IT_EXECD);
4403
4404         /* take lock in ldlm_lock_enqueue() for LAYOUT_INTENT_ACCESS */
4405         if (layout.mlc_opc == MD_LAYOUT_NOP)
4406                 GOTO(out, rc = 0);
4407
4408         rc = mdt_check_resent(info, mdt_reconstruct_generic, lhc);
4409         if (rc < 0)
4410                 GOTO(out, rc);
4411         if (rc == 1) {
4412                 DEBUG_REQ(D_INODE, mdt_info_req(info), "resent opt.");
4413                 rc = lustre_msg_get_status(mdt_info_req(info)->rq_repmsg);
4414                 GOTO(out, rc);
4415         }
4416
4417         buf->lb_buf = NULL;
4418         buf->lb_len = 0;
4419         if (unlikely(req_is_replay(mdt_info_req(info)))) {
4420                 buf->lb_buf = req_capsule_client_get(info->mti_pill,
4421                                                      &RMF_EADATA);
4422                 buf->lb_len = req_capsule_get_size(info->mti_pill,
4423                                                      &RMF_EADATA, RCL_CLIENT);
4424                 /*
4425                  * If it's a replay of layout write intent RPC, the client has
4426                  * saved the extended lovea when it get reply then.
4427                  */
4428                 if (buf->lb_len > 0)
4429                         mdt_fix_lov_magic(info, buf->lb_buf);
4430         }
4431
4432         /* Get lock from request for possible resent case. */
4433         mdt_intent_fixup_resent(info, *lockp, lhc, flags);
4434         (*lockp)->l_lvb_type = LVB_T_LAYOUT;
4435
4436         /*
4437          * Instantiate some layout components, if @buf contains lovea, then it's
4438          * a replay of the layout intent write RPC.
4439          */
4440         rc = mdt_layout_change(info, obj, lhc, &layout);
4441         ldlm_rep->lock_policy_res2 = clear_serious(rc);
4442
4443         if (lustre_handle_is_used(&lhc->mlh_reg_lh)) {
4444                 rc = mdt_intent_lock_replace(info, lockp, lhc, flags, rc);
4445                 if (rc == ELDLM_LOCK_REPLACED &&
4446                     (*lockp)->l_granted_mode == LCK_EX)
4447                         ldlm_lock_mode_downgrade(*lockp, LCK_CR);
4448         }
4449
4450         EXIT;
4451 out:
4452         mdt_object_put(info->mti_env, obj);
4453         return rc;
4454 }
4455
4456 static int mdt_intent_open(enum ldlm_intent_flags it_opc,
4457                            struct mdt_thread_info *info,
4458                            struct ldlm_lock **lockp,
4459                            __u64 flags)
4460 {
4461         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
4462         struct ldlm_reply      *rep = NULL;
4463         long                    opc;
4464         int                     rc;
4465         struct ptlrpc_request  *req = mdt_info_req(info);
4466
4467         static const struct req_format *intent_fmts[REINT_MAX] = {
4468                 [REINT_CREATE]  = &RQF_LDLM_INTENT_CREATE,
4469                 [REINT_OPEN]    = &RQF_LDLM_INTENT_OPEN
4470         };
4471
4472         ENTRY;
4473
4474         opc = mdt_reint_opcode(mdt_info_req(info), intent_fmts);
4475         if (opc < 0)
4476                 RETURN(opc);
4477
4478         /* Get lock from request for possible resent case. */
4479         mdt_intent_fixup_resent(info, *lockp, lhc, flags);
4480
4481         rc = mdt_reint_internal(info, lhc, opc);
4482
4483         if (rc < 0 && lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)
4484                 DEBUG_REQ(D_ERROR, req, "Replay open failed with %d", rc);
4485
4486         /* Check whether the reply has been packed successfully. */
4487         if (mdt_info_req(info)->rq_repmsg != NULL)
4488                 rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
4489         if (rep == NULL) {
4490                 if (is_serious(rc))
4491                         RETURN(rc);
4492                 else
4493                         RETURN(err_serious(-EFAULT));
4494         }
4495
4496         /* MDC expects this in any case */
4497         if (rc != 0)
4498                 mdt_set_disposition(info, rep, DISP_LOOKUP_EXECD);
4499
4500         /* the open lock or the lock for cross-ref object should be
4501          * returned to the client */
4502         if (lustre_handle_is_used(&lhc->mlh_reg_lh) &&
4503             (rc == 0 || rc == -MDT_EREMOTE_OPEN)) {
4504                 rep->lock_policy_res2 = 0;
4505                 rc = mdt_intent_lock_replace(info, lockp, lhc, flags, rc);
4506                 RETURN(rc);
4507         }
4508
4509         rep->lock_policy_res2 = clear_serious(rc);
4510
4511         if (rep->lock_policy_res2 == -ENOENT &&
4512             mdt_get_disposition(rep, DISP_LOOKUP_NEG) &&
4513             !mdt_get_disposition(rep, DISP_OPEN_CREATE))
4514                 rep->lock_policy_res2 = 0;
4515
4516         lhc->mlh_reg_lh.cookie = 0ull;
4517         if (rc == -ENOTCONN || rc == -ENODEV ||
4518             rc == -EOVERFLOW) { /**< if VBR failure then return error */
4519                 /*
4520                  * If it is the disconnect error (ENODEV & ENOCONN), the error
4521                  * will be returned by rq_status, and client at ptlrpc layer
4522                  * will detect this, then disconnect, reconnect the import
4523                  * immediately, instead of impacting the following the rpc.
4524                  */
4525                 RETURN(rc);
4526         }
4527         /*
4528          * For other cases, the error will be returned by intent, and client
4529          * will retrieve the result from intent.
4530          */
4531         RETURN(ELDLM_LOCK_ABORTED);
4532 }
4533
4534 static int mdt_intent_opc(enum ldlm_intent_flags it_opc,
4535                           struct mdt_thread_info *info,
4536                           struct ldlm_lock **lockp,
4537                           u64 flags /* LDLM_FL_* */)
4538 {
4539         struct req_capsule *pill = info->mti_pill;
4540         struct ptlrpc_request *req = mdt_info_req(info);
4541         const struct req_format *it_format;
4542         int (*it_handler)(enum ldlm_intent_flags,
4543                           struct mdt_thread_info *,
4544                           struct ldlm_lock **,
4545                           u64);
4546         enum tgt_handler_flags it_handler_flags = 0;
4547         struct ldlm_reply *rep;
4548         bool check_mdt_object = false;
4549         int rc;
4550         ENTRY;
4551
4552         switch (it_opc) {
4553         case IT_OPEN:
4554         case IT_OPEN|IT_CREAT:
4555                 /*
4556                  * OCREAT is not a IS_MUTABLE request since the file may
4557                  * already exist. We do the extra check of
4558                  * OBD_CONNECT_RDONLY in mdt_reint_open() when we
4559                  * really need to create the object.
4560                  */
4561                 it_format = &RQF_LDLM_INTENT;
4562                 it_handler = &mdt_intent_open;
4563                 break;
4564         case IT_GETATTR:
4565                 check_mdt_object = true;
4566                 /* fallthrough */
4567         case IT_LOOKUP:
4568                 it_format = &RQF_LDLM_INTENT_GETATTR;
4569                 it_handler = &mdt_intent_getattr;
4570                 it_handler_flags = HAS_REPLY;
4571                 break;
4572         case IT_GETXATTR:
4573                 check_mdt_object = true;
4574                 it_format = &RQF_LDLM_INTENT_GETXATTR;
4575                 it_handler = &mdt_intent_getxattr;
4576                 it_handler_flags = HAS_BODY;
4577                 break;
4578         case IT_LAYOUT:
4579                 it_format = &RQF_LDLM_INTENT_LAYOUT;
4580                 it_handler = &mdt_intent_layout;
4581                 break;
4582         case IT_GLIMPSE:
4583                 it_format = &RQF_LDLM_INTENT;
4584                 it_handler = &mdt_intent_glimpse;
4585                 break;
4586         case IT_BRW:
4587                 it_format = &RQF_LDLM_INTENT;
4588                 it_handler = &mdt_intent_brw;
4589                 break;
4590         case IT_QUOTA_DQACQ:
4591         case IT_QUOTA_CONN: {
4592                 struct lu_device *qmt = info->mti_mdt->mdt_qmt_dev;
4593
4594                 if (qmt == NULL)
4595                         RETURN(-EOPNOTSUPP);
4596
4597                 if (mdt_rdonly(req->rq_export))
4598                         RETURN(-EROFS);
4599
4600                 (*lockp)->l_lvb_type = LVB_T_LQUOTA;
4601                 /* pass the request to quota master */
4602                 rc = qmt_hdls.qmth_intent_policy(info->mti_env, qmt,
4603                                                  mdt_info_req(info), lockp,
4604                                                  flags);
4605                 RETURN(rc);
4606         }
4607         default:
4608                 CERROR("%s: unknown intent code %#x\n",
4609                        mdt_obd_name(info->mti_mdt), it_opc);
4610                 RETURN(-EPROTO);
4611         }
4612
4613         req_capsule_extend(pill, it_format);
4614
4615         rc = mdt_unpack_req_pack_rep(info, it_handler_flags);
4616         if (rc < 0)
4617                 RETURN(rc);
4618
4619         if (unlikely(info->mti_object == NULL && check_mdt_object))
4620                 RETURN(-EPROTO);
4621
4622         if (it_handler_flags & IS_MUTABLE && mdt_rdonly(req->rq_export))
4623                 RETURN(-EROFS);
4624
4625         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_INTENT_DELAY, 10);
4626
4627         /* execute policy */
4628         rc = (*it_handler)(it_opc, info, lockp, flags);
4629
4630         /* Check whether the reply has been packed successfully. */
4631         if (req->rq_repmsg != NULL) {
4632                 rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
4633                 rep->lock_policy_res2 =
4634                         ptlrpc_status_hton(rep->lock_policy_res2);
4635         }
4636
4637         RETURN(rc);
4638 }
4639
4640 static void mdt_ptlrpc_stats_update(struct ptlrpc_request *req,
4641                                     enum ldlm_intent_flags it_opc)
4642 {
4643         struct lprocfs_stats *srv_stats = ptlrpc_req2svc(req)->srv_stats;
4644
4645         /* update stats when IT code is known */
4646         if (srv_stats != NULL)
4647                 lprocfs_counter_incr(srv_stats,
4648                                 PTLRPC_LAST_CNTR + (it_opc == IT_GLIMPSE ?
4649                                 LDLM_GLIMPSE_ENQUEUE : LDLM_IBITS_ENQUEUE));
4650 }
4651
4652 static int mdt_intent_policy(const struct lu_env *env,
4653                              struct ldlm_namespace *ns,
4654                              struct ldlm_lock **lockp,
4655                              void *req_cookie,
4656                              enum ldlm_mode mode,
4657                              __u64 flags, void *data)
4658 {
4659         struct tgt_session_info *tsi;
4660         struct mdt_thread_info  *info;
4661         struct ptlrpc_request   *req  =  req_cookie;
4662         struct ldlm_intent      *it;
4663         struct req_capsule      *pill;
4664         const struct ldlm_lock_desc *ldesc;
4665         int rc;
4666
4667         ENTRY;
4668
4669         LASSERT(req != NULL);
4670
4671         tsi = tgt_ses_info(env);
4672
4673         info = tsi2mdt_info(tsi);
4674         LASSERT(info != NULL);
4675         pill = info->mti_pill;
4676         LASSERT(pill->rc_req == req);
4677         ldesc = &info->mti_dlm_req->lock_desc;
4678
4679         if (req->rq_reqmsg->lm_bufcount > DLM_INTENT_IT_OFF) {
4680                 req_capsule_extend(pill, &RQF_LDLM_INTENT_BASIC);
4681                 it = req_capsule_client_get(pill, &RMF_LDLM_INTENT);
4682                 if (it != NULL) {
4683                         mdt_ptlrpc_stats_update(req, it->opc);
4684                         rc = mdt_intent_opc(it->opc, info, lockp, flags);
4685                         if (rc == 0)
4686                                 rc = ELDLM_OK;
4687
4688                         /* Lock without inodebits makes no sense and will oops
4689                          * later in ldlm. Let's check it now to see if we have
4690                          * ibits corrupted somewhere in mdt_intent_opc().
4691                          * The case for client miss to set ibits has been
4692                          * processed by others. */
4693                         LASSERT(ergo(ldesc->l_resource.lr_type == LDLM_IBITS,
4694                                 ldesc->l_policy_data.l_inodebits.bits != 0));
4695                 } else {
4696                         rc = err_serious(-EFAULT);
4697                 }
4698         } else if (ldesc->l_resource.lr_type == LDLM_IBITS &&
4699                    ldesc->l_policy_data.l_inodebits.bits == MDS_INODELOCK_DOM) {
4700                 struct ldlm_reply *rep;
4701
4702                 /* No intent was provided but INTENT flag is set along with
4703                  * DOM bit, this is considered as GLIMPSE request.
4704                  * This logic is common for MDT and OST glimpse
4705                  */
4706                 mdt_ptlrpc_stats_update(req, IT_GLIMPSE);
4707                 rc = mdt_glimpse_enqueue(info, ns, lockp, flags);
4708                 /* Check whether the reply has been packed successfully. */
4709                 if (req->rq_repmsg != NULL) {
4710                         rep = req_capsule_server_get(info->mti_pill,
4711                                                      &RMF_DLM_REP);
4712                         rep->lock_policy_res2 =
4713                                 ptlrpc_status_hton(rep->lock_policy_res2);
4714                 }
4715         } else {
4716                 /* No intent was provided */
4717                 req_capsule_set_size(pill, &RMF_DLM_LVB, RCL_SERVER, 0);
4718                 rc = req_capsule_server_pack(pill);
4719                 if (rc)
4720                         rc = err_serious(rc);
4721         }
4722         mdt_thread_info_fini(info);
4723         RETURN(rc);
4724 }
4725
4726 static void mdt_deregister_seq_exp(struct mdt_device *mdt)
4727 {
4728         struct seq_server_site  *ss = mdt_seq_site(mdt);
4729
4730         if (ss->ss_node_id == 0)
4731                 return;
4732
4733         if (ss->ss_client_seq != NULL) {
4734                 lustre_deregister_lwp_item(&ss->ss_client_seq->lcs_exp);
4735                 ss->ss_client_seq->lcs_exp = NULL;
4736         }
4737
4738         if (ss->ss_server_fld != NULL) {
4739                 lustre_deregister_lwp_item(&ss->ss_server_fld->lsf_control_exp);
4740                 ss->ss_server_fld->lsf_control_exp = NULL;
4741         }
4742 }
4743
4744 static void mdt_seq_fini_cli(struct mdt_device *mdt)
4745 {
4746         struct seq_server_site *ss = mdt_seq_site(mdt);
4747
4748         if (ss == NULL)
4749                 return;
4750
4751         if (ss->ss_server_seq != NULL)
4752                 seq_server_set_cli(NULL, ss->ss_server_seq, NULL);
4753 }
4754
4755 static int mdt_seq_fini(const struct lu_env *env, struct mdt_device *mdt)
4756 {
4757         mdt_seq_fini_cli(mdt);
4758         mdt_deregister_seq_exp(mdt);
4759
4760         return seq_site_fini(env, mdt_seq_site(mdt));
4761 }
4762
4763 /**
4764  * It will retrieve its FLDB entries from MDT0, and it only happens
4765  * when upgrading existent FS to 2.6 or when local FLDB is corrupted,
4766  * and it needs to refresh FLDB from the MDT0.
4767  **/
4768 static int mdt_register_lwp_callback(void *data)
4769 {
4770         struct lu_env           env;
4771         struct mdt_device       *mdt = data;
4772         struct lu_server_fld    *fld = mdt_seq_site(mdt)->ss_server_fld;
4773         int                     rc;
4774         ENTRY;
4775
4776         LASSERT(mdt_seq_site(mdt)->ss_node_id != 0);
4777
4778         rc = lu_env_init(&env, LCT_MD_THREAD);
4779         if (rc < 0) {
4780                 CERROR("%s: cannot init env: rc = %d\n", mdt_obd_name(mdt), rc);
4781                 RETURN(rc);
4782         }
4783
4784         /* Allocate new sequence now to avoid creating local transaction
4785          * in the normal transaction process */
4786         rc = seq_server_check_and_alloc_super(&env,
4787                                               mdt_seq_site(mdt)->ss_server_seq);
4788         if (rc < 0)
4789                 GOTO(out, rc);
4790
4791         if (fld->lsf_new) {
4792                 rc = fld_update_from_controller(&env, fld);
4793                 if (rc != 0) {
4794                         CERROR("%s: cannot update controller: rc = %d\n",
4795                                mdt_obd_name(mdt), rc);
4796                         GOTO(out, rc);
4797                 }
4798         }
4799 out:
4800         lu_env_fini(&env);
4801         RETURN(rc);
4802 }
4803
4804 static int mdt_register_seq_exp(struct mdt_device *mdt)
4805 {
4806         struct seq_server_site  *ss = mdt_seq_site(mdt);
4807         char                    *lwp_name = NULL;
4808         int                     rc;
4809
4810         if (ss->ss_node_id == 0)
4811                 return 0;
4812
4813         OBD_ALLOC(lwp_name, MAX_OBD_NAME);
4814         if (lwp_name == NULL)
4815                 GOTO(out_free, rc = -ENOMEM);
4816
4817         rc = tgt_name2lwp_name(mdt_obd_name(mdt), lwp_name, MAX_OBD_NAME, 0);
4818         if (rc != 0)
4819                 GOTO(out_free, rc);
4820
4821         rc = lustre_register_lwp_item(lwp_name, &ss->ss_client_seq->lcs_exp,
4822                                       NULL, NULL);
4823         if (rc != 0)
4824                 GOTO(out_free, rc);
4825
4826         rc = lustre_register_lwp_item(lwp_name,
4827                                       &ss->ss_server_fld->lsf_control_exp,
4828                                       mdt_register_lwp_callback, mdt);
4829         if (rc != 0) {
4830                 lustre_deregister_lwp_item(&ss->ss_client_seq->lcs_exp);
4831                 ss->ss_client_seq->lcs_exp = NULL;
4832                 GOTO(out_free, rc);
4833         }
4834 out_free:
4835         if (lwp_name != NULL)
4836                 OBD_FREE(lwp_name, MAX_OBD_NAME);
4837
4838         return rc;
4839 }
4840
4841 /*
4842  * Init client sequence manager which is used by local MDS to talk to sequence
4843  * controller on remote node.
4844  */
4845 static int mdt_seq_init_cli(const struct lu_env *env, struct mdt_device *mdt)
4846 {
4847         struct seq_server_site *ss = mdt_seq_site(mdt);
4848         char *prefix;
4849         ENTRY;
4850
4851         /* check if this is adding the first MDC and controller is not yet
4852          * initialized. */
4853         OBD_ALLOC_PTR(ss->ss_client_seq);
4854         if (ss->ss_client_seq == NULL)
4855                 RETURN(-ENOMEM);
4856
4857         OBD_ALLOC(prefix, MAX_OBD_NAME + 5);
4858         if (prefix == NULL) {
4859                 OBD_FREE_PTR(ss->ss_client_seq);
4860                 ss->ss_client_seq = NULL;
4861                 RETURN(-ENOMEM);
4862         }
4863
4864         /* Note: seq_client_fini will be called in seq_site_fini */
4865         snprintf(prefix, MAX_OBD_NAME + 5, "ctl-%s", mdt_obd_name(mdt));
4866         seq_client_init(ss->ss_client_seq, NULL, LUSTRE_SEQ_METADATA,
4867                         prefix, ss->ss_node_id == 0 ?  ss->ss_control_seq :
4868                                                             NULL);
4869         OBD_FREE(prefix, MAX_OBD_NAME + 5);
4870
4871         RETURN(seq_server_set_cli(env, ss->ss_server_seq, ss->ss_client_seq));
4872 }
4873
4874 static int mdt_seq_init(const struct lu_env *env, struct mdt_device *mdt)
4875 {
4876         struct seq_server_site  *ss;
4877         int                     rc;
4878         ENTRY;
4879
4880         ss = mdt_seq_site(mdt);
4881         /* init sequence controller server(MDT0) */
4882         if (ss->ss_node_id == 0) {
4883                 OBD_ALLOC_PTR(ss->ss_control_seq);
4884                 if (ss->ss_control_seq == NULL)
4885                         RETURN(-ENOMEM);
4886
4887                 rc = seq_server_init(env, ss->ss_control_seq, mdt->mdt_bottom,
4888                                      mdt_obd_name(mdt), LUSTRE_SEQ_CONTROLLER,
4889                                      ss);
4890                 if (rc)
4891                         GOTO(out_seq_fini, rc);
4892         }
4893
4894         /* Init normal sequence server */
4895         OBD_ALLOC_PTR(ss->ss_server_seq);
4896         if (ss->ss_server_seq == NULL)
4897                 GOTO(out_seq_fini, rc = -ENOMEM);
4898
4899         rc = seq_server_init(env, ss->ss_server_seq, mdt->mdt_bottom,
4900                              mdt_obd_name(mdt), LUSTRE_SEQ_SERVER, ss);
4901         if (rc)
4902                 GOTO(out_seq_fini, rc);
4903
4904         /* init seq client for seq server to talk to seq controller(MDT0) */
4905         rc = mdt_seq_init_cli(env, mdt);
4906         if (rc != 0)
4907                 GOTO(out_seq_fini, rc);
4908
4909         if (ss->ss_node_id != 0)
4910                 /* register controller export through lwp */
4911                 rc = mdt_register_seq_exp(mdt);
4912
4913         EXIT;
4914 out_seq_fini:
4915         if (rc)
4916                 mdt_seq_fini(env, mdt);
4917
4918         return rc;
4919 }
4920
4921 /*
4922  * FLD wrappers
4923  */
4924 static int mdt_fld_fini(const struct lu_env *env,
4925                         struct mdt_device *m)
4926 {
4927         struct seq_server_site *ss = mdt_seq_site(m);
4928         ENTRY;
4929
4930         if (ss && ss->ss_server_fld) {
4931                 fld_server_fini(env, ss->ss_server_fld);
4932                 OBD_FREE_PTR(ss->ss_server_fld);
4933                 ss->ss_server_fld = NULL;
4934         }
4935
4936         RETURN(0);
4937 }
4938
4939 static int mdt_fld_init(const struct lu_env *env,
4940                         const char *uuid,
4941                         struct mdt_device *m)
4942 {
4943         struct seq_server_site *ss;
4944         int rc;
4945         ENTRY;
4946
4947         ss = mdt_seq_site(m);
4948
4949         OBD_ALLOC_PTR(ss->ss_server_fld);
4950         if (ss->ss_server_fld == NULL)
4951                 RETURN(rc = -ENOMEM);
4952
4953         rc = fld_server_init(env, ss->ss_server_fld, m->mdt_bottom, uuid,
4954                              LU_SEQ_RANGE_MDT);
4955         if (rc) {
4956                 OBD_FREE_PTR(ss->ss_server_fld);
4957                 ss->ss_server_fld = NULL;
4958                 RETURN(rc);
4959         }
4960
4961         RETURN(0);
4962 }
4963
4964 static void mdt_stack_pre_fini(const struct lu_env *env,
4965                            struct mdt_device *m, struct lu_device *top)
4966 {
4967         struct lustre_cfg_bufs  *bufs;
4968         struct lustre_cfg       *lcfg;
4969         struct mdt_thread_info  *info;
4970         ENTRY;
4971
4972         LASSERT(top);
4973
4974         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
4975         LASSERT(info != NULL);
4976
4977         bufs = &info->mti_u.bufs;
4978
4979         LASSERT(m->mdt_child_exp);
4980         LASSERT(m->mdt_child_exp->exp_obd);
4981
4982         /* process cleanup, pass mdt obd name to get obd umount flags */
4983         /* XXX: this is needed because all layers are referenced by
4984          * objects (some of them are pinned by osd, for example *
4985          * the proper solution should be a model where object used
4986          * by osd only doesn't have mdt/mdd slices -bzzz */
4987         lustre_cfg_bufs_reset(bufs, mdt_obd_name(m));
4988         lustre_cfg_bufs_set_string(bufs, 1, NULL);
4989         OBD_ALLOC(lcfg, lustre_cfg_len(bufs->lcfg_bufcount, bufs->lcfg_buflen));
4990         if (!lcfg)
4991                 RETURN_EXIT;
4992         lustre_cfg_init(lcfg, LCFG_PRE_CLEANUP, bufs);
4993
4994         top->ld_ops->ldo_process_config(env, top, lcfg);
4995         OBD_FREE(lcfg, lustre_cfg_len(lcfg->lcfg_bufcount, lcfg->lcfg_buflens));
4996         EXIT;
4997 }
4998
4999 static void mdt_stack_fini(const struct lu_env *env,
5000                            struct mdt_device *m, struct lu_device *top)
5001 {
5002         struct obd_device       *obd = mdt2obd_dev(m);
5003         struct lustre_cfg_bufs  *bufs;
5004         struct lustre_cfg       *lcfg;
5005         struct mdt_thread_info  *info;
5006         char                     flags[3] = "";
5007         ENTRY;
5008
5009         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
5010         LASSERT(info != NULL);
5011
5012         lu_dev_del_linkage(top->ld_site, top);
5013
5014         lu_site_purge(env, top->ld_site, -1);
5015
5016         bufs = &info->mti_u.bufs;
5017         /* process cleanup, pass mdt obd name to get obd umount flags */
5018         /* another purpose is to let all layers to release their objects */
5019         lustre_cfg_bufs_reset(bufs, mdt_obd_name(m));
5020         if (obd->obd_force)
5021                 strcat(flags, "F");
5022         if (obd->obd_fail)
5023                 strcat(flags, "A");
5024         lustre_cfg_bufs_set_string(bufs, 1, flags);
5025         OBD_ALLOC(lcfg, lustre_cfg_len(bufs->lcfg_bufcount, bufs->lcfg_buflen));
5026         if (!lcfg)
5027                 RETURN_EXIT;
5028         lustre_cfg_init(lcfg, LCFG_CLEANUP, bufs);
5029
5030         LASSERT(top);
5031         top->ld_ops->ldo_process_config(env, top, lcfg);
5032         OBD_FREE(lcfg, lustre_cfg_len(lcfg->lcfg_bufcount, lcfg->lcfg_buflens));
5033
5034         lu_site_purge(env, top->ld_site, -1);
5035
5036         m->mdt_child = NULL;
5037         m->mdt_bottom = NULL;
5038
5039         obd_disconnect(m->mdt_child_exp);
5040         m->mdt_child_exp = NULL;
5041
5042         obd_disconnect(m->mdt_bottom_exp);
5043         m->mdt_child_exp = NULL;
5044 }
5045
5046 static int mdt_connect_to_next(const struct lu_env *env, struct mdt_device *m,
5047                                const char *next, struct obd_export **exp)
5048 {
5049         struct obd_connect_data *data = NULL;
5050         struct obd_device       *obd;
5051         int                      rc;
5052         ENTRY;
5053
5054         OBD_ALLOC_PTR(data);
5055         if (data == NULL)
5056                 GOTO(out, rc = -ENOMEM);
5057
5058         obd = class_name2obd(next);
5059         if (obd == NULL) {
5060                 CERROR("%s: can't locate next device: %s\n",
5061                        mdt_obd_name(m), next);
5062                 GOTO(out, rc = -ENOTCONN);
5063         }
5064
5065         data->ocd_connect_flags = OBD_CONNECT_VERSION;
5066         data->ocd_version = LUSTRE_VERSION_CODE;
5067
5068         rc = obd_connect(NULL, exp, obd, &obd->obd_uuid, data, NULL);
5069         if (rc) {
5070                 CERROR("%s: cannot connect to next dev %s (%d)\n",
5071                        mdt_obd_name(m), next, rc);
5072                 GOTO(out, rc);
5073         }
5074
5075 out:
5076         if (data)
5077                 OBD_FREE_PTR(data);
5078         RETURN(rc);
5079 }
5080
5081 static int mdt_stack_init(const struct lu_env *env, struct mdt_device *mdt,
5082                           struct lustre_cfg *cfg)
5083 {
5084         char                   *dev = lustre_cfg_string(cfg, 0);
5085         int                     rc, name_size, uuid_size;
5086         char                   *name, *uuid, *p;
5087         struct lustre_cfg_bufs *bufs;
5088         struct lustre_cfg      *lcfg;
5089         struct obd_device      *obd;
5090         struct lustre_profile  *lprof;
5091         struct lu_site         *site;
5092         ENTRY;
5093
5094         /* in 1.8 we had the only device in the stack - MDS.
5095          * 2.0 introduces MDT, MDD, OSD; MDT starts others internally.
5096          * in 2.3 OSD is instantiated by obd_mount.c, so we need
5097          * to generate names and setup MDT, MDD. MDT will be using
5098          * generated name to connect to MDD. for MDD the next device
5099          * will be LOD with name taken from so called "profile" which
5100          * is generated by mount_option line
5101          *
5102          * 1.8 MGS generates config. commands like this:
5103          *   #06 (104)mount_option 0:  1:lustre-MDT0000  2:lustre-mdtlov
5104          *   #08 (120)setup   0:lustre-MDT0000  1:dev 2:type 3:lustre-MDT0000
5105          * 2.0 MGS generates config. commands like this:
5106          *   #07 (112)mount_option 0:  1:lustre-MDT0000  2:lustre-MDT0000-mdtlov
5107          *   #08 (160)setup   0:lustre-MDT0000  1:lustre-MDT0000_UUID  2:0
5108          *                    3:lustre-MDT0000-mdtlov  4:f
5109          *
5110          * we generate MDD name from MDT one, just replacing T with D
5111          *
5112          * after all the preparations, the logical equivalent will be
5113          *   #01 (160)setup   0:lustre-MDD0000  1:lustre-MDD0000_UUID  2:0
5114          *                    3:lustre-MDT0000-mdtlov  4:f
5115          *   #02 (160)setup   0:lustre-MDT0000  1:lustre-MDT0000_UUID  2:0
5116          *                    3:lustre-MDD0000  4:f
5117          *
5118          *  notice we build the stack from down to top: MDD first, then MDT */
5119
5120         name_size = MAX_OBD_NAME;
5121         uuid_size = MAX_OBD_NAME;
5122
5123         OBD_ALLOC(name, name_size);
5124         OBD_ALLOC(uuid, uuid_size);
5125         if (name == NULL || uuid == NULL)
5126                 GOTO(cleanup_mem, rc = -ENOMEM);
5127
5128         OBD_ALLOC_PTR(bufs);
5129         if (!bufs)
5130                 GOTO(cleanup_mem, rc = -ENOMEM);
5131
5132         strcpy(name, dev);
5133         p = strstr(name, "-MDT");
5134         if (p == NULL)
5135                 GOTO(free_bufs, rc = -ENOMEM);
5136         p[3] = 'D';
5137
5138         snprintf(uuid, MAX_OBD_NAME, "%s_UUID", name);
5139
5140         lprof = class_get_profile(lustre_cfg_string(cfg, 0));
5141         if (lprof == NULL || lprof->lp_dt == NULL) {
5142                 CERROR("can't find the profile: %s\n",
5143                        lustre_cfg_string(cfg, 0));
5144                 GOTO(free_bufs, rc = -EINVAL);
5145         }
5146
5147         lustre_cfg_bufs_reset(bufs, name);
5148         lustre_cfg_bufs_set_string(bufs, 1, LUSTRE_MDD_NAME);
5149         lustre_cfg_bufs_set_string(bufs, 2, uuid);
5150         lustre_cfg_bufs_set_string(bufs, 3, lprof->lp_dt);
5151
5152         OBD_ALLOC(lcfg, lustre_cfg_len(bufs->lcfg_bufcount, bufs->lcfg_buflen));
5153         if (!lcfg)
5154                 GOTO(put_profile, rc = -ENOMEM);
5155         lustre_cfg_init(lcfg, LCFG_ATTACH, bufs);
5156
5157         rc = class_attach(lcfg);
5158         if (rc)
5159                 GOTO(lcfg_cleanup, rc);
5160
5161         obd = class_name2obd(name);
5162         if (!obd) {
5163                 CERROR("Can not find obd %s (%s in config)\n",
5164                        MDD_OBD_NAME, lustre_cfg_string(cfg, 0));
5165                 GOTO(lcfg_cleanup, rc = -EINVAL);
5166         }
5167
5168         OBD_FREE(lcfg, lustre_cfg_len(lcfg->lcfg_bufcount, lcfg->lcfg_buflens));
5169
5170         lustre_cfg_bufs_reset(bufs, name);
5171         lustre_cfg_bufs_set_string(bufs, 1, uuid);
5172         lustre_cfg_bufs_set_string(bufs, 2, dev);
5173         lustre_cfg_bufs_set_string(bufs, 3, lprof->lp_dt);
5174
5175         OBD_ALLOC(lcfg, lustre_cfg_len(bufs->lcfg_bufcount, bufs->lcfg_buflen));
5176         if (!lcfg)
5177                 GOTO(class_detach, rc = -ENOMEM);
5178         lustre_cfg_init(lcfg, LCFG_SETUP, bufs);
5179
5180         rc = class_setup(obd, lcfg);
5181         if (rc)
5182                 GOTO(class_detach, rc);
5183
5184         /* connect to MDD we just setup */
5185         rc = mdt_connect_to_next(env, mdt, name, &mdt->mdt_child_exp);
5186         if (rc)
5187                 GOTO(class_detach, rc);
5188
5189         site = mdt->mdt_child_exp->exp_obd->obd_lu_dev->ld_site;
5190         LASSERT(site);
5191         LASSERT(mdt_lu_site(mdt) == NULL);
5192         mdt->mdt_lu_dev.ld_site = site;
5193         site->ls_top_dev = &mdt->mdt_lu_dev;
5194         mdt->mdt_child = lu2md_dev(mdt->mdt_child_exp->exp_obd->obd_lu_dev);
5195
5196         /* now connect to bottom OSD */
5197         snprintf(name, MAX_OBD_NAME, "%s-osd", dev);
5198         rc = mdt_connect_to_next(env, mdt, name, &mdt->mdt_bottom_exp);
5199         if (rc)
5200                 GOTO(class_detach, rc);
5201         mdt->mdt_bottom =
5202                 lu2dt_dev(mdt->mdt_bottom_exp->exp_obd->obd_lu_dev);
5203
5204         rc = lu_env_refill((struct lu_env *)env);
5205         if (rc != 0)
5206                 CERROR("Failure to refill session: '%d'\n", rc);
5207
5208         lu_dev_add_linkage(site, &mdt->mdt_lu_dev);
5209
5210         EXIT;
5211 class_detach:
5212         if (rc)
5213                 class_detach(obd, lcfg);
5214 lcfg_cleanup:
5215         OBD_FREE(lcfg, lustre_cfg_len(lcfg->lcfg_bufcount, lcfg->lcfg_buflens));
5216 put_profile:
5217         class_put_profile(lprof);
5218 free_bufs:
5219         OBD_FREE_PTR(bufs);
5220 cleanup_mem:
5221         if (name)
5222                 OBD_FREE(name, name_size);
5223         if (uuid)
5224                 OBD_FREE(uuid, uuid_size);
5225         RETURN(rc);
5226 }
5227
5228 /* setup quota master target on MDT0 */
5229 static int mdt_quota_init(const struct lu_env *env, struct mdt_device *mdt,
5230                           struct lustre_cfg *cfg)
5231 {
5232         struct obd_device       *obd;
5233         char                    *dev = lustre_cfg_string(cfg, 0);
5234         char                    *qmtname, *uuid, *p;
5235         struct lustre_cfg_bufs  *bufs;
5236         struct lustre_cfg       *lcfg;
5237         struct lustre_profile   *lprof;
5238         struct obd_connect_data *data;
5239         int                      rc;
5240         ENTRY;
5241
5242         LASSERT(mdt->mdt_qmt_exp == NULL);
5243         LASSERT(mdt->mdt_qmt_dev == NULL);
5244
5245         /* quota master is on MDT0 only for now */
5246         if (mdt->mdt_seq_site.ss_node_id != 0)
5247                 RETURN(0);
5248
5249         /* MGS generates config commands which look as follows:
5250          *   #01 (160)setup   0:lustre-MDT0000  1:lustre-MDT0000_UUID  2:0
5251          *                    3:lustre-MDT0000-mdtlov  4:f
5252          *
5253          * We generate the QMT name from the MDT one, just replacing MD with QM
5254          * after all the preparations, the logical equivalent will be:
5255          *   #01 (160)setup   0:lustre-QMT0000  1:lustre-QMT0000_UUID  2:0
5256          *                    3:lustre-MDT0000-osd  4:f */
5257         OBD_ALLOC(qmtname, MAX_OBD_NAME);
5258         OBD_ALLOC(uuid, UUID_MAX);
5259         OBD_ALLOC_PTR(bufs);
5260         OBD_ALLOC_PTR(data);
5261         if (qmtname == NULL || uuid == NULL || bufs == NULL || data == NULL)
5262                 GOTO(cleanup_mem, rc = -ENOMEM);
5263
5264         strcpy(qmtname, dev);
5265         p = strstr(qmtname, "-MDT");
5266         if (p == NULL)
5267                 GOTO(cleanup_mem, rc = -ENOMEM);
5268         /* replace MD with QM */
5269         p[1] = 'Q';
5270         p[2] = 'M';
5271
5272         snprintf(uuid, UUID_MAX, "%s_UUID", qmtname);
5273
5274         lprof = class_get_profile(lustre_cfg_string(cfg, 0));
5275         if (lprof == NULL || lprof->lp_dt == NULL) {
5276                 CERROR("can't find profile for %s\n",
5277                        lustre_cfg_string(cfg, 0));
5278                 GOTO(cleanup_mem, rc = -EINVAL);
5279         }
5280
5281         lustre_cfg_bufs_reset(bufs, qmtname);
5282         lustre_cfg_bufs_set_string(bufs, 1, LUSTRE_QMT_NAME);
5283         lustre_cfg_bufs_set_string(bufs, 2, uuid);
5284         lustre_cfg_bufs_set_string(bufs, 3, lprof->lp_dt);
5285
5286         OBD_ALLOC(lcfg, lustre_cfg_len(bufs->lcfg_bufcount, bufs->lcfg_buflen));
5287         if (!lcfg)
5288                 GOTO(put_profile, rc = -ENOMEM);
5289         lustre_cfg_init(lcfg, LCFG_ATTACH, bufs);
5290
5291         rc = class_attach(lcfg);
5292         if (rc)
5293                 GOTO(lcfg_cleanup, rc);
5294
5295         obd = class_name2obd(qmtname);
5296         if (!obd) {
5297                 CERROR("Can not find obd %s (%s in config)\n", qmtname,
5298                        lustre_cfg_string(cfg, 0));
5299                 GOTO(lcfg_cleanup, rc = -EINVAL);
5300         }
5301
5302         OBD_FREE(lcfg, lustre_cfg_len(lcfg->lcfg_bufcount, lcfg->lcfg_buflens));
5303
5304         lustre_cfg_bufs_reset(bufs, qmtname);
5305         lustre_cfg_bufs_set_string(bufs, 1, uuid);
5306         lustre_cfg_bufs_set_string(bufs, 2, dev);
5307
5308         /* for quota, the next device should be the OSD device */
5309         lustre_cfg_bufs_set_string(bufs, 3,
5310                                    mdt->mdt_bottom->dd_lu_dev.ld_obd->obd_name);
5311
5312         OBD_ALLOC(lcfg, lustre_cfg_len(bufs->lcfg_bufcount, bufs->lcfg_buflen));
5313         if (!lcfg)
5314                 GOTO(class_detach, rc = -ENOMEM);
5315         lustre_cfg_init(lcfg, LCFG_SETUP, bufs);
5316
5317         rc = class_setup(obd, lcfg);
5318         if (rc)
5319                 GOTO(class_detach, rc);
5320
5321         mdt->mdt_qmt_dev = obd->obd_lu_dev;
5322
5323         /* configure local quota objects */
5324         if (OBD_FAIL_CHECK(OBD_FAIL_QUOTA_INIT))
5325                 rc = -EBADF;
5326         else
5327                 rc = mdt->mdt_qmt_dev->ld_ops->ldo_prepare(env,
5328                                                            &mdt->mdt_lu_dev,
5329                                                            mdt->mdt_qmt_dev);
5330         if (rc)
5331                 GOTO(class_cleanup, rc);
5332
5333         /* connect to quota master target */
5334         data->ocd_connect_flags = OBD_CONNECT_VERSION;
5335         data->ocd_version = LUSTRE_VERSION_CODE;
5336         rc = obd_connect(NULL, &mdt->mdt_qmt_exp, obd, &obd->obd_uuid,
5337                          data, NULL);
5338         if (rc) {
5339                 CERROR("cannot connect to quota master device %s (%d)\n",
5340                        qmtname, rc);
5341                 GOTO(class_cleanup, rc);
5342         }
5343
5344         EXIT;
5345 class_cleanup:
5346         if (rc) {
5347                 class_manual_cleanup(obd);
5348                 mdt->mdt_qmt_dev = NULL;
5349                 GOTO(lcfg_cleanup, rc);
5350         }
5351 class_detach:
5352         if (rc)
5353                 class_detach(obd, lcfg);
5354 lcfg_cleanup:
5355         OBD_FREE(lcfg, lustre_cfg_len(lcfg->lcfg_bufcount, lcfg->lcfg_buflens));
5356 put_profile:
5357         class_put_profile(lprof);
5358 cleanup_mem:
5359         if (bufs)
5360                 OBD_FREE_PTR(bufs);
5361         if (qmtname)
5362                 OBD_FREE(qmtname, MAX_OBD_NAME);
5363         if (uuid)
5364                 OBD_FREE(uuid, UUID_MAX);
5365         if (data)
5366                 OBD_FREE_PTR(data);
5367         return rc;
5368 }
5369
5370 /* Shutdown quota master target associated with mdt */
5371 static void mdt_quota_fini(const struct lu_env *env, struct mdt_device *mdt)
5372 {
5373         ENTRY;
5374
5375         if (mdt->mdt_qmt_exp == NULL)
5376                 RETURN_EXIT;
5377         LASSERT(mdt->mdt_qmt_dev != NULL);
5378
5379         /* the qmt automatically shuts down when the mdt disconnects */
5380         obd_disconnect(mdt->mdt_qmt_exp);
5381         mdt->mdt_qmt_exp = NULL;
5382         mdt->mdt_qmt_dev = NULL;
5383         EXIT;
5384 }
5385
5386 /* mdt_getxattr() is used from mdt_intent_getxattr(), use this wrapper
5387  * for now. This will be removed along with converting rest of MDT code
5388  * to use tgt_session_info */
5389 static int mdt_tgt_getxattr(struct tgt_session_info *tsi)
5390 {
5391         struct mdt_thread_info  *info = tsi2mdt_info(tsi);
5392         int                      rc;
5393
5394         if (unlikely(info->mti_object == NULL))
5395                 return -EPROTO;
5396
5397         rc = mdt_getxattr(info);
5398
5399         mdt_thread_info_fini(info);
5400         return rc;
5401 }
5402
5403 static int mdt_llog_open(struct tgt_session_info *tsi)
5404 {
5405         ENTRY;
5406
5407         if (!mdt_is_rootadmin(tsi2mdt_info(tsi)))
5408                 RETURN(err_serious(-EACCES));
5409
5410         RETURN(tgt_llog_open(tsi));
5411 }
5412
5413 #define OBD_FAIL_OST_READ_NET   OBD_FAIL_OST_BRW_NET
5414 #define OBD_FAIL_OST_WRITE_NET  OBD_FAIL_OST_BRW_NET
5415 #define OST_BRW_READ    OST_READ
5416 #define OST_BRW_WRITE   OST_WRITE
5417
5418 static struct tgt_handler mdt_tgt_handlers[] = {
5419 TGT_RPC_HANDLER(MDS_FIRST_OPC,
5420                 0,                      MDS_CONNECT,    mdt_tgt_connect,
5421                 &RQF_CONNECT, LUSTRE_OBD_VERSION),
5422 TGT_RPC_HANDLER(MDS_FIRST_OPC,
5423                 0,                      MDS_DISCONNECT, tgt_disconnect,
5424                 &RQF_MDS_DISCONNECT, LUSTRE_OBD_VERSION),
5425 TGT_RPC_HANDLER(MDS_FIRST_OPC,
5426                 HAS_REPLY,              MDS_SET_INFO,   mdt_set_info,
5427                 &RQF_MDT_SET_INFO, LUSTRE_MDS_VERSION),
5428 TGT_MDT_HDL(0,                          MDS_GET_INFO,   mdt_get_info),
5429 TGT_MDT_HDL(HAS_REPLY,          MDS_GET_ROOT,   mdt_get_root),
5430 TGT_MDT_HDL(HAS_BODY,           MDS_GETATTR,    mdt_getattr),
5431 TGT_MDT_HDL(HAS_BODY | HAS_REPLY,       MDS_GETATTR_NAME,
5432                                                         mdt_getattr_name),
5433 TGT_MDT_HDL(HAS_BODY,           MDS_GETXATTR,   mdt_tgt_getxattr),
5434 TGT_MDT_HDL(HAS_REPLY,          MDS_STATFS,     mdt_statfs),
5435 TGT_MDT_HDL(IS_MUTABLE,         MDS_REINT,      mdt_reint),
5436 TGT_MDT_HDL(HAS_BODY,           MDS_CLOSE,      mdt_close),
5437 TGT_MDT_HDL(HAS_BODY | HAS_REPLY,       MDS_READPAGE,   mdt_readpage),
5438 TGT_MDT_HDL(HAS_BODY | HAS_REPLY,       MDS_SYNC,       mdt_sync),
5439 TGT_MDT_HDL(0,                          MDS_QUOTACTL,   mdt_quotactl),
5440 TGT_MDT_HDL(HAS_BODY | HAS_REPLY | IS_MUTABLE, MDS_HSM_PROGRESS,
5441                                                         mdt_hsm_progress),
5442 TGT_MDT_HDL(HAS_BODY | HAS_REPLY | IS_MUTABLE, MDS_HSM_CT_REGISTER,
5443                                                         mdt_hsm_ct_register),
5444 TGT_MDT_HDL(HAS_BODY | HAS_REPLY | IS_MUTABLE, MDS_HSM_CT_UNREGISTER,
5445                                                         mdt_hsm_ct_unregister),
5446 TGT_MDT_HDL(HAS_BODY | HAS_REPLY, MDS_HSM_STATE_GET,
5447                                                         mdt_hsm_state_get),
5448 TGT_MDT_HDL(HAS_BODY | HAS_REPLY | IS_MUTABLE, MDS_HSM_STATE_SET,
5449                                                         mdt_hsm_state_set),
5450 TGT_MDT_HDL(HAS_BODY | HAS_REPLY, MDS_HSM_ACTION,       mdt_hsm_action),
5451 TGT_MDT_HDL(HAS_BODY | HAS_REPLY, MDS_HSM_REQUEST,
5452                                                         mdt_hsm_request),
5453 TGT_MDT_HDL(HAS_KEY | HAS_BODY | HAS_REPLY | IS_MUTABLE,
5454             MDS_SWAP_LAYOUTS,
5455             mdt_swap_layouts),
5456 TGT_MDT_HDL(IS_MUTABLE,         MDS_RMFID,      mdt_rmfid),
5457 };
5458
5459 static struct tgt_handler mdt_io_ops[] = {
5460 TGT_OST_HDL_HP(HAS_BODY | HAS_REPLY, OST_BRW_READ, tgt_brw_read,
5461                                                         mdt_hp_brw),
5462 TGT_OST_HDL_HP(HAS_BODY | IS_MUTABLE,    OST_BRW_WRITE, tgt_brw_write,
5463                                                         mdt_hp_brw),
5464 TGT_OST_HDL_HP(HAS_BODY | HAS_REPLY | IS_MUTABLE,
5465                                          OST_PUNCH,     mdt_punch_hdl,
5466                                                         mdt_hp_punch),
5467 TGT_OST_HDL(HAS_BODY | HAS_REPLY, OST_SYNC,     mdt_data_sync),
5468 TGT_OST_HDL(HAS_BODY | HAS_REPLY, OST_SEEK, tgt_lseek),
5469 };
5470
5471 static struct tgt_handler mdt_sec_ctx_ops[] = {
5472 TGT_SEC_HDL_VAR(0,                      SEC_CTX_INIT,     mdt_sec_ctx_handle),
5473 TGT_SEC_HDL_VAR(0,                      SEC_CTX_INIT_CONT,mdt_sec_ctx_handle),
5474 TGT_SEC_HDL_VAR(0,                      SEC_CTX_FINI,     mdt_sec_ctx_handle)
5475 };
5476
5477 static struct tgt_handler mdt_quota_ops[] = {
5478 TGT_QUOTA_HDL(HAS_REPLY,                QUOTA_DQACQ,      mdt_quota_dqacq),
5479 };
5480
5481 static struct tgt_handler mdt_llog_handlers[] = {
5482         TGT_LLOG_HDL(0, LLOG_ORIGIN_HANDLE_CREATE,      mdt_llog_open),
5483         TGT_LLOG_HDL(0, LLOG_ORIGIN_HANDLE_NEXT_BLOCK,  tgt_llog_next_block),
5484         TGT_LLOG_HDL(0, LLOG_ORIGIN_HANDLE_READ_HEADER, tgt_llog_read_header),
5485         TGT_LLOG_HDL(0, LLOG_ORIGIN_HANDLE_PREV_BLOCK,  tgt_llog_prev_block),
5486 };
5487
5488 static struct tgt_opc_slice mdt_common_slice[] = {
5489         {
5490                 .tos_opc_start  = MDS_FIRST_OPC,
5491                 .tos_opc_end    = MDS_LAST_OPC,
5492                 .tos_hs         = mdt_tgt_handlers
5493         },
5494         {
5495                 .tos_opc_start  = OBD_FIRST_OPC,
5496                 .tos_opc_end    = OBD_LAST_OPC,
5497                 .tos_hs         = tgt_obd_handlers
5498         },
5499         {
5500                 .tos_opc_start  = LDLM_FIRST_OPC,
5501                 .tos_opc_end    = LDLM_LAST_OPC,
5502                 .tos_hs         = tgt_dlm_handlers
5503         },
5504         {
5505                 .tos_opc_start  = SEC_FIRST_OPC,
5506                 .tos_opc_end    = SEC_LAST_OPC,
5507                 .tos_hs         = mdt_sec_ctx_ops
5508         },
5509         {
5510                 .tos_opc_start  = OUT_UPDATE_FIRST_OPC,
5511                 .tos_opc_end    = OUT_UPDATE_LAST_OPC,
5512                 .tos_hs         = tgt_out_handlers
5513         },
5514         {
5515                 .tos_opc_start  = FLD_FIRST_OPC,
5516                 .tos_opc_end    = FLD_LAST_OPC,
5517                 .tos_hs         = fld_handlers
5518         },
5519         {
5520                 .tos_opc_start  = SEQ_FIRST_OPC,
5521                 .tos_opc_end    = SEQ_LAST_OPC,
5522                 .tos_hs         = seq_handlers
5523         },
5524         {
5525                 .tos_opc_start  = QUOTA_DQACQ,
5526                 .tos_opc_end    = QUOTA_LAST_OPC,
5527                 .tos_hs         = mdt_quota_ops
5528         },
5529         {
5530                 .tos_opc_start  = LLOG_FIRST_OPC,
5531                 .tos_opc_end    = LLOG_LAST_OPC,
5532                 .tos_hs         = mdt_llog_handlers
5533         },
5534         {
5535                 .tos_opc_start  = LFSCK_FIRST_OPC,
5536                 .tos_opc_end    = LFSCK_LAST_OPC,
5537                 .tos_hs         = tgt_lfsck_handlers
5538         },
5539         {
5540                 .tos_opc_start  = OST_FIRST_OPC,
5541                 .tos_opc_end    = OST_LAST_OPC,
5542                 .tos_hs         = mdt_io_ops
5543         },
5544         {
5545                 .tos_hs         = NULL
5546         }
5547 };
5548
5549 static void mdt_fini(const struct lu_env *env, struct mdt_device *m)
5550 {
5551         struct md_device *next = m->mdt_child;
5552         struct lu_device *d = &m->mdt_lu_dev;
5553         struct obd_device *obd = mdt2obd_dev(m);
5554         struct lfsck_stop stop;
5555
5556         ENTRY;
5557         stop.ls_status = LS_PAUSED;
5558         stop.ls_flags = 0;
5559         next->md_ops->mdo_iocontrol(env, next, OBD_IOC_STOP_LFSCK, 0, &stop);
5560
5561         mdt_stack_pre_fini(env, m, md2lu_dev(m->mdt_child));
5562
5563         mdt_restriper_stop(m);
5564         ping_evictor_stop();
5565
5566         /* Remove the HSM /proc entry so the coordinator cannot be
5567          * restarted by a user while it's shutting down.
5568          */
5569         mdt_hsm_cdt_stop(m);
5570
5571         mdt_llog_ctxt_unclone(env, m, LLOG_AGENT_ORIG_CTXT);
5572         mdt_llog_ctxt_unclone(env, m, LLOG_CHANGELOG_ORIG_CTXT);
5573
5574         if (m->mdt_namespace != NULL)
5575                 ldlm_namespace_free_prior(m->mdt_namespace, NULL,
5576                                           d->ld_obd->obd_force);
5577
5578         obd_exports_barrier(obd);
5579         obd_zombie_barrier();
5580
5581         mdt_quota_fini(env, m);
5582
5583         cfs_free_nidlist(&m->mdt_squash.rsi_nosquash_nids);
5584
5585         /* Calling the cleanup functions in the same order as in the mdt_init0
5586          * error path
5587          */
5588         mdt_tunables_fini(m);
5589
5590         target_recovery_fini(obd);
5591         upcall_cache_cleanup(m->mdt_identity_cache);
5592         m->mdt_identity_cache = NULL;
5593
5594         mdt_fs_cleanup(env, m);
5595
5596         tgt_fini(env, &m->mdt_lut);
5597
5598         mdt_hsm_cdt_fini(m);
5599
5600         if (m->mdt_los != NULL) {
5601                 local_oid_storage_fini(env, m->mdt_los);
5602                 m->mdt_los = NULL;
5603         }
5604
5605         if (m->mdt_namespace != NULL) {
5606                 ldlm_namespace_free_post(m->mdt_namespace);
5607                 d->ld_obd->obd_namespace = m->mdt_namespace = NULL;
5608         }
5609
5610         if (m->mdt_md_root != NULL) {
5611                 mdt_object_put(env, m->mdt_md_root);
5612                 m->mdt_md_root = NULL;
5613         }
5614
5615         mdt_seq_fini(env, m);
5616
5617         mdt_fld_fini(env, m);
5618
5619         /*
5620          * Finish the stack
5621          */
5622         mdt_stack_fini(env, m, md2lu_dev(m->mdt_child));
5623
5624         LASSERT(atomic_read(&d->ld_ref) == 0);
5625
5626         server_put_mount(mdt_obd_name(m), true);
5627
5628         EXIT;
5629 }
5630
5631 static int mdt_postrecov(const struct lu_env *, struct mdt_device *);
5632
5633 static int mdt_init0(const struct lu_env *env, struct mdt_device *m,
5634                      struct lu_device_type *ldt, struct lustre_cfg *cfg)
5635 {
5636         const struct dt_device_param *dt_conf;
5637         struct mdt_thread_info *info;
5638         struct obd_device *obd;
5639         const char *dev = lustre_cfg_string(cfg, 0);
5640         const char *num = lustre_cfg_string(cfg, 2);
5641         struct tg_grants_data *tgd = &m->mdt_lut.lut_tgd;
5642         struct lustre_mount_info *lmi = NULL;
5643         struct lustre_sb_info *lsi;
5644         struct lu_site *s;
5645         struct seq_server_site *ss_site;
5646         const char *identity_upcall = "NONE";
5647         struct md_device *next;
5648         struct lu_fid fid;
5649         int rc;
5650         long node_id;
5651         mntopt_t mntopts;
5652         ENTRY;
5653
5654         lu_device_init(&m->mdt_lu_dev, ldt);
5655         /*
5656          * Environment (env) might be missing mdt_thread_key values at that
5657          * point, if device is allocated when mdt_thread_key is in QUIESCENT
5658          * mode.
5659          *
5660          * Usually device allocation path doesn't use module key values, but
5661          * mdt has to do a lot of work here, so allocate key value.
5662          */
5663         rc = lu_env_refill((struct lu_env *)env);
5664         if (rc != 0)
5665                 RETURN(rc);
5666
5667         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
5668         LASSERT(info != NULL);
5669
5670         obd = class_name2obd(dev);
5671         LASSERT(obd != NULL);
5672
5673         m->mdt_max_mdsize = MAX_MD_SIZE_OLD;
5674         m->mdt_opts.mo_evict_tgt_nids = 1;
5675         m->mdt_opts.mo_cos = MDT_COS_DEFAULT;
5676
5677         lmi = server_get_mount(dev);
5678         if (lmi == NULL) {
5679                 CERROR("Cannot get mount info for %s!\n", dev);
5680                 RETURN(-EFAULT);
5681         } else {
5682                 lsi = s2lsi(lmi->lmi_sb);
5683                 LASSERT(lsi->lsi_lmd);
5684                 /* CMD is supported only in IAM mode */
5685                 LASSERT(num);
5686                 rc = kstrtol(num, 10, &node_id);
5687                 if (rc)
5688                         RETURN(rc);
5689
5690                 obd->u.obt.obt_magic = OBT_MAGIC;
5691                 if (lsi->lsi_lmd->lmd_flags & LMD_FLG_SKIP_LFSCK)
5692                         m->mdt_skip_lfsck = 1;
5693         }
5694
5695         /* Just try to get a DoM lock by default. Otherwise, having a group
5696          * lock granted, it may get blocked for a long time. */
5697         m->mdt_opts.mo_dom_lock = TRYLOCK_DOM_ON_OPEN;
5698         /* DoM files are read at open and data is packed in the reply */
5699         m->mdt_opts.mo_dom_read_open = 1;
5700
5701         m->mdt_squash.rsi_uid = 0;
5702         m->mdt_squash.rsi_gid = 0;
5703         INIT_LIST_HEAD(&m->mdt_squash.rsi_nosquash_nids);
5704         spin_lock_init(&m->mdt_squash.rsi_lock);
5705         spin_lock_init(&m->mdt_lock);
5706         m->mdt_enable_remote_dir = 1;
5707         m->mdt_enable_striped_dir = 1;
5708         m->mdt_enable_dir_migration = 1;
5709         m->mdt_enable_dir_restripe = 0;
5710         m->mdt_enable_dir_auto_split = 0;
5711         m->mdt_enable_remote_dir_gid = 0;
5712         m->mdt_enable_chprojid_gid = 0;
5713         m->mdt_enable_remote_rename = 1;
5714         m->mdt_dir_restripe_nsonly = 1;
5715         m->mdt_enable_remote_subdir_mount = 1;
5716
5717         atomic_set(&m->mdt_mds_mds_conns, 0);
5718         atomic_set(&m->mdt_async_commit_count, 0);
5719
5720         m->mdt_lu_dev.ld_ops = &mdt_lu_ops;
5721         m->mdt_lu_dev.ld_obd = obd;
5722         /* Set this lu_device to obd for error handling purposes. */
5723         obd->obd_lu_dev = &m->mdt_lu_dev;
5724
5725         /* init the stack */
5726         rc = mdt_stack_init((struct lu_env *)env, m, cfg);
5727         if (rc) {
5728                 CERROR("%s: Can't init device stack, rc %d\n",
5729                        mdt_obd_name(m), rc);
5730                 GOTO(err_lmi, rc);
5731         }
5732
5733         s = mdt_lu_site(m);
5734         ss_site = mdt_seq_site(m);
5735         s->ld_seq_site = ss_site;
5736         ss_site->ss_lu = s;
5737
5738         /* set server index */
5739         ss_site->ss_node_id = node_id;
5740
5741         /* failover is the default
5742          * FIXME: we do not failout mds0/mgs, which may cause some problems.
5743          * assumed whose ss_node_id == 0 XXX
5744          * */
5745         obd->obd_replayable = 1;
5746         /* No connection accepted until configurations will finish */
5747         obd->obd_no_conn = 1;
5748
5749         if (cfg->lcfg_bufcount > 4 && LUSTRE_CFG_BUFLEN(cfg, 4) > 0) {
5750                 char *str = lustre_cfg_string(cfg, 4);
5751                 if (strchr(str, 'n')) {
5752                         CWARN("%s: recovery disabled\n", mdt_obd_name(m));
5753                         obd->obd_replayable = 0;
5754                 }
5755         }
5756
5757         rc = mdt_fld_init(env, mdt_obd_name(m), m);
5758         if (rc)
5759                 GOTO(err_fini_stack, rc);
5760
5761         rc = mdt_seq_init(env, m);
5762         if (rc)
5763                 GOTO(err_fini_fld, rc);
5764
5765         snprintf(info->mti_u.ns_name, sizeof(info->mti_u.ns_name), "%s-%s",
5766                  LUSTRE_MDT_NAME, obd->obd_uuid.uuid);
5767         m->mdt_namespace = ldlm_namespace_new(obd, info->mti_u.ns_name,
5768                                               LDLM_NAMESPACE_SERVER,
5769                                               LDLM_NAMESPACE_GREEDY,
5770                                               LDLM_NS_TYPE_MDT);
5771         if (IS_ERR(m->mdt_namespace)) {
5772                 rc = PTR_ERR(m->mdt_namespace);
5773                 CERROR("%s: unable to create server namespace: rc = %d\n",
5774                        obd->obd_name, rc);
5775                 m->mdt_namespace = NULL;
5776                 GOTO(err_fini_seq, rc);
5777         }
5778
5779         m->mdt_namespace->ns_lvbp = m;
5780         m->mdt_namespace->ns_lvbo = &mdt_lvbo;
5781
5782         ldlm_register_intent(m->mdt_namespace, mdt_intent_policy);
5783         /* set obd_namespace for compatibility with old code */
5784         obd->obd_namespace = m->mdt_namespace;
5785
5786         rc = tgt_init(env, &m->mdt_lut, obd, m->mdt_bottom, mdt_common_slice,
5787                       OBD_FAIL_MDS_ALL_REQUEST_NET,
5788                       OBD_FAIL_MDS_ALL_REPLY_NET);
5789         if (rc)
5790                 GOTO(err_free_ns, rc);
5791
5792         /* Amount of available space excluded from granting and reserved
5793          * for metadata. It is a percentage of the total MDT size. */
5794         tgd->tgd_reserved_pcnt = 10;
5795
5796         if (ONE_MB_BRW_SIZE < (1U << tgd->tgd_blockbits))
5797                 m->mdt_brw_size = 1U << tgd->tgd_blockbits;
5798         else
5799                 m->mdt_brw_size = ONE_MB_BRW_SIZE;
5800
5801         rc = mdt_fs_setup(env, m, obd, lsi);
5802         if (rc)
5803                 GOTO(err_tgt, rc);
5804
5805         fid.f_seq = FID_SEQ_LOCAL_NAME;
5806         fid.f_oid = 1;
5807         fid.f_ver = 0;
5808         rc = local_oid_storage_init(env, m->mdt_bottom, &fid, &m->mdt_los);
5809         if (rc != 0)
5810                 GOTO(err_fs_cleanup, rc);
5811
5812         rc = mdt_hsm_cdt_init(m);
5813         if (rc != 0) {
5814                 CERROR("%s: error initializing coordinator, rc %d\n",
5815                        mdt_obd_name(m), rc);
5816                 GOTO(err_los_fini, rc);
5817         }
5818
5819         tgt_adapt_sptlrpc_conf(&m->mdt_lut);
5820
5821         next = m->mdt_child;
5822         dt_conf = next->md_ops->mdo_dtconf_get(env, next);
5823
5824         mntopts = dt_conf->ddp_mntopts;
5825
5826         if (mntopts & MNTOPT_USERXATTR)
5827                 m->mdt_opts.mo_user_xattr = 1;
5828         else
5829                 m->mdt_opts.mo_user_xattr = 0;
5830
5831         m->mdt_max_ea_size = dt_conf->ddp_max_ea_size;
5832
5833         if (mntopts & MNTOPT_ACL)
5834                 m->mdt_opts.mo_acl = 1;
5835         else
5836                 m->mdt_opts.mo_acl = 0;
5837
5838         /* XXX: to support suppgid for ACL, we enable identity_upcall
5839          * by default, otherwise, maybe got unexpected -EACCESS. */
5840         if (m->mdt_opts.mo_acl)
5841                 identity_upcall = MDT_IDENTITY_UPCALL_PATH;
5842
5843         m->mdt_identity_cache = upcall_cache_init(mdt_obd_name(m),
5844                                                 identity_upcall,
5845                                                 &mdt_identity_upcall_cache_ops);
5846         if (IS_ERR(m->mdt_identity_cache)) {
5847                 rc = PTR_ERR(m->mdt_identity_cache);
5848                 m->mdt_identity_cache = NULL;
5849                 GOTO(err_free_hsm, rc);
5850         }
5851
5852         rc = mdt_tunables_init(m, dev);
5853         if (rc) {
5854                 CERROR("Can't init MDT lprocfs, rc %d\n", rc);
5855                 GOTO(err_recovery, rc);
5856         }
5857
5858         rc = mdt_quota_init(env, m, cfg);
5859         if (rc)
5860                 GOTO(err_procfs, rc);
5861
5862         m->mdt_ldlm_client = &mdt2obd_dev(m)->obd_ldlm_client;
5863         ptlrpc_init_client(LDLM_CB_REQUEST_PORTAL, LDLM_CB_REPLY_PORTAL,
5864                            "mdt_ldlm_client", m->mdt_ldlm_client);
5865
5866         ping_evictor_start();
5867
5868         /* recovery will be started upon mdt_prepare()
5869          * when the whole stack is complete and ready
5870          * to serve the requests */
5871
5872         /* Reduce the initial timeout on an MDS because it doesn't need such
5873          * a long timeout as an OST does. Adaptive timeouts will adjust this
5874          * value appropriately. */
5875         if (ldlm_timeout == LDLM_TIMEOUT_DEFAULT)
5876                 ldlm_timeout = MDS_LDLM_TIMEOUT_DEFAULT;
5877
5878         if ((lsi->lsi_lmd->lmd_flags & LMD_FLG_LOCAL_RECOV))
5879                 m->mdt_lut.lut_local_recovery = 1;
5880
5881         rc = mdt_restriper_start(m);
5882         if (rc)
5883                 GOTO(err_ping_evictor, rc);
5884
5885         RETURN(0);
5886
5887 err_ping_evictor:
5888         ping_evictor_stop();
5889 err_procfs:
5890         mdt_tunables_fini(m);
5891 err_recovery:
5892         upcall_cache_cleanup(m->mdt_identity_cache);
5893         m->mdt_identity_cache = NULL;
5894 err_free_hsm:
5895         mdt_hsm_cdt_fini(m);
5896 err_los_fini:
5897         local_oid_storage_fini(env, m->mdt_los);
5898         m->mdt_los = NULL;
5899 err_fs_cleanup:
5900         mdt_fs_cleanup(env, m);
5901 err_tgt:
5902         /* keep recoverable clients */
5903         obd->obd_fail = 1;
5904         target_recovery_fini(obd);
5905         obd_exports_barrier(obd);
5906         obd_zombie_barrier();
5907         tgt_fini(env, &m->mdt_lut);
5908 err_free_ns:
5909         ldlm_namespace_free(m->mdt_namespace, NULL, 0);
5910         obd->obd_namespace = m->mdt_namespace = NULL;
5911 err_fini_seq:
5912         mdt_seq_fini(env, m);
5913 err_fini_fld:
5914         mdt_fld_fini(env, m);
5915 err_fini_stack:
5916         mdt_stack_fini(env, m, md2lu_dev(m->mdt_child));
5917 err_lmi:
5918         if (lmi)
5919                 server_put_mount(dev, true);
5920         return(rc);
5921 }
5922
5923 /* For interoperability, the left element is old parameter, the right one
5924  * is the new version of the parameter, if some parameter is deprecated,
5925  * the new version should be set as NULL. */
5926 static struct cfg_interop_param mdt_interop_param[] = {
5927         { "mdt.group_upcall",   NULL },
5928         { "mdt.quota_type",     NULL },
5929         { "mdd.quota_type",     NULL },
5930         { "mdt.som",            NULL },
5931         { "mdt.rootsquash",     "mdt.root_squash" },
5932         { "mdt.nosquash_nid",   "mdt.nosquash_nids" },
5933         { NULL }
5934 };
5935
5936 /* used by MGS to process specific configurations */
5937 static int mdt_process_config(const struct lu_env *env,
5938                               struct lu_device *d, struct lustre_cfg *cfg)
5939 {
5940         struct mdt_device *m = mdt_dev(d);
5941         struct md_device *md_next = m->mdt_child;
5942         struct lu_device *next = md2lu_dev(md_next);
5943         int rc;
5944         ENTRY;
5945
5946         switch (cfg->lcfg_command) {
5947         case LCFG_PARAM: {
5948                 struct obd_device *obd = d->ld_obd;
5949                 /* For interoperability */
5950                 struct cfg_interop_param *ptr = NULL;
5951                 struct lustre_cfg *old_cfg = NULL;
5952                 char *param = NULL;
5953                 ssize_t count;
5954
5955                 param = lustre_cfg_string(cfg, 1);
5956                 if (param == NULL) {
5957                         CERROR("param is empty\n");
5958                         rc = -EINVAL;
5959                         break;
5960                 }
5961
5962                 ptr = class_find_old_param(param, mdt_interop_param);
5963                 if (ptr != NULL) {
5964                         if (ptr->new_param == NULL) {
5965                                 rc = 0;
5966                                 CWARN("For interoperability, skip this %s."
5967                                       " It is obsolete.\n", ptr->old_param);
5968                                 break;
5969                         }
5970
5971                         CWARN("Found old param %s, changed it to %s.\n",
5972                               ptr->old_param, ptr->new_param);
5973
5974                         old_cfg = cfg;
5975                         cfg = lustre_cfg_rename(old_cfg, ptr->new_param);
5976                         if (IS_ERR(cfg)) {
5977                                 rc = PTR_ERR(cfg);
5978                                 break;
5979                         }
5980                 }
5981
5982                 count = class_modify_config(cfg, PARAM_MDT,
5983                                             &obd->obd_kset.kobj);
5984                 if (count < 0) {
5985                         struct coordinator *cdt = &m->mdt_coordinator;
5986
5987                         /* is it an HSM var ? */
5988                         count = class_modify_config(cfg, PARAM_HSM,
5989                                                     &cdt->cdt_hsm_kobj);
5990                         if (count < 0)
5991                                 /* we don't understand; pass it on */
5992                                 rc = next->ld_ops->ldo_process_config(env, next,
5993                                                                       cfg);
5994                         else
5995                                 rc = count > 0 ? 0 : count;
5996                 } else {
5997                         rc = count > 0 ? 0 : count;
5998                 }
5999
6000                 if (old_cfg)
6001                         OBD_FREE(cfg, lustre_cfg_len(cfg->lcfg_bufcount,
6002                                                      cfg->lcfg_buflens));
6003                 break;
6004         }
6005         default:
6006                 /* others are passed further */
6007                 rc = next->ld_ops->ldo_process_config(env, next, cfg);
6008                 break;
6009         }
6010         RETURN(rc);
6011 }
6012
6013 static struct lu_object *mdt_object_alloc(const struct lu_env *env,
6014                                           const struct lu_object_header *hdr,
6015                                           struct lu_device *d)
6016 {
6017         struct mdt_object *mo;
6018
6019         ENTRY;
6020
6021         OBD_SLAB_ALLOC_PTR_GFP(mo, mdt_object_kmem, GFP_NOFS);
6022         if (mo != NULL) {
6023                 struct lu_object *o;
6024                 struct lu_object_header *h;
6025
6026                 o = &mo->mot_obj;
6027                 h = &mo->mot_header;
6028                 lu_object_header_init(h);
6029                 lu_object_init(o, h, d);
6030                 lu_object_add_top(h, o);
6031                 o->lo_ops = &mdt_obj_ops;
6032                 spin_lock_init(&mo->mot_write_lock);
6033                 mutex_init(&mo->mot_som_mutex);
6034                 mutex_init(&mo->mot_lov_mutex);
6035                 init_rwsem(&mo->mot_dom_sem);
6036                 init_rwsem(&mo->mot_open_sem);
6037                 atomic_set(&mo->mot_open_count, 0);
6038                 mo->mot_restripe_offset = 0;
6039                 INIT_LIST_HEAD(&mo->mot_restripe_linkage);
6040                 RETURN(o);
6041         }
6042         RETURN(NULL);
6043 }
6044
6045 static int mdt_object_init(const struct lu_env *env, struct lu_object *o,
6046                            const struct lu_object_conf *unused)
6047 {
6048         struct mdt_device *d = mdt_dev(o->lo_dev);
6049         struct lu_device  *under;
6050         struct lu_object  *below;
6051         int                rc = 0;
6052         ENTRY;
6053
6054         CDEBUG(D_INFO, "object init, fid = "DFID"\n",
6055                PFID(lu_object_fid(o)));
6056
6057         under = &d->mdt_child->md_lu_dev;
6058         below = under->ld_ops->ldo_object_alloc(env, o->lo_header, under);
6059         if (below != NULL) {
6060                 lu_object_add(o, below);
6061         } else
6062                 rc = -ENOMEM;
6063
6064         RETURN(rc);
6065 }
6066
6067 static void mdt_object_free_rcu(struct rcu_head *head)
6068 {
6069         struct mdt_object *mo = container_of(head, struct mdt_object,
6070                                              mot_header.loh_rcu);
6071
6072         kmem_cache_free(mdt_object_kmem, mo);
6073 }
6074
6075 static void mdt_object_free(const struct lu_env *env, struct lu_object *o)
6076 {
6077         struct mdt_object *mo = mdt_obj(o);
6078         struct lu_object_header *h;
6079         ENTRY;
6080
6081         h = o->lo_header;
6082         CDEBUG(D_INFO, "object free, fid = "DFID"\n",
6083                PFID(lu_object_fid(o)));
6084
6085         LASSERT(atomic_read(&mo->mot_open_count) == 0);
6086         LASSERT(atomic_read(&mo->mot_lease_count) == 0);
6087
6088         lu_object_fini(o);
6089         lu_object_header_fini(h);
6090         OBD_FREE_PRE(mo, sizeof(*mo), "slab-freed");
6091         call_rcu(&mo->mot_header.loh_rcu, mdt_object_free_rcu);
6092
6093         EXIT;
6094 }
6095
6096 static int mdt_object_print(const struct lu_env *env, void *cookie,
6097                             lu_printer_t p, const struct lu_object *o)
6098 {
6099         struct mdt_object *mdto = mdt_obj((struct lu_object *)o);
6100
6101         return (*p)(env, cookie,
6102                     LUSTRE_MDT_NAME"-object@%p(%s %s, writecount=%d)",
6103                     mdto, mdto->mot_lov_created ? "lov_created" : "",
6104                     mdto->mot_cache_attr ? "cache_attr" : "",
6105                     mdto->mot_write_count);
6106 }
6107
6108 static int mdt_prepare(const struct lu_env *env,
6109                 struct lu_device *pdev,
6110                 struct lu_device *cdev)
6111 {
6112         struct mdt_device *mdt = mdt_dev(cdev);
6113         struct lu_device *next = &mdt->mdt_child->md_lu_dev;
6114         struct obd_device *obd = cdev->ld_obd;
6115         int rc;
6116
6117         ENTRY;
6118
6119         LASSERT(obd);
6120
6121         rc = next->ld_ops->ldo_prepare(env, cdev, next);
6122         if (rc)
6123                 RETURN(rc);
6124
6125         rc = mdt_llog_ctxt_clone(env, mdt, LLOG_CHANGELOG_ORIG_CTXT);
6126         if (rc)
6127                 RETURN(rc);
6128
6129         rc = mdt_llog_ctxt_clone(env, mdt, LLOG_AGENT_ORIG_CTXT);
6130         if (rc)
6131                 RETURN(rc);
6132
6133         rc = lfsck_register_namespace(env, mdt->mdt_bottom, mdt->mdt_namespace);
6134         /* The LFSCK instance is registered just now, so it must be there when
6135          * register the namespace to such instance. */
6136         LASSERTF(rc == 0, "register namespace failed: rc = %d\n", rc);
6137
6138         if (mdt->mdt_seq_site.ss_node_id == 0) {
6139                 rc = mdt->mdt_child->md_ops->mdo_root_get(env, mdt->mdt_child,
6140                                                          &mdt->mdt_md_root_fid);
6141                 if (rc)
6142                         RETURN(rc);
6143         }
6144
6145         LASSERT(!test_bit(MDT_FL_CFGLOG, &mdt->mdt_state));
6146
6147         target_recovery_init(&mdt->mdt_lut, tgt_request_handle);
6148         set_bit(MDT_FL_CFGLOG, &mdt->mdt_state);
6149         LASSERT(obd->obd_no_conn);
6150         spin_lock(&obd->obd_dev_lock);
6151         obd->obd_no_conn = 0;
6152         spin_unlock(&obd->obd_dev_lock);
6153
6154         if (obd->obd_recovering == 0)
6155                 mdt_postrecov(env, mdt);
6156
6157         RETURN(rc);
6158 }
6159
6160 const struct lu_device_operations mdt_lu_ops = {
6161         .ldo_object_alloc   = mdt_object_alloc,
6162         .ldo_process_config = mdt_process_config,
6163         .ldo_prepare        = mdt_prepare,
6164 };
6165
6166 static const struct lu_object_operations mdt_obj_ops = {
6167         .loo_object_init    = mdt_object_init,
6168         .loo_object_free    = mdt_object_free,
6169         .loo_object_print   = mdt_object_print
6170 };
6171
6172 static int mdt_obd_set_info_async(const struct lu_env *env,
6173                                   struct obd_export *exp,
6174                                   __u32 keylen, void *key,
6175                                   __u32 vallen, void *val,
6176                                   struct ptlrpc_request_set *set)
6177 {
6178         int rc;
6179
6180         ENTRY;
6181
6182         if (KEY_IS(KEY_SPTLRPC_CONF)) {
6183                 rc = tgt_adapt_sptlrpc_conf(class_exp2tgt(exp));
6184                 RETURN(rc);
6185         }
6186
6187         RETURN(0);
6188 }
6189
6190 static inline void mdt_enable_slc(struct mdt_device *mdt)
6191 {
6192         if (mdt->mdt_lut.lut_sync_lock_cancel == SYNC_LOCK_CANCEL_NEVER)
6193                 mdt->mdt_lut.lut_sync_lock_cancel = SYNC_LOCK_CANCEL_BLOCKING;
6194 }
6195
6196 static inline void mdt_disable_slc(struct mdt_device *mdt)
6197 {
6198         if (mdt->mdt_lut.lut_sync_lock_cancel == SYNC_LOCK_CANCEL_BLOCKING)
6199                 mdt->mdt_lut.lut_sync_lock_cancel = SYNC_LOCK_CANCEL_NEVER;
6200 }
6201
6202 /**
6203  * Match client and server connection feature flags.
6204  *
6205  * Compute the compatibility flags for a connection request based on
6206  * features mutually supported by client and server.
6207  *
6208  * The obd_export::exp_connect_data.ocd_connect_flags field in \a exp
6209  * must not be updated here, otherwise a partially initialized value may
6210  * be exposed. After the connection request is successfully processed,
6211  * the top-level MDT connect request handler atomically updates the export
6212  * connect flags from the obd_connect_data::ocd_connect_flags field of the
6213  * reply. \see mdt_connect().
6214  *
6215  * Before 2.7.50 clients will send a struct obd_connect_data_v1 rather than a
6216  * full struct obd_connect_data. So care must be taken when accessing fields
6217  * that are not present in struct obd_connect_data_v1. See LU-16.
6218  *
6219  * \param exp   the obd_export associated with this client/target pair
6220  * \param mdt   the target device for the connection
6221  * \param data  stores data for this connect request
6222  *
6223  * \retval 0       success
6224  * \retval -EPROTO \a data unexpectedly has zero obd_connect_data::ocd_brw_size
6225  * \retval -EBADE  client and server feature requirements are incompatible
6226  */
6227 static int mdt_connect_internal(const struct lu_env *env,
6228                                 struct obd_export *exp,
6229                                 struct mdt_device *mdt,
6230                                 struct obd_connect_data *data, bool reconnect)
6231 {
6232         const char *obd_name = mdt_obd_name(mdt);
6233         LASSERT(data != NULL);
6234
6235         data->ocd_connect_flags &= MDT_CONNECT_SUPPORTED;
6236
6237         if (mdt->mdt_bottom->dd_rdonly &&
6238             !(data->ocd_connect_flags & OBD_CONNECT_MDS_MDS) &&
6239             !(data->ocd_connect_flags & OBD_CONNECT_RDONLY))
6240                 RETURN(-EACCES);
6241
6242         if (data->ocd_connect_flags & OBD_CONNECT_FLAGS2)
6243                 data->ocd_connect_flags2 &= MDT_CONNECT_SUPPORTED2;
6244
6245         data->ocd_ibits_known &= MDS_INODELOCK_FULL;
6246
6247         if (!mdt->mdt_opts.mo_acl)
6248                 data->ocd_connect_flags &= ~OBD_CONNECT_ACL;
6249
6250         if (!mdt->mdt_opts.mo_user_xattr)
6251                 data->ocd_connect_flags &= ~OBD_CONNECT_XATTR;
6252
6253         if (OCD_HAS_FLAG(data, BRW_SIZE)) {
6254                 data->ocd_brw_size = min(data->ocd_brw_size,
6255                                          mdt->mdt_brw_size);
6256                 if (data->ocd_brw_size == 0) {
6257                         CERROR("%s: cli %s/%p ocd_connect_flags: %#llx "
6258                                "ocd_version: %x ocd_grant: %d ocd_index: %u "
6259                                "ocd_brw_size unexpectedly zero, network data "
6260                                "corruption? Refusing to connect this client\n",
6261                                obd_name, exp->exp_client_uuid.uuid,
6262                                exp, data->ocd_connect_flags, data->ocd_version,
6263                                data->ocd_grant, data->ocd_index);
6264                         return -EPROTO;
6265                 }
6266         }
6267
6268         if (OCD_HAS_FLAG(data, GRANT_PARAM)) {
6269                 struct dt_device_param *ddp = &mdt->mdt_lut.lut_dt_conf;
6270
6271                 /* client is reporting its page size, for future use */
6272                 exp->exp_target_data.ted_pagebits = data->ocd_grant_blkbits;
6273                 data->ocd_grant_blkbits  = mdt->mdt_lut.lut_tgd.tgd_blockbits;
6274                 /* ddp_inodespace may not be power-of-two value, eg. for ldiskfs
6275                  * it's LDISKFS_DIR_REC_LEN(20) = 28. */
6276                 data->ocd_grant_inobits = fls(ddp->ddp_inodespace - 1);
6277                 /* ocd_grant_tax_kb is in 1K byte blocks */
6278                 data->ocd_grant_tax_kb = ddp->ddp_extent_tax >> 10;
6279                 data->ocd_grant_max_blks = ddp->ddp_max_extent_blks;
6280         }
6281
6282         /* Save connect_data we have so far because tgt_grant_connect()
6283          * uses it to calculate grant, and we want to save the client
6284          * version before it is overwritten by LUSTRE_VERSION_CODE. */
6285         exp->exp_connect_data = *data;
6286         if (OCD_HAS_FLAG(data, GRANT))
6287                 tgt_grant_connect(env, exp, data, !reconnect);
6288
6289         if (OCD_HAS_FLAG(data, MAXBYTES))
6290                 data->ocd_maxbytes = mdt->mdt_lut.lut_dt_conf.ddp_maxbytes;
6291
6292         /* NB: Disregard the rule against updating
6293          * exp_connect_data.ocd_connect_flags in this case, since
6294          * tgt_client_new() needs to know if this is a lightweight
6295          * connection, and it is safe to expose this flag before
6296          * connection processing completes. */
6297         if (data->ocd_connect_flags & OBD_CONNECT_LIGHTWEIGHT) {
6298                 spin_lock(&exp->exp_lock);
6299                 *exp_connect_flags_ptr(exp) |= OBD_CONNECT_LIGHTWEIGHT;
6300                 spin_unlock(&exp->exp_lock);
6301         }
6302
6303         data->ocd_version = LUSTRE_VERSION_CODE;
6304
6305         if ((data->ocd_connect_flags & OBD_CONNECT_FID) == 0) {
6306                 CWARN("%s: MDS requires FID support, but client not\n",
6307                       obd_name);
6308                 return -EBADE;
6309         }
6310
6311         if (OCD_HAS_FLAG(data, PINGLESS)) {
6312                 if (ptlrpc_pinger_suppress_pings()) {
6313                         spin_lock(&exp->exp_obd->obd_dev_lock);
6314                         list_del_init(&exp->exp_obd_chain_timed);
6315                         spin_unlock(&exp->exp_obd->obd_dev_lock);
6316                 } else {
6317                         data->ocd_connect_flags &= ~OBD_CONNECT_PINGLESS;
6318                 }
6319         }
6320
6321         data->ocd_max_easize = mdt->mdt_max_ea_size;
6322
6323         /* NB: Disregard the rule against updating
6324          * exp_connect_data.ocd_connect_flags in this case, since
6325          * tgt_client_new() needs to know if this is client supports
6326          * multiple modify RPCs, and it is safe to expose this flag before
6327          * connection processing completes. */
6328         if (data->ocd_connect_flags & OBD_CONNECT_MULTIMODRPCS) {
6329                 data->ocd_maxmodrpcs = max_mod_rpcs_per_client;
6330                 spin_lock(&exp->exp_lock);
6331                 *exp_connect_flags_ptr(exp) |= OBD_CONNECT_MULTIMODRPCS;
6332                 spin_unlock(&exp->exp_lock);
6333         }
6334
6335         if (OCD_HAS_FLAG(data, CKSUM)) {
6336                 __u32 cksum_types = data->ocd_cksum_types;
6337
6338                 tgt_mask_cksum_types(&mdt->mdt_lut, &data->ocd_cksum_types);
6339
6340                 if (unlikely(data->ocd_cksum_types == 0)) {
6341                         CERROR("%s: Connect with checksum support but no "
6342                                "ocd_cksum_types is set\n",
6343                                exp->exp_obd->obd_name);
6344                         RETURN(-EPROTO);
6345                 }
6346
6347                 CDEBUG(D_RPCTRACE, "%s: cli %s supports cksum type %x, return "
6348                        "%x\n", exp->exp_obd->obd_name, obd_export_nid2str(exp),
6349                        cksum_types, data->ocd_cksum_types);
6350         } else {
6351                 /* This client does not support OBD_CONNECT_CKSUM
6352                  * fall back to CRC32 */
6353                 CDEBUG(D_RPCTRACE, "%s: cli %s does not support "
6354                        "OBD_CONNECT_CKSUM, CRC32 will be used\n",
6355                        exp->exp_obd->obd_name, obd_export_nid2str(exp));
6356         }
6357
6358         if ((data->ocd_connect_flags & OBD_CONNECT_MDS_MDS) &&
6359             !(data->ocd_connect_flags & OBD_CONNECT_LIGHTWEIGHT)) {
6360                 atomic_inc(&mdt->mdt_mds_mds_conns);
6361                 mdt_enable_slc(mdt);
6362         }
6363
6364         if (!mdt->mdt_lut.lut_dt_conf.ddp_has_lseek_data_hole)
6365                 data->ocd_connect_flags2 &= ~OBD_CONNECT2_LSEEK;
6366
6367         return 0;
6368 }
6369
6370 static int mdt_ctxt_add_dirty_flag(struct lu_env *env,
6371                                    struct mdt_thread_info *info,
6372                                    struct mdt_file_data *mfd)
6373 {
6374         struct lu_context ses;
6375         int rc;
6376         ENTRY;
6377
6378         rc = lu_context_init(&ses, LCT_SERVER_SESSION);
6379         if (rc)
6380                 RETURN(rc);
6381
6382         env->le_ses = &ses;
6383         lu_context_enter(&ses);
6384
6385         mdt_ucred(info)->uc_valid = UCRED_OLD;
6386         rc = mdt_add_dirty_flag(info, mfd->mfd_object, &info->mti_attr);
6387
6388         lu_context_exit(&ses);
6389         lu_context_fini(&ses);
6390         env->le_ses = NULL;
6391
6392         RETURN(rc);
6393 }
6394
6395 static int mdt_export_cleanup(struct obd_export *exp)
6396 {
6397         LIST_HEAD(closing_list);
6398         struct mdt_export_data  *med = &exp->exp_mdt_data;
6399         struct obd_device       *obd = exp->exp_obd;
6400         struct mdt_device       *mdt;
6401         struct mdt_thread_info  *info;
6402         struct lu_env            env;
6403         struct mdt_file_data    *mfd, *n;
6404         int rc = 0;
6405         ENTRY;
6406
6407         spin_lock(&med->med_open_lock);
6408         while (!list_empty(&med->med_open_head)) {
6409                 struct list_head *tmp = med->med_open_head.next;
6410                 mfd = list_entry(tmp, struct mdt_file_data, mfd_list);
6411
6412                 /* Remove mfd handle so it can't be found again.
6413                  * We are consuming the mfd_list reference here. */
6414                 class_handle_unhash(&mfd->mfd_open_handle);
6415                 list_move_tail(&mfd->mfd_list, &closing_list);
6416         }
6417         spin_unlock(&med->med_open_lock);
6418         mdt = mdt_dev(obd->obd_lu_dev);
6419         LASSERT(mdt != NULL);
6420
6421         rc = lu_env_init(&env, LCT_MD_THREAD);
6422         if (rc)
6423                 RETURN(rc);
6424
6425         info = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
6426         LASSERT(info != NULL);
6427         memset(info, 0, sizeof *info);
6428         info->mti_env = &env;
6429         info->mti_mdt = mdt;
6430         info->mti_exp = exp;
6431
6432         if (!list_empty(&closing_list)) {
6433                 struct md_attr *ma = &info->mti_attr;
6434
6435                 /* Close any open files (which may also cause orphan
6436                  * unlinking). */
6437                 list_for_each_entry_safe(mfd, n, &closing_list, mfd_list) {
6438                         list_del_init(&mfd->mfd_list);
6439                         ma->ma_need = ma->ma_valid = 0;
6440
6441                         /* This file is being closed due to an eviction, it
6442                          * could have been modified and now dirty regarding to
6443                          * HSM archive, check this!
6444                          * The logic here is to mark a file dirty if there's a
6445                          * chance it was dirtied before the client was evicted,
6446                          * so that we don't have to wait for a release attempt
6447                          * before finding out the file was actually dirty and
6448                          * fail the release. Aggressively marking it dirty here
6449                          * will cause the policy engine to attempt to
6450                          * re-archive it; when rearchiving, we can compare the
6451                          * current version to the HSM data_version and make the
6452                          * archive request into a noop if it's not actually
6453                          * dirty.
6454                          */
6455                         if (mfd->mfd_open_flags & MDS_FMODE_WRITE)
6456                                 rc = mdt_ctxt_add_dirty_flag(&env, info, mfd);
6457
6458                         /* Don't unlink orphan on failover umount, LU-184 */
6459                         if (exp->exp_flags & OBD_OPT_FAILOVER) {
6460                                 ma->ma_valid = MA_FLAGS;
6461                                 ma->ma_attr_flags |= MDS_KEEP_ORPHAN;
6462                         }
6463                         ma->ma_valid |= MA_FORCE_LOG;
6464                         mdt_mfd_close(info, mfd);
6465                 }
6466         }
6467         info->mti_mdt = NULL;
6468         /* cleanup client slot early */
6469         /* Do not erase record for recoverable client. */
6470         if (!(exp->exp_flags & OBD_OPT_FAILOVER) || exp->exp_failed)
6471                 tgt_client_del(&env, exp);
6472         lu_env_fini(&env);
6473
6474         RETURN(rc);
6475 }
6476
6477 static int mdt_obd_disconnect(struct obd_export *exp)
6478 {
6479         int rc;
6480
6481         ENTRY;
6482
6483         LASSERT(exp);
6484         class_export_get(exp);
6485
6486         if (!(exp->exp_flags & OBD_OPT_FORCE))
6487                 tgt_grant_sanity_check(exp->exp_obd, __func__);
6488
6489         if ((exp_connect_flags(exp) & OBD_CONNECT_MDS_MDS) &&
6490             !(exp_connect_flags(exp) & OBD_CONNECT_LIGHTWEIGHT)) {
6491                 struct mdt_device *mdt = mdt_dev(exp->exp_obd->obd_lu_dev);
6492
6493                 if (atomic_dec_and_test(&mdt->mdt_mds_mds_conns))
6494                         mdt_disable_slc(mdt);
6495         }
6496
6497         rc = server_disconnect_export(exp);
6498         if (rc != 0)
6499                 CDEBUG(D_IOCTL, "server disconnect error: rc = %d\n", rc);
6500
6501         tgt_grant_discard(exp);
6502
6503         rc = mdt_export_cleanup(exp);
6504         nodemap_del_member(exp);
6505         class_export_put(exp);
6506         RETURN(rc);
6507 }
6508
6509 /* mds_connect copy */
6510 static int mdt_obd_connect(const struct lu_env *env,
6511                            struct obd_export **exp, struct obd_device *obd,
6512                            struct obd_uuid *cluuid,
6513                            struct obd_connect_data *data,
6514                            void *localdata)
6515 {
6516         struct obd_export       *lexp;
6517         struct lustre_handle    conn = { 0 };
6518         struct mdt_device       *mdt;
6519         int                      rc;
6520         lnet_nid_t              *client_nid = localdata;
6521         ENTRY;
6522
6523         LASSERT(env != NULL);
6524         LASSERT(data != NULL);
6525
6526         if (!exp || !obd || !cluuid)
6527                 RETURN(-EINVAL);
6528
6529         mdt = mdt_dev(obd->obd_lu_dev);
6530
6531         /*
6532          * first, check whether the stack is ready to handle requests
6533          * XXX: probably not very appropriate method is used now
6534          *      at some point we should find a better one
6535          */
6536         if (!test_bit(MDT_FL_SYNCED, &mdt->mdt_state) &&
6537             !(data->ocd_connect_flags & OBD_CONNECT_LIGHTWEIGHT) &&
6538             !(data->ocd_connect_flags & OBD_CONNECT_MDS_MDS)) {
6539                 rc = obd_get_info(env, mdt->mdt_child_exp,
6540                                   sizeof(KEY_OSP_CONNECTED),
6541                                   KEY_OSP_CONNECTED, NULL, NULL);
6542                 if (rc)
6543                         RETURN(-EAGAIN);
6544                 set_bit(MDT_FL_SYNCED, &mdt->mdt_state);
6545         }
6546
6547         rc = class_connect(&conn, obd, cluuid);
6548         if (rc)
6549                 RETURN(rc);
6550
6551         lexp = class_conn2export(&conn);
6552         LASSERT(lexp != NULL);
6553
6554         rc = nodemap_add_member(*client_nid, lexp);
6555         if (rc != 0 && rc != -EEXIST)
6556                 GOTO(out, rc);
6557
6558         rc = mdt_connect_internal(env, lexp, mdt, data, false);
6559         if (rc == 0) {
6560                 struct lsd_client_data *lcd = lexp->exp_target_data.ted_lcd;
6561
6562                 LASSERT(lcd);
6563                 memcpy(lcd->lcd_uuid, cluuid, sizeof lcd->lcd_uuid);
6564                 rc = tgt_client_new(env, lexp);
6565                 if (rc == 0)
6566                         mdt_export_stats_init(obd, lexp, localdata);
6567         }
6568 out:
6569         if (rc != 0) {
6570                 class_disconnect(lexp);
6571                 nodemap_del_member(lexp);
6572                 *exp = NULL;
6573         } else {
6574                 *exp = lexp;
6575                 /* Because we do not want this export to be evicted by pinger,
6576                  * let's not add this export to the timed chain list. */
6577                 if (data->ocd_connect_flags & OBD_CONNECT_MDS_MDS) {
6578                         spin_lock(&lexp->exp_obd->obd_dev_lock);
6579                         list_del_init(&lexp->exp_obd_chain_timed);
6580                         spin_unlock(&lexp->exp_obd->obd_dev_lock);
6581                 }
6582         }
6583
6584         RETURN(rc);
6585 }
6586
6587 static int mdt_obd_reconnect(const struct lu_env *env,
6588                              struct obd_export *exp, struct obd_device *obd,
6589                              struct obd_uuid *cluuid,
6590                              struct obd_connect_data *data,
6591                              void *localdata)
6592 {
6593         lnet_nid_t             *client_nid = localdata;
6594         int                     rc;
6595         ENTRY;
6596
6597         if (exp == NULL || obd == NULL || cluuid == NULL)
6598                 RETURN(-EINVAL);
6599
6600         rc = nodemap_add_member(*client_nid, exp);
6601         if (rc != 0 && rc != -EEXIST)
6602                 RETURN(rc);
6603
6604         rc = mdt_connect_internal(env, exp, mdt_dev(obd->obd_lu_dev), data,
6605                                   true);
6606         if (rc == 0)
6607                 mdt_export_stats_init(obd, exp, localdata);
6608         else
6609                 nodemap_del_member(exp);
6610
6611         RETURN(rc);
6612 }
6613
6614 /* FIXME: Can we avoid using these two interfaces? */
6615 static int mdt_init_export(struct obd_export *exp)
6616 {
6617         struct mdt_export_data *med = &exp->exp_mdt_data;
6618         int                     rc;
6619         ENTRY;
6620
6621         INIT_LIST_HEAD(&med->med_open_head);
6622         spin_lock_init(&med->med_open_lock);
6623         spin_lock(&exp->exp_lock);
6624         exp->exp_connecting = 1;
6625         spin_unlock(&exp->exp_lock);
6626
6627         OBD_ALLOC(exp->exp_used_slots,
6628                   BITS_TO_LONGS(OBD_MAX_RIF_MAX) * sizeof(long));
6629         if (exp->exp_used_slots == NULL)
6630                 RETURN(-ENOMEM);
6631
6632         /* self-export doesn't need client data and ldlm initialization */
6633         if (unlikely(obd_uuid_equals(&exp->exp_obd->obd_uuid,
6634                                      &exp->exp_client_uuid)))
6635                 RETURN(0);
6636
6637         rc = tgt_client_alloc(exp);
6638         if (rc)
6639                 GOTO(err, rc);
6640
6641         rc = ldlm_init_export(exp);
6642         if (rc)
6643                 GOTO(err_free, rc);
6644
6645         RETURN(rc);
6646
6647 err_free:
6648         tgt_client_free(exp);
6649 err:
6650         OBD_FREE(exp->exp_used_slots,
6651                  BITS_TO_LONGS(OBD_MAX_RIF_MAX) * sizeof(long));
6652         exp->exp_used_slots = NULL;
6653
6654         CERROR("%s: Failed to initialize export: rc = %d\n",
6655                exp->exp_obd->obd_name, rc);
6656         return rc;
6657 }
6658
6659 static int mdt_destroy_export(struct obd_export *exp)
6660 {
6661         ENTRY;
6662
6663         target_destroy_export(exp);
6664         if (exp->exp_used_slots)
6665                 OBD_FREE(exp->exp_used_slots,
6666                          BITS_TO_LONGS(OBD_MAX_RIF_MAX) * sizeof(long));
6667
6668         /* destroy can be called from failed obd_setup, so
6669          * checking uuid is safer than obd_self_export */
6670         if (unlikely(obd_uuid_equals(&exp->exp_obd->obd_uuid,
6671                                      &exp->exp_client_uuid)))
6672                 RETURN(0);
6673
6674         ldlm_destroy_export(exp);
6675         tgt_client_free(exp);
6676
6677         LASSERT(list_empty(&exp->exp_outstanding_replies));
6678         LASSERT(list_empty(&exp->exp_mdt_data.med_open_head));
6679
6680         /*
6681          * discard grants once we're sure no more
6682          * interaction with the client is possible
6683          */
6684         tgt_grant_discard(exp);
6685         if (exp_connect_flags(exp) & OBD_CONNECT_GRANT)
6686                 exp->exp_obd->u.obt.obt_lut->lut_tgd.tgd_tot_granted_clients--;
6687
6688         if (!(exp->exp_flags & OBD_OPT_FORCE))
6689                 tgt_grant_sanity_check(exp->exp_obd, __func__);
6690
6691         RETURN(0);
6692 }
6693
6694 int mdt_links_read(struct mdt_thread_info *info, struct mdt_object *mdt_obj,
6695                    struct linkea_data *ldata)
6696 {
6697         int rc;
6698
6699         LASSERT(ldata->ld_buf->lb_buf != NULL);
6700
6701         if (!mdt_object_exists(mdt_obj))
6702                 return -ENODATA;
6703
6704         rc = mo_xattr_get(info->mti_env, mdt_object_child(mdt_obj),
6705                           ldata->ld_buf, XATTR_NAME_LINK);
6706         if (rc == -ERANGE) {
6707                 /* Buf was too small, figure out what we need. */
6708                 lu_buf_free(ldata->ld_buf);
6709                 rc = mo_xattr_get(info->mti_env, mdt_object_child(mdt_obj),
6710                                   ldata->ld_buf, XATTR_NAME_LINK);
6711                 if (rc < 0)
6712                         return rc;
6713                 ldata->ld_buf = lu_buf_check_and_alloc(ldata->ld_buf, rc);
6714                 if (ldata->ld_buf->lb_buf == NULL)
6715                         return -ENOMEM;
6716                 rc = mo_xattr_get(info->mti_env, mdt_object_child(mdt_obj),
6717                                   ldata->ld_buf, XATTR_NAME_LINK);
6718         }
6719         if (rc < 0)
6720                 return rc;
6721
6722         return linkea_init_with_rec(ldata);
6723 }
6724
6725 /**
6726  * Given an MDT object, try to look up the full path to the object.
6727  * Part of the MDT layer implementation of lfs fid2path.
6728  *
6729  * \param[in]     info  Per-thread common data shared by MDT level handlers.
6730  * \param[in]     obj   Object to do path lookup of
6731  * \param[in,out] fp    User-provided struct to store path information
6732  * \param[in]     root_fid Root FID of current path should reach
6733  *
6734  * \retval 0 Lookup successful, path information stored in fp
6735  * \retval -EAGAIN Lookup failed, usually because object is being moved
6736  * \retval negative errno if there was a problem
6737  */
6738 static int mdt_path_current(struct mdt_thread_info *info,
6739                             struct mdt_object *obj,
6740                             struct getinfo_fid2path *fp,
6741                             struct lu_fid *root_fid)
6742 {
6743         struct mdt_device *mdt = info->mti_mdt;
6744         struct lu_name *tmpname = &info->mti_name;
6745         struct lu_fid *tmpfid = &info->mti_tmp_fid1;
6746         struct lu_buf *buf = &info->mti_big_buf;
6747         struct md_attr *ma = &info->mti_attr;
6748         struct linkea_data ldata = { NULL };
6749         bool first = true;
6750         struct mdt_object *mdt_obj;
6751         struct link_ea_header *leh;
6752         struct link_ea_entry *lee;
6753         char *ptr;
6754         int reclen;
6755         int rc = 0;
6756
6757         ENTRY;
6758
6759         /* temp buffer for path element, the buffer will be finally freed
6760          * in mdt_thread_info_fini */
6761         buf = lu_buf_check_and_alloc(buf, PATH_MAX);
6762         if (buf->lb_buf == NULL)
6763                 RETURN(-ENOMEM);
6764
6765         ldata.ld_buf = buf;
6766         ptr = fp->gf_u.gf_path + fp->gf_pathlen - 1;
6767         *ptr = 0;
6768         --ptr;
6769         *tmpfid = fp->gf_fid = *mdt_object_fid(obj);
6770
6771         while (!lu_fid_eq(root_fid, &fp->gf_fid)) {
6772                 if (!lu_fid_eq(root_fid, &mdt->mdt_md_root_fid) &&
6773                     lu_fid_eq(&mdt->mdt_md_root_fid, &fp->gf_fid))
6774                         GOTO(out, rc = -ENOENT);
6775
6776                 if (lu_fid_eq(mdt_object_fid(obj), tmpfid)) {
6777                         mdt_obj = obj;
6778                         mdt_object_get(info->mti_env, mdt_obj);
6779                 } else {
6780                         mdt_obj = mdt_object_find(info->mti_env, mdt, tmpfid);
6781                         if (IS_ERR(mdt_obj))
6782                                 GOTO(out, rc = PTR_ERR(mdt_obj));
6783                 }
6784
6785                 if (!mdt_object_exists(mdt_obj)) {
6786                         mdt_object_put(info->mti_env, mdt_obj);
6787                         GOTO(out, rc = -ENOENT);
6788                 }
6789
6790                 if (mdt_object_remote(mdt_obj)) {
6791                         mdt_object_put(info->mti_env, mdt_obj);
6792                         GOTO(remote_out, rc = -EREMOTE);
6793                 }
6794
6795                 rc = mdt_links_read(info, mdt_obj, &ldata);
6796                 if (rc != 0) {
6797                         mdt_object_put(info->mti_env, mdt_obj);
6798                         GOTO(out, rc);
6799                 }
6800
6801                 leh = buf->lb_buf;
6802                 lee = (struct link_ea_entry *)(leh + 1); /* link #0 */
6803                 linkea_entry_unpack(lee, &reclen, tmpname, tmpfid);
6804                 /* If set, use link #linkno for path lookup, otherwise use
6805                    link #0.  Only do this for the final path element. */
6806                 if (first && fp->gf_linkno < leh->leh_reccount) {
6807                         int count;
6808                         for (count = 0; count < fp->gf_linkno; count++) {
6809                                 lee = (struct link_ea_entry *)
6810                                      ((char *)lee + reclen);
6811                                 linkea_entry_unpack(lee, &reclen, tmpname,
6812                                                     tmpfid);
6813                         }
6814                         if (fp->gf_linkno < leh->leh_reccount - 1)
6815                                 /* indicate to user there are more links */
6816                                 fp->gf_linkno++;
6817                 }
6818
6819                 /* Check if it is slave stripes */
6820                 rc = mdt_stripe_get(info, mdt_obj, ma, XATTR_NAME_LMV);
6821                 mdt_object_put(info->mti_env, mdt_obj);
6822                 if (rc < 0)
6823                         GOTO(out, rc);
6824
6825                 if (ma->ma_valid & MA_LMV) {
6826                         struct lmv_mds_md_v1 *lmv = &ma->ma_lmv->lmv_md_v1;
6827
6828                         if (!lmv_is_sane2(lmv))
6829                                 GOTO(out, rc = -EBADF);
6830
6831                         /* For slave stripes, get its master */
6832                         if (le32_to_cpu(lmv->lmv_magic) == LMV_MAGIC_STRIPE) {
6833                                 fp->gf_fid = *tmpfid;
6834                                 continue;
6835                         }
6836                 }
6837
6838                 /* Pack the name in the end of the buffer */
6839                 ptr -= tmpname->ln_namelen;
6840                 if (ptr - 1 <= fp->gf_u.gf_path)
6841                         GOTO(out, rc = -EOVERFLOW);
6842                 strncpy(ptr, tmpname->ln_name, tmpname->ln_namelen);
6843                 *(--ptr) = '/';
6844
6845                 /* keep the last resolved fid to the client, so the
6846                  * client will build the left path on another MDT for
6847                  * remote object */
6848                 fp->gf_fid = *tmpfid;
6849
6850                 first = false;
6851         }
6852
6853         /* non-zero will be treated as an error */
6854         rc = 0;
6855
6856 remote_out:
6857         ptr++; /* skip leading / */
6858         memmove(fp->gf_u.gf_path, ptr,
6859                 fp->gf_u.gf_path + fp->gf_pathlen - ptr);
6860
6861 out:
6862         RETURN(rc);
6863 }
6864
6865 /**
6866  * Given an MDT object, use mdt_path_current to get the path.
6867  * Essentially a wrapper to retry mdt_path_current a set number of times
6868  * if -EAGAIN is returned (usually because an object is being moved).
6869  *
6870  * Part of the MDT layer implementation of lfs fid2path.
6871  *
6872  * \param[in]     info  Per-thread common data shared by mdt level handlers.
6873  * \param[in]     obj   Object to do path lookup of
6874  * \param[in,out] fp    User-provided struct for arguments and to store path
6875  *                      information
6876  *
6877  * \retval 0 Lookup successful, path information stored in fp
6878  * \retval negative errno if there was a problem
6879  */
6880 static int mdt_path(struct mdt_thread_info *info, struct mdt_object *obj,
6881                     struct getinfo_fid2path *fp, struct lu_fid *root_fid)
6882 {
6883         struct mdt_device       *mdt = info->mti_mdt;
6884         int                     tries = 3;
6885         int                     rc = -EAGAIN;
6886         ENTRY;
6887
6888         if (fp->gf_pathlen < 3)
6889                 RETURN(-EOVERFLOW);
6890
6891         if (root_fid == NULL)
6892                 root_fid = &mdt->mdt_md_root_fid;
6893
6894         if (lu_fid_eq(root_fid, mdt_object_fid(obj))) {
6895                 fp->gf_u.gf_path[0] = '\0';
6896                 RETURN(0);
6897         }
6898
6899         /* Retry multiple times in case file is being moved */
6900         while (tries-- && rc == -EAGAIN)
6901                 rc = mdt_path_current(info, obj, fp, root_fid);
6902
6903         RETURN(rc);
6904 }
6905
6906 /**
6907  * Get the full path of the provided FID, as of changelog record recno.
6908  *
6909  * This checks sanity and looks up object for user provided FID
6910  * before calling the actual path lookup code.
6911  *
6912  * Part of the MDT layer implementation of lfs fid2path.
6913  *
6914  * \param[in]     info  Per-thread common data shared by mdt level handlers.
6915  * \param[in,out] fp    User-provided struct for arguments and to store path
6916  *                      information
6917  *
6918  * \retval 0 Lookup successful, path information and recno stored in fp
6919  * \retval -ENOENT, object does not exist
6920  * \retval negative errno if there was a problem
6921  */
6922 static int mdt_fid2path(struct mdt_thread_info *info,
6923                         struct lu_fid *root_fid,
6924                         struct getinfo_fid2path *fp)
6925 {
6926         struct mdt_device *mdt = info->mti_mdt;
6927         struct mdt_object *obj;
6928         int    rc;
6929         ENTRY;
6930
6931         CDEBUG(D_IOCTL, "path get "DFID" from %llu #%d\n",
6932                 PFID(&fp->gf_fid), fp->gf_recno, fp->gf_linkno);
6933
6934         if (!fid_is_sane(&fp->gf_fid))
6935                 RETURN(-EINVAL);
6936
6937         if (!fid_is_namespace_visible(&fp->gf_fid)) {
6938                 CDEBUG(D_INFO, "%s: "DFID" is invalid, f_seq should be >= %#llx"
6939                        ", or f_oid != 0, or f_ver == 0\n", mdt_obd_name(mdt),
6940                        PFID(&fp->gf_fid), (__u64)FID_SEQ_NORMAL);
6941                 RETURN(-EINVAL);
6942         }
6943
6944         obj = mdt_object_find(info->mti_env, mdt, &fp->gf_fid);
6945         if (IS_ERR(obj)) {
6946                 rc = PTR_ERR(obj);
6947                 CDEBUG(D_IOCTL, "cannot find "DFID": rc = %d\n",
6948                        PFID(&fp->gf_fid), rc);
6949                 RETURN(rc);
6950         }
6951
6952         if (mdt_object_remote(obj))
6953                 rc = -EREMOTE;
6954         else if (!mdt_object_exists(obj))
6955                 rc = -ENOENT;
6956         else
6957                 rc = 0;
6958
6959         if (rc < 0) {
6960                 mdt_object_put(info->mti_env, obj);
6961                 CDEBUG(D_IOCTL, "nonlocal object "DFID": rc = %d\n",
6962                        PFID(&fp->gf_fid), rc);
6963                 RETURN(rc);
6964         }
6965
6966         rc = mdt_path(info, obj, fp, root_fid);
6967
6968         CDEBUG(D_INFO, "fid "DFID", path %s recno %#llx linkno %u\n",
6969                PFID(&fp->gf_fid), fp->gf_u.gf_path,
6970                fp->gf_recno, fp->gf_linkno);
6971
6972         mdt_object_put(info->mti_env, obj);
6973
6974         RETURN(rc);
6975 }
6976
6977 static int mdt_rpc_fid2path(struct mdt_thread_info *info, void *key, int keylen,
6978                             void *val, int vallen)
6979 {
6980         struct getinfo_fid2path *fpout, *fpin;
6981         struct lu_fid *root_fid = NULL;
6982         int rc = 0;
6983
6984         fpin = key + cfs_size_round(sizeof(KEY_FID2PATH));
6985         fpout = val;
6986
6987         if (ptlrpc_req_need_swab(info->mti_pill->rc_req))
6988                 lustre_swab_fid2path(fpin);
6989
6990         memcpy(fpout, fpin, sizeof(*fpin));
6991         if (fpout->gf_pathlen != vallen - sizeof(*fpin))
6992                 RETURN(-EINVAL);
6993
6994         if (keylen >= cfs_size_round(sizeof(KEY_FID2PATH)) + sizeof(*fpin) +
6995                       sizeof(struct lu_fid)) {
6996                 /* client sent its root FID, which is normally fileset FID */
6997                 root_fid = fpin->gf_u.gf_root_fid;
6998                 if (ptlrpc_req_need_swab(info->mti_pill->rc_req))
6999                         lustre_swab_lu_fid(root_fid);
7000
7001                 if (root_fid != NULL && !fid_is_sane(root_fid))
7002                         RETURN(-EINVAL);
7003         }
7004
7005         rc = mdt_fid2path(info, root_fid, fpout);
7006         RETURN(rc);
7007 }
7008
7009 int mdt_get_info(struct tgt_session_info *tsi)
7010 {
7011         char    *key;
7012         int      keylen;
7013         __u32   *vallen;
7014         void    *valout;
7015         int      rc;
7016
7017         ENTRY;
7018
7019         key = req_capsule_client_get(tsi->tsi_pill, &RMF_GETINFO_KEY);
7020         if (key == NULL) {
7021                 CDEBUG(D_IOCTL, "No GETINFO key\n");
7022                 RETURN(err_serious(-EFAULT));
7023         }
7024         keylen = req_capsule_get_size(tsi->tsi_pill, &RMF_GETINFO_KEY,
7025                                       RCL_CLIENT);
7026
7027         vallen = req_capsule_client_get(tsi->tsi_pill, &RMF_GETINFO_VALLEN);
7028         if (vallen == NULL) {
7029                 CDEBUG(D_IOCTL, "%s: cannot get RMF_GETINFO_VALLEN buffer\n",
7030                                 tgt_name(tsi->tsi_tgt));
7031                 RETURN(err_serious(-EFAULT));
7032         }
7033
7034         req_capsule_set_size(tsi->tsi_pill, &RMF_GETINFO_VAL, RCL_SERVER,
7035                              *vallen);
7036         rc = req_capsule_server_pack(tsi->tsi_pill);
7037         if (rc)
7038                 RETURN(err_serious(rc));
7039
7040         valout = req_capsule_server_get(tsi->tsi_pill, &RMF_GETINFO_VAL);
7041         if (valout == NULL) {
7042                 CDEBUG(D_IOCTL, "%s: cannot get get-info RPC out buffer\n",
7043                                 tgt_name(tsi->tsi_tgt));
7044                 RETURN(err_serious(-EFAULT));
7045         }
7046
7047         if (KEY_IS(KEY_FID2PATH)) {
7048                 struct mdt_thread_info  *info = tsi2mdt_info(tsi);
7049
7050                 rc = mdt_rpc_fid2path(info, key, keylen, valout, *vallen);
7051                 mdt_thread_info_fini(info);
7052         } else {
7053                 rc = -EINVAL;
7054         }
7055         RETURN(rc);
7056 }
7057
7058 static int mdt_ioc_version_get(struct mdt_thread_info *mti, void *karg)
7059 {
7060         struct obd_ioctl_data *data = karg;
7061         struct lu_fid *fid;
7062         __u64 version;
7063         struct mdt_object *obj;
7064         struct mdt_lock_handle  *lh;
7065         int rc;
7066         ENTRY;
7067
7068         if (data->ioc_inlbuf1 == NULL || data->ioc_inllen1 != sizeof(*fid) ||
7069             data->ioc_inlbuf2 == NULL || data->ioc_inllen2 != sizeof(version))
7070                 RETURN(-EINVAL);
7071
7072         fid = (struct lu_fid *)data->ioc_inlbuf1;
7073
7074         if (!fid_is_sane(fid))
7075                 RETURN(-EINVAL);
7076
7077         CDEBUG(D_IOCTL, "getting version for "DFID"\n", PFID(fid));
7078
7079         lh = &mti->mti_lh[MDT_LH_PARENT];
7080         mdt_lock_reg_init(lh, LCK_CR);
7081
7082         obj = mdt_object_find_lock(mti, fid, lh, MDS_INODELOCK_UPDATE);
7083         if (IS_ERR(obj))
7084                 RETURN(PTR_ERR(obj));
7085
7086         if (mdt_object_remote(obj)) {
7087                 rc = -EREMOTE;
7088                 /**
7089                  * before calling version get the correct MDS should be
7090                  * fid, this is error to find remote object here
7091                  */
7092                 CERROR("nonlocal object "DFID"\n", PFID(fid));
7093         } else if (!mdt_object_exists(obj)) {
7094                 *(__u64 *)data->ioc_inlbuf2 = ENOENT_VERSION;
7095                 rc = -ENOENT;
7096         } else {
7097                 version = dt_version_get(mti->mti_env, mdt_obj2dt(obj));
7098                *(__u64 *)data->ioc_inlbuf2 = version;
7099                 rc = 0;
7100         }
7101         mdt_object_unlock_put(mti, obj, lh, 1);
7102         RETURN(rc);
7103 }
7104
7105 /* ioctls on obd dev */
7106 static int mdt_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
7107                          void *karg, void __user *uarg)
7108 {
7109         struct lu_env      env;
7110         struct obd_device *obd = exp->exp_obd;
7111         struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
7112         struct dt_device  *dt = mdt->mdt_bottom;
7113         int rc;
7114
7115         ENTRY;
7116         CDEBUG(D_IOCTL, "handling ioctl cmd %#x\n", cmd);
7117         rc = lu_env_init(&env, LCT_MD_THREAD);
7118         if (rc)
7119                 RETURN(rc);
7120
7121         switch (cmd) {
7122         case OBD_IOC_SYNC:
7123                 rc = mdt_device_sync(&env, mdt);
7124                 break;
7125         case OBD_IOC_SET_READONLY:
7126                 rc = dt_sync(&env, dt);
7127                 if (rc == 0)
7128                         rc = dt_ro(&env, dt);
7129                 break;
7130         case OBD_IOC_ABORT_RECOVERY: {
7131                 struct obd_ioctl_data *data = karg;
7132
7133                 CERROR("%s: Aborting recovery for device\n", mdt_obd_name(mdt));
7134                 if (data->ioc_type & OBD_FLG_ABORT_RECOV_MDT)
7135                         obd->obd_abort_recov_mdt = 1;
7136                 else /* if (data->ioc_type & OBD_FLG_ABORT_RECOV_OST) */
7137                         /* lctl didn't set OBD_FLG_ABORT_RECOV_OST < 2.13.57 */
7138                         obd->obd_abort_recovery = 1;
7139
7140                 target_stop_recovery_thread(obd);
7141                 rc = 0;
7142                 break;
7143         }
7144         case OBD_IOC_CHANGELOG_REG:
7145         case OBD_IOC_CHANGELOG_DEREG:
7146         case OBD_IOC_CHANGELOG_CLEAR:
7147                 rc = mdt->mdt_child->md_ops->mdo_iocontrol(&env,
7148                                                            mdt->mdt_child,
7149                                                            cmd, len, karg);
7150                 break;
7151         case OBD_IOC_START_LFSCK: {
7152                 struct md_device *next = mdt->mdt_child;
7153                 struct obd_ioctl_data *data = karg;
7154                 struct lfsck_start_param lsp;
7155
7156                 if (unlikely(data == NULL)) {
7157                         rc = -EINVAL;
7158                         break;
7159                 }
7160
7161                 lsp.lsp_start = (struct lfsck_start *)(data->ioc_inlbuf1);
7162                 lsp.lsp_index_valid = 0;
7163                 rc = next->md_ops->mdo_iocontrol(&env, next, cmd, 0, &lsp);
7164                 break;
7165         }
7166         case OBD_IOC_STOP_LFSCK: {
7167                 struct md_device        *next = mdt->mdt_child;
7168                 struct obd_ioctl_data   *data = karg;
7169                 struct lfsck_stop        stop;
7170
7171                 stop.ls_status = LS_STOPPED;
7172                 /* Old lfsck utils may pass NULL @stop. */
7173                 if (data->ioc_inlbuf1 == NULL)
7174                         stop.ls_flags = 0;
7175                 else
7176                         stop.ls_flags =
7177                         ((struct lfsck_stop *)(data->ioc_inlbuf1))->ls_flags;
7178
7179                 rc = next->md_ops->mdo_iocontrol(&env, next, cmd, 0, &stop);
7180                 break;
7181         }
7182         case OBD_IOC_QUERY_LFSCK: {
7183                 struct md_device        *next = mdt->mdt_child;
7184                 struct obd_ioctl_data   *data = karg;
7185
7186                 rc = next->md_ops->mdo_iocontrol(&env, next, cmd, 0,
7187                                                  data->ioc_inlbuf1);
7188                 break;
7189         }
7190         case OBD_IOC_GET_OBJ_VERSION: {
7191                 struct mdt_thread_info *mti;
7192                 mti = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
7193                 memset(mti, 0, sizeof *mti);
7194                 mti->mti_env = &env;
7195                 mti->mti_mdt = mdt;
7196                 mti->mti_exp = exp;
7197
7198                 rc = mdt_ioc_version_get(mti, karg);
7199                 break;
7200         }
7201         case OBD_IOC_CATLOGLIST: {
7202                 struct mdt_thread_info *mti;
7203
7204                 mti = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
7205                 lu_local_obj_fid(&mti->mti_tmp_fid1, LLOG_CATALOGS_OID);
7206                 rc = llog_catalog_list(&env, mdt->mdt_bottom, 0, karg,
7207                                        &mti->mti_tmp_fid1);
7208                 break;
7209          }
7210         default:
7211                 rc = -EOPNOTSUPP;
7212                 CERROR("%s: Not supported cmd = %d, rc = %d\n",
7213                         mdt_obd_name(mdt), cmd, rc);
7214         }
7215
7216         lu_env_fini(&env);
7217         RETURN(rc);
7218 }
7219
7220 static int mdt_postrecov(const struct lu_env *env, struct mdt_device *mdt)
7221 {
7222         struct lu_device *ld = md2lu_dev(mdt->mdt_child);
7223         int rc;
7224         ENTRY;
7225
7226         if (!mdt->mdt_skip_lfsck && !mdt->mdt_bottom->dd_rdonly) {
7227                 struct lfsck_start_param lsp;
7228
7229                 lsp.lsp_start = NULL;
7230                 lsp.lsp_index_valid = 0;
7231                 rc = mdt->mdt_child->md_ops->mdo_iocontrol(env, mdt->mdt_child,
7232                                                            OBD_IOC_START_LFSCK,
7233                                                            0, &lsp);
7234                 if (rc != 0 && rc != -EALREADY)
7235                         CWARN("%s: auto trigger paused LFSCK failed: rc = %d\n",
7236                               mdt_obd_name(mdt), rc);
7237         }
7238
7239         rc = ld->ld_ops->ldo_recovery_complete(env, ld);
7240         RETURN(rc);
7241 }
7242
7243 static int mdt_obd_postrecov(struct obd_device *obd)
7244 {
7245         struct lu_env env;
7246         int rc;
7247
7248         rc = lu_env_init(&env, LCT_MD_THREAD);
7249         if (rc)
7250                 RETURN(rc);
7251         rc = mdt_postrecov(&env, mdt_dev(obd->obd_lu_dev));
7252         lu_env_fini(&env);
7253         return rc;
7254 }
7255
7256 static const struct obd_ops mdt_obd_device_ops = {
7257         .o_owner          = THIS_MODULE,
7258         .o_set_info_async = mdt_obd_set_info_async,
7259         .o_connect        = mdt_obd_connect,
7260         .o_reconnect      = mdt_obd_reconnect,
7261         .o_disconnect     = mdt_obd_disconnect,
7262         .o_init_export    = mdt_init_export,
7263         .o_destroy_export = mdt_destroy_export,
7264         .o_iocontrol      = mdt_iocontrol,
7265         .o_postrecov      = mdt_obd_postrecov,
7266         /* Data-on-MDT IO methods */
7267         .o_preprw         = mdt_obd_preprw,
7268         .o_commitrw       = mdt_obd_commitrw,
7269 };
7270
7271 static struct lu_device* mdt_device_fini(const struct lu_env *env,
7272                                          struct lu_device *d)
7273 {
7274         struct mdt_device *m = mdt_dev(d);
7275         ENTRY;
7276
7277         mdt_fini(env, m);
7278         RETURN(NULL);
7279 }
7280
7281 static struct lu_device *mdt_device_free(const struct lu_env *env,
7282                                          struct lu_device *d)
7283 {
7284         struct mdt_device *m = mdt_dev(d);
7285         ENTRY;
7286
7287         lu_device_fini(&m->mdt_lu_dev);
7288         OBD_FREE_PTR(m);
7289
7290         RETURN(NULL);
7291 }
7292
7293 static struct lu_device *mdt_device_alloc(const struct lu_env *env,
7294                                           struct lu_device_type *t,
7295                                           struct lustre_cfg *cfg)
7296 {
7297         struct lu_device  *l;
7298         struct mdt_device *m;
7299
7300         OBD_ALLOC_PTR(m);
7301         if (m != NULL) {
7302                 int rc;
7303
7304                 l = &m->mdt_lu_dev;
7305                 rc = mdt_init0(env, m, t, cfg);
7306                 if (rc != 0) {
7307                         mdt_device_free(env, l);
7308                         l = ERR_PTR(rc);
7309                         return l;
7310                 }
7311         } else
7312                 l = ERR_PTR(-ENOMEM);
7313         return l;
7314 }
7315
7316 /* context key constructor/destructor: mdt_key_init, mdt_key_fini */
7317 LU_KEY_INIT(mdt, struct mdt_thread_info);
7318
7319 static void mdt_key_fini(const struct lu_context *ctx,
7320                          struct lu_context_key *key, void* data)
7321 {
7322         struct mdt_thread_info *info = data;
7323
7324         if (info->mti_big_lmm) {
7325                 OBD_FREE_LARGE(info->mti_big_lmm, info->mti_big_lmmsize);
7326                 info->mti_big_lmm = NULL;
7327                 info->mti_big_lmmsize = 0;
7328         }
7329
7330         if (info->mti_big_acl) {
7331                 OBD_FREE_LARGE(info->mti_big_acl, info->mti_big_aclsize);
7332                 info->mti_big_acl = NULL;
7333                 info->mti_big_aclsize = 0;
7334         }
7335
7336         OBD_FREE_PTR(info);
7337 }
7338
7339 /* context key: mdt_thread_key */
7340 LU_CONTEXT_KEY_DEFINE(mdt, LCT_MD_THREAD);
7341
7342 struct lu_ucred *mdt_ucred(const struct mdt_thread_info *info)
7343 {
7344         return lu_ucred(info->mti_env);
7345 }
7346
7347 struct lu_ucred *mdt_ucred_check(const struct mdt_thread_info *info)
7348 {
7349         return lu_ucred_check(info->mti_env);
7350 }
7351
7352 /**
7353  * Enable/disable COS (Commit On Sharing).
7354  *
7355  * Set/Clear the COS flag in mdt options.
7356  *
7357  * \param mdt mdt device
7358  * \param val 0 disables COS, other values enable COS
7359  */
7360 void mdt_enable_cos(struct mdt_device *mdt, bool val)
7361 {
7362         struct lu_env env;
7363         int rc;
7364
7365         mdt->mdt_opts.mo_cos = val;
7366         rc = lu_env_init(&env, LCT_LOCAL);
7367         if (unlikely(rc != 0)) {
7368                 CWARN("%s: lu_env initialization failed, cannot "
7369                       "sync: rc = %d\n", mdt_obd_name(mdt), rc);
7370                 return;
7371         }
7372         mdt_device_sync(&env, mdt);
7373         lu_env_fini(&env);
7374 }
7375
7376 /**
7377  * Check COS (Commit On Sharing) status.
7378  *
7379  * Return COS flag status.
7380  *
7381  * \param mdt mdt device
7382  */
7383 int mdt_cos_is_enabled(struct mdt_device *mdt)
7384 {
7385         return mdt->mdt_opts.mo_cos != 0;
7386 }
7387
7388 static const struct lu_device_type_operations mdt_device_type_ops = {
7389         .ldto_device_alloc = mdt_device_alloc,
7390         .ldto_device_free  = mdt_device_free,
7391         .ldto_device_fini  = mdt_device_fini
7392 };
7393
7394 static struct lu_device_type mdt_device_type = {
7395         .ldt_tags     = LU_DEVICE_MD,
7396         .ldt_name     = LUSTRE_MDT_NAME,
7397         .ldt_ops      = &mdt_device_type_ops,
7398         .ldt_ctx_tags = LCT_MD_THREAD
7399 };
7400
7401 static int __init mdt_init(void)
7402 {
7403         int rc;
7404
7405         BUILD_BUG_ON(sizeof("0x0123456789ABCDEF:0x01234567:0x01234567") !=
7406                      FID_NOBRACE_LEN + 1);
7407         BUILD_BUG_ON(sizeof("[0x0123456789ABCDEF:0x01234567:0x01234567]") !=
7408                      FID_LEN + 1);
7409         rc = lu_kmem_init(mdt_caches);
7410         if (rc)
7411                 return rc;
7412
7413         rc = mds_mod_init();
7414         if (rc)
7415                 GOTO(lu_fini, rc);
7416
7417         rc = class_register_type(&mdt_obd_device_ops, NULL, true,
7418                                  LUSTRE_MDT_NAME, &mdt_device_type);
7419         if (rc)
7420                 GOTO(mds_fini, rc);
7421 lu_fini:
7422         if (rc)
7423                 lu_kmem_fini(mdt_caches);
7424 mds_fini:
7425         if (rc)
7426                 mds_mod_exit();
7427         return rc;
7428 }
7429
7430 static void __exit mdt_exit(void)
7431 {
7432         class_unregister_type(LUSTRE_MDT_NAME);
7433         mds_mod_exit();
7434         lu_kmem_fini(mdt_caches);
7435 }
7436
7437 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
7438 MODULE_DESCRIPTION("Lustre Metadata Target ("LUSTRE_MDT_NAME")");
7439 MODULE_VERSION(LUSTRE_VERSION_STRING);
7440 MODULE_LICENSE("GPL");
7441
7442 module_init(mdt_init);
7443 module_exit(mdt_exit);