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