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