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