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