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