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