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