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