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