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