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