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