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