Whamcloud - gitweb
LU-14692 tests: allow FID_SEQ_NORMAL for MDT0000
[fs/lustre-release.git] / lustre / lfsck / lfsck_layout.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,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License version 2 for more details.  A copy is
14  * included in the COPYING file that accompanied this code.
15
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2014, 2017, Intel Corporation.
24  */
25 /*
26  * lustre/lfsck/lfsck_layout.c
27  *
28  * Author: Fan, Yong <fan.yong@intel.com>
29  */
30
31 #ifndef EXPORT_SYMTAB
32 # define EXPORT_SYMTAB
33 #endif
34 #define DEBUG_SUBSYSTEM S_LFSCK
35
36 #include <linux/bitops.h>
37 #include <linux/rbtree.h>
38
39 #include <lu_object.h>
40 #include <dt_object.h>
41 #include <lustre_fid.h>
42 #include <lustre_lib.h>
43 #include <lustre_net.h>
44 #include <md_object.h>
45 #include <obd_class.h>
46
47 #include "lfsck_internal.h"
48
49 #define LFSCK_LAYOUT_MAGIC_V1           0xB173AE14
50 #define LFSCK_LAYOUT_MAGIC_V2           0xB1734D76
51 #define LFSCK_LAYOUT_MAGIC_V3           0xB17371B9
52 #define LFSCK_LAYOUT_MAGIC_V4           0xB1732FED
53
54 #define LFSCK_LAYOUT_MAGIC              LFSCK_LAYOUT_MAGIC_V4
55
56 struct lfsck_layout_seq {
57         struct list_head         lls_list;
58         __u64                    lls_seq;
59         __u64                    lls_lastid;
60         __u64                    lls_lastid_known;
61         struct dt_object        *lls_lastid_obj;
62         unsigned int             lls_dirty:1;
63 };
64
65 struct lfsck_layout_slave_target {
66         /* link into lfsck_layout_slave_data::llsd_master_list. */
67         struct list_head        llst_list;
68         /* The position for next record in the rbtree for iteration. */
69         struct lu_fid           llst_fid;
70         /* Dummy hash for iteration against the rbtree. */
71         __u64                   llst_hash;
72         __u64                   llst_gen;
73         atomic_t                llst_ref;
74         __u32                   llst_index;
75         /* How many times we have failed to get the master status. */
76         int                     llst_failures;
77 };
78
79 struct lfsck_layout_slave_data {
80         /* list for lfsck_layout_seq */
81         struct list_head         llsd_seq_list;
82
83         /* list for the masters involve layout verification. */
84         struct list_head         llsd_master_list;
85         spinlock_t               llsd_lock;
86         __u64                    llsd_touch_gen;
87         struct dt_object        *llsd_rb_obj;
88         struct rb_root           llsd_rb_root;
89         struct rw_semaphore      llsd_rb_rwsem;
90         unsigned int             llsd_rbtree_valid:1;
91 };
92
93 struct lfsck_layout_slave_async_args {
94         struct obd_export                *llsaa_exp;
95         struct lfsck_component           *llsaa_com;
96         struct lfsck_layout_slave_target *llsaa_llst;
97 };
98
99 static inline bool lfsck_comp_extent_aligned(__u64 border, __u32 size)
100 {
101         return (border & (size - 1)) == 0;
102 }
103
104 static inline void
105 lfsck_layout_llst_put(struct lfsck_layout_slave_target *llst)
106 {
107         if (atomic_dec_and_test(&llst->llst_ref)) {
108                 LASSERT(list_empty(&llst->llst_list));
109
110                 OBD_FREE_PTR(llst);
111         }
112 }
113
114 static inline int
115 lfsck_layout_llst_add(struct lfsck_layout_slave_data *llsd, __u32 index)
116 {
117         struct lfsck_layout_slave_target *llst;
118         struct lfsck_layout_slave_target *tmp;
119         int                               rc   = 0;
120
121         OBD_ALLOC_PTR(llst);
122         if (llst == NULL)
123                 return -ENOMEM;
124
125         INIT_LIST_HEAD(&llst->llst_list);
126         llst->llst_gen = 0;
127         llst->llst_index = index;
128         atomic_set(&llst->llst_ref, 1);
129
130         spin_lock(&llsd->llsd_lock);
131         list_for_each_entry(tmp, &llsd->llsd_master_list, llst_list) {
132                 if (tmp->llst_index == index) {
133                         rc = -EALREADY;
134                         break;
135                 }
136         }
137         if (rc == 0)
138                 list_add_tail(&llst->llst_list, &llsd->llsd_master_list);
139         spin_unlock(&llsd->llsd_lock);
140
141         if (rc != 0)
142                 OBD_FREE_PTR(llst);
143
144         return rc;
145 }
146
147 static inline void
148 lfsck_layout_llst_del(struct lfsck_layout_slave_data *llsd,
149                       struct lfsck_layout_slave_target *llst)
150 {
151         bool del = false;
152
153         spin_lock(&llsd->llsd_lock);
154         if (!list_empty(&llst->llst_list)) {
155                 list_del_init(&llst->llst_list);
156                 del = true;
157         }
158         spin_unlock(&llsd->llsd_lock);
159
160         if (del)
161                 lfsck_layout_llst_put(llst);
162 }
163
164 static inline struct lfsck_layout_slave_target *
165 lfsck_layout_llst_find_and_del(struct lfsck_layout_slave_data *llsd,
166                                __u32 index, bool unlink)
167 {
168         struct lfsck_layout_slave_target *llst;
169
170         spin_lock(&llsd->llsd_lock);
171         list_for_each_entry(llst, &llsd->llsd_master_list, llst_list) {
172                 if (llst->llst_index == index) {
173                         if (unlink)
174                                 list_del_init(&llst->llst_list);
175                         else
176                                 atomic_inc(&llst->llst_ref);
177                         spin_unlock(&llsd->llsd_lock);
178
179                         return llst;
180                 }
181         }
182         spin_unlock(&llsd->llsd_lock);
183
184         return NULL;
185 }
186
187 static struct lfsck_layout_req *
188 lfsck_layout_assistant_req_init(struct lfsck_assistant_object *lso,
189                                 struct dt_object *child, __u32 comp_id,
190                                 __u32 ost_idx, __u32 lov_idx)
191 {
192         struct lfsck_layout_req *llr;
193
194         OBD_ALLOC_PTR(llr);
195         if (llr == NULL)
196                 return ERR_PTR(-ENOMEM);
197
198         INIT_LIST_HEAD(&llr->llr_lar.lar_list);
199         llr->llr_lar.lar_parent = lfsck_assistant_object_get(lso);
200         llr->llr_child = child;
201         llr->llr_comp_id = comp_id;
202         llr->llr_ost_idx = ost_idx;
203         llr->llr_lov_idx = lov_idx;
204
205         return llr;
206 }
207
208 static void lfsck_layout_assistant_req_fini(const struct lu_env *env,
209                                             struct lfsck_assistant_req *lar)
210 {
211         struct lfsck_layout_req *llr =
212                 container_of(lar, struct lfsck_layout_req, llr_lar);
213
214         lfsck_object_put(env, llr->llr_child);
215         lfsck_assistant_object_put(env, lar->lar_parent);
216         OBD_FREE_PTR(llr);
217 }
218
219 static int
220 lfsck_layout_assistant_sync_failures_interpret(const struct lu_env *env,
221                                                struct ptlrpc_request *req,
222                                                void *args, int rc)
223 {
224         if (rc == 0) {
225                 struct lfsck_async_interpret_args *laia = args;
226                 struct lfsck_tgt_desc             *ltd  = laia->laia_ltd;
227
228                 ltd->ltd_synced_failures = 1;
229                 atomic_dec(laia->laia_count);
230         }
231
232         return 0;
233 }
234
235 /**
236  * Notify remote LFSCK instances about former failures.
237  *
238  * The local LFSCK instance has recorded which OSTs have ever failed to respond
239  * some LFSCK verification requests (maybe because of network issues or the OST
240  * itself trouble). During the respond gap, the OST may missed some OST-objects
241  * verification, then the OST cannot know whether related OST-objects have been
242  * referenced by related MDT-objects or not, then in the second-stage scanning,
243  * these OST-objects will be regarded as orphan, if the OST-object contains bad
244  * parent FID for back reference, then it will misguide the LFSCK to make wrong
245  * fixing for the fake orphan.
246  *
247  * To avoid above trouble, when layout LFSCK finishes the first-stage scanning,
248  * it will scan the bitmap for the ever failed OSTs, and notify them that they
249  * have ever missed some OST-object verification and should skip the handling
250  * for orphan OST-objects on all MDTs that are in the layout LFSCK.
251  *
252  * \param[in] env       pointer to the thread context
253  * \param[in] com       pointer to the lfsck component
254  * \param[in] lr        pointer to the lfsck request
255  */
256 static void lfsck_layout_assistant_sync_failures(const struct lu_env *env,
257                                                  struct lfsck_component *com,
258                                                  struct lfsck_request *lr)
259 {
260         struct lfsck_async_interpret_args *laia  =
261                                 &lfsck_env_info(env)->lti_laia2;
262         struct lfsck_assistant_data       *lad   = com->lc_data;
263         struct lfsck_layout               *lo    = com->lc_file_ram;
264         struct lfsck_instance             *lfsck = com->lc_lfsck;
265         struct lfsck_tgt_descs            *ltds  = &lfsck->li_ost_descs;
266         struct lfsck_tgt_desc             *ltd;
267         struct ptlrpc_request_set         *set;
268         atomic_t                           count;
269         __u32                              idx;
270         int                                rc    = 0;
271         ENTRY;
272
273         if (!test_bit(LAD_INCOMPLETE, &lad->lad_flags))
274                 RETURN_EXIT;
275
276         /* If the MDT has ever failed to verfiy some OST-objects,
277          * then sync failures with them firstly. */
278         lr->lr_flags2 = lo->ll_flags | LF_INCOMPLETE;
279
280         atomic_set(&count, 0);
281         memset(laia, 0, sizeof(*laia));
282         laia->laia_count = &count;
283         set = ptlrpc_prep_set();
284         if (set == NULL)
285                 GOTO(out, rc = -ENOMEM);
286
287         down_read(&ltds->ltd_rw_sem);
288         for_each_set_bit(idx, lad->lad_bitmap, lad->lad_bitmap_count) {
289                 ltd = lfsck_ltd2tgt(ltds, idx);
290                 if (unlikely(!ltd))
291                         continue;
292
293                 laia->laia_ltd = ltd;
294                 rc = lfsck_async_request(env, ltd->ltd_exp, lr, set,
295                                 lfsck_layout_assistant_sync_failures_interpret,
296                                 laia, LFSCK_NOTIFY);
297                 if (rc != 0) {
298                         CDEBUG(D_LFSCK, "%s: LFSCK assistant fail to "
299                                "notify target %x for %s phase1 done: "
300                                "rc = %d\n", lfsck_lfsck2name(com->lc_lfsck),
301                                ltd->ltd_index, lad->lad_name, rc);
302
303                         break;
304                 }
305
306                 atomic_inc(&count);
307         }
308         up_read(&ltds->ltd_rw_sem);
309
310         if (rc == 0 && atomic_read(&count) > 0)
311                 rc = ptlrpc_set_wait(env, set);
312
313         ptlrpc_set_destroy(set);
314
315         if (rc == 0 && atomic_read(&count) > 0)
316                 rc = -EINVAL;
317
318         GOTO(out, rc);
319
320 out:
321         if (rc != 0)
322                 /* If failed to sync failures with the OSTs, then have to
323                  * mark the whole LFSCK as LF_INCOMPLETE to skip the whole
324                  * subsequent orphan OST-object handling. */
325                 lo->ll_flags |= LF_INCOMPLETE;
326
327         lr->lr_flags2 = lo->ll_flags;
328 }
329
330 static int lfsck_layout_verify_header_v1v3(struct dt_object *obj,
331                                            struct lov_mds_md_v1 *lmm,
332                                            __u64 start, __u64 end,
333                                            __u32 comp_id,
334                                            bool ext, bool *dom)
335 {
336         __u32 magic;
337         __u32 pattern;
338         __u32 size;
339
340         magic = le32_to_cpu(lmm->lmm_magic);
341         /* If magic crashed, keep it there. Sometime later, during OST-object
342          * orphan handling, if some OST-object(s) back-point to it, it can be
343          * verified and repaired. */
344         if (magic != LOV_MAGIC_V1 && magic != LOV_MAGIC_V3) {
345                 int rc;
346
347                 if ((magic & LOV_MAGIC_MASK) == LOV_MAGIC_MAGIC)
348                         rc = -EOPNOTSUPP;
349                 else
350                         rc = -EINVAL;
351
352                 CDEBUG(D_LFSCK, "%s LOV EA magic 0x%X for the file "DFID"\n",
353                        rc == -EINVAL ? "Unknown" : "Unsupported",
354                        magic, PFID(lfsck_dto2fid(obj)));
355
356                 return rc;
357         }
358
359         pattern = le32_to_cpu(lmm->lmm_pattern);
360         *dom = !!(lov_pattern(pattern) == LOV_PATTERN_MDT);
361
362         /* XXX: DoM file verification will be supportted via LU-11081. */
363         if (lov_pattern(pattern) == LOV_PATTERN_MDT) {
364 #if 0
365                 if (start != 0) {
366                         CDEBUG(D_LFSCK, "The DoM entry for "DFID" is not "
367                                "the first component in the mirror %x/%llu\n",
368                                PFID(lfsck_dto2fid(obj)), comp_id, start);
369
370                         return -EINVAL;
371                 }
372 #endif
373         } else if (!lov_pattern_supported_normal_comp(lov_pattern(pattern))) {
374                 CDEBUG(D_LFSCK, "Unsupported LOV EA pattern %u for the file "
375                        DFID" in the component %x\n",
376                        pattern, PFID(lfsck_dto2fid(obj)), comp_id);
377
378                 return -EOPNOTSUPP;
379         }
380
381         size = le32_to_cpu(lmm->lmm_stripe_size);
382         if (!ext && end != LUSTRE_EOF && start != end &&
383             !lfsck_comp_extent_aligned(end, size)){
384                 CDEBUG(D_LFSCK, "not aligned border in PFL extent range "
385                        "[%llu - %llu) stripesize %u for the file "DFID
386                        " at idx %d\n", start, end, size,
387                        PFID(lfsck_dto2fid(obj)), comp_id);
388
389                 return -EINVAL;
390         }
391
392         return 0;
393 }
394
395 static int lfsck_layout_verify_header_foreign(struct dt_object *obj,
396                                               struct lov_foreign_md *lfm,
397                                               size_t len)
398 {
399         /* magic has been verified already */
400         __u32 value_len = le32_to_cpu(lfm->lfm_length);
401         /* type and flags are not checked for instance */
402
403         CDEBUG(D_INFO, "foreign LOV EA, magic %x, len %u, type %x, flags %x, for file "DFID"\n",
404                le32_to_cpu(lfm->lfm_magic), value_len,
405                le32_to_cpu(lfm->lfm_type), le32_to_cpu(lfm->lfm_flags),
406                PFID(lfsck_dto2fid(obj)));
407
408         if (len != value_len + offsetof(typeof(*lfm), lfm_value))
409                 CDEBUG(D_LFSCK, "foreign LOV EA internal size %u does not match EA full size %zu for file "DFID"\n",
410                        value_len, len, PFID(lfsck_dto2fid(obj)));
411
412         /* nothing to repair */
413         return -ENODATA;
414 }
415
416 static int lfsck_layout_verify_header(struct dt_object *obj,
417                                       struct lov_mds_md_v1 *lmm, size_t len)
418 {
419         bool p_dom = false;
420         int rc = 0;
421
422         if (le32_to_cpu(lmm->lmm_magic) == LOV_MAGIC_COMP_V1 ||
423             le32_to_cpu(lmm->lmm_magic) == LOV_MAGIC_SEL) {
424                 struct lov_comp_md_v1 *lcm = (struct lov_comp_md_v1 *)lmm;
425                 bool p_zero = false;
426                 int i;
427                 __u16 count = le16_to_cpu(lcm->lcm_entry_count);
428
429                 if (unlikely(count == 0)) {
430                         CDEBUG(D_LFSCK, "the PFL file "DFID" contains invalid "
431                                "components count 0\n",
432                                PFID(lfsck_dto2fid(obj)));
433
434                         return -EINVAL;
435                 }
436
437                 for (i = 0; i < count && !rc; i++) {
438                         struct lov_comp_md_entry_v1 *lcme =
439                                                 &lcm->lcm_entries[i];
440                         __u64 start = le64_to_cpu(lcme->lcme_extent.e_start);
441                         __u64 end = le64_to_cpu(lcme->lcme_extent.e_end);
442                         __u32 comp_id = le32_to_cpu(lcme->lcme_id);
443                         bool ext, inited, zero;
444                         __u32 flags;
445
446                         if (unlikely(comp_id == LCME_ID_INVAL ||
447                                      comp_id > LCME_ID_MAX)) {
448                                 CDEBUG(D_LFSCK, "found invalid PFL ID %u "
449                                        "for the file "DFID" at idx %d\n",
450                                        comp_id, PFID(lfsck_dto2fid(obj)), i);
451
452                                 return -EINVAL;
453                         }
454
455                         flags = le32_to_cpu(lcme->lcme_flags);
456                         ext = flags & LCME_FL_EXTENSION;
457                         inited = flags & LCME_FL_INIT;
458                         zero = !!(start == end);
459
460                         if ((i == 0) && zero) {
461                                 CDEBUG(D_LFSCK, "invalid PFL comp %d: [%llu "
462                                        "- %llu) for "DFID"\n", i, start, end,
463                                        PFID(lfsck_dto2fid(obj)));
464                                 return -EINVAL;
465                         }
466
467                         if ((zero && (inited || (i + 1 == count))) ||
468                             (start > end)) {
469                                 CDEBUG(D_LFSCK, "invalid PFL comp %d/%d: "
470                                        "[%llu, %llu) for "DFID", %sinited\n",
471                                        i, count, start, end,
472                                        PFID(lfsck_dto2fid(obj)),
473                                        inited ? "" : "NOT ");
474                                 return -EINVAL;
475                         }
476
477                         if (!ext && p_zero) {
478                                 CDEBUG(D_LFSCK, "invalid PFL comp %d: [%llu, "
479                                        "%llu) for "DFID": NOT extension "
480                                        "after 0-length component\n", i,
481                                        start, end, PFID(lfsck_dto2fid(obj)));
482                                 return -EINVAL;
483                         }
484
485                         if (ext && (inited || p_dom || zero)) {
486                                 CDEBUG(D_LFSCK, "invalid PFL comp %d: [%llu, "
487                                        "%llu) for "DFID": %s\n", i,
488                                        start, end, PFID(lfsck_dto2fid(obj)),
489                                        inited ? "inited extension" :
490                                        p_dom ? "extension follows DOM" :
491                                        zero ? "zero length extension" : "");
492                                 return -EINVAL;
493                         }
494
495                         rc = lfsck_layout_verify_header_v1v3(obj,
496                                         (struct lov_mds_md_v1 *)((char *)lmm +
497                                         le32_to_cpu(lcme->lcme_offset)), start,
498                                         end, comp_id, ext, &p_dom);
499
500                         p_zero = zero;
501                 }
502         } else if (le32_to_cpu(lmm->lmm_magic) == LOV_MAGIC_FOREIGN) {
503                 rc = lfsck_layout_verify_header_foreign(obj,
504                                                 (struct lov_foreign_md *)lmm,
505                                                 len);
506         } else {
507                 rc = lfsck_layout_verify_header_v1v3(obj, lmm, 0, LUSTRE_EOF,
508                                                      0, false, &p_dom);
509         }
510
511         return rc;
512 }
513
514 static int lfsck_layout_get_lovea(const struct lu_env *env,
515                                   struct dt_object *obj, struct lu_buf *buf)
516 {
517         int rc;
518         int rc1;
519
520 again:
521         rc = dt_xattr_get(env, obj, buf, XATTR_NAME_LOV);
522         if (rc == -ERANGE) {
523                 rc = dt_xattr_get(env, obj, &LU_BUF_NULL, XATTR_NAME_LOV);
524                 if (rc <= 0)
525                         return !rc ? -ENODATA : rc;
526
527                 lu_buf_realloc(buf, rc);
528                 if (buf->lb_buf == NULL)
529                         return -ENOMEM;
530
531                 goto again;
532         }
533
534         if (rc <= 0)
535                 return !rc ? -ENODATA : rc;
536
537         if (unlikely(buf->lb_buf == NULL)) {
538                 lu_buf_alloc(buf, rc);
539                 if (buf->lb_buf == NULL)
540                         return -ENOMEM;
541
542                 goto again;
543         }
544
545         rc1 = lfsck_layout_verify_header(obj, buf->lb_buf, rc);
546
547         return rc1 ? rc1 : rc;
548 }
549
550 #define LFSCK_RBTREE_BITMAP_SIZE        PAGE_SIZE
551 #define LFSCK_RBTREE_BITMAP_WIDTH       (LFSCK_RBTREE_BITMAP_SIZE << 3)
552 #define LFSCK_RBTREE_BITMAP_MASK        (LFSCK_RBTREE_BITMAP_WIDTH - 1)
553
554 struct lfsck_rbtree_node {
555         struct rb_node   lrn_node;
556         __u64            lrn_seq;
557         __u32            lrn_first_oid;
558         atomic_t         lrn_known_count;
559         atomic_t         lrn_accessed_count;
560         void            *lrn_known_bitmap;
561         void            *lrn_accessed_bitmap;
562 };
563
564 static inline int lfsck_rbtree_cmp(struct lfsck_rbtree_node *lrn,
565                                    __u64 seq, __u32 oid)
566 {
567         if (seq < lrn->lrn_seq)
568                 return -1;
569
570         if (seq > lrn->lrn_seq)
571                 return 1;
572
573         if (oid < lrn->lrn_first_oid)
574                 return -1;
575
576         if (oid - lrn->lrn_first_oid >= LFSCK_RBTREE_BITMAP_WIDTH)
577                 return 1;
578
579         return 0;
580 }
581
582 /* The caller should hold llsd->llsd_rb_lock. */
583 static struct lfsck_rbtree_node *
584 lfsck_rbtree_search(struct lfsck_layout_slave_data *llsd,
585                     const struct lu_fid *fid, bool *exact)
586 {
587         struct rb_node           *node  = llsd->llsd_rb_root.rb_node;
588         struct rb_node           *prev  = NULL;
589         struct lfsck_rbtree_node *lrn   = NULL;
590         int                       rc    = 0;
591
592         if (exact != NULL)
593                 *exact = true;
594
595         while (node != NULL) {
596                 prev = node;
597                 lrn = rb_entry(node, struct lfsck_rbtree_node, lrn_node);
598                 rc = lfsck_rbtree_cmp(lrn, fid_seq(fid), fid_oid(fid));
599                 if (rc < 0)
600                         node = node->rb_left;
601                 else if (rc > 0)
602                         node = node->rb_right;
603                 else
604                         return lrn;
605         }
606
607         if (exact == NULL)
608                 return NULL;
609
610         /* If there is no exactly matched one, then to the next valid one. */
611         *exact = false;
612
613         /* The rbtree is empty. */
614         if (rc == 0)
615                 return NULL;
616
617         if (rc < 0)
618                 return lrn;
619
620         node = rb_next(prev);
621
622         /* The end of the rbtree. */
623         if (node == NULL)
624                 return NULL;
625
626         lrn = rb_entry(node, struct lfsck_rbtree_node, lrn_node);
627
628         return lrn;
629 }
630
631 static struct lfsck_rbtree_node *lfsck_rbtree_new(const struct lu_env *env,
632                                                   const struct lu_fid *fid)
633 {
634         struct lfsck_rbtree_node *lrn;
635
636         OBD_ALLOC_PTR(lrn);
637         if (lrn == NULL)
638                 return ERR_PTR(-ENOMEM);
639
640         OBD_ALLOC(lrn->lrn_known_bitmap, LFSCK_RBTREE_BITMAP_SIZE);
641         if (lrn->lrn_known_bitmap == NULL) {
642                 OBD_FREE_PTR(lrn);
643
644                 return ERR_PTR(-ENOMEM);
645         }
646
647         OBD_ALLOC(lrn->lrn_accessed_bitmap, LFSCK_RBTREE_BITMAP_SIZE);
648         if (lrn->lrn_accessed_bitmap == NULL) {
649                 OBD_FREE(lrn->lrn_known_bitmap, LFSCK_RBTREE_BITMAP_SIZE);
650                 OBD_FREE_PTR(lrn);
651
652                 return ERR_PTR(-ENOMEM);
653         }
654
655         RB_CLEAR_NODE(&lrn->lrn_node);
656         lrn->lrn_seq = fid_seq(fid);
657         lrn->lrn_first_oid = fid_oid(fid) & ~LFSCK_RBTREE_BITMAP_MASK;
658         atomic_set(&lrn->lrn_known_count, 0);
659         atomic_set(&lrn->lrn_accessed_count, 0);
660
661         return lrn;
662 }
663
664 static void lfsck_rbtree_free(struct lfsck_rbtree_node *lrn)
665 {
666         OBD_FREE(lrn->lrn_accessed_bitmap, LFSCK_RBTREE_BITMAP_SIZE);
667         OBD_FREE(lrn->lrn_known_bitmap, LFSCK_RBTREE_BITMAP_SIZE);
668         OBD_FREE_PTR(lrn);
669 }
670
671 /* The caller should hold lock. */
672 static struct lfsck_rbtree_node *
673 lfsck_rbtree_insert(struct lfsck_layout_slave_data *llsd,
674                     struct lfsck_rbtree_node *lrn)
675 {
676         struct rb_node           **pos    = &llsd->llsd_rb_root.rb_node;
677         struct rb_node            *parent = NULL;
678         struct lfsck_rbtree_node  *tmp;
679         int                        rc;
680
681         while (*pos != NULL) {
682                 parent = *pos;
683                 tmp = rb_entry(parent, struct lfsck_rbtree_node, lrn_node);
684                 rc = lfsck_rbtree_cmp(tmp, lrn->lrn_seq, lrn->lrn_first_oid);
685                 if (rc < 0)
686                         pos = &(*pos)->rb_left;
687                 else if (rc > 0)
688                         pos = &(*pos)->rb_right;
689                 else
690                         return tmp;
691         }
692
693         rb_link_node(&lrn->lrn_node, parent, pos);
694         rb_insert_color(&lrn->lrn_node, &llsd->llsd_rb_root);
695
696         return lrn;
697 }
698
699 static const struct dt_index_operations lfsck_orphan_index_ops;
700
701 static int lfsck_rbtree_setup(const struct lu_env *env,
702                               struct lfsck_component *com)
703 {
704         struct lu_fid                   *fid    = &lfsck_env_info(env)->lti_fid;
705         struct lfsck_instance           *lfsck  = com->lc_lfsck;
706         struct dt_device                *dev    = lfsck->li_bottom;
707         struct lfsck_layout_slave_data  *llsd   = com->lc_data;
708         struct dt_object                *obj;
709
710         fid->f_seq = FID_SEQ_LAYOUT_RBTREE;
711         fid->f_oid = lfsck_dev_idx(lfsck);
712         fid->f_ver = 0;
713         obj = dt_locate(env, dev, fid);
714         if (IS_ERR(obj))
715                 RETURN(PTR_ERR(obj));
716
717         /* Generate an in-RAM object to stand for the layout rbtree.
718          * Scanning the layout rbtree will be via the iteration over
719          * the object. In the future, the rbtree may be written onto
720          * disk with the object.
721          *
722          * Mark the object to be as exist. */
723         obj->do_lu.lo_header->loh_attr |= LOHA_EXISTS;
724         obj->do_index_ops = &lfsck_orphan_index_ops;
725         llsd->llsd_rb_obj = obj;
726         llsd->llsd_rbtree_valid = 1;
727         dev->dd_record_fid_accessed = 1;
728
729         CDEBUG(D_LFSCK, "%s: layout LFSCK init OST-objects accessing bitmap\n",
730                lfsck_lfsck2name(lfsck));
731
732         return 0;
733 }
734
735 static void lfsck_rbtree_cleanup(const struct lu_env *env,
736                                  struct lfsck_component *com)
737 {
738         struct lfsck_instance           *lfsck = com->lc_lfsck;
739         struct lfsck_layout_slave_data  *llsd  = com->lc_data;
740         struct rb_node                  *node  = rb_first(&llsd->llsd_rb_root);
741         struct rb_node                  *next;
742         struct lfsck_rbtree_node        *lrn;
743
744         lfsck->li_bottom->dd_record_fid_accessed = 0;
745         /* Invalid the rbtree, then no others will use it. */
746         down_write(&llsd->llsd_rb_rwsem);
747         llsd->llsd_rbtree_valid = 0;
748         up_write(&llsd->llsd_rb_rwsem);
749
750         while (node != NULL) {
751                 next = rb_next(node);
752                 lrn = rb_entry(node, struct lfsck_rbtree_node, lrn_node);
753                 rb_erase(node, &llsd->llsd_rb_root);
754                 lfsck_rbtree_free(lrn);
755                 node = next;
756         }
757
758         if (llsd->llsd_rb_obj != NULL) {
759                 lfsck_object_put(env, llsd->llsd_rb_obj);
760                 llsd->llsd_rb_obj = NULL;
761         }
762
763         CDEBUG(D_LFSCK, "%s: layout LFSCK fini OST-objects accessing bitmap\n",
764                lfsck_lfsck2name(lfsck));
765 }
766
767 static void lfsck_rbtree_update_bitmap(const struct lu_env *env,
768                                        struct lfsck_component *com,
769                                        const struct lu_fid *fid,
770                                        bool accessed)
771 {
772         struct lfsck_layout_slave_data  *llsd   = com->lc_data;
773         struct lfsck_rbtree_node        *lrn;
774         bool                             insert = false;
775         int                              idx;
776         int                              rc     = 0;
777         ENTRY;
778
779         if (unlikely(!fid_is_sane(fid) || fid_is_last_id(fid)))
780                 RETURN_EXIT;
781
782         if (!fid_is_idif(fid) && !fid_is_norm(fid))
783                 RETURN_EXIT;
784
785         down_read(&llsd->llsd_rb_rwsem);
786         if (!llsd->llsd_rbtree_valid)
787                 GOTO(unlock, rc = 0);
788
789         lrn = lfsck_rbtree_search(llsd, fid, NULL);
790         if (lrn == NULL) {
791                 struct lfsck_rbtree_node *tmp;
792
793                 LASSERT(!insert);
794
795                 up_read(&llsd->llsd_rb_rwsem);
796                 tmp = lfsck_rbtree_new(env, fid);
797                 if (IS_ERR(tmp))
798                         GOTO(out, rc = PTR_ERR(tmp));
799
800                 insert = true;
801                 down_write(&llsd->llsd_rb_rwsem);
802                 if (!llsd->llsd_rbtree_valid) {
803                         lfsck_rbtree_free(tmp);
804                         GOTO(unlock, rc = 0);
805                 }
806
807                 lrn = lfsck_rbtree_insert(llsd, tmp);
808                 if (lrn != tmp)
809                         lfsck_rbtree_free(tmp);
810         }
811
812         idx = fid_oid(fid) & LFSCK_RBTREE_BITMAP_MASK;
813         /* Any accessed object must be a known object. */
814         if (!test_and_set_bit(idx, lrn->lrn_known_bitmap))
815                 atomic_inc(&lrn->lrn_known_count);
816         if (accessed && !test_and_set_bit(idx, lrn->lrn_accessed_bitmap))
817                 atomic_inc(&lrn->lrn_accessed_count);
818
819         GOTO(unlock, rc = 0);
820
821 unlock:
822         if (insert)
823                 up_write(&llsd->llsd_rb_rwsem);
824         else
825                 up_read(&llsd->llsd_rb_rwsem);
826 out:
827         if (rc != 0 && accessed) {
828                 struct lfsck_layout *lo = com->lc_file_ram;
829
830                 CDEBUG(D_LFSCK, "%s: fail to update OST-objects accessing "
831                        "bitmap, and will cause incorrect LFSCK OST-object "
832                        "handling, so disable it to cancel orphan handling "
833                        "for related device. rc = %d\n",
834                        lfsck_lfsck2name(com->lc_lfsck), rc);
835
836                 lo->ll_flags |= LF_INCOMPLETE;
837                 lfsck_rbtree_cleanup(env, com);
838         }
839 }
840
841 static inline void lldk_le_to_cpu(struct lfsck_layout_dangling_key *des,
842                                   const struct lfsck_layout_dangling_key *src)
843 {
844         fid_le_to_cpu(&des->lldk_fid, &src->lldk_fid);
845         des->lldk_comp_id = le32_to_cpu(src->lldk_comp_id);
846         des->lldk_ea_off = le32_to_cpu(src->lldk_ea_off);
847 }
848
849 static inline void lldk_cpu_to_le(struct lfsck_layout_dangling_key *des,
850                                   const struct lfsck_layout_dangling_key *src)
851 {
852         fid_cpu_to_le(&des->lldk_fid, &src->lldk_fid);
853         des->lldk_comp_id = cpu_to_le32(src->lldk_comp_id);
854         des->lldk_ea_off = cpu_to_le32(src->lldk_ea_off);
855 }
856
857 static inline void lldk_be_to_cpu(struct lfsck_layout_dangling_key *des,
858                                   const struct lfsck_layout_dangling_key *src)
859 {
860         fid_be_to_cpu(&des->lldk_fid, &src->lldk_fid);
861         des->lldk_comp_id = be32_to_cpu(src->lldk_comp_id);
862         des->lldk_ea_off = be32_to_cpu(src->lldk_ea_off);
863 }
864
865 static inline void lldk_cpu_to_be(struct lfsck_layout_dangling_key *des,
866                                   const struct lfsck_layout_dangling_key *src)
867 {
868         fid_cpu_to_be(&des->lldk_fid, &src->lldk_fid);
869         des->lldk_comp_id = cpu_to_be32(src->lldk_comp_id);
870         des->lldk_ea_off = cpu_to_be32(src->lldk_ea_off);
871 }
872
873 static void lfsck_layout_le_to_cpu(struct lfsck_layout *des,
874                                    const struct lfsck_layout *src)
875 {
876         int i;
877
878         des->ll_magic = le32_to_cpu(src->ll_magic);
879         des->ll_status = le32_to_cpu(src->ll_status);
880         des->ll_flags = le32_to_cpu(src->ll_flags);
881         des->ll_success_count = le32_to_cpu(src->ll_success_count);
882         des->ll_run_time_phase1 = le64_to_cpu(src->ll_run_time_phase1);
883         des->ll_run_time_phase2 = le64_to_cpu(src->ll_run_time_phase2);
884         des->ll_time_last_complete = le64_to_cpu(src->ll_time_last_complete);
885         des->ll_time_latest_start = le64_to_cpu(src->ll_time_latest_start);
886         des->ll_time_last_checkpoint =
887                                 le64_to_cpu(src->ll_time_last_checkpoint);
888         des->ll_pos_latest_start = le64_to_cpu(src->ll_pos_latest_start);
889         des->ll_pos_last_checkpoint = le64_to_cpu(src->ll_pos_last_checkpoint);
890         des->ll_pos_first_inconsistent =
891                         le64_to_cpu(src->ll_pos_first_inconsistent);
892         des->ll_objs_checked_phase1 = le64_to_cpu(src->ll_objs_checked_phase1);
893         des->ll_objs_failed_phase1 = le64_to_cpu(src->ll_objs_failed_phase1);
894         des->ll_objs_checked_phase2 = le64_to_cpu(src->ll_objs_checked_phase2);
895         des->ll_objs_failed_phase2 = le64_to_cpu(src->ll_objs_failed_phase2);
896         for (i = 0; i < LLIT_MAX; i++)
897                 des->ll_objs_repaired[i] =
898                                 le64_to_cpu(src->ll_objs_repaired[i]);
899         des->ll_objs_skipped = le64_to_cpu(src->ll_objs_skipped);
900         des->ll_bitmap_size = le32_to_cpu(src->ll_bitmap_size);
901         lldk_le_to_cpu(&des->ll_lldk_latest_scanned_phase2,
902                        &src->ll_lldk_latest_scanned_phase2);
903 }
904
905 static void lfsck_layout_cpu_to_le(struct lfsck_layout *des,
906                                    const struct lfsck_layout *src)
907 {
908         int i;
909
910         des->ll_magic = cpu_to_le32(src->ll_magic);
911         des->ll_status = cpu_to_le32(src->ll_status);
912         des->ll_flags = cpu_to_le32(src->ll_flags);
913         des->ll_success_count = cpu_to_le32(src->ll_success_count);
914         des->ll_run_time_phase1 = cpu_to_le64(src->ll_run_time_phase1);
915         des->ll_run_time_phase2 = cpu_to_le64(src->ll_run_time_phase2);
916         des->ll_time_last_complete = cpu_to_le64(src->ll_time_last_complete);
917         des->ll_time_latest_start = cpu_to_le64(src->ll_time_latest_start);
918         des->ll_time_last_checkpoint =
919                                 cpu_to_le64(src->ll_time_last_checkpoint);
920         des->ll_pos_latest_start = cpu_to_le64(src->ll_pos_latest_start);
921         des->ll_pos_last_checkpoint = cpu_to_le64(src->ll_pos_last_checkpoint);
922         des->ll_pos_first_inconsistent =
923                         cpu_to_le64(src->ll_pos_first_inconsistent);
924         des->ll_objs_checked_phase1 = cpu_to_le64(src->ll_objs_checked_phase1);
925         des->ll_objs_failed_phase1 = cpu_to_le64(src->ll_objs_failed_phase1);
926         des->ll_objs_checked_phase2 = cpu_to_le64(src->ll_objs_checked_phase2);
927         des->ll_objs_failed_phase2 = cpu_to_le64(src->ll_objs_failed_phase2);
928         for (i = 0; i < LLIT_MAX; i++)
929                 des->ll_objs_repaired[i] =
930                                 cpu_to_le64(src->ll_objs_repaired[i]);
931         des->ll_objs_skipped = cpu_to_le64(src->ll_objs_skipped);
932         des->ll_bitmap_size = cpu_to_le32(src->ll_bitmap_size);
933         lldk_cpu_to_le(&des->ll_lldk_latest_scanned_phase2,
934                        &src->ll_lldk_latest_scanned_phase2);
935 }
936
937 /**
938  * Load the OST bitmap from the lfsck_layout trace file.
939  *
940  * \param[in] env       pointer to the thread context
941  * \param[in] com       pointer to the lfsck component
942  *
943  * \retval              0 for success
944  * \retval              negative error number on failure or data corruption
945  */
946 static int lfsck_layout_load_bitmap(const struct lu_env *env,
947                                     struct lfsck_component *com)
948 {
949         struct dt_object *obj = com->lc_obj;
950         struct lfsck_assistant_data *lad = com->lc_data;
951         struct lfsck_layout *lo = com->lc_file_ram;
952         unsigned long *bitmap = lad->lad_bitmap;
953         loff_t pos = com->lc_file_size;
954         ssize_t size;
955         __u32 nbits;
956         int rc;
957
958         ENTRY;
959         if (com->lc_lfsck->li_ost_descs.ltd_tgts_mask_len > lo->ll_bitmap_size)
960                 nbits = com->lc_lfsck->li_ost_descs.ltd_tgts_mask_len;
961         else
962                 nbits = lo->ll_bitmap_size;
963
964         if (unlikely(nbits < BITS_PER_LONG))
965                 nbits = BITS_PER_LONG;
966
967         if (nbits > lad->lad_bitmap_count) {
968                 u32 new_bits = lad->lad_bitmap_count;
969                 unsigned long *new_bitmap;
970
971                 while (new_bits < nbits)
972                         new_bits <<= 1;
973
974                 new_bitmap = bitmap_zalloc(new_bits, GFP_KERNEL);
975                 if (new_bitmap == NULL)
976                         RETURN(-ENOMEM);
977
978                 lad->lad_bitmap = new_bitmap;
979                 lad->lad_bitmap_count = new_bits;
980                 bitmap_free(bitmap);
981                 bitmap = new_bitmap;
982         }
983
984         if (lo->ll_bitmap_size == 0) {
985                 clear_bit(LAD_INCOMPLETE, &lad->lad_flags);
986                 bitmap_zero(bitmap, lad->lad_bitmap_count);
987                 RETURN(0);
988         }
989
990         size = (lo->ll_bitmap_size + 7) >> 3;
991         rc = dt_read(env, obj, lfsck_buf_get(env, bitmap, size), &pos);
992         if (rc != size)
993                 RETURN(rc >= 0 ? -EINVAL : rc);
994
995         if (bitmap_empty(bitmap, lad->lad_bitmap_count))
996                 clear_bit(LAD_INCOMPLETE, &lad->lad_flags);
997         else
998                 set_bit(LAD_INCOMPLETE, &lad->lad_flags);
999
1000         RETURN(0);
1001 }
1002
1003 /**
1004  * Load the layout LFSCK trace file from disk.
1005  *
1006  * The layout LFSCK trace file records the layout LFSCK status information
1007  * and other statistics, such as how many objects have been scanned, and how
1008  * many objects have been repaired, and etc. It also contains the bitmap for
1009  * failed OSTs during the layout LFSCK. All these information will be loaded
1010  * from disk to RAM when the layout LFSCK component setup.
1011  *
1012  * \param[in] env       pointer to the thread context
1013  * \param[in] com       pointer to the lfsck component
1014  *
1015  * \retval              positive number for file data corruption, the caller
1016  *                      should reset the layout LFSCK trace file
1017  * \retval              0 for success
1018  * \retval              negative error number on failure
1019  */
1020 static int lfsck_layout_load(const struct lu_env *env,
1021                              struct lfsck_component *com)
1022 {
1023         struct lfsck_layout             *lo     = com->lc_file_ram;
1024         ssize_t                          size   = com->lc_file_size;
1025         loff_t                           pos    = 0;
1026         int                              rc;
1027
1028         rc = dt_read(env, com->lc_obj,
1029                      lfsck_buf_get(env, com->lc_file_disk, size), &pos);
1030         if (rc == 0) {
1031                 return -ENOENT;
1032         } else if (rc < 0) {
1033                 CDEBUG(D_LFSCK, "%s: failed to load lfsck_layout: rc = %d\n",
1034                        lfsck_lfsck2name(com->lc_lfsck), rc);
1035                 return rc;
1036         } else if (rc != size) {
1037                 CDEBUG(D_LFSCK, "%s: lfsck_layout size %u != %u; reset it\n",
1038                        lfsck_lfsck2name(com->lc_lfsck), rc, (unsigned int)size);
1039                 return 1;
1040         }
1041
1042         lfsck_layout_le_to_cpu(lo, com->lc_file_disk);
1043         if (lo->ll_magic != LFSCK_LAYOUT_MAGIC) {
1044                 CDEBUG(D_LFSCK, "%s: invalid lfsck_layout magic %#x != %#x, "
1045                        "to be reset\n", lfsck_lfsck2name(com->lc_lfsck),
1046                        lo->ll_magic, LFSCK_LAYOUT_MAGIC);
1047                 return 1;
1048         }
1049
1050         return 0;
1051 }
1052
1053 /**
1054  * Store the layout LFSCK trace file on disk.
1055  *
1056  * The layout LFSCK trace file records the layout LFSCK status information
1057  * and other statistics, such as how many objects have been scanned, and how
1058  * many objects have been repaired, and etc. It also contains the bitmap for
1059  * failed OSTs during the layout LFSCK. All these information will be synced
1060  * from RAM to disk periodically.
1061  *
1062  * \param[in] env       pointer to the thread context
1063  * \param[in] com       pointer to the lfsck component
1064  *
1065  * \retval              0 for success
1066  * \retval              negative error number on failure
1067  */
1068 static int lfsck_layout_store(const struct lu_env *env,
1069                               struct lfsck_component *com)
1070 {
1071         struct dt_object *obj = com->lc_obj;
1072         struct lfsck_instance *lfsck = com->lc_lfsck;
1073         struct lfsck_layout *lo_ram = com->lc_file_ram;
1074         struct lfsck_layout *lo = com->lc_file_disk;
1075         struct thandle *th;
1076         struct dt_device *dev = lfsck_obj2dev(obj);
1077         unsigned long *bitmap = NULL;
1078         loff_t pos;
1079         ssize_t size = com->lc_file_size;
1080         __u32 nbits = 0;
1081         int rc;
1082
1083         ENTRY;
1084         if (lfsck->li_master) {
1085                 struct lfsck_assistant_data *lad = com->lc_data;
1086
1087                 bitmap = lad->lad_bitmap;
1088                 nbits = lad->lad_bitmap_count;
1089
1090                 LASSERT(nbits > 0);
1091                 LASSERTF((nbits & 7) == 0, "Invalid nbits %u\n", nbits);
1092         }
1093
1094         lo_ram->ll_bitmap_size = nbits;
1095         lfsck_layout_cpu_to_le(lo, lo_ram);
1096         th = dt_trans_create(env, dev);
1097         if (IS_ERR(th))
1098                 GOTO(log, rc = PTR_ERR(th));
1099
1100         rc = dt_declare_record_write(env, obj, lfsck_buf_get(env, lo, size),
1101                                      (loff_t)0, th);
1102         if (rc != 0)
1103                 GOTO(out, rc);
1104
1105         if (bitmap != NULL) {
1106                 rc = dt_declare_record_write(env, obj,
1107                                 lfsck_buf_get(env, bitmap, nbits >> 3),
1108                                 (loff_t)size, th);
1109                 if (rc != 0)
1110                         GOTO(out, rc);
1111         }
1112
1113         rc = dt_trans_start_local(env, dev, th);
1114         if (rc != 0)
1115                 GOTO(out, rc);
1116
1117         pos = 0;
1118         rc = dt_record_write(env, obj, lfsck_buf_get(env, lo, size), &pos, th);
1119         if (rc != 0)
1120                 GOTO(out, rc);
1121
1122         if (bitmap != NULL) {
1123                 pos = size;
1124                 rc = dt_record_write(env, obj,
1125                                 lfsck_buf_get(env, bitmap, nbits >> 3),
1126                                 &pos, th);
1127         }
1128
1129         GOTO(out, rc);
1130
1131 out:
1132         dt_trans_stop(env, dev, th);
1133
1134 log:
1135         if (rc != 0)
1136                 CDEBUG(D_LFSCK, "%s: fail to store lfsck_layout: rc = %d\n",
1137                        lfsck_lfsck2name(lfsck), rc);
1138
1139         return rc;
1140 }
1141
1142 static int lfsck_layout_init(const struct lu_env *env,
1143                              struct lfsck_component *com)
1144 {
1145         struct lfsck_layout *lo = com->lc_file_ram;
1146         int rc;
1147
1148         memset(lo, 0, com->lc_file_size);
1149         lo->ll_magic = LFSCK_LAYOUT_MAGIC;
1150         lo->ll_status = LS_INIT;
1151         down_write(&com->lc_sem);
1152         rc = lfsck_layout_store(env, com);
1153         if (rc == 0 && com->lc_lfsck->li_master)
1154                 rc = lfsck_load_sub_trace_files(env, com,
1155                         &dt_lfsck_layout_dangling_features, LFSCK_LAYOUT, true);
1156         up_write(&com->lc_sem);
1157
1158         return rc;
1159 }
1160
1161 static int fid_is_for_ostobj(const struct lu_env *env,
1162                              struct lfsck_instance *lfsck,
1163                              struct dt_object *obj, const struct lu_fid *fid)
1164 {
1165         struct seq_server_site  *ss     = lfsck_dev_site(lfsck);
1166         struct lu_seq_range     *range  = &lfsck_env_info(env)->lti_range;
1167         struct lustre_ost_attrs *loa;
1168         int                      rc;
1169
1170         fld_range_set_any(range);
1171         rc = fld_server_lookup(env, ss->ss_server_fld, fid_seq(fid), range);
1172         if (rc == 0) {
1173                 if (fld_range_is_ost(range))
1174                         return 1;
1175
1176                 return 0;
1177         }
1178
1179         loa = &lfsck_env_info(env)->lti_loa;
1180         rc = dt_xattr_get(env, obj, lfsck_buf_get(env, loa, sizeof(*loa)),
1181                           XATTR_NAME_LMA);
1182         if (rc >= (int)sizeof(struct lustre_mdt_attrs)) {
1183                 lustre_lma_swab(&loa->loa_lma);
1184
1185                 return loa->loa_lma.lma_compat & LMAC_FID_ON_OST ? 1 : 0;
1186         }
1187
1188         rc = dt_xattr_get(env, obj, &LU_BUF_NULL, XATTR_NAME_FID);
1189
1190         return rc > 0;
1191 }
1192
1193 static struct lfsck_layout_seq *
1194 lfsck_layout_seq_lookup(struct lfsck_layout_slave_data *llsd, __u64 seq)
1195 {
1196         struct lfsck_layout_seq *lls;
1197
1198         list_for_each_entry(lls, &llsd->llsd_seq_list, lls_list) {
1199                 if (lls->lls_seq == seq)
1200                         return lls;
1201
1202                 if (lls->lls_seq > seq)
1203                         return NULL;
1204         }
1205
1206         return NULL;
1207 }
1208
1209 static void
1210 lfsck_layout_seq_insert(struct lfsck_layout_slave_data *llsd,
1211                         struct lfsck_layout_seq *lls)
1212 {
1213         struct lfsck_layout_seq *tmp;
1214         struct list_head        *pos = &llsd->llsd_seq_list;
1215
1216         list_for_each_entry(tmp, &llsd->llsd_seq_list, lls_list) {
1217                 if (lls->lls_seq < tmp->lls_seq) {
1218                         pos = &tmp->lls_list;
1219                         break;
1220                 }
1221         }
1222         list_add_tail(&lls->lls_list, pos);
1223 }
1224
1225 static int
1226 lfsck_layout_lastid_create(const struct lu_env *env,
1227                            struct lfsck_instance *lfsck,
1228                            struct dt_object *obj)
1229 {
1230         struct lfsck_thread_info *info   = lfsck_env_info(env);
1231         struct lu_attr           *la     = &info->lti_la;
1232         struct dt_object_format  *dof    = &info->lti_dof;
1233         struct lfsck_bookmark    *bk     = &lfsck->li_bookmark_ram;
1234         struct dt_device         *dt     = lfsck_obj2dev(obj);
1235         struct thandle           *th;
1236         __u64                     lastid = 0;
1237         loff_t                    pos    = 0;
1238         int                       rc;
1239         ENTRY;
1240
1241         if (bk->lb_param & LPF_DRYRUN)
1242                 return 0;
1243
1244         memset(la, 0, sizeof(*la));
1245         la->la_mode = S_IFREG |  S_IRUGO | S_IWUSR;
1246         la->la_valid = LA_MODE | LA_UID | LA_GID;
1247         memset(dof, 0, sizeof(*dof));
1248         dof->dof_type = dt_mode_to_dft(S_IFREG);
1249
1250         th = lfsck_trans_create(env, dt, lfsck);
1251         if (IS_ERR(th))
1252                 GOTO(log, rc = PTR_ERR(th));
1253
1254         rc = dt_declare_create(env, obj, la, NULL, dof, th);
1255         if (rc != 0)
1256                 GOTO(stop, rc);
1257
1258         rc = dt_declare_record_write(env, obj,
1259                                      lfsck_buf_get(env, &lastid,
1260                                                    sizeof(lastid)),
1261                                      pos, th);
1262         if (rc != 0)
1263                 GOTO(stop, rc);
1264
1265         rc = dt_trans_start_local(env, dt, th);
1266         if (rc != 0)
1267                 GOTO(stop, rc);
1268
1269         dt_write_lock(env, obj, 0);
1270         if (likely(dt_object_exists(obj) == 0)) {
1271                 rc = dt_create(env, obj, la, NULL, dof, th);
1272                 if (rc == 0)
1273                         rc = dt_record_write(env, obj,
1274                                 lfsck_buf_get(env, &lastid, sizeof(lastid)),
1275                                 &pos, th);
1276         }
1277         dt_write_unlock(env, obj);
1278
1279         GOTO(stop, rc);
1280
1281 stop:
1282         dt_trans_stop(env, dt, th);
1283
1284 log:
1285         CDEBUG(D_LFSCK, "%s: layout LFSCK will create LAST_ID for <seq> "
1286                "%#llx: rc = %d\n",
1287                lfsck_lfsck2name(lfsck), fid_seq(lfsck_dto2fid(obj)), rc);
1288
1289         return rc;
1290 }
1291
1292 static int
1293 lfsck_layout_lastid_reload(const struct lu_env *env,
1294                            struct lfsck_component *com,
1295                            struct lfsck_layout_seq *lls)
1296 {
1297         __u64   lastid;
1298         loff_t  pos     = 0;
1299         int     rc;
1300
1301         dt_read_lock(env, lls->lls_lastid_obj, 0);
1302         rc = dt_record_read(env, lls->lls_lastid_obj,
1303                             lfsck_buf_get(env, &lastid, sizeof(lastid)), &pos);
1304         dt_read_unlock(env, lls->lls_lastid_obj);
1305         if (unlikely(rc != 0))
1306                 return rc;
1307
1308         lastid = le64_to_cpu(lastid);
1309         if (lastid < lls->lls_lastid_known) {
1310                 struct lfsck_instance   *lfsck  = com->lc_lfsck;
1311                 struct lfsck_layout     *lo     = com->lc_file_ram;
1312
1313                 lls->lls_lastid = lls->lls_lastid_known;
1314                 lls->lls_dirty = 1;
1315                 if (!(lo->ll_flags & LF_CRASHED_LASTID)) {
1316                         LASSERT(lfsck->li_out_notify != NULL);
1317
1318                         lfsck->li_out_notify(env, lfsck->li_out_notify_data,
1319                                              LE_LASTID_REBUILDING);
1320                         lo->ll_flags |= LF_CRASHED_LASTID;
1321
1322                         CDEBUG(D_LFSCK, "%s: layout LFSCK finds crashed "
1323                                "LAST_ID file (1) for the sequence %#llx"
1324                                ", old value %llu, known value %llu\n",
1325                                lfsck_lfsck2name(lfsck), lls->lls_seq,
1326                                lastid, lls->lls_lastid);
1327                 }
1328         } else if (lastid >= lls->lls_lastid) {
1329                 lls->lls_lastid = lastid;
1330                 lls->lls_dirty = 0;
1331         }
1332
1333         return 0;
1334 }
1335
1336 static int
1337 lfsck_layout_lastid_store(const struct lu_env *env,
1338                           struct lfsck_component *com)
1339 {
1340         struct lfsck_instance           *lfsck  = com->lc_lfsck;
1341         struct lfsck_bookmark           *bk     = &lfsck->li_bookmark_ram;
1342         struct dt_device                *dt     = lfsck->li_bottom;
1343         struct lfsck_layout_slave_data  *llsd   = com->lc_data;
1344         struct lfsck_layout_seq         *lls;
1345         struct thandle                  *th;
1346         __u64                            lastid;
1347         int                              rc     = 0;
1348         int                              rc1    = 0;
1349
1350         list_for_each_entry(lls, &llsd->llsd_seq_list, lls_list) {
1351                 loff_t pos = 0;
1352
1353                 if (!lls->lls_dirty)
1354                         continue;
1355
1356                 CDEBUG(D_LFSCK, "%s: layout LFSCK will sync the LAST_ID for "
1357                        "<seq> %#llx as <oid> %llu\n",
1358                        lfsck_lfsck2name(lfsck), lls->lls_seq, lls->lls_lastid);
1359
1360                 if (bk->lb_param & LPF_DRYRUN) {
1361                         lls->lls_dirty = 0;
1362                         continue;
1363                 }
1364
1365                 th = lfsck_trans_create(env, dt, lfsck);
1366                 if (IS_ERR(th)) {
1367                         rc1 = PTR_ERR(th);
1368                         CDEBUG(D_LFSCK, "%s: layout LFSCK failed to store "
1369                                "the LAST_ID for <seq> %#llx(1): rc = %d\n",
1370                                lfsck_lfsck2name(com->lc_lfsck),
1371                                lls->lls_seq, rc1);
1372                         continue;
1373                 }
1374
1375                 lastid = cpu_to_le64(lls->lls_lastid);
1376                 rc = dt_declare_record_write(env, lls->lls_lastid_obj,
1377                                              lfsck_buf_get(env, &lastid,
1378                                                            sizeof(lastid)),
1379                                              pos, th);
1380                 if (rc != 0)
1381                         goto stop;
1382
1383                 rc = dt_trans_start_local(env, dt, th);
1384                 if (rc != 0)
1385                         goto stop;
1386
1387                 dt_write_lock(env, lls->lls_lastid_obj, 0);
1388                 rc = dt_record_write(env, lls->lls_lastid_obj,
1389                                      lfsck_buf_get(env, &lastid,
1390                                      sizeof(lastid)), &pos, th);
1391                 dt_write_unlock(env, lls->lls_lastid_obj);
1392                 if (rc == 0)
1393                         lls->lls_dirty = 0;
1394
1395 stop:
1396                 dt_trans_stop(env, dt, th);
1397                 if (rc != 0) {
1398                         rc1 = rc;
1399                         CDEBUG(D_LFSCK, "%s: layout LFSCK failed to store "
1400                                "the LAST_ID for <seq> %#llx(2): rc = %d\n",
1401                                lfsck_lfsck2name(com->lc_lfsck),
1402                                lls->lls_seq, rc1);
1403                 }
1404         }
1405
1406         return rc1;
1407 }
1408
1409 static int
1410 lfsck_layout_lastid_load(const struct lu_env *env,
1411                          struct lfsck_component *com,
1412                          struct lfsck_layout_seq *lls)
1413 {
1414         struct lfsck_instance   *lfsck  = com->lc_lfsck;
1415         struct lfsck_layout     *lo     = com->lc_file_ram;
1416         struct lu_fid           *fid    = &lfsck_env_info(env)->lti_fid;
1417         struct dt_object        *obj;
1418         loff_t                   pos    = 0;
1419         int                      rc;
1420         ENTRY;
1421
1422         lu_last_id_fid(fid, lls->lls_seq, lfsck_dev_idx(lfsck));
1423         obj = dt_locate(env, lfsck->li_bottom, fid);
1424         if (IS_ERR(obj))
1425                 RETURN(PTR_ERR(obj));
1426
1427         /* LAST_ID crashed, to be rebuilt */
1428         if (dt_object_exists(obj) == 0) {
1429                 if (!(lo->ll_flags & LF_CRASHED_LASTID)) {
1430                         LASSERT(lfsck->li_out_notify != NULL);
1431
1432                         lfsck->li_out_notify(env, lfsck->li_out_notify_data,
1433                                              LE_LASTID_REBUILDING);
1434                         lo->ll_flags |= LF_CRASHED_LASTID;
1435
1436                         CDEBUG(D_LFSCK, "%s: layout LFSCK cannot find the "
1437                                "LAST_ID file for sequence %#llx\n",
1438                                lfsck_lfsck2name(lfsck), lls->lls_seq);
1439
1440                         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_DELAY4) &&
1441                             cfs_fail_val > 0) {
1442                                 struct ptlrpc_thread *thread =
1443                                         &lfsck->li_thread;
1444
1445                                 up_write(&com->lc_sem);
1446                                 wait_event_idle_timeout(
1447                                         thread->t_ctl_waitq,
1448                                         !thread_is_running(thread),
1449                                         cfs_time_seconds(cfs_fail_val));
1450                                 down_write(&com->lc_sem);
1451                         }
1452                 }
1453
1454                 rc = lfsck_layout_lastid_create(env, lfsck, obj);
1455         } else {
1456                 dt_read_lock(env, obj, 0);
1457                 rc = dt_read(env, obj,
1458                         lfsck_buf_get(env, &lls->lls_lastid, sizeof(__u64)),
1459                         &pos);
1460                 dt_read_unlock(env, obj);
1461                 if (rc != 0 && rc != sizeof(__u64))
1462                         GOTO(out, rc = (rc > 0 ? -EFAULT : rc));
1463
1464                 if (rc == 0 && !(lo->ll_flags & LF_CRASHED_LASTID)) {
1465                         LASSERT(lfsck->li_out_notify != NULL);
1466
1467                         lfsck->li_out_notify(env, lfsck->li_out_notify_data,
1468                                              LE_LASTID_REBUILDING);
1469                         lo->ll_flags |= LF_CRASHED_LASTID;
1470
1471                         CDEBUG(D_LFSCK, "%s: layout LFSCK finds invalid "
1472                                "LAST_ID file for the sequence %#llx"
1473                                ": rc = %d\n",
1474                                lfsck_lfsck2name(lfsck), lls->lls_seq, rc);
1475                 }
1476
1477                 lls->lls_lastid = le64_to_cpu(lls->lls_lastid);
1478                 rc = 0;
1479         }
1480
1481         GOTO(out, rc);
1482
1483 out:
1484         if (rc != 0)
1485                 lfsck_object_put(env, obj);
1486         else
1487                 lls->lls_lastid_obj = obj;
1488
1489         return rc;
1490 }
1491
1492 static void lfsck_layout_record_failure(const struct lu_env *env,
1493                                         struct lfsck_instance *lfsck,
1494                                         struct lfsck_layout *lo)
1495 {
1496         __u64 cookie;
1497
1498         lo->ll_objs_failed_phase1++;
1499         cookie = lfsck->li_obj_oit->do_index_ops->dio_it.store(env,
1500                                                         lfsck->li_di_oit);
1501         if (lo->ll_pos_first_inconsistent == 0 ||
1502             lo->ll_pos_first_inconsistent < cookie) {
1503                 lo->ll_pos_first_inconsistent = cookie;
1504
1505                 CDEBUG(D_LFSCK, "%s: layout LFSCK hit first non-repaired "
1506                        "inconsistency at the pos [%llu]\n",
1507                        lfsck_lfsck2name(lfsck),
1508                        lo->ll_pos_first_inconsistent);
1509         }
1510 }
1511
1512 static int lfsck_layout_double_scan_result(const struct lu_env *env,
1513                                            struct lfsck_component *com,
1514                                            int rc)
1515 {
1516         struct lfsck_instance   *lfsck = com->lc_lfsck;
1517         struct lfsck_layout     *lo    = com->lc_file_ram;
1518
1519         CDEBUG(D_LFSCK, "%s: layout LFSCK double scan: rc = %d\n",
1520                lfsck_lfsck2name(lfsck), rc);
1521
1522         down_write(&com->lc_sem);
1523         lo->ll_run_time_phase2 += ktime_get_seconds() -
1524                                   com->lc_time_last_checkpoint;
1525         lo->ll_time_last_checkpoint = ktime_get_real_seconds();
1526         lo->ll_objs_checked_phase2 += com->lc_new_checked;
1527
1528         if (rc > 0) {
1529                 if (lo->ll_flags & LF_INCOMPLETE) {
1530                         lo->ll_status = LS_PARTIAL;
1531                 } else {
1532                         if (lfsck->li_master) {
1533                                 struct lfsck_assistant_data *lad = com->lc_data;
1534
1535                                 if (test_bit(LAD_INCOMPLETE, &lad->lad_flags))
1536                                         lo->ll_status = LS_PARTIAL;
1537                                 else
1538                                         lo->ll_status = LS_COMPLETED;
1539                         } else {
1540                                 lo->ll_status = LS_COMPLETED;
1541                         }
1542                 }
1543                 lo->ll_flags &= ~LF_SCANNED_ONCE;
1544                 if (!(lfsck->li_bookmark_ram.lb_param & LPF_DRYRUN))
1545                         lo->ll_flags &= ~LF_INCONSISTENT;
1546                 lo->ll_time_last_complete = lo->ll_time_last_checkpoint;
1547                 lo->ll_success_count++;
1548         } else if (rc == 0) {
1549                 if (lfsck->li_status != 0)
1550                         lo->ll_status = lfsck->li_status;
1551                 else
1552                         lo->ll_status = LS_STOPPED;
1553         } else {
1554                 lo->ll_status = LS_FAILED;
1555         }
1556
1557         rc = lfsck_layout_store(env, com);
1558         up_write(&com->lc_sem);
1559
1560         CDEBUG(D_LFSCK, "%s: layout LFSCK double scan result %u: rc = %d\n",
1561                lfsck_lfsck2name(lfsck), lo->ll_status, rc);
1562
1563         return rc;
1564 }
1565
1566 static int lfsck_layout_trans_stop(const struct lu_env *env,
1567                                    struct dt_device *dev,
1568                                    struct thandle *handle, int result)
1569 {
1570         int rc;
1571
1572         /* XXX: If there is something worng or it needs to repair nothing,
1573          *      then notify the lower to stop the modification. Currently,
1574          *      we use th_result for such purpose, that may be replaced by
1575          *      some rollback mechanism in the future. */
1576         handle->th_result = result;
1577         rc = dt_trans_stop(env, dev, handle);
1578         if (result != 0)
1579                 return result > 0 ? 0 : result;
1580
1581         return rc == 0 ? 1 : rc;
1582 }
1583
1584 static int lfsck_layout_ins_dangling_rec(const struct lu_env *env,
1585                                          struct lfsck_component *com,
1586                                          const struct lu_fid *pfid,
1587                                          const struct lu_fid *cfid,
1588                                          __u32 comp_id, __u32 ea_off,
1589                                          __u32 ost_idx)
1590 {
1591         struct lfsck_layout_dangling_key *key = &lfsck_env_info(env)->lti_lldk;
1592         struct lu_fid *rec = &lfsck_env_info(env)->lti_fid3;
1593         struct dt_device *dev;
1594         struct dt_object *obj;
1595         struct thandle *th = NULL;
1596         int idx;
1597         int rc = 0;
1598         ENTRY;
1599
1600         idx = lfsck_sub_trace_file_fid2idx(pfid);
1601         obj = com->lc_sub_trace_objs[idx].lsto_obj;
1602         dev = lfsck_obj2dev(obj);
1603
1604         fid_cpu_to_be(&key->lldk_fid, pfid);
1605         key->lldk_comp_id = cpu_to_be32(comp_id);
1606         key->lldk_ea_off = cpu_to_be32(ea_off);
1607
1608         fid_cpu_to_be(rec, cfid);
1609         rec->f_ver = cpu_to_be32(ost_idx);
1610
1611         mutex_lock(&com->lc_sub_trace_objs[idx].lsto_mutex);
1612
1613         th = lfsck_trans_create(env, dev, com->lc_lfsck);
1614         if (IS_ERR(th))
1615                 GOTO(unlock, rc = PTR_ERR(th));
1616
1617         rc = dt_declare_insert(env, obj,
1618                                (const struct dt_rec *)rec,
1619                                (const struct dt_key *)key, th);
1620         if (rc)
1621                 GOTO(unlock, rc);
1622
1623         rc = dt_trans_start_local(env, dev, th);
1624         if (rc)
1625                 GOTO(unlock, rc);
1626
1627         rc = dt_insert(env, obj, (const struct dt_rec *)rec,
1628                        (const struct dt_key *)key, th);
1629
1630         GOTO(unlock, rc);
1631
1632 unlock:
1633         if (th && !IS_ERR(th))
1634                 dt_trans_stop(env, dev, th);
1635
1636         mutex_unlock(&com->lc_sub_trace_objs[idx].lsto_mutex);
1637
1638         CDEBUG(D_LFSCK, "%s: insert the paris "DFID" => "DFID", comp_id = %u, "
1639                "ea_off = %u, ost_idx = %u, into the trace file for further "
1640                "dangling check: rc = %d\n", lfsck_lfsck2name(com->lc_lfsck),
1641                PFID(pfid), PFID(cfid), comp_id, ea_off, ost_idx, rc);
1642
1643         return rc;
1644 }
1645
1646 static int lfsck_layout_del_dangling_rec(const struct lu_env *env,
1647                                          struct lfsck_component *com,
1648                                          const struct lu_fid *fid,
1649                                          __u32 comp_id, __u32 ea_off)
1650 {
1651         struct lfsck_layout_dangling_key *key = &lfsck_env_info(env)->lti_lldk;
1652         struct dt_device *dev;
1653         struct dt_object *obj;
1654         struct thandle *th = NULL;
1655         int idx;
1656         int rc = 0;
1657         ENTRY;
1658
1659         idx = lfsck_sub_trace_file_fid2idx(fid);
1660         obj = com->lc_sub_trace_objs[idx].lsto_obj;
1661         dev = lfsck_obj2dev(obj);
1662
1663         fid_cpu_to_be(&key->lldk_fid, fid);
1664         key->lldk_comp_id = cpu_to_be32(comp_id);
1665         key->lldk_ea_off = cpu_to_be32(ea_off);
1666
1667         mutex_lock(&com->lc_sub_trace_objs[idx].lsto_mutex);
1668
1669         th = lfsck_trans_create(env, dev, com->lc_lfsck);
1670         if (IS_ERR(th))
1671                 GOTO(unlock, rc = PTR_ERR(th));
1672
1673         rc = dt_declare_delete(env, obj, (const struct dt_key *)key, th);
1674         if (rc)
1675                 GOTO(unlock, rc);
1676
1677         rc = dt_trans_start_local(env, dev, th);
1678         if (rc)
1679                 GOTO(unlock, rc);
1680
1681         rc = dt_delete(env, obj, (const struct dt_key *)key, th);
1682
1683         GOTO(unlock, rc);
1684
1685 unlock:
1686         if (th && !IS_ERR(th))
1687                 dt_trans_stop(env, dev, th);
1688
1689         mutex_unlock(&com->lc_sub_trace_objs[idx].lsto_mutex);
1690
1691         CDEBUG(D_LFSCK, "%s: delete the dangling record for "DFID
1692                ", comp_id = %u, ea_off = %u from the trace file: rc = %d\n",
1693                lfsck_lfsck2name(com->lc_lfsck), PFID(fid), comp_id, ea_off, rc);
1694
1695         return rc;
1696 }
1697
1698 /**
1699  * Get the system default stripe size.
1700  *
1701  * \param[in] env       pointer to the thread context
1702  * \param[in] lfsck     pointer to the lfsck instance
1703  * \param[out] size     pointer to the default stripe size
1704  *
1705  * \retval              0 for success
1706  * \retval              negative error number on failure
1707  */
1708 static int lfsck_layout_get_def_stripesize(const struct lu_env *env,
1709                                            struct lfsck_instance *lfsck,
1710                                            __u32 *size)
1711 {
1712         struct lov_user_md      *lum = &lfsck_env_info(env)->lti_lum;
1713         struct dt_object        *root;
1714         int                      rc;
1715
1716         root = dt_locate(env, lfsck->li_next, &lfsck->li_local_root_fid);
1717         if (IS_ERR(root))
1718                 return PTR_ERR(root);
1719
1720         /* Get the default stripe size via xattr_get on the backend root. */
1721         rc = dt_xattr_get(env, root, lfsck_buf_get(env, lum, sizeof(*lum)),
1722                           XATTR_NAME_LOV);
1723         if (rc > 0) {
1724                 /* The lum->lmm_stripe_size is LE mode. The *size also
1725                  * should be LE mode. So it is unnecessary to convert. */
1726                 *size = lum->lmm_stripe_size;
1727                 rc = 0;
1728         } else if (unlikely(rc == 0)) {
1729                 rc = -EINVAL;
1730         }
1731
1732         lfsck_object_put(env, root);
1733
1734         return rc;
1735 }
1736
1737 /**
1738  * \retval       +1: repaired
1739  * \retval        0: did nothing
1740  * \retval      -ve: on error
1741  */
1742 static int lfsck_layout_refill_lovea(const struct lu_env *env,
1743                                      struct lfsck_instance *lfsck,
1744                                      struct thandle *handle,
1745                                      struct dt_object *parent,
1746                                      const struct lu_fid *cfid,
1747                                      struct lu_buf *buf,
1748                                      struct lov_mds_md_v1 *lmm,
1749                                      struct lov_ost_data_v1 *slot,
1750                                      int fl, __u32 ost_idx, int size)
1751 {
1752         struct ost_id           *oi     = &lfsck_env_info(env)->lti_oi;
1753         struct lu_buf            ea_buf;
1754         int                      rc;
1755         __u32                    magic;
1756         __u32                    pattern;
1757         __u16                    count;
1758         ENTRY;
1759
1760         magic = le32_to_cpu(lmm->lmm_magic);
1761         pattern = le32_to_cpu(lmm->lmm_pattern);
1762         count = le16_to_cpu(lmm->lmm_stripe_count);
1763
1764         fid_to_ostid(cfid, oi);
1765         ostid_cpu_to_le(oi, &slot->l_ost_oi);
1766         slot->l_ost_gen = cpu_to_le32(0);
1767         slot->l_ost_idx = cpu_to_le32(ost_idx);
1768
1769         if (pattern & LOV_PATTERN_F_HOLE) {
1770                 struct lov_ost_data_v1 *objs;
1771                 int                     i;
1772
1773                 if (magic == LOV_MAGIC_V1)
1774                         objs = &lmm->lmm_objects[0];
1775                 else
1776                         objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[0];
1777                 for (i = 0; i < count; i++, objs++) {
1778                         if (lovea_slot_is_dummy(objs))
1779                                 break;
1780                 }
1781
1782                 /* If the @slot is the last dummy slot to be refilled,
1783                  * then drop LOV_PATTERN_F_HOLE from lmm::lmm_pattern. */
1784                 if (i == count) {
1785                         lmm->lmm_pattern =
1786                                 cpu_to_le32(pattern & ~LOV_PATTERN_F_HOLE);
1787
1788                         CDEBUG(D_LFSCK, "%s: remove layout HOLE for "DFID
1789                                ": parent "DFID"\n", lfsck_lfsck2name(lfsck),
1790                                PFID(cfid), PFID(lfsck_dto2fid(parent)));
1791                 }
1792         }
1793
1794         lfsck_buf_init(&ea_buf, buf->lb_buf, size);
1795         rc = dt_xattr_set(env, parent, &ea_buf, XATTR_NAME_LOV, fl, handle);
1796         if (rc == 0)
1797                 rc = 1;
1798
1799         RETURN(rc);
1800 }
1801
1802 static struct lov_ost_data_v1 *
1803 __lfsck_layout_new_v1_lovea(struct lov_mds_md_v1 *lmm,
1804                             const struct lu_fid *pfid,
1805                             __u32 stripe_size, __u32 ea_off,
1806                             __u32 pattern, __u16 count)
1807 {
1808         lmm->lmm_magic = cpu_to_le32(LOV_MAGIC_V1);
1809         lmm->lmm_pattern = cpu_to_le32(pattern);
1810         fid_to_lmm_oi(pfid, &lmm->lmm_oi);
1811         lmm_oi_cpu_to_le(&lmm->lmm_oi, &lmm->lmm_oi);
1812         lmm->lmm_stripe_size = cpu_to_le32(stripe_size);
1813         lmm->lmm_stripe_count = cpu_to_le16(count);
1814         lmm->lmm_layout_gen = cpu_to_le16(1);
1815         memset(&lmm->lmm_objects[0], 0,
1816                sizeof(struct lov_ost_data_v1) * count);
1817
1818         return &lmm->lmm_objects[ea_off];
1819 }
1820
1821 static int lfsck_layout_new_v1_lovea(const struct lu_env *env,
1822                                      struct lfsck_instance *lfsck,
1823                                      struct ost_layout *ol,
1824                                      struct dt_object *parent,
1825                                      struct lu_buf *buf, __u32 ea_off,
1826                                      struct lov_mds_md_v1 **lmm,
1827                                      struct lov_ost_data_v1 **objs)
1828 {
1829         int size;
1830         __u32 stripe_size = ol->ol_stripe_size;
1831         __u32 pattern = LOV_PATTERN_RAID0;
1832         __u16 count;
1833
1834         if (ol->ol_stripe_count != 0)
1835                 count = ol->ol_stripe_count;
1836         else
1837                 count = ea_off + 1;
1838
1839         size = lov_mds_md_size(count, LOV_MAGIC_V1);
1840         LASSERTF(buf->lb_len >= size,
1841                  "buffer len %d is less than real size %d\n",
1842                  (int)buf->lb_len, size);
1843
1844         if (stripe_size == 0) {
1845                 int rc;
1846
1847                 rc = lfsck_layout_get_def_stripesize(env, lfsck, &stripe_size);
1848                 if (rc)
1849                         return rc;
1850         }
1851
1852         *lmm = buf->lb_buf;
1853         if (ol->ol_stripe_count > 1 ||
1854             (ol->ol_stripe_count == 0 && ea_off != 0)) {
1855                 pattern |= LOV_PATTERN_F_HOLE;
1856                 memset(&(*lmm)->lmm_objects[0], 0,
1857                        count * sizeof(struct lov_ost_data_v1));
1858         }
1859
1860         *objs = __lfsck_layout_new_v1_lovea(*lmm, lfsck_dto2fid(parent),
1861                                 stripe_size, ea_off, pattern, count);
1862
1863         return size;
1864 }
1865
1866 static int lfsck_layout_new_comp_lovea(const struct lu_env *env,
1867                                        struct lu_orphan_rec_v3 *rec,
1868                                        struct dt_object *parent,
1869                                        struct lu_buf *buf, __u32 ea_off,
1870                                        struct lov_mds_md_v1 **lmm,
1871                                        struct lov_ost_data_v1 **objs)
1872 {
1873         struct ost_layout *ol = &rec->lor_layout;
1874         struct lov_comp_md_v1 *lcm;
1875         struct lov_comp_md_entry_v1 *lcme;
1876         __u32 pattern = LOV_PATTERN_RAID0;
1877         __u32 offset = sizeof(*lcm) + sizeof(*lcme);
1878         int lcme_size = lov_mds_md_size(ol->ol_stripe_count, LOV_MAGIC_V1);
1879         int size = offset + lcme_size;
1880
1881         LASSERTF(buf->lb_len >= size,
1882                  "buffer len %d is less than real size %d\n",
1883                  (int)buf->lb_len, size);
1884
1885         lcm = buf->lb_buf;
1886         lcm->lcm_magic = cpu_to_le32(LOV_MAGIC_COMP_V1);
1887         lcm->lcm_size = cpu_to_le32(size);
1888         if (rec->lor_range) {
1889                 lcm->lcm_layout_gen = cpu_to_le32(rec->lor_layout_version +
1890                                                   rec->lor_range);
1891                 lcm->lcm_flags = cpu_to_le16(LCM_FL_WRITE_PENDING);
1892         } else if (rec->lor_layout_version) {
1893                 lcm->lcm_layout_gen = cpu_to_le32(rec->lor_layout_version +
1894                                                   rec->lor_range);
1895                 lcm->lcm_flags = cpu_to_le16(LCM_FL_NONE);
1896         } else {
1897                 lcm->lcm_layout_gen = cpu_to_le32(1);
1898                 lcm->lcm_flags = cpu_to_le16(LCM_FL_NONE);
1899         }
1900         lcm->lcm_entry_count = cpu_to_le16(1);
1901         /* Currently, we do not know how many mirrors will be, set it as zero
1902          * at the beginning. It will be updated when more mirrors are found. */
1903         lcm->lcm_mirror_count = 0;
1904
1905         lcme = &lcm->lcm_entries[0];
1906         lcme->lcme_id = cpu_to_le32(ol->ol_comp_id);
1907         lcme->lcme_flags = cpu_to_le32(LCME_FL_INIT);
1908         lcme->lcme_extent.e_start = cpu_to_le64(ol->ol_comp_start);
1909         lcme->lcme_extent.e_end = cpu_to_le64(ol->ol_comp_end);
1910         lcme->lcme_offset = cpu_to_le32(offset);
1911         lcme->lcme_size = cpu_to_le32(lcme_size);
1912         lcme->lcme_layout_gen = lcm->lcm_layout_gen;
1913         if (ol->ol_stripe_count > 1)
1914                 pattern |= LOV_PATTERN_F_HOLE;
1915
1916         *lmm = buf->lb_buf + offset;
1917         *objs = __lfsck_layout_new_v1_lovea(*lmm, lfsck_dto2fid(parent),
1918                                             ol->ol_stripe_size, ea_off,
1919                                             pattern, ol->ol_stripe_count);
1920
1921         return size;
1922 }
1923
1924 static void lfsck_layout_update_lcm(struct lov_comp_md_v1 *lcm,
1925                                     struct lov_comp_md_entry_v1 *lcme,
1926                                     __u32 version, __u32 range)
1927 {
1928         struct lov_comp_md_entry_v1 *tmp;
1929         __u64 start = le64_to_cpu(lcme->lcme_extent.e_start);
1930         __u64 end = le64_to_cpu(lcme->lcme_extent.e_end);
1931         __u32 gen = version + range;
1932         __u32 tmp_gen;
1933         int i;
1934         __u16 count = le16_to_cpu(lcm->lcm_entry_count);
1935         __u16 flags = le16_to_cpu(lcm->lcm_flags);
1936
1937         if (!gen)
1938                 gen = 1;
1939         lcme->lcme_layout_gen = cpu_to_le32(gen);
1940         if (le32_to_cpu(lcm->lcm_layout_gen) < gen)
1941                 lcm->lcm_layout_gen = cpu_to_le32(gen);
1942
1943         if (range)
1944                 lcm->lcm_flags = cpu_to_le16(LCM_FL_WRITE_PENDING);
1945         else if (flags == LCM_FL_NONE && le16_to_cpu(lcm->lcm_mirror_count) > 0)
1946                 lcm->lcm_flags = cpu_to_le16(LCM_FL_RDONLY);
1947
1948         for (i = 0; i < count; i++) {
1949                 tmp = &lcm->lcm_entries[i];
1950                 if (le64_to_cpu(tmp->lcme_extent.e_end) <= start)
1951                         continue;
1952
1953                 if (le64_to_cpu(tmp->lcme_extent.e_start) >= end)
1954                         continue;
1955
1956                 if (le32_to_cpu(tmp->lcme_flags) & LCME_FL_STALE)
1957                         continue;
1958
1959                 tmp_gen = le32_to_cpu(tmp->lcme_layout_gen);
1960                 /* "lcme_layout_gen == 0" but without LCME_FL_STALE flag,
1961                  * then it should be the latest version of all mirrors. */
1962                 if (tmp_gen == 0 || tmp_gen > gen) {
1963                         lcme->lcme_flags = cpu_to_le32(
1964                                 le32_to_cpu(lcme->lcme_flags) | LCME_FL_STALE);
1965                         break;
1966                 }
1967
1968                 if (tmp_gen < gen)
1969                         tmp->lcme_flags = cpu_to_le32(
1970                                 le32_to_cpu(tmp->lcme_flags) | LCME_FL_STALE);
1971         }
1972 }
1973
1974 static int lfsck_layout_add_comp(const struct lu_env *env,
1975                                  struct lfsck_instance *lfsck,
1976                                  struct thandle *handle,
1977                                  struct lu_orphan_rec_v3 *rec,
1978                                  struct dt_object *parent,
1979                                  const struct lu_fid *cfid,
1980                                  struct lu_buf *buf, __u32 ost_idx,
1981                                  __u32 ea_off, int pos, bool new_mirror)
1982 {
1983         struct ost_layout *ol = &rec->lor_layout;
1984         struct lov_comp_md_v1 *lcm = buf->lb_buf;
1985         struct lov_comp_md_entry_v1 *lcme;
1986         struct lov_mds_md_v1 *lmm;
1987         struct lov_ost_data_v1 *objs;
1988         int added = sizeof(*lcme) +
1989                     lov_mds_md_size(ol->ol_stripe_count, LOV_MAGIC_V1);
1990         int size = le32_to_cpu(lcm->lcm_size) + added;
1991         int rc;
1992         int i;
1993         __u32 offset;
1994         __u32 pattern = LOV_PATTERN_RAID0;
1995         __u16 count = le16_to_cpu(lcm->lcm_entry_count);
1996         ENTRY;
1997
1998         lu_buf_check_and_grow(buf, size);
1999         /* set the lcm again because lu_buf_check_and_grow() may
2000          * have reallocated the buf. */
2001         lcm = buf->lb_buf;
2002         lcm->lcm_size = cpu_to_le32(size);
2003         lcm->lcm_entry_count = cpu_to_le16(count + 1);
2004         if (new_mirror)
2005                 le16_add_cpu(&lcm->lcm_mirror_count, 1);
2006
2007         /* 1. Move the component bodies from [pos, count-1] to [pos+1, count]
2008          *    with distance of 'added'. */
2009         if (pos < count) {
2010                 size = 0;
2011                 for (i = pos; i < count; i++) {
2012                         lcme = &lcm->lcm_entries[i];
2013                         size += le32_to_cpu(lcme->lcme_size);
2014                 }
2015
2016                 offset = le32_to_cpu(lcm->lcm_entries[pos].lcme_offset);
2017                 memmove(buf->lb_buf + offset + added,
2018                         buf->lb_buf + offset, size);
2019         }
2020
2021         size = 0;
2022         /* 2. Move the component header [0, pos-1] to [0, pos-1] with distance
2023          *    of 'sizeof(struct lov_comp_md_entry_v1)' */
2024         if (pos > 0) {
2025                 for (i = 0; i < pos; i++) {
2026                         lcme = &lcm->lcm_entries[i];
2027                         size += le32_to_cpu(lcme->lcme_size);
2028                 }
2029
2030                 offset = le32_to_cpu(lcm->lcm_entries[0].lcme_offset);
2031                 memmove(buf->lb_buf + offset + sizeof(*lcme),
2032                         buf->lb_buf + offset, size);
2033         }
2034
2035         /* 3. Recalculate the enter offset for the component [pos, count-1] */
2036         for (i = count - 1; i >= pos; i--) {
2037                 lcm->lcm_entries[i + 1] = lcm->lcm_entries[i];
2038                 lcm->lcm_entries[i + 1].lcme_offset =
2039                         cpu_to_le32(le32_to_cpu(lcm->lcm_entries[i + 1].
2040                                                 lcme_offset) + added);
2041         }
2042
2043         /* 4. Recalculate the enter offset for the component [0, pos) */
2044         for (i = 0; i < pos; i++) {
2045                 lcm->lcm_entries[i].lcme_offset =
2046                         cpu_to_le32(le32_to_cpu(lcm->lcm_entries[i].
2047                                                 lcme_offset) + sizeof(*lcme));
2048         }
2049
2050         offset = sizeof(*lcm) + sizeof(*lcme) * (count + 1) + size;
2051         /* 4. Insert the new component header (entry) at the slot 'pos'. */
2052         lcme = &lcm->lcm_entries[pos];
2053         lcme->lcme_id = cpu_to_le32(ol->ol_comp_id);
2054         lcme->lcme_flags = cpu_to_le32(LCME_FL_INIT);
2055         lcme->lcme_extent.e_start = cpu_to_le64(ol->ol_comp_start);
2056         lcme->lcme_extent.e_end = cpu_to_le64(ol->ol_comp_end);
2057         lcme->lcme_offset = cpu_to_le32(offset);
2058         lcme->lcme_size = cpu_to_le32(lov_mds_md_size(ol->ol_stripe_count,
2059                                                       LOV_MAGIC_V1));
2060
2061         if (ol->ol_stripe_count > 1)
2062                 pattern |= LOV_PATTERN_F_HOLE;
2063
2064         lmm = buf->lb_buf + offset;
2065         /* 5. Insert teh new component body at the 'offset'. */
2066         objs = __lfsck_layout_new_v1_lovea(lmm, lfsck_dto2fid(parent),
2067                                            ol->ol_stripe_size, ea_off,
2068                                            pattern, ol->ol_stripe_count);
2069
2070         /* 6. Update mirror related flags and version. */
2071         lfsck_layout_update_lcm(lcm, lcme, rec->lor_layout_version,
2072                                 rec->lor_range);
2073
2074         rc = lfsck_layout_refill_lovea(env, lfsck, handle, parent, cfid, buf,
2075                                        lmm, objs, LU_XATTR_REPLACE, ost_idx,
2076                                        le32_to_cpu(lcm->lcm_size));
2077
2078         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant add new COMP for "
2079                DFID": parent "DFID", OST-index %u, stripe-index %u, "
2080                "stripe_size %u, stripe_count %u, comp_id %u, comp_start %llu, "
2081                "comp_end %llu, layout version %u, range %u, "
2082                "%s LOV EA hole: rc = %d\n",
2083                lfsck_lfsck2name(lfsck), PFID(cfid), PFID(lfsck_dto2fid(parent)),
2084                ost_idx, ea_off, ol->ol_stripe_size, ol->ol_stripe_count,
2085                ol->ol_comp_id, ol->ol_comp_start, ol->ol_comp_end,
2086                rec->lor_layout_version, rec->lor_range,
2087                le32_to_cpu(lmm->lmm_pattern) & LOV_PATTERN_F_HOLE ?
2088                "with" : "without", rc);
2089
2090         RETURN(rc);
2091 }
2092
2093 static int lfsck_layout_extend_v1v3_lovea(const struct lu_env *env,
2094                                           struct lfsck_instance *lfsck,
2095                                           struct thandle *handle,
2096                                           struct ost_layout *ol,
2097                                           struct dt_object *parent,
2098                                           const struct lu_fid *cfid,
2099                                           struct lu_buf *buf, __u32 ost_idx,
2100                                           __u32 ea_off)
2101 {
2102         struct lov_mds_md_v1 *lmm = buf->lb_buf;
2103         struct lov_ost_data_v1 *objs;
2104         __u16 count = le16_to_cpu(lmm->lmm_stripe_count);
2105         __u32 magic = le32_to_cpu(lmm->lmm_magic);
2106         int size;
2107         int gap;
2108         int rc;
2109         ENTRY;
2110
2111         /* The original LOVEA maybe re-generated via old filter_fid, at
2112          * that time, we do not know the stripe count and stripe size. */
2113         if (ol->ol_stripe_count > count)
2114                 count = ol->ol_stripe_count;
2115         if (ol->ol_stripe_size != 0 &&
2116             ol->ol_stripe_size != le32_to_cpu(lmm->lmm_stripe_size))
2117                 lmm->lmm_stripe_size = cpu_to_le32(ol->ol_stripe_size);
2118
2119         if (magic == LOV_MAGIC_V1)
2120                 objs = &lmm->lmm_objects[count];
2121         else
2122                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[count];
2123
2124         gap = ea_off - count;
2125         if (gap >= 0)
2126                 count = ea_off + 1;
2127
2128         size = lov_mds_md_size(count, magic);
2129         LASSERTF(buf->lb_len >= size,
2130                  "buffer len %d is less than real size %d\n",
2131                  (int)buf->lb_len, size);
2132
2133         if (gap > 0) {
2134                 memset(objs, 0, gap * sizeof(*objs));
2135                 lmm->lmm_pattern |= cpu_to_le32(LOV_PATTERN_F_HOLE);
2136         }
2137
2138         lmm->lmm_layout_gen = cpu_to_le16(le16_to_cpu(lmm->lmm_layout_gen) + 1);
2139         lmm->lmm_stripe_count = cpu_to_le16(count);
2140         objs += gap;
2141
2142         rc = lfsck_layout_refill_lovea(env, lfsck, handle, parent, cfid, buf,
2143                                 lmm, objs, LU_XATTR_REPLACE, ost_idx, size);
2144
2145         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant extend layout EA for "
2146                DFID": parent "DFID", OST-index %u, stripe-index %u, "
2147                "stripe_size %u, stripe_count %u, comp_id %u, comp_start %llu, "
2148                "comp_end %llu, %s LOV EA hole: rc = %d\n",
2149                lfsck_lfsck2name(lfsck), PFID(cfid), PFID(lfsck_dto2fid(parent)),
2150                ost_idx, ea_off, ol->ol_stripe_size, ol->ol_stripe_count,
2151                ol->ol_comp_id, ol->ol_comp_start, ol->ol_comp_end,
2152                le32_to_cpu(lmm->lmm_pattern) & LOV_PATTERN_F_HOLE ?
2153                "with" : "without", rc);
2154
2155         RETURN(rc);
2156 }
2157
2158 /**
2159  * \retval       +1: repaired
2160  * \retval        0: did nothing
2161  * \retval      -ve: on error
2162  */
2163 static int lfsck_layout_update_lovea(const struct lu_env *env,
2164                                      struct lfsck_instance *lfsck,
2165                                      struct thandle *handle,
2166                                      struct lu_orphan_rec_v3 *rec,
2167                                      struct dt_object *parent,
2168                                      const struct lu_fid *cfid,
2169                                      struct lu_buf *buf, int fl,
2170                                      __u32 ost_idx, __u32 ea_off)
2171 {
2172         struct ost_layout *ol = &rec->lor_layout;
2173         struct lov_mds_md_v1 *lmm = NULL;
2174         struct lov_ost_data_v1 *objs = NULL;
2175         int rc = 0;
2176         ENTRY;
2177
2178         if (ol->ol_comp_id != 0)
2179                 rc = lfsck_layout_new_comp_lovea(env, rec, parent, buf, ea_off,
2180                                                  &lmm, &objs);
2181         else
2182                 rc = lfsck_layout_new_v1_lovea(env, lfsck, &rec->lor_layout,
2183                                                parent, buf, ea_off, &lmm,
2184                                                &objs);
2185         if (rc > 0)
2186                 rc = lfsck_layout_refill_lovea(env, lfsck, handle, parent, cfid,
2187                                                buf, lmm, objs, fl, ost_idx, rc);
2188
2189         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant created layout EA for "
2190                DFID": parent "DFID", OST-index %u, stripe-index %u, "
2191                "stripe_size %u, stripe_count %u, comp_id %u, comp_start %llu, "
2192                "comp_end %llu, layout version %u, range %u, fl %d, "
2193                "%s LOV EA hole: rc = %d\n",
2194                lfsck_lfsck2name(lfsck), PFID(cfid), PFID(lfsck_dto2fid(parent)),
2195                ost_idx, ea_off, ol->ol_stripe_size, ol->ol_stripe_count,
2196                ol->ol_comp_id, ol->ol_comp_start, ol->ol_comp_end,
2197                rec->lor_layout_version, rec->lor_range, fl,
2198                le32_to_cpu(lmm->lmm_pattern) & LOV_PATTERN_F_HOLE ?
2199                "with" : "without", rc);
2200
2201         RETURN(rc);
2202 }
2203
2204 static int __lfsck_layout_update_pfid(const struct lu_env *env,
2205                                       struct lfsck_component *com,
2206                                       struct dt_object *child,
2207                                       const struct lu_fid *pfid,
2208                                       const struct ost_layout *ol, __u32 offset,
2209                                       __u32 version, __u32 range)
2210 {
2211         struct dt_device        *dev    = lfsck_obj2dev(child);
2212         struct filter_fid       *ff     = &lfsck_env_info(env)->lti_ff;
2213         struct thandle          *handle;
2214         struct lu_buf            buf    = { NULL };
2215         int                      rc;
2216
2217         ff->ff_parent.f_seq = cpu_to_le64(pfid->f_seq);
2218         ff->ff_parent.f_oid = cpu_to_le32(pfid->f_oid);
2219         /* Currently, the filter_fid::ff_parent::f_ver is not the real parent
2220          * MDT-object's FID::f_ver, instead it is the OST-object index in its
2221          * parent MDT-object's layout EA. */
2222         ff->ff_parent.f_stripe_idx = cpu_to_le32(offset);
2223         ost_layout_cpu_to_le(&ff->ff_layout, ol);
2224         ff->ff_layout_version = cpu_to_le32(version);
2225         ff->ff_range = cpu_to_le32(range);
2226         lfsck_buf_init(&buf, ff, sizeof(*ff));
2227
2228         handle = lfsck_trans_create(env, dev, com->lc_lfsck);
2229         if (IS_ERR(handle))
2230                 RETURN(PTR_ERR(handle));
2231
2232         rc = dt_declare_xattr_set(env, child, &buf, XATTR_NAME_FID, 0, handle);
2233         if (rc != 0)
2234                 GOTO(stop, rc);
2235
2236         rc = dt_trans_start_local(env, dev, handle);
2237         if (rc != 0)
2238                 GOTO(stop, rc);
2239
2240         rc = dt_xattr_set(env, child, &buf, XATTR_NAME_FID, 0, handle);
2241
2242         GOTO(stop, rc);
2243
2244 stop:
2245         dt_trans_stop(env, dev, handle);
2246
2247         return rc;
2248 }
2249
2250 /**
2251  * \retval       +1: repaired
2252  * \retval        0: did nothing
2253  * \retval      -ve: on error
2254  */
2255 static int lfsck_layout_update_pfid(const struct lu_env *env,
2256                                     struct lfsck_component *com,
2257                                     struct dt_object *parent,
2258                                     struct lu_fid *cfid,
2259                                     struct dt_device *cdev,
2260                                     struct lu_orphan_rec_v3 *rec, __u32 ea_off)
2261 {
2262         struct dt_object        *child;
2263         int                      rc     = 0;
2264         ENTRY;
2265
2266         child = lfsck_object_find_by_dev(env, cdev, cfid);
2267         if (IS_ERR(child))
2268                 RETURN(PTR_ERR(child));
2269
2270         rc = __lfsck_layout_update_pfid(env, com, child,
2271                                         lu_object_fid(&parent->do_lu),
2272                                         &rec->lor_layout, ea_off,
2273                                         rec->lor_layout_version,
2274                                         rec->lor_range);
2275         lfsck_object_put(env, child);
2276
2277         RETURN(rc == 0 ? 1 : rc);
2278 }
2279
2280 static int lfsck_lovea_size(struct ost_layout *ol, __u32 ea_off)
2281 {
2282         if (ol->ol_comp_id != 0)
2283                 return sizeof(struct lov_comp_md_v1) +
2284                        sizeof(struct lov_comp_md_entry_v1) +
2285                        lov_mds_md_size(ol->ol_stripe_count, LOV_MAGIC_V1);
2286
2287         if (ol->ol_stripe_count != 0)
2288                 return lov_mds_md_size(ol->ol_stripe_count, LOV_MAGIC_V1);
2289
2290         return lov_mds_md_size(ea_off + 1, LOV_MAGIC_V1);
2291 }
2292
2293 /**
2294  * This function will create the MDT-object with the given (partial) LOV EA.
2295  *
2296  * Under some data corruption cases, the MDT-object of the file may be lost,
2297  * but its OST-objects, or some of them are there. The layout LFSCK needs to
2298  * re-create the MDT-object with the orphan OST-object(s) information.
2299  *
2300  * On the other hand, the LFSCK may has created some OST-object for repairing
2301  * dangling LOV EA reference, but as the LFSCK processing, it may find that
2302  * the old OST-object is there and should replace the former new created OST
2303  * object. Unfortunately, some others have modified such newly created object.
2304  * To keep the data (both new and old), the LFSCK will create MDT-object with
2305  * new FID to reference the original OST-object.
2306  *
2307  * \param[in] env       pointer to the thread context
2308  * \param[in] com       pointer to the lfsck component
2309  * \param[in] ltd       pointer to target device descriptor
2310  * \param[in] rec       pointer to the record for the orphan OST-object
2311  * \param[in] cfid      pointer to FID for the orphan OST-object
2312  * \param[in] infix     additional information, such as the FID for original
2313  *                      MDT-object and the stripe offset in the LOV EA
2314  * \param[in] type      the type for describing why the orphan MDT-object is
2315  *                      created. The rules are as following:
2316  *
2317  *  type "C":           Multiple OST-objects claim the same MDT-object and the
2318  *                      same slot in the layout EA. Then the LFSCK will create
2319  *                      new MDT-object(s) to hold the conflict OST-object(s).
2320  *
2321  *  type "N":           The orphan OST-object does not know which one was the
2322  *                      real parent MDT-object, so the LFSCK uses new FID for
2323  *                      its parent MDT-object.
2324  *
2325  *  type "R":           The orphan OST-object knows its parent MDT-object FID,
2326  *                      but does not know the position (the file name) in the
2327  *                      layout.
2328  *
2329  *  type "D":           The MDT-object is a directory, it may knows its parent
2330  *                      but because there is no valid linkEA, the LFSCK cannot
2331  *                      know where to put it back to the namespace.
2332  *  type "O":           The MDT-object has no linkEA, and there is no name
2333  *                      entry that references the MDT-object.
2334  *
2335  *  type "P":           The orphan object to be created was a parent directory
2336  *                      of some MDT-object which linkEA shows that the @orphan
2337  *                      object is missing.
2338  *
2339  * The orphan name will be like:
2340  * ${FID}-${infix}-${type}-${conflict_version}
2341  *
2342  * \param[in] ea_off    the stripe offset in the LOV EA
2343  *
2344  * \retval              positive on repaired something
2345  * \retval              0 if needs to repair nothing
2346  * \retval              negative error number on failure
2347  */
2348 static int lfsck_layout_recreate_parent(const struct lu_env *env,
2349                                         struct lfsck_component *com,
2350                                         struct lfsck_tgt_desc *ltd,
2351                                         struct lu_orphan_rec_v3 *rec,
2352                                         struct lu_fid *cfid,
2353                                         const char *infix,
2354                                         const char *type,
2355                                         __u32 ea_off)
2356 {
2357         struct lfsck_thread_info        *info   = lfsck_env_info(env);
2358         struct dt_insert_rec            *dtrec  = &info->lti_dt_rec;
2359         char                            *name   = info->lti_key;
2360         struct lu_attr                  *la     = &info->lti_la2;
2361         struct dt_object_format         *dof    = &info->lti_dof;
2362         struct lfsck_instance           *lfsck  = com->lc_lfsck;
2363         struct lu_fid                   *pfid   = &rec->lor_rec.lor_fid;
2364         struct lu_fid                   *tfid   = &info->lti_fid3;
2365         struct dt_device                *dev    = lfsck->li_bottom;
2366         struct dt_object                *lpf    = lfsck->li_lpf_obj;
2367         struct dt_object                *pobj   = NULL;
2368         struct dt_object                *cobj   = NULL;
2369         struct thandle                  *th     = NULL;
2370         struct lu_buf                   *ea_buf = &info->lti_big_buf;
2371         struct lu_buf                    lov_buf;
2372         struct lfsck_lock_handle        *llh    = &info->lti_llh;
2373         struct linkea_data               ldata  = { NULL };
2374         struct lu_buf                    linkea_buf;
2375         const struct lu_name            *pname;
2376         int                              size   = 0;
2377         int                              idx    = 0;
2378         int                              rc     = 0;
2379         ENTRY;
2380
2381         if (lfsck_is_dryrun(lfsck))
2382                 GOTO(log, rc = 0);
2383
2384         if (unlikely(lpf == NULL))
2385                 GOTO(log, rc = -ENXIO);
2386
2387         /* We use two separated transactions to repair the inconsistency.
2388          *
2389          * 1) create the MDT-object locally.
2390          * 2) update the OST-object's PFID EA if necessary.
2391          *
2392          * If 1) succeed, but 2) failed, then the OST-object's PFID EA will be
2393          * updated when the layout LFSCK run next time.
2394          *
2395          * If 1) failed, but 2) succeed, then such MDT-object will be re-created
2396          * when the layout LFSCK run next time. */
2397
2398         if (fid_is_zero(pfid)) {
2399                 rc = lfsck_fid_alloc(env, lfsck, pfid, false);
2400                 if (rc != 0)
2401                         GOTO(log, rc);
2402
2403                 cobj = lfsck_object_find_by_dev(env, ltd->ltd_tgt, cfid);
2404                 if (IS_ERR(cobj))
2405                         GOTO(log, rc = PTR_ERR(cobj));
2406         }
2407
2408         pobj = lfsck_object_find_by_dev(env, dev, pfid);
2409         if (IS_ERR(pobj))
2410                 GOTO(log, rc = PTR_ERR(pobj));
2411
2412         LASSERT(infix != NULL);
2413         LASSERT(type != NULL);
2414
2415         memset(la, 0, sizeof(*la));
2416         la->la_uid = rec->lor_rec.lor_uid;
2417         la->la_gid = rec->lor_rec.lor_gid;
2418         la->la_mode = S_IFREG | S_IRUSR;
2419         la->la_valid = LA_MODE | LA_UID | LA_GID;
2420
2421         memset(dof, 0, sizeof(*dof));
2422         dof->dof_type = dt_mode_to_dft(S_IFREG);
2423         /* Because the dof->dof_reg.striped = 0, the LOD will not create
2424          * the stripe(s). The LFSCK will specify the LOV EA via
2425          * lfsck_layout_update_lovea(). */
2426
2427         size = lfsck_lovea_size(&rec->lor_layout, ea_off);
2428         if (ea_buf->lb_len < size) {
2429                 lu_buf_realloc(ea_buf, size);
2430                 if (ea_buf->lb_buf == NULL)
2431                         GOTO(log, rc = -ENOMEM);
2432         }
2433
2434 again:
2435         do {
2436                 snprintf(name, NAME_MAX, DFID"%s-%s-%d", PFID(pfid), infix,
2437                          type, idx++);
2438                 rc = dt_lookup_dir(env, lfsck->li_lpf_obj, name, tfid);
2439                 if (rc != 0 && rc != -ENOENT)
2440                         GOTO(log, rc);
2441         } while (rc == 0);
2442
2443         rc = lfsck_lock(env, lfsck, lfsck->li_lpf_obj, name, llh,
2444                         MDS_INODELOCK_UPDATE, LCK_PW);
2445         if (rc != 0)
2446                 GOTO(log, rc);
2447
2448         /* Re-check whether the name conflict with othrs after taken
2449          * the ldlm lock. */
2450         rc = dt_lookup_dir(env, lfsck->li_lpf_obj, name, tfid);
2451         if (unlikely(rc == 0)) {
2452                 lfsck_unlock(llh);
2453                 goto again;
2454         }
2455
2456         if (rc != -ENOENT)
2457                 GOTO(unlock, rc);
2458
2459         pname = lfsck_name_get_const(env, name, strlen(name));
2460         rc = linkea_links_new(&ldata, &lfsck_env_info(env)->lti_linkea_buf,
2461                               pname, lfsck_dto2fid(lfsck->li_lpf_obj));
2462         if (rc != 0)
2463                 GOTO(unlock, rc);
2464
2465         /* The 1st transaction. */
2466         th = lfsck_trans_create(env, dev, lfsck);
2467         if (IS_ERR(th))
2468                 GOTO(unlock, rc = PTR_ERR(th));
2469
2470         rc = dt_declare_create(env, pobj, la, NULL, dof, th);
2471         if (rc != 0)
2472                 GOTO(stop, rc);
2473
2474         lfsck_buf_init(&lov_buf, ea_buf->lb_buf, size);
2475         rc = dt_declare_xattr_set(env, pobj, &lov_buf, XATTR_NAME_LOV,
2476                                   LU_XATTR_CREATE, th);
2477         if (rc != 0)
2478                 GOTO(stop, rc);
2479
2480         dtrec->rec_fid = pfid;
2481         dtrec->rec_type = S_IFREG;
2482         rc = dt_declare_insert(env, lpf,
2483                                (const struct dt_rec *)dtrec,
2484                                (const struct dt_key *)name, th);
2485         if (rc != 0)
2486                 GOTO(stop, rc);
2487
2488         lfsck_buf_init(&linkea_buf, ldata.ld_buf->lb_buf,
2489                        ldata.ld_leh->leh_len);
2490         rc = dt_declare_xattr_set(env, pobj, &linkea_buf,
2491                                   XATTR_NAME_LINK, 0, th);
2492         if (rc != 0)
2493                 GOTO(stop, rc);
2494
2495         rc = dt_trans_start_local(env, dev, th);
2496         if (rc != 0)
2497                 GOTO(stop, rc);
2498
2499         dt_write_lock(env, pobj, 0);
2500         rc = dt_create(env, pobj, la, NULL, dof, th);
2501         if (rc == 0)
2502                 rc = lfsck_layout_update_lovea(env, lfsck, th, rec, pobj, cfid,
2503                         &lov_buf, LU_XATTR_CREATE, ltd->ltd_index, ea_off);
2504         dt_write_unlock(env, pobj);
2505         if (rc < 0)
2506                 GOTO(stop, rc);
2507
2508         rc = dt_insert(env, lpf, (const struct dt_rec *)dtrec,
2509                        (const struct dt_key *)name, th);
2510         if (rc != 0)
2511                 GOTO(stop, rc);
2512
2513         rc = dt_xattr_set(env, pobj, &linkea_buf, XATTR_NAME_LINK, 0, th);
2514         if (rc == 0 && cobj != NULL) {
2515                 dt_trans_stop(env, dev, th);
2516                 th = NULL;
2517
2518                 /* The 2nd transaction. */
2519                 rc = __lfsck_layout_update_pfid(env, com, cobj, pfid,
2520                                                 &rec->lor_layout, ea_off,
2521                                                 rec->lor_layout_version,
2522                                                 rec->lor_range);
2523         }
2524
2525         GOTO(stop, rc);
2526
2527 stop:
2528         if (th != NULL)
2529                 dt_trans_stop(env, dev, th);
2530
2531 unlock:
2532         lfsck_unlock(llh);
2533
2534 log:
2535         if (cobj != NULL && !IS_ERR(cobj))
2536                 lfsck_object_put(env, cobj);
2537         if (pobj != NULL && !IS_ERR(pobj))
2538                 lfsck_object_put(env, pobj);
2539
2540         if (rc < 0)
2541                 CDEBUG(D_LFSCK, "%s layout LFSCK assistant failed to "
2542                        "recreate the lost MDT-object: parent "DFID
2543                        ", child "DFID", OST-index %u, stripe-index %u, "
2544                        "infix %s, type %s: rc = %d\n",
2545                        lfsck_lfsck2name(lfsck), PFID(pfid), PFID(cfid),
2546                        ltd->ltd_index, ea_off, infix, type, rc);
2547
2548         return rc >= 0 ? 1 : rc;
2549 }
2550
2551 static int lfsck_layout_master_conditional_destroy(const struct lu_env *env,
2552                                                    struct lfsck_component *com,
2553                                                    const struct lu_fid *fid,
2554                                                    __u32 index)
2555 {
2556         struct lfsck_thread_info *info  = lfsck_env_info(env);
2557         struct lfsck_request     *lr    = &info->lti_lr;
2558         struct lfsck_instance    *lfsck = com->lc_lfsck;
2559         struct lfsck_tgt_desc    *ltd;
2560         struct ptlrpc_request    *req;
2561         struct lfsck_request     *tmp;
2562         struct obd_export        *exp;
2563         int                       rc    = 0;
2564         ENTRY;
2565
2566         ltd = lfsck_tgt_get(&lfsck->li_ost_descs, index);
2567         if (unlikely(ltd == NULL))
2568                 RETURN(-ENXIO);
2569
2570         exp = ltd->ltd_exp;
2571         if (!(exp_connect_flags(exp) & OBD_CONNECT_LFSCK))
2572                 GOTO(put, rc = -EOPNOTSUPP);
2573
2574         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_LFSCK_NOTIFY);
2575         if (req == NULL)
2576                 GOTO(put, rc = -ENOMEM);
2577
2578         rc = ptlrpc_request_pack(req, LUSTRE_OBD_VERSION, LFSCK_NOTIFY);
2579         if (rc != 0) {
2580                 ptlrpc_request_free(req);
2581
2582                 GOTO(put, rc);
2583         }
2584
2585         memset(lr, 0, sizeof(*lr));
2586         lr->lr_event = LE_CONDITIONAL_DESTROY;
2587         lr->lr_active = LFSCK_TYPE_LAYOUT;
2588         lr->lr_fid = *fid;
2589
2590         tmp = req_capsule_client_get(&req->rq_pill, &RMF_LFSCK_REQUEST);
2591         *tmp = *lr;
2592         ptlrpc_request_set_replen(req);
2593
2594         rc = ptlrpc_queue_wait(req);
2595         ptlrpc_req_finished(req);
2596
2597         GOTO(put, rc);
2598
2599 put:
2600         lfsck_tgt_put(ltd);
2601
2602         return rc;
2603 }
2604
2605 static int lfsck_layout_slave_conditional_destroy(const struct lu_env *env,
2606                                                   struct lfsck_component *com,
2607                                                   struct lfsck_request *lr)
2608 {
2609         struct lfsck_thread_info        *info   = lfsck_env_info(env);
2610         struct lu_attr                  *la     = &info->lti_la;
2611         union ldlm_policy_data          *policy = &info->lti_policy;
2612         struct ldlm_res_id              *resid  = &info->lti_resid;
2613         struct lfsck_instance           *lfsck  = com->lc_lfsck;
2614         struct dt_device                *dev    = lfsck->li_bottom;
2615         struct lu_fid                   *fid    = &lr->lr_fid;
2616         struct dt_object                *obj;
2617         struct thandle                  *th     = NULL;
2618         struct lustre_handle             lh     = { 0 };
2619         __u64                            flags  = 0;
2620         int                              rc     = 0;
2621         ENTRY;
2622
2623         obj = lfsck_object_find_by_dev(env, dev, fid);
2624         if (IS_ERR(obj))
2625                 RETURN(PTR_ERR(obj));
2626
2627         dt_read_lock(env, obj, 0);
2628         if (dt_object_exists(obj) == 0 ||
2629             lfsck_is_dead_obj(obj)) {
2630                 dt_read_unlock(env, obj);
2631
2632                 GOTO(put, rc = -ENOENT);
2633         }
2634
2635         /* Get obj's attr without lock firstly. */
2636         rc = dt_attr_get(env, obj, la);
2637         dt_read_unlock(env, obj);
2638         if (rc != 0)
2639                 GOTO(put, rc);
2640
2641         if (likely(la->la_ctime != 0 || la->la_mode & S_ISUID))
2642                 GOTO(put, rc = -ETXTBSY);
2643
2644         /* Acquire extent lock on [0, EOF] to sync with all possible written. */
2645         LASSERT(lfsck->li_namespace != NULL);
2646
2647         memset(policy, 0, sizeof(*policy));
2648         policy->l_extent.end = OBD_OBJECT_EOF;
2649         ost_fid_build_resid(fid, resid);
2650         rc = ldlm_cli_enqueue_local(env, lfsck->li_namespace, resid,
2651                                     LDLM_EXTENT, policy, LCK_EX, &flags,
2652                                     ldlm_blocking_ast, ldlm_completion_ast,
2653                                     NULL, NULL, 0, LVB_T_NONE, NULL, &lh);
2654         if (rc != ELDLM_OK)
2655                 GOTO(put, rc = -EIO);
2656
2657         dt_write_lock(env, obj, 0);
2658         /* Get obj's attr within lock again. */
2659         rc = dt_attr_get(env, obj, la);
2660         if (rc != 0)
2661                 GOTO(unlock, rc);
2662
2663         if (la->la_ctime != 0)
2664                 GOTO(unlock, rc = -ETXTBSY);
2665
2666         th = lfsck_trans_create(env, dev, lfsck);
2667         if (IS_ERR(th))
2668                 GOTO(unlock, rc = PTR_ERR(th));
2669
2670         rc = dt_declare_ref_del(env, obj, th);
2671         if (rc != 0)
2672                 GOTO(stop, rc);
2673
2674         rc = dt_declare_destroy(env, obj, th);
2675         if (rc != 0)
2676                 GOTO(stop, rc);
2677
2678         rc = dt_trans_start_local(env, dev, th);
2679         if (rc != 0)
2680                 GOTO(stop, rc);
2681
2682         rc = dt_ref_del(env, obj, th);
2683         if (rc != 0)
2684                 GOTO(stop, rc);
2685
2686         rc = dt_destroy(env, obj, th);
2687         if (rc == 0)
2688                 CDEBUG(D_LFSCK, "%s: layout LFSCK destroyed the empty "
2689                        "OST-object "DFID" that was created for reparing "
2690                        "dangling referenced case. But the original missing "
2691                        "OST-object is found now.\n",
2692                        lfsck_lfsck2name(lfsck), PFID(fid));
2693
2694         GOTO(stop, rc);
2695
2696 stop:
2697         dt_trans_stop(env, dev, th);
2698
2699 unlock:
2700         dt_write_unlock(env, obj);
2701         ldlm_lock_decref(&lh, LCK_EX);
2702
2703 put:
2704         lfsck_object_put(env, obj);
2705
2706         return rc;
2707 }
2708
2709 /**
2710  * Some OST-object has occupied the specified layout EA slot.
2711  * Such OST-object may be generated by the LFSCK when repair
2712  * dangling referenced MDT-object, which can be indicated by
2713  * attr::la_ctime == 0 but without S_ISUID in la_mode. If it
2714  * is true and such OST-object has not been modified yet, we
2715  * will replace it with the orphan OST-object; otherwise the
2716  * LFSCK will create new MDT-object to reference the orphan.
2717  *
2718  * \retval       +1: repaired
2719  * \retval        0: did nothing
2720  * \retval      -ve: on error
2721  */
2722 static int lfsck_layout_conflict_create(const struct lu_env *env,
2723                                         struct lfsck_component *com,
2724                                         struct lfsck_tgt_desc *ltd,
2725                                         struct lu_orphan_rec_v3 *rec,
2726                                         struct dt_object *parent,
2727                                         struct lu_fid *cfid,
2728                                         struct lu_buf *ea_buf,
2729                                         struct lov_mds_md_v1 *lmm,
2730                                         struct lov_ost_data_v1 *slot,
2731                                         __u32 ea_off, int lovea_size)
2732 {
2733         struct lfsck_thread_info *info          = lfsck_env_info(env);
2734         struct lu_fid            *cfid2         = &info->lti_fid2;
2735         struct ost_id            *oi            = &info->lti_oi;
2736         struct dt_device         *dev           = lfsck_obj2dev(parent);
2737         struct thandle           *th            = NULL;
2738         struct lustre_handle      lh            = { 0 };
2739         __u32                     ost_idx2      = le32_to_cpu(slot->l_ost_idx);
2740         int                       rc            = 0;
2741         ENTRY;
2742
2743         while (CFS_FAIL_TIMEOUT(OBD_FAIL_LFSCK_DELAY3, cfs_fail_val)) {
2744                 if (unlikely(!thread_is_running(&com->lc_lfsck->li_thread)))
2745                         RETURN(0);
2746         }
2747
2748         ostid_le_to_cpu(&slot->l_ost_oi, oi);
2749         rc = ostid_to_fid(cfid2, oi, ost_idx2);
2750         if (rc != 0)
2751                 GOTO(out, rc);
2752
2753         rc = lfsck_ibits_lock(env, com->lc_lfsck, parent, &lh,
2754                               MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR,
2755                               LCK_EX);
2756         if (rc != 0)
2757                 GOTO(out, rc);
2758
2759         rc = lfsck_layout_master_conditional_destroy(env, com, cfid2, ost_idx2);
2760
2761         /* If the conflict OST-obejct is not created for fixing dangling
2762          * referenced MDT-object in former LFSCK check/repair, or it has
2763          * been modified by others, then we cannot destroy it. Re-create
2764          * a new MDT-object for the orphan OST-object. */
2765         if (rc == -ETXTBSY) {
2766                 /* No need the layout lock on the original parent. */
2767                 lfsck_ibits_unlock(&lh, LCK_EX);
2768
2769                 fid_zero(&rec->lor_rec.lor_fid);
2770                 snprintf(info->lti_tmpbuf, sizeof(info->lti_tmpbuf),
2771                          "-"DFID"-%x", PFID(lu_object_fid(&parent->do_lu)),
2772                          ea_off);
2773                 rc = lfsck_layout_recreate_parent(env, com, ltd, rec, cfid,
2774                                                 info->lti_tmpbuf, "C", ea_off);
2775
2776                 RETURN(rc);
2777         }
2778
2779         if (rc != 0 && rc != -ENOENT)
2780                 GOTO(unlock, rc);
2781
2782         if (lfsck_is_dryrun(com->lc_lfsck))
2783                 GOTO(unlock, rc = 0);
2784
2785         th = lfsck_trans_create(env, dev, com->lc_lfsck);
2786         if (IS_ERR(th))
2787                 GOTO(unlock, rc = PTR_ERR(th));
2788
2789         rc = dt_declare_xattr_set(env, parent, ea_buf, XATTR_NAME_LOV,
2790                                   LU_XATTR_REPLACE, th);
2791         if (rc != 0)
2792                 GOTO(stop, rc);
2793
2794         rc = dt_trans_start_local(env, dev, th);
2795         if (rc != 0)
2796                 GOTO(stop, rc);
2797
2798         dt_write_lock(env, parent, 0);
2799         lmm->lmm_layout_gen = cpu_to_le16(le16_to_cpu(lmm->lmm_layout_gen) + 1);
2800         rc = lfsck_layout_refill_lovea(env, com->lc_lfsck, th, parent, cfid,
2801                                        ea_buf, lmm, slot, LU_XATTR_REPLACE,
2802                                        ltd->ltd_index, lovea_size);
2803         dt_write_unlock(env, parent);
2804
2805         GOTO(stop, rc);
2806
2807 stop:
2808         dt_trans_stop(env, dev, th);
2809
2810 unlock:
2811         lfsck_ibits_unlock(&lh, LCK_EX);
2812
2813 out:
2814         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant replaced the conflict "
2815                "OST-object "DFID" on the OST %x with the orphan "DFID" on "
2816                "the OST %x: parent "DFID", stripe-index %u: rc = %d\n",
2817                lfsck_lfsck2name(com->lc_lfsck), PFID(cfid2), ost_idx2,
2818                PFID(cfid), ltd->ltd_index, PFID(lfsck_dto2fid(parent)),
2819                ea_off, rc);
2820
2821         return rc >= 0 ? 1 : rc;
2822 }
2823
2824 /**
2825  * \retval       +1: repaired
2826  * \retval        0: did nothing
2827  * \retval      -ve: on error
2828  */
2829 static int lfsck_layout_recreate_lovea(const struct lu_env *env,
2830                                        struct lfsck_component *com,
2831                                        struct lfsck_tgt_desc *ltd,
2832                                        struct lu_orphan_rec_v3 *rec,
2833                                        struct dt_object *parent,
2834                                        struct lu_fid *cfid,
2835                                        __u32 ost_idx, __u32 ea_off)
2836 {
2837         struct lfsck_thread_info *info          = lfsck_env_info(env);
2838         struct lu_buf            *buf           = &info->lti_big_buf;
2839         struct lu_fid            *fid           = &info->lti_fid2;
2840         struct ost_id            *oi            = &info->lti_oi;
2841         struct lfsck_instance    *lfsck         = com->lc_lfsck;
2842         struct dt_device         *dt            = lfsck_obj2dev(parent);
2843         struct lfsck_bookmark    *bk            = &lfsck->li_bookmark_ram;
2844         struct ost_layout        *ol            = &rec->lor_layout;
2845         struct lov_comp_md_v1    *lcm           = NULL;
2846         struct lov_comp_md_entry_v1 *lcme       = NULL;
2847         struct thandle           *handle        = NULL;
2848         size_t                    lovea_size;
2849         struct lov_mds_md_v1     *lmm;
2850         struct lov_ost_data_v1   *objs;
2851         struct lustre_handle      lh            = { 0 };
2852         __u32                     magic;
2853         __u32 flags = 0;
2854         int                       fl            = 0;
2855         int                       rc            = 0;
2856         int                       rc1;
2857         int                       i;
2858         int pos = 0;
2859         __u16 count;
2860         bool locked = false;
2861         bool new_mirror = true;
2862         ENTRY;
2863
2864         if (lfsck_is_dryrun(lfsck))
2865                 RETURN(0);
2866
2867         rc = lfsck_ibits_lock(env, lfsck, parent, &lh,
2868                               MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR,
2869                               LCK_EX);
2870         if (rc != 0) {
2871                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant failed to recreate "
2872                        "LOV EA for "DFID": parent "DFID", OST-index %u, "
2873                        "stripe-index %u, comp_id %u, comp_start %llu, "
2874                        "comp_end %llu, layout version %u, range %u: rc = %d\n",
2875                        lfsck_lfsck2name(lfsck), PFID(cfid),
2876                        PFID(lfsck_dto2fid(parent)), ost_idx, ea_off,
2877                        ol->ol_comp_id, ol->ol_comp_start,
2878                        ol->ol_comp_end, rec->lor_layout_version,
2879                        rec->lor_range, rc);
2880
2881                 RETURN(rc);
2882         }
2883
2884 again:
2885         if (locked) {
2886                 dt_write_unlock(env, parent);
2887                 locked = false;
2888         }
2889
2890         if (handle != NULL) {
2891                 dt_trans_stop(env, dt, handle);
2892                 handle = NULL;
2893         }
2894
2895         if (rc < 0)
2896                 GOTO(unlock_layout, rc);
2897
2898         lovea_size = rc;
2899         if (buf->lb_len < lovea_size) {
2900                 lu_buf_realloc(buf, lovea_size);
2901                 if (buf->lb_buf == NULL)
2902                         GOTO(unlock_layout, rc = -ENOMEM);
2903         }
2904
2905         if (!(bk->lb_param & LPF_DRYRUN)) {
2906                 handle = lfsck_trans_create(env, dt, lfsck);
2907                 if (IS_ERR(handle))
2908                         GOTO(unlock_layout, rc = PTR_ERR(handle));
2909
2910                 rc = dt_declare_xattr_set(env, parent, buf, XATTR_NAME_LOV,
2911                                           fl, handle);
2912                 if (rc != 0)
2913                         GOTO(stop, rc);
2914
2915                 rc = dt_trans_start_local(env, dt, handle);
2916                 if (rc != 0)
2917                         GOTO(stop, rc);
2918         }
2919
2920         dt_write_lock(env, parent, 0);
2921         locked = true;
2922         rc = dt_xattr_get(env, parent, buf, XATTR_NAME_LOV);
2923         if (rc == -ERANGE) {
2924                 rc = dt_xattr_get(env, parent, &LU_BUF_NULL, XATTR_NAME_LOV);
2925                 LASSERT(rc != 0);
2926                 goto again;
2927         } else if (rc == -ENODATA || rc == 0) {
2928                 lovea_size = lfsck_lovea_size(ol, ea_off);
2929                 /* If the declared is not big enough, re-try. */
2930                 if (buf->lb_len < lovea_size) {
2931                         rc = lovea_size;
2932                         goto again;
2933                 }
2934                 fl = LU_XATTR_CREATE;
2935         } else if (rc < 0) {
2936                 GOTO(unlock_parent, rc);
2937         } else if (unlikely(buf->lb_len == 0)) {
2938                 goto again;
2939         } else {
2940                 fl = LU_XATTR_REPLACE;
2941                 lovea_size = rc;
2942         }
2943
2944         if (fl == LU_XATTR_CREATE) {
2945                 if (bk->lb_param & LPF_DRYRUN)
2946                         GOTO(unlock_parent, rc = 1);
2947
2948                 LASSERT(buf->lb_len >= lovea_size);
2949
2950                 rc = lfsck_layout_update_lovea(env, lfsck, handle, rec, parent,
2951                                                cfid, buf, fl, ost_idx, ea_off);
2952
2953                 GOTO(unlock_parent, rc);
2954         }
2955
2956         lmm = buf->lb_buf;
2957         rc1 = lfsck_layout_verify_header(parent, lmm, lovea_size);
2958
2959         /* If the LOV EA crashed, the rebuild it. */
2960         if (rc1 == -EINVAL) {
2961                 if (bk->lb_param & LPF_DRYRUN)
2962                         GOTO(unlock_parent, rc = 1);
2963
2964                 LASSERT(buf->lb_len >= lovea_size);
2965
2966                 rc = lfsck_layout_update_lovea(env, lfsck, handle, rec, parent,
2967                                                cfid, buf, fl, ost_idx, ea_off);
2968
2969                 GOTO(unlock_parent, rc);
2970         }
2971
2972         /* For other unknown magic/pattern, keep the current LOV EA. */
2973         if (rc1 == -EOPNOTSUPP)
2974                 GOTO(unlock_parent, rc1 = 0);
2975
2976         if (rc1)
2977                 GOTO(unlock_parent, rc = rc1);
2978
2979         magic = le32_to_cpu(lmm->lmm_magic);
2980         if (magic == LOV_MAGIC_COMP_V1 || magic == LOV_MAGIC_SEL) {
2981                 __u64 start;
2982                 __u64 end;
2983                 __u16 mirror_id0 = mirror_id_of(ol->ol_comp_id);
2984                 __u16 mirror_id1;
2985
2986                 if (bk->lb_param & LPF_DRYRUN)
2987                         GOTO(unlock_parent, rc = 1);
2988
2989                 lcm = buf->lb_buf;
2990                 count = le16_to_cpu(lcm->lcm_entry_count);
2991                 for (i = 0; i < count; pos = ++i) {
2992                         lcme = &lcm->lcm_entries[i];
2993                         start = le64_to_cpu(lcme->lcme_extent.e_start);
2994                         end = le64_to_cpu(lcme->lcme_extent.e_end);
2995                         mirror_id1 = mirror_id_of(le32_to_cpu(lcme->lcme_id));
2996
2997                         if (mirror_id0 > mirror_id1)
2998                                 continue;
2999
3000                         if (mirror_id0 < mirror_id1)
3001                                 break;
3002
3003                         new_mirror = false;
3004                         if (end <= ol->ol_comp_start)
3005                                 continue;
3006
3007                         if (start >= ol->ol_comp_end)
3008                                 break;
3009
3010                         lmm = buf->lb_buf + le32_to_cpu(lcme->lcme_offset);
3011                         magic = le32_to_cpu(lmm->lmm_magic);
3012                         flags = le32_to_cpu(lcme->lcme_flags);
3013                         goto further;
3014                 }
3015
3016                 rc = lfsck_layout_add_comp(env, lfsck, handle, rec, parent,
3017                                 cfid, buf, ost_idx, ea_off, pos, new_mirror);
3018
3019                 GOTO(unlock_parent, rc);
3020         }
3021
3022 further:
3023         count = le16_to_cpu(lmm->lmm_stripe_count);
3024         if (count == 0)
3025                 GOTO(unlock_parent, rc = -EINVAL);
3026         LASSERT(count > 0);
3027
3028         /* Exceed the current end of MDT-object layout EA. Then extend it. */
3029         if (count <= ea_off) {
3030                 if (bk->lb_param & LPF_DRYRUN)
3031                         GOTO(unlock_parent, rc = 1);
3032
3033                 lovea_size = lov_mds_md_size(ea_off + 1, magic);
3034                 /* If the declared is not big enough, re-try. */
3035                 if (buf->lb_len < lovea_size) {
3036                         rc = lovea_size;
3037                         goto again;
3038                 }
3039
3040                 if (lcm) {
3041                         LASSERT(lcme);
3042
3043                         lcme->lcme_flags = cpu_to_le32(flags | LCME_FL_INIT);
3044                         lfsck_layout_update_lcm(lcm, lcme,
3045                                                 rec->lor_layout_version,
3046                                                 rec->lor_range);
3047                 }
3048
3049                 rc = lfsck_layout_extend_v1v3_lovea(env, lfsck, handle, ol,
3050                                         parent, cfid, buf, ost_idx, ea_off);
3051
3052                 GOTO(unlock_parent, rc);
3053         }
3054
3055         LASSERTF(rc > 0, "invalid rc = %d\n", rc);
3056
3057         if (magic == LOV_MAGIC_V1) {
3058                 objs = &lmm->lmm_objects[0];
3059         } else {
3060                 LASSERT(magic == LOV_MAGIC_V3);
3061                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[0];
3062         }
3063
3064         for (i = 0; i < count; i++, objs++) {
3065                 /* The MDT-object was created via lfsck_layout_recover_create()
3066                  * by others before, and we fill the dummy layout EA. */
3067                 if ((lcme && !(flags & LCME_FL_INIT)) ||
3068                      lovea_slot_is_dummy(objs)) {
3069                         if (i != ea_off)
3070                                 continue;
3071
3072                         if (bk->lb_param & LPF_DRYRUN)
3073                                 GOTO(unlock_parent, rc = 1);
3074
3075                         lmm->lmm_layout_gen =
3076                             cpu_to_le16(le16_to_cpu(lmm->lmm_layout_gen) + 1);
3077                         if (lcme) {
3078                                 LASSERT(lcm);
3079
3080                                 if (le32_to_cpu(lmm->lmm_stripe_size) !=
3081                                         ol->ol_stripe_size ||
3082                                     le16_to_cpu(lmm->lmm_stripe_count) !=
3083                                         ol->ol_stripe_count ||
3084                                     le64_to_cpu(lcme->lcme_extent.e_start) !=
3085                                         ol->ol_comp_start ||
3086                                     le64_to_cpu(lcme->lcme_extent.e_end) !=
3087                                         ol->ol_comp_end) {
3088                                         CDEBUG(D_LFSCK, "%s: found invalid "
3089                                         "component for "DFID ": parent "DFID
3090                                         ", stripe-index %u, stripe_size %u, "
3091                                         "stripe_count %u, comp_id %u, "
3092                                         "comp_start %llu, comp_end %llu, "
3093                                         "cur_stripe_size %u, "
3094                                         "cur_stripe_count %u, "
3095                                         "cur_comp_start %llu, "
3096                                         "cur_comp_end %llu\n",
3097                                         lfsck_lfsck2name(lfsck), PFID(cfid),
3098                                         PFID(lfsck_dto2fid(parent)), ea_off,
3099                                         ol->ol_stripe_size,
3100                                         ol->ol_stripe_count, ol->ol_comp_id,
3101                                         ol->ol_comp_start, ol->ol_comp_end,
3102                                         le32_to_cpu(lmm->lmm_stripe_size),
3103                                         le16_to_cpu(lmm->lmm_stripe_count),
3104                                         le64_to_cpu(lcme->lcme_extent.e_start),
3105                                         le64_to_cpu(lcme->lcme_extent.e_end));
3106
3107                                         GOTO(unlock_parent, rc = -EINVAL);
3108                                 }
3109
3110                                 lovea_size = le32_to_cpu(lcm->lcm_size);
3111                                 lcme->lcme_flags = cpu_to_le32(flags |
3112                                                                LCME_FL_INIT);
3113                                 lfsck_layout_update_lcm(lcm, lcme,
3114                                                         rec->lor_layout_version,
3115                                                         rec->lor_range);
3116                         }
3117
3118                         LASSERTF(buf->lb_len >= lovea_size,
3119                                  "buffer len %d is less than real size %d\n",
3120                                  (int)buf->lb_len, (int)lovea_size);
3121
3122                         rc = lfsck_layout_refill_lovea(env, lfsck, handle,
3123                                                 parent, cfid, buf, lmm, objs,
3124                                                 fl, ost_idx, lovea_size);
3125
3126                         CDEBUG(D_LFSCK, "%s layout LFSCK assistant fill "
3127                                "dummy layout slot for "DFID": parent "DFID
3128                                ", OST-index %u, stripe-index %u: rc = %d\n",
3129                                lfsck_lfsck2name(lfsck), PFID(cfid),
3130                                PFID(lfsck_dto2fid(parent)), ost_idx, i, rc);
3131
3132                         GOTO(unlock_parent, rc);
3133                 }
3134
3135                 ostid_le_to_cpu(&objs->l_ost_oi, oi);
3136                 rc = ostid_to_fid(fid, oi, le32_to_cpu(objs->l_ost_idx));
3137                 if (rc != 0) {
3138                         CDEBUG(D_LFSCK, "%s: the parent "DFID" contains "
3139                                "invalid layout EA at the slot %d, index %u\n",
3140                                lfsck_lfsck2name(lfsck),
3141                                PFID(lfsck_dto2fid(parent)), i,
3142                                le32_to_cpu(objs->l_ost_idx));
3143
3144                         GOTO(unlock_parent, rc);
3145                 }
3146
3147                 /* It should be rare case, the slot is there, but the LFSCK
3148                  * does not handle it during the first-phase cycle scanning. */
3149                 if (unlikely(lu_fid_eq(fid, cfid))) {
3150                         if (i == ea_off) {
3151                                 GOTO(unlock_parent, rc = 0);
3152                         } else {
3153                                 /* Rare case that the OST-object index
3154                                  * does not match the parent MDT-object
3155                                  * layout EA. We trust the later one. */
3156                                 if (bk->lb_param & LPF_DRYRUN)
3157                                         GOTO(unlock_parent, rc = 1);
3158
3159                                 dt_write_unlock(env, parent);
3160                                 if (handle != NULL)
3161                                         dt_trans_stop(env, dt, handle);
3162                                 lfsck_ibits_unlock(&lh, LCK_EX);
3163                                 rc = lfsck_layout_update_pfid(env, com, parent,
3164                                                         cfid, ltd->ltd_tgt,
3165                                                         rec, i);
3166
3167                                 CDEBUG(D_LFSCK, "%s layout LFSCK assistant "
3168                                        "updated OST-object's pfid for "DFID
3169                                        ": parent "DFID", OST-index %u, "
3170                                        "stripe-index %u: rc = %d\n",
3171                                        lfsck_lfsck2name(lfsck), PFID(cfid),
3172                                        PFID(lfsck_dto2fid(parent)),
3173                                        ltd->ltd_index, i, rc);
3174
3175                                 RETURN(rc);
3176                         }
3177                 }
3178         }
3179
3180         /* The MDT-object exists, but related layout EA slot is occupied
3181          * by others. */
3182         if (bk->lb_param & LPF_DRYRUN)
3183                 GOTO(unlock_parent, rc = 1);
3184
3185         dt_write_unlock(env, parent);
3186         if (handle != NULL)
3187                 dt_trans_stop(env, dt, handle);
3188         lfsck_ibits_unlock(&lh, LCK_EX);
3189         if (magic == LOV_MAGIC_V1)
3190                 objs = &lmm->lmm_objects[ea_off];
3191         else
3192                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[ea_off];
3193         rc = lfsck_layout_conflict_create(env, com, ltd, rec, parent, cfid,
3194                                           buf, lmm, objs, ea_off, lovea_size);
3195
3196         RETURN(rc);
3197
3198 unlock_parent:
3199         if (locked)
3200                 dt_write_unlock(env, parent);
3201
3202 stop:
3203         if (handle != NULL)
3204                 dt_trans_stop(env, dt, handle);
3205
3206 unlock_layout:
3207         lfsck_ibits_unlock(&lh, LCK_EX);
3208
3209         return rc;
3210 }
3211
3212 static int lfsck_layout_scan_orphan_one(const struct lu_env *env,
3213                                         struct lfsck_component *com,
3214                                         struct lfsck_tgt_desc *ltd,
3215                                         struct lu_orphan_rec_v3 *rec,
3216                                         struct lu_fid *cfid)
3217 {
3218         struct lfsck_layout     *lo     = com->lc_file_ram;
3219         struct lu_fid           *pfid   = &rec->lor_rec.lor_fid;
3220         struct dt_object        *parent = NULL;
3221         __u32                    ea_off = pfid->f_stripe_idx;
3222         int                      rc     = 0;
3223         ENTRY;
3224
3225         if (!fid_is_sane(cfid))
3226                 GOTO(out, rc = -EINVAL);
3227
3228         pfid->f_ver = 0;
3229         if (fid_is_zero(pfid)) {
3230                 rc = lfsck_layout_recreate_parent(env, com, ltd, rec, cfid,
3231                                                   "", "N", ea_off);
3232                 GOTO(out, rc);
3233         }
3234
3235         if (!fid_is_sane(pfid))
3236                 GOTO(out, rc = -EINVAL);
3237
3238         parent = lfsck_object_find_by_dev(env, com->lc_lfsck->li_bottom, pfid);
3239         if (IS_ERR(parent))
3240                 GOTO(out, rc = PTR_ERR(parent));
3241
3242         if (unlikely(dt_object_remote(parent) != 0))
3243                 GOTO(put, rc = -EXDEV);
3244
3245         if (dt_object_exists(parent) == 0) {
3246                 lfsck_object_put(env, parent);
3247                 rc = lfsck_layout_recreate_parent(env, com, ltd, rec, cfid,
3248                                                   "", "R", ea_off);
3249                 GOTO(out, rc);
3250         }
3251
3252         if (!S_ISREG(lu_object_attr(&parent->do_lu)))
3253                 GOTO(put, rc = -EISDIR);
3254
3255         /* The orphan OST-object claims to be the parent's stripe, then
3256          * related dangling record in the trace file is meaningless. */
3257         rc = lfsck_layout_del_dangling_rec(env, com, pfid,
3258                                            rec->lor_layout.ol_comp_id, ea_off);
3259         if (rc && rc != -ENOENT)
3260                 GOTO(put, rc);
3261
3262         rc = lfsck_layout_recreate_lovea(env, com, ltd, rec, parent, cfid,
3263                                          ltd->ltd_index, ea_off);
3264
3265         GOTO(put, rc);
3266
3267 put:
3268         if (rc <= 0)
3269                 lfsck_object_put(env, parent);
3270         else
3271                 /* The layout EA is changed, need to be reloaded next time. */
3272                 dt_object_put_nocache(env, parent);
3273
3274 out:
3275         down_write(&com->lc_sem);
3276         com->lc_new_scanned++;
3277         com->lc_new_checked++;
3278         if (rc > 0) {
3279                 lo->ll_objs_repaired[LLIT_ORPHAN - 1]++;
3280                 rc = 0;
3281         } else if (rc < 0) {
3282                 lo->ll_objs_failed_phase2++;
3283         }
3284         up_write(&com->lc_sem);
3285
3286         return rc;
3287 }
3288
3289 static int lfsck_layout_scan_orphan(const struct lu_env *env,
3290                                     struct lfsck_component *com,
3291                                     struct lfsck_tgt_desc *ltd)
3292 {
3293         struct lfsck_assistant_data     *lad    = com->lc_data;
3294         struct lfsck_instance           *lfsck  = com->lc_lfsck;
3295         struct lfsck_bookmark           *bk     = &lfsck->li_bookmark_ram;
3296         struct lfsck_thread_info        *info   = lfsck_env_info(env);
3297         struct lu_fid                   *fid    = &info->lti_fid;
3298         struct dt_object                *obj;
3299         const struct dt_it_ops          *iops;
3300         struct dt_it                    *di;
3301         int                              rc     = 0;
3302         ENTRY;
3303
3304         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant starts the orphan "
3305                "scanning for OST%04x\n",
3306                lfsck_lfsck2name(lfsck), ltd->ltd_index);
3307
3308         if (test_bit(ltd->ltd_index, lad->lad_bitmap)) {
3309                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant skip the orphan "
3310                        "scanning for OST%04x\n",
3311                        lfsck_lfsck2name(lfsck), ltd->ltd_index);
3312
3313                 RETURN(0);
3314         }
3315
3316         fid->f_seq = fid_idif_seq(0, ltd->ltd_index);
3317         fid->f_oid = fid->f_ver = 0;
3318
3319         obj = lfsck_object_find_by_dev(env, ltd->ltd_tgt, fid);
3320         if (unlikely(IS_ERR(obj)))
3321                 GOTO(log, rc = PTR_ERR(obj));
3322
3323         rc = obj->do_ops->do_index_try(env, obj,
3324                                        &dt_lfsck_layout_orphan_features);
3325         if (rc != 0)
3326                 GOTO(put, rc);
3327
3328         iops = &obj->do_index_ops->dio_it;
3329         di = iops->init(env, obj, 0);
3330         if (IS_ERR(di))
3331                 GOTO(put, rc = PTR_ERR(di));
3332
3333         rc = iops->load(env, di, 0);
3334         if (rc == -ESRCH) {
3335                 /* -ESRCH means that the orphan OST-objects rbtree has been
3336                  * cleanup because of the OSS server restart or other errors. */
3337                 lfsck_lad_set_bitmap(env, com, ltd->ltd_index);
3338                 GOTO(fini, rc);
3339         }
3340
3341         if (rc == 0)
3342                 rc = iops->next(env, di);
3343         else if (rc > 0)
3344                 rc = 0;
3345
3346         if (rc < 0)
3347                 GOTO(fini, rc);
3348
3349         if (rc > 0)
3350                 GOTO(fini, rc = 0);
3351
3352         do {
3353                 struct dt_key           *key;
3354                 struct lu_orphan_rec_v3 *rec = &info->lti_rec;
3355
3356                 if (CFS_FAIL_TIMEOUT(OBD_FAIL_LFSCK_DELAY3, cfs_fail_val) &&
3357                     unlikely(!thread_is_running(&lfsck->li_thread)))
3358                         break;
3359
3360                 key = iops->key(env, di);
3361                 com->lc_fid_latest_scanned_phase2 = *(struct lu_fid *)key;
3362                 /* Remote target OST may be runnning old LFSCK */
3363                 memset(rec, 0, sizeof(*rec));
3364                 rc = iops->rec(env, di, (struct dt_rec *)rec, 0);
3365                 if (rc == 0)
3366                         rc = lfsck_layout_scan_orphan_one(env, com, ltd, rec,
3367                                         &com->lc_fid_latest_scanned_phase2);
3368                 if (rc != 0 && bk->lb_param & LPF_FAILOUT)
3369                         GOTO(fini, rc);
3370
3371                 lfsck_control_speed_by_self(com);
3372                 do {
3373                         rc = iops->next(env, di);
3374                 } while (rc < 0 && !(bk->lb_param & LPF_FAILOUT));
3375         } while (rc == 0);
3376
3377         GOTO(fini, rc);
3378
3379 fini:
3380         iops->put(env, di);
3381         iops->fini(env, di);
3382 put:
3383         lfsck_object_put(env, obj);
3384
3385 log:
3386         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant finished the orphan "
3387                "scanning for OST%04x: rc = %d\n",
3388                lfsck_lfsck2name(lfsck), ltd->ltd_index, rc);
3389
3390         return rc > 0 ? 0 : rc;
3391 }
3392
3393 static int lfsck_lov2layout(struct lov_mds_md_v1 *lmm, struct filter_fid *ff,
3394                             __u32 comp_id)
3395 {
3396         struct ost_layout *ol = &ff->ff_layout;
3397         __u32 magic = le32_to_cpu(lmm->lmm_magic);
3398         int rc = 0;
3399         ENTRY;
3400
3401         if (magic == LOV_MAGIC_V1 || magic == LOV_MAGIC_V3) {
3402                 ol->ol_stripe_size = lmm->lmm_stripe_size;
3403                 ol->ol_stripe_count = lmm->lmm_stripe_count;
3404                 ol->ol_comp_start = 0;
3405                 ol->ol_comp_end = 0;
3406                 ol->ol_comp_id = 0;
3407                 ff->ff_layout_version = 0;
3408                 ff->ff_range = 0;
3409         } else if (magic == LOV_MAGIC_COMP_V1 || magic == LOV_MAGIC_SEL) {
3410                 struct lov_comp_md_v1 *lcm = (struct lov_comp_md_v1 *)lmm;
3411                 struct lov_comp_md_entry_v1 *lcme = NULL;
3412                 __u16 count = le16_to_cpu(lcm->lcm_entry_count);
3413                 int i;
3414
3415                 for (i = 0; i < count; i++) {
3416                         lcme = &lcm->lcm_entries[i];
3417                         if (le32_to_cpu(lcme->lcme_id) == comp_id) {
3418                                 LASSERT(le32_to_cpu(lcme->lcme_flags) &
3419                                         LCME_FL_INIT);
3420
3421                                 break;
3422                         }
3423                 }
3424
3425                 /* The comp has been removed, do nothing. */
3426                 if (i == count)
3427                         GOTO(out, rc = 1);
3428
3429                 lmm = (void *)lmm + le32_to_cpu(lcme->lcme_offset);
3430                 ol->ol_stripe_size = le32_to_cpu(lmm->lmm_stripe_size);
3431                 ol->ol_stripe_count = le32_to_cpu(lmm->lmm_stripe_count);
3432                 ol->ol_comp_start = le64_to_cpu(lcme->lcme_extent.e_start);
3433                 ol->ol_comp_end = le64_to_cpu(lcme->lcme_extent.e_end);
3434                 ol->ol_comp_id = le32_to_cpu(lcme->lcme_id);
3435                 ff->ff_layout_version = le32_to_cpu(lcme->lcme_layout_gen);
3436                 ff->ff_range = 0;
3437         } else {
3438                 GOTO(out, rc = -EINVAL);
3439         }
3440
3441         EXIT;
3442
3443 out:
3444         return rc;
3445 }
3446
3447 /**
3448  * Repair the MDT-object with dangling LOV EA reference.
3449  *
3450  * we need to repair the inconsistency according to the users' requirement:
3451  *
3452  * 1) Keep the inconsistency there and report the inconsistency case,
3453  *    then give the chance to the application to find related issues,
3454  *    and the users can make the decision about how to handle it with
3455  *    more human knownledge. (by default)
3456  *
3457  * 2) Re-create the missing OST-object with the FID/owner information.
3458  *
3459  * \param[in] env       pointer to the thread context
3460  * \param[in] com       the layout LFSCK component
3461  * \param[in] parent    the MDT-object with dangling LOV EA reference
3462  * \param[in] child     the OST-object to be created
3463  * \param[in] comp_id   the component ID of the OST-object in the LOV EA
3464  * \param[in] ea_off    the offset of the OST-object in the LOV EA
3465  * \param[in] ost_idx   the index of OST on which the OST-object resides
3466  *
3467  * \retval              +1 for repair successfully
3468  * \retval              0 for did nothing
3469  * \retval              negative error number on failure
3470  */
3471 static int __lfsck_layout_repair_dangling(const struct lu_env *env,
3472                                           struct lfsck_component *com,
3473                                           struct dt_object *parent,
3474                                           struct dt_object *child,
3475                                           __u32 comp_id, __u32 ea_off,
3476                                           __u32 ost_idx, bool log)
3477 {
3478         struct lfsck_thread_info *info = lfsck_env_info(env);
3479         struct filter_fid *ff = &info->lti_ff;
3480         struct dt_object_format *dof = &info->lti_dof;
3481         struct lu_attr *la = &info->lti_la;
3482         struct lfsck_instance *lfsck = com->lc_lfsck;
3483         struct dt_device *dev = lfsck_obj2dev(child);
3484         const struct lu_fid *pfid = lfsck_dto2fid(parent);
3485         const struct lu_fid *cfid = lfsck_dto2fid(child);
3486         struct lu_buf *tbuf = &info->lti_big_buf;
3487         struct thandle *handle;
3488         struct lu_buf *buf;
3489         struct lustre_handle lh = { 0 };
3490         int rc;
3491         ENTRY;
3492
3493         if (!(lfsck->li_bookmark_ram.lb_param & LPF_CREATE_OSTOBJ))
3494                 GOTO(log, rc = 1);
3495
3496         rc = lfsck_ibits_lock(env, lfsck, parent, &lh,
3497                               MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR,
3498                               LCK_EX);
3499         if (rc != 0)
3500                 GOTO(log, rc);
3501
3502         rc = dt_attr_get(env, parent, la);
3503         if (rc != 0)
3504                 GOTO(unlock1, rc);
3505
3506         la->la_mode = S_IFREG | 0666;
3507         la->la_atime = la->la_mtime = la->la_ctime = 0;
3508         la->la_valid = LA_TYPE | LA_MODE | LA_UID | LA_GID |
3509                        LA_ATIME | LA_MTIME | LA_CTIME;
3510         memset(dof, 0, sizeof(*dof));
3511         ff->ff_parent.f_seq = cpu_to_le64(pfid->f_seq);
3512         ff->ff_parent.f_oid = cpu_to_le32(pfid->f_oid);
3513         /* Currently, the filter_fid::ff_parent::f_ver is not the real parent
3514          * MDT-object's FID::f_ver, instead it is the OST-object index in its
3515          * parent MDT-object's layout EA. */
3516         ff->ff_parent.f_stripe_idx = cpu_to_le32(ea_off);
3517
3518         rc = lfsck_layout_get_lovea(env, parent, tbuf);
3519         if (unlikely(rc == -ENODATA))
3520                 rc = 0;
3521         if (rc <= 0)
3522                 GOTO(unlock1, rc);
3523
3524         rc = lfsck_lov2layout(tbuf->lb_buf, ff, comp_id);
3525         if (rc)
3526                 GOTO(unlock1, rc);
3527
3528         buf = lfsck_buf_get(env, ff, sizeof(struct filter_fid));
3529         handle = lfsck_trans_create(env, dev, lfsck);
3530         if (IS_ERR(handle))
3531                 GOTO(unlock1, rc = PTR_ERR(handle));
3532
3533         rc = dt_declare_create(env, child, la, NULL, dof, handle);
3534         if (rc != 0)
3535                 GOTO(stop, rc);
3536
3537         rc = dt_declare_xattr_set(env, child, buf, XATTR_NAME_FID,
3538                                   LU_XATTR_CREATE, handle);
3539         if (rc != 0)
3540                 GOTO(stop, rc);
3541
3542         rc = dt_trans_start_local(env, dev, handle);
3543         if (rc != 0)
3544                 GOTO(stop, rc);
3545
3546         dt_read_lock(env, parent, 0);
3547         if (unlikely(lfsck_is_dead_obj(parent)))
3548                 GOTO(unlock2, rc = 0);
3549
3550         if (lfsck->li_bookmark_ram.lb_param & LPF_DELAY_CREATE_OSTOBJ) {
3551                 struct ost_id *oi = &info->lti_oi;
3552                 struct lu_fid *tfid = &info->lti_fid2;
3553                 struct lu_buf *lovea = &info->lti_big_buf;
3554                 struct lov_mds_md_v1 *lmm;
3555                 struct lov_ost_data_v1 *objs;
3556                 __u32 magic;
3557                 int count;
3558                 int idx2;
3559
3560                 rc = lfsck_layout_get_lovea(env, parent, lovea);
3561                 if (unlikely(rc == -ENODATA))
3562                         rc = 0;
3563                 if (rc <= 0)
3564                         GOTO(unlock2, rc);
3565
3566                 lmm = lovea->lb_buf;
3567                 magic = le32_to_cpu(lmm->lmm_magic);
3568                 if (magic == LOV_MAGIC_COMP_V1 || magic == LOV_MAGIC_SEL) {
3569                         struct lov_comp_md_v1 *lcm = buf->lb_buf;
3570                         struct lov_comp_md_entry_v1 *lcme;
3571                         __u16 count = le16_to_cpu(lcm->lcm_entry_count);
3572                         int i;
3573
3574                         for (i = 0; i < count; i++) {
3575                                 lcme = &lcm->lcm_entries[i];
3576                                 if (le32_to_cpu(lcme->lcme_id) == comp_id) {
3577                                         LASSERT(le32_to_cpu(lcme->lcme_flags) &
3578                                                 LCME_FL_INIT);
3579
3580                                         lmm = lovea->lb_buf +
3581                                                 le32_to_cpu(lcme->lcme_offset);
3582                                         magic = le32_to_cpu(lmm->lmm_magic);
3583                                         goto check;
3584                                 }
3585                         }
3586
3587                         /* Someone removed the component, do nothing. */
3588                         GOTO(unlock2, rc = 0);
3589                 }
3590
3591 check:
3592                 count = le16_to_cpu(lmm->lmm_stripe_count);
3593                 /* Someone changed the LOV EA, do nothing. */
3594                 if (count <= ea_off)
3595                         GOTO(unlock2, rc = 0);
3596
3597                 if (magic == LOV_MAGIC_V1) {
3598                         objs = &lmm->lmm_objects[ea_off];
3599                 } else {
3600                         LASSERT(magic == LOV_MAGIC_V3);
3601
3602                         objs = &((struct lov_mds_md_v3 *)lmm)->\
3603                                                         lmm_objects[ea_off];
3604                 }
3605
3606                 ostid_le_to_cpu(&objs->l_ost_oi, oi);
3607                 idx2 = le32_to_cpu(objs->l_ost_idx);
3608                 rc = ostid_to_fid(tfid, oi, idx2);
3609                 /* Someone changed the LOV EA, do nothing. */
3610                 if (rc != 0 || !lu_fid_eq(tfid, cfid))
3611                         GOTO(unlock2, rc);
3612         }
3613
3614         rc = dt_create(env, child, la, NULL, dof, handle);
3615         if (rc != 0)
3616                 GOTO(unlock2, rc);
3617
3618         rc = dt_xattr_set(env, child, buf, XATTR_NAME_FID, LU_XATTR_CREATE,
3619                           handle);
3620
3621         GOTO(unlock2, rc);
3622
3623 unlock2:
3624         dt_read_unlock(env, parent);
3625
3626 stop:
3627         rc = lfsck_layout_trans_stop(env, dev, handle, rc);
3628
3629 unlock1:
3630         lfsck_ibits_unlock(&lh, LCK_EX);
3631
3632 log:
3633         if (rc && log)
3634                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant found "
3635                        "dangling reference for: parent "DFID", child "
3636                        DFID", comp_id %u, ea_off %u, ost_idx %u, %s: "
3637                        "rc = %d\n",
3638                        lfsck_lfsck2name(lfsck), PFID(pfid), PFID(cfid),
3639                        comp_id, ea_off, ost_idx,
3640                        (lfsck->li_bookmark_ram.lb_param & LPF_CREATE_OSTOBJ) ?
3641                                 "Create the lost OST-object as required" :
3642                                 "Keep the MDT-object there by default", rc);
3643
3644         return rc;
3645 }
3646
3647 /**
3648  * Repair the MDT-object with dangling LOV EA reference.
3649  *
3650  * Prepare parameters and call __lfsck_layout_repair_dangling()
3651  * to repair the dangling LOV EA reference.
3652  *
3653  * \param[in] env       pointer to the thread context
3654  * \param[in] com       the layout LFSCK component
3655  * \param[in] pfid      the MDT-object's FID
3656  * \param[in] cfid      the FID for the OST-object to be created
3657  * \param[in] comp_id   the component ID of the OST-object in the LOV EA
3658  * \param[in] ea_off    the offset of the OST-object in the LOV EA
3659  * \param[in] ost_idx   the index of OST on which the OST-object resides
3660  *
3661  * \retval              +1 for repair successfully
3662  * \retval              0 for did nothing
3663  * \retval              negative error number on failure
3664  */
3665 static int lfsck_layout_repair_dangling(const struct lu_env *env,
3666                                         struct lfsck_component *com,
3667                                         const struct lu_fid *pfid,
3668                                         const struct lu_fid *cfid,
3669                                         __u32 comp_id, __u32 ea_off,
3670                                         __u32 ost_idx)
3671 {
3672         struct lfsck_instance *lfsck = com->lc_lfsck;
3673         struct dt_object *parent = NULL;
3674         struct dt_object *child = NULL;
3675         struct lfsck_tgt_desc *ltd;
3676         int rc;
3677         ENTRY;
3678
3679         parent = lfsck_object_find_bottom(env, lfsck, pfid);
3680         if (IS_ERR(parent))
3681                 GOTO(log, rc = PTR_ERR(parent));
3682
3683         /* The MDT-object has been removed. */
3684         if (dt_object_exists(parent) == 0)
3685                 GOTO(log, rc = 0);
3686
3687         ltd = lfsck_ltd2tgt(&lfsck->li_ost_descs, ost_idx);
3688         if (unlikely(ltd == NULL))
3689                 GOTO(log, rc = -ENODEV);
3690
3691         child = lfsck_object_find_by_dev(env, ltd->ltd_tgt, cfid);
3692         if (IS_ERR(child))
3693                 GOTO(log, rc = PTR_ERR(child));
3694
3695         /* The OST-object has been created. */
3696         if (unlikely(dt_object_exists(child) != 0))
3697                 GOTO(log, rc = 0);
3698
3699         rc = __lfsck_layout_repair_dangling(env, com, parent, child,
3700                                             comp_id, ea_off, ost_idx, false);
3701
3702         GOTO(log, rc);
3703
3704 log:
3705         if (child != NULL && !IS_ERR(child))
3706                 lfsck_object_put(env, child);
3707
3708         if (parent != NULL && !IS_ERR(parent))
3709                 lfsck_object_put(env, parent);
3710
3711         if (rc)
3712                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant found "
3713                        "dangling reference for: parent "DFID", child "
3714                        DFID", comp_id %u, ea_off %u, ost_idx %u, %s: rc = %d\n",
3715                        lfsck_lfsck2name(lfsck), PFID(pfid), PFID(cfid),
3716                        comp_id, ea_off, ost_idx,
3717                        (lfsck->li_bookmark_ram.lb_param & LPF_CREATE_OSTOBJ) ?
3718                                 "Create the lost OST-object as required" :
3719                                 "Keep the MDT-object there by default", rc);
3720
3721         return rc;
3722 }
3723
3724 /* If the OST-object does not recognize the MDT-object as its parent, and
3725  * there is no other MDT-object claims as its parent, then just trust the
3726  * given MDT-object as its parent. So update the OST-object filter_fid. */
3727 static int lfsck_layout_repair_unmatched_pair(const struct lu_env *env,
3728                                               struct lfsck_component *com,
3729                                               struct dt_object *parent,
3730                                               struct lfsck_layout_req *llr,
3731                                               struct lu_attr *la)
3732 {
3733         struct lfsck_thread_info        *info   = lfsck_env_info(env);
3734         struct filter_fid               *ff     = &info->lti_ff;
3735         struct dt_object                *child  = llr->llr_child;
3736         struct dt_device                *dev    = lfsck_obj2dev(child);
3737         const struct lu_fid             *tfid   = lu_object_fid(&parent->do_lu);
3738         struct lu_buf                   *tbuf   = &info->lti_big_buf;
3739         struct thandle                  *handle;
3740         struct lu_buf                   *buf;
3741         struct lustre_handle             lh     = { 0 };
3742         int                              rc;
3743         ENTRY;
3744
3745         rc = lfsck_ibits_lock(env, com->lc_lfsck, parent, &lh,
3746                               MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR,
3747                               LCK_EX);
3748         if (rc != 0)
3749                 GOTO(log, rc);
3750
3751         ff->ff_parent.f_seq = cpu_to_le64(tfid->f_seq);
3752         ff->ff_parent.f_oid = cpu_to_le32(tfid->f_oid);
3753         /* Currently, the filter_fid::ff_parent::f_ver is not the real parent
3754          * MDT-object's FID::f_ver, instead it is the OST-object index in its
3755          * parent MDT-object's layout EA. */
3756         ff->ff_parent.f_stripe_idx = cpu_to_le32(llr->llr_lov_idx);
3757
3758         rc = lfsck_layout_get_lovea(env, parent, tbuf);
3759         if (unlikely(rc == -ENODATA))
3760                 rc = 0;
3761         if (rc <= 0)
3762                 GOTO(unlock1, rc);
3763
3764         rc = lfsck_lov2layout(tbuf->lb_buf, ff, llr->llr_comp_id);
3765         if (rc)
3766                 GOTO(unlock1, rc);
3767
3768         buf = lfsck_buf_get(env, ff, sizeof(*ff));
3769
3770         handle = lfsck_trans_create(env, dev, com->lc_lfsck);
3771         if (IS_ERR(handle))
3772                 GOTO(unlock1, rc = PTR_ERR(handle));
3773
3774         rc = dt_declare_xattr_set(env, child, buf, XATTR_NAME_FID, 0, handle);
3775         if (rc != 0)
3776                 GOTO(stop, rc);
3777
3778         rc = dt_attr_get(env, parent, la);
3779         if (rc != 0)
3780                 GOTO(stop, rc);
3781
3782         la->la_valid = LA_UID | LA_GID;
3783         rc = dt_declare_attr_set(env, child, la, handle);
3784         if (rc != 0)
3785                 GOTO(stop, rc);
3786
3787         rc = dt_trans_start_local(env, dev, handle);
3788         if (rc != 0)
3789                 GOTO(stop, rc);
3790
3791         dt_write_lock(env, parent, 0);
3792         if (unlikely(lfsck_is_dead_obj(parent)))
3793                 GOTO(unlock2, rc = 1);
3794
3795         rc = dt_xattr_set(env, child, buf, XATTR_NAME_FID, 0, handle);
3796         if (rc != 0)
3797                 GOTO(unlock2, rc);
3798
3799         /* Get the latest parent's owner. */
3800         rc = dt_attr_get(env, parent, la);
3801         if (rc != 0)
3802                 GOTO(unlock2, rc);
3803
3804         la->la_valid = LA_UID | LA_GID;
3805         rc = dt_attr_set(env, child, la, handle);
3806
3807         GOTO(unlock2, rc);
3808
3809 unlock2:
3810         dt_write_unlock(env, parent);
3811
3812 stop:
3813         rc = lfsck_layout_trans_stop(env, dev, handle, rc);
3814
3815 unlock1:
3816         lfsck_ibits_unlock(&lh, LCK_EX);
3817
3818 log:
3819         if (rc)
3820                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant repaired "
3821                        "unmatched MDT-OST pair for: parent "DFID
3822                        ", child "DFID", comp_id %u, OST-index %u, "
3823                        "stripe-index %u, owner %u/%u: rc = %d\n",
3824                        lfsck_lfsck2name(com->lc_lfsck),
3825                        PFID(lfsck_dto2fid(parent)),
3826                        PFID(lfsck_dto2fid(child)),
3827                        llr->llr_comp_id, llr->llr_ost_idx, llr->llr_lov_idx,
3828                        la->la_uid, la->la_gid, rc);
3829
3830         return rc;
3831 }
3832
3833 /* If there are more than one MDT-objects claim as the OST-object's parent,
3834  * and the OST-object only recognizes one of them, then we need to generate
3835  * new OST-object(s) with new fid(s) for the non-recognized MDT-object(s). */
3836 static int lfsck_layout_repair_multiple_references(const struct lu_env *env,
3837                                                    struct lfsck_component *com,
3838                                                    struct dt_object *parent,
3839                                                    struct lfsck_layout_req *llr,
3840                                                    struct lu_attr *la)
3841 {
3842         struct lfsck_thread_info        *info   = lfsck_env_info(env);
3843         struct dt_allocation_hint       *hint   = &info->lti_hint;
3844         struct dt_object_format         *dof    = &info->lti_dof;
3845         struct ost_id                   *oi     = &info->lti_oi;
3846         struct lu_buf                   *buf    = &info->lti_big_buf;
3847         struct lfsck_instance           *lfsck  = com->lc_lfsck;
3848         struct dt_device                *dev;
3849         struct lu_device                *d      =
3850                                 &lfsck_obj2dev(llr->llr_child)->dd_lu_dev;
3851         struct lu_object                *o;
3852         struct lu_object                *n;
3853         struct dt_object                *child  = NULL;
3854         struct thandle                  *handle = NULL;
3855         struct lov_mds_md_v1            *lmm;
3856         struct lov_ost_data_v1          *objs;
3857         const struct lu_fid             *pfid   = lfsck_dto2fid(parent);
3858         struct lu_fid                    tfid;
3859         struct lustre_handle             lh     = { 0 };
3860         __u32                            magic;
3861         __u32                            index;
3862         int                              rc;
3863         ENTRY;
3864
3865         /* We use two separated transactions to repair the inconsistency.
3866          *
3867          * 1) create the child (OST-object).
3868          * 2) update the parent LOV EA according to the child's FID.
3869          *
3870          * If 1) succeed, but 2) failed or aborted, then such OST-object will be
3871          * handled as orphan when the layout LFSCK run next time.
3872          *
3873          * If 1) failed, but 2) succeed, then such OST-object will be re-created
3874          * as dangling referened case when the layout LFSCK run next time. */
3875
3876         /* The 1st transaction. */
3877         o = lu_object_anon(env, d, NULL);
3878         if (IS_ERR(o))
3879                 GOTO(log, rc = PTR_ERR(o));
3880
3881         n = lu_object_locate(o->lo_header, d->ld_type);
3882         if (unlikely(n == NULL)) {
3883                 lu_object_put_nocache(env, o);
3884
3885                 GOTO(log, rc = -EINVAL);
3886         }
3887
3888         child = container_of(n, struct dt_object, do_lu);
3889         memset(hint, 0, sizeof(*hint));
3890         rc = dt_attr_get(env, parent, la);
3891         if (rc != 0)
3892                 GOTO(log, rc);
3893
3894         la->la_valid = LA_UID | LA_GID;
3895         memset(dof, 0, sizeof(*dof));
3896
3897         dev = lfsck_obj2dev(child);
3898         handle = lfsck_trans_create(env, dev, lfsck);
3899         if (IS_ERR(handle))
3900                 GOTO(log, rc = PTR_ERR(handle));
3901
3902         rc = dt_declare_create(env, child, la, hint, dof, handle);
3903         if (rc != 0)
3904                 GOTO(stop, rc);
3905
3906         rc = dt_trans_start_local(env, dev, handle);
3907         if (rc != 0)
3908                 GOTO(stop, rc);
3909
3910         rc = dt_create(env, child, la, hint, dof, handle);
3911         dt_trans_stop(env, dev, handle);
3912         handle = NULL;
3913         if (rc != 0)
3914                 GOTO(log, rc);
3915
3916         rc = lfsck_ibits_lock(env, lfsck, parent, &lh,
3917                               MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR,
3918                               LCK_EX);
3919         if (rc != 0)
3920                 GOTO(log, rc);
3921
3922         /* The 2nd transaction. */
3923
3924         /* XXX: Generally, we should use bottom device (OSD) to update parent
3925          *      LOV EA. But because the LOD-object still references the wrong
3926          *      OSP-object that should be detached after the parent's LOV EA
3927          *      refreshed. Unfortunately, there is no suitable API for that.
3928          *      So we have to make the LOD to re-load the OSP-object(s) via
3929          *      replacing the LOV EA against the LOD-object.
3930          *
3931          *      Once the DNE2 patches have been landed, we can replace the
3932          *      LOD device with the OSD device. LU-6230. */
3933
3934         dev = lfsck->li_next;
3935         parent = lfsck_object_locate(dev, parent);
3936         if (IS_ERR(parent))
3937                 GOTO(log, rc = PTR_ERR(parent));
3938
3939         handle = lfsck_trans_create(env, dev, lfsck);
3940         if (IS_ERR(handle))
3941                 GOTO(log, rc = PTR_ERR(handle));
3942
3943         rc = dt_declare_xattr_set(env, parent, buf, XATTR_NAME_LOV,
3944                                   LU_XATTR_REPLACE, handle);
3945         if (rc != 0)
3946                 GOTO(stop, rc);
3947
3948         rc = dt_trans_start_local(env, dev, handle);
3949         if (rc != 0)
3950                 GOTO(stop, rc);
3951
3952         dt_write_lock(env, parent, 0);
3953         if (unlikely(lfsck_is_dead_obj(parent)))
3954                 GOTO(unlock, rc = 0);
3955
3956         rc = lfsck_layout_get_lovea(env, parent, buf);
3957         if (unlikely(rc == -ENODATA))
3958                 rc = 0;
3959         if (rc <= 0)
3960                 GOTO(unlock, rc);
3961
3962         lmm = buf->lb_buf;
3963         magic = le32_to_cpu(lmm->lmm_magic);
3964         if (magic == LOV_MAGIC_COMP_V1 || magic == LOV_MAGIC_SEL) {
3965                 struct lov_comp_md_v1 *lcm = buf->lb_buf;
3966                 struct lov_comp_md_entry_v1 *lcme;
3967                 __u16 count = le16_to_cpu(lcm->lcm_entry_count);
3968                 int i;
3969
3970                 LASSERT(llr->llr_comp_id != 0);
3971
3972                 for (i = 0; i < count; i++) {
3973                         lcme = &lcm->lcm_entries[i];
3974                         if (le32_to_cpu(lcme->lcme_id) == llr->llr_comp_id) {
3975                                 LASSERT(le32_to_cpu(lcme->lcme_flags) &
3976                                         LCME_FL_INIT);
3977
3978                                 le32_add_cpu(&lcm->lcm_layout_gen, 1);
3979                                 lmm = buf->lb_buf +
3980                                         le32_to_cpu(lcme->lcme_offset);
3981                                 magic = le32_to_cpu(lmm->lmm_magic);
3982                                 goto set;
3983                         }
3984                 }
3985
3986                 GOTO(unlock, rc = 0);
3987         }
3988
3989 set:
3990         if (magic == LOV_MAGIC_V1) {
3991                 objs = &lmm->lmm_objects[llr->llr_lov_idx];
3992         } else {
3993                 LASSERT(magic == LOV_MAGIC_V3);
3994                 objs =
3995                 &((struct lov_mds_md_v3 *)lmm)->lmm_objects[llr->llr_lov_idx];
3996         }
3997
3998         ostid_le_to_cpu(&objs->l_ost_oi, oi);
3999         index = le32_to_cpu(objs->l_ost_idx);
4000         rc = ostid_to_fid(&tfid, oi, index);
4001         /* Someone changed layout during the LFSCK, no need to repair then. */
4002         if (rc == 0 && !lu_fid_eq(&tfid, lu_object_fid(&llr->llr_child->do_lu)))
4003                 GOTO(unlock, rc = 0);
4004
4005         lmm->lmm_layout_gen = cpu_to_le16(le16_to_cpu(lmm->lmm_layout_gen) + 1);
4006         fid_to_ostid(lu_object_fid(&child->do_lu), oi);
4007         ostid_cpu_to_le(oi, &objs->l_ost_oi);
4008         objs->l_ost_gen = cpu_to_le32(0);
4009         objs->l_ost_idx = cpu_to_le32(llr->llr_ost_idx);
4010         rc = dt_xattr_set(env, parent, buf, XATTR_NAME_LOV,
4011                           LU_XATTR_REPLACE, handle);
4012
4013         GOTO(unlock, rc = (rc == 0 ? 1 : rc));
4014
4015 unlock:
4016         dt_write_unlock(env, parent);
4017
4018 stop:
4019         if (handle != NULL)
4020                 dt_trans_stop(env, dev, handle);
4021
4022 log:
4023         lfsck_ibits_unlock(&lh, LCK_EX);
4024         if (child != NULL)
4025                 lfsck_object_put(env, child);
4026
4027         if (rc)
4028                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant repaired "
4029                        "multiple references for: parent "DFID", comp_id %u, "
4030                        "OST-index %u, stripe-index %u, owner %u/%u: rc = %d\n",
4031                        lfsck_lfsck2name(lfsck), PFID(pfid),
4032                        llr->llr_comp_id, llr->llr_ost_idx, llr->llr_lov_idx,
4033                        la->la_uid, la->la_gid, rc);
4034
4035         return rc;
4036 }
4037
4038 /* If the MDT-object and the OST-object have different owner information,
4039  * then trust the MDT-object, because the normal chown/chgrp handle order
4040  * is from MDT to OST, and it is possible that some chown/chgrp operation
4041  * is partly done. */
4042 static int lfsck_layout_repair_owner(const struct lu_env *env,
4043                                      struct lfsck_component *com,
4044                                      struct dt_object *parent,
4045                                      struct lfsck_layout_req *llr,
4046                                      struct lu_attr *pla,
4047                                      const struct lu_attr *cla)
4048 {
4049         struct lfsck_thread_info        *info   = lfsck_env_info(env);
4050         struct lu_attr                  *tla    = &info->lti_la2;
4051         struct dt_object                *child  = llr->llr_child;
4052         struct dt_device                *dev    = lfsck_obj2dev(child);
4053         struct thandle                  *handle;
4054         int                              rc;
4055         dt_obj_version_t                 version;
4056         ENTRY;
4057
4058         tla->la_uid = pla->la_uid;
4059         tla->la_gid = pla->la_gid;
4060         tla->la_valid = LA_UID | LA_GID;
4061         handle = lfsck_trans_create(env, dev, com->lc_lfsck);
4062         if (IS_ERR(handle))
4063                 GOTO(log, rc = PTR_ERR(handle));
4064
4065         rc = dt_declare_attr_set(env, child, tla, handle);
4066         if (rc != 0)
4067                 GOTO(stop, rc);
4068
4069         rc = dt_trans_start_local(env, dev, handle);
4070         if (rc != 0)
4071                 GOTO(stop, rc);
4072
4073         /* Use the dt_object lock to serialize with destroy and attr_set. */
4074         dt_read_lock(env, parent, 0);
4075         if (unlikely(lfsck_is_dead_obj(parent)))
4076                 GOTO(unlock, rc = 1);
4077
4078         version = dt_version_get(env, child);
4079         if (version == -EOPNOTSUPP)
4080                 version = 0;
4081
4082         /* Get the latest parent's owner. */
4083         rc = dt_attr_get(env, parent, pla);
4084         if (rc != 0)
4085                 GOTO(unlock, rc);
4086
4087         /* Some others chown/chgrp during the LFSCK, needs to do nothing. */
4088         if (unlikely((!version && tla->la_ctime == 0) ||
4089                      tla->la_uid != pla->la_uid || tla->la_gid != pla->la_gid))
4090                 rc = 1;
4091         else
4092                 rc = dt_attr_set(env, child, tla, handle);
4093
4094         GOTO(unlock, rc);
4095
4096 unlock:
4097         dt_read_unlock(env, parent);
4098
4099 stop:
4100         rc = lfsck_layout_trans_stop(env, dev, handle, rc);
4101
4102 log:
4103         if (rc != 0)
4104                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant repaired "
4105                        "inconsistent file owner for: parent "DFID", child "DFID
4106                        ", OST-index %u, stripe-index %u, old owner %u/%u, "
4107                        "new owner %u/%u: rc = %d\n",
4108                        lfsck_lfsck2name(com->lc_lfsck),
4109                        PFID(lfsck_dto2fid(parent)), PFID(lfsck_dto2fid(child)),
4110                        llr->llr_ost_idx, llr->llr_lov_idx,
4111                        cla->la_uid, cla->la_gid, tla->la_uid, tla->la_gid, rc);
4112
4113         return rc;
4114 }
4115
4116 #define CDEBUG_UNMATCHED_PAIR(lfsck, lso, pfid, cfid, msg)               \
4117         CDEBUG(D_LFSCK, "%s:("DFID"|"DFID")/"DFID":XATTR %s: %s\n",      \
4118                lfsck_lfsck2name(lfsck), PFID(&lso->lso_fid), PFID(pfid), \
4119                PFID(cfid), XATTR_NAME_FID, msg);
4120
4121 /* Check whether the OST-object correctly back points to the
4122  * MDT-object (@parent) via the XATTR_NAME_FID xattr (@pfid). */
4123 static int lfsck_layout_check_parent(const struct lu_env *env,
4124                                      struct lfsck_component *com,
4125                                      struct lfsck_assistant_object *lso,
4126                                      struct filter_fid *ff,
4127                                      const struct lu_fid *cfid,
4128                                      const struct lu_attr *cla,
4129                                      struct lfsck_layout_req *llr)
4130 {
4131         struct lfsck_thread_info        *info   = lfsck_env_info(env);
4132         struct lu_buf                   *buf    = &info->lti_big_buf;
4133         struct lu_fid                   *pfid   = &info->lti_fid;
4134         struct dt_object                *tobj;
4135         struct lov_mds_md_v1            *lmm;
4136         struct lov_ost_data_v1          *objs;
4137         struct lustre_handle             lh     = { 0 };
4138         struct lfsck_instance           *lfsck  = com->lc_lfsck;
4139         int                              rc;
4140         int                              i;
4141         __u32                            magic;
4142         __u32                            idx;
4143         __u16                            count;
4144         ENTRY;
4145
4146         *pfid = ff->ff_parent;
4147         idx = pfid->f_stripe_idx;
4148         pfid->f_ver = 0;
4149
4150         if (unlikely(!fid_is_sane(pfid))) {
4151                 CDEBUG_UNMATCHED_PAIR(lfsck, lso, pfid, cfid,
4152                                       "the parent FID is invalid");
4153
4154                 RETURN(LLIT_UNMATCHED_PAIR);
4155         }
4156
4157         if (lu_fid_eq(pfid, &lso->lso_fid)) {
4158                 if (likely(llr->llr_lov_idx == idx))
4159                         RETURN(0);
4160
4161                 CDEBUG_UNMATCHED_PAIR(lfsck, lso, pfid, cfid,
4162                                       "the stripe index is unmatched");
4163
4164                 RETURN(LLIT_UNMATCHED_PAIR);
4165         }
4166
4167         tobj = lfsck_object_find_bottom(env, com->lc_lfsck, pfid);
4168         if (IS_ERR(tobj))
4169                 RETURN(PTR_ERR(tobj));
4170
4171         if (dt_object_exists(tobj) == 0) {
4172                 CDEBUG_UNMATCHED_PAIR(lfsck, lso, pfid, cfid,
4173                                       "the parent is nonexistent");
4174
4175                 GOTO(out, rc = LLIT_UNMATCHED_PAIR);
4176         }
4177
4178         if (lfsck_is_dead_obj(tobj)) {
4179                 CDEBUG_UNMATCHED_PAIR(lfsck, lso, pfid, cfid,
4180                                       "the parent is dead object");
4181
4182                 GOTO(out, rc = LLIT_UNMATCHED_PAIR);
4183         }
4184
4185         if (!S_ISREG(lfsck_object_type(tobj))) {
4186                 CDEBUG_UNMATCHED_PAIR(lfsck, lso, pfid, cfid,
4187                                       "the parent is not a regular file");
4188
4189                 GOTO(out, rc = LLIT_UNMATCHED_PAIR);
4190         }
4191
4192         /* Load the tobj's layout EA, in spite of it is a local MDT-object or
4193          * remote one on another MDT. Then check whether the given OST-object
4194          * is in such layout. If yes, it is multiple referenced, otherwise it
4195          * is unmatched referenced case. */
4196         rc = lfsck_layout_get_lovea(env, tobj, buf);
4197         if (rc == 0 || rc == -ENODATA || rc == -ENOENT) {
4198                 CDEBUG_UNMATCHED_PAIR(lfsck, lso, pfid, cfid,
4199                                       "the parent has no stripe data");
4200
4201                 GOTO(out, rc = LLIT_UNMATCHED_PAIR);
4202         }
4203
4204         if (unlikely(rc == -EOPNOTSUPP))
4205                 GOTO(out, rc = LLIT_NONE);
4206
4207         if (rc < 0)
4208                 GOTO(out, rc);
4209
4210         lmm = buf->lb_buf;
4211         magic = le32_to_cpu(lmm->lmm_magic);
4212         if (magic == LOV_MAGIC_COMP_V1 || magic == LOV_MAGIC_SEL) {
4213                 struct lov_comp_md_v1 *lcm = buf->lb_buf;
4214                 struct lov_comp_md_entry_v1 *lcme;
4215
4216                 if (ff->ff_layout.ol_comp_id == 0) {
4217                         CDEBUG_UNMATCHED_PAIR(lfsck, lso, pfid, cfid,
4218                                               "the parent has incorrect comp_id");
4219
4220                         GOTO(out, rc = LLIT_UNMATCHED_PAIR);
4221                 }
4222
4223                 count = le16_to_cpu(lcm->lcm_entry_count);
4224                 for (i = 0; i < count; i++) {
4225                         lcme = &lcm->lcm_entries[i];
4226                         if (le32_to_cpu(lcme->lcme_id) ==
4227                             ff->ff_layout.ol_comp_id) {
4228                                 lmm = buf->lb_buf +
4229                                         le32_to_cpu(lcme->lcme_offset);
4230                                 magic = le32_to_cpu(lmm->lmm_magic);
4231                                 if (!(le32_to_cpu(lcme->lcme_flags) &
4232                                       LCME_FL_INIT)) {
4233                                         CDEBUG_UNMATCHED_PAIR(lfsck, lso, pfid,
4234                                                               cfid,
4235                                                               "the parent has uninitialized component");
4236
4237                                         GOTO(out, rc = LLIT_UNMATCHED_PAIR);
4238                                 }
4239
4240                                 goto further;
4241                         }
4242                 }
4243
4244                 CDEBUG_UNMATCHED_PAIR(lfsck, lso, pfid, cfid,
4245                                       "the parent has no matched comp_id");
4246
4247                 GOTO(out, rc = LLIT_UNMATCHED_PAIR);
4248         }
4249
4250 further:
4251         if (magic == LOV_MAGIC_V1) {
4252                 objs = &lmm->lmm_objects[0];
4253         } else {
4254                 LASSERT(magic == LOV_MAGIC_V3);
4255                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[0];
4256         }
4257
4258         count = le16_to_cpu(lmm->lmm_stripe_count);
4259         for (i = 0; i < count; i++, objs++) {
4260                 struct lu_fid           *tfid   = &info->lti_fid2;
4261                 struct ost_id           *oi     = &info->lti_oi;
4262                 __u32                    idx2;
4263
4264                 if (lovea_slot_is_dummy(objs))
4265                         continue;
4266
4267                 ostid_le_to_cpu(&objs->l_ost_oi, oi);
4268                 idx2 = le32_to_cpu(objs->l_ost_idx);
4269                 rc = ostid_to_fid(tfid, oi, idx2);
4270                 if (rc != 0) {
4271                         CDEBUG(D_LFSCK, "%s: the parent "DFID" contains "
4272                                "invalid layout EA at the slot %d, index %u\n",
4273                                lfsck_lfsck2name(com->lc_lfsck),
4274                                PFID(pfid), i, idx2);
4275
4276                         GOTO(out, rc = LLIT_UNMATCHED_PAIR);
4277                 }
4278
4279                 if (lu_fid_eq(cfid, tfid)) {
4280                         rc = lfsck_ibits_lock(env, com->lc_lfsck, tobj, &lh,
4281                                               MDS_INODELOCK_UPDATE |
4282                                               MDS_INODELOCK_LAYOUT |
4283                                               MDS_INODELOCK_XATTR,
4284                                               LCK_EX);
4285                         if (rc != 0)
4286                                 GOTO(out, rc);
4287
4288                         dt_read_lock(env, tobj, 0);
4289
4290                         /* For local MDT-object, re-check existence
4291                          * after taken the lock. */
4292                         if (!dt_object_remote(tobj)) {
4293                                 if (dt_object_exists(tobj) == 0 ||
4294                                     lfsck_is_dead_obj(tobj)) {
4295                                         CDEBUG_UNMATCHED_PAIR(lfsck, lso, pfid,
4296                                                               cfid,
4297                                                               "the parent doesn't exist anymore after lock");
4298
4299                                         rc = LLIT_UNMATCHED_PAIR;
4300                                 } else {
4301                                         rc = LLIT_MULTIPLE_REFERENCED;
4302                                 }
4303
4304                                 GOTO(unlock, rc);
4305                         }
4306
4307                         /* For migration case, the new MDT-object and old
4308                          * MDT-object may reference the same OST-object at
4309                          * some migration internal time.
4310                          *
4311                          * For remote MDT-object, the local MDT may not know
4312                          * whether it has been removed or not.  Try checking
4313                          * for a non-existent xattr to check if this object
4314                          * has been been removed or not. */
4315                         rc = dt_xattr_get(env, tobj, &LU_BUF_NULL,
4316                                           XATTR_NAME_DUMMY);
4317                         if (unlikely(rc == -ENOENT || rc >= 0)) {
4318                                 CDEBUG_UNMATCHED_PAIR(lfsck, lso, pfid, cfid,
4319                                                       "the parent is remote object and nonexistent after lock");
4320
4321                                 rc = LLIT_UNMATCHED_PAIR;
4322                         } else if (rc == -ENODATA) {
4323                                 rc = LLIT_MULTIPLE_REFERENCED;
4324                         }
4325
4326                         GOTO(unlock, rc);
4327                 }
4328         }
4329
4330         CDEBUG_UNMATCHED_PAIR(lfsck, lso, pfid, cfid,
4331                               "the parent has no matched stripe");
4332
4333         GOTO(out, rc = LLIT_UNMATCHED_PAIR);
4334
4335 unlock:
4336         if (lustre_handle_is_used(&lh)) {
4337                 dt_read_unlock(env, tobj);
4338                 lfsck_ibits_unlock(&lh, LCK_EX);
4339         }
4340
4341 out:
4342         lfsck_object_put(env, tobj);
4343
4344         return rc;
4345 }
4346
4347 /*
4348  * If the MDT-object has the LUSTRE_ENCRYPT_FL flag, it needs to be set
4349  * on the OST-object as well.
4350  */
4351 static int lfsck_layout_repair_encflag(const struct lu_env *env,
4352                                        struct lfsck_component *com,
4353                                        struct dt_object *parent,
4354                                        struct lfsck_layout_req *llr)
4355 {
4356         struct lfsck_thread_info *info = lfsck_env_info(env);
4357         struct lu_attr *tla = &info->lti_la2;
4358         struct dt_object *child = llr->llr_child;
4359         struct dt_device *dev = lfsck_obj2dev(child);
4360         struct thandle *handle;
4361         int rc;
4362
4363         ENTRY;
4364
4365         tla->la_valid = LA_FLAGS;
4366         tla->la_flags = LUSTRE_ENCRYPT_FL;
4367         handle = lfsck_trans_create(env, dev, com->lc_lfsck);
4368         if (IS_ERR(handle))
4369                 GOTO(log, rc = PTR_ERR(handle));
4370
4371         rc = dt_declare_attr_set(env, child, tla, handle);
4372         if (rc != 0)
4373                 GOTO(stop, rc);
4374
4375         rc = dt_trans_start_local(env, dev, handle);
4376         if (rc != 0)
4377                 GOTO(stop, rc);
4378
4379         /* Use the dt_object lock to serialize with destroy and attr_set. */
4380         dt_read_lock(env, parent, 0);
4381         if (unlikely(lfsck_is_dead_obj(parent)))
4382                 GOTO(unlock, rc = 1);
4383
4384         rc = dt_attr_set(env, child, tla, handle);
4385         GOTO(unlock, rc);
4386
4387 unlock:
4388         dt_read_unlock(env, parent);
4389
4390 stop:
4391         rc = lfsck_layout_trans_stop(env, dev, handle, rc);
4392
4393 log:
4394         if (rc != 0)
4395                 CDEBUG(D_LFSCK,
4396                        "%s: layout LFSCK assistant repair of inconsistent file enc flag for: parent "
4397                        DFID", child "
4398                        DFID", OST-index %u, stripe-index %u: rc = %d\n",
4399                        lfsck_lfsck2name(com->lc_lfsck),
4400                        PFID(lfsck_dto2fid(parent)), PFID(lfsck_dto2fid(child)),
4401                        llr->llr_ost_idx, llr->llr_lov_idx, rc);
4402
4403         return rc;
4404 }
4405
4406 static int lfsck_layout_assistant_handler_p1(const struct lu_env *env,
4407                                              struct lfsck_component *com,
4408                                              struct lfsck_assistant_req *lar)
4409 {
4410         struct lfsck_layout_req              *llr    =
4411                 container_of(lar, struct lfsck_layout_req, llr_lar);
4412         struct lfsck_assistant_object        *lso    = lar->lar_parent;
4413         struct lfsck_layout                  *lo     = com->lc_file_ram;
4414         struct lfsck_thread_info             *info   = lfsck_env_info(env);
4415         struct filter_fid                    *ff     = &info->lti_ff;
4416         struct lu_buf buf = { .lb_buf = ff,
4417                               .lb_len = sizeof(*ff) };
4418         struct dt_object                     *parent = NULL;
4419         struct dt_object                     *child  = llr->llr_child;
4420         struct lu_attr                       *pla    = &lso->lso_attr;
4421         struct lu_attr                       *cla    = &info->lti_la;
4422         struct lfsck_instance                *lfsck  = com->lc_lfsck;
4423         struct lfsck_bookmark                *bk     = &lfsck->li_bookmark_ram;
4424         enum lfsck_layout_inconsistency_type  type   = LLIT_NONE;
4425         int                                   rc;
4426         ENTRY;
4427
4428         if (lso->lso_dead)
4429                 RETURN(0);
4430
4431         CFS_FAIL_TIMEOUT(OBD_FAIL_LFSCK_ENGINE_DELAY, cfs_fail_val);
4432
4433         rc = dt_attr_get(env, child, cla);
4434         if (rc == -ENOENT) {
4435                 parent = lfsck_assistant_object_load(env, lfsck, lso);
4436                 if (IS_ERR(parent)) {
4437                         rc = PTR_ERR(parent);
4438
4439                         RETURN(rc == -ENOENT ? 0 : rc);
4440                 }
4441
4442                 type = LLIT_DANGLING;
4443                 goto repair;
4444         }
4445
4446         if (rc != 0)
4447                 GOTO(out, rc);
4448
4449         if (!(bk->lb_param & LPF_DRYRUN) &&
4450             pla->la_valid & LA_FLAGS && pla->la_flags & LUSTRE_ENCRYPT_FL) {
4451                 /* MDT-inode is encrypted */
4452                 struct lu_buf lb = { .lb_buf = NULL, .lb_len = 0 };
4453
4454                 /* if OST-inode is missing encryption.c xattr, fix it */
4455                 if (dt_xattr_get(env, child, &lb,
4456                                  LL_XATTR_NAME_ENCRYPTION_CONTEXT) >= 0)
4457                         goto check_fid;
4458
4459                 if (parent == NULL)
4460                         parent = lfsck_assistant_object_load(env, lfsck, lso);
4461                 if (!IS_ERR_OR_NULL(parent))
4462                         rc = lfsck_layout_repair_encflag(env, com, parent, llr);
4463                 down_write(&com->lc_sem);
4464                 if (rc < 0)
4465                         lfsck_layout_record_failure(env, lfsck, lo);
4466                 else if (rc > 0)
4467                         lo->ll_objs_repaired[LLIT_OTHERS - 1]++;
4468                 up_write(&com->lc_sem);
4469         }
4470
4471 check_fid:
4472         lfsck_buf_init(&buf, ff, sizeof(*ff));
4473         rc = dt_xattr_get(env, child, &buf, XATTR_NAME_FID);
4474         if (unlikely(rc > 0 && rc < sizeof(struct lu_fid))) {
4475                 CDEBUG(D_LFSCK, "%s:"DFID"/"DFID": "
4476                        "the child object's %s is corrupted\n",
4477                        lfsck_lfsck2name(lfsck), PFID(&lso->lso_fid),
4478                        PFID(lu_object_fid(&child->do_lu)),
4479                        XATTR_NAME_FID);
4480
4481                 type = LLIT_UNMATCHED_PAIR;
4482                 goto repair;
4483         }
4484
4485         if (rc < 0 && rc != -ENODATA)
4486                 GOTO(out, rc);
4487
4488         if (rc == 0 || rc == -ENODATA)
4489                 GOTO(check_owner, rc = 0);
4490
4491         filter_fid_le_to_cpu(ff, ff, sizeof(*ff));
4492         rc = lfsck_layout_check_parent(env, com, lso, ff,
4493                                        lu_object_fid(&child->do_lu), cla, llr);
4494         if (rc > 0) {
4495                 type = rc;
4496                 goto repair;
4497         }
4498
4499         if (rc < 0)
4500                 GOTO(out, rc);
4501
4502 check_owner:
4503         /* Someone may has changed the owner after the parent attr pre-loaded.
4504          * It can be handled later inside the lfsck_layout_repair_owner(). */
4505         if (unlikely(cla->la_uid != pla->la_uid ||
4506                      cla->la_gid != pla->la_gid)) {
4507                 type = LLIT_INCONSISTENT_OWNER;
4508                 goto repair;
4509         }
4510
4511 repair:
4512         if (type == LLIT_NONE)
4513                 GOTO(out, rc = 0);
4514
4515         if (bk->lb_param & LPF_DRYRUN)
4516                 GOTO(out, rc = 1);
4517
4518         if (parent == NULL) {
4519                 parent = lfsck_assistant_object_load(env, lfsck, lso);
4520                 if (IS_ERR(parent)) {
4521                         rc = PTR_ERR(parent);
4522
4523                         if (rc == -ENOENT)
4524                                 RETURN(0);
4525
4526                         GOTO(out, rc);
4527                 }
4528         }
4529
4530         switch (type) {
4531         case LLIT_DANGLING:
4532                 if (bk->lb_param & LPF_DELAY_CREATE_OSTOBJ)
4533                         rc = lfsck_layout_ins_dangling_rec(env, com,
4534                                 lfsck_dto2fid(parent), lfsck_dto2fid(child),
4535                                 llr->llr_comp_id, llr->llr_lov_idx,
4536                                 llr->llr_ost_idx);
4537                 else
4538                         rc = __lfsck_layout_repair_dangling(env, com, parent,
4539                                                             llr->llr_child,
4540                                                             llr->llr_comp_id,
4541                                                             llr->llr_lov_idx,
4542                                                             llr->llr_ost_idx,
4543                                                             true);
4544                 break;
4545         case LLIT_UNMATCHED_PAIR:
4546                 rc = lfsck_layout_repair_unmatched_pair(env, com, parent,
4547                                                         llr, pla);
4548                 break;
4549         case LLIT_MULTIPLE_REFERENCED:
4550                 rc = lfsck_layout_repair_multiple_references(env, com, parent,
4551                                                              llr, pla);
4552                 break;
4553         case LLIT_INCONSISTENT_OWNER:
4554                 rc = lfsck_layout_repair_owner(env, com, parent, llr, pla, cla);
4555                 break;
4556         default:
4557                 rc = 0;
4558                 break;
4559         }
4560
4561         GOTO(out, rc);
4562
4563 out:
4564         down_write(&com->lc_sem);
4565         if (rc < 0) {
4566                 struct lfsck_assistant_data *lad = com->lc_data;
4567
4568                 if (unlikely(test_bit(LAD_EXIT, &lad->lad_flags))) {
4569                         rc = 0;
4570                 } else if (rc == -ENOTCONN || rc == -ESHUTDOWN ||
4571                            rc == -ETIMEDOUT || rc == -EHOSTDOWN ||
4572                            rc == -EHOSTUNREACH) {
4573                         /* If cannot touch the target server,
4574                          * mark the LFSCK as INCOMPLETE. */
4575                         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant fail to "
4576                                "talk with OST %x: rc = %d\n",
4577                                lfsck_lfsck2name(lfsck), llr->llr_ost_idx, rc);
4578                         lfsck_lad_set_bitmap(env, com, llr->llr_ost_idx);
4579                         lo->ll_objs_skipped++;
4580                         rc = 0;
4581                 } else {
4582                         lfsck_layout_record_failure(env, lfsck, lo);
4583                 }
4584         } else if (rc > 0 && (type != LLIT_DANGLING ||
4585                               !(bk->lb_param & LPF_DELAY_CREATE_OSTOBJ))) {
4586                 LASSERTF(type > LLIT_NONE && type <= LLIT_MAX,
4587                          "unknown type = %d\n", type);
4588
4589                 lo->ll_objs_repaired[type - 1]++;
4590                 if (bk->lb_param & LPF_DRYRUN &&
4591                     unlikely(lo->ll_pos_first_inconsistent == 0))
4592                         lo->ll_pos_first_inconsistent =
4593                         lfsck->li_obj_oit->do_index_ops->dio_it.store(env,
4594                                                         lfsck->li_di_oit);
4595         }
4596         up_write(&com->lc_sem);
4597
4598         if (parent != NULL && !IS_ERR(parent))
4599                 lfsck_object_put(env, parent);
4600
4601         return rc;
4602 }
4603
4604 static int
4605 lfsck_layout_double_scan_one_trace_file(const struct lu_env *env,
4606                                         struct lfsck_component *com,
4607                                         struct dt_object *obj, bool first)
4608 {
4609         struct lfsck_instance *lfsck = com->lc_lfsck;
4610         struct ptlrpc_thread *thread = &lfsck->li_thread;
4611         struct lfsck_bookmark *bk = &lfsck->li_bookmark_ram;
4612         struct lfsck_layout *lo = com->lc_file_ram;
4613         const struct dt_it_ops *iops = &obj->do_index_ops->dio_it;
4614         struct dt_it *di;
4615         struct dt_key *key;
4616         struct lfsck_layout_dangling_key *parent =
4617                                         &lfsck_env_info(env)->lti_lldk;
4618         struct lu_fid *cfid = &lfsck_env_info(env)->lti_fid3;
4619         __u32 ost_idx;
4620         int rc;
4621         ENTRY;
4622
4623         di = iops->init(env, obj, 0);
4624         if (IS_ERR(di))
4625                 RETURN(PTR_ERR(di));
4626
4627         if (first)
4628                 lldk_cpu_to_be(parent, &lo->ll_lldk_latest_scanned_phase2);
4629         else
4630                 memset(parent, 0, sizeof(*parent));
4631         rc = iops->get(env, di, (const struct dt_key *)parent);
4632         if (rc < 0)
4633                 GOTO(fini, rc);
4634
4635         if (first) {
4636                 /* The start one either has been processed or does not exist,
4637                  * skip it. */
4638                 rc = iops->next(env, di);
4639                 if (rc != 0)
4640                         GOTO(put, rc);
4641         }
4642
4643         do {
4644                 if (CFS_FAIL_TIMEOUT(OBD_FAIL_LFSCK_DELAY3, cfs_fail_val) &&
4645                     unlikely(!thread_is_running(thread)))
4646                         GOTO(put, rc = 0);
4647
4648                 key = iops->key(env, di);
4649                 if (IS_ERR(key)) {
4650                         rc = PTR_ERR(key);
4651                         if (rc == -ENOENT)
4652                                 GOTO(put, rc = 1);
4653
4654                         goto checkpoint;
4655                 }
4656
4657                 lldk_be_to_cpu(parent,
4658                                 (const struct lfsck_layout_dangling_key *)key);
4659                 if (!fid_is_sane(&parent->lldk_fid)) {
4660                         rc = 0;
4661                         goto checkpoint;
4662                 }
4663
4664                 rc = iops->rec(env, di, (struct dt_rec *)cfid, 0);
4665                 if (rc == 0) {
4666                         fid_be_to_cpu(cfid, cfid);
4667                         ost_idx = cfid->f_ver;
4668                         cfid->f_ver = 0;
4669                         if (!fid_is_sane(cfid)) {
4670                                 rc = 0;
4671                                 goto checkpoint;
4672                         }
4673
4674                         rc = lfsck_layout_repair_dangling(env, com,
4675                                         &parent->lldk_fid, cfid,
4676                                         parent->lldk_comp_id,
4677                                         parent->lldk_ea_off, ost_idx);
4678                 }
4679
4680 checkpoint:
4681                 down_write(&com->lc_sem);
4682                 com->lc_new_checked++;
4683                 com->lc_new_scanned++;
4684                 if (rc >= 0)
4685                         lo->ll_lldk_latest_scanned_phase2 = *parent;
4686
4687                 if (rc > 0)
4688                         lo->ll_objs_repaired[LLIT_DANGLING - 1]++;
4689                 else if (rc < 0)
4690                         lo->ll_objs_failed_phase2++;
4691                 up_write(&com->lc_sem);
4692
4693                 if (rc < 0 && bk->lb_param & LPF_FAILOUT)
4694                         GOTO(put, rc);
4695
4696                 if (unlikely(com->lc_time_next_checkpoint <=
4697                              ktime_get_seconds()) &&
4698                     com->lc_new_checked != 0) {
4699                         down_write(&com->lc_sem);
4700                         lo->ll_run_time_phase2 += ktime_get_seconds() -
4701                                                   com->lc_time_last_checkpoint;
4702                         lo->ll_time_last_checkpoint = ktime_get_real_seconds();
4703                         lo->ll_objs_checked_phase2 += com->lc_new_checked;
4704                         com->lc_new_checked = 0;
4705                         lfsck_layout_store(env, com);
4706                         up_write(&com->lc_sem);
4707
4708                         com->lc_time_last_checkpoint = ktime_get_seconds();
4709                         com->lc_time_next_checkpoint =
4710                                 com->lc_time_last_checkpoint +
4711                                 LFSCK_CHECKPOINT_INTERVAL;
4712                 }
4713
4714                 lfsck_control_speed_by_self(com);
4715                 if (unlikely(!thread_is_running(thread)))
4716                         GOTO(put, rc = 0);
4717
4718                 rc = iops->next(env, di);
4719         } while (rc == 0);
4720
4721         GOTO(put, rc);
4722
4723 put:
4724         iops->put(env, di);
4725
4726 fini:
4727         iops->fini(env, di);
4728
4729         return rc;
4730 }
4731
4732 static int lfsck_layout_assistant_handler_p2(const struct lu_env *env,
4733                                              struct lfsck_component *com)
4734 {
4735         struct lfsck_assistant_data     *lad    = com->lc_data;
4736         struct lfsck_instance           *lfsck  = com->lc_lfsck;
4737         struct lfsck_bookmark           *bk     = &lfsck->li_bookmark_ram;
4738         struct lfsck_tgt_descs          *ltds   = &lfsck->li_ost_descs;
4739         struct lfsck_tgt_desc           *ltd;
4740         int                              rc     = 0;
4741         ENTRY;
4742
4743         CDEBUG(D_LFSCK, "%s: layout LFSCK phase2 scan start\n",
4744                lfsck_lfsck2name(lfsck));
4745
4746         spin_lock(&ltds->ltd_lock);
4747         while (!list_empty(&lad->lad_ost_phase2_list)) {
4748                 ltd = list_entry(lad->lad_ost_phase2_list.next,
4749                                  struct lfsck_tgt_desc,
4750                                  ltd_layout_phase_list);
4751                 list_del_init(&ltd->ltd_layout_phase_list);
4752                 if (bk->lb_param & LPF_OST_ORPHAN) {
4753                         spin_unlock(&ltds->ltd_lock);
4754                         rc = lfsck_layout_scan_orphan(env, com, ltd);
4755                         if (rc != 0 && bk->lb_param & LPF_FAILOUT)
4756                                 RETURN(rc);
4757
4758                         if (unlikely(test_bit(LAD_EXIT, &lad->lad_flags) ||
4759                                      !thread_is_running(&lfsck->li_thread)))
4760                                 RETURN(0);
4761                         spin_lock(&ltds->ltd_lock);
4762                 }
4763         }
4764
4765         if (list_empty(&lad->lad_ost_phase1_list))
4766                 rc = 1;
4767         else
4768                 rc = 0;
4769         spin_unlock(&ltds->ltd_lock);
4770
4771         if (rc == 1 && bk->lb_param & LPF_OST_ORPHAN) {
4772                 struct lfsck_layout *lo = com->lc_file_ram;
4773                 int i;
4774
4775                 com->lc_new_checked = 0;
4776                 com->lc_new_scanned = 0;
4777                 com->lc_time_last_checkpoint = ktime_get_seconds();
4778                 com->lc_time_next_checkpoint = com->lc_time_last_checkpoint +
4779                                                LFSCK_CHECKPOINT_INTERVAL;
4780
4781                 i = lfsck_sub_trace_file_fid2idx(
4782                                 &lo->ll_lldk_latest_scanned_phase2.lldk_fid);
4783                 rc = lfsck_layout_double_scan_one_trace_file(env, com,
4784                                 com->lc_sub_trace_objs[i].lsto_obj, true);
4785                 while (rc > 0 && ++i < LFSCK_STF_COUNT)
4786                         rc = lfsck_layout_double_scan_one_trace_file(env, com,
4787                                 com->lc_sub_trace_objs[i].lsto_obj, false);
4788
4789                 CDEBUG(D_LFSCK, "%s: layout LFSCK phase2 scan dangling stop "
4790                        "at the No. %d trace file: rc = %d\n",
4791                        lfsck_lfsck2name(lfsck), i, rc);
4792         }
4793
4794         CDEBUG(D_LFSCK, "%s: layout LFSCK phase2 scan stop: rc = %d\n",
4795                lfsck_lfsck2name(lfsck), rc);
4796
4797         RETURN(rc);
4798 }
4799
4800 static int
4801 lfsck_layout_slave_async_interpret(const struct lu_env *env,
4802                                    struct ptlrpc_request *req,
4803                                    void *args, int rc)
4804 {
4805         struct lfsck_layout_slave_async_args *llsaa = args;
4806         struct obd_export *exp = llsaa->llsaa_exp;
4807         struct lfsck_component *com = llsaa->llsaa_com;
4808         struct lfsck_layout_slave_target *llst = llsaa->llsaa_llst;
4809         struct lfsck_layout_slave_data *llsd = com->lc_data;
4810         struct lfsck_reply *lr = NULL;
4811         bool done = false;
4812
4813         if (rc != 0) {
4814                 /* It is probably caused by network trouble, or target crash,
4815                  * it will try several times (depends on the obd_timeout, and
4816                  * will not less than 3 times). But to make the LFSCK can go
4817                  * ahead, we should not try for ever. After some try but still
4818                  * hit failure, it will assume that the target exit the LFSCK
4819                  * prcoessing and stop try. */
4820                 if (rc == -ENOTCONN || rc == -ESHUTDOWN) {
4821                         int max_try = max_t(int, obd_timeout / 30, 3);
4822
4823                         if (++(llst->llst_failures) > max_try)
4824                                 done = true;
4825                 } else {
4826                         done = true;
4827                 }
4828         } else {
4829                 llst->llst_failures = 0;
4830                 lr = req_capsule_server_get(&req->rq_pill, &RMF_LFSCK_REPLY);
4831                 if (lr->lr_status != LS_SCANNING_PHASE1 &&
4832                     lr->lr_status != LS_SCANNING_PHASE2)
4833                         done = true;
4834         }
4835
4836         if (done) {
4837                 CDEBUG(D_LFSCK, "%s: layout LFSCK slave gets the MDT %x "
4838                        "status %d, failures_try %d\n", lfsck_lfsck2name(com->lc_lfsck),
4839                        llst->llst_index, lr != NULL ? lr->lr_status : rc,
4840                        llst->llst_failures);
4841
4842                 lfsck_layout_llst_del(llsd, llst);
4843         }
4844
4845         lfsck_layout_llst_put(llst);
4846         lfsck_component_put(env, com);
4847         class_export_put(exp);
4848
4849         return 0;
4850 }
4851
4852 static int lfsck_layout_async_query(const struct lu_env *env,
4853                                     struct lfsck_component *com,
4854                                     struct obd_export *exp,
4855                                     struct lfsck_layout_slave_target *llst,
4856                                     struct lfsck_request *lr,
4857                                     struct ptlrpc_request_set *set)
4858 {
4859         struct lfsck_layout_slave_async_args *llsaa;
4860         struct ptlrpc_request                *req;
4861         struct lfsck_request                 *tmp;
4862         int                                   rc;
4863         ENTRY;
4864
4865         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_LFSCK_QUERY);
4866         if (req == NULL)
4867                 RETURN(-ENOMEM);
4868
4869         rc = ptlrpc_request_pack(req, LUSTRE_OBD_VERSION, LFSCK_QUERY);
4870         if (rc != 0) {
4871                 ptlrpc_request_free(req);
4872                 RETURN(rc);
4873         }
4874
4875         tmp = req_capsule_client_get(&req->rq_pill, &RMF_LFSCK_REQUEST);
4876         *tmp = *lr;
4877         ptlrpc_request_set_replen(req);
4878
4879         llsaa = ptlrpc_req_async_args(llsaa, req);
4880         llsaa->llsaa_exp = exp;
4881         llsaa->llsaa_com = lfsck_component_get(com);
4882         llsaa->llsaa_llst = llst;
4883         req->rq_interpret_reply = lfsck_layout_slave_async_interpret;
4884         req->rq_allow_intr = 1;
4885         req->rq_no_delay = 1;
4886         ptlrpc_set_add_req(set, req);
4887
4888         RETURN(0);
4889 }
4890
4891 static int lfsck_layout_async_notify(const struct lu_env *env,
4892                                      struct obd_export *exp,
4893                                      struct lfsck_request *lr,
4894                                      struct ptlrpc_request_set *set)
4895 {
4896         struct ptlrpc_request   *req;
4897         struct lfsck_request    *tmp;
4898         int                      rc;
4899         ENTRY;
4900
4901         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_LFSCK_NOTIFY);
4902         if (req == NULL)
4903                 RETURN(-ENOMEM);
4904
4905         rc = ptlrpc_request_pack(req, LUSTRE_OBD_VERSION, LFSCK_NOTIFY);
4906         if (rc != 0) {
4907                 ptlrpc_request_free(req);
4908                 RETURN(rc);
4909         }
4910
4911         tmp = req_capsule_client_get(&req->rq_pill, &RMF_LFSCK_REQUEST);
4912         *tmp = *lr;
4913         ptlrpc_request_set_replen(req);
4914         req->rq_allow_intr = 1;
4915         req->rq_no_delay = 1;
4916         ptlrpc_set_add_req(set, req);
4917
4918         RETURN(0);
4919 }
4920
4921 static int
4922 lfsck_layout_slave_query_master(const struct lu_env *env,
4923                                 struct lfsck_component *com)
4924 {
4925         struct lfsck_request             *lr    = &lfsck_env_info(env)->lti_lr;
4926         struct lfsck_instance            *lfsck = com->lc_lfsck;
4927         struct lfsck_layout_slave_data   *llsd  = com->lc_data;
4928         struct lfsck_layout_slave_target *llst;
4929         struct obd_export                *exp;
4930         struct ptlrpc_request_set        *set;
4931         int                               rc    = 0;
4932         int                               rc1   = 0;
4933         ENTRY;
4934
4935         set = ptlrpc_prep_set();
4936         if (set == NULL)
4937                 GOTO(log, rc = -ENOMEM);
4938
4939         memset(lr, 0, sizeof(*lr));
4940         lr->lr_event = LE_QUERY;
4941         lr->lr_active = LFSCK_TYPE_LAYOUT;
4942
4943         llsd->llsd_touch_gen++;
4944         spin_lock(&llsd->llsd_lock);
4945         while (!list_empty(&llsd->llsd_master_list)) {
4946                 llst = list_entry(llsd->llsd_master_list.next,
4947                                   struct lfsck_layout_slave_target,
4948                                   llst_list);
4949                 if (llst->llst_gen == llsd->llsd_touch_gen)
4950                         break;
4951
4952                 llst->llst_gen = llsd->llsd_touch_gen;
4953                 list_move_tail(&llst->llst_list,
4954                                &llsd->llsd_master_list);
4955                 atomic_inc(&llst->llst_ref);
4956                 spin_unlock(&llsd->llsd_lock);
4957
4958                 exp = lustre_find_lwp_by_index(lfsck->li_obd->obd_name,
4959                                                llst->llst_index);
4960                 if (exp == NULL) {
4961                         lfsck_layout_llst_del(llsd, llst);
4962                         lfsck_layout_llst_put(llst);
4963                         spin_lock(&llsd->llsd_lock);
4964                         continue;
4965                 }
4966
4967                 rc = lfsck_layout_async_query(env, com, exp, llst, lr, set);
4968                 if (rc != 0) {
4969                         CDEBUG(D_LFSCK, "%s: layout LFSCK slave fail to "
4970                                "query %s for layout: rc = %d\n",
4971                                lfsck_lfsck2name(lfsck),
4972                                exp->exp_obd->obd_name, rc);
4973
4974                         rc1 = rc;
4975                         lfsck_layout_llst_put(llst);
4976                         class_export_put(exp);
4977                 }
4978                 spin_lock(&llsd->llsd_lock);
4979         }
4980         spin_unlock(&llsd->llsd_lock);
4981
4982         rc = ptlrpc_set_wait(env, set);
4983         ptlrpc_set_destroy(set);
4984
4985         GOTO(log, rc = (rc1 != 0 ? rc1 : rc));
4986
4987 log:
4988         CDEBUG(D_LFSCK, "%s: layout LFSCK slave queries master: rc = %d\n",
4989                lfsck_lfsck2name(com->lc_lfsck), rc);
4990
4991         return rc;
4992 }
4993
4994 static void
4995 lfsck_layout_slave_notify_master(const struct lu_env *env,
4996                                  struct lfsck_component *com,
4997                                  enum lfsck_events event, int result)
4998 {
4999         struct lfsck_layout              *lo    = com->lc_file_ram;
5000         struct lfsck_instance            *lfsck = com->lc_lfsck;
5001         struct lfsck_layout_slave_data   *llsd  = com->lc_data;
5002         struct lfsck_request             *lr    = &lfsck_env_info(env)->lti_lr;
5003         struct lfsck_layout_slave_target *llst;
5004         struct obd_export                *exp;
5005         struct ptlrpc_request_set        *set;
5006         int                               rc;
5007         ENTRY;
5008
5009         CDEBUG(D_LFSCK, "%s: layout LFSCK slave notifies master\n",
5010                lfsck_lfsck2name(com->lc_lfsck));
5011
5012         set = ptlrpc_prep_set();
5013         if (set == NULL)
5014                 RETURN_EXIT;
5015
5016         memset(lr, 0, sizeof(*lr));
5017         lr->lr_event = event;
5018         lr->lr_flags = LEF_FROM_OST;
5019         lr->lr_status = result;
5020         lr->lr_index = lfsck_dev_idx(lfsck);
5021         lr->lr_active = LFSCK_TYPE_LAYOUT;
5022         lr->lr_flags2 = lo->ll_flags;
5023         llsd->llsd_touch_gen++;
5024         spin_lock(&llsd->llsd_lock);
5025         while (!list_empty(&llsd->llsd_master_list)) {
5026                 llst = list_entry(llsd->llsd_master_list.next,
5027                                   struct lfsck_layout_slave_target,
5028                                   llst_list);
5029                 if (llst->llst_gen == llsd->llsd_touch_gen)
5030                         break;
5031
5032                 llst->llst_gen = llsd->llsd_touch_gen;
5033                 list_move_tail(&llst->llst_list,
5034                                &llsd->llsd_master_list);
5035                 atomic_inc(&llst->llst_ref);
5036                 spin_unlock(&llsd->llsd_lock);
5037
5038                 exp = lustre_find_lwp_by_index(lfsck->li_obd->obd_name,
5039                                                llst->llst_index);
5040                 if (exp == NULL) {
5041                         lfsck_layout_llst_del(llsd, llst);
5042                         lfsck_layout_llst_put(llst);
5043                         spin_lock(&llsd->llsd_lock);
5044                         continue;
5045                 }
5046
5047                 rc = lfsck_layout_async_notify(env, exp, lr, set);
5048                 if (rc != 0)
5049                         CDEBUG(D_LFSCK, "%s: layout LFSCK slave fail to "
5050                                "notify %s for layout: rc = %d\n",
5051                                lfsck_lfsck2name(lfsck),
5052                                exp->exp_obd->obd_name, rc);
5053
5054                 lfsck_layout_llst_put(llst);
5055                 class_export_put(exp);
5056                 spin_lock(&llsd->llsd_lock);
5057         }
5058         spin_unlock(&llsd->llsd_lock);
5059
5060         ptlrpc_set_wait(env, set);
5061         ptlrpc_set_destroy(set);
5062
5063         RETURN_EXIT;
5064 }
5065
5066 /*
5067  * \ret -ENODATA: unrecognized stripe
5068  * \ret = 0     : recognized stripe
5069  * \ret < 0     : other failures
5070  */
5071 static int lfsck_layout_master_check_pairs(const struct lu_env *env,
5072                                            struct lfsck_component *com,
5073                                            struct lu_fid *cfid,
5074                                            struct lu_fid *pfid, __u32 comp_id)
5075 {
5076         struct lfsck_thread_info        *info   = lfsck_env_info(env);
5077         struct lu_buf                   *buf    = &info->lti_big_buf;
5078         struct ost_id                   *oi     = &info->lti_oi;
5079         struct dt_object                *obj;
5080         struct lov_mds_md_v1            *lmm;
5081         struct lov_ost_data_v1          *objs;
5082         __u32                            idx    = pfid->f_stripe_idx;
5083         __u32                            magic;
5084         int                              rc     = 0;
5085         int                              i;
5086         __u16                            count;
5087         ENTRY;
5088
5089         pfid->f_ver = 0;
5090         obj = lfsck_object_find_bottom(env, com->lc_lfsck, pfid);
5091         if (IS_ERR(obj))
5092                 RETURN(PTR_ERR(obj));
5093
5094         dt_read_lock(env, obj, 0);
5095         if (unlikely(dt_object_exists(obj) == 0 ||
5096                      lfsck_is_dead_obj(obj)))
5097                 GOTO(unlock, rc = -ENOENT);
5098
5099         if (!S_ISREG(lfsck_object_type(obj)))
5100                 GOTO(unlock, rc = -ENODATA);
5101
5102         rc = lfsck_layout_get_lovea(env, obj, buf);
5103         if (rc < 0)
5104                 GOTO(unlock, rc);
5105
5106         lmm = buf->lb_buf;
5107         magic = le32_to_cpu(lmm->lmm_magic);
5108         if (magic == LOV_MAGIC_COMP_V1 || magic == LOV_MAGIC_SEL) {
5109                 struct lov_comp_md_v1 *lcm = buf->lb_buf;
5110                 struct lov_comp_md_entry_v1 *lcme;
5111
5112                 if (comp_id == 0)
5113                         GOTO(unlock, rc = -ENODATA);
5114
5115                 count = le16_to_cpu(lcm->lcm_entry_count);
5116                 for (i = 0; i < count; i++) {
5117                         lcme = &lcm->lcm_entries[i];
5118                         if (le32_to_cpu(lcme->lcme_id) == comp_id) {
5119                                 lmm = buf->lb_buf +
5120                                         le32_to_cpu(lcme->lcme_offset);
5121                                 magic = le32_to_cpu(lmm->lmm_magic);
5122                                 if (!(le32_to_cpu(lcme->lcme_flags) &
5123                                       LCME_FL_INIT))
5124                                         GOTO(unlock, rc = -ENODATA);
5125
5126                                 goto further;
5127                         }
5128                 }
5129
5130                 GOTO(unlock, rc = -ENODATA);
5131         }
5132
5133 further:
5134         if (magic == LOV_MAGIC_V1) {
5135                 objs = &lmm->lmm_objects[0];
5136         } else {
5137                 LASSERT(magic == LOV_MAGIC_V3);
5138                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[0];
5139         }
5140
5141         fid_to_ostid(cfid, oi);
5142         count = le16_to_cpu(lmm->lmm_stripe_count);
5143         for (i = 0; i < count; i++, objs++) {
5144                 struct ost_id oi2;
5145
5146                 ostid_le_to_cpu(&objs->l_ost_oi, &oi2);
5147                 if (memcmp(oi, &oi2, sizeof(*oi)) == 0)
5148                         GOTO(unlock, rc = (i != idx ? -ENODATA : 0));
5149         }
5150
5151         GOTO(unlock, rc = -ENODATA);
5152
5153 unlock:
5154         dt_read_unlock(env, obj);
5155         lfsck_object_put(env, obj);
5156
5157         return rc;
5158 }
5159
5160 /*
5161  * The LFSCK-on-OST will ask the LFSCK-on-MDT to check whether the given
5162  * MDT-object/OST-object pairs match or not to aviod transfer MDT-object
5163  * layout EA from MDT to OST. On one hand, the OST no need to understand
5164  * the layout EA structure; on the other hand, it may cause trouble when
5165  * transfer large layout EA from MDT to OST via normal OUT RPC.
5166  *
5167  * \ret > 0: unrecognized stripe
5168  * \ret = 0: recognized stripe
5169  * \ret < 0: other failures
5170  */
5171 static int lfsck_layout_slave_check_pairs(const struct lu_env *env,
5172                                           struct lfsck_component *com,
5173                                           struct lu_fid *cfid,
5174                                           struct lu_fid *pfid, __u32 comp_id)
5175 {
5176         struct lfsck_instance    *lfsck  = com->lc_lfsck;
5177         struct obd_device        *obd    = lfsck->li_obd;
5178         struct seq_server_site   *ss     = lfsck_dev_site(lfsck);
5179         struct obd_export        *exp    = NULL;
5180         struct ptlrpc_request    *req    = NULL;
5181         struct lfsck_request     *lr;
5182         struct lu_seq_range      *range  = &lfsck_env_info(env)->lti_range;
5183         int                       rc     = 0;
5184         ENTRY;
5185
5186         if (unlikely(fid_is_idif(pfid)))
5187                 RETURN(1);
5188
5189         fld_range_set_any(range);
5190         rc = fld_server_lookup(env, ss->ss_server_fld, fid_seq(pfid), range);
5191         if (rc != 0)
5192                 RETURN(rc == -ENOENT ? 1 : rc);
5193
5194         if (unlikely(!fld_range_is_mdt(range)))
5195                 RETURN(1);
5196
5197         exp = lustre_find_lwp_by_index(obd->obd_name, range->lsr_index);
5198         if (unlikely(exp == NULL))
5199                 RETURN(1);
5200
5201         if (!(exp_connect_flags(exp) & OBD_CONNECT_LFSCK))
5202                 GOTO(out, rc = -EOPNOTSUPP);
5203
5204         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_LFSCK_NOTIFY);
5205         if (req == NULL)
5206                 GOTO(out, rc = -ENOMEM);
5207
5208         rc = ptlrpc_request_pack(req, LUSTRE_OBD_VERSION, LFSCK_NOTIFY);
5209         if (rc != 0) {
5210                 ptlrpc_request_free(req);
5211
5212                 GOTO(out, rc);
5213         }
5214
5215         lr = req_capsule_client_get(&req->rq_pill, &RMF_LFSCK_REQUEST);
5216         memset(lr, 0, sizeof(*lr));
5217         lr->lr_event = LE_PAIRS_VERIFY;
5218         lr->lr_active = LFSCK_TYPE_LAYOUT;
5219         lr->lr_fid = *cfid; /* OST-object itself FID. */
5220         lr->lr_fid2 = *pfid; /* The claimed parent FID. */
5221         lr->lr_comp_id = comp_id;
5222
5223         ptlrpc_request_set_replen(req);
5224         rc = ptlrpc_queue_wait(req);
5225         ptlrpc_req_finished(req);
5226
5227         if (rc == -ENOENT || rc == -ENODATA)
5228                 rc = 1;
5229
5230         GOTO(out, rc);
5231
5232 out:
5233         if (exp != NULL)
5234                 class_export_put(exp);
5235
5236         return rc;
5237 }
5238
5239 static int lfsck_layout_slave_repair_pfid(const struct lu_env *env,
5240                                           struct lfsck_component *com,
5241                                           struct lfsck_req_local *lrl)
5242 {
5243         struct dt_object        *obj;
5244         int                      rc     = 0;
5245         ENTRY;
5246
5247         obj = lfsck_object_find_bottom(env, com->lc_lfsck, &lrl->lrl_fid);
5248         if (IS_ERR(obj))
5249                 GOTO(log, rc = PTR_ERR(obj));
5250
5251         dt_write_lock(env, obj, 0);
5252         if (unlikely(dt_object_exists(obj) == 0 ||
5253                      lfsck_is_dead_obj(obj)))
5254                 GOTO(unlock, rc = 0);
5255
5256         rc = __lfsck_layout_update_pfid(env, com, obj,
5257                                         &lrl->lrl_ff_client.ff_parent,
5258                                         &lrl->lrl_ff_client.ff_layout,
5259                                         lrl->lrl_ff_client.ff_layout_version,
5260                                         lrl->lrl_ff_client.ff_range,
5261                                         lrl->lrl_ff_client.ff_parent.f_ver);
5262
5263         GOTO(unlock, rc);
5264
5265 unlock:
5266         dt_write_unlock(env, obj);
5267         lfsck_object_put(env, obj);
5268
5269 log:
5270         CDEBUG(D_LFSCK, "%s: layout LFSCK slave repaired pfid for "DFID
5271                ", parent "DFID": rc = %d\n", lfsck_lfsck2name(com->lc_lfsck),
5272                PFID(&lrl->lrl_fid), PFID(&lrl->lrl_ff_client.ff_parent), rc);
5273
5274         return rc;
5275 }
5276
5277 /* layout APIs */
5278
5279 static void lfsck_layout_slave_quit(const struct lu_env *env,
5280                                     struct lfsck_component *com);
5281
5282 static int lfsck_layout_reset(const struct lu_env *env,
5283                               struct lfsck_component *com, bool init)
5284 {
5285         struct lfsck_layout     *lo    = com->lc_file_ram;
5286         int                      rc;
5287
5288         down_write(&com->lc_sem);
5289         if (init) {
5290                 memset(lo, 0, com->lc_file_size);
5291         } else {
5292                 __u32 count = lo->ll_success_count;
5293                 time64_t last_time = lo->ll_time_last_complete;
5294
5295                 memset(lo, 0, com->lc_file_size);
5296                 lo->ll_success_count = count;
5297                 lo->ll_time_last_complete = last_time;
5298         }
5299
5300         lo->ll_magic = LFSCK_LAYOUT_MAGIC;
5301         lo->ll_status = LS_INIT;
5302
5303         if (com->lc_lfsck->li_master) {
5304                 struct lfsck_assistant_data *lad = com->lc_data;
5305
5306                 clear_bit(LAD_INCOMPLETE, &lad->lad_flags);
5307                 bitmap_zero(lad->lad_bitmap, lad->lad_bitmap_count);
5308         }
5309
5310         rc = lfsck_layout_store(env, com);
5311         if (rc == 0 && com->lc_lfsck->li_master)
5312                 rc = lfsck_load_sub_trace_files(env, com,
5313                         &dt_lfsck_layout_dangling_features, LFSCK_LAYOUT, true);
5314         up_write(&com->lc_sem);
5315
5316         CDEBUG(D_LFSCK, "%s: layout LFSCK reset: rc = %d\n",
5317                lfsck_lfsck2name(com->lc_lfsck), rc);
5318
5319         return rc;
5320 }
5321
5322 static void lfsck_layout_fail(const struct lu_env *env,
5323                               struct lfsck_component *com, bool new_checked)
5324 {
5325         struct lfsck_layout *lo = com->lc_file_ram;
5326
5327         down_write(&com->lc_sem);
5328         if (new_checked)
5329                 com->lc_new_checked++;
5330         lfsck_layout_record_failure(env, com->lc_lfsck, lo);
5331         up_write(&com->lc_sem);
5332 }
5333
5334 static int lfsck_layout_master_checkpoint(const struct lu_env *env,
5335                                           struct lfsck_component *com, bool init)
5336 {
5337         struct lfsck_instance   *lfsck   = com->lc_lfsck;
5338         struct lfsck_layout     *lo      = com->lc_file_ram;
5339         int                      rc;
5340
5341         if (!init) {
5342                 rc = lfsck_checkpoint_generic(env, com);
5343                 if (rc != 0)
5344                         return rc > 0 ? 0 : rc;
5345         }
5346
5347         down_write(&com->lc_sem);
5348         if (init) {
5349                 lo->ll_pos_latest_start =
5350                                 lfsck->li_pos_checkpoint.lp_oit_cookie;
5351         } else {
5352                 lo->ll_pos_last_checkpoint =
5353                                 lfsck->li_pos_checkpoint.lp_oit_cookie;
5354                 lo->ll_run_time_phase1 += ktime_get_seconds() -
5355                                           lfsck->li_time_last_checkpoint;
5356                 lo->ll_time_last_checkpoint = ktime_get_real_seconds();
5357                 lo->ll_objs_checked_phase1 += com->lc_new_checked;
5358                 com->lc_new_checked = 0;
5359         }
5360
5361         rc = lfsck_layout_store(env, com);
5362         up_write(&com->lc_sem);
5363
5364         CDEBUG(D_LFSCK, "%s: layout LFSCK master checkpoint at the pos ["
5365                "%llu], status = %d: rc = %d\n", lfsck_lfsck2name(lfsck),
5366                lfsck->li_pos_current.lp_oit_cookie, lo->ll_status, rc);
5367
5368         return rc;
5369 }
5370
5371 static int lfsck_layout_slave_checkpoint(const struct lu_env *env,
5372                                          struct lfsck_component *com, bool init)
5373 {
5374         struct lfsck_instance   *lfsck = com->lc_lfsck;
5375         struct lfsck_layout     *lo    = com->lc_file_ram;
5376         int                      rc;
5377
5378         if (com->lc_new_checked == 0 && !init)
5379                 return 0;
5380
5381         down_write(&com->lc_sem);
5382         if (init) {
5383                 lo->ll_pos_latest_start =
5384                                 lfsck->li_pos_checkpoint.lp_oit_cookie;
5385         } else {
5386                 lo->ll_pos_last_checkpoint =
5387                                 lfsck->li_pos_checkpoint.lp_oit_cookie;
5388                 lo->ll_run_time_phase1 += ktime_get_seconds() -
5389                                           lfsck->li_time_last_checkpoint;
5390                 lo->ll_time_last_checkpoint = ktime_get_real_seconds();
5391                 lo->ll_objs_checked_phase1 += com->lc_new_checked;
5392                 com->lc_new_checked = 0;
5393         }
5394
5395         rc = lfsck_layout_store(env, com);
5396         up_write(&com->lc_sem);
5397
5398         CDEBUG(D_LFSCK, "%s: layout LFSCK slave checkpoint at the pos ["
5399                "%llu], status = %d: rc = %d\n", lfsck_lfsck2name(lfsck),
5400                lfsck->li_pos_current.lp_oit_cookie, lo->ll_status, rc);
5401
5402         return rc;
5403 }
5404
5405 static int lfsck_layout_prep(const struct lu_env *env,
5406                              struct lfsck_component *com,
5407                              struct lfsck_start *start)
5408 {
5409         struct lfsck_instance   *lfsck  = com->lc_lfsck;
5410         struct lfsck_layout     *lo     = com->lc_file_ram;
5411         struct lfsck_position   *pos    = &com->lc_pos_start;
5412
5413         fid_zero(&pos->lp_dir_parent);
5414         pos->lp_dir_cookie = 0;
5415         if (lo->ll_status == LS_COMPLETED ||
5416             lo->ll_status == LS_PARTIAL ||
5417             /* To handle orphan, must scan from the beginning. */
5418             (start != NULL && start->ls_flags & LPF_OST_ORPHAN)) {
5419                 int rc;
5420
5421                 rc = lfsck_layout_reset(env, com, false);
5422                 if (rc == 0)
5423                         rc = lfsck_set_param(env, lfsck, start, true);
5424
5425                 if (rc != 0) {
5426                         CDEBUG(D_LFSCK, "%s: layout LFSCK prep failed: "
5427                                "rc = %d\n", lfsck_lfsck2name(lfsck), rc);
5428
5429                         return rc;
5430                 }
5431         }
5432
5433         down_write(&com->lc_sem);
5434         lo->ll_time_latest_start = ktime_get_real_seconds();
5435         spin_lock(&lfsck->li_lock);
5436         if (lo->ll_flags & LF_SCANNED_ONCE) {
5437                 if (!lfsck->li_drop_dryrun ||
5438                     lo->ll_pos_first_inconsistent == 0) {
5439                         lo->ll_status = LS_SCANNING_PHASE2;
5440                         list_move_tail(&com->lc_link,
5441                                        &lfsck->li_list_double_scan);
5442                         pos->lp_oit_cookie = 0;
5443                 } else {
5444                         int i;
5445
5446                         lo->ll_status = LS_SCANNING_PHASE1;
5447                         lo->ll_run_time_phase1 = 0;
5448                         lo->ll_run_time_phase2 = 0;
5449                         lo->ll_objs_checked_phase1 = 0;
5450                         lo->ll_objs_checked_phase2 = 0;
5451                         lo->ll_objs_failed_phase1 = 0;
5452                         lo->ll_objs_failed_phase2 = 0;
5453                         for (i = 0; i < LLIT_MAX; i++)
5454                                 lo->ll_objs_repaired[i] = 0;
5455
5456                         pos->lp_oit_cookie = lo->ll_pos_first_inconsistent;
5457                         fid_zero(&com->lc_fid_latest_scanned_phase2);
5458                 }
5459         } else {
5460                 lo->ll_status = LS_SCANNING_PHASE1;
5461                 if (!lfsck->li_drop_dryrun ||
5462                     lo->ll_pos_first_inconsistent == 0)
5463                         pos->lp_oit_cookie = lo->ll_pos_last_checkpoint + 1;
5464                 else
5465                         pos->lp_oit_cookie = lo->ll_pos_first_inconsistent;
5466         }
5467         spin_unlock(&lfsck->li_lock);
5468         up_write(&com->lc_sem);
5469
5470         return 0;
5471 }
5472
5473 static int lfsck_layout_slave_prep(const struct lu_env *env,
5474                                    struct lfsck_component *com,
5475                                    struct lfsck_start_param *lsp)
5476 {
5477         struct lfsck_layout_slave_data  *llsd   = com->lc_data;
5478         struct lfsck_instance           *lfsck  = com->lc_lfsck;
5479         struct lfsck_layout             *lo     = com->lc_file_ram;
5480         struct lfsck_start              *start  = lsp->lsp_start;
5481         int                              rc;
5482
5483         rc = lfsck_layout_prep(env, com, start);
5484         if (rc != 0)
5485                 return rc;
5486
5487         if (lo->ll_flags & LF_CRASHED_LASTID &&
5488             list_empty(&llsd->llsd_master_list)) {
5489                 LASSERT(lfsck->li_out_notify != NULL);
5490
5491                 lfsck->li_out_notify(env, lfsck->li_out_notify_data,
5492                                      LE_LASTID_REBUILDING);
5493         }
5494
5495         if (!lsp->lsp_index_valid)
5496                 return 0;
5497
5498         rc = lfsck_layout_llst_add(llsd, lsp->lsp_index);
5499         if (rc == 0 && start != NULL && start->ls_flags & LPF_OST_ORPHAN) {
5500                 LASSERT(!llsd->llsd_rbtree_valid);
5501
5502                 down_write(&llsd->llsd_rb_rwsem);
5503                 rc = lfsck_rbtree_setup(env, com);
5504                 up_write(&llsd->llsd_rb_rwsem);
5505         }
5506
5507         CDEBUG(D_LFSCK, "%s: layout LFSCK slave prep done, start pos ["
5508                "%llu]\n", lfsck_lfsck2name(lfsck),
5509                com->lc_pos_start.lp_oit_cookie);
5510
5511         return rc;
5512 }
5513
5514 static int lfsck_layout_master_prep(const struct lu_env *env,
5515                                     struct lfsck_component *com,
5516                                     struct lfsck_start_param *lsp)
5517 {
5518         int rc;
5519         ENTRY;
5520
5521         rc = lfsck_layout_load_bitmap(env, com);
5522         if (rc != 0) {
5523                 rc = lfsck_layout_reset(env, com, false);
5524                 if (rc == 0)
5525                         rc = lfsck_set_param(env, com->lc_lfsck,
5526                                              lsp->lsp_start, true);
5527
5528                 if (rc != 0)
5529                         GOTO(log, rc);
5530         }
5531
5532         rc = lfsck_layout_prep(env, com, lsp->lsp_start);
5533         if (rc != 0)
5534                 RETURN(rc);
5535
5536         rc = lfsck_start_assistant(env, com, lsp);
5537
5538         GOTO(log, rc);
5539
5540 log:
5541         CDEBUG(D_LFSCK, "%s: layout LFSCK master prep done, start pos ["
5542                "%llu]\n", lfsck_lfsck2name(com->lc_lfsck),
5543                com->lc_pos_start.lp_oit_cookie);
5544
5545         return 0;
5546 }
5547
5548 /* Pre-fetch the attribute for each stripe in the given layout EA. */
5549 static int lfsck_layout_scan_stripes(const struct lu_env *env,
5550                                      struct lfsck_component *com,
5551                                      struct dt_object *parent,
5552                                      struct lov_mds_md_v1 *lmm, __u32 comp_id)
5553 {
5554         struct lfsck_thread_info        *info    = lfsck_env_info(env);
5555         struct lfsck_instance           *lfsck   = com->lc_lfsck;
5556         struct lfsck_bookmark           *bk      = &lfsck->li_bookmark_ram;
5557         struct lfsck_layout             *lo      = com->lc_file_ram;
5558         struct lfsck_assistant_data     *lad     = com->lc_data;
5559         struct lfsck_assistant_object   *lso     = NULL;
5560         struct lov_ost_data_v1          *objs;
5561         struct lfsck_tgt_descs          *ltds    = &lfsck->li_ost_descs;
5562         struct ptlrpc_thread            *mthread = &lfsck->li_thread;
5563         struct ptlrpc_thread            *athread = &lad->lad_thread;
5564         struct lu_buf                    buf;
5565         int                              rc      = 0;
5566         int                              i;
5567         __u32                            magic;
5568         __u16                            count;
5569         ENTRY;
5570
5571         lfsck_buf_init(&buf, &info->lti_ff, sizeof(struct filter_fid));
5572         magic = le32_to_cpu(lmm->lmm_magic);
5573         if (magic == LOV_MAGIC_V1) {
5574                 objs = &lmm->lmm_objects[0];
5575         } else {
5576                 LASSERT(magic == LOV_MAGIC_V3);
5577                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[0];
5578         }
5579
5580         count = le16_to_cpu(lmm->lmm_stripe_count);
5581         for (i = 0; i < count; i++, objs++) {
5582                 struct lu_fid           *fid    = &info->lti_fid;
5583                 struct ost_id           *oi     = &info->lti_oi;
5584                 struct lfsck_layout_req *llr;
5585                 struct lfsck_tgt_desc   *tgt    = NULL;
5586                 struct dt_object        *cobj   = NULL;
5587                 __u32                    index;
5588                 bool                     wakeup = false;
5589
5590                 if (unlikely(lovea_slot_is_dummy(objs)))
5591                         continue;
5592
5593                 wait_event_idle(mthread->t_ctl_waitq,
5594                                 lad->lad_prefetched < bk->lb_async_windows ||
5595                                 !thread_is_running(mthread) ||
5596                                 thread_is_stopped(athread));
5597
5598                 if (unlikely(!thread_is_running(mthread)) ||
5599                              thread_is_stopped(athread))
5600                         GOTO(out, rc = 0);
5601
5602                 if (unlikely(lfsck_is_dead_obj(parent)))
5603                         GOTO(out, rc = 0);
5604
5605                 ostid_le_to_cpu(&objs->l_ost_oi, oi);
5606                 index = le32_to_cpu(objs->l_ost_idx);
5607                 rc = ostid_to_fid(fid, oi, index);
5608                 if (rc != 0) {
5609                         CDEBUG(D_LFSCK, "%s: get invalid layout EA for "DFID
5610                                ": "DOSTID", idx %u, comp_id %u\n",
5611                                lfsck_lfsck2name(lfsck),
5612                                PFID(lfsck_dto2fid(parent)), POSTID(oi),
5613                                index, comp_id);
5614                         goto next;
5615                 }
5616
5617                 tgt = lfsck_tgt_get(ltds, index);
5618                 if (unlikely(tgt == NULL)) {
5619                         CDEBUG(D_LFSCK, "%s: cannot talk with OST %x which "
5620                                "did not join the layout LFSCK, comp_id %u\n",
5621                                lfsck_lfsck2name(lfsck), index, comp_id);
5622                         lfsck_lad_set_bitmap(env, com, index);
5623                         goto next;
5624                 }
5625
5626                 /* There is potential deadlock race condition between object
5627                  * destroy and layout LFSCK. Consider the following scenario:
5628                  *
5629                  * 1) The LFSCK thread obtained the parent object firstly, at
5630                  *    that time, the parent object has not been destroyed yet.
5631                  *
5632                  * 2) One RPC service thread destroyed the parent and all its
5633                  *    children objects. Because the LFSCK is referencing the
5634                  *    parent object, then the parent object will be marked as
5635                  *    dying in RAM. On the other hand, the parent object is
5636                  *    referencing all its children objects, then all children
5637                  *    objects will be marked as dying in RAM also.
5638                  *
5639                  * 3) The LFSCK thread tries to find some child object with
5640                  *    the parent object referenced. Then it will find that the
5641                  *    child object is dying. According to the object visibility
5642                  *    rules: the object with dying flag cannot be returned to
5643                  *    others. So the LFSCK thread has to wait until the dying
5644                  *    object has been purged from RAM, then it can allocate a
5645                  *    new object (with the same FID) in RAM. Unfortunately, the
5646                  *    LFSCK thread itself is referencing the parent object, and
5647                  *    cause the parent object cannot be purged, then cause the
5648                  *    child object cannot be purged also. So the LFSCK thread
5649                  *    will fall into deadlock.
5650                  */
5651                 cobj = lfsck_object_find_by_dev(env, tgt->ltd_tgt, fid);
5652                 if (IS_ERR(cobj)) {
5653                         if (lfsck_is_dead_obj(parent)) {
5654                                 lfsck_tgt_put(tgt);
5655
5656                                 GOTO(out, rc = 0);
5657                         }
5658
5659                         rc = PTR_ERR(cobj);
5660                         goto next;
5661                 }
5662
5663                 rc = dt_declare_attr_get(env, cobj);
5664                 if (rc)
5665                         goto next;
5666
5667                 rc = dt_declare_xattr_get(env, cobj, &buf, XATTR_NAME_FID);
5668                 if (rc)
5669                         goto next;
5670
5671                 if (lso == NULL) {
5672                         struct lu_attr *attr = &info->lti_la;
5673
5674                         rc = dt_attr_get(env, parent, attr);
5675                         if (rc != 0)
5676                                 goto next;
5677
5678                         lso = lfsck_assistant_object_init(env,
5679                                 lfsck_dto2fid(parent), attr,
5680                                 lfsck->li_pos_current.lp_oit_cookie, false);
5681                         if (IS_ERR(lso)) {
5682                                 rc = PTR_ERR(lso);
5683                                 lso = NULL;
5684
5685                                 goto next;
5686                         }
5687                 }
5688
5689                 llr = lfsck_layout_assistant_req_init(lso, cobj, comp_id,
5690                                                       index, i);
5691                 if (IS_ERR(llr)) {
5692                         rc = PTR_ERR(llr);
5693                         goto next;
5694                 }
5695
5696                 cobj = NULL;
5697                 spin_lock(&lad->lad_lock);
5698                 if (lad->lad_assistant_status < 0) {
5699                         spin_unlock(&lad->lad_lock);
5700                         lfsck_layout_assistant_req_fini(env, &llr->llr_lar);
5701                         lfsck_tgt_put(tgt);
5702                         RETURN(lad->lad_assistant_status);
5703                 }
5704
5705                 list_add_tail(&llr->llr_lar.lar_list, &lad->lad_req_list);
5706                 if (lad->lad_prefetched == 0)
5707                         wakeup = true;
5708
5709                 lad->lad_prefetched++;
5710                 spin_unlock(&lad->lad_lock);
5711                 if (wakeup)
5712                         wake_up(&athread->t_ctl_waitq);
5713
5714 next:
5715                 down_write(&com->lc_sem);
5716                 com->lc_new_checked++;
5717                 if (rc < 0)
5718                         lfsck_layout_record_failure(env, lfsck, lo);
5719                 up_write(&com->lc_sem);
5720
5721                 if (cobj != NULL && !IS_ERR(cobj))
5722                         lfsck_object_put(env, cobj);
5723
5724                 if (likely(tgt != NULL))
5725                         lfsck_tgt_put(tgt);
5726
5727                 if (rc < 0 && bk->lb_param & LPF_FAILOUT)
5728                         GOTO(out, rc);
5729         }
5730
5731         GOTO(out, rc = 0);
5732
5733 out:
5734         if (lso != NULL)
5735                 lfsck_assistant_object_put(env, lso);
5736
5737         return rc;
5738 }
5739
5740 /* For the given object, read its layout EA locally. For each stripe, pre-fetch
5741  * the OST-object's attribute and generate an structure lfsck_layout_req on the
5742  * list ::lad_req_list.
5743  *
5744  * For each request on above list, the lfsck_layout_assistant thread compares
5745  * the OST side attribute with local attribute, if inconsistent, then repair it.
5746  *
5747  * All above processing is async mode with pipeline. */
5748 static int lfsck_layout_master_exec_oit(const struct lu_env *env,
5749                                         struct lfsck_component *com,
5750                                         struct dt_object *obj)
5751 {
5752         struct lfsck_thread_info        *info   = lfsck_env_info(env);
5753         struct ost_id                   *oi     = &info->lti_oi;
5754         struct lfsck_layout             *lo     = com->lc_file_ram;
5755         struct lfsck_assistant_data     *lad    = com->lc_data;
5756         struct lfsck_instance           *lfsck  = com->lc_lfsck;
5757         struct lfsck_bookmark           *bk     = &lfsck->li_bookmark_ram;
5758         struct thandle                  *handle = NULL;
5759         struct lu_buf                   *buf    = &info->lti_big_buf;
5760         struct lov_mds_md_v1            *lmm    = NULL;
5761         struct dt_device                *dev    = lfsck_obj2dev(obj);
5762         struct lustre_handle             lh     = { 0 };
5763         struct lu_buf                    ea_buf = { NULL };
5764         struct lov_comp_md_v1           *lcm    = NULL;
5765         struct lov_comp_md_entry_v1     *lcme   = NULL;
5766         int                              rc     = 0;
5767         int                              size   = 0;
5768         __u32                            magic  = 0;
5769         __u16                            count  = 0;
5770         bool                             locked = false;
5771         bool                             stripe = false;
5772         bool                             bad_oi = false;
5773         ENTRY;
5774
5775         if (!S_ISREG(lfsck_object_type(obj)))
5776                 GOTO(out, rc = 0);
5777
5778         if (lad->lad_assistant_status < 0)
5779                 GOTO(out, rc = -ESRCH);
5780
5781         fid_to_lmm_oi(lfsck_dto2fid(obj), oi);
5782         lmm_oi_cpu_to_le(oi, oi);
5783         dt_read_lock(env, obj, 0);
5784         locked = true;
5785
5786 again:
5787         bad_oi = false;
5788         if (dt_object_exists(obj) == 0 ||
5789             lfsck_is_dead_obj(obj))
5790                 GOTO(out, rc = 0);
5791
5792         rc = lfsck_layout_get_lovea(env, obj, buf);
5793         if (rc == -EINVAL || rc == -ENODATA || rc == -EOPNOTSUPP)
5794                 /* Skip bad lov EA during the 1st cycle scanning, and
5795                  * try to recover it via orphan in the 2nd scanning. */
5796                 rc = 0;
5797         if (rc <= 0)
5798                 GOTO(out, rc);
5799
5800         size = rc;
5801         lmm = buf->lb_buf;
5802         magic = le32_to_cpu(lmm->lmm_magic);
5803         if (magic == LOV_MAGIC_COMP_V1 || magic == LOV_MAGIC_SEL) {
5804                 struct lov_mds_md_v1 *v1;
5805                 int i;
5806
5807                 lcm = buf->lb_buf;
5808                 count = le16_to_cpu(lcm->lcm_entry_count);
5809                 for (i = 0; i < count; i++) {
5810                         lcme = &lcm->lcm_entries[i];
5811                         v1 = buf->lb_buf + le32_to_cpu(lcme->lcme_offset);
5812                         if (memcmp(oi, &v1->lmm_oi, sizeof(*oi)) != 0)
5813                                 goto fix;
5814                 }
5815
5816                 GOTO(out, stripe = true);
5817         } else if (memcmp(oi, &lmm->lmm_oi, sizeof(*oi)) == 0) {
5818                 GOTO(out, stripe = true);
5819         }
5820
5821 fix:
5822         /* Inconsistent lmm_oi, should be repaired. */
5823         bad_oi = true;
5824
5825         if (bk->lb_param & LPF_DRYRUN) {
5826                 lo->ll_objs_repaired[LLIT_OTHERS - 1]++;
5827
5828                 GOTO(out, stripe = true);
5829         }
5830
5831         if (!lustre_handle_is_used(&lh)) {
5832                 dt_read_unlock(env, obj);
5833                 locked = false;
5834                 rc = lfsck_ibits_lock(env, lfsck, obj, &lh,
5835                                       MDS_INODELOCK_LAYOUT |
5836                                       MDS_INODELOCK_XATTR, LCK_EX);
5837                 if (rc != 0)
5838                         GOTO(out, rc);
5839
5840                 handle = lfsck_trans_create(env, dev, lfsck);
5841                 if (IS_ERR(handle))
5842                         GOTO(out, rc = PTR_ERR(handle));
5843
5844                 lfsck_buf_init(&ea_buf, buf->lb_buf, size);
5845                 rc = dt_declare_xattr_set(env, obj, &ea_buf, XATTR_NAME_LOV,
5846                                           LU_XATTR_REPLACE, handle);
5847                 if (rc != 0)
5848                         GOTO(out, rc);
5849
5850                 rc = dt_trans_start_local(env, dev, handle);
5851                 if (rc != 0)
5852                         GOTO(out, rc);
5853
5854                 dt_write_lock(env, obj, 0);
5855                 locked = true;
5856
5857                 goto again;
5858         }
5859
5860         if (magic == LOV_MAGIC_COMP_V1 || magic == LOV_MAGIC_SEL) {
5861                 struct lov_mds_md_v1 *v1;
5862                 int i;
5863
5864                 for (i = 0; i < count; i++) {
5865                         lcme = &lcm->lcm_entries[i];
5866                         v1 = buf->lb_buf + le32_to_cpu(lcme->lcme_offset);
5867                         v1->lmm_oi = *oi;
5868                 }
5869         } else {
5870                 lmm->lmm_oi = *oi;
5871         }
5872
5873         rc = dt_xattr_set(env, obj, &ea_buf, XATTR_NAME_LOV,
5874                           LU_XATTR_REPLACE, handle);
5875         if (rc != 0)
5876                 GOTO(out, rc);
5877
5878         lo->ll_objs_repaired[LLIT_OTHERS - 1]++;
5879
5880         GOTO(out, stripe = true);
5881
5882 out:
5883         if (locked) {
5884                 if (lustre_handle_is_used(&lh))
5885                         dt_write_unlock(env, obj);
5886                 else
5887                         dt_read_unlock(env, obj);
5888         }
5889
5890         if (handle != NULL && !IS_ERR(handle))
5891                 dt_trans_stop(env, dev, handle);
5892
5893         lfsck_ibits_unlock(&lh, LCK_EX);
5894
5895         if (bad_oi)
5896                 CDEBUG(D_LFSCK, "%s: layout LFSCK master %s bad lmm_oi for "
5897                        DFID": rc = %d\n", lfsck_lfsck2name(lfsck),
5898                        bk->lb_param & LPF_DRYRUN ? "found" : "repaired",
5899                        PFID(lfsck_dto2fid(obj)), rc);
5900
5901         if (stripe) {
5902                 if (magic == LOV_MAGIC_COMP_V1 || magic == LOV_MAGIC_SEL) {
5903                         int i;
5904
5905                         for (i = 0; i < count; i++) {
5906                                 lcme = &lcm->lcm_entries[i];
5907                                 if (!(le32_to_cpu(lcme->lcme_flags) &
5908                                       LCME_FL_INIT))
5909                                         continue;
5910
5911                                 rc = lfsck_layout_scan_stripes(env, com, obj,
5912                                         (struct lov_mds_md_v1 *)(buf->lb_buf +
5913                                         le32_to_cpu(lcme->lcme_offset)),
5914                                         le32_to_cpu(lcme->lcme_id));
5915                         }
5916                 } else {
5917                         rc = lfsck_layout_scan_stripes(env, com, obj, lmm, 0);
5918                 }
5919         } else {
5920                 down_write(&com->lc_sem);
5921                 com->lc_new_checked++;
5922                 if (rc < 0)
5923                         lfsck_layout_record_failure(env, lfsck, lo);
5924                 up_write(&com->lc_sem);
5925         }
5926
5927         return rc;
5928 }
5929
5930 static int lfsck_layout_slave_exec_oit(const struct lu_env *env,
5931                                        struct lfsck_component *com,
5932                                        struct dt_object *obj)
5933 {
5934         struct lfsck_instance           *lfsck  = com->lc_lfsck;
5935         struct lfsck_layout             *lo     = com->lc_file_ram;
5936         const struct lu_fid             *fid    = lfsck_dto2fid(obj);
5937         struct lfsck_layout_slave_data  *llsd   = com->lc_data;
5938         struct lfsck_layout_seq         *lls;
5939         __u64                            seq;
5940         __u64                            oid;
5941         int                              rc;
5942         ENTRY;
5943
5944         LASSERT(llsd != NULL);
5945
5946         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_DELAY5) &&
5947             cfs_fail_val == lfsck_dev_idx(lfsck)) {
5948                 struct ptlrpc_thread    *thread = &lfsck->li_thread;
5949
5950                 wait_event_idle_timeout(thread->t_ctl_waitq,
5951                                         !thread_is_running(thread),
5952                                         cfs_time_seconds(1));
5953         }
5954
5955         lfsck_rbtree_update_bitmap(env, com, fid, false);
5956
5957         down_write(&com->lc_sem);
5958         if (fid_is_idif(fid))
5959                 seq = 0;
5960         else if (!fid_is_norm(fid) ||
5961                  !fid_is_for_ostobj(env, lfsck, obj, fid))
5962                 GOTO(unlock, rc = 0);
5963         else
5964                 seq = fid_seq(fid);
5965         com->lc_new_checked++;
5966
5967         lls = lfsck_layout_seq_lookup(llsd, seq);
5968         if (lls == NULL) {
5969                 OBD_ALLOC_PTR(lls);
5970                 if (unlikely(lls == NULL))
5971                         GOTO(unlock, rc = -ENOMEM);
5972
5973                 INIT_LIST_HEAD(&lls->lls_list);
5974                 lls->lls_seq = seq;
5975                 rc = lfsck_layout_lastid_load(env, com, lls);
5976                 if (rc != 0) {
5977                         CDEBUG(D_LFSCK, "%s: layout LFSCK failed to "
5978                               "load LAST_ID for %#llx: rc = %d\n",
5979                               lfsck_lfsck2name(com->lc_lfsck), seq, rc);
5980                         lo->ll_objs_failed_phase1++;
5981                         OBD_FREE_PTR(lls);
5982                         GOTO(unlock, rc);
5983                 }
5984
5985                 lfsck_layout_seq_insert(llsd, lls);
5986         }
5987
5988         if (unlikely(fid_is_last_id(fid)))
5989                 GOTO(unlock, rc = 0);
5990
5991         if (fid_is_idif(fid))
5992                 oid = fid_idif_id(fid_seq(fid), fid_oid(fid), fid_ver(fid));
5993         else
5994                 oid = fid_oid(fid);
5995
5996         if (oid > lls->lls_lastid_known)
5997                 lls->lls_lastid_known = oid;
5998
5999         if (oid > lls->lls_lastid) {
6000                 if (!(lo->ll_flags & LF_CRASHED_LASTID)) {
6001                         /* OFD may create new objects during LFSCK scanning. */
6002                         rc = lfsck_layout_lastid_reload(env, com, lls);
6003                         if (unlikely(rc != 0)) {
6004                                 CDEBUG(D_LFSCK, "%s: layout LFSCK failed to "
6005                                       "reload LAST_ID for %#llx: rc = %d\n",
6006                                       lfsck_lfsck2name(com->lc_lfsck),
6007                                       lls->lls_seq, rc);
6008
6009                                 GOTO(unlock, rc);
6010                         }
6011
6012                         if (oid <= lls->lls_lastid ||
6013                             lo->ll_flags & LF_CRASHED_LASTID)
6014                                 GOTO(unlock, rc = 0);
6015
6016                         LASSERT(lfsck->li_out_notify != NULL);
6017
6018                         lfsck->li_out_notify(env, lfsck->li_out_notify_data,
6019                                              LE_LASTID_REBUILDING);
6020                         lo->ll_flags |= LF_CRASHED_LASTID;
6021
6022                         CDEBUG(D_LFSCK, "%s: layout LFSCK finds crashed "
6023                                "LAST_ID file (2) for the sequence %#llx"
6024                                ", old value %llu, known value %llu\n",
6025                                lfsck_lfsck2name(lfsck), lls->lls_seq,
6026                                lls->lls_lastid, oid);
6027                 }
6028
6029                 lls->lls_lastid = oid;
6030                 lls->lls_dirty = 1;
6031         }
6032
6033         GOTO(unlock, rc = 0);
6034
6035 unlock:
6036         up_write(&com->lc_sem);
6037
6038         return rc;
6039 }
6040
6041 static int lfsck_layout_exec_dir(const struct lu_env *env,
6042                                  struct lfsck_component *com,
6043                                  struct lfsck_assistant_object *lso,
6044                                  struct lu_dirent *ent, __u16 type)
6045 {
6046         return 0;
6047 }
6048
6049 static int lfsck_layout_master_post(const struct lu_env *env,
6050                                     struct lfsck_component *com,
6051                                     int result, bool init)
6052 {
6053         struct lfsck_instance   *lfsck  = com->lc_lfsck;
6054         struct lfsck_layout     *lo     = com->lc_file_ram;
6055         int                      rc;
6056         ENTRY;
6057
6058         lfsck_post_generic(env, com, &result);
6059
6060         down_write(&com->lc_sem);
6061         spin_lock(&lfsck->li_lock);
6062         if (!init)
6063                 lo->ll_pos_last_checkpoint =
6064                                 lfsck->li_pos_checkpoint.lp_oit_cookie;
6065
6066         if (result > 0) {
6067                 if (lo->ll_flags & LF_INCOMPLETE)
6068                         lo->ll_status = LS_PARTIAL;
6069                 else
6070                         lo->ll_status = LS_SCANNING_PHASE2;
6071                 lo->ll_flags |= LF_SCANNED_ONCE;
6072                 lo->ll_flags &= ~LF_UPGRADE;
6073                 list_move_tail(&com->lc_link, &lfsck->li_list_double_scan);
6074         } else if (result == 0) {
6075                 if (lfsck->li_status != 0)
6076                         lo->ll_status = lfsck->li_status;
6077                 else
6078                         lo->ll_status = LS_STOPPED;
6079                 if (lo->ll_status != LS_PAUSED)
6080                         list_move_tail(&com->lc_link, &lfsck->li_list_idle);
6081         } else {
6082                 lo->ll_status = LS_FAILED;
6083                 list_move_tail(&com->lc_link, &lfsck->li_list_idle);
6084         }
6085         spin_unlock(&lfsck->li_lock);
6086
6087         if (!init) {
6088                 lo->ll_run_time_phase1 += ktime_get_seconds() -
6089                                           lfsck->li_time_last_checkpoint;
6090                 lo->ll_time_last_checkpoint = ktime_get_real_seconds();
6091                 lo->ll_objs_checked_phase1 += com->lc_new_checked;
6092                 com->lc_new_checked = 0;
6093         }
6094
6095         rc = lfsck_layout_store(env, com);
6096         up_write(&com->lc_sem);
6097
6098         CDEBUG(D_LFSCK, "%s: layout LFSCK master post done: rc = %d\n",
6099                lfsck_lfsck2name(lfsck), rc);
6100
6101         RETURN(rc);
6102 }
6103
6104 static int lfsck_layout_slave_post(const struct lu_env *env,
6105                                    struct lfsck_component *com,
6106                                    int result, bool init)
6107 {
6108         struct lfsck_instance   *lfsck = com->lc_lfsck;
6109         struct lfsck_layout     *lo    = com->lc_file_ram;
6110         int                      rc;
6111         bool                     done  = false;
6112
6113         down_write(&com->lc_sem);
6114         rc = lfsck_layout_lastid_store(env, com);
6115         if (rc != 0)
6116                 result = rc;
6117
6118         LASSERT(lfsck->li_out_notify != NULL);
6119
6120         spin_lock(&lfsck->li_lock);
6121         if (!init)
6122                 lo->ll_pos_last_checkpoint =
6123                                 lfsck->li_pos_checkpoint.lp_oit_cookie;
6124
6125         if (result > 0) {
6126                 lo->ll_status = LS_SCANNING_PHASE2;
6127                 lo->ll_flags |= LF_SCANNED_ONCE;
6128                 if (lo->ll_flags & LF_CRASHED_LASTID) {
6129                         done = true;
6130                         lo->ll_flags &= ~LF_CRASHED_LASTID;
6131
6132                         CDEBUG(D_LFSCK, "%s: layout LFSCK has rebuilt "
6133                                "crashed LAST_ID files successfully\n",
6134                                lfsck_lfsck2name(lfsck));
6135                 }
6136                 lo->ll_flags &= ~LF_UPGRADE;
6137                 list_move_tail(&com->lc_link, &lfsck->li_list_double_scan);
6138         } else if (result == 0) {
6139                 if (lfsck->li_status != 0)
6140                         lo->ll_status = lfsck->li_status;
6141                 else
6142                         lo->ll_status = LS_STOPPED;
6143                 if (lo->ll_status != LS_PAUSED)
6144                         list_move_tail(&com->lc_link, &lfsck->li_list_idle);
6145         } else {
6146                 lo->ll_status = LS_FAILED;
6147                 list_move_tail(&com->lc_link, &lfsck->li_list_idle);
6148         }
6149         spin_unlock(&lfsck->li_lock);
6150
6151         if (done)
6152                 lfsck->li_out_notify(env, lfsck->li_out_notify_data,
6153                                      LE_LASTID_REBUILT);
6154
6155         if (!init) {
6156                 lo->ll_run_time_phase1 += ktime_get_seconds() -
6157                                           lfsck->li_time_last_checkpoint;
6158                 lo->ll_time_last_checkpoint = ktime_get_real_seconds();
6159                 lo->ll_objs_checked_phase1 += com->lc_new_checked;
6160                 com->lc_new_checked = 0;
6161         }
6162
6163         rc = lfsck_layout_store(env, com);
6164         up_write(&com->lc_sem);
6165
6166         lfsck_layout_slave_notify_master(env, com, LE_PHASE1_DONE, result);
6167
6168         CDEBUG(D_LFSCK, "%s: layout LFSCK slave post done: rc = %d\n",
6169                lfsck_lfsck2name(lfsck), rc);
6170
6171         return rc;
6172 }
6173
6174 static void lfsck_layout_dump(const struct lu_env *env,
6175                               struct lfsck_component *com, struct seq_file *m)
6176 {
6177         struct lfsck_instance   *lfsck = com->lc_lfsck;
6178         struct lfsck_bookmark   *bk    = &lfsck->li_bookmark_ram;
6179         struct lfsck_layout     *lo    = com->lc_file_ram;
6180         const char *prefix;
6181
6182         down_read(&com->lc_sem);
6183         if (bk->lb_param & LPF_DRYRUN)
6184                 prefix = "inconsistent";
6185         else
6186                 prefix = "repaired";
6187
6188         seq_printf(m, "name: lfsck_layout\n"
6189                    "magic: %#x\n"
6190                    "version: %d\n"
6191                    "status: %s\n",
6192                    lo->ll_magic,
6193                    bk->lb_version,
6194                    lfsck_status2name(lo->ll_status));
6195
6196         lfsck_bits_dump(m, lo->ll_flags, lfsck_flags_names, "flags");
6197
6198         lfsck_bits_dump(m, bk->lb_param, lfsck_param_names, "param");
6199
6200         lfsck_time_dump(m, lo->ll_time_last_complete, "last_completed");
6201
6202         lfsck_time_dump(m, lo->ll_time_latest_start, "latest_start");
6203
6204         lfsck_time_dump(m, lo->ll_time_last_checkpoint, "last_checkpoint");
6205
6206         seq_printf(m, "latest_start_position: %llu\n"
6207                    "last_checkpoint_position: %llu\n"
6208                    "first_failure_position: %llu\n",
6209                    lo->ll_pos_latest_start,
6210                    lo->ll_pos_last_checkpoint,
6211                    lo->ll_pos_first_inconsistent);
6212
6213         seq_printf(m, "success_count: %u\n"
6214                    "%s_dangling: %llu\n"
6215                    "%s_unmatched_pair: %llu\n"
6216                    "%s_multiple_referenced: %llu\n"
6217                    "%s_orphan: %llu\n"
6218                    "%s_inconsistent_owner: %llu\n"
6219                    "%s_others: %llu\n"
6220                    "skipped: %llu\n"
6221                    "failed_phase1: %llu\n"
6222                    "failed_phase2: %llu\n",
6223                    lo->ll_success_count,
6224                    prefix, lo->ll_objs_repaired[LLIT_DANGLING - 1],
6225                    prefix, lo->ll_objs_repaired[LLIT_UNMATCHED_PAIR - 1],
6226                    prefix, lo->ll_objs_repaired[LLIT_MULTIPLE_REFERENCED - 1],
6227                    prefix, lo->ll_objs_repaired[LLIT_ORPHAN - 1],
6228                    prefix, lo->ll_objs_repaired[LLIT_INCONSISTENT_OWNER - 1],
6229                    prefix, lo->ll_objs_repaired[LLIT_OTHERS - 1],
6230                    lo->ll_objs_skipped,
6231                    lo->ll_objs_failed_phase1,
6232                    lo->ll_objs_failed_phase2);
6233
6234         if (lo->ll_status == LS_SCANNING_PHASE1) {
6235                 time64_t duration = ktime_get_seconds() -
6236                                     lfsck->li_time_last_checkpoint;
6237                 u64 checked = lo->ll_objs_checked_phase1 +
6238                               com->lc_new_checked;
6239                 u64 speed = checked;
6240                 u64 new_checked = com->lc_new_checked;
6241                 time64_t rtime = lo->ll_run_time_phase1 + duration;
6242                 u64 pos;
6243
6244                 if (duration != 0)
6245                         new_checked = div64_s64(new_checked, duration);
6246                 if (rtime != 0)
6247                         speed = div64_s64(speed, rtime);
6248                 seq_printf(m, "checked_phase1: %llu\n"
6249                            "checked_phase2: %llu\n"
6250                            "run_time_phase1: %lld seconds\n"
6251                            "run_time_phase2: %lld seconds\n"
6252                            "average_speed_phase1: %llu items/sec\n"
6253                            "average_speed_phase2: N/A\n"
6254                            "real_time_speed_phase1: %llu items/sec\n"
6255                            "real_time_speed_phase2: N/A\n",
6256                            checked,
6257                            lo->ll_objs_checked_phase2,
6258                            rtime,
6259                            lo->ll_run_time_phase2,
6260                            speed,
6261                            new_checked);
6262
6263                 if (likely(lfsck->li_di_oit)) {
6264                         const struct dt_it_ops *iops =
6265                                 &lfsck->li_obj_oit->do_index_ops->dio_it;
6266
6267                         /* The low layer otable-based iteration position may NOT
6268                          * exactly match the layout-based directory traversal
6269                          * cookie. Generally, it is not a serious issue. But the
6270                          * caller should NOT make assumption on that. */
6271                         pos = iops->store(env, lfsck->li_di_oit);
6272                         if (!lfsck->li_current_oit_processed)
6273                                 pos--;
6274                 } else {
6275                         pos = lo->ll_pos_last_checkpoint;
6276                 }
6277
6278                 seq_printf(m, "current_position: %llu\n", pos);
6279         } else if (lo->ll_status == LS_SCANNING_PHASE2) {
6280                 time64_t duration = ktime_get_seconds() -
6281                                     com->lc_time_last_checkpoint;
6282                 u64 checked = lo->ll_objs_checked_phase2 +
6283                               com->lc_new_checked;
6284                 u64 speed1 = lo->ll_objs_checked_phase1;
6285                 u64 speed2 = checked;
6286                 u64 new_checked = com->lc_new_checked;
6287                 time64_t rtime = lo->ll_run_time_phase2 + duration;
6288
6289                 if (duration != 0)
6290                         new_checked = div64_s64(new_checked, duration);
6291                 if (lo->ll_run_time_phase1 != 0)
6292                         speed1 = div64_s64(speed1, lo->ll_run_time_phase1);
6293                 if (rtime != 0)
6294                         speed2 = div64_s64(speed2, rtime);
6295                 seq_printf(m, "checked_phase1: %llu\n"
6296                            "checked_phase2: %llu\n"
6297                            "run_time_phase1: %lld seconds\n"
6298                            "run_time_phase2: %lld seconds\n"
6299                            "average_speed_phase1: %llu items/sec\n"
6300                            "average_speed_phase2: %llu items/sec\n"
6301                            "real_time_speed_phase1: N/A\n"
6302                            "real_time_speed_phase2: %llu items/sec\n"
6303                            "current_position: "DFID"\n",
6304                            lo->ll_objs_checked_phase1,
6305                            checked,
6306                            lo->ll_run_time_phase1,
6307                            rtime,
6308                            speed1,
6309                            speed2,
6310                            new_checked,
6311                            PFID(&com->lc_fid_latest_scanned_phase2));
6312         } else {
6313                 __u64 speed1 = lo->ll_objs_checked_phase1;
6314                 __u64 speed2 = lo->ll_objs_checked_phase2;
6315
6316                 if (lo->ll_run_time_phase1 != 0)
6317                         speed1 = div64_s64(speed1, lo->ll_run_time_phase1);
6318                 if (lo->ll_run_time_phase2 != 0)
6319                         speed2 = div64_s64(speed2, lo->ll_run_time_phase2);
6320                 seq_printf(m, "checked_phase1: %llu\n"
6321                            "checked_phase2: %llu\n"
6322                            "run_time_phase1: %lld seconds\n"
6323                            "run_time_phase2: %lld seconds\n"
6324                            "average_speed_phase1: %llu items/sec\n"
6325                            "average_speed_phase2: %llu objs/sec\n"
6326                            "real_time_speed_phase1: N/A\n"
6327                            "real_time_speed_phase2: N/A\n"
6328                            "current_position: N/A\n",
6329                            lo->ll_objs_checked_phase1,
6330                            lo->ll_objs_checked_phase2,
6331                            lo->ll_run_time_phase1,
6332                            lo->ll_run_time_phase2,
6333                            speed1,
6334                            speed2);
6335         }
6336
6337         up_read(&com->lc_sem);
6338 }
6339
6340 static int lfsck_layout_master_double_scan(const struct lu_env *env,
6341                                            struct lfsck_component *com)
6342 {
6343         struct lfsck_layout             *lo     = com->lc_file_ram;
6344         struct lfsck_assistant_data     *lad    = com->lc_data;
6345         struct lfsck_instance           *lfsck  = com->lc_lfsck;
6346         struct lfsck_tgt_descs          *ltds;
6347         struct lfsck_tgt_desc           *ltd;
6348         struct lfsck_tgt_desc           *next;
6349         int                              rc;
6350
6351         rc = lfsck_double_scan_generic(env, com, lo->ll_status);
6352
6353         if (thread_is_stopped(&lad->lad_thread)) {
6354                 LASSERT(list_empty(&lad->lad_req_list));
6355                 LASSERT(list_empty(&lad->lad_ost_phase1_list));
6356                 LASSERT(list_empty(&lad->lad_mdt_phase1_list));
6357
6358                 ltds = &lfsck->li_ost_descs;
6359                 spin_lock(&ltds->ltd_lock);
6360                 list_for_each_entry_safe(ltd, next, &lad->lad_ost_phase2_list,
6361                                          ltd_layout_phase_list) {
6362                         list_del_init(&ltd->ltd_layout_phase_list);
6363                 }
6364                 spin_unlock(&ltds->ltd_lock);
6365
6366                 ltds = &lfsck->li_mdt_descs;
6367                 spin_lock(&ltds->ltd_lock);
6368                 list_for_each_entry_safe(ltd, next, &lad->lad_mdt_phase2_list,
6369                                          ltd_layout_phase_list) {
6370                         list_del_init(&ltd->ltd_layout_phase_list);
6371                 }
6372                 spin_unlock(&ltds->ltd_lock);
6373         }
6374
6375         return rc;
6376 }
6377
6378 static int lfsck_layout_slave_double_scan(const struct lu_env *env,
6379                                           struct lfsck_component *com)
6380 {
6381         struct lfsck_instance           *lfsck  = com->lc_lfsck;
6382         struct lfsck_layout_slave_data  *llsd   = com->lc_data;
6383         struct lfsck_layout             *lo     = com->lc_file_ram;
6384         struct ptlrpc_thread            *thread = &lfsck->li_thread;
6385         int                              rc;
6386         ENTRY;
6387
6388         CDEBUG(D_LFSCK, "%s: layout LFSCK slave phase2 scan start\n",
6389                lfsck_lfsck2name(lfsck));
6390
6391         atomic_inc(&lfsck->li_double_scan_count);
6392
6393         if (lo->ll_flags & LF_INCOMPLETE)
6394                 GOTO(done, rc = 1);
6395
6396         com->lc_new_checked = 0;
6397         com->lc_new_scanned = 0;
6398         com->lc_time_last_checkpoint = ktime_get_seconds();
6399         com->lc_time_next_checkpoint = com->lc_time_last_checkpoint +
6400                                        LFSCK_CHECKPOINT_INTERVAL;
6401
6402         while (1) {
6403                 rc = lfsck_layout_slave_query_master(env, com);
6404                 if (list_empty(&llsd->llsd_master_list)) {
6405                         if (unlikely(!thread_is_running(thread)))
6406                                 rc = 0;
6407                         else
6408                                 rc = 1;
6409
6410                         GOTO(done, rc);
6411                 }
6412
6413                 if (rc < 0)
6414                         GOTO(done, rc);
6415
6416                 rc = wait_event_idle_timeout(
6417                         thread->t_ctl_waitq,
6418                         !thread_is_running(thread) ||
6419                         lo->ll_flags & LF_INCOMPLETE ||
6420                         list_empty(&llsd->llsd_master_list),
6421                         cfs_time_seconds(30));
6422                 if (unlikely(!thread_is_running(thread)))
6423                         GOTO(done, rc = 0);
6424
6425                 if (lo->ll_flags & LF_INCOMPLETE)
6426                         GOTO(done, rc = 1);
6427
6428                 if (rc == 0)
6429                         continue;
6430
6431                 GOTO(done, rc = 1);
6432         }
6433
6434 done:
6435         rc = lfsck_layout_double_scan_result(env, com, rc);
6436         lfsck_layout_slave_notify_master(env, com, LE_PHASE2_DONE,
6437                         (rc > 0 && lo->ll_flags & LF_INCOMPLETE) ? 0 : rc);
6438         lfsck_layout_slave_quit(env, com);
6439         if (atomic_dec_and_test(&lfsck->li_double_scan_count))
6440                 wake_up(&lfsck->li_thread.t_ctl_waitq);
6441
6442         CDEBUG(D_LFSCK, "%s: layout LFSCK slave phase2 scan finished, "
6443                "status %d: rc = %d\n",
6444                lfsck_lfsck2name(lfsck), lo->ll_status, rc);
6445
6446         return rc;
6447 }
6448
6449 static void lfsck_layout_master_data_release(const struct lu_env *env,
6450                                              struct lfsck_component *com)
6451 {
6452         struct lfsck_assistant_data     *lad    = com->lc_data;
6453         struct lfsck_instance           *lfsck  = com->lc_lfsck;
6454         struct lfsck_tgt_descs          *ltds;
6455         struct lfsck_tgt_desc           *ltd;
6456         struct lfsck_tgt_desc           *next;
6457
6458         LASSERT(lad != NULL);
6459         LASSERT(thread_is_init(&lad->lad_thread) ||
6460                 thread_is_stopped(&lad->lad_thread));
6461         LASSERT(list_empty(&lad->lad_req_list));
6462
6463         com->lc_data = NULL;
6464
6465         ltds = &lfsck->li_ost_descs;
6466         spin_lock(&ltds->ltd_lock);
6467         list_for_each_entry_safe(ltd, next, &lad->lad_ost_phase1_list,
6468                                  ltd_layout_phase_list) {
6469                 list_del_init(&ltd->ltd_layout_phase_list);
6470         }
6471         list_for_each_entry_safe(ltd, next, &lad->lad_ost_phase2_list,
6472                                  ltd_layout_phase_list) {
6473                 list_del_init(&ltd->ltd_layout_phase_list);
6474         }
6475         list_for_each_entry_safe(ltd, next, &lad->lad_ost_list,
6476                                  ltd_layout_list) {
6477                 list_del_init(&ltd->ltd_layout_list);
6478         }
6479         spin_unlock(&ltds->ltd_lock);
6480
6481         ltds = &lfsck->li_mdt_descs;
6482         spin_lock(&ltds->ltd_lock);
6483         list_for_each_entry_safe(ltd, next, &lad->lad_mdt_phase1_list,
6484                                  ltd_layout_phase_list) {
6485                 list_del_init(&ltd->ltd_layout_phase_list);
6486         }
6487         list_for_each_entry_safe(ltd, next, &lad->lad_mdt_phase2_list,
6488                                  ltd_layout_phase_list) {
6489                 list_del_init(&ltd->ltd_layout_phase_list);
6490         }
6491         list_for_each_entry_safe(ltd, next, &lad->lad_mdt_list,
6492                                  ltd_layout_list) {
6493                 list_del_init(&ltd->ltd_layout_list);
6494         }
6495         spin_unlock(&ltds->ltd_lock);
6496
6497         bitmap_free(lad->lad_bitmap);
6498
6499         OBD_FREE_PTR(lad);
6500 }
6501
6502 static void lfsck_layout_slave_data_release(const struct lu_env *env,
6503                                             struct lfsck_component *com)
6504 {
6505         struct lfsck_layout_slave_data *llsd = com->lc_data;
6506
6507         lfsck_layout_slave_quit(env, com);
6508         com->lc_data = NULL;
6509         OBD_FREE_PTR(llsd);
6510 }
6511
6512 static void lfsck_layout_master_quit(const struct lu_env *env,
6513                                      struct lfsck_component *com)
6514 {
6515         struct lfsck_assistant_data     *lad    = com->lc_data;
6516         struct lfsck_instance           *lfsck  = com->lc_lfsck;
6517         struct lfsck_tgt_descs          *ltds;
6518         struct lfsck_tgt_desc           *ltd;
6519         struct lfsck_tgt_desc           *next;
6520
6521         LASSERT(lad != NULL);
6522
6523         lfsck_quit_generic(env, com);
6524
6525         LASSERT(thread_is_init(&lad->lad_thread) ||
6526                 thread_is_stopped(&lad->lad_thread));
6527         LASSERT(list_empty(&lad->lad_req_list));
6528
6529         ltds = &lfsck->li_ost_descs;
6530         spin_lock(&ltds->ltd_lock);
6531         list_for_each_entry_safe(ltd, next, &lad->lad_ost_phase1_list,
6532                                  ltd_layout_phase_list) {
6533                 list_del_init(&ltd->ltd_layout_phase_list);
6534         }
6535         list_for_each_entry_safe(ltd, next, &lad->lad_ost_phase2_list,
6536                                  ltd_layout_phase_list) {
6537                 list_del_init(&ltd->ltd_layout_phase_list);
6538         }
6539         spin_unlock(&ltds->ltd_lock);
6540
6541         ltds = &lfsck->li_mdt_descs;
6542         spin_lock(&ltds->ltd_lock);
6543         list_for_each_entry_safe(ltd, next, &lad->lad_mdt_phase1_list,
6544                                  ltd_layout_phase_list) {
6545                 list_del_init(&ltd->ltd_layout_phase_list);
6546         }
6547         list_for_each_entry_safe(ltd, next, &lad->lad_mdt_phase2_list,
6548                                  ltd_layout_phase_list) {
6549                 list_del_init(&ltd->ltd_layout_phase_list);
6550         }
6551         spin_unlock(&ltds->ltd_lock);
6552 }
6553
6554 static void lfsck_layout_slave_quit(const struct lu_env *env,
6555                                     struct lfsck_component *com)
6556 {
6557         struct lfsck_layout_slave_data   *llsd  = com->lc_data;
6558         struct lfsck_layout_seq          *lls;
6559         struct lfsck_layout_seq          *next;
6560         struct lfsck_layout_slave_target *llst;
6561
6562         LASSERT(llsd != NULL);
6563
6564         down_write(&com->lc_sem);
6565         list_for_each_entry_safe(lls, next, &llsd->llsd_seq_list,
6566                                  lls_list) {
6567                 list_del_init(&lls->lls_list);
6568                 lfsck_object_put(env, lls->lls_lastid_obj);
6569                 OBD_FREE_PTR(lls);
6570         }
6571         up_write(&com->lc_sem);
6572
6573         spin_lock(&llsd->llsd_lock);
6574         while (!list_empty(&llsd->llsd_master_list)) {
6575                 llst = list_entry(llsd->llsd_master_list.next,
6576                                   struct lfsck_layout_slave_target, llst_list);
6577                 list_del_init(&llst->llst_list);
6578                 spin_unlock(&llsd->llsd_lock);
6579                 lfsck_layout_llst_put(llst);
6580                 spin_lock(&llsd->llsd_lock);
6581         }
6582         spin_unlock(&llsd->llsd_lock);
6583
6584         lfsck_rbtree_cleanup(env, com);
6585 }
6586
6587 static int lfsck_layout_master_in_notify(const struct lu_env *env,
6588                                          struct lfsck_component *com,
6589                                          struct lfsck_request *lr)
6590 {
6591         struct lfsck_instance           *lfsck = com->lc_lfsck;
6592         struct lfsck_layout             *lo    = com->lc_file_ram;
6593         struct lfsck_assistant_data     *lad   = com->lc_data;
6594         struct lfsck_tgt_descs          *ltds;
6595         struct lfsck_tgt_desc           *ltd;
6596         bool                             fail  = false;
6597         ENTRY;
6598
6599         if (lr->lr_event == LE_PAIRS_VERIFY) {
6600                 int rc;
6601
6602                 rc = lfsck_layout_master_check_pairs(env, com, &lr->lr_fid,
6603                                                      &lr->lr_fid2,
6604                                                      lr->lr_comp_id);
6605
6606                 RETURN(rc);
6607         }
6608
6609         CDEBUG(D_LFSCK, "%s: layout LFSCK master handles notify %u "
6610                "from %s %x, status %d, flags %x, flags2 %x\n",
6611                lfsck_lfsck2name(lfsck), lr->lr_event,
6612                (lr->lr_flags & LEF_FROM_OST) ? "OST" : "MDT",
6613                lr->lr_index, lr->lr_status, lr->lr_flags, lr->lr_flags2);
6614
6615         if (lr->lr_event != LE_PHASE1_DONE &&
6616             lr->lr_event != LE_PHASE2_DONE &&
6617             lr->lr_event != LE_PEER_EXIT)
6618                 RETURN(-EINVAL);
6619
6620         if (lr->lr_flags & LEF_FROM_OST)
6621                 ltds = &lfsck->li_ost_descs;
6622         else
6623                 ltds = &lfsck->li_mdt_descs;
6624         spin_lock(&ltds->ltd_lock);
6625         ltd = lfsck_ltd2tgt(ltds, lr->lr_index);
6626         if (ltd == NULL) {
6627                 spin_unlock(&ltds->ltd_lock);
6628
6629                 RETURN(-ENXIO);
6630         }
6631
6632         list_del_init(&ltd->ltd_layout_phase_list);
6633         switch (lr->lr_event) {
6634         case LE_PHASE1_DONE:
6635                 if (lr->lr_status <= 0 || lr->lr_flags2 & LF_INCOMPLETE) {
6636                         if (lr->lr_flags2 & LF_INCOMPLETE) {
6637                                 if (lr->lr_flags & LEF_FROM_OST)
6638                                         lfsck_lad_set_bitmap(env, com,
6639                                                              ltd->ltd_index);
6640                                 else
6641                                         lo->ll_flags |= LF_INCOMPLETE;
6642                         }
6643                         ltd->ltd_layout_done = 1;
6644                         list_del_init(&ltd->ltd_layout_list);
6645                         fail = true;
6646                         break;
6647                 }
6648
6649                 if (lr->lr_flags & LEF_FROM_OST) {
6650                         if (list_empty(&ltd->ltd_layout_list))
6651                                 list_add_tail(&ltd->ltd_layout_list,
6652                                               &lad->lad_ost_list);
6653                         list_add_tail(&ltd->ltd_layout_phase_list,
6654                                       &lad->lad_ost_phase2_list);
6655                 } else {
6656                         if (list_empty(&ltd->ltd_layout_list))
6657                                 list_add_tail(&ltd->ltd_layout_list,
6658                                               &lad->lad_mdt_list);
6659                         list_add_tail(&ltd->ltd_layout_phase_list,
6660                                       &lad->lad_mdt_phase2_list);
6661                 }
6662                 break;
6663         case LE_PHASE2_DONE:
6664                 ltd->ltd_layout_done = 1;
6665                 if (!list_empty(&ltd->ltd_layout_list))
6666                         list_del_init(&ltd->ltd_layout_list);
6667
6668                 if (lr->lr_flags2 & LF_INCOMPLETE) {
6669                         lfsck_lad_set_bitmap(env, com, ltd->ltd_index);
6670                         fail = true;
6671                 }
6672
6673                 break;
6674         case LE_PEER_EXIT:
6675                 fail = true;
6676                 ltd->ltd_layout_done = 1;
6677                 list_del_init(&ltd->ltd_layout_list);
6678                 if (!(lfsck->li_bookmark_ram.lb_param & LPF_FAILOUT) &&
6679                     !(lr->lr_flags & LEF_FROM_OST))
6680                                 lo->ll_flags |= LF_INCOMPLETE;
6681                 break;
6682         default:
6683                 break;
6684         }
6685         spin_unlock(&ltds->ltd_lock);
6686
6687         if (fail && lfsck->li_bookmark_ram.lb_param & LPF_FAILOUT) {
6688                 struct lfsck_stop *stop = &lfsck_env_info(env)->lti_stop;
6689
6690                 memset(stop, 0, sizeof(*stop));
6691                 stop->ls_status = lr->lr_status;
6692                 stop->ls_flags = lr->lr_param & ~LPF_BROADCAST;
6693                 lfsck_stop(env, lfsck->li_bottom, stop);
6694         } else if (lfsck_phase2_next_ready(lad)) {
6695                 wake_up(&lad->lad_thread.t_ctl_waitq);
6696         }
6697
6698         RETURN(0);
6699 }
6700
6701 static int lfsck_layout_slave_in_notify_local(const struct lu_env *env,
6702                                               struct lfsck_component *com,
6703                                               struct lfsck_req_local *lrl,
6704                                               struct thandle *th)
6705 {
6706         ENTRY;
6707
6708         switch (lrl->lrl_event) {
6709         case LEL_FID_ACCESSED:
6710                 lfsck_rbtree_update_bitmap(env, com, &lrl->lrl_fid, true);
6711                 RETURN(0);
6712         case LEL_PAIRS_VERIFY_LOCAL: {
6713                 int rc;
6714
6715                 lrl->lrl_status = LPVS_INIT;
6716                 /* Firstly, if the MDT-object which is claimed via OST-object
6717                  * local stored PFID xattr recognizes the OST-object, then it
6718                  * must be that the client given PFID is wrong. */
6719                 rc = lfsck_layout_slave_check_pairs(env, com, &lrl->lrl_fid,
6720                                 &lrl->lrl_ff_local.ff_parent,
6721                                 lrl->lrl_ff_local.ff_layout.ol_comp_id);
6722                 if (rc <= 0)
6723                         RETURN(0);
6724
6725                 lrl->lrl_status = LPVS_INCONSISTENT;
6726                 /* The OST-object local stored PFID xattr is stale. We need to
6727                  * check whether the MDT-object that is claimed via the client
6728                  * given PFID information recognizes the OST-object or not. If
6729                  * matches, then need to update the OST-object's PFID xattr. */
6730                 rc = lfsck_layout_slave_check_pairs(env, com, &lrl->lrl_fid,
6731                                 &lrl->lrl_ff_client.ff_parent,
6732                                 lrl->lrl_ff_client.ff_layout.ol_comp_id);
6733                 /* For rc < 0 case:
6734                  * We are not sure whether the client given PFID information
6735                  * is correct or not, do nothing to avoid improper fixing.
6736                  *
6737                  * For rc > 0 case:
6738                  * The client given PFID information is also invalid, we can
6739                  * NOT fix the OST-object inconsistency.
6740                  */
6741                 if (!rc) {
6742                         lrl->lrl_status = LPVS_INCONSISTENT_TOFIX;
6743                         rc = lfsck_layout_slave_repair_pfid(env, com, lrl);
6744                 }
6745
6746                 RETURN(rc);
6747         }
6748         default:
6749                 break;
6750         }
6751
6752         RETURN(-EOPNOTSUPP);
6753 }
6754
6755 static int lfsck_layout_slave_in_notify(const struct lu_env *env,
6756                                         struct lfsck_component *com,
6757                                         struct lfsck_request *lr)
6758 {
6759         struct lfsck_instance *lfsck = com->lc_lfsck;
6760         struct lfsck_layout_slave_data *llsd = com->lc_data;
6761         struct lfsck_layout_slave_target *llst;
6762         int rc;
6763         ENTRY;
6764
6765         switch (lr->lr_event) {
6766         case LE_CONDITIONAL_DESTROY:
6767                 rc = lfsck_layout_slave_conditional_destroy(env, com, lr);
6768                 RETURN(rc);
6769         case LE_PHASE1_DONE: {
6770                 if (lr->lr_flags2 & LF_INCOMPLETE) {
6771                         struct lfsck_layout *lo = com->lc_file_ram;
6772
6773                         lo->ll_flags |= LF_INCOMPLETE;
6774                         llst = lfsck_layout_llst_find_and_del(llsd,
6775                                                               lr->lr_index,
6776                                                               true);
6777                         if (llst != NULL) {
6778                                 lfsck_layout_llst_put(llst);
6779                                 wake_up(&lfsck->li_thread.t_ctl_waitq);
6780                         }
6781                 }
6782
6783                 RETURN(0);
6784         }
6785         case LE_PHASE2_DONE:
6786         case LE_PEER_EXIT:
6787                 CDEBUG(D_LFSCK, "%s: layout LFSCK slave handle notify %u "
6788                        "from MDT %x, status %d\n", lfsck_lfsck2name(lfsck),
6789                        lr->lr_event, lr->lr_index, lr->lr_status);
6790                 break;
6791         default:
6792                 RETURN(-EINVAL);
6793         }
6794
6795         llst = lfsck_layout_llst_find_and_del(llsd, lr->lr_index, true);
6796         if (llst == NULL)
6797                 RETURN(0);
6798
6799         lfsck_layout_llst_put(llst);
6800         if (list_empty(&llsd->llsd_master_list))
6801                 wake_up(&lfsck->li_thread.t_ctl_waitq);
6802
6803         if (lr->lr_event == LE_PEER_EXIT &&
6804             (lfsck->li_bookmark_ram.lb_param & LPF_FAILOUT ||
6805              (list_empty(&llsd->llsd_master_list) &&
6806               (lr->lr_status == LS_STOPPED ||
6807                lr->lr_status == LS_CO_STOPPED)))) {
6808                 struct lfsck_stop *stop = &lfsck_env_info(env)->lti_stop;
6809
6810                 memset(stop, 0, sizeof(*stop));
6811                 stop->ls_status = lr->lr_status;
6812                 stop->ls_flags = lr->lr_param & ~LPF_BROADCAST;
6813                 lfsck_stop(env, lfsck->li_bottom, stop);
6814         }
6815
6816         RETURN(0);
6817 }
6818
6819 static void lfsck_layout_repaired(struct lfsck_layout *lo, __u64 *count)
6820 {
6821         int i;
6822
6823         for (i = 0; i < LLIT_MAX; i++)
6824                 *count += lo->ll_objs_repaired[i];
6825 }
6826
6827 static int lfsck_layout_query_all(const struct lu_env *env,
6828                                   struct lfsck_component *com,
6829                                   __u32 *mdts_count, __u32 *osts_count,
6830                                   __u64 *repaired)
6831 {
6832         struct lfsck_layout *lo = com->lc_file_ram;
6833         struct lfsck_tgt_descs *ltds;
6834         struct lfsck_tgt_desc *ltd;
6835         int idx;
6836         int rc;
6837         ENTRY;
6838
6839         rc = lfsck_query_all(env, com);
6840         if (rc != 0)
6841                 RETURN(rc);
6842
6843         ltds = &com->lc_lfsck->li_mdt_descs;
6844         down_read(&ltds->ltd_rw_sem);
6845         for_each_set_bit(idx, ltds->ltd_tgts_bitmap, ltds->ltd_tgts_mask_len) {
6846                 ltd = lfsck_ltd2tgt(ltds, idx);
6847                 LASSERT(ltd != NULL);
6848
6849                 mdts_count[ltd->ltd_layout_status]++;
6850                 *repaired += ltd->ltd_layout_repaired;
6851         }
6852         up_read(&ltds->ltd_rw_sem);
6853
6854         ltds = &com->lc_lfsck->li_ost_descs;
6855         down_read(&ltds->ltd_rw_sem);
6856         for_each_set_bit(idx, ltds->ltd_tgts_bitmap, ltds->ltd_tgts_mask_len) {
6857                 ltd = lfsck_ltd2tgt(ltds, idx);
6858                 LASSERT(ltd != NULL);
6859
6860                 osts_count[ltd->ltd_layout_status]++;
6861                 *repaired += ltd->ltd_layout_repaired;
6862         }
6863         up_read(&ltds->ltd_rw_sem);
6864
6865         down_read(&com->lc_sem);
6866         mdts_count[lo->ll_status]++;
6867         lfsck_layout_repaired(lo, repaired);
6868         up_read(&com->lc_sem);
6869
6870         RETURN(0);
6871 }
6872
6873 static int lfsck_layout_query(const struct lu_env *env,
6874                               struct lfsck_component *com,
6875                               struct lfsck_request *req,
6876                               struct lfsck_reply *rep,
6877                               struct lfsck_query *que, int idx)
6878 {
6879         struct lfsck_layout *lo = com->lc_file_ram;
6880         int rc = 0;
6881
6882         if (que != NULL) {
6883                 LASSERT(com->lc_lfsck->li_master);
6884
6885                 rc = lfsck_layout_query_all(env, com,
6886                                             que->lu_mdts_count[idx],
6887                                             que->lu_osts_count[idx],
6888                                             &que->lu_repaired[idx]);
6889         } else {
6890                 down_read(&com->lc_sem);
6891                 rep->lr_status = lo->ll_status;
6892                 if (req->lr_flags & LEF_QUERY_ALL)
6893                         lfsck_layout_repaired(lo, &rep->lr_repaired);
6894                 up_read(&com->lc_sem);
6895         }
6896
6897         return rc;
6898 }
6899
6900 /* with lfsck::li_lock held */
6901 static int lfsck_layout_slave_join(const struct lu_env *env,
6902                                    struct lfsck_component *com,
6903                                    struct lfsck_start_param *lsp)
6904 {
6905         struct lfsck_instance            *lfsck = com->lc_lfsck;
6906         struct lfsck_layout_slave_data   *llsd  = com->lc_data;
6907         struct lfsck_layout_slave_target *llst;
6908         struct lfsck_start               *start = lsp->lsp_start;
6909         int                               rc    = 0;
6910         ENTRY;
6911
6912         if (start == NULL || !(start->ls_flags & LPF_OST_ORPHAN))
6913                 RETURN(0);
6914
6915         if (!lsp->lsp_index_valid)
6916                 RETURN(-EINVAL);
6917
6918         /* If someone is running the LFSCK without orphan handling,
6919          * it will not maintain the object accessing rbtree. So we
6920          * cannot join it for orphan handling. */
6921         if (!llsd->llsd_rbtree_valid)
6922                 RETURN(-EBUSY);
6923
6924         spin_unlock(&lfsck->li_lock);
6925         rc = lfsck_layout_llst_add(llsd, lsp->lsp_index);
6926         spin_lock(&lfsck->li_lock);
6927         if (rc == 0 && !thread_is_running(&lfsck->li_thread)) {
6928                 spin_unlock(&lfsck->li_lock);
6929                 llst = lfsck_layout_llst_find_and_del(llsd, lsp->lsp_index,
6930                                                       true);
6931                 if (llst != NULL)
6932                         lfsck_layout_llst_put(llst);
6933                 spin_lock(&lfsck->li_lock);
6934                 rc = -EAGAIN;
6935         }
6936
6937         RETURN(rc);
6938 }
6939
6940 static const struct lfsck_operations lfsck_layout_master_ops = {
6941         .lfsck_reset            = lfsck_layout_reset,
6942         .lfsck_fail             = lfsck_layout_fail,
6943         .lfsck_checkpoint       = lfsck_layout_master_checkpoint,
6944         .lfsck_prep             = lfsck_layout_master_prep,
6945         .lfsck_exec_oit         = lfsck_layout_master_exec_oit,
6946         .lfsck_exec_dir         = lfsck_layout_exec_dir,
6947         .lfsck_post             = lfsck_layout_master_post,
6948         .lfsck_dump             = lfsck_layout_dump,
6949         .lfsck_double_scan      = lfsck_layout_master_double_scan,
6950         .lfsck_data_release     = lfsck_layout_master_data_release,
6951         .lfsck_quit             = lfsck_layout_master_quit,
6952         .lfsck_in_notify        = lfsck_layout_master_in_notify,
6953         .lfsck_query            = lfsck_layout_query,
6954 };
6955
6956 static const struct lfsck_operations lfsck_layout_slave_ops = {
6957         .lfsck_reset            = lfsck_layout_reset,
6958         .lfsck_fail             = lfsck_layout_fail,
6959         .lfsck_checkpoint       = lfsck_layout_slave_checkpoint,
6960         .lfsck_prep             = lfsck_layout_slave_prep,
6961         .lfsck_exec_oit         = lfsck_layout_slave_exec_oit,
6962         .lfsck_exec_dir         = lfsck_layout_exec_dir,
6963         .lfsck_post             = lfsck_layout_slave_post,
6964         .lfsck_dump             = lfsck_layout_dump,
6965         .lfsck_double_scan      = lfsck_layout_slave_double_scan,
6966         .lfsck_data_release     = lfsck_layout_slave_data_release,
6967         .lfsck_quit             = lfsck_layout_slave_quit,
6968         .lfsck_in_notify_local  = lfsck_layout_slave_in_notify_local,
6969         .lfsck_in_notify        = lfsck_layout_slave_in_notify,
6970         .lfsck_query            = lfsck_layout_query,
6971         .lfsck_join             = lfsck_layout_slave_join,
6972 };
6973
6974 static void lfsck_layout_assistant_fill_pos(const struct lu_env *env,
6975                                             struct lfsck_component *com,
6976                                             struct lfsck_position *pos)
6977 {
6978         struct lfsck_assistant_data     *lad = com->lc_data;
6979         struct lfsck_layout_req         *llr;
6980
6981         if (((struct lfsck_layout *)(com->lc_file_ram))->ll_status !=
6982             LS_SCANNING_PHASE1)
6983                 return;
6984
6985         if (list_empty(&lad->lad_req_list))
6986                 return;
6987
6988         llr = list_entry(lad->lad_req_list.next,
6989                          struct lfsck_layout_req,
6990                          llr_lar.lar_list);
6991         pos->lp_oit_cookie = llr->llr_lar.lar_parent->lso_oit_cookie - 1;
6992 }
6993
6994 const struct lfsck_assistant_operations lfsck_layout_assistant_ops = {
6995         .la_handler_p1          = lfsck_layout_assistant_handler_p1,
6996         .la_handler_p2          = lfsck_layout_assistant_handler_p2,
6997         .la_fill_pos            = lfsck_layout_assistant_fill_pos,
6998         .la_double_scan_result  = lfsck_layout_double_scan_result,
6999         .la_req_fini            = lfsck_layout_assistant_req_fini,
7000         .la_sync_failures       = lfsck_layout_assistant_sync_failures,
7001 };
7002
7003 int lfsck_layout_setup(const struct lu_env *env, struct lfsck_instance *lfsck)
7004 {
7005         struct lfsck_component  *com;
7006         struct lfsck_layout     *lo;
7007         struct dt_object        *root = NULL;
7008         struct dt_object        *obj;
7009         int                      i;
7010         int                      rc;
7011         ENTRY;
7012
7013         OBD_ALLOC_PTR(com);
7014         if (com == NULL)
7015                 RETURN(-ENOMEM);
7016
7017         INIT_LIST_HEAD(&com->lc_link);
7018         INIT_LIST_HEAD(&com->lc_link_dir);
7019         init_rwsem(&com->lc_sem);
7020         atomic_set(&com->lc_ref, 1);
7021         com->lc_lfsck = lfsck;
7022         com->lc_type = LFSCK_TYPE_LAYOUT;
7023         if (lfsck->li_master) {
7024                 com->lc_ops = &lfsck_layout_master_ops;
7025                 com->lc_data = lfsck_assistant_data_init(
7026                                 &lfsck_layout_assistant_ops,
7027                                 LFSCK_LAYOUT);
7028                 if (com->lc_data == NULL)
7029                         GOTO(out, rc = -ENOMEM);
7030
7031                 for (i = 0; i < LFSCK_STF_COUNT; i++)
7032                         mutex_init(&com->lc_sub_trace_objs[i].lsto_mutex);
7033         } else {
7034                 struct lfsck_layout_slave_data *llsd;
7035
7036                 com->lc_ops = &lfsck_layout_slave_ops;
7037                 OBD_ALLOC_PTR(llsd);
7038                 if (llsd == NULL)
7039                         GOTO(out, rc = -ENOMEM);
7040
7041                 INIT_LIST_HEAD(&llsd->llsd_seq_list);
7042                 INIT_LIST_HEAD(&llsd->llsd_master_list);
7043                 spin_lock_init(&llsd->llsd_lock);
7044                 llsd->llsd_rb_root = RB_ROOT;
7045                 init_rwsem(&llsd->llsd_rb_rwsem);
7046                 com->lc_data = llsd;
7047         }
7048         com->lc_file_size = sizeof(*lo);
7049         OBD_ALLOC(com->lc_file_ram, com->lc_file_size);
7050         if (com->lc_file_ram == NULL)
7051                 GOTO(out, rc = -ENOMEM);
7052
7053         OBD_ALLOC(com->lc_file_disk, com->lc_file_size);
7054         if (com->lc_file_disk == NULL)
7055                 GOTO(out, rc = -ENOMEM);
7056
7057         root = dt_locate(env, lfsck->li_bottom, &lfsck->li_local_root_fid);
7058         if (IS_ERR(root))
7059                 GOTO(out, rc = PTR_ERR(root));
7060
7061         if (unlikely(!dt_try_as_dir(env, root, true)))
7062                 GOTO(out, rc = -ENOTDIR);
7063
7064         obj = local_file_find_or_create(env, lfsck->li_los, root,
7065                                         LFSCK_LAYOUT,
7066                                         S_IFREG | S_IRUGO | S_IWUSR);
7067         if (IS_ERR(obj))
7068                 GOTO(out, rc = PTR_ERR(obj));
7069
7070         com->lc_obj = obj;
7071         rc = lfsck_layout_load(env, com);
7072         if (rc > 0) {
7073                 rc = lfsck_layout_reset(env, com, true);
7074         } else if (rc == -ENOENT) {
7075                 rc = lfsck_layout_init(env, com);
7076         } else if (lfsck->li_master) {
7077                 rc = lfsck_load_sub_trace_files(env, com,
7078                                 &dt_lfsck_layout_dangling_features,
7079                                 LFSCK_LAYOUT, false);
7080                 if (rc)
7081                         rc = lfsck_layout_reset(env, com, true);
7082         }
7083
7084         if (rc != 0)
7085                 GOTO(out, rc);
7086
7087         lo = com->lc_file_ram;
7088         switch (lo->ll_status) {
7089         case LS_INIT:
7090         case LS_COMPLETED:
7091         case LS_FAILED:
7092         case LS_STOPPED:
7093         case LS_PARTIAL:
7094                 spin_lock(&lfsck->li_lock);
7095                 list_add_tail(&com->lc_link, &lfsck->li_list_idle);
7096                 spin_unlock(&lfsck->li_lock);
7097                 break;
7098         default:
7099                 CERROR("%s: unknown lfsck_layout status %d\n",
7100                        lfsck_lfsck2name(lfsck), lo->ll_status);
7101                 fallthrough;
7102         case LS_SCANNING_PHASE1:
7103         case LS_SCANNING_PHASE2:
7104                 /* No need to store the status to disk right now.
7105                  * If the system crashed before the status stored,
7106                  * it will be loaded back when next time. */
7107                 lo->ll_status = LS_CRASHED;
7108                 if (!lfsck->li_master)
7109                         lo->ll_flags |= LF_INCOMPLETE;
7110                 fallthrough;
7111         case LS_PAUSED:
7112         case LS_CRASHED:
7113         case LS_CO_FAILED:
7114         case LS_CO_STOPPED:
7115         case LS_CO_PAUSED:
7116                 spin_lock(&lfsck->li_lock);
7117                 list_add_tail(&com->lc_link, &lfsck->li_list_scan);
7118                 spin_unlock(&lfsck->li_lock);
7119                 break;
7120         }
7121
7122         if (lo->ll_flags & LF_CRASHED_LASTID) {
7123                 LASSERT(lfsck->li_out_notify != NULL);
7124
7125                 lfsck->li_out_notify(env, lfsck->li_out_notify_data,
7126                                      LE_LASTID_REBUILDING);
7127         }
7128
7129         GOTO(out, rc = 0);
7130
7131 out:
7132         if (root != NULL && !IS_ERR(root))
7133                 lfsck_object_put(env, root);
7134
7135         if (rc != 0) {
7136                 lfsck_component_cleanup(env, com);
7137                 CERROR("%s: fail to init layout LFSCK component: rc = %d\n",
7138                        lfsck_lfsck2name(lfsck), rc);
7139         }
7140
7141         return rc;
7142 }
7143
7144 struct lfsck_orphan_it {
7145         struct lfsck_component           *loi_com;
7146         struct lfsck_rbtree_node         *loi_lrn;
7147         struct lfsck_layout_slave_target *loi_llst;
7148         struct lu_fid                     loi_key;
7149         struct lu_orphan_rec_v3           loi_rec;
7150         __u64                             loi_hash;
7151         unsigned int                      loi_over:1;
7152 };
7153
7154 static int lfsck_fid_match_idx(const struct lu_env *env,
7155                                struct lfsck_instance *lfsck,
7156                                const struct lu_fid *fid, int idx)
7157 {
7158         struct seq_server_site  *ss;
7159         struct lu_server_fld    *sf;
7160         struct lu_seq_range     *range = &lfsck_env_info(env)->lti_range;
7161         int                      rc;
7162
7163         /* All abnormal cases will be returned to MDT0. */
7164         if (!fid_is_norm(fid)) {
7165                 if (idx == 0)
7166                         return 1;
7167
7168                 return 0;
7169         }
7170
7171         ss = lfsck_dev_site(lfsck);
7172         if (unlikely(ss == NULL))
7173                 return -ENOTCONN;
7174
7175         sf = ss->ss_server_fld;
7176         LASSERT(sf != NULL);
7177
7178         fld_range_set_any(range);
7179         rc = fld_server_lookup(env, sf, fid_seq(fid), range);
7180         if (rc != 0)
7181                 return rc;
7182
7183         if (!fld_range_is_mdt(range))
7184                 return -EINVAL;
7185
7186         if (range->lsr_index == idx)
7187                 return 1;
7188
7189         return 0;
7190 }
7191
7192 static void lfsck_layout_destroy_orphan(const struct lu_env *env,
7193                                         struct lfsck_instance *lfsck,
7194                                         struct dt_object *obj)
7195 {
7196         struct dt_device        *dev    = lfsck_obj2dev(obj);
7197         struct thandle          *handle;
7198         int                      rc;
7199         ENTRY;
7200
7201         handle = lfsck_trans_create(env, dev, lfsck);
7202         if (IS_ERR(handle))
7203                 RETURN_EXIT;
7204
7205         rc = dt_declare_ref_del(env, obj, handle);
7206         if (rc != 0)
7207                 GOTO(stop, rc);
7208
7209         rc = dt_declare_destroy(env, obj, handle);
7210         if (rc != 0)
7211                 GOTO(stop, rc);
7212
7213         rc = dt_trans_start_local(env, dev, handle);
7214         if (rc != 0)
7215                 GOTO(stop, rc);
7216
7217         dt_write_lock(env, obj, 0);
7218         rc = dt_ref_del(env, obj, handle);
7219         if (rc == 0)
7220                 rc = dt_destroy(env, obj, handle);
7221         dt_write_unlock(env, obj);
7222
7223         GOTO(stop, rc);
7224
7225 stop:
7226         dt_trans_stop(env, dev, handle);
7227
7228         CDEBUG(D_LFSCK, "destroy orphan OST-object "DFID": rc = %d\n",
7229                PFID(lfsck_dto2fid(obj)), rc);
7230
7231         RETURN_EXIT;
7232 }
7233
7234 static int lfsck_orphan_index_lookup(const struct lu_env *env,
7235                                      struct dt_object *dt,
7236                                      struct dt_rec *rec,
7237                                      const struct dt_key *key)
7238 {
7239         return -EOPNOTSUPP;
7240 }
7241
7242 static int lfsck_orphan_index_declare_insert(const struct lu_env *env,
7243                                              struct dt_object *dt,
7244                                              const struct dt_rec *rec,
7245                                              const struct dt_key *key,
7246                                              struct thandle *handle)
7247 {
7248         return -EOPNOTSUPP;
7249 }
7250
7251 static int lfsck_orphan_index_insert(const struct lu_env *env,
7252                                      struct dt_object *dt,
7253                                      const struct dt_rec *rec,
7254                                      const struct dt_key *key,
7255                                      struct thandle *handle)
7256 {
7257         return -EOPNOTSUPP;
7258 }
7259
7260 static int lfsck_orphan_index_declare_delete(const struct lu_env *env,
7261                                              struct dt_object *dt,
7262                                              const struct dt_key *key,
7263                                              struct thandle *handle)
7264 {
7265         return -EOPNOTSUPP;
7266 }
7267
7268 static int lfsck_orphan_index_delete(const struct lu_env *env,
7269                                      struct dt_object *dt,
7270                                      const struct dt_key *key,
7271                                      struct thandle *handle)
7272 {
7273         return -EOPNOTSUPP;
7274 }
7275
7276 static struct dt_it *lfsck_orphan_it_init(const struct lu_env *env,
7277                                           struct dt_object *dt,
7278                                           __u32 attr)
7279 {
7280         struct dt_device                *dev    = lu2dt_dev(dt->do_lu.lo_dev);
7281         struct lfsck_instance           *lfsck;
7282         struct lfsck_component          *com    = NULL;
7283         struct lfsck_layout_slave_data  *llsd;
7284         struct lfsck_orphan_it          *it     = NULL;
7285         struct lfsck_layout             *lo;
7286         int                              rc     = 0;
7287         ENTRY;
7288
7289         lfsck = lfsck_instance_find(dev, true, false);
7290         if (unlikely(lfsck == NULL))
7291                 RETURN(ERR_PTR(-ENXIO));
7292
7293         com = lfsck_component_find(lfsck, LFSCK_TYPE_LAYOUT);
7294         if (unlikely(com == NULL))
7295                 GOTO(out, rc = -ENOENT);
7296
7297         lo = com->lc_file_ram;
7298         if (lo->ll_flags & LF_INCOMPLETE)
7299                 GOTO(out, rc = -ESRCH);
7300
7301         llsd = com->lc_data;
7302         if (!llsd->llsd_rbtree_valid)
7303                 GOTO(out, rc = -ESRCH);
7304
7305         OBD_ALLOC_PTR(it);
7306         if (it == NULL)
7307                 GOTO(out, rc = -ENOMEM);
7308
7309         it->loi_llst = lfsck_layout_llst_find_and_del(llsd, attr, false);
7310         if (it->loi_llst == NULL)
7311                 GOTO(out, rc = -ENXIO);
7312
7313         if (dev->dd_record_fid_accessed) {
7314                 /* The first iteration against the rbtree, scan the whole rbtree
7315                  * to remove the nodes which do NOT need to be handled. */
7316                 down_write(&llsd->llsd_rb_rwsem);
7317                 if (dev->dd_record_fid_accessed) {
7318                         struct rb_node                  *node;
7319                         struct rb_node                  *next;
7320                         struct lfsck_rbtree_node        *lrn;
7321
7322                         /* No need to record the fid accessing anymore. */
7323                         dev->dd_record_fid_accessed = 0;
7324
7325                         node = rb_first(&llsd->llsd_rb_root);
7326                         while (node != NULL) {
7327                                 next = rb_next(node);
7328                                 lrn = rb_entry(node, struct lfsck_rbtree_node,
7329                                                lrn_node);
7330                                 if (atomic_read(&lrn->lrn_known_count) <=
7331                                     atomic_read(&lrn->lrn_accessed_count)) {
7332                                         rb_erase(node, &llsd->llsd_rb_root);
7333                                         lfsck_rbtree_free(lrn);
7334                                 }
7335                                 node = next;
7336                         }
7337                 }
7338                 up_write(&llsd->llsd_rb_rwsem);
7339         }
7340
7341         /* read lock the rbtree when init, and unlock when fini */
7342         down_read(&llsd->llsd_rb_rwsem);
7343         it->loi_com = com;
7344         com = NULL;
7345
7346         GOTO(out, rc = 0);
7347
7348 out:
7349         if (com != NULL)
7350                 lfsck_component_put(env, com);
7351
7352         CDEBUG(D_LFSCK, "%s: init the orphan iteration: rc = %d\n",
7353                lfsck_lfsck2name(lfsck), rc);
7354
7355         lfsck_instance_put(env, lfsck);
7356         if (rc != 0) {
7357                 if (it != NULL)
7358                         OBD_FREE_PTR(it);
7359
7360                 it = (struct lfsck_orphan_it *)ERR_PTR(rc);
7361         }
7362
7363         return (struct dt_it *)it;
7364 }
7365
7366 static void lfsck_orphan_it_fini(const struct lu_env *env,
7367                                  struct dt_it *di)
7368 {
7369         struct lfsck_orphan_it           *it    = (struct lfsck_orphan_it *)di;
7370         struct lfsck_component           *com   = it->loi_com;
7371         struct lfsck_layout_slave_data   *llsd;
7372         struct lfsck_layout_slave_target *llst;
7373
7374         if (com != NULL) {
7375                 CDEBUG(D_LFSCK, "%s: fini the orphan iteration\n",
7376                        lfsck_lfsck2name(com->lc_lfsck));
7377
7378                 llsd = com->lc_data;
7379                 up_read(&llsd->llsd_rb_rwsem);
7380                 llst = it->loi_llst;
7381                 LASSERT(llst != NULL);
7382
7383                 /* Save the key and hash for iterate next. */
7384                 llst->llst_fid = it->loi_key;
7385                 llst->llst_hash = it->loi_hash;
7386                 lfsck_layout_llst_put(llst);
7387                 lfsck_component_put(env, com);
7388         }
7389         OBD_FREE_PTR(it);
7390 }
7391
7392 /**
7393  * \retval       +1: the iteration finished
7394  * \retval        0: on success, not finished
7395  * \retval      -ve: on error
7396  */
7397 static int lfsck_orphan_it_next(const struct lu_env *env,
7398                                 struct dt_it *di)
7399 {
7400         struct lfsck_thread_info        *info   = lfsck_env_info(env);
7401         struct filter_fid               *ff     = &info->lti_ff;
7402         struct lu_attr                  *la     = &info->lti_la;
7403         struct lfsck_orphan_it          *it     = (struct lfsck_orphan_it *)di;
7404         struct lu_fid                   *key    = &it->loi_key;
7405         struct lu_orphan_rec_v3         *rec    = &it->loi_rec;
7406         struct ost_layout               *ol     = &rec->lor_layout;
7407         struct lfsck_component          *com    = it->loi_com;
7408         struct lfsck_instance           *lfsck  = com->lc_lfsck;
7409         struct lfsck_layout_slave_data  *llsd   = com->lc_data;
7410         struct dt_object                *obj;
7411         struct lfsck_rbtree_node        *lrn;
7412         int                              pos;
7413         int                              rc;
7414         __u32                            save;
7415         __u32                            idx    = it->loi_llst->llst_index;
7416         bool                             exact  = false;
7417         ENTRY;
7418
7419         if (it->loi_over)
7420                 RETURN(1);
7421
7422 again0:
7423         lrn = it->loi_lrn;
7424         if (lrn == NULL) {
7425                 lrn = lfsck_rbtree_search(llsd, key, &exact);
7426                 if (lrn == NULL) {
7427                         it->loi_over = 1;
7428                         RETURN(1);
7429                 }
7430
7431                 it->loi_lrn = lrn;
7432                 if (!exact) {
7433                         key->f_seq = lrn->lrn_seq;
7434                         key->f_oid = lrn->lrn_first_oid;
7435                         key->f_ver = 0;
7436                 }
7437         } else {
7438                 key->f_oid++;
7439                 if (unlikely(key->f_oid == 0)) {
7440                         key->f_seq++;
7441                         it->loi_lrn = NULL;
7442                         goto again0;
7443                 }
7444
7445                 if (key->f_oid >=
7446                     lrn->lrn_first_oid + LFSCK_RBTREE_BITMAP_WIDTH) {
7447                         it->loi_lrn = NULL;
7448                         goto again0;
7449                 }
7450         }
7451
7452         if (unlikely(atomic_read(&lrn->lrn_known_count) <=
7453                      atomic_read(&lrn->lrn_accessed_count))) {
7454                 struct rb_node *next = rb_next(&lrn->lrn_node);
7455
7456                 while (next != NULL) {
7457                         lrn = rb_entry(next, struct lfsck_rbtree_node,
7458                                        lrn_node);
7459                         if (atomic_read(&lrn->lrn_known_count) >
7460                             atomic_read(&lrn->lrn_accessed_count))
7461                                 break;
7462                         next = rb_next(next);
7463                 }
7464
7465                 if (next == NULL) {
7466                         it->loi_over = 1;
7467                         RETURN(1);
7468                 }
7469
7470                 it->loi_lrn = lrn;
7471                 key->f_seq = lrn->lrn_seq;
7472                 key->f_oid = lrn->lrn_first_oid;
7473                 key->f_ver = 0;
7474         }
7475
7476         pos = key->f_oid - lrn->lrn_first_oid;
7477
7478 again1:
7479         pos = find_next_bit(lrn->lrn_known_bitmap,
7480                             LFSCK_RBTREE_BITMAP_WIDTH, pos);
7481         if (pos >= LFSCK_RBTREE_BITMAP_WIDTH) {
7482                 key->f_oid = lrn->lrn_first_oid + pos;
7483                 if (unlikely(key->f_oid < lrn->lrn_first_oid)) {
7484                         key->f_seq++;
7485                         key->f_oid = 0;
7486                 }
7487                 it->loi_lrn = NULL;
7488                 goto again0;
7489         }
7490
7491         if (test_bit(pos, lrn->lrn_accessed_bitmap)) {
7492                 pos++;
7493                 goto again1;
7494         }
7495
7496         key->f_oid = lrn->lrn_first_oid + pos;
7497         obj = lfsck_object_find_bottom(env, lfsck, key);
7498         if (IS_ERR(obj)) {
7499                 rc = PTR_ERR(obj);
7500                 if (rc == -ENOENT) {
7501                         pos++;
7502                         goto again1;
7503                 }
7504                 RETURN(rc);
7505         }
7506
7507         dt_read_lock(env, obj, 0);
7508         if (dt_object_exists(obj) == 0 ||
7509             lfsck_is_dead_obj(obj)) {
7510                 dt_read_unlock(env, obj);
7511                 lfsck_object_put(env, obj);
7512                 pos++;
7513                 goto again1;
7514         }
7515
7516         rc = dt_attr_get(env, obj, la);
7517         if (rc != 0)
7518                 GOTO(out, rc);
7519
7520         rc = dt_xattr_get(env, obj, lfsck_buf_get(env, ff, sizeof(*ff)),
7521                           XATTR_NAME_FID);
7522         if (rc == -ENODATA) {
7523                 /* For the pre-created OST-object, update the bitmap to avoid
7524                  * others LFSCK (second phase) iteration to touch it again. */
7525                 if (la->la_ctime == 0) {
7526                         if (!test_and_set_bit(pos, lrn->lrn_accessed_bitmap))
7527                                 atomic_inc(&lrn->lrn_accessed_count);
7528
7529                         /* For the race between repairing dangling referenced
7530                          * MDT-object and unlink the file, it may left orphan
7531                          * OST-object there. Destroy it now! */
7532                         if (unlikely(!(la->la_mode & S_ISUID))) {
7533                                 dt_read_unlock(env, obj);
7534                                 lfsck_layout_destroy_orphan(env, lfsck, obj);
7535                                 lfsck_object_put(env, obj);
7536                                 pos++;
7537                                 goto again1;
7538                         }
7539                 } else if (idx == 0) {
7540                         /* If the orphan OST-object has no parent information,
7541                          * regard it as referenced by the MDT-object on MDT0. */
7542                         fid_zero(&rec->lor_rec.lor_fid);
7543                         rec->lor_rec.lor_uid = la->la_uid;
7544                         rec->lor_rec.lor_gid = la->la_gid;
7545                         memset(ol, 0, sizeof(*ol));
7546                         rec->lor_layout_version = 0;
7547                         rec->lor_range = 0;
7548
7549                         GOTO(out, rc = 0);
7550                 }
7551
7552                 dt_read_unlock(env, obj);
7553                 lfsck_object_put(env, obj);
7554                 pos++;
7555                 goto again1;
7556         }
7557
7558         if (rc < sizeof(struct lu_fid))
7559                 GOTO(out, rc = (rc < 0 ? rc : -EINVAL));
7560
7561         fid_le_to_cpu(&rec->lor_rec.lor_fid, &ff->ff_parent);
7562         /* Currently, the filter_fid::ff_parent::f_ver is not the real parent
7563          * MDT-object's FID::f_ver, instead it is the OST-object index in its
7564          * parent MDT-object's layout EA. */
7565         save = rec->lor_rec.lor_fid.f_stripe_idx;
7566         rec->lor_rec.lor_fid.f_ver = 0;
7567         rc = lfsck_fid_match_idx(env, lfsck, &rec->lor_rec.lor_fid, idx);
7568         /* If the orphan OST-object does not claim the MDT, then next.
7569          *
7570          * If we do not know whether it matches or not, then return it
7571          * to the MDT for further check. */
7572         if (rc == 0) {
7573                 dt_read_unlock(env, obj);
7574                 lfsck_object_put(env, obj);
7575                 pos++;
7576                 goto again1;
7577         }
7578
7579         rec->lor_rec.lor_fid.f_stripe_idx = save;
7580         rec->lor_rec.lor_uid = la->la_uid;
7581         rec->lor_rec.lor_gid = la->la_gid;
7582         ost_layout_le_to_cpu(ol, &ff->ff_layout);
7583         rec->lor_layout_version =
7584                 le32_to_cpu(ff->ff_layout_version & ~LU_LAYOUT_RESYNC);
7585         rec->lor_range = le32_to_cpu(ff->ff_range);
7586
7587         CDEBUG(D_LFSCK, "%s: return orphan "DFID", PFID "DFID", owner %u:%u, "
7588                "stripe size %u, stripe count %u, COMP id %u, COMP start %llu, "
7589                "COMP end %llu, layout version %u, range %u\n",
7590                lfsck_lfsck2name(com->lc_lfsck), PFID(key),
7591                PFID(&rec->lor_rec.lor_fid), rec->lor_rec.lor_uid,
7592                rec->lor_rec.lor_gid, ol->ol_stripe_size, ol->ol_stripe_count,
7593                ol->ol_comp_id, ol->ol_comp_start, ol->ol_comp_end,
7594                rec->lor_layout_version, rec->lor_range);
7595
7596         GOTO(out, rc = 0);
7597
7598 out:
7599         dt_read_unlock(env, obj);
7600         lfsck_object_put(env, obj);
7601         if (rc == 0)
7602                 it->loi_hash++;
7603
7604         return rc;
7605 }
7606
7607 /**
7608  * \retval       +1: locate to the exactly position
7609  * \retval        0: cannot locate to the exactly position,
7610  *                   call next() to move to a valid position.
7611  * \retval      -ve: on error
7612  */
7613 static int lfsck_orphan_it_get(const struct lu_env *env,
7614                                struct dt_it *di,
7615                                const struct dt_key *key)
7616 {
7617         struct lfsck_orphan_it  *it   = (struct lfsck_orphan_it *)di;
7618         int                      rc;
7619
7620         it->loi_key = *(struct lu_fid *)key;
7621         rc = lfsck_orphan_it_next(env, di);
7622         if (rc == 1)
7623                 return 0;
7624
7625         if (rc == 0)
7626                 return 1;
7627
7628         return rc;
7629 }
7630
7631 static void lfsck_orphan_it_put(const struct lu_env *env,
7632                                 struct dt_it *di)
7633 {
7634 }
7635
7636 static struct dt_key *lfsck_orphan_it_key(const struct lu_env *env,
7637                                           const struct dt_it *di)
7638 {
7639         struct lfsck_orphan_it *it = (struct lfsck_orphan_it *)di;
7640
7641         return (struct dt_key *)&it->loi_key;
7642 }
7643
7644 static int lfsck_orphan_it_key_size(const struct lu_env *env,
7645                                     const struct dt_it *di)
7646 {
7647         return sizeof(struct lu_fid);
7648 }
7649
7650 static int lfsck_orphan_it_rec(const struct lu_env *env,
7651                                const struct dt_it *di,
7652                                struct dt_rec *rec,
7653                                __u32 attr)
7654 {
7655         struct lfsck_orphan_it *it = (struct lfsck_orphan_it *)di;
7656
7657         *(struct lu_orphan_rec_v3 *)rec = it->loi_rec;
7658
7659         return 0;
7660 }
7661
7662 static __u64 lfsck_orphan_it_store(const struct lu_env *env,
7663                                    const struct dt_it *di)
7664 {
7665         struct lfsck_orphan_it  *it   = (struct lfsck_orphan_it *)di;
7666
7667         return it->loi_hash;
7668 }
7669
7670 /**
7671  * \retval       +1: locate to the exactly position
7672  * \retval        0: cannot locate to the exactly position,
7673  *                   call next() to move to a valid position.
7674  * \retval      -ve: on error
7675  */
7676 static int lfsck_orphan_it_load(const struct lu_env *env,
7677                                 const struct dt_it *di,
7678                                 __u64 hash)
7679 {
7680         struct lfsck_orphan_it           *it   = (struct lfsck_orphan_it *)di;
7681         struct lfsck_layout_slave_target *llst = it->loi_llst;
7682         int                               rc;
7683
7684         LASSERT(llst != NULL);
7685
7686         if (hash != llst->llst_hash) {
7687                 CDEBUG(D_LFSCK, "%s: the given hash %llu for orphan "
7688                        "iteration does not match the one when fini "
7689                        "%llu, to be reset.\n",
7690                        lfsck_lfsck2name(it->loi_com->lc_lfsck), hash,
7691                        llst->llst_hash);
7692                 fid_zero(&llst->llst_fid);
7693                 llst->llst_hash = 0;
7694         }
7695
7696         it->loi_key = llst->llst_fid;
7697         it->loi_hash = llst->llst_hash;
7698         rc = lfsck_orphan_it_next(env, (struct dt_it *)di);
7699         if (rc == 1)
7700                 return 0;
7701
7702         if (rc == 0)
7703                 return 1;
7704
7705         return rc;
7706 }
7707
7708 static int lfsck_orphan_it_key_rec(const struct lu_env *env,
7709                                    const struct dt_it *di,
7710                                    void *key_rec)
7711 {
7712         return 0;
7713 }
7714
7715 static const struct dt_index_operations lfsck_orphan_index_ops = {
7716         .dio_lookup             = lfsck_orphan_index_lookup,
7717         .dio_declare_insert     = lfsck_orphan_index_declare_insert,
7718         .dio_insert             = lfsck_orphan_index_insert,
7719         .dio_declare_delete     = lfsck_orphan_index_declare_delete,
7720         .dio_delete             = lfsck_orphan_index_delete,
7721         .dio_it = {
7722                 .init           = lfsck_orphan_it_init,
7723                 .fini           = lfsck_orphan_it_fini,
7724                 .get            = lfsck_orphan_it_get,
7725                 .put            = lfsck_orphan_it_put,
7726                 .next           = lfsck_orphan_it_next,
7727                 .key            = lfsck_orphan_it_key,
7728                 .key_size       = lfsck_orphan_it_key_size,
7729                 .rec            = lfsck_orphan_it_rec,
7730                 .store          = lfsck_orphan_it_store,
7731                 .load           = lfsck_orphan_it_load,
7732                 .key_rec        = lfsck_orphan_it_key_rec,
7733         }
7734 };