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