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