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