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