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