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