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