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