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