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