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