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