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