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