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