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