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