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