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