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