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