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