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