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