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