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