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