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