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