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