Whamcloud - gitweb
LU-5216 hsm: cancel hsm actions running on CT when killed
[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, 2016, 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         if (mdt_object_remote(o)) {
2817                 LASSERT(*ibits == MDS_INODELOCK_LOOKUP);
2818         }
2819
2820         if (lh->mlh_type == MDT_PDO_LOCK) {
2821                 /* check for exists after object is locked */
2822                 if (mdt_object_exists(o) == 0) {
2823                         /* Non-existent object shouldn't have PDO lock */
2824                         RETURN(-ESTALE);
2825                 } else {
2826                         /* Non-dir object shouldn't have PDO lock */
2827                         if (!S_ISDIR(lu_object_attr(&o->mot_obj)))
2828                                 RETURN(-ENOTDIR);
2829                 }
2830         }
2831
2832
2833         fid_build_reg_res_name(mdt_object_fid(o), res_id);
2834         dlmflags |= LDLM_FL_ATOMIC_CB;
2835
2836         /*
2837          * Take PDO lock on whole directory and build correct @res_id for lock
2838          * on part of directory.
2839          */
2840         if (lh->mlh_pdo_hash != 0) {
2841                 LASSERT(lh->mlh_type == MDT_PDO_LOCK);
2842                 mdt_lock_pdo_mode(info, o, lh);
2843                 if (lh->mlh_pdo_mode != LCK_NL) {
2844                         /*
2845                          * Do not use LDLM_FL_LOCAL_ONLY for parallel lock, it
2846                          * is never going to be sent to client and we do not
2847                          * want it slowed down due to possible cancels.
2848                          */
2849                         policy->l_inodebits.bits = MDS_INODELOCK_UPDATE;
2850                         policy->l_inodebits.try_bits = 0;
2851                         rc = mdt_fid_lock(ns, &lh->mlh_pdo_lh, lh->mlh_pdo_mode,
2852                                           policy, res_id, dlmflags,
2853                                           info->mti_exp == NULL ? NULL :
2854                                           &info->mti_exp->exp_handle.h_cookie);
2855                         if (unlikely(rc != 0))
2856                                 GOTO(out_unlock, rc);
2857                 }
2858
2859                 /*
2860                  * Finish res_id initializing by name hash marking part of
2861                  * directory which is taking modification.
2862                  */
2863                 res_id->name[LUSTRE_RES_ID_HSH_OFF] = lh->mlh_pdo_hash;
2864         }
2865
2866         policy->l_inodebits.bits = *ibits;
2867         policy->l_inodebits.try_bits = trybits;
2868
2869         /*
2870          * Use LDLM_FL_LOCAL_ONLY for this lock. We do not know yet if it is
2871          * going to be sent to client. If it is - mdt_intent_policy() path will
2872          * fix it up and turn FL_LOCAL flag off.
2873          */
2874         rc = mdt_fid_lock(ns, &lh->mlh_reg_lh, lh->mlh_reg_mode, policy,
2875                           res_id, LDLM_FL_LOCAL_ONLY | dlmflags,
2876                           info->mti_exp == NULL ? NULL :
2877                           &info->mti_exp->exp_handle.h_cookie);
2878 out_unlock:
2879         if (rc != 0)
2880                 mdt_object_unlock(info, o, lh, 1);
2881         else if (unlikely(OBD_FAIL_PRECHECK(OBD_FAIL_MDS_PDO_LOCK)) &&
2882                    lh->mlh_pdo_hash != 0 &&
2883                    (lh->mlh_reg_mode == LCK_PW || lh->mlh_reg_mode == LCK_EX))
2884                 OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_PDO_LOCK, 15);
2885
2886         /* Return successfully acquired bits to a caller */
2887         if (rc == 0) {
2888                 struct ldlm_lock *lock = ldlm_handle2lock(&lh->mlh_reg_lh);
2889
2890                 LASSERT(lock);
2891                 *ibits = lock->l_policy_data.l_inodebits.bits;
2892                 LDLM_LOCK_PUT(lock);
2893         }
2894         RETURN(rc);
2895 }
2896
2897 static int
2898 mdt_object_lock_internal(struct mdt_thread_info *info, struct mdt_object *o,
2899                          struct mdt_lock_handle *lh, __u64 *ibits,
2900                          __u64 trybits, bool cos_incompat)
2901 {
2902         struct mdt_lock_handle *local_lh = NULL;
2903         int rc;
2904         ENTRY;
2905
2906         if (!mdt_object_remote(o)) {
2907                 rc = mdt_object_local_lock(info, o, lh, ibits, trybits,
2908                                            cos_incompat);
2909                 RETURN(rc);
2910         }
2911
2912         /* XXX do not support PERM/LAYOUT/XATTR lock for remote object yet */
2913         *ibits &= ~(MDS_INODELOCK_PERM | MDS_INODELOCK_LAYOUT |
2914                     MDS_INODELOCK_XATTR);
2915
2916         /* Only enqueue LOOKUP lock for remote object */
2917         if (*ibits & MDS_INODELOCK_LOOKUP) {
2918                 __u64 local = MDS_INODELOCK_LOOKUP;
2919
2920                 rc = mdt_object_local_lock(info, o, lh, &local, 0,
2921                                            cos_incompat);
2922                 if (rc != ELDLM_OK)
2923                         RETURN(rc);
2924
2925                 local_lh = lh;
2926         }
2927
2928         if ((*ibits | trybits) & MDS_INODELOCK_UPDATE) {
2929                 /* Sigh, PDO needs to enqueue 2 locks right now, but
2930                  * enqueue RPC can only request 1 lock, to avoid extra
2931                  * RPC, so it will instead enqueue EX lock for remote
2932                  * object anyway XXX*/
2933                 if (lh->mlh_type == MDT_PDO_LOCK &&
2934                     lh->mlh_pdo_hash != 0) {
2935                         CDEBUG(D_INFO, "%s: "DFID" convert PDO lock to"
2936                                "EX lock.\n", mdt_obd_name(info->mti_mdt),
2937                                PFID(mdt_object_fid(o)));
2938                         lh->mlh_pdo_hash = 0;
2939                         lh->mlh_rreg_mode = LCK_EX;
2940                         lh->mlh_type = MDT_REG_LOCK;
2941                 }
2942
2943                 rc = mdt_remote_object_lock_try(info, o, mdt_object_fid(o),
2944                                                 &lh->mlh_rreg_lh,
2945                                                 lh->mlh_rreg_mode,
2946                                                 ibits, trybits, false);
2947                 if (rc != ELDLM_OK) {
2948                         if (local_lh != NULL)
2949                                 mdt_object_unlock(info, o, local_lh, rc);
2950                         RETURN(rc);
2951                 }
2952         }
2953
2954         RETURN(0);
2955 }
2956
2957 int mdt_object_lock(struct mdt_thread_info *info, struct mdt_object *o,
2958                     struct mdt_lock_handle *lh, __u64 ibits)
2959 {
2960         return mdt_object_lock_internal(info, o, lh, &ibits, 0, false);
2961 }
2962
2963 int mdt_reint_object_lock(struct mdt_thread_info *info, struct mdt_object *o,
2964                           struct mdt_lock_handle *lh, __u64 ibits,
2965                           bool cos_incompat)
2966 {
2967         LASSERT(lh->mlh_reg_mode == LCK_PW || lh->mlh_reg_mode == LCK_EX);
2968         return mdt_object_lock_internal(info, o, lh, &ibits, 0,
2969                                         cos_incompat);
2970 }
2971
2972 int mdt_object_lock_try(struct mdt_thread_info *info, struct mdt_object *o,
2973                         struct mdt_lock_handle *lh, __u64 *ibits,
2974                         __u64 trybits, bool cos_incompat)
2975 {
2976         return mdt_object_lock_internal(info, o, lh, ibits, trybits,
2977                                         cos_incompat);
2978 }
2979
2980 /**
2981  * Save a lock within request object.
2982  *
2983  * Keep the lock referenced until whether client ACK or transaction
2984  * commit happens or release the lock immediately depending on input
2985  * parameters. If COS is ON, a write lock is converted to COS lock
2986  * before saving.
2987  *
2988  * \param info thead info object
2989  * \param h lock handle
2990  * \param mode lock mode
2991  * \param decref force immediate lock releasing
2992  */
2993 void mdt_save_lock(struct mdt_thread_info *info, struct lustre_handle *h,
2994                    enum ldlm_mode mode, int decref)
2995 {
2996         ENTRY;
2997
2998         if (lustre_handle_is_used(h)) {
2999                 if (decref || !info->mti_has_trans ||
3000                     !(mode & (LCK_PW | LCK_EX))) {
3001                         mdt_fid_unlock(h, mode);
3002                 } else {
3003                         struct mdt_device *mdt = info->mti_mdt;
3004                         struct ldlm_lock *lock = ldlm_handle2lock(h);
3005                         struct ptlrpc_request *req = mdt_info_req(info);
3006                         bool cos = mdt_cos_is_enabled(mdt);
3007                         bool convert_lock = !cos && mdt_slc_is_enabled(mdt);
3008
3009                         LASSERTF(lock != NULL, "no lock for cookie %#llx\n",
3010                                  h->cookie);
3011
3012                         /* there is no request if mdt_object_unlock() is called
3013                          * from mdt_export_cleanup()->mdt_add_dirty_flag() */
3014                         if (likely(req != NULL)) {
3015                                 LDLM_DEBUG(lock, "save lock request %p reply "
3016                                         "state %p transno %lld\n", req,
3017                                         req->rq_reply_state, req->rq_transno);
3018                                 if (cos) {
3019                                         ldlm_lock_downgrade(lock, LCK_COS);
3020                                         mode = LCK_COS;
3021                                 }
3022                                 if (req->rq_export->exp_disconnected)
3023                                         mdt_fid_unlock(h, mode);
3024                                 else
3025                                         ptlrpc_save_lock(req, h, mode, cos,
3026                                                          convert_lock);
3027                         } else {
3028                                 mdt_fid_unlock(h, mode);
3029                         }
3030                         if (mdt_is_lock_sync(lock)) {
3031                                 CDEBUG(D_HA, "found sync-lock,"
3032                                        " async commit started\n");
3033                                 mdt_device_commit_async(info->mti_env,
3034                                                         mdt);
3035                         }
3036                         LDLM_LOCK_PUT(lock);
3037                 }
3038                 h->cookie = 0ull;
3039         }
3040
3041         EXIT;
3042 }
3043
3044 /**
3045  * Save cross-MDT lock in uncommitted_slc_locks
3046  *
3047  * Keep the lock referenced until transaction commit happens or release the lock
3048  * immediately depending on input parameters.
3049  *
3050  * \param info thead info object
3051  * \param h lock handle
3052  * \param mode lock mode
3053  * \param decref force immediate lock releasing
3054  */
3055 static void mdt_save_remote_lock(struct mdt_thread_info *info,
3056                                  struct mdt_object *o, struct lustre_handle *h,
3057                                  enum ldlm_mode mode, int decref)
3058 {
3059         ENTRY;
3060
3061         if (lustre_handle_is_used(h)) {
3062                 struct ldlm_lock *lock = ldlm_handle2lock(h);
3063
3064                 if (o != NULL &&
3065                     (lock->l_policy_data.l_inodebits.bits &
3066                      (MDS_INODELOCK_XATTR | MDS_INODELOCK_UPDATE)))
3067                         mo_invalidate(info->mti_env, mdt_object_child(o));
3068
3069                 if (decref || !info->mti_has_trans ||
3070                     !(mode & (LCK_PW | LCK_EX))) {
3071                         ldlm_lock_decref_and_cancel(h, mode);
3072                         LDLM_LOCK_PUT(lock);
3073                 } else {
3074                         struct ptlrpc_request *req = mdt_info_req(info);
3075
3076                         LASSERT(req != NULL);
3077                         tgt_save_slc_lock(&info->mti_mdt->mdt_lut, lock,
3078                                           req->rq_transno);
3079                         ldlm_lock_decref(h, mode);
3080                 }
3081                 h->cookie = 0ull;
3082         }
3083
3084         EXIT;
3085 }
3086
3087 /**
3088  * Unlock mdt object.
3089  *
3090  * Immeditely release the regular lock and the PDO lock or save the
3091  * lock in request and keep them referenced until client ACK or
3092  * transaction commit.
3093  *
3094  * \param info thread info object
3095  * \param o mdt object
3096  * \param lh mdt lock handle referencing regular and PDO locks
3097  * \param decref force immediate lock releasing
3098  *
3099  * XXX o is not used and may be NULL, see hsm_cdt_request_completed().
3100  */
3101 void mdt_object_unlock(struct mdt_thread_info *info, struct mdt_object *o,
3102                        struct mdt_lock_handle *lh, int decref)
3103 {
3104         ENTRY;
3105
3106         mdt_save_lock(info, &lh->mlh_pdo_lh, lh->mlh_pdo_mode, decref);
3107         mdt_save_lock(info, &lh->mlh_reg_lh, lh->mlh_reg_mode, decref);
3108         mdt_save_remote_lock(info, o, &lh->mlh_rreg_lh, lh->mlh_rreg_mode,
3109                              decref);
3110
3111         EXIT;
3112 }
3113
3114 struct mdt_object *mdt_object_find_lock(struct mdt_thread_info *info,
3115                                         const struct lu_fid *f,
3116                                         struct mdt_lock_handle *lh,
3117                                         __u64 ibits)
3118 {
3119         struct mdt_object *o;
3120
3121         o = mdt_object_find(info->mti_env, info->mti_mdt, f);
3122         if (!IS_ERR(o)) {
3123                 int rc;
3124
3125                 rc = mdt_object_lock(info, o, lh, ibits);
3126                 if (rc != 0) {
3127                         mdt_object_put(info->mti_env, o);
3128                         o = ERR_PTR(rc);
3129                 }
3130         }
3131         return o;
3132 }
3133
3134 void mdt_object_unlock_put(struct mdt_thread_info * info,
3135                            struct mdt_object * o,
3136                            struct mdt_lock_handle *lh,
3137                            int decref)
3138 {
3139         mdt_object_unlock(info, o, lh, decref);
3140         mdt_object_put(info->mti_env, o);
3141 }
3142
3143 /*
3144  * Generic code handling requests that have struct mdt_body passed in:
3145  *
3146  *  - extract mdt_body from request and save it in @info, if present;
3147  *
3148  *  - create lu_object, corresponding to the fid in mdt_body, and save it in
3149  *  @info;
3150  *
3151  *  - if HABEO_CORPUS flag is set for this request type check whether object
3152  *  actually exists on storage (lu_object_exists()).
3153  *
3154  */
3155 static int mdt_body_unpack(struct mdt_thread_info *info, __u32 flags)
3156 {
3157         const struct mdt_body    *body;
3158         struct mdt_object        *obj;
3159         const struct lu_env      *env;
3160         struct req_capsule       *pill;
3161         int                       rc;
3162         ENTRY;
3163
3164         env = info->mti_env;
3165         pill = info->mti_pill;
3166
3167         body = info->mti_body = req_capsule_client_get(pill, &RMF_MDT_BODY);
3168         if (body == NULL)
3169                 RETURN(-EFAULT);
3170
3171         if (!(body->mbo_valid & OBD_MD_FLID))
3172                 RETURN(0);
3173
3174         if (!fid_is_sane(&body->mbo_fid1)) {
3175                 CERROR("Invalid fid: "DFID"\n", PFID(&body->mbo_fid1));
3176                 RETURN(-EINVAL);
3177         }
3178
3179         obj = mdt_object_find(env, info->mti_mdt, &body->mbo_fid1);
3180         if (!IS_ERR(obj)) {
3181                 if ((flags & HABEO_CORPUS) && !mdt_object_exists(obj)) {
3182                         mdt_object_put(env, obj);
3183                         rc = -ENOENT;
3184                 } else {
3185                         info->mti_object = obj;
3186                         rc = 0;
3187                 }
3188         } else
3189                 rc = PTR_ERR(obj);
3190
3191         RETURN(rc);
3192 }
3193
3194 static int mdt_unpack_req_pack_rep(struct mdt_thread_info *info, __u32 flags)
3195 {
3196         struct req_capsule *pill = info->mti_pill;
3197         int rc;
3198         ENTRY;
3199
3200         if (req_capsule_has_field(pill, &RMF_MDT_BODY, RCL_CLIENT))
3201                 rc = mdt_body_unpack(info, flags);
3202         else
3203                 rc = 0;
3204
3205         if (rc == 0 && (flags & HABEO_REFERO)) {
3206                 /* Pack reply. */
3207                 if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
3208                         req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER,
3209                                              DEF_REP_MD_SIZE);
3210                 if (req_capsule_has_field(pill, &RMF_LOGCOOKIES, RCL_SERVER))
3211                         req_capsule_set_size(pill, &RMF_LOGCOOKIES,
3212                                              RCL_SERVER, 0);
3213
3214                 /* Set ACL reply buffer size as LUSTRE_POSIX_ACL_MAX_SIZE_OLD
3215                  * by default. If the target object has more ACL entries, then
3216                  * enlarge the buffer when necessary. */
3217                 if (req_capsule_has_field(pill, &RMF_ACL, RCL_SERVER))
3218                         req_capsule_set_size(pill, &RMF_ACL, RCL_SERVER,
3219                                              LUSTRE_POSIX_ACL_MAX_SIZE_OLD);
3220
3221                 rc = req_capsule_server_pack(pill);
3222         }
3223         RETURN(rc);
3224 }
3225
3226 void mdt_lock_handle_init(struct mdt_lock_handle *lh)
3227 {
3228         lh->mlh_type = MDT_NUL_LOCK;
3229         lh->mlh_reg_lh.cookie = 0ull;
3230         lh->mlh_reg_mode = LCK_MINMODE;
3231         lh->mlh_pdo_lh.cookie = 0ull;
3232         lh->mlh_pdo_mode = LCK_MINMODE;
3233         lh->mlh_rreg_lh.cookie = 0ull;
3234         lh->mlh_rreg_mode = LCK_MINMODE;
3235 }
3236
3237 void mdt_lock_handle_fini(struct mdt_lock_handle *lh)
3238 {
3239         LASSERT(!lustre_handle_is_used(&lh->mlh_reg_lh));
3240         LASSERT(!lustre_handle_is_used(&lh->mlh_pdo_lh));
3241 }
3242
3243 /*
3244  * Initialize fields of struct mdt_thread_info. Other fields are left in
3245  * uninitialized state, because it's too expensive to zero out whole
3246  * mdt_thread_info (> 1K) on each request arrival.
3247  */
3248 void mdt_thread_info_init(struct ptlrpc_request *req,
3249                           struct mdt_thread_info *info)
3250 {
3251         int i;
3252
3253         info->mti_pill = &req->rq_pill;
3254
3255         /* lock handle */
3256         for (i = 0; i < ARRAY_SIZE(info->mti_lh); i++)
3257                 mdt_lock_handle_init(&info->mti_lh[i]);
3258
3259         /* mdt device: it can be NULL while CONNECT */
3260         if (req->rq_export) {
3261                 info->mti_mdt = mdt_dev(req->rq_export->exp_obd->obd_lu_dev);
3262                 info->mti_exp = req->rq_export;
3263         } else
3264                 info->mti_mdt = NULL;
3265         info->mti_env = req->rq_svc_thread->t_env;
3266         info->mti_transno = lustre_msg_get_transno(req->rq_reqmsg);
3267
3268         memset(&info->mti_attr, 0, sizeof(info->mti_attr));
3269         info->mti_big_buf = LU_BUF_NULL;
3270         info->mti_body = NULL;
3271         info->mti_object = NULL;
3272         info->mti_dlm_req = NULL;
3273         info->mti_has_trans = 0;
3274         info->mti_cross_ref = 0;
3275         info->mti_opdata = 0;
3276         info->mti_big_lmm_used = 0;
3277         info->mti_big_acl_used = 0;
3278         info->mti_som_valid = 0;
3279
3280         info->mti_spec.no_create = 0;
3281         info->mti_spec.sp_rm_entry = 0;
3282         info->mti_spec.sp_permitted = 0;
3283         info->mti_spec.sp_migrate_close = 0;
3284
3285         info->mti_spec.u.sp_ea.eadata = NULL;
3286         info->mti_spec.u.sp_ea.eadatalen = 0;
3287 }
3288
3289 void mdt_thread_info_fini(struct mdt_thread_info *info)
3290 {
3291         int i;
3292
3293         if (info->mti_object != NULL) {
3294                 mdt_object_put(info->mti_env, info->mti_object);
3295                 info->mti_object = NULL;
3296         }
3297
3298         for (i = 0; i < ARRAY_SIZE(info->mti_lh); i++)
3299                 mdt_lock_handle_fini(&info->mti_lh[i]);
3300         info->mti_env = NULL;
3301         info->mti_pill = NULL;
3302         info->mti_exp = NULL;
3303
3304         if (unlikely(info->mti_big_buf.lb_buf != NULL))
3305                 lu_buf_free(&info->mti_big_buf);
3306 }
3307
3308 struct mdt_thread_info *tsi2mdt_info(struct tgt_session_info *tsi)
3309 {
3310         struct mdt_thread_info  *mti;
3311
3312         mti = mdt_th_info(tsi->tsi_env);
3313         LASSERT(mti != NULL);
3314
3315         mdt_thread_info_init(tgt_ses_req(tsi), mti);
3316         if (tsi->tsi_corpus != NULL) {
3317                 mti->mti_object = mdt_obj(tsi->tsi_corpus);
3318                 lu_object_get(tsi->tsi_corpus);
3319         }
3320         mti->mti_body = tsi->tsi_mdt_body;
3321         mti->mti_dlm_req = tsi->tsi_dlm_req;
3322
3323         return mti;
3324 }
3325
3326 static int mdt_tgt_connect(struct tgt_session_info *tsi)
3327 {
3328         if (OBD_FAIL_CHECK(OBD_FAIL_TGT_DELAY_CONDITIONAL) &&
3329             cfs_fail_val ==
3330             tsi2mdt_info(tsi)->mti_mdt->mdt_seq_site.ss_node_id) {
3331                 set_current_state(TASK_UNINTERRUPTIBLE);
3332                 schedule_timeout(msecs_to_jiffies(3 * MSEC_PER_SEC));
3333         }
3334
3335         return tgt_connect(tsi);
3336 }
3337
3338 enum mdt_it_code {
3339         MDT_IT_OPEN,
3340         MDT_IT_OCREAT,
3341         MDT_IT_CREATE,
3342         MDT_IT_GETATTR,
3343         MDT_IT_READDIR,
3344         MDT_IT_LOOKUP,
3345         MDT_IT_UNLINK,
3346         MDT_IT_TRUNC,
3347         MDT_IT_GETXATTR,
3348         MDT_IT_LAYOUT,
3349         MDT_IT_QUOTA,
3350         MDT_IT_GLIMPSE,
3351         MDT_IT_BRW,
3352         MDT_IT_NR
3353 };
3354
3355 static int mdt_intent_getattr(enum mdt_it_code opcode,
3356                               struct mdt_thread_info *info,
3357                               struct ldlm_lock **, __u64);
3358
3359 static int mdt_intent_getxattr(enum mdt_it_code opcode,
3360                                 struct mdt_thread_info *info,
3361                                 struct ldlm_lock **lockp,
3362                                 __u64 flags);
3363
3364 static int mdt_intent_layout(enum mdt_it_code opcode,
3365                              struct mdt_thread_info *info,
3366                              struct ldlm_lock **,
3367                              __u64);
3368 static int mdt_intent_reint(enum mdt_it_code opcode,
3369                             struct mdt_thread_info *info,
3370                             struct ldlm_lock **,
3371                             __u64);
3372 static int mdt_intent_glimpse(enum mdt_it_code opcode,
3373                               struct mdt_thread_info *info,
3374                               struct ldlm_lock **lockp, __u64 flags)
3375 {
3376         return mdt_glimpse_enqueue(info, info->mti_mdt->mdt_namespace,
3377                                    lockp, flags);
3378 }
3379 static int mdt_intent_brw(enum mdt_it_code opcode,
3380                           struct mdt_thread_info *info,
3381                           struct ldlm_lock **lockp, __u64 flags)
3382 {
3383         return mdt_brw_enqueue(info, info->mti_mdt->mdt_namespace,
3384                                lockp, flags);
3385 }
3386
3387 static struct mdt_it_flavor {
3388         const struct req_format *it_fmt;
3389         __u32                    it_flags;
3390         int                    (*it_act)(enum mdt_it_code ,
3391                                          struct mdt_thread_info *,
3392                                          struct ldlm_lock **,
3393                                          __u64);
3394         long                     it_reint;
3395 } mdt_it_flavor[] = {
3396         [MDT_IT_OPEN]     = {
3397                 .it_fmt   = &RQF_LDLM_INTENT,
3398                 /*.it_flags = HABEO_REFERO,*/
3399                 .it_flags = 0,
3400                 .it_act   = mdt_intent_reint,
3401                 .it_reint = REINT_OPEN
3402         },
3403         [MDT_IT_OCREAT]   = {
3404                 .it_fmt   = &RQF_LDLM_INTENT,
3405                 /*
3406                  * OCREAT is not a MUTABOR request as if the file
3407                  * already exists.
3408                  * We do the extra check of OBD_CONNECT_RDONLY in
3409                  * mdt_reint_open() when we really need to create
3410                  * the object.
3411                  */
3412                 .it_flags = 0,
3413                 .it_act   = mdt_intent_reint,
3414                 .it_reint = REINT_OPEN
3415         },
3416         [MDT_IT_CREATE]   = {
3417                 .it_fmt   = &RQF_LDLM_INTENT,
3418                 .it_flags = MUTABOR,
3419                 .it_act   = mdt_intent_reint,
3420                 .it_reint = REINT_CREATE
3421         },
3422         [MDT_IT_GETATTR]  = {
3423                 .it_fmt   = &RQF_LDLM_INTENT_GETATTR,
3424                 .it_flags = HABEO_REFERO,
3425                 .it_act   = mdt_intent_getattr
3426         },
3427         [MDT_IT_READDIR]  = {
3428                 .it_fmt   = NULL,
3429                 .it_flags = 0,
3430                 .it_act   = NULL
3431         },
3432         [MDT_IT_LOOKUP]   = {
3433                 .it_fmt   = &RQF_LDLM_INTENT_GETATTR,
3434                 .it_flags = HABEO_REFERO,
3435                 .it_act   = mdt_intent_getattr
3436         },
3437         [MDT_IT_UNLINK]   = {
3438                 .it_fmt   = &RQF_LDLM_INTENT_UNLINK,
3439                 .it_flags = MUTABOR,
3440                 .it_act   = NULL,
3441                 .it_reint = REINT_UNLINK
3442         },
3443         [MDT_IT_TRUNC]    = {
3444                 .it_fmt   = NULL,
3445                 .it_flags = MUTABOR,
3446                 .it_act   = NULL
3447         },
3448         [MDT_IT_GETXATTR] = {
3449                 .it_fmt   = &RQF_LDLM_INTENT_GETXATTR,
3450                 .it_flags = HABEO_CORPUS,
3451                 .it_act   = mdt_intent_getxattr
3452         },
3453         [MDT_IT_LAYOUT] = {
3454                 .it_fmt   = &RQF_LDLM_INTENT_LAYOUT,
3455                 .it_flags = 0,
3456                 .it_act   = mdt_intent_layout
3457         },
3458         [MDT_IT_GLIMPSE] = {
3459                 .it_fmt = &RQF_LDLM_INTENT,
3460                 .it_flags = 0,
3461                 .it_act = mdt_intent_glimpse,
3462         },
3463         [MDT_IT_BRW] = {
3464                 .it_fmt = &RQF_LDLM_INTENT,
3465                 .it_flags = 0,
3466                 .it_act = mdt_intent_brw,
3467         },
3468
3469 };
3470
3471 int mdt_intent_lock_replace(struct mdt_thread_info *info,
3472                             struct ldlm_lock **lockp,
3473                             struct mdt_lock_handle *lh,
3474                             __u64 flags, int result)
3475 {
3476         struct ptlrpc_request  *req = mdt_info_req(info);
3477         struct ldlm_lock       *lock = *lockp;
3478         struct ldlm_lock       *new_lock;
3479
3480         /* If possible resent found a lock, @lh is set to its handle */
3481         new_lock = ldlm_handle2lock_long(&lh->mlh_reg_lh, 0);
3482
3483         if (new_lock == NULL && (flags & LDLM_FL_INTENT_ONLY)) {
3484                 lh->mlh_reg_lh.cookie = 0;
3485                 RETURN(0);
3486         }
3487
3488         if (new_lock == NULL && (flags & LDLM_FL_RESENT)) {
3489                 /* Lock is pinned by ldlm_handle_enqueue0() as it is
3490                  * a resend case, however, it could be already destroyed
3491                  * due to client eviction or a raced cancel RPC. */
3492                 LDLM_DEBUG_NOLOCK("Invalid lock handle %#llx\n",
3493                                   lh->mlh_reg_lh.cookie);
3494                 lh->mlh_reg_lh.cookie = 0;
3495                 RETURN(-ESTALE);
3496         }
3497
3498         LASSERTF(new_lock != NULL,
3499                  "lockh %#llx flags %#llx : rc = %d\n",
3500                  lh->mlh_reg_lh.cookie, flags, result);
3501
3502         /*
3503          * If we've already given this lock to a client once, then we should
3504          * have no readers or writers.  Otherwise, we should have one reader
3505          * _or_ writer ref (which will be zeroed below) before returning the
3506          * lock to a client.
3507          */
3508         if (new_lock->l_export == req->rq_export) {
3509                 LASSERT(new_lock->l_readers + new_lock->l_writers == 0);
3510         } else {
3511                 LASSERT(new_lock->l_export == NULL);
3512                 LASSERT(new_lock->l_readers + new_lock->l_writers == 1);
3513         }
3514
3515         *lockp = new_lock;
3516
3517         if (new_lock->l_export == req->rq_export) {
3518                 /*
3519                  * Already gave this to the client, which means that we
3520                  * reconstructed a reply.
3521                  */
3522                 LASSERT(lustre_msg_get_flags(req->rq_reqmsg) &
3523                         MSG_RESENT);
3524
3525                 LDLM_LOCK_RELEASE(new_lock);
3526                 lh->mlh_reg_lh.cookie = 0;
3527                 RETURN(ELDLM_LOCK_REPLACED);
3528         }
3529
3530         /*
3531          * Fixup the lock to be given to the client.
3532          */
3533         lock_res_and_lock(new_lock);
3534         /* Zero new_lock->l_readers and new_lock->l_writers without triggering
3535          * possible blocking AST. */
3536         while (new_lock->l_readers > 0) {
3537                 lu_ref_del(&new_lock->l_reference, "reader", new_lock);
3538                 lu_ref_del(&new_lock->l_reference, "user", new_lock);
3539                 new_lock->l_readers--;
3540         }
3541         while (new_lock->l_writers > 0) {
3542                 lu_ref_del(&new_lock->l_reference, "writer", new_lock);
3543                 lu_ref_del(&new_lock->l_reference, "user", new_lock);
3544                 new_lock->l_writers--;
3545         }
3546
3547         new_lock->l_export = class_export_lock_get(req->rq_export, new_lock);
3548         new_lock->l_blocking_ast = lock->l_blocking_ast;
3549         new_lock->l_completion_ast = lock->l_completion_ast;
3550         if (ldlm_has_dom(new_lock))
3551                 new_lock->l_glimpse_ast = ldlm_server_glimpse_ast;
3552         new_lock->l_remote_handle = lock->l_remote_handle;
3553         new_lock->l_flags &= ~LDLM_FL_LOCAL;
3554
3555         unlock_res_and_lock(new_lock);
3556
3557         cfs_hash_add(new_lock->l_export->exp_lock_hash,
3558                      &new_lock->l_remote_handle,
3559                      &new_lock->l_exp_hash);
3560
3561         LDLM_LOCK_RELEASE(new_lock);
3562         lh->mlh_reg_lh.cookie = 0;
3563
3564         RETURN(ELDLM_LOCK_REPLACED);
3565 }
3566
3567 void mdt_intent_fixup_resent(struct mdt_thread_info *info,
3568                              struct ldlm_lock *new_lock,
3569                              struct mdt_lock_handle *lh, __u64 flags)
3570 {
3571         struct ptlrpc_request  *req = mdt_info_req(info);
3572         struct ldlm_request    *dlmreq;
3573
3574         if (!(lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT))
3575                 return;
3576
3577         dlmreq = req_capsule_client_get(info->mti_pill, &RMF_DLM_REQ);
3578
3579         /* Check if this is a resend case (MSG_RESENT is set on RPC) and a
3580          * lock was found by ldlm_handle_enqueue(); if so @lh must be
3581          * initialized. */
3582         if (flags & LDLM_FL_RESENT) {
3583                 lh->mlh_reg_lh.cookie = new_lock->l_handle.h_cookie;
3584                 lh->mlh_reg_mode = new_lock->l_granted_mode;
3585
3586                 LDLM_DEBUG(new_lock, "Restoring lock cookie");
3587                 DEBUG_REQ(D_DLMTRACE, req, "restoring lock cookie %#llx",
3588                           lh->mlh_reg_lh.cookie);
3589                 return;
3590         }
3591
3592         /*
3593          * If the xid matches, then we know this is a resent request, and allow
3594          * it. (It's probably an OPEN, for which we don't send a lock.
3595          */
3596         if (req_can_reconstruct(req, NULL))
3597                 return;
3598
3599         /*
3600          * This remote handle isn't enqueued, so we never received or processed
3601          * this request.  Clear MSG_RESENT, because it can be handled like any
3602          * normal request now.
3603          */
3604         lustre_msg_clear_flags(req->rq_reqmsg, MSG_RESENT);
3605
3606         DEBUG_REQ(D_DLMTRACE, req, "no existing lock with rhandle %#llx",
3607                   dlmreq->lock_handle[0].cookie);
3608 }
3609
3610 static int mdt_intent_getxattr(enum mdt_it_code opcode,
3611                                 struct mdt_thread_info *info,
3612                                 struct ldlm_lock **lockp,
3613                                 __u64 flags)
3614 {
3615         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
3616         struct ldlm_reply      *ldlm_rep = NULL;
3617         int rc;
3618         ENTRY;
3619
3620         /*
3621          * Initialize lhc->mlh_reg_lh either from a previously granted lock
3622          * (for the resend case) or a new lock. Below we will use it to
3623          * replace the original lock.
3624          */
3625         mdt_intent_fixup_resent(info, *lockp, lhc, flags);
3626         if (!lustre_handle_is_used(&lhc->mlh_reg_lh)) {
3627                 mdt_lock_reg_init(lhc, (*lockp)->l_req_mode);
3628                 rc = mdt_object_lock(info, info->mti_object, lhc,
3629                                      MDS_INODELOCK_XATTR);
3630                 if (rc)
3631                         return rc;
3632         }
3633
3634         rc = mdt_getxattr(info);
3635
3636         if (mdt_info_req(info)->rq_repmsg != NULL)
3637                 ldlm_rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
3638
3639         if (ldlm_rep == NULL ||
3640             OBD_FAIL_CHECK(OBD_FAIL_MDS_XATTR_REP)) {
3641                 mdt_object_unlock(info,  info->mti_object, lhc, 1);
3642                 RETURN(err_serious(-EFAULT));
3643         }
3644
3645         ldlm_rep->lock_policy_res2 = clear_serious(rc);
3646
3647         /* This is left for interop instead of adding a new interop flag.
3648          * LU-7433 */
3649 #if LUSTRE_VERSION_CODE > OBD_OCD_VERSION(3, 0, 0, 0)
3650         if (ldlm_rep->lock_policy_res2) {
3651                 mdt_object_unlock(info, info->mti_object, lhc, 1);
3652                 RETURN(ELDLM_LOCK_ABORTED);
3653         }
3654 #endif
3655
3656         rc = mdt_intent_lock_replace(info, lockp, lhc, flags, rc);
3657         RETURN(rc);
3658 }
3659
3660 static int mdt_intent_getattr(enum mdt_it_code opcode,
3661                               struct mdt_thread_info *info,
3662                               struct ldlm_lock **lockp,
3663                               __u64 flags)
3664 {
3665         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
3666         __u64                   child_bits;
3667         struct ldlm_reply      *ldlm_rep;
3668         struct mdt_body        *reqbody;
3669         struct mdt_body        *repbody;
3670         int                     rc, rc2;
3671         ENTRY;
3672
3673         reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
3674         LASSERT(reqbody);
3675
3676         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
3677         LASSERT(repbody);
3678
3679         info->mti_cross_ref = !!(reqbody->mbo_valid & OBD_MD_FLCROSSREF);
3680         repbody->mbo_eadatasize = 0;
3681         repbody->mbo_aclsize = 0;
3682
3683         switch (opcode) {
3684         case MDT_IT_LOOKUP:
3685                 child_bits = MDS_INODELOCK_LOOKUP | MDS_INODELOCK_PERM;
3686                 break;
3687         case MDT_IT_GETATTR:
3688                 child_bits = MDS_INODELOCK_LOOKUP | MDS_INODELOCK_UPDATE |
3689                              MDS_INODELOCK_PERM;
3690                 break;
3691         default:
3692                 CERROR("Unsupported intent (%d)\n", opcode);
3693                 GOTO(out_shrink, rc = -EINVAL);
3694         }
3695
3696         rc = mdt_init_ucred_intent_getattr(info, reqbody);
3697         if (rc)
3698                 GOTO(out_shrink, rc);
3699
3700         ldlm_rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
3701         mdt_set_disposition(info, ldlm_rep, DISP_IT_EXECD);
3702
3703         /* Get lock from request for possible resent case. */
3704         mdt_intent_fixup_resent(info, *lockp, lhc, flags);
3705
3706         rc = mdt_getattr_name_lock(info, lhc, child_bits, ldlm_rep);
3707         ldlm_rep->lock_policy_res2 = clear_serious(rc);
3708
3709         if (mdt_get_disposition(ldlm_rep, DISP_LOOKUP_NEG))
3710                 ldlm_rep->lock_policy_res2 = 0;
3711         if (!mdt_get_disposition(ldlm_rep, DISP_LOOKUP_POS) ||
3712             ldlm_rep->lock_policy_res2) {
3713                 lhc->mlh_reg_lh.cookie = 0ull;
3714                 GOTO(out_ucred, rc = ELDLM_LOCK_ABORTED);
3715         }
3716
3717         rc = mdt_intent_lock_replace(info, lockp, lhc, flags, rc);
3718         EXIT;
3719 out_ucred:
3720         mdt_exit_ucred(info);
3721 out_shrink:
3722         mdt_client_compatibility(info);
3723         rc2 = mdt_fix_reply(info);
3724         if (rc == 0)
3725                 rc = rc2;
3726         return rc;
3727 }
3728
3729 static int mdt_intent_layout(enum mdt_it_code opcode,
3730                              struct mdt_thread_info *info,
3731                              struct ldlm_lock **lockp,
3732                              __u64 flags)
3733 {
3734         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_LAYOUT];
3735         struct md_layout_change layout = { .mlc_opc = MD_LAYOUT_NOP };
3736         struct layout_intent *intent;
3737         struct lu_fid *fid = &info->mti_tmp_fid2;
3738         struct mdt_object *obj = NULL;
3739         int layout_size = 0;
3740         int rc = 0;
3741         ENTRY;
3742
3743         if (opcode != MDT_IT_LAYOUT) {
3744                 CERROR("%s: Unknown intent (%d)\n", mdt_obd_name(info->mti_mdt),
3745                         opcode);
3746                 RETURN(-EINVAL);
3747         }
3748
3749         fid_extract_from_res_name(fid, &(*lockp)->l_resource->lr_name);
3750
3751         intent = req_capsule_client_get(info->mti_pill, &RMF_LAYOUT_INTENT);
3752         if (intent == NULL)
3753                 RETURN(-EPROTO);
3754
3755         CDEBUG(D_INFO, DFID "got layout change request from client: "
3756                "opc:%u flags:%#x extent "DEXT"\n",
3757                PFID(fid), intent->li_opc, intent->li_flags,
3758                PEXT(&intent->li_extent));
3759
3760         switch (intent->li_opc) {
3761         case LAYOUT_INTENT_TRUNC:
3762         case LAYOUT_INTENT_WRITE:
3763                 layout.mlc_opc = MD_LAYOUT_WRITE;
3764                 layout.mlc_intent = intent;
3765                 break;
3766         case LAYOUT_INTENT_ACCESS:
3767                 break;
3768         case LAYOUT_INTENT_READ:
3769         case LAYOUT_INTENT_GLIMPSE:
3770         case LAYOUT_INTENT_RELEASE:
3771         case LAYOUT_INTENT_RESTORE:
3772                 CERROR("%s: Unsupported layout intent opc %d\n",
3773                        mdt_obd_name(info->mti_mdt), intent->li_opc);
3774                 rc = -ENOTSUPP;
3775                 break;
3776         default:
3777                 CERROR("%s: Unknown layout intent opc %d\n",
3778                        mdt_obd_name(info->mti_mdt), intent->li_opc);
3779                 rc = -EINVAL;
3780                 break;
3781         }
3782         if (rc < 0)
3783                 RETURN(rc);
3784
3785         /* Get lock from request for possible resent case. */
3786         mdt_intent_fixup_resent(info, *lockp, lhc, flags);
3787
3788         obj = mdt_object_find(info->mti_env, info->mti_mdt, fid);
3789         if (IS_ERR(obj))
3790                 GOTO(out, rc = PTR_ERR(obj));
3791
3792         if (mdt_object_exists(obj) && !mdt_object_remote(obj)) {
3793                 layout_size = mdt_attr_get_eabuf_size(info, obj);
3794                 if (layout_size < 0)
3795                         GOTO(out_obj, rc = layout_size);
3796
3797                 if (layout_size > info->mti_mdt->mdt_max_mdsize)
3798                         info->mti_mdt->mdt_max_mdsize = layout_size;
3799         }
3800
3801         /*
3802          * set reply buffer size, so that ldlm_handle_enqueue0()->
3803          * ldlm_lvbo_fill() will fill the reply buffer with lovea.
3804          */
3805         (*lockp)->l_lvb_type = LVB_T_LAYOUT;
3806         req_capsule_set_size(info->mti_pill, &RMF_DLM_LVB, RCL_SERVER,
3807                              layout_size);
3808         rc = req_capsule_server_pack(info->mti_pill);
3809         if (rc)
3810                 GOTO(out_obj, rc);
3811
3812
3813         if (layout.mlc_opc != MD_LAYOUT_NOP) {
3814                 struct lu_buf *buf = &layout.mlc_buf;
3815
3816                 /**
3817                  * mdt_layout_change is a reint operation, when the request
3818                  * is resent, layout write shouldn't reprocess it again.
3819                  */
3820                 rc = mdt_check_resent(info, mdt_reconstruct_generic, lhc);
3821                 if (rc)
3822                         GOTO(out_obj, rc = rc < 0 ? rc : 0);
3823
3824                 /**
3825                  * There is another resent case: the client's job has been
3826                  * done by another client, referring lod_declare_layout_change
3827                  * -EALREADY case, and it became a operation w/o transaction,
3828                  * so we should not do the layout change, otherwise
3829                  * mdt_layout_change() will try to cancel the granted server
3830                  * CR lock whose remote counterpart is still in hold on the
3831                  * client, and a deadlock ensues.
3832                  */
3833                 rc = mdt_check_resent_lock(info, obj, lhc);
3834                 if (rc <= 0)
3835                         GOTO(out_obj, rc);
3836
3837                 buf->lb_buf = NULL;
3838                 buf->lb_len = 0;
3839                 if (unlikely(req_is_replay(mdt_info_req(info)))) {
3840                         buf->lb_buf = req_capsule_client_get(info->mti_pill,
3841                                         &RMF_EADATA);
3842                         buf->lb_len = req_capsule_get_size(info->mti_pill,
3843                                         &RMF_EADATA, RCL_CLIENT);
3844                         /*
3845                          * If it's a replay of layout write intent RPC, the
3846                          * client has saved the extended lovea when
3847                          * it get reply then.
3848                          */
3849                         if (buf->lb_len > 0)
3850                                 mdt_fix_lov_magic(info, buf->lb_buf);
3851                 }
3852
3853                 /*
3854                  * Instantiate some layout components, if @buf contains
3855                  * lovea, then it's a replay of the layout intent write
3856                  * RPC.
3857                  */
3858                 rc = mdt_layout_change(info, obj, &layout);
3859                 if (rc)
3860                         GOTO(out_obj, rc);
3861         }
3862 out_obj:
3863         mdt_object_put(info->mti_env, obj);
3864
3865         if (rc == 0 && lustre_handle_is_used(&lhc->mlh_reg_lh))
3866                 rc = mdt_intent_lock_replace(info, lockp, lhc, flags, rc);
3867
3868 out:
3869         lhc->mlh_reg_lh.cookie = 0;
3870
3871         return rc;
3872 }
3873
3874 static int mdt_intent_reint(enum mdt_it_code opcode,
3875                             struct mdt_thread_info *info,
3876                             struct ldlm_lock **lockp,
3877                             __u64 flags)
3878 {
3879         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
3880         struct ldlm_reply      *rep = NULL;
3881         long                    opc;
3882         int                     rc;
3883
3884         static const struct req_format *intent_fmts[REINT_MAX] = {
3885                 [REINT_CREATE]  = &RQF_LDLM_INTENT_CREATE,
3886                 [REINT_OPEN]    = &RQF_LDLM_INTENT_OPEN
3887         };
3888
3889         ENTRY;
3890
3891         opc = mdt_reint_opcode(mdt_info_req(info), intent_fmts);
3892         if (opc < 0)
3893                 RETURN(opc);
3894
3895         if (mdt_it_flavor[opcode].it_reint != opc) {
3896                 CERROR("Reint code %ld doesn't match intent: %d\n",
3897                        opc, opcode);
3898                 RETURN(err_serious(-EPROTO));
3899         }
3900
3901         /* Get lock from request for possible resent case. */
3902         mdt_intent_fixup_resent(info, *lockp, lhc, flags);
3903
3904         rc = mdt_reint_internal(info, lhc, opc);
3905
3906         /* Check whether the reply has been packed successfully. */
3907         if (mdt_info_req(info)->rq_repmsg != NULL)
3908                 rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
3909         if (rep == NULL)
3910                 RETURN(err_serious(-EFAULT));
3911
3912         /* MDC expects this in any case */
3913         if (rc != 0)
3914                 mdt_set_disposition(info, rep, DISP_LOOKUP_EXECD);
3915
3916         /* the open lock or the lock for cross-ref object should be
3917          * returned to the client */
3918         if (lustre_handle_is_used(&lhc->mlh_reg_lh) &&
3919             (rc == 0 || rc == -MDT_EREMOTE_OPEN)) {
3920                 rep->lock_policy_res2 = 0;
3921                 rc = mdt_intent_lock_replace(info, lockp, lhc, flags, rc);
3922                 RETURN(rc);
3923         }
3924
3925         rep->lock_policy_res2 = clear_serious(rc);
3926
3927         if (rep->lock_policy_res2 == -ENOENT &&
3928             mdt_get_disposition(rep, DISP_LOOKUP_NEG) &&
3929             !mdt_get_disposition(rep, DISP_OPEN_CREATE))
3930                 rep->lock_policy_res2 = 0;
3931
3932         lhc->mlh_reg_lh.cookie = 0ull;
3933         if (rc == -ENOTCONN || rc == -ENODEV ||
3934             rc == -EOVERFLOW) { /**< if VBR failure then return error */
3935                 /*
3936                  * If it is the disconnect error (ENODEV & ENOCONN), the error
3937                  * will be returned by rq_status, and client at ptlrpc layer
3938                  * will detect this, then disconnect, reconnect the import
3939                  * immediately, instead of impacting the following the rpc.
3940                  */
3941                 RETURN(rc);
3942         }
3943         /*
3944          * For other cases, the error will be returned by intent, and client
3945          * will retrieve the result from intent.
3946          */
3947         RETURN(ELDLM_LOCK_ABORTED);
3948 }
3949
3950 static int mdt_intent_code(enum ldlm_intent_flags itcode)
3951 {
3952         int rc;
3953
3954         switch (itcode) {
3955         case IT_OPEN:
3956                 rc = MDT_IT_OPEN;
3957                 break;
3958         case IT_OPEN|IT_CREAT:
3959                 rc = MDT_IT_OCREAT;
3960                 break;
3961         case IT_CREAT:
3962                 rc = MDT_IT_CREATE;
3963                 break;
3964         case IT_READDIR:
3965                 rc = MDT_IT_READDIR;
3966                 break;
3967         case IT_GETATTR:
3968                 rc = MDT_IT_GETATTR;
3969                 break;
3970         case IT_LOOKUP:
3971                 rc = MDT_IT_LOOKUP;
3972                 break;
3973         case IT_UNLINK:
3974                 rc = MDT_IT_UNLINK;
3975                 break;
3976         case IT_TRUNC:
3977                 rc = MDT_IT_TRUNC;
3978                 break;
3979         case IT_GETXATTR:
3980                 rc = MDT_IT_GETXATTR;
3981                 break;
3982         case IT_LAYOUT:
3983                 rc = MDT_IT_LAYOUT;
3984                 break;
3985         case IT_QUOTA_DQACQ:
3986         case IT_QUOTA_CONN:
3987                 rc = MDT_IT_QUOTA;
3988                 break;
3989         case IT_GLIMPSE:
3990                 rc = MDT_IT_GLIMPSE;
3991                 break;
3992         case IT_BRW:
3993                 rc = MDT_IT_BRW;
3994                 break;
3995         default:
3996                 CERROR("Unknown intent opcode: 0x%08x\n", itcode);
3997                 rc = -EINVAL;
3998                 break;
3999         }
4000         return rc;
4001 }
4002
4003 static int mdt_intent_opc(enum ldlm_intent_flags itopc,
4004                           struct mdt_thread_info *info,
4005                           struct ldlm_lock **lockp, __u64 flags)
4006 {
4007         struct req_capsule      *pill = info->mti_pill;
4008         struct ptlrpc_request   *req = mdt_info_req(info);
4009         struct mdt_it_flavor    *flv;
4010         int opc;
4011         int rc;
4012         ENTRY;
4013
4014         opc = mdt_intent_code(itopc);
4015         if (opc < 0)
4016                 RETURN(-EINVAL);
4017
4018         if (opc == MDT_IT_QUOTA) {
4019                 struct lu_device *qmt = info->mti_mdt->mdt_qmt_dev;
4020
4021                 if (qmt == NULL)
4022                         RETURN(-EOPNOTSUPP);
4023
4024                 if (mdt_rdonly(req->rq_export))
4025                         RETURN(-EROFS);
4026
4027                 (*lockp)->l_lvb_type = LVB_T_LQUOTA;
4028                 /* pass the request to quota master */
4029                 rc = qmt_hdls.qmth_intent_policy(info->mti_env, qmt,
4030                                                  mdt_info_req(info), lockp,
4031                                                  flags);
4032                 RETURN(rc);
4033         }
4034
4035         flv = &mdt_it_flavor[opc];
4036         if (flv->it_fmt != NULL)
4037                 req_capsule_extend(pill, flv->it_fmt);
4038
4039         rc = mdt_unpack_req_pack_rep(info, flv->it_flags);
4040         if (rc < 0)
4041                 RETURN(rc);
4042
4043         if (flv->it_flags & MUTABOR && mdt_rdonly(req->rq_export))
4044                 RETURN(-EROFS);
4045
4046         if (flv->it_act != NULL) {
4047                 struct ldlm_reply *rep;
4048
4049                 OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_INTENT_DELAY, 10);
4050
4051                 /* execute policy */
4052                 rc = flv->it_act(opc, info, lockp, flags);
4053
4054                 /* Check whether the reply has been packed successfully. */
4055                 if (req->rq_repmsg != NULL) {
4056                         rep = req_capsule_server_get(info->mti_pill,
4057                                                      &RMF_DLM_REP);
4058                         rep->lock_policy_res2 =
4059                                 ptlrpc_status_hton(rep->lock_policy_res2);
4060                 }
4061         }
4062
4063         RETURN(rc);
4064 }
4065
4066 static void mdt_ptlrpc_stats_update(struct ptlrpc_request *req,
4067                                     enum ldlm_intent_flags it_opc)
4068 {
4069         struct lprocfs_stats *srv_stats = ptlrpc_req2svc(req)->srv_stats;
4070
4071         /* update stats when IT code is known */
4072         if (srv_stats != NULL)
4073                 lprocfs_counter_incr(srv_stats,
4074                                 PTLRPC_LAST_CNTR + (it_opc == IT_GLIMPSE ?
4075                                 LDLM_GLIMPSE_ENQUEUE : LDLM_IBITS_ENQUEUE));
4076 }
4077
4078 static int mdt_intent_policy(struct ldlm_namespace *ns,
4079                              struct ldlm_lock **lockp, void *req_cookie,
4080                              enum ldlm_mode mode, __u64 flags, void *data)
4081 {
4082         struct tgt_session_info *tsi;
4083         struct mdt_thread_info  *info;
4084         struct ptlrpc_request   *req  =  req_cookie;
4085         struct ldlm_intent      *it;
4086         struct req_capsule      *pill;
4087         const struct ldlm_lock_desc *ldesc;
4088         int rc;
4089
4090         ENTRY;
4091
4092         LASSERT(req != NULL);
4093
4094         tsi = tgt_ses_info(req->rq_svc_thread->t_env);
4095
4096         info = tsi2mdt_info(tsi);
4097         LASSERT(info != NULL);
4098         pill = info->mti_pill;
4099         LASSERT(pill->rc_req == req);
4100         ldesc = &info->mti_dlm_req->lock_desc;
4101
4102         if (req->rq_reqmsg->lm_bufcount > DLM_INTENT_IT_OFF) {
4103                 req_capsule_extend(pill, &RQF_LDLM_INTENT_BASIC);
4104                 it = req_capsule_client_get(pill, &RMF_LDLM_INTENT);
4105                 if (it != NULL) {
4106                         mdt_ptlrpc_stats_update(req, it->opc);
4107                         rc = mdt_intent_opc(it->opc, info, lockp, flags);
4108                         if (rc == 0)
4109                                 rc = ELDLM_OK;
4110
4111                         /* Lock without inodebits makes no sense and will oops
4112                          * later in ldlm. Let's check it now to see if we have
4113                          * ibits corrupted somewhere in mdt_intent_opc().
4114                          * The case for client miss to set ibits has been
4115                          * processed by others. */
4116                         LASSERT(ergo(ldesc->l_resource.lr_type == LDLM_IBITS,
4117                                 ldesc->l_policy_data.l_inodebits.bits != 0));
4118                 } else {
4119                         rc = err_serious(-EFAULT);
4120                 }
4121         } else {
4122                 /* No intent was provided */
4123                 req_capsule_set_size(pill, &RMF_DLM_LVB, RCL_SERVER, 0);
4124                 rc = req_capsule_server_pack(pill);
4125                 if (rc)
4126                         rc = err_serious(rc);
4127         }
4128         mdt_thread_info_fini(info);
4129         RETURN(rc);
4130 }
4131
4132 static void mdt_deregister_seq_exp(struct mdt_device *mdt)
4133 {
4134         struct seq_server_site  *ss = mdt_seq_site(mdt);
4135
4136         if (ss->ss_node_id == 0)
4137                 return;
4138
4139         if (ss->ss_client_seq != NULL) {
4140                 lustre_deregister_lwp_item(&ss->ss_client_seq->lcs_exp);
4141                 ss->ss_client_seq->lcs_exp = NULL;
4142         }
4143
4144         if (ss->ss_server_fld != NULL) {
4145                 lustre_deregister_lwp_item(&ss->ss_server_fld->lsf_control_exp);
4146                 ss->ss_server_fld->lsf_control_exp = NULL;
4147         }
4148 }
4149
4150 static void mdt_seq_fini_cli(struct mdt_device *mdt)
4151 {
4152         struct seq_server_site *ss = mdt_seq_site(mdt);
4153
4154         if (ss == NULL)
4155                 return;
4156
4157         if (ss->ss_server_seq != NULL)
4158                 seq_server_set_cli(NULL, ss->ss_server_seq, NULL);
4159 }
4160
4161 static int mdt_seq_fini(const struct lu_env *env, struct mdt_device *mdt)
4162 {
4163         mdt_seq_fini_cli(mdt);
4164         mdt_deregister_seq_exp(mdt);
4165
4166         return seq_site_fini(env, mdt_seq_site(mdt));
4167 }
4168
4169 /**
4170  * It will retrieve its FLDB entries from MDT0, and it only happens
4171  * when upgrading existent FS to 2.6 or when local FLDB is corrupted,
4172  * and it needs to refresh FLDB from the MDT0.
4173  **/
4174 static int mdt_register_lwp_callback(void *data)
4175 {
4176         struct lu_env           env;
4177         struct mdt_device       *mdt = data;
4178         struct lu_server_fld    *fld = mdt_seq_site(mdt)->ss_server_fld;
4179         int                     rc;
4180         ENTRY;
4181
4182         LASSERT(mdt_seq_site(mdt)->ss_node_id != 0);
4183
4184         rc = lu_env_init(&env, LCT_MD_THREAD);
4185         if (rc < 0) {
4186                 CERROR("%s: cannot init env: rc = %d\n", mdt_obd_name(mdt), rc);
4187                 RETURN(rc);
4188         }
4189
4190         /* Allocate new sequence now to avoid creating local transaction
4191          * in the normal transaction process */
4192         rc = seq_server_check_and_alloc_super(&env,
4193                                               mdt_seq_site(mdt)->ss_server_seq);
4194         if (rc < 0)
4195                 GOTO(out, rc);
4196
4197         if (fld->lsf_new) {
4198                 rc = fld_update_from_controller(&env, fld);
4199                 if (rc != 0) {
4200                         CERROR("%s: cannot update controller: rc = %d\n",
4201                                mdt_obd_name(mdt), rc);
4202                         GOTO(out, rc);
4203                 }
4204         }
4205 out:
4206         lu_env_fini(&env);
4207         RETURN(rc);
4208 }
4209
4210 static int mdt_register_seq_exp(struct mdt_device *mdt)
4211 {
4212         struct seq_server_site  *ss = mdt_seq_site(mdt);
4213         char                    *lwp_name = NULL;
4214         int                     rc;
4215
4216         if (ss->ss_node_id == 0)
4217                 return 0;
4218
4219         OBD_ALLOC(lwp_name, MAX_OBD_NAME);
4220         if (lwp_name == NULL)
4221                 GOTO(out_free, rc = -ENOMEM);
4222
4223         rc = tgt_name2lwp_name(mdt_obd_name(mdt), lwp_name, MAX_OBD_NAME, 0);
4224         if (rc != 0)
4225                 GOTO(out_free, rc);
4226
4227         rc = lustre_register_lwp_item(lwp_name, &ss->ss_client_seq->lcs_exp,
4228                                       NULL, NULL);
4229         if (rc != 0)
4230                 GOTO(out_free, rc);
4231
4232         rc = lustre_register_lwp_item(lwp_name,
4233                                       &ss->ss_server_fld->lsf_control_exp,
4234                                       mdt_register_lwp_callback, mdt);
4235         if (rc != 0) {
4236                 lustre_deregister_lwp_item(&ss->ss_client_seq->lcs_exp);
4237                 ss->ss_client_seq->lcs_exp = NULL;
4238                 GOTO(out_free, rc);
4239         }
4240 out_free:
4241         if (lwp_name != NULL)
4242                 OBD_FREE(lwp_name, MAX_OBD_NAME);
4243
4244         return rc;
4245 }
4246
4247 /*
4248  * Init client sequence manager which is used by local MDS to talk to sequence
4249  * controller on remote node.
4250  */
4251 static int mdt_seq_init_cli(const struct lu_env *env, struct mdt_device *mdt)
4252 {
4253         struct seq_server_site  *ss = mdt_seq_site(mdt);
4254         int                     rc;
4255         char                    *prefix;
4256         ENTRY;
4257
4258         /* check if this is adding the first MDC and controller is not yet
4259          * initialized. */
4260         OBD_ALLOC_PTR(ss->ss_client_seq);
4261         if (ss->ss_client_seq == NULL)
4262                 RETURN(-ENOMEM);
4263
4264         OBD_ALLOC(prefix, MAX_OBD_NAME + 5);
4265         if (prefix == NULL) {
4266                 OBD_FREE_PTR(ss->ss_client_seq);
4267                 ss->ss_client_seq = NULL;
4268                 RETURN(-ENOMEM);
4269         }
4270
4271         /* Note: seq_client_fini will be called in seq_site_fini */
4272         snprintf(prefix, MAX_OBD_NAME + 5, "ctl-%s", mdt_obd_name(mdt));
4273         rc = seq_client_init(ss->ss_client_seq, NULL, LUSTRE_SEQ_METADATA,
4274                              prefix, ss->ss_node_id == 0 ?  ss->ss_control_seq :
4275                                                             NULL);
4276         OBD_FREE(prefix, MAX_OBD_NAME + 5);
4277         if (rc != 0) {
4278                 OBD_FREE_PTR(ss->ss_client_seq);
4279                 ss->ss_client_seq = NULL;
4280                 RETURN(rc);
4281         }
4282
4283         rc = seq_server_set_cli(env, ss->ss_server_seq, ss->ss_client_seq);
4284
4285         RETURN(rc);
4286 }
4287
4288 static int mdt_seq_init(const struct lu_env *env, struct mdt_device *mdt)
4289 {
4290         struct seq_server_site  *ss;
4291         int                     rc;
4292         ENTRY;
4293
4294         ss = mdt_seq_site(mdt);
4295         /* init sequence controller server(MDT0) */
4296         if (ss->ss_node_id == 0) {
4297                 OBD_ALLOC_PTR(ss->ss_control_seq);
4298                 if (ss->ss_control_seq == NULL)
4299                         RETURN(-ENOMEM);
4300
4301                 rc = seq_server_init(env, ss->ss_control_seq, mdt->mdt_bottom,
4302                                      mdt_obd_name(mdt), LUSTRE_SEQ_CONTROLLER,
4303                                      ss);
4304                 if (rc)
4305                         GOTO(out_seq_fini, rc);
4306         }
4307
4308         /* Init normal sequence server */
4309         OBD_ALLOC_PTR(ss->ss_server_seq);
4310         if (ss->ss_server_seq == NULL)
4311                 GOTO(out_seq_fini, rc = -ENOMEM);
4312
4313         rc = seq_server_init(env, ss->ss_server_seq, mdt->mdt_bottom,
4314                              mdt_obd_name(mdt), LUSTRE_SEQ_SERVER, ss);
4315         if (rc)
4316                 GOTO(out_seq_fini, rc);
4317
4318         /* init seq client for seq server to talk to seq controller(MDT0) */
4319         rc = mdt_seq_init_cli(env, mdt);
4320         if (rc != 0)
4321                 GOTO(out_seq_fini, rc);
4322
4323         if (ss->ss_node_id != 0)
4324                 /* register controller export through lwp */
4325                 rc = mdt_register_seq_exp(mdt);
4326
4327         EXIT;
4328 out_seq_fini:
4329         if (rc)
4330                 mdt_seq_fini(env, mdt);
4331
4332         return rc;
4333 }
4334
4335 /*
4336  * FLD wrappers
4337  */
4338 static int mdt_fld_fini(const struct lu_env *env,
4339                         struct mdt_device *m)
4340 {
4341         struct seq_server_site *ss = mdt_seq_site(m);
4342         ENTRY;
4343
4344         if (ss && ss->ss_server_fld) {
4345                 fld_server_fini(env, ss->ss_server_fld);
4346                 OBD_FREE_PTR(ss->ss_server_fld);
4347                 ss->ss_server_fld = NULL;
4348         }
4349
4350         RETURN(0);
4351 }
4352
4353 static int mdt_fld_init(const struct lu_env *env,
4354                         const char *uuid,
4355                         struct mdt_device *m)
4356 {
4357         struct seq_server_site *ss;
4358         int rc;
4359         ENTRY;
4360
4361         ss = mdt_seq_site(m);
4362
4363         OBD_ALLOC_PTR(ss->ss_server_fld);
4364         if (ss->ss_server_fld == NULL)
4365                 RETURN(rc = -ENOMEM);
4366
4367         rc = fld_server_init(env, ss->ss_server_fld, m->mdt_bottom, uuid,
4368                              LU_SEQ_RANGE_MDT);
4369         if (rc) {
4370                 OBD_FREE_PTR(ss->ss_server_fld);
4371                 ss->ss_server_fld = NULL;
4372                 RETURN(rc);
4373         }
4374
4375         RETURN(0);
4376 }
4377
4378 static void mdt_stack_pre_fini(const struct lu_env *env,
4379                            struct mdt_device *m, struct lu_device *top)
4380 {
4381         struct lustre_cfg_bufs  *bufs;
4382         struct lustre_cfg       *lcfg;
4383         struct mdt_thread_info  *info;
4384         ENTRY;
4385
4386         LASSERT(top);
4387
4388         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
4389         LASSERT(info != NULL);
4390
4391         bufs = &info->mti_u.bufs;
4392
4393         LASSERT(m->mdt_child_exp);
4394         LASSERT(m->mdt_child_exp->exp_obd);
4395
4396         /* process cleanup, pass mdt obd name to get obd umount flags */
4397         /* XXX: this is needed because all layers are referenced by
4398          * objects (some of them are pinned by osd, for example *
4399          * the proper solution should be a model where object used
4400          * by osd only doesn't have mdt/mdd slices -bzzz */
4401         lustre_cfg_bufs_reset(bufs, mdt_obd_name(m));
4402         lustre_cfg_bufs_set_string(bufs, 1, NULL);
4403         OBD_ALLOC(lcfg, lustre_cfg_len(bufs->lcfg_bufcount, bufs->lcfg_buflen));
4404         if (!lcfg)
4405                 RETURN_EXIT;
4406         lustre_cfg_init(lcfg, LCFG_PRE_CLEANUP, bufs);
4407
4408         top->ld_ops->ldo_process_config(env, top, lcfg);
4409         OBD_FREE(lcfg, lustre_cfg_len(lcfg->lcfg_bufcount, lcfg->lcfg_buflens));
4410         EXIT;
4411 }
4412
4413 static void mdt_stack_fini(const struct lu_env *env,
4414                            struct mdt_device *m, struct lu_device *top)
4415 {
4416         struct obd_device       *obd = mdt2obd_dev(m);
4417         struct lustre_cfg_bufs  *bufs;
4418         struct lustre_cfg       *lcfg;
4419         struct mdt_thread_info  *info;
4420         char                     flags[3] = "";
4421         ENTRY;
4422
4423         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
4424         LASSERT(info != NULL);
4425
4426         lu_dev_del_linkage(top->ld_site, top);
4427
4428         lu_site_purge(env, top->ld_site, -1);
4429
4430         bufs = &info->mti_u.bufs;
4431         /* process cleanup, pass mdt obd name to get obd umount flags */
4432         /* another purpose is to let all layers to release their objects */
4433         lustre_cfg_bufs_reset(bufs, mdt_obd_name(m));
4434         if (obd->obd_force)
4435                 strcat(flags, "F");
4436         if (obd->obd_fail)
4437                 strcat(flags, "A");
4438         lustre_cfg_bufs_set_string(bufs, 1, flags);
4439         OBD_ALLOC(lcfg, lustre_cfg_len(bufs->lcfg_bufcount, bufs->lcfg_buflen));
4440         if (!lcfg)
4441                 RETURN_EXIT;
4442         lustre_cfg_init(lcfg, LCFG_CLEANUP, bufs);
4443
4444         LASSERT(top);
4445         top->ld_ops->ldo_process_config(env, top, lcfg);
4446         OBD_FREE(lcfg, lustre_cfg_len(lcfg->lcfg_bufcount, lcfg->lcfg_buflens));
4447
4448         lu_site_purge(env, top->ld_site, -1);
4449
4450         m->mdt_child = NULL;
4451         m->mdt_bottom = NULL;
4452
4453         obd_disconnect(m->mdt_child_exp);
4454         m->mdt_child_exp = NULL;
4455
4456         obd_disconnect(m->mdt_bottom_exp);
4457         m->mdt_child_exp = NULL;
4458 }
4459
4460 static int mdt_connect_to_next(const struct lu_env *env, struct mdt_device *m,
4461                                const char *next, struct obd_export **exp)
4462 {
4463         struct obd_connect_data *data = NULL;
4464         struct obd_device       *obd;
4465         int                      rc;
4466         ENTRY;
4467
4468         OBD_ALLOC_PTR(data);
4469         if (data == NULL)
4470                 GOTO(out, rc = -ENOMEM);
4471
4472         obd = class_name2obd(next);
4473         if (obd == NULL) {
4474                 CERROR("%s: can't locate next device: %s\n",
4475                        mdt_obd_name(m), next);
4476                 GOTO(out, rc = -ENOTCONN);
4477         }
4478
4479         data->ocd_connect_flags = OBD_CONNECT_VERSION;
4480         data->ocd_version = LUSTRE_VERSION_CODE;
4481
4482         rc = obd_connect(NULL, exp, obd, &obd->obd_uuid, data, NULL);
4483         if (rc) {
4484                 CERROR("%s: cannot connect to next dev %s (%d)\n",
4485                        mdt_obd_name(m), next, rc);
4486                 GOTO(out, rc);
4487         }
4488
4489 out:
4490         if (data)
4491                 OBD_FREE_PTR(data);
4492         RETURN(rc);
4493 }
4494
4495 static int mdt_stack_init(const struct lu_env *env, struct mdt_device *mdt,
4496                           struct lustre_cfg *cfg)
4497 {
4498         char                   *dev = lustre_cfg_string(cfg, 0);
4499         int                     rc, name_size, uuid_size;
4500         char                   *name, *uuid, *p;
4501         struct lustre_cfg_bufs *bufs;
4502         struct lustre_cfg      *lcfg;
4503         struct obd_device      *obd;
4504         struct lustre_profile  *lprof;
4505         struct lu_site         *site;
4506         ENTRY;
4507
4508         /* in 1.8 we had the only device in the stack - MDS.
4509          * 2.0 introduces MDT, MDD, OSD; MDT starts others internally.
4510          * in 2.3 OSD is instantiated by obd_mount.c, so we need
4511          * to generate names and setup MDT, MDD. MDT will be using
4512          * generated name to connect to MDD. for MDD the next device
4513          * will be LOD with name taken from so called "profile" which
4514          * is generated by mount_option line
4515          *
4516          * 1.8 MGS generates config. commands like this:
4517          *   #06 (104)mount_option 0:  1:lustre-MDT0000  2:lustre-mdtlov
4518          *   #08 (120)setup   0:lustre-MDT0000  1:dev 2:type 3:lustre-MDT0000
4519          * 2.0 MGS generates config. commands like this:
4520          *   #07 (112)mount_option 0:  1:lustre-MDT0000  2:lustre-MDT0000-mdtlov
4521          *   #08 (160)setup   0:lustre-MDT0000  1:lustre-MDT0000_UUID  2:0
4522          *                    3:lustre-MDT0000-mdtlov  4:f
4523          *
4524          * we generate MDD name from MDT one, just replacing T with D
4525          *
4526          * after all the preparations, the logical equivalent will be
4527          *   #01 (160)setup   0:lustre-MDD0000  1:lustre-MDD0000_UUID  2:0
4528          *                    3:lustre-MDT0000-mdtlov  4:f
4529          *   #02 (160)setup   0:lustre-MDT0000  1:lustre-MDT0000_UUID  2:0
4530          *                    3:lustre-MDD0000  4:f
4531          *
4532          *  notice we build the stack from down to top: MDD first, then MDT */
4533
4534         name_size = MAX_OBD_NAME;
4535         uuid_size = MAX_OBD_NAME;
4536
4537         OBD_ALLOC(name, name_size);
4538         OBD_ALLOC(uuid, uuid_size);
4539         if (name == NULL || uuid == NULL)
4540                 GOTO(cleanup_mem, rc = -ENOMEM);
4541
4542         OBD_ALLOC_PTR(bufs);
4543         if (!bufs)
4544                 GOTO(cleanup_mem, rc = -ENOMEM);
4545
4546         strcpy(name, dev);
4547         p = strstr(name, "-MDT");
4548         if (p == NULL)
4549                 GOTO(free_bufs, rc = -ENOMEM);
4550         p[3] = 'D';
4551
4552         snprintf(uuid, MAX_OBD_NAME, "%s_UUID", name);
4553
4554         lprof = class_get_profile(lustre_cfg_string(cfg, 0));
4555         if (lprof == NULL || lprof->lp_dt == NULL) {
4556                 CERROR("can't find the profile: %s\n",
4557                        lustre_cfg_string(cfg, 0));
4558                 GOTO(free_bufs, rc = -EINVAL);
4559         }
4560
4561         lustre_cfg_bufs_reset(bufs, name);
4562         lustre_cfg_bufs_set_string(bufs, 1, LUSTRE_MDD_NAME);
4563         lustre_cfg_bufs_set_string(bufs, 2, uuid);
4564         lustre_cfg_bufs_set_string(bufs, 3, lprof->lp_dt);
4565
4566         OBD_ALLOC(lcfg, lustre_cfg_len(bufs->lcfg_bufcount, bufs->lcfg_buflen));
4567         if (!lcfg)
4568                 GOTO(put_profile, rc = -ENOMEM);
4569         lustre_cfg_init(lcfg, LCFG_ATTACH, bufs);
4570
4571         rc = class_attach(lcfg);
4572         if (rc)
4573                 GOTO(lcfg_cleanup, rc);
4574
4575         obd = class_name2obd(name);
4576         if (!obd) {
4577                 CERROR("Can not find obd %s (%s in config)\n",
4578                        MDD_OBD_NAME, lustre_cfg_string(cfg, 0));
4579                 GOTO(lcfg_cleanup, rc = -EINVAL);
4580         }
4581
4582         OBD_FREE(lcfg, lustre_cfg_len(lcfg->lcfg_bufcount, lcfg->lcfg_buflens));
4583
4584         lustre_cfg_bufs_reset(bufs, name);
4585         lustre_cfg_bufs_set_string(bufs, 1, uuid);
4586         lustre_cfg_bufs_set_string(bufs, 2, dev);
4587         lustre_cfg_bufs_set_string(bufs, 3, lprof->lp_dt);
4588
4589         OBD_ALLOC(lcfg, lustre_cfg_len(bufs->lcfg_bufcount, bufs->lcfg_buflen));
4590         if (!lcfg)
4591                 GOTO(class_detach, rc = -ENOMEM);
4592         lustre_cfg_init(lcfg, LCFG_SETUP, bufs);
4593
4594         rc = class_setup(obd, lcfg);
4595         if (rc)
4596                 GOTO(class_detach, rc);
4597
4598         /* connect to MDD we just setup */
4599         rc = mdt_connect_to_next(env, mdt, name, &mdt->mdt_child_exp);
4600         if (rc)
4601                 GOTO(class_detach, rc);
4602
4603         site = mdt->mdt_child_exp->exp_obd->obd_lu_dev->ld_site;
4604         LASSERT(site);
4605         LASSERT(mdt_lu_site(mdt) == NULL);
4606         mdt->mdt_lu_dev.ld_site = site;
4607         site->ls_top_dev = &mdt->mdt_lu_dev;
4608         mdt->mdt_child = lu2md_dev(mdt->mdt_child_exp->exp_obd->obd_lu_dev);
4609
4610         /* now connect to bottom OSD */
4611         snprintf(name, MAX_OBD_NAME, "%s-osd", dev);
4612         rc = mdt_connect_to_next(env, mdt, name, &mdt->mdt_bottom_exp);
4613         if (rc)
4614                 GOTO(class_detach, rc);
4615         mdt->mdt_bottom =
4616                 lu2dt_dev(mdt->mdt_bottom_exp->exp_obd->obd_lu_dev);
4617
4618         rc = lu_env_refill((struct lu_env *)env);
4619         if (rc != 0)
4620                 CERROR("Failure to refill session: '%d'\n", rc);
4621
4622         lu_dev_add_linkage(site, &mdt->mdt_lu_dev);
4623
4624         EXIT;
4625 class_detach:
4626         if (rc)
4627                 class_detach(obd, lcfg);
4628 lcfg_cleanup:
4629         OBD_FREE(lcfg, lustre_cfg_len(lcfg->lcfg_bufcount, lcfg->lcfg_buflens));
4630 put_profile:
4631         class_put_profile(lprof);
4632 free_bufs:
4633         OBD_FREE_PTR(bufs);
4634 cleanup_mem:
4635         if (name)
4636                 OBD_FREE(name, name_size);
4637         if (uuid)
4638                 OBD_FREE(uuid, uuid_size);
4639         RETURN(rc);
4640 }
4641
4642 /* setup quota master target on MDT0 */
4643 static int mdt_quota_init(const struct lu_env *env, struct mdt_device *mdt,
4644                           struct lustre_cfg *cfg)
4645 {
4646         struct obd_device       *obd;
4647         char                    *dev = lustre_cfg_string(cfg, 0);
4648         char                    *qmtname, *uuid, *p;
4649         struct lustre_cfg_bufs  *bufs;
4650         struct lustre_cfg       *lcfg;
4651         struct lustre_profile   *lprof;
4652         struct obd_connect_data *data;
4653         int                      rc;
4654         ENTRY;
4655
4656         LASSERT(mdt->mdt_qmt_exp == NULL);
4657         LASSERT(mdt->mdt_qmt_dev == NULL);
4658
4659         /* quota master is on MDT0 only for now */
4660         if (mdt->mdt_seq_site.ss_node_id != 0)
4661                 RETURN(0);
4662
4663         /* MGS generates config commands which look as follows:
4664          *   #01 (160)setup   0:lustre-MDT0000  1:lustre-MDT0000_UUID  2:0
4665          *                    3:lustre-MDT0000-mdtlov  4:f
4666          *
4667          * We generate the QMT name from the MDT one, just replacing MD with QM
4668          * after all the preparations, the logical equivalent will be:
4669          *   #01 (160)setup   0:lustre-QMT0000  1:lustre-QMT0000_UUID  2:0
4670          *                    3:lustre-MDT0000-osd  4:f */
4671         OBD_ALLOC(qmtname, MAX_OBD_NAME);
4672         OBD_ALLOC(uuid, UUID_MAX);
4673         OBD_ALLOC_PTR(bufs);
4674         OBD_ALLOC_PTR(data);
4675         if (qmtname == NULL || uuid == NULL || bufs == NULL || data == NULL)
4676                 GOTO(cleanup_mem, rc = -ENOMEM);
4677
4678         strcpy(qmtname, dev);
4679         p = strstr(qmtname, "-MDT");
4680         if (p == NULL)
4681                 GOTO(cleanup_mem, rc = -ENOMEM);
4682         /* replace MD with QM */
4683         p[1] = 'Q';
4684         p[2] = 'M';
4685
4686         snprintf(uuid, UUID_MAX, "%s_UUID", qmtname);
4687
4688         lprof = class_get_profile(lustre_cfg_string(cfg, 0));
4689         if (lprof == NULL || lprof->lp_dt == NULL) {
4690                 CERROR("can't find profile for %s\n",
4691                        lustre_cfg_string(cfg, 0));
4692                 GOTO(cleanup_mem, rc = -EINVAL);
4693         }
4694
4695         lustre_cfg_bufs_reset(bufs, qmtname);
4696         lustre_cfg_bufs_set_string(bufs, 1, LUSTRE_QMT_NAME);
4697         lustre_cfg_bufs_set_string(bufs, 2, uuid);
4698         lustre_cfg_bufs_set_string(bufs, 3, lprof->lp_dt);
4699
4700         OBD_ALLOC(lcfg, lustre_cfg_len(bufs->lcfg_bufcount, bufs->lcfg_buflen));
4701         if (!lcfg)
4702                 GOTO(put_profile, rc = -ENOMEM);
4703         lustre_cfg_init(lcfg, LCFG_ATTACH, bufs);
4704
4705         rc = class_attach(lcfg);
4706         if (rc)
4707                 GOTO(lcfg_cleanup, rc);
4708
4709         obd = class_name2obd(qmtname);
4710         if (!obd) {
4711                 CERROR("Can not find obd %s (%s in config)\n", qmtname,
4712                        lustre_cfg_string(cfg, 0));
4713                 GOTO(lcfg_cleanup, rc = -EINVAL);
4714         }
4715
4716         OBD_FREE(lcfg, lustre_cfg_len(lcfg->lcfg_bufcount, lcfg->lcfg_buflens));
4717
4718         lustre_cfg_bufs_reset(bufs, qmtname);
4719         lustre_cfg_bufs_set_string(bufs, 1, uuid);
4720         lustre_cfg_bufs_set_string(bufs, 2, dev);
4721
4722         /* for quota, the next device should be the OSD device */
4723         lustre_cfg_bufs_set_string(bufs, 3,
4724                                    mdt->mdt_bottom->dd_lu_dev.ld_obd->obd_name);
4725
4726         OBD_ALLOC(lcfg, lustre_cfg_len(bufs->lcfg_bufcount, bufs->lcfg_buflen));
4727         if (!lcfg)
4728                 GOTO(class_detach, rc = -ENOMEM);
4729         lustre_cfg_init(lcfg, LCFG_SETUP, bufs);
4730
4731         rc = class_setup(obd, lcfg);
4732         if (rc)
4733                 GOTO(class_detach, rc);
4734
4735         mdt->mdt_qmt_dev = obd->obd_lu_dev;
4736
4737         /* configure local quota objects */
4738         rc = mdt->mdt_qmt_dev->ld_ops->ldo_prepare(env,
4739                                                    &mdt->mdt_lu_dev,
4740                                                    mdt->mdt_qmt_dev);
4741         if (rc)
4742                 GOTO(class_cleanup, rc);
4743
4744         /* connect to quota master target */
4745         data->ocd_connect_flags = OBD_CONNECT_VERSION;
4746         data->ocd_version = LUSTRE_VERSION_CODE;
4747         rc = obd_connect(NULL, &mdt->mdt_qmt_exp, obd, &obd->obd_uuid,
4748                          data, NULL);
4749         if (rc) {
4750                 CERROR("cannot connect to quota master device %s (%d)\n",
4751                        qmtname, rc);
4752                 GOTO(class_cleanup, rc);
4753         }
4754
4755         EXIT;
4756 class_cleanup:
4757         if (rc) {
4758                 class_manual_cleanup(obd);
4759                 mdt->mdt_qmt_dev = NULL;
4760         }
4761 class_detach:
4762         if (rc)
4763                 class_detach(obd, lcfg);
4764 lcfg_cleanup:
4765         OBD_FREE(lcfg, lustre_cfg_len(lcfg->lcfg_bufcount, lcfg->lcfg_buflens));
4766 put_profile:
4767         class_put_profile(lprof);
4768 cleanup_mem:
4769         if (bufs)
4770                 OBD_FREE_PTR(bufs);
4771         if (qmtname)
4772                 OBD_FREE(qmtname, MAX_OBD_NAME);
4773         if (uuid)
4774                 OBD_FREE(uuid, UUID_MAX);
4775         if (data)
4776                 OBD_FREE_PTR(data);
4777         return rc;
4778 }
4779
4780 /* Shutdown quota master target associated with mdt */
4781 static void mdt_quota_fini(const struct lu_env *env, struct mdt_device *mdt)
4782 {
4783         ENTRY;
4784
4785         if (mdt->mdt_qmt_exp == NULL)
4786                 RETURN_EXIT;
4787         LASSERT(mdt->mdt_qmt_dev != NULL);
4788
4789         /* the qmt automatically shuts down when the mdt disconnects */
4790         obd_disconnect(mdt->mdt_qmt_exp);
4791         mdt->mdt_qmt_exp = NULL;
4792         mdt->mdt_qmt_dev = NULL;
4793         EXIT;
4794 }
4795
4796 /* mdt_getxattr() is used from mdt_intent_getxattr(), use this wrapper
4797  * for now. This will be removed along with converting rest of MDT code
4798  * to use tgt_session_info */
4799 static int mdt_tgt_getxattr(struct tgt_session_info *tsi)
4800 {
4801         struct mdt_thread_info  *info = tsi2mdt_info(tsi);
4802         int                      rc;
4803
4804         rc = mdt_getxattr(info);
4805
4806         mdt_thread_info_fini(info);
4807         return rc;
4808 }
4809
4810 #define OBD_FAIL_OST_READ_NET   OBD_FAIL_OST_BRW_NET
4811 #define OBD_FAIL_OST_WRITE_NET  OBD_FAIL_OST_BRW_NET
4812 #define OST_BRW_READ    OST_READ
4813 #define OST_BRW_WRITE   OST_WRITE
4814
4815 static struct tgt_handler mdt_tgt_handlers[] = {
4816 TGT_RPC_HANDLER(MDS_FIRST_OPC,
4817                 0,                      MDS_CONNECT,    mdt_tgt_connect,
4818                 &RQF_CONNECT, LUSTRE_OBD_VERSION),
4819 TGT_RPC_HANDLER(MDS_FIRST_OPC,
4820                 0,                      MDS_DISCONNECT, tgt_disconnect,
4821                 &RQF_MDS_DISCONNECT, LUSTRE_OBD_VERSION),
4822 TGT_RPC_HANDLER(MDS_FIRST_OPC,
4823                 HABEO_REFERO,           MDS_SET_INFO,   mdt_set_info,
4824                 &RQF_OBD_SET_INFO, LUSTRE_MDS_VERSION),
4825 TGT_MDT_HDL(0,                          MDS_GET_INFO,   mdt_get_info),
4826 TGT_MDT_HDL(0           | HABEO_REFERO, MDS_GET_ROOT,   mdt_get_root),
4827 TGT_MDT_HDL(HABEO_CORPUS,               MDS_GETATTR,    mdt_getattr),
4828 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO, MDS_GETATTR_NAME,
4829                                                         mdt_getattr_name),
4830 TGT_MDT_HDL(HABEO_CORPUS,               MDS_GETXATTR,   mdt_tgt_getxattr),
4831 TGT_MDT_HDL(0           | HABEO_REFERO, MDS_STATFS,     mdt_statfs),
4832 TGT_MDT_HDL(0           | MUTABOR,      MDS_REINT,      mdt_reint),
4833 TGT_MDT_HDL(HABEO_CORPUS,               MDS_CLOSE,      mdt_close),
4834 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO, MDS_READPAGE,   mdt_readpage),
4835 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO, MDS_SYNC,       mdt_sync),
4836 TGT_MDT_HDL(0,                          MDS_QUOTACTL,   mdt_quotactl),
4837 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO | MUTABOR, MDS_HSM_PROGRESS,
4838                                                         mdt_hsm_progress),
4839 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO | MUTABOR, MDS_HSM_CT_REGISTER,
4840                                                         mdt_hsm_ct_register),
4841 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO | MUTABOR, MDS_HSM_CT_UNREGISTER,
4842                                                         mdt_hsm_ct_unregister),
4843 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO, MDS_HSM_STATE_GET,
4844                                                         mdt_hsm_state_get),
4845 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO | MUTABOR, MDS_HSM_STATE_SET,
4846                                                         mdt_hsm_state_set),
4847 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO, MDS_HSM_ACTION, mdt_hsm_action),
4848 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO, MDS_HSM_REQUEST,
4849                                                         mdt_hsm_request),
4850 TGT_MDT_HDL(HABEO_CLAVIS | HABEO_CORPUS | HABEO_REFERO | MUTABOR,
4851             MDS_SWAP_LAYOUTS,
4852             mdt_swap_layouts),
4853 };
4854
4855 static struct tgt_handler mdt_io_ops[] = {
4856 TGT_OST_HDL(HABEO_CORPUS | HABEO_REFERO, OST_BRW_READ,  tgt_brw_read),
4857 TGT_OST_HDL(HABEO_CORPUS | MUTABOR,      OST_BRW_WRITE, tgt_brw_write),
4858 TGT_OST_HDL(HABEO_CORPUS | HABEO_REFERO | MUTABOR,
4859                                          OST_PUNCH,     mdt_punch_hdl),
4860 TGT_OST_HDL(HABEO_CORPUS | HABEO_REFERO, OST_SYNC,      mdt_data_sync),
4861 };
4862
4863 static struct tgt_handler mdt_sec_ctx_ops[] = {
4864 TGT_SEC_HDL_VAR(0,                      SEC_CTX_INIT,     mdt_sec_ctx_handle),
4865 TGT_SEC_HDL_VAR(0,                      SEC_CTX_INIT_CONT,mdt_sec_ctx_handle),
4866 TGT_SEC_HDL_VAR(0,                      SEC_CTX_FINI,     mdt_sec_ctx_handle)
4867 };
4868
4869 static struct tgt_handler mdt_quota_ops[] = {
4870 TGT_QUOTA_HDL(HABEO_REFERO,             QUOTA_DQACQ,      mdt_quota_dqacq),
4871 };
4872
4873 static struct tgt_opc_slice mdt_common_slice[] = {
4874         {
4875                 .tos_opc_start  = MDS_FIRST_OPC,
4876                 .tos_opc_end    = MDS_LAST_OPC,
4877                 .tos_hs         = mdt_tgt_handlers
4878         },
4879         {
4880                 .tos_opc_start  = OBD_FIRST_OPC,
4881                 .tos_opc_end    = OBD_LAST_OPC,
4882                 .tos_hs         = tgt_obd_handlers
4883         },
4884         {
4885                 .tos_opc_start  = LDLM_FIRST_OPC,
4886                 .tos_opc_end    = LDLM_LAST_OPC,
4887                 .tos_hs         = tgt_dlm_handlers
4888         },
4889         {
4890                 .tos_opc_start  = SEC_FIRST_OPC,
4891                 .tos_opc_end    = SEC_LAST_OPC,
4892                 .tos_hs         = mdt_sec_ctx_ops
4893         },
4894         {
4895                 .tos_opc_start  = OUT_UPDATE_FIRST_OPC,
4896                 .tos_opc_end    = OUT_UPDATE_LAST_OPC,
4897                 .tos_hs         = tgt_out_handlers
4898         },
4899         {
4900                 .tos_opc_start  = FLD_FIRST_OPC,
4901                 .tos_opc_end    = FLD_LAST_OPC,
4902                 .tos_hs         = fld_handlers
4903         },
4904         {
4905                 .tos_opc_start  = SEQ_FIRST_OPC,
4906                 .tos_opc_end    = SEQ_LAST_OPC,
4907                 .tos_hs         = seq_handlers
4908         },
4909         {
4910                 .tos_opc_start  = QUOTA_DQACQ,
4911                 .tos_opc_end    = QUOTA_LAST_OPC,
4912                 .tos_hs         = mdt_quota_ops
4913         },
4914         {
4915                 .tos_opc_start  = LLOG_FIRST_OPC,
4916                 .tos_opc_end    = LLOG_LAST_OPC,
4917                 .tos_hs         = tgt_llog_handlers
4918         },
4919         {
4920                 .tos_opc_start  = LFSCK_FIRST_OPC,
4921                 .tos_opc_end    = LFSCK_LAST_OPC,
4922                 .tos_hs         = tgt_lfsck_handlers
4923         },
4924         {
4925                 .tos_opc_start  = OST_FIRST_OPC,
4926                 .tos_opc_end    = OST_LAST_OPC,
4927                 .tos_hs         = mdt_io_ops
4928         },
4929         {
4930                 .tos_hs         = NULL
4931         }
4932 };
4933
4934 static void mdt_fini(const struct lu_env *env, struct mdt_device *m)
4935 {
4936         struct md_device *next = m->mdt_child;
4937         struct lu_device *d = &m->mdt_lu_dev;
4938         struct obd_device *obd = mdt2obd_dev(m);
4939         struct lfsck_stop stop;
4940
4941         ENTRY;
4942         stop.ls_status = LS_PAUSED;
4943         stop.ls_flags = 0;
4944         next->md_ops->mdo_iocontrol(env, next, OBD_IOC_STOP_LFSCK, 0, &stop);
4945
4946         mdt_stack_pre_fini(env, m, md2lu_dev(m->mdt_child));
4947         ping_evictor_stop();
4948
4949         /* Remove the HSM /proc entry so the coordinator cannot be
4950          * restarted by a user while it's shutting down. */
4951         hsm_cdt_procfs_fini(m);
4952         mdt_hsm_cdt_stop(m);
4953
4954         mdt_llog_ctxt_unclone(env, m, LLOG_AGENT_ORIG_CTXT);
4955         mdt_llog_ctxt_unclone(env, m, LLOG_CHANGELOG_ORIG_CTXT);
4956
4957         if (m->mdt_namespace != NULL)
4958                 ldlm_namespace_free_prior(m->mdt_namespace, NULL,
4959                                           d->ld_obd->obd_force);
4960
4961         obd_exports_barrier(obd);
4962         obd_zombie_barrier();
4963
4964         mdt_quota_fini(env, m);
4965
4966         cfs_free_nidlist(&m->mdt_squash.rsi_nosquash_nids);
4967
4968         /* Calling the cleanup functions in the same order as in the mdt_init0
4969          * error path
4970          */
4971         mdt_procfs_fini(m);
4972
4973         target_recovery_fini(obd);
4974         upcall_cache_cleanup(m->mdt_identity_cache);
4975         m->mdt_identity_cache = NULL;
4976
4977         mdt_fs_cleanup(env, m);
4978
4979         tgt_fini(env, &m->mdt_lut);
4980
4981         mdt_hsm_cdt_fini(m);
4982
4983         if (m->mdt_namespace != NULL) {
4984                 ldlm_namespace_free_post(m->mdt_namespace);
4985                 d->ld_obd->obd_namespace = m->mdt_namespace = NULL;
4986         }
4987
4988         if (m->mdt_md_root != NULL) {
4989                 mdt_object_put(env, m->mdt_md_root);
4990                 m->mdt_md_root = NULL;
4991         }
4992
4993         mdt_seq_fini(env, m);
4994
4995         mdt_fld_fini(env, m);
4996
4997         /*
4998          * Finish the stack
4999          */
5000         mdt_stack_fini(env, m, md2lu_dev(m->mdt_child));
5001
5002         LASSERT(atomic_read(&d->ld_ref) == 0);
5003
5004         server_put_mount(mdt_obd_name(m), true);
5005
5006         EXIT;
5007 }
5008
5009 static int mdt_postrecov(const struct lu_env *, struct mdt_device *);
5010
5011 static int mdt_init0(const struct lu_env *env, struct mdt_device *m,
5012                      struct lu_device_type *ldt, struct lustre_cfg *cfg)
5013 {
5014         const struct dt_device_param *dt_conf;
5015         struct mdt_thread_info *info;
5016         struct obd_device *obd;
5017         const char *dev = lustre_cfg_string(cfg, 0);
5018         const char *num = lustre_cfg_string(cfg, 2);
5019         struct tg_grants_data *tgd = &m->mdt_lut.lut_tgd;
5020         struct lustre_mount_info *lmi = NULL;
5021         struct lustre_sb_info *lsi;
5022         struct lu_site *s;
5023         struct seq_server_site *ss_site;
5024         const char *identity_upcall = "NONE";
5025         struct md_device *next;
5026         int rc;
5027         long node_id;
5028         mntopt_t mntopts;
5029         ENTRY;
5030
5031         lu_device_init(&m->mdt_lu_dev, ldt);
5032         /*
5033          * Environment (env) might be missing mdt_thread_key values at that
5034          * point, if device is allocated when mdt_thread_key is in QUIESCENT
5035          * mode.
5036          *
5037          * Usually device allocation path doesn't use module key values, but
5038          * mdt has to do a lot of work here, so allocate key value.
5039          */
5040         rc = lu_env_refill((struct lu_env *)env);
5041         if (rc != 0)
5042                 RETURN(rc);
5043
5044         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
5045         LASSERT(info != NULL);
5046
5047         obd = class_name2obd(dev);
5048         LASSERT(obd != NULL);
5049
5050         m->mdt_max_mdsize = MAX_MD_SIZE; /* 4 stripes */
5051         m->mdt_opts.mo_evict_tgt_nids = 1;
5052         m->mdt_opts.mo_cos = MDT_COS_DEFAULT;
5053
5054         lmi = server_get_mount(dev);
5055         if (lmi == NULL) {
5056                 CERROR("Cannot get mount info for %s!\n", dev);
5057                 RETURN(-EFAULT);
5058         } else {
5059                 lsi = s2lsi(lmi->lmi_sb);
5060                 /* CMD is supported only in IAM mode */
5061                 LASSERT(num);
5062                 node_id = simple_strtol(num, NULL, 10);
5063                 obd->u.obt.obt_magic = OBT_MAGIC;
5064                 if (lsi->lsi_lmd != NULL &&
5065                     lsi->lsi_lmd->lmd_flags & LMD_FLG_SKIP_LFSCK)
5066                         m->mdt_skip_lfsck = 1;
5067         }
5068
5069         /* DoM files get IO lock at open by default */
5070         m->mdt_opts.mo_dom_lock = 1;
5071
5072         m->mdt_squash.rsi_uid = 0;
5073         m->mdt_squash.rsi_gid = 0;
5074         INIT_LIST_HEAD(&m->mdt_squash.rsi_nosquash_nids);
5075         init_rwsem(&m->mdt_squash.rsi_sem);
5076         spin_lock_init(&m->mdt_lock);
5077         m->mdt_enable_remote_dir = 0;
5078         m->mdt_enable_remote_dir_gid = 0;
5079
5080         atomic_set(&m->mdt_mds_mds_conns, 0);
5081         atomic_set(&m->mdt_async_commit_count, 0);
5082
5083         m->mdt_lu_dev.ld_ops = &mdt_lu_ops;
5084         m->mdt_lu_dev.ld_obd = obd;
5085         /* Set this lu_device to obd for error handling purposes. */
5086         obd->obd_lu_dev = &m->mdt_lu_dev;
5087
5088         /* init the stack */
5089         rc = mdt_stack_init((struct lu_env *)env, m, cfg);
5090         if (rc) {
5091                 CERROR("%s: Can't init device stack, rc %d\n",
5092                        mdt_obd_name(m), rc);
5093                 GOTO(err_lmi, rc);
5094         }
5095
5096         s = mdt_lu_site(m);
5097         ss_site = mdt_seq_site(m);
5098         s->ld_seq_site = ss_site;
5099         ss_site->ss_lu = s;
5100
5101         /* set server index */
5102         ss_site->ss_node_id = node_id;
5103
5104         /* failover is the default
5105          * FIXME: we do not failout mds0/mgs, which may cause some problems.
5106          * assumed whose ss_node_id == 0 XXX
5107          * */
5108         obd->obd_replayable = 1;
5109         /* No connection accepted until configurations will finish */
5110         obd->obd_no_conn = 1;
5111
5112         if (cfg->lcfg_bufcount > 4 && LUSTRE_CFG_BUFLEN(cfg, 4) > 0) {
5113                 char *str = lustre_cfg_string(cfg, 4);
5114                 if (strchr(str, 'n')) {
5115                         CWARN("%s: recovery disabled\n", mdt_obd_name(m));
5116                         obd->obd_replayable = 0;
5117                 }
5118         }
5119
5120         rc = mdt_fld_init(env, mdt_obd_name(m), m);
5121         if (rc)
5122                 GOTO(err_fini_stack, rc);
5123
5124         rc = mdt_seq_init(env, m);
5125         if (rc)
5126                 GOTO(err_fini_fld, rc);
5127
5128         snprintf(info->mti_u.ns_name, sizeof(info->mti_u.ns_name), "%s-%s",
5129                  LUSTRE_MDT_NAME, obd->obd_uuid.uuid);
5130         m->mdt_namespace = ldlm_namespace_new(obd, info->mti_u.ns_name,
5131                                               LDLM_NAMESPACE_SERVER,
5132                                               LDLM_NAMESPACE_GREEDY,
5133                                               LDLM_NS_TYPE_MDT);
5134         if (m->mdt_namespace == NULL)
5135                 GOTO(err_fini_seq, rc = -ENOMEM);
5136
5137         m->mdt_namespace->ns_lvbp = m;
5138         m->mdt_namespace->ns_lvbo = &mdt_lvbo;
5139
5140         ldlm_register_intent(m->mdt_namespace, mdt_intent_policy);
5141         /* set obd_namespace for compatibility with old code */
5142         obd->obd_namespace = m->mdt_namespace;
5143
5144         rc = mdt_hsm_cdt_init(m);
5145         if (rc != 0) {
5146                 CERROR("%s: error initializing coordinator, rc %d\n",
5147                        mdt_obd_name(m), rc);
5148                 GOTO(err_free_ns, rc);
5149         }
5150
5151         rc = tgt_init(env, &m->mdt_lut, obd, m->mdt_bottom, mdt_common_slice,
5152                       OBD_FAIL_MDS_ALL_REQUEST_NET,
5153                       OBD_FAIL_MDS_ALL_REPLY_NET);
5154         if (rc)
5155                 GOTO(err_free_hsm, rc);
5156
5157         /* Amount of available space excluded from granting and reserved
5158          * for metadata. It is in percentage and 50% is default value. */
5159         tgd->tgd_reserved_pcnt = 50;
5160
5161         if (ONE_MB_BRW_SIZE < (1U << tgd->tgd_blockbits))
5162                 m->mdt_brw_size = 1U << tgd->tgd_blockbits;
5163         else
5164                 m->mdt_brw_size = ONE_MB_BRW_SIZE;
5165
5166         rc = mdt_fs_setup(env, m, obd, lsi);
5167         if (rc)
5168                 GOTO(err_tgt, rc);
5169
5170         tgt_adapt_sptlrpc_conf(&m->mdt_lut);
5171
5172         next = m->mdt_child;
5173         dt_conf = next->md_ops->mdo_dtconf_get(env, next);
5174
5175         mntopts = dt_conf->ddp_mntopts;
5176
5177         if (mntopts & MNTOPT_USERXATTR)
5178                 m->mdt_opts.mo_user_xattr = 1;
5179         else
5180                 m->mdt_opts.mo_user_xattr = 0;
5181
5182         m->mdt_max_ea_size = dt_conf->ddp_max_ea_size;
5183
5184         if (mntopts & MNTOPT_ACL)
5185                 m->mdt_opts.mo_acl = 1;
5186         else
5187                 m->mdt_opts.mo_acl = 0;
5188
5189         /* XXX: to support suppgid for ACL, we enable identity_upcall
5190          * by default, otherwise, maybe got unexpected -EACCESS. */
5191         if (m->mdt_opts.mo_acl)
5192                 identity_upcall = MDT_IDENTITY_UPCALL_PATH;
5193
5194         m->mdt_identity_cache = upcall_cache_init(mdt_obd_name(m),
5195                                                 identity_upcall,
5196                                                 &mdt_identity_upcall_cache_ops);
5197         if (IS_ERR(m->mdt_identity_cache)) {
5198                 rc = PTR_ERR(m->mdt_identity_cache);
5199                 m->mdt_identity_cache = NULL;
5200                 GOTO(err_fs_cleanup, rc);
5201         }
5202
5203         rc = mdt_procfs_init(m, dev);
5204         if (rc) {
5205                 CERROR("Can't init MDT lprocfs, rc %d\n", rc);
5206                 GOTO(err_recovery, rc);
5207         }
5208
5209         rc = mdt_quota_init(env, m, cfg);
5210         if (rc)
5211                 GOTO(err_procfs, rc);
5212
5213         m->mdt_ldlm_client = &mdt2obd_dev(m)->obd_ldlm_client;
5214         ptlrpc_init_client(LDLM_CB_REQUEST_PORTAL, LDLM_CB_REPLY_PORTAL,
5215                            "mdt_ldlm_client", m->mdt_ldlm_client);
5216
5217         ping_evictor_start();
5218
5219         /* recovery will be started upon mdt_prepare()
5220          * when the whole stack is complete and ready
5221          * to serve the requests */
5222
5223         /* Reduce the initial timeout on an MDS because it doesn't need such
5224          * a long timeout as an OST does. Adaptive timeouts will adjust this
5225          * value appropriately. */
5226         if (ldlm_timeout == LDLM_TIMEOUT_DEFAULT)
5227                 ldlm_timeout = MDS_LDLM_TIMEOUT_DEFAULT;
5228
5229         RETURN(0);
5230 err_procfs:
5231         mdt_procfs_fini(m);
5232 err_recovery:
5233         target_recovery_fini(obd);
5234         upcall_cache_cleanup(m->mdt_identity_cache);
5235         m->mdt_identity_cache = NULL;
5236 err_fs_cleanup:
5237         mdt_fs_cleanup(env, m);
5238 err_tgt:
5239         tgt_fini(env, &m->mdt_lut);
5240 err_free_hsm:
5241         mdt_hsm_cdt_fini(m);
5242 err_free_ns:
5243         ldlm_namespace_free(m->mdt_namespace, NULL, 0);
5244         obd->obd_namespace = m->mdt_namespace = NULL;
5245 err_fini_seq:
5246         mdt_seq_fini(env, m);
5247 err_fini_fld:
5248         mdt_fld_fini(env, m);
5249 err_fini_stack:
5250         mdt_stack_fini(env, m, md2lu_dev(m->mdt_child));
5251 err_lmi:
5252         if (lmi)
5253                 server_put_mount(dev, true);
5254         return(rc);
5255 }
5256
5257 /* For interoperability, the left element is old parameter, the right one
5258  * is the new version of the parameter, if some parameter is deprecated,
5259  * the new version should be set as NULL. */
5260 static struct cfg_interop_param mdt_interop_param[] = {
5261         { "mdt.group_upcall",   NULL },
5262         { "mdt.quota_type",     NULL },
5263         { "mdd.quota_type",     NULL },
5264         { "mdt.som",            NULL },
5265         { "mdt.rootsquash",     "mdt.root_squash" },
5266         { "mdt.nosquash_nid",   "mdt.nosquash_nids" },
5267         { NULL }
5268 };
5269
5270 /* used by MGS to process specific configurations */
5271 static int mdt_process_config(const struct lu_env *env,
5272                               struct lu_device *d, struct lustre_cfg *cfg)
5273 {
5274         struct mdt_device *m = mdt_dev(d);
5275         struct md_device *md_next = m->mdt_child;
5276         struct lu_device *next = md2lu_dev(md_next);
5277         int rc;
5278         ENTRY;
5279
5280         switch (cfg->lcfg_command) {
5281         case LCFG_PARAM: {
5282                 struct obd_device          *obd = d->ld_obd;
5283
5284                 /* For interoperability */
5285                 struct cfg_interop_param   *ptr = NULL;
5286                 struct lustre_cfg          *old_cfg = NULL;
5287                 char                       *param = NULL;
5288
5289                 param = lustre_cfg_string(cfg, 1);
5290                 if (param == NULL) {
5291                         CERROR("param is empty\n");
5292                         rc = -EINVAL;
5293                         break;
5294                 }
5295
5296                 ptr = class_find_old_param(param, mdt_interop_param);
5297                 if (ptr != NULL) {
5298                         if (ptr->new_param == NULL) {
5299                                 rc = 0;
5300                                 CWARN("For interoperability, skip this %s."
5301                                       " It is obsolete.\n", ptr->old_param);
5302                                 break;
5303                         }
5304
5305                         CWARN("Found old param %s, changed it to %s.\n",
5306                               ptr->old_param, ptr->new_param);
5307
5308                         old_cfg = cfg;
5309                         cfg = lustre_cfg_rename(old_cfg, ptr->new_param);
5310                         if (IS_ERR(cfg)) {
5311                                 rc = PTR_ERR(cfg);
5312                                 break;
5313                         }
5314                 }
5315
5316                 rc = class_process_proc_param(PARAM_MDT, obd->obd_vars,
5317                                               cfg, obd);
5318                 if (rc > 0 || rc == -ENOSYS) {
5319                         /* is it an HSM var ? */
5320                         rc = class_process_proc_param(PARAM_HSM,
5321                                                       hsm_cdt_get_proc_vars(),
5322                                                       cfg, obd);
5323                         if (rc > 0 || rc == -ENOSYS)
5324                                 /* we don't understand; pass it on */
5325                                 rc = next->ld_ops->ldo_process_config(env, next,
5326                                                                       cfg);
5327                 }
5328
5329                 if (old_cfg)
5330                         OBD_FREE(cfg, lustre_cfg_len(cfg->lcfg_bufcount,
5331                                                      cfg->lcfg_buflens));
5332                 break;
5333         }
5334         default:
5335                 /* others are passed further */
5336                 rc = next->ld_ops->ldo_process_config(env, next, cfg);
5337                 break;
5338         }
5339         RETURN(rc);
5340 }
5341
5342 static struct lu_object *mdt_object_alloc(const struct lu_env *env,
5343                                           const struct lu_object_header *hdr,
5344                                           struct lu_device *d)
5345 {
5346         struct mdt_object *mo;
5347
5348         ENTRY;
5349
5350         OBD_SLAB_ALLOC_PTR_GFP(mo, mdt_object_kmem, GFP_NOFS);
5351         if (mo != NULL) {
5352                 struct lu_object *o;
5353                 struct lu_object_header *h;
5354
5355                 o = &mo->mot_obj;
5356                 h = &mo->mot_header;
5357                 lu_object_header_init(h);
5358                 lu_object_init(o, h, d);
5359                 lu_object_add_top(h, o);
5360                 o->lo_ops = &mdt_obj_ops;
5361                 spin_lock_init(&mo->mot_write_lock);
5362                 mutex_init(&mo->mot_lov_mutex);
5363                 init_rwsem(&mo->mot_dom_sem);
5364                 init_rwsem(&mo->mot_open_sem);
5365                 atomic_set(&mo->mot_open_count, 0);
5366                 RETURN(o);
5367         }
5368         RETURN(NULL);
5369 }
5370
5371 static int mdt_object_init(const struct lu_env *env, struct lu_object *o,
5372                            const struct lu_object_conf *unused)
5373 {
5374         struct mdt_device *d = mdt_dev(o->lo_dev);
5375         struct lu_device  *under;
5376         struct lu_object  *below;
5377         int                rc = 0;
5378         ENTRY;
5379
5380         CDEBUG(D_INFO, "object init, fid = "DFID"\n",
5381                PFID(lu_object_fid(o)));
5382
5383         under = &d->mdt_child->md_lu_dev;
5384         below = under->ld_ops->ldo_object_alloc(env, o->lo_header, under);
5385         if (below != NULL) {
5386                 lu_object_add(o, below);
5387         } else
5388                 rc = -ENOMEM;
5389
5390         RETURN(rc);
5391 }
5392
5393 static void mdt_object_free(const struct lu_env *env, struct lu_object *o)
5394 {
5395         struct mdt_object *mo = mdt_obj(o);
5396         struct lu_object_header *h;
5397         ENTRY;
5398
5399         h = o->lo_header;
5400         CDEBUG(D_INFO, "object free, fid = "DFID"\n",
5401                PFID(lu_object_fid(o)));
5402
5403         LASSERT(atomic_read(&mo->mot_open_count) == 0);
5404         LASSERT(atomic_read(&mo->mot_lease_count) == 0);
5405
5406         lu_object_fini(o);
5407         lu_object_header_fini(h);
5408         OBD_SLAB_FREE_PTR(mo, mdt_object_kmem);
5409
5410         EXIT;
5411 }
5412
5413 static int mdt_object_print(const struct lu_env *env, void *cookie,
5414                             lu_printer_t p, const struct lu_object *o)
5415 {
5416         struct mdt_object *mdto = mdt_obj((struct lu_object *)o);
5417
5418         return (*p)(env, cookie,
5419                     LUSTRE_MDT_NAME"-object@%p(%s %s, writecount=%d)",
5420                     mdto, mdto->mot_lov_created ? "lov_created" : "",
5421                     mdto->mot_cache_attr ? "cache_attr" : "",
5422                     mdto->mot_write_count);
5423 }
5424
5425 static int mdt_prepare(const struct lu_env *env,
5426                 struct lu_device *pdev,
5427                 struct lu_device *cdev)
5428 {
5429         struct mdt_device *mdt = mdt_dev(cdev);
5430         struct lu_device *next = &mdt->mdt_child->md_lu_dev;
5431         struct obd_device *obd = cdev->ld_obd;
5432         int rc;
5433
5434         ENTRY;
5435
5436         LASSERT(obd);
5437
5438         rc = next->ld_ops->ldo_prepare(env, cdev, next);
5439         if (rc)
5440                 RETURN(rc);
5441
5442         rc = mdt_llog_ctxt_clone(env, mdt, LLOG_CHANGELOG_ORIG_CTXT);
5443         if (rc)
5444                 RETURN(rc);
5445
5446         rc = mdt_llog_ctxt_clone(env, mdt, LLOG_AGENT_ORIG_CTXT);
5447         if (rc)
5448                 RETURN(rc);
5449
5450         rc = lfsck_register_namespace(env, mdt->mdt_bottom, mdt->mdt_namespace);
5451         /* The LFSCK instance is registered just now, so it must be there when
5452          * register the namespace to such instance. */
5453         LASSERTF(rc == 0, "register namespace failed: rc = %d\n", rc);
5454
5455         if (mdt->mdt_seq_site.ss_node_id == 0) {
5456                 rc = mdt->mdt_child->md_ops->mdo_root_get(env, mdt->mdt_child,
5457                                                          &mdt->mdt_md_root_fid);
5458                 if (rc)
5459                         RETURN(rc);
5460         }
5461
5462         LASSERT(!test_bit(MDT_FL_CFGLOG, &mdt->mdt_state));
5463
5464         target_recovery_init(&mdt->mdt_lut, tgt_request_handle);
5465         set_bit(MDT_FL_CFGLOG, &mdt->mdt_state);
5466         LASSERT(obd->obd_no_conn);
5467         spin_lock(&obd->obd_dev_lock);
5468         obd->obd_no_conn = 0;
5469         spin_unlock(&obd->obd_dev_lock);
5470
5471         if (obd->obd_recovering == 0)
5472                 mdt_postrecov(env, mdt);
5473
5474         RETURN(rc);
5475 }
5476
5477 const struct lu_device_operations mdt_lu_ops = {
5478         .ldo_object_alloc   = mdt_object_alloc,
5479         .ldo_process_config = mdt_process_config,
5480         .ldo_prepare        = mdt_prepare,
5481 };
5482
5483 static const struct lu_object_operations mdt_obj_ops = {
5484         .loo_object_init    = mdt_object_init,
5485         .loo_object_free    = mdt_object_free,
5486         .loo_object_print   = mdt_object_print
5487 };
5488
5489 static int mdt_obd_set_info_async(const struct lu_env *env,
5490                                   struct obd_export *exp,
5491                                   __u32 keylen, void *key,
5492                                   __u32 vallen, void *val,
5493                                   struct ptlrpc_request_set *set)
5494 {
5495         int rc;
5496
5497         ENTRY;
5498
5499         if (KEY_IS(KEY_SPTLRPC_CONF)) {
5500                 rc = tgt_adapt_sptlrpc_conf(class_exp2tgt(exp));
5501                 RETURN(rc);
5502         }
5503
5504         RETURN(0);
5505 }
5506
5507 /**
5508  * Match client and server connection feature flags.
5509  *
5510  * Compute the compatibility flags for a connection request based on
5511  * features mutually supported by client and server.
5512  *
5513  * The obd_export::exp_connect_data.ocd_connect_flags field in \a exp
5514  * must not be updated here, otherwise a partially initialized value may
5515  * be exposed. After the connection request is successfully processed,
5516  * the top-level MDT connect request handler atomically updates the export
5517  * connect flags from the obd_connect_data::ocd_connect_flags field of the
5518  * reply. \see mdt_connect().
5519  *
5520  * Before 2.7.50 clients will send a struct obd_connect_data_v1 rather than a
5521  * full struct obd_connect_data. So care must be taken when accessing fields
5522  * that are not present in struct obd_connect_data_v1. See LU-16.
5523  *
5524  * \param exp   the obd_export associated with this client/target pair
5525  * \param mdt   the target device for the connection
5526  * \param data  stores data for this connect request
5527  *
5528  * \retval 0       success
5529  * \retval -EPROTO \a data unexpectedly has zero obd_connect_data::ocd_brw_size
5530  * \retval -EBADE  client and server feature requirements are incompatible
5531  */
5532 static int mdt_connect_internal(const struct lu_env *env,
5533                                 struct obd_export *exp,
5534                                 struct mdt_device *mdt,
5535                                 struct obd_connect_data *data, bool reconnect)
5536 {
5537         LASSERT(data != NULL);
5538
5539         data->ocd_connect_flags &= MDT_CONNECT_SUPPORTED;
5540
5541         if (mdt->mdt_bottom->dd_rdonly &&
5542             !(data->ocd_connect_flags & OBD_CONNECT_MDS_MDS) &&
5543             !(data->ocd_connect_flags & OBD_CONNECT_RDONLY))
5544                 RETURN(-EACCES);
5545
5546         if (data->ocd_connect_flags & OBD_CONNECT_FLAGS2)
5547                 data->ocd_connect_flags2 &= MDT_CONNECT_SUPPORTED2;
5548
5549         data->ocd_ibits_known &= MDS_INODELOCK_FULL;
5550
5551         if (!mdt->mdt_opts.mo_acl)
5552                 data->ocd_connect_flags &= ~OBD_CONNECT_ACL;
5553
5554         if (!mdt->mdt_opts.mo_user_xattr)
5555                 data->ocd_connect_flags &= ~OBD_CONNECT_XATTR;
5556
5557         if (OCD_HAS_FLAG(data, BRW_SIZE)) {
5558                 data->ocd_brw_size = min(data->ocd_brw_size,
5559                                          mdt->mdt_brw_size);
5560                 if (data->ocd_brw_size == 0) {
5561                         CERROR("%s: cli %s/%p ocd_connect_flags: %#llx "
5562                                "ocd_version: %x ocd_grant: %d ocd_index: %u "
5563                                "ocd_brw_size unexpectedly zero, network data "
5564                                "corruption? Refusing to connect this client\n",
5565                                mdt_obd_name(mdt),
5566                                exp->exp_client_uuid.uuid,
5567                                exp, data->ocd_connect_flags, data->ocd_version,
5568                                data->ocd_grant, data->ocd_index);
5569                         return -EPROTO;
5570                 }
5571         }
5572
5573         if (OCD_HAS_FLAG(data, GRANT_PARAM)) {
5574                 struct dt_device_param *ddp = &mdt->mdt_lut.lut_dt_conf;
5575
5576                 /* client is reporting its page size, for future use */
5577                 exp->exp_target_data.ted_pagebits = data->ocd_grant_blkbits;
5578                 data->ocd_grant_blkbits  = mdt->mdt_lut.lut_tgd.tgd_blockbits;
5579                 /* ddp_inodespace may not be power-of-two value, eg. for ldiskfs
5580                  * it's LDISKFS_DIR_REC_LEN(20) = 28. */
5581                 data->ocd_grant_inobits = fls(ddp->ddp_inodespace - 1);
5582                 /* ocd_grant_tax_kb is in 1K byte blocks */
5583                 data->ocd_grant_tax_kb = ddp->ddp_extent_tax >> 10;
5584                 data->ocd_grant_max_blks = ddp->ddp_max_extent_blks;
5585         }
5586
5587         if (OCD_HAS_FLAG(data, GRANT)) {
5588                 /* Save connect_data we have so far because tgt_grant_connect()
5589                  * uses it to calculate grant. */
5590                 exp->exp_connect_data = *data;
5591                 tgt_grant_connect(env, exp, data, !reconnect);
5592         }
5593
5594         if (OCD_HAS_FLAG(data, MAXBYTES))
5595                 data->ocd_maxbytes = mdt->mdt_lut.lut_dt_conf.ddp_maxbytes;
5596
5597         /* NB: Disregard the rule against updating
5598          * exp_connect_data.ocd_connect_flags in this case, since
5599          * tgt_client_new() needs to know if this is a lightweight
5600          * connection, and it is safe to expose this flag before
5601          * connection processing completes. */
5602         if (data->ocd_connect_flags & OBD_CONNECT_LIGHTWEIGHT) {
5603                 spin_lock(&exp->exp_lock);
5604                 *exp_connect_flags_ptr(exp) |= OBD_CONNECT_LIGHTWEIGHT;
5605                 spin_unlock(&exp->exp_lock);
5606         }
5607
5608         data->ocd_version = LUSTRE_VERSION_CODE;
5609
5610         if ((data->ocd_connect_flags & OBD_CONNECT_FID) == 0) {
5611                 CWARN("%s: MDS requires FID support, but client not\n",
5612                       mdt_obd_name(mdt));
5613                 return -EBADE;
5614         }
5615
5616         if (OCD_HAS_FLAG(data, PINGLESS)) {
5617                 if (ptlrpc_pinger_suppress_pings()) {
5618                         spin_lock(&exp->exp_obd->obd_dev_lock);
5619                         list_del_init(&exp->exp_obd_chain_timed);
5620                         spin_unlock(&exp->exp_obd->obd_dev_lock);
5621                 } else {
5622                         data->ocd_connect_flags &= ~OBD_CONNECT_PINGLESS;
5623                 }
5624         }
5625
5626         data->ocd_max_easize = mdt->mdt_max_ea_size;
5627
5628         /* NB: Disregard the rule against updating
5629          * exp_connect_data.ocd_connect_flags in this case, since
5630          * tgt_client_new() needs to know if this is client supports
5631          * multiple modify RPCs, and it is safe to expose this flag before
5632          * connection processing completes. */
5633         if (data->ocd_connect_flags & OBD_CONNECT_MULTIMODRPCS) {
5634                 data->ocd_maxmodrpcs = max_mod_rpcs_per_client;
5635                 spin_lock(&exp->exp_lock);
5636                 *exp_connect_flags_ptr(exp) |= OBD_CONNECT_MULTIMODRPCS;
5637                 spin_unlock(&exp->exp_lock);
5638         }
5639
5640         if (OCD_HAS_FLAG(data, CKSUM)) {
5641                 __u32 cksum_types = data->ocd_cksum_types;
5642
5643                 /* The client set in ocd_cksum_types the checksum types it
5644                  * supports. We have to mask off the algorithms that we don't
5645                  * support */
5646                 data->ocd_cksum_types &= cksum_types_supported_server();
5647
5648                 if (unlikely(data->ocd_cksum_types == 0)) {
5649                         CERROR("%s: Connect with checksum support but no "
5650                                "ocd_cksum_types is set\n",
5651                                exp->exp_obd->obd_name);
5652                         RETURN(-EPROTO);
5653                 }
5654
5655                 CDEBUG(D_RPCTRACE, "%s: cli %s supports cksum type %x, return "
5656                        "%x\n", exp->exp_obd->obd_name, obd_export_nid2str(exp),
5657                        cksum_types, data->ocd_cksum_types);
5658         } else {
5659                 /* This client does not support OBD_CONNECT_CKSUM
5660                  * fall back to CRC32 */
5661                 CDEBUG(D_RPCTRACE, "%s: cli %s does not support "
5662                        "OBD_CONNECT_CKSUM, CRC32 will be used\n",
5663                        exp->exp_obd->obd_name, obd_export_nid2str(exp));
5664         }
5665
5666         return 0;
5667 }
5668
5669 static int mdt_ctxt_add_dirty_flag(struct lu_env *env,
5670                                    struct mdt_thread_info *info,
5671                                    struct mdt_file_data *mfd)
5672 {
5673         struct lu_context ses;
5674         int rc;
5675         ENTRY;
5676
5677         rc = lu_context_init(&ses, LCT_SERVER_SESSION);
5678         if (rc)
5679                 RETURN(rc);
5680
5681         env->le_ses = &ses;
5682         lu_context_enter(&ses);
5683
5684         mdt_ucred(info)->uc_valid = UCRED_OLD;
5685         rc = mdt_add_dirty_flag(info, mfd->mfd_object, &info->mti_attr);
5686
5687         lu_context_exit(&ses);
5688         lu_context_fini(&ses);
5689         env->le_ses = NULL;
5690
5691         RETURN(rc);
5692 }
5693
5694 static int mdt_export_cleanup(struct obd_export *exp)
5695 {
5696         struct list_head         closing_list;
5697         struct mdt_export_data  *med = &exp->exp_mdt_data;
5698         struct obd_device       *obd = exp->exp_obd;
5699         struct mdt_device       *mdt;
5700         struct mdt_thread_info  *info;
5701         struct lu_env            env;
5702         struct mdt_file_data    *mfd, *n;
5703         int rc = 0;
5704         ENTRY;
5705
5706         INIT_LIST_HEAD(&closing_list);
5707         spin_lock(&med->med_open_lock);
5708         while (!list_empty(&med->med_open_head)) {
5709                 struct list_head *tmp = med->med_open_head.next;
5710                 mfd = list_entry(tmp, struct mdt_file_data, mfd_list);
5711
5712                 /* Remove mfd handle so it can't be found again.
5713                  * We are consuming the mfd_list reference here. */
5714                 class_handle_unhash(&mfd->mfd_handle);
5715                 list_move_tail(&mfd->mfd_list, &closing_list);
5716         }
5717         spin_unlock(&med->med_open_lock);
5718         mdt = mdt_dev(obd->obd_lu_dev);
5719         LASSERT(mdt != NULL);
5720
5721         rc = lu_env_init(&env, LCT_MD_THREAD);
5722         if (rc)
5723                 RETURN(rc);
5724
5725         info = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
5726         LASSERT(info != NULL);
5727         memset(info, 0, sizeof *info);
5728         info->mti_env = &env;
5729         info->mti_mdt = mdt;
5730         info->mti_exp = exp;
5731
5732         mdt_hsm_agent_unregister(info, &exp->exp_client_uuid);
5733         if (!list_empty(&closing_list)) {
5734                 struct md_attr *ma = &info->mti_attr;
5735
5736                 /* Close any open files (which may also cause orphan
5737                  * unlinking). */
5738                 list_for_each_entry_safe(mfd, n, &closing_list, mfd_list) {
5739                         list_del_init(&mfd->mfd_list);
5740                         ma->ma_need = ma->ma_valid = 0;
5741
5742                         /* This file is being closed due to an eviction, it
5743                          * could have been modified and now dirty regarding to
5744                          * HSM archive, check this!
5745                          * The logic here is to mark a file dirty if there's a
5746                          * chance it was dirtied before the client was evicted,
5747                          * so that we don't have to wait for a release attempt
5748                          * before finding out the file was actually dirty and
5749                          * fail the release. Aggressively marking it dirty here
5750                          * will cause the policy engine to attempt to
5751                          * re-archive it; when rearchiving, we can compare the
5752                          * current version to the HSM data_version and make the
5753                          * archive request into a noop if it's not actually
5754                          * dirty.
5755                          */
5756                         if (mfd->mfd_mode & FMODE_WRITE)
5757                                 rc = mdt_ctxt_add_dirty_flag(&env, info, mfd);
5758
5759                         /* Don't unlink orphan on failover umount, LU-184 */
5760                         if (exp->exp_flags & OBD_OPT_FAILOVER) {
5761                                 ma->ma_valid = MA_FLAGS;
5762                                 ma->ma_attr_flags |= MDS_KEEP_ORPHAN;
5763                         }
5764                         mdt_mfd_close(info, mfd);
5765                 }
5766         }
5767         info->mti_mdt = NULL;
5768         /* cleanup client slot early */
5769         /* Do not erase record for recoverable client. */
5770         if (!(exp->exp_flags & OBD_OPT_FAILOVER) || exp->exp_failed)
5771                 tgt_client_del(&env, exp);
5772         lu_env_fini(&env);
5773
5774         RETURN(rc);
5775 }
5776
5777 static inline void mdt_enable_slc(struct mdt_device *mdt)
5778 {
5779         if (mdt->mdt_lut.lut_sync_lock_cancel == NEVER_SYNC_ON_CANCEL)
5780                 mdt->mdt_lut.lut_sync_lock_cancel = BLOCKING_SYNC_ON_CANCEL;
5781 }
5782
5783 static inline void mdt_disable_slc(struct mdt_device *mdt)
5784 {
5785         if (mdt->mdt_lut.lut_sync_lock_cancel == BLOCKING_SYNC_ON_CANCEL)
5786                 mdt->mdt_lut.lut_sync_lock_cancel = NEVER_SYNC_ON_CANCEL;
5787 }
5788
5789 static int mdt_obd_disconnect(struct obd_export *exp)
5790 {
5791         int rc;
5792
5793         ENTRY;
5794
5795         LASSERT(exp);
5796         class_export_get(exp);
5797
5798         if (!(exp->exp_flags & OBD_OPT_FORCE))
5799                 tgt_grant_sanity_check(exp->exp_obd, __func__);
5800
5801         if ((exp_connect_flags(exp) & OBD_CONNECT_MDS_MDS) &&
5802             !(exp_connect_flags(exp) & OBD_CONNECT_LIGHTWEIGHT)) {
5803                 struct mdt_device *mdt = mdt_dev(exp->exp_obd->obd_lu_dev);
5804
5805                 if (atomic_dec_and_test(&mdt->mdt_mds_mds_conns))
5806                         mdt_disable_slc(mdt);
5807         }
5808
5809         rc = server_disconnect_export(exp);
5810         if (rc != 0)
5811                 CDEBUG(D_IOCTL, "server disconnect error: rc = %d\n", rc);
5812
5813         tgt_grant_discard(exp);
5814
5815         rc = mdt_export_cleanup(exp);
5816         nodemap_del_member(exp);
5817         class_export_put(exp);
5818         RETURN(rc);
5819 }
5820
5821 /* mds_connect copy */
5822 static int mdt_obd_connect(const struct lu_env *env,
5823                            struct obd_export **exp, struct obd_device *obd,
5824                            struct obd_uuid *cluuid,
5825                            struct obd_connect_data *data,
5826                            void *localdata)
5827 {
5828         struct obd_export       *lexp;
5829         struct lustre_handle    conn = { 0 };
5830         struct mdt_device       *mdt;
5831         int                      rc;
5832         lnet_nid_t              *client_nid = localdata;
5833         ENTRY;
5834
5835         LASSERT(env != NULL);
5836         LASSERT(data != NULL);
5837
5838         if (!exp || !obd || !cluuid)
5839                 RETURN(-EINVAL);
5840
5841         mdt = mdt_dev(obd->obd_lu_dev);
5842
5843         if ((data->ocd_connect_flags & OBD_CONNECT_MDS_MDS) &&
5844             !(data->ocd_connect_flags & OBD_CONNECT_LIGHTWEIGHT)) {
5845                 atomic_inc(&mdt->mdt_mds_mds_conns);
5846                 mdt_enable_slc(mdt);
5847         }
5848
5849         /*
5850          * first, check whether the stack is ready to handle requests
5851          * XXX: probably not very appropriate method is used now
5852          *      at some point we should find a better one
5853          */
5854         if (!test_bit(MDT_FL_SYNCED, &mdt->mdt_state) &&
5855             !(data->ocd_connect_flags & OBD_CONNECT_LIGHTWEIGHT) &&
5856             !(data->ocd_connect_flags & OBD_CONNECT_MDS_MDS)) {
5857                 rc = obd_get_info(env, mdt->mdt_child_exp,
5858                                   sizeof(KEY_OSP_CONNECTED),
5859                                   KEY_OSP_CONNECTED, NULL, NULL);
5860                 if (rc)
5861                         RETURN(-EAGAIN);
5862                 set_bit(MDT_FL_SYNCED, &mdt->mdt_state);
5863         }
5864
5865         rc = class_connect(&conn, obd, cluuid);
5866         if (rc)
5867                 RETURN(rc);
5868
5869         lexp = class_conn2export(&conn);
5870         LASSERT(lexp != NULL);
5871
5872         rc = nodemap_add_member(*client_nid, lexp);
5873         if (rc != 0 && rc != -EEXIST)
5874                 GOTO(out, rc);
5875
5876         rc = mdt_connect_internal(env, lexp, mdt, data, false);
5877         if (rc == 0) {
5878                 struct lsd_client_data *lcd = lexp->exp_target_data.ted_lcd;
5879
5880                 LASSERT(lcd);
5881                 memcpy(lcd->lcd_uuid, cluuid, sizeof lcd->lcd_uuid);
5882                 rc = tgt_client_new(env, lexp);
5883                 if (rc == 0)
5884                         mdt_export_stats_init(obd, lexp, localdata);
5885         }
5886 out:
5887         if (rc != 0) {
5888                 class_disconnect(lexp);
5889                 nodemap_del_member(lexp);
5890                 *exp = NULL;
5891         } else {
5892                 *exp = lexp;
5893                 /* Because we do not want this export to be evicted by pinger,
5894                  * let's not add this export to the timed chain list. */
5895                 if (data->ocd_connect_flags & OBD_CONNECT_MDS_MDS) {
5896                         spin_lock(&lexp->exp_obd->obd_dev_lock);
5897                         list_del_init(&lexp->exp_obd_chain_timed);
5898                         spin_unlock(&lexp->exp_obd->obd_dev_lock);
5899                 }
5900         }
5901
5902         RETURN(rc);
5903 }
5904
5905 static int mdt_obd_reconnect(const struct lu_env *env,
5906                              struct obd_export *exp, struct obd_device *obd,
5907                              struct obd_uuid *cluuid,
5908                              struct obd_connect_data *data,
5909                              void *localdata)
5910 {
5911         lnet_nid_t             *client_nid = localdata;
5912         int                     rc;
5913         ENTRY;
5914
5915         if (exp == NULL || obd == NULL || cluuid == NULL)
5916                 RETURN(-EINVAL);
5917
5918         rc = nodemap_add_member(*client_nid, exp);
5919         if (rc != 0 && rc != -EEXIST)
5920                 RETURN(rc);
5921
5922         rc = mdt_connect_internal(env, exp, mdt_dev(obd->obd_lu_dev), data,
5923                                   true);
5924         if (rc == 0)
5925                 mdt_export_stats_init(obd, exp, localdata);
5926         else
5927                 nodemap_del_member(exp);
5928
5929         RETURN(rc);
5930 }
5931
5932 /* FIXME: Can we avoid using these two interfaces? */
5933 static int mdt_init_export(struct obd_export *exp)
5934 {
5935         struct mdt_export_data *med = &exp->exp_mdt_data;
5936         int                     rc;
5937         ENTRY;
5938
5939         INIT_LIST_HEAD(&med->med_open_head);
5940         spin_lock_init(&med->med_open_lock);
5941         spin_lock(&exp->exp_lock);
5942         exp->exp_connecting = 1;
5943         spin_unlock(&exp->exp_lock);
5944
5945         /* self-export doesn't need client data and ldlm initialization */
5946         if (unlikely(obd_uuid_equals(&exp->exp_obd->obd_uuid,
5947                                      &exp->exp_client_uuid)))
5948                 RETURN(0);
5949
5950         rc = tgt_client_alloc(exp);
5951         if (rc)
5952                 GOTO(err, rc);
5953
5954         rc = ldlm_init_export(exp);
5955         if (rc)
5956                 GOTO(err_free, rc);
5957
5958         RETURN(rc);
5959
5960 err_free:
5961         tgt_client_free(exp);
5962 err:
5963         CERROR("%s: Failed to initialize export: rc = %d\n",
5964                exp->exp_obd->obd_name, rc);
5965         return rc;
5966 }
5967
5968 static int mdt_destroy_export(struct obd_export *exp)
5969 {
5970         ENTRY;
5971
5972         target_destroy_export(exp);
5973         /* destroy can be called from failed obd_setup, so
5974          * checking uuid is safer than obd_self_export */
5975         if (unlikely(obd_uuid_equals(&exp->exp_obd->obd_uuid,
5976                                      &exp->exp_client_uuid)))
5977                 RETURN(0);
5978
5979         ldlm_destroy_export(exp);
5980         tgt_client_free(exp);
5981
5982         LASSERT(list_empty(&exp->exp_outstanding_replies));
5983         LASSERT(list_empty(&exp->exp_mdt_data.med_open_head));
5984
5985         /*
5986          * discard grants once we're sure no more
5987          * interaction with the client is possible
5988          */
5989         tgt_grant_discard(exp);
5990         if (exp_connect_flags(exp) & OBD_CONNECT_GRANT)
5991                 exp->exp_obd->u.obt.obt_lut->lut_tgd.tgd_tot_granted_clients--;
5992
5993         if (!(exp->exp_flags & OBD_OPT_FORCE))
5994                 tgt_grant_sanity_check(exp->exp_obd, __func__);
5995
5996         RETURN(0);
5997 }
5998
5999 int mdt_links_read(struct mdt_thread_info *info, struct mdt_object *mdt_obj,
6000                    struct linkea_data *ldata)
6001 {
6002         int rc;
6003
6004         LASSERT(ldata->ld_buf->lb_buf != NULL);
6005
6006         if (!mdt_object_exists(mdt_obj))
6007                 return -ENODATA;
6008
6009         rc = mo_xattr_get(info->mti_env, mdt_object_child(mdt_obj),
6010                           ldata->ld_buf, XATTR_NAME_LINK);
6011         if (rc == -ERANGE) {
6012                 /* Buf was too small, figure out what we need. */
6013                 lu_buf_free(ldata->ld_buf);
6014                 rc = mo_xattr_get(info->mti_env, mdt_object_child(mdt_obj),
6015                                   ldata->ld_buf, XATTR_NAME_LINK);
6016                 if (rc < 0)
6017                         return rc;
6018                 ldata->ld_buf = lu_buf_check_and_alloc(ldata->ld_buf, rc);
6019                 if (ldata->ld_buf->lb_buf == NULL)
6020                         return -ENOMEM;
6021                 rc = mo_xattr_get(info->mti_env, mdt_object_child(mdt_obj),
6022                                   ldata->ld_buf, XATTR_NAME_LINK);
6023         }
6024         if (rc < 0)
6025                 return rc;
6026
6027         return linkea_init_with_rec(ldata);
6028 }
6029
6030 /**
6031  * Given an MDT object, try to look up the full path to the object.
6032  * Part of the MDT layer implementation of lfs fid2path.
6033  *
6034  * \param[in]     info  Per-thread common data shared by MDT level handlers.
6035  * \param[in]     obj   Object to do path lookup of
6036  * \param[in,out] fp    User-provided struct to store path information
6037  * \param[in]     root_fid Root FID of current path should reach
6038  *
6039  * \retval 0 Lookup successful, path information stored in fp
6040  * \retval -EAGAIN Lookup failed, usually because object is being moved
6041  * \retval negative errno if there was a problem
6042  */
6043 static int mdt_path_current(struct mdt_thread_info *info,
6044                             struct mdt_object *obj,
6045                             struct getinfo_fid2path *fp,
6046                             struct lu_fid *root_fid)
6047 {
6048         struct mdt_device       *mdt = info->mti_mdt;
6049         struct mdt_object       *mdt_obj;
6050         struct link_ea_header   *leh;
6051         struct link_ea_entry    *lee;
6052         struct lu_name          *tmpname = &info->mti_name;
6053         struct lu_fid           *tmpfid = &info->mti_tmp_fid1;
6054         struct lu_buf           *buf = &info->mti_big_buf;
6055         char                    *ptr;
6056         int                     reclen;
6057         struct linkea_data      ldata = { NULL };
6058         int                     rc = 0;
6059         bool                    first = true;
6060         ENTRY;
6061
6062         /* temp buffer for path element, the buffer will be finally freed
6063          * in mdt_thread_info_fini */
6064         buf = lu_buf_check_and_alloc(buf, PATH_MAX);
6065         if (buf->lb_buf == NULL)
6066                 RETURN(-ENOMEM);
6067
6068         ldata.ld_buf = buf;
6069         ptr = fp->gf_u.gf_path + fp->gf_pathlen - 1;
6070         *ptr = 0;
6071         --ptr;
6072         *tmpfid = fp->gf_fid = *mdt_object_fid(obj);
6073
6074         while (!lu_fid_eq(root_fid, &fp->gf_fid)) {
6075                 struct lu_buf           lmv_buf;
6076
6077                 if (!lu_fid_eq(root_fid, &mdt->mdt_md_root_fid) &&
6078                     lu_fid_eq(&mdt->mdt_md_root_fid, &fp->gf_fid))
6079                         GOTO(out, rc = -ENOENT);
6080
6081                 if (lu_fid_eq(mdt_object_fid(obj), tmpfid)) {
6082                         mdt_obj = obj;
6083                         mdt_object_get(info->mti_env, mdt_obj);
6084                 } else {
6085                         mdt_obj = mdt_object_find(info->mti_env, mdt, tmpfid);
6086                         if (IS_ERR(mdt_obj))
6087                                 GOTO(out, rc = PTR_ERR(mdt_obj));
6088                 }
6089
6090                 if (!mdt_object_exists(mdt_obj)) {
6091                         mdt_object_put(info->mti_env, mdt_obj);
6092                         GOTO(out, rc = -ENOENT);
6093                 }
6094
6095                 if (mdt_object_remote(mdt_obj)) {
6096                         mdt_object_put(info->mti_env, mdt_obj);
6097                         GOTO(remote_out, rc = -EREMOTE);
6098                 }
6099
6100                 rc = mdt_links_read(info, mdt_obj, &ldata);
6101                 if (rc != 0) {
6102                         mdt_object_put(info->mti_env, mdt_obj);
6103                         GOTO(out, rc);
6104                 }
6105
6106                 leh = buf->lb_buf;
6107                 lee = (struct link_ea_entry *)(leh + 1); /* link #0 */
6108                 linkea_entry_unpack(lee, &reclen, tmpname, tmpfid);
6109                 /* If set, use link #linkno for path lookup, otherwise use
6110                    link #0.  Only do this for the final path element. */
6111                 if (first && fp->gf_linkno < leh->leh_reccount) {
6112                         int count;
6113                         for (count = 0; count < fp->gf_linkno; count++) {
6114                                 lee = (struct link_ea_entry *)
6115                                      ((char *)lee + reclen);
6116                                 linkea_entry_unpack(lee, &reclen, tmpname,
6117                                                     tmpfid);
6118                         }
6119                         if (fp->gf_linkno < leh->leh_reccount - 1)
6120                                 /* indicate to user there are more links */
6121                                 fp->gf_linkno++;
6122                 }
6123
6124                 lmv_buf.lb_buf = info->mti_xattr_buf;
6125                 lmv_buf.lb_len = sizeof(info->mti_xattr_buf);
6126                 /* Check if it is slave stripes */
6127                 rc = mo_xattr_get(info->mti_env, mdt_object_child(mdt_obj),
6128                                   &lmv_buf, XATTR_NAME_LMV);
6129                 mdt_object_put(info->mti_env, mdt_obj);
6130                 if (rc > 0) {
6131                         union lmv_mds_md *lmm = lmv_buf.lb_buf;
6132
6133                         /* For slave stripes, get its master */
6134                         if (le32_to_cpu(lmm->lmv_magic) == LMV_MAGIC_STRIPE) {
6135                                 fp->gf_fid = *tmpfid;
6136                                 continue;
6137                         }
6138                 } else if (rc < 0 && rc != -ENODATA) {
6139                         GOTO(out, rc);
6140                 }
6141
6142                 rc = 0;
6143
6144                 /* Pack the name in the end of the buffer */
6145                 ptr -= tmpname->ln_namelen;
6146                 if (ptr - 1 <= fp->gf_u.gf_path)
6147                         GOTO(out, rc = -EOVERFLOW);
6148                 strncpy(ptr, tmpname->ln_name, tmpname->ln_namelen);
6149                 *(--ptr) = '/';
6150
6151                 /* keep the last resolved fid to the client, so the
6152                  * client will build the left path on another MDT for
6153                  * remote object */
6154                 fp->gf_fid = *tmpfid;
6155
6156                 first = false;
6157         }
6158
6159 remote_out:
6160         ptr++; /* skip leading / */
6161         memmove(fp->gf_u.gf_path, ptr,
6162                 fp->gf_u.gf_path + fp->gf_pathlen - ptr);
6163
6164 out:
6165         RETURN(rc);
6166 }
6167
6168 /**
6169  * Given an MDT object, use mdt_path_current to get the path.
6170  * Essentially a wrapper to retry mdt_path_current a set number of times
6171  * if -EAGAIN is returned (usually because an object is being moved).
6172  *
6173  * Part of the MDT layer implementation of lfs fid2path.
6174  *
6175  * \param[in]     info  Per-thread common data shared by mdt level handlers.
6176  * \param[in]     obj   Object to do path lookup of
6177  * \param[in,out] fp    User-provided struct for arguments and to store path
6178  *                      information
6179  *
6180  * \retval 0 Lookup successful, path information stored in fp
6181  * \retval negative errno if there was a problem
6182  */
6183 static int mdt_path(struct mdt_thread_info *info, struct mdt_object *obj,
6184                     struct getinfo_fid2path *fp, struct lu_fid *root_fid)
6185 {
6186         struct mdt_device       *mdt = info->mti_mdt;
6187         int                     tries = 3;
6188         int                     rc = -EAGAIN;
6189         ENTRY;
6190
6191         if (fp->gf_pathlen < 3)
6192                 RETURN(-EOVERFLOW);
6193
6194         if (root_fid == NULL)
6195                 root_fid = &mdt->mdt_md_root_fid;
6196
6197         if (lu_fid_eq(root_fid, mdt_object_fid(obj))) {
6198                 fp->gf_u.gf_path[0] = '\0';
6199                 RETURN(0);
6200         }
6201
6202         /* Retry multiple times in case file is being moved */
6203         while (tries-- && rc == -EAGAIN)
6204                 rc = mdt_path_current(info, obj, fp, root_fid);
6205
6206         RETURN(rc);
6207 }
6208
6209 /**
6210  * Get the full path of the provided FID, as of changelog record recno.
6211  *
6212  * This checks sanity and looks up object for user provided FID
6213  * before calling the actual path lookup code.
6214  *
6215  * Part of the MDT layer implementation of lfs fid2path.
6216  *
6217  * \param[in]     info  Per-thread common data shared by mdt level handlers.
6218  * \param[in,out] fp    User-provided struct for arguments and to store path
6219  *                      information
6220  *
6221  * \retval 0 Lookup successful, path information and recno stored in fp
6222  * \retval -ENOENT, object does not exist
6223  * \retval negative errno if there was a problem
6224  */
6225 static int mdt_fid2path(struct mdt_thread_info *info,
6226                         struct lu_fid *root_fid,
6227                         struct getinfo_fid2path *fp)
6228 {
6229         struct mdt_device *mdt = info->mti_mdt;
6230         struct mdt_object *obj;
6231         int    rc;
6232         ENTRY;
6233
6234         CDEBUG(D_IOCTL, "path get "DFID" from %llu #%d\n",
6235                 PFID(&fp->gf_fid), fp->gf_recno, fp->gf_linkno);
6236
6237         if (!fid_is_sane(&fp->gf_fid))
6238                 RETURN(-EINVAL);
6239
6240         if (!fid_is_namespace_visible(&fp->gf_fid)) {
6241                 CDEBUG(D_INFO, "%s: "DFID" is invalid, f_seq should be >= %#llx"
6242                        ", or f_oid != 0, or f_ver == 0\n", mdt_obd_name(mdt),
6243                        PFID(&fp->gf_fid), (__u64)FID_SEQ_NORMAL);
6244                 RETURN(-EINVAL);
6245         }
6246
6247         obj = mdt_object_find(info->mti_env, mdt, &fp->gf_fid);
6248         if (IS_ERR(obj)) {
6249                 rc = PTR_ERR(obj);
6250                 CDEBUG(D_IOCTL, "cannot find "DFID": rc = %d\n",
6251                        PFID(&fp->gf_fid), rc);
6252                 RETURN(rc);
6253         }
6254
6255         if (mdt_object_remote(obj))
6256                 rc = -EREMOTE;
6257         else if (!mdt_object_exists(obj))
6258                 rc = -ENOENT;
6259         else
6260                 rc = 0;
6261
6262         if (rc < 0) {
6263                 mdt_object_put(info->mti_env, obj);
6264                 CDEBUG(D_IOCTL, "nonlocal object "DFID": rc = %d\n",
6265                        PFID(&fp->gf_fid), rc);
6266                 RETURN(rc);
6267         }
6268
6269         rc = mdt_path(info, obj, fp, root_fid);
6270
6271         CDEBUG(D_INFO, "fid "DFID", path %s recno %#llx linkno %u\n",
6272                PFID(&fp->gf_fid), fp->gf_u.gf_path,
6273                fp->gf_recno, fp->gf_linkno);
6274
6275         mdt_object_put(info->mti_env, obj);
6276
6277         RETURN(rc);
6278 }
6279
6280 static int mdt_rpc_fid2path(struct mdt_thread_info *info, void *key, int keylen,
6281                             void *val, int vallen)
6282 {
6283         struct getinfo_fid2path *fpout, *fpin;
6284         struct lu_fid *root_fid = NULL;
6285         int rc = 0;
6286
6287         fpin = key + cfs_size_round(sizeof(KEY_FID2PATH));
6288         fpout = val;
6289
6290         if (ptlrpc_req_need_swab(info->mti_pill->rc_req))
6291                 lustre_swab_fid2path(fpin);
6292
6293         memcpy(fpout, fpin, sizeof(*fpin));
6294         if (fpout->gf_pathlen != vallen - sizeof(*fpin))
6295                 RETURN(-EINVAL);
6296
6297         if (keylen >= cfs_size_round(sizeof(KEY_FID2PATH)) + sizeof(*fpin) +
6298                       sizeof(struct lu_fid)) {
6299                 /* client sent its root FID, which is normally fileset FID */
6300                 root_fid = fpin->gf_u.gf_root_fid;
6301                 if (ptlrpc_req_need_swab(info->mti_pill->rc_req))
6302                         lustre_swab_lu_fid(root_fid);
6303
6304                 if (root_fid != NULL && !fid_is_sane(root_fid))
6305                         RETURN(-EINVAL);
6306         }
6307
6308         rc = mdt_fid2path(info, root_fid, fpout);
6309         RETURN(rc);
6310 }
6311
6312 int mdt_get_info(struct tgt_session_info *tsi)
6313 {
6314         char    *key;
6315         int      keylen;
6316         __u32   *vallen;
6317         void    *valout;
6318         int      rc;
6319
6320         ENTRY;
6321
6322         key = req_capsule_client_get(tsi->tsi_pill, &RMF_GETINFO_KEY);
6323         if (key == NULL) {
6324                 CDEBUG(D_IOCTL, "No GETINFO key\n");
6325                 RETURN(err_serious(-EFAULT));
6326         }
6327         keylen = req_capsule_get_size(tsi->tsi_pill, &RMF_GETINFO_KEY,
6328                                       RCL_CLIENT);
6329
6330         vallen = req_capsule_client_get(tsi->tsi_pill, &RMF_GETINFO_VALLEN);
6331         if (vallen == NULL) {
6332                 CDEBUG(D_IOCTL, "%s: cannot get RMF_GETINFO_VALLEN buffer\n",
6333                                 tgt_name(tsi->tsi_tgt));
6334                 RETURN(err_serious(-EFAULT));
6335         }
6336
6337         req_capsule_set_size(tsi->tsi_pill, &RMF_GETINFO_VAL, RCL_SERVER,
6338                              *vallen);
6339         rc = req_capsule_server_pack(tsi->tsi_pill);
6340         if (rc)
6341                 RETURN(err_serious(rc));
6342
6343         valout = req_capsule_server_get(tsi->tsi_pill, &RMF_GETINFO_VAL);
6344         if (valout == NULL) {
6345                 CDEBUG(D_IOCTL, "%s: cannot get get-info RPC out buffer\n",
6346                                 tgt_name(tsi->tsi_tgt));
6347                 RETURN(err_serious(-EFAULT));
6348         }
6349
6350         if (KEY_IS(KEY_FID2PATH)) {
6351                 struct mdt_thread_info  *info = tsi2mdt_info(tsi);
6352
6353                 rc = mdt_rpc_fid2path(info, key, keylen, valout, *vallen);
6354                 mdt_thread_info_fini(info);
6355         } else {
6356                 rc = -EINVAL;
6357         }
6358         RETURN(rc);
6359 }
6360
6361 static int mdt_ioc_version_get(struct mdt_thread_info *mti, void *karg)
6362 {
6363         struct obd_ioctl_data *data = karg;
6364         struct lu_fid *fid;
6365         __u64 version;
6366         struct mdt_object *obj;
6367         struct mdt_lock_handle  *lh;
6368         int rc;
6369         ENTRY;
6370
6371         if (data->ioc_inlbuf1 == NULL || data->ioc_inllen1 != sizeof(*fid) ||
6372             data->ioc_inlbuf2 == NULL || data->ioc_inllen2 != sizeof(version))
6373                 RETURN(-EINVAL);
6374
6375         fid = (struct lu_fid *)data->ioc_inlbuf1;
6376
6377         if (!fid_is_sane(fid))
6378                 RETURN(-EINVAL);
6379
6380         CDEBUG(D_IOCTL, "getting version for "DFID"\n", PFID(fid));
6381
6382         lh = &mti->mti_lh[MDT_LH_PARENT];
6383         mdt_lock_reg_init(lh, LCK_CR);
6384
6385         obj = mdt_object_find_lock(mti, fid, lh, MDS_INODELOCK_UPDATE);
6386         if (IS_ERR(obj))
6387                 RETURN(PTR_ERR(obj));
6388
6389         if (mdt_object_remote(obj)) {
6390                 rc = -EREMOTE;
6391                 /**
6392                  * before calling version get the correct MDS should be
6393                  * fid, this is error to find remote object here
6394                  */
6395                 CERROR("nonlocal object "DFID"\n", PFID(fid));
6396         } else if (!mdt_object_exists(obj)) {
6397                 *(__u64 *)data->ioc_inlbuf2 = ENOENT_VERSION;
6398                 rc = -ENOENT;
6399         } else {
6400                 version = dt_version_get(mti->mti_env, mdt_obj2dt(obj));
6401                *(__u64 *)data->ioc_inlbuf2 = version;
6402                 rc = 0;
6403         }
6404         mdt_object_unlock_put(mti, obj, lh, 1);
6405         RETURN(rc);
6406 }
6407
6408 /* ioctls on obd dev */
6409 static int mdt_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
6410                          void *karg, void __user *uarg)
6411 {
6412         struct lu_env      env;
6413         struct obd_device *obd = exp->exp_obd;
6414         struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
6415         struct dt_device  *dt = mdt->mdt_bottom;
6416         int rc;
6417
6418         ENTRY;
6419         CDEBUG(D_IOCTL, "handling ioctl cmd %#x\n", cmd);
6420         rc = lu_env_init(&env, LCT_MD_THREAD);
6421         if (rc)
6422                 RETURN(rc);
6423
6424         switch (cmd) {
6425         case OBD_IOC_SYNC:
6426                 rc = mdt_device_sync(&env, mdt);
6427                 break;
6428         case OBD_IOC_SET_READONLY:
6429                 rc = dt_sync(&env, dt);
6430                 if (rc == 0)
6431                         rc = dt_ro(&env, dt);
6432                 break;
6433         case OBD_IOC_ABORT_RECOVERY:
6434                 CERROR("%s: Aborting recovery for device\n", mdt_obd_name(mdt));
6435                 obd->obd_abort_recovery = 1;
6436                 target_stop_recovery_thread(obd);
6437                 rc = 0;
6438                 break;
6439         case OBD_IOC_CHANGELOG_REG:
6440         case OBD_IOC_CHANGELOG_DEREG:
6441         case OBD_IOC_CHANGELOG_CLEAR:
6442                 rc = mdt->mdt_child->md_ops->mdo_iocontrol(&env,
6443                                                            mdt->mdt_child,
6444                                                            cmd, len, karg);
6445                 break;
6446         case OBD_IOC_START_LFSCK: {
6447                 struct md_device *next = mdt->mdt_child;
6448                 struct obd_ioctl_data *data = karg;
6449                 struct lfsck_start_param lsp;
6450
6451                 if (unlikely(data == NULL)) {
6452                         rc = -EINVAL;
6453                         break;
6454                 }
6455
6456                 lsp.lsp_start = (struct lfsck_start *)(data->ioc_inlbuf1);
6457                 lsp.lsp_index_valid = 0;
6458                 rc = next->md_ops->mdo_iocontrol(&env, next, cmd, 0, &lsp);
6459                 break;
6460         }
6461         case OBD_IOC_STOP_LFSCK: {
6462                 struct md_device        *next = mdt->mdt_child;
6463                 struct obd_ioctl_data   *data = karg;
6464                 struct lfsck_stop        stop;
6465
6466                 stop.ls_status = LS_STOPPED;
6467                 /* Old lfsck utils may pass NULL @stop. */
6468                 if (data->ioc_inlbuf1 == NULL)
6469                         stop.ls_flags = 0;
6470                 else
6471                         stop.ls_flags =
6472                         ((struct lfsck_stop *)(data->ioc_inlbuf1))->ls_flags;
6473
6474                 rc = next->md_ops->mdo_iocontrol(&env, next, cmd, 0, &stop);
6475                 break;
6476         }
6477         case OBD_IOC_QUERY_LFSCK: {
6478                 struct md_device        *next = mdt->mdt_child;
6479                 struct obd_ioctl_data   *data = karg;
6480
6481                 rc = next->md_ops->mdo_iocontrol(&env, next, cmd, 0,
6482                                                  data->ioc_inlbuf1);
6483                 break;
6484         }
6485         case OBD_IOC_GET_OBJ_VERSION: {
6486                 struct mdt_thread_info *mti;
6487                 mti = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
6488                 memset(mti, 0, sizeof *mti);
6489                 mti->mti_env = &env;
6490                 mti->mti_mdt = mdt;
6491                 mti->mti_exp = exp;
6492
6493                 rc = mdt_ioc_version_get(mti, karg);
6494                 break;
6495         }
6496         case OBD_IOC_CATLOGLIST: {
6497                 struct mdt_thread_info *mti;
6498
6499                 mti = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
6500                 lu_local_obj_fid(&mti->mti_tmp_fid1, LLOG_CATALOGS_OID);
6501                 rc = llog_catalog_list(&env, mdt->mdt_bottom, 0, karg,
6502                                        &mti->mti_tmp_fid1);
6503                 break;
6504          }
6505         default:
6506                 rc = -EOPNOTSUPP;
6507                 CERROR("%s: Not supported cmd = %d, rc = %d\n",
6508                         mdt_obd_name(mdt), cmd, rc);
6509         }
6510
6511         lu_env_fini(&env);
6512         RETURN(rc);
6513 }
6514
6515 static int mdt_postrecov(const struct lu_env *env, struct mdt_device *mdt)
6516 {
6517         struct lu_device *ld = md2lu_dev(mdt->mdt_child);
6518         int rc;
6519         ENTRY;
6520
6521         if (!mdt->mdt_skip_lfsck && !mdt->mdt_bottom->dd_rdonly) {
6522                 struct lfsck_start_param lsp;
6523
6524                 lsp.lsp_start = NULL;
6525                 lsp.lsp_index_valid = 0;
6526                 rc = mdt->mdt_child->md_ops->mdo_iocontrol(env, mdt->mdt_child,
6527                                                            OBD_IOC_START_LFSCK,
6528                                                            0, &lsp);
6529                 if (rc != 0 && rc != -EALREADY)
6530                         CWARN("%s: auto trigger paused LFSCK failed: rc = %d\n",
6531                               mdt_obd_name(mdt), rc);
6532         }
6533
6534         rc = ld->ld_ops->ldo_recovery_complete(env, ld);
6535         RETURN(rc);
6536 }
6537
6538 static int mdt_obd_postrecov(struct obd_device *obd)
6539 {
6540         struct lu_env env;
6541         int rc;
6542
6543         rc = lu_env_init(&env, LCT_MD_THREAD);
6544         if (rc)
6545                 RETURN(rc);
6546         rc = mdt_postrecov(&env, mdt_dev(obd->obd_lu_dev));
6547         lu_env_fini(&env);
6548         return rc;
6549 }
6550
6551 static struct obd_ops mdt_obd_device_ops = {
6552         .o_owner          = THIS_MODULE,
6553         .o_set_info_async = mdt_obd_set_info_async,
6554         .o_connect        = mdt_obd_connect,
6555         .o_reconnect      = mdt_obd_reconnect,
6556         .o_disconnect     = mdt_obd_disconnect,
6557         .o_init_export    = mdt_init_export,
6558         .o_destroy_export = mdt_destroy_export,
6559         .o_iocontrol      = mdt_iocontrol,
6560         .o_postrecov      = mdt_obd_postrecov,
6561         /* Data-on-MDT IO methods */
6562         .o_preprw         = mdt_obd_preprw,
6563         .o_commitrw       = mdt_obd_commitrw,
6564 };
6565
6566 static struct lu_device* mdt_device_fini(const struct lu_env *env,
6567                                          struct lu_device *d)
6568 {
6569         struct mdt_device *m = mdt_dev(d);
6570         ENTRY;
6571
6572         mdt_fini(env, m);
6573         RETURN(NULL);
6574 }
6575
6576 static struct lu_device *mdt_device_free(const struct lu_env *env,
6577                                          struct lu_device *d)
6578 {
6579         struct mdt_device *m = mdt_dev(d);
6580         ENTRY;
6581
6582         lu_device_fini(&m->mdt_lu_dev);
6583         OBD_FREE_PTR(m);
6584
6585         RETURN(NULL);
6586 }
6587
6588 static struct lu_device *mdt_device_alloc(const struct lu_env *env,
6589                                           struct lu_device_type *t,
6590                                           struct lustre_cfg *cfg)
6591 {
6592         struct lu_device  *l;
6593         struct mdt_device *m;
6594
6595         OBD_ALLOC_PTR(m);
6596         if (m != NULL) {
6597                 int rc;
6598
6599                 l = &m->mdt_lu_dev;
6600                 rc = mdt_init0(env, m, t, cfg);
6601                 if (rc != 0) {
6602                         mdt_device_free(env, l);
6603                         l = ERR_PTR(rc);
6604                         return l;
6605                 }
6606         } else
6607                 l = ERR_PTR(-ENOMEM);
6608         return l;
6609 }
6610
6611 /* context key constructor/destructor: mdt_key_init, mdt_key_fini */
6612 LU_KEY_INIT(mdt, struct mdt_thread_info);
6613
6614 static void mdt_key_fini(const struct lu_context *ctx,
6615                          struct lu_context_key *key, void* data)
6616 {
6617         struct mdt_thread_info *info = data;
6618
6619         if (info->mti_big_lmm) {
6620                 OBD_FREE_LARGE(info->mti_big_lmm, info->mti_big_lmmsize);
6621                 info->mti_big_lmm = NULL;
6622                 info->mti_big_lmmsize = 0;
6623         }
6624
6625         if (info->mti_big_acl) {
6626                 OBD_FREE_LARGE(info->mti_big_acl, info->mti_big_aclsize);
6627                 info->mti_big_acl = NULL;
6628                 info->mti_big_aclsize = 0;
6629         }
6630
6631         OBD_FREE_PTR(info);
6632 }
6633
6634 /* context key: mdt_thread_key */
6635 LU_CONTEXT_KEY_DEFINE(mdt, LCT_MD_THREAD);
6636
6637 struct lu_ucred *mdt_ucred(const struct mdt_thread_info *info)
6638 {
6639         return lu_ucred(info->mti_env);
6640 }
6641
6642 struct lu_ucred *mdt_ucred_check(const struct mdt_thread_info *info)
6643 {
6644         return lu_ucred_check(info->mti_env);
6645 }
6646
6647 /**
6648  * Enable/disable COS (Commit On Sharing).
6649  *
6650  * Set/Clear the COS flag in mdt options.
6651  *
6652  * \param mdt mdt device
6653  * \param val 0 disables COS, other values enable COS
6654  */
6655 void mdt_enable_cos(struct mdt_device *mdt, int val)
6656 {
6657         struct lu_env env;
6658         int rc;
6659
6660         mdt->mdt_opts.mo_cos = !!val;
6661         rc = lu_env_init(&env, LCT_LOCAL);
6662         if (unlikely(rc != 0)) {
6663                 CWARN("%s: lu_env initialization failed, cannot "
6664                       "sync: rc = %d\n", mdt_obd_name(mdt), rc);
6665                 return;
6666         }
6667         mdt_device_sync(&env, mdt);
6668         lu_env_fini(&env);
6669 }
6670
6671 /**
6672  * Check COS (Commit On Sharing) status.
6673  *
6674  * Return COS flag status.
6675  *
6676  * \param mdt mdt device
6677  */
6678 int mdt_cos_is_enabled(struct mdt_device *mdt)
6679 {
6680         return mdt->mdt_opts.mo_cos != 0;
6681 }
6682
6683 static struct lu_device_type_operations mdt_device_type_ops = {
6684         .ldto_device_alloc = mdt_device_alloc,
6685         .ldto_device_free  = mdt_device_free,
6686         .ldto_device_fini  = mdt_device_fini
6687 };
6688
6689 static struct lu_device_type mdt_device_type = {
6690         .ldt_tags     = LU_DEVICE_MD,
6691         .ldt_name     = LUSTRE_MDT_NAME,
6692         .ldt_ops      = &mdt_device_type_ops,
6693         .ldt_ctx_tags = LCT_MD_THREAD
6694 };
6695
6696 static int __init mdt_init(void)
6697 {
6698         int rc;
6699
6700         CLASSERT(sizeof("0x0123456789ABCDEF:0x01234567:0x01234567") ==
6701                  FID_NOBRACE_LEN + 1);
6702         CLASSERT(sizeof("[0x0123456789ABCDEF:0x01234567:0x01234567]") ==
6703                  FID_LEN + 1);
6704         rc = lu_kmem_init(mdt_caches);
6705         if (rc)
6706                 return rc;
6707
6708         rc = mds_mod_init();
6709         if (rc)
6710                 GOTO(lu_fini, rc);
6711
6712         rc = class_register_type(&mdt_obd_device_ops, NULL, true, NULL,
6713                                  LUSTRE_MDT_NAME, &mdt_device_type);
6714         if (rc)
6715                 GOTO(mds_fini, rc);
6716 lu_fini:
6717         if (rc)
6718                 lu_kmem_fini(mdt_caches);
6719 mds_fini:
6720         if (rc)
6721                 mds_mod_exit();
6722         return rc;
6723 }
6724
6725 static void __exit mdt_exit(void)
6726 {
6727         class_unregister_type(LUSTRE_MDT_NAME);
6728         mds_mod_exit();
6729         lu_kmem_fini(mdt_caches);
6730 }
6731
6732 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
6733 MODULE_DESCRIPTION("Lustre Metadata Target ("LUSTRE_MDT_NAME")");
6734 MODULE_VERSION(LUSTRE_VERSION_STRING);
6735 MODULE_LICENSE("GPL");
6736
6737 module_init(mdt_init);
6738 module_exit(mdt_exit);