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