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