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