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