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