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