Whamcloud - gitweb
95b764dd07b0ec0d25a445144c5ab60fdcb84a6a
[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_of(lar, struct lfsck_layout_req, llr_lar);
213
214         lfsck_object_put(env, llr->llr_child);
215         lfsck_assistant_object_put(env, lar->lar_parent);
216         OBD_FREE_PTR(llr);
217 }
218
219 static int
220 lfsck_layout_assistant_sync_failures_interpret(const struct lu_env *env,
221                                                struct ptlrpc_request *req,
222                                                void *args, int rc)
223 {
224         if (rc == 0) {
225                 struct lfsck_async_interpret_args *laia = args;
226                 struct lfsck_tgt_desc             *ltd  = laia->laia_ltd;
227
228                 ltd->ltd_synced_failures = 1;
229                 atomic_dec(laia->laia_count);
230         }
231
232         return 0;
233 }
234
235 /**
236  * Notify remote LFSCK instances about former failures.
237  *
238  * The local LFSCK instance has recorded which OSTs have ever failed to respond
239  * some LFSCK verification requests (maybe because of network issues or the OST
240  * itself trouble). During the respond gap, the OST may missed some OST-objects
241  * verification, then the OST cannot know whether related OST-objects have been
242  * referenced by related MDT-objects or not, then in the second-stage scanning,
243  * these OST-objects will be regarded as orphan, if the OST-object contains bad
244  * parent FID for back reference, then it will misguide the LFSCK to make wrong
245  * fixing for the fake orphan.
246  *
247  * To avoid above trouble, when layout LFSCK finishes the first-stage scanning,
248  * it will scan the bitmap for the ever failed OSTs, and notify them that they
249  * have ever missed some OST-object verification and should skip the handling
250  * for orphan OST-objects on all MDTs that are in the layout LFSCK.
251  *
252  * \param[in] env       pointer to the thread context
253  * \param[in] com       pointer to the lfsck component
254  * \param[in] lr        pointer to the lfsck request
255  */
256 static void lfsck_layout_assistant_sync_failures(const struct lu_env *env,
257                                                  struct lfsck_component *com,
258                                                  struct lfsck_request *lr)
259 {
260         struct lfsck_async_interpret_args *laia  =
261                                 &lfsck_env_info(env)->lti_laia2;
262         struct lfsck_assistant_data       *lad   = com->lc_data;
263         struct lfsck_layout               *lo    = com->lc_file_ram;
264         struct lfsck_instance             *lfsck = com->lc_lfsck;
265         struct lfsck_tgt_descs            *ltds  = &lfsck->li_ost_descs;
266         struct lfsck_tgt_desc             *ltd;
267         struct ptlrpc_request_set         *set;
268         atomic_t                           count;
269         __u32                              idx;
270         int                                rc    = 0;
271         ENTRY;
272
273         if (!test_bit(LAD_INCOMPLETE, &lad->lad_flags))
274                 RETURN_EXIT;
275
276         /* If the MDT has ever failed to verfiy some OST-objects,
277          * then sync failures with them firstly. */
278         lr->lr_flags2 = lo->ll_flags | LF_INCOMPLETE;
279
280         atomic_set(&count, 0);
281         memset(laia, 0, sizeof(*laia));
282         laia->laia_count = &count;
283         set = ptlrpc_prep_set();
284         if (set == NULL)
285                 GOTO(out, rc = -ENOMEM);
286
287         down_read(&ltds->ltd_rw_sem);
288         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 (lfsck_is_dryrun(lfsck))
2333                 GOTO(log, rc = 0);
2334
2335         if (unlikely(lpf == NULL))
2336                 GOTO(log, rc = -ENXIO);
2337
2338         /* We use two separated transactions to repair the inconsistency.
2339          *
2340          * 1) create the MDT-object locally.
2341          * 2) update the OST-object's PFID EA if necessary.
2342          *
2343          * If 1) succeed, but 2) failed, then the OST-object's PFID EA will be
2344          * updated when the layout LFSCK run next time.
2345          *
2346          * If 1) failed, but 2) succeed, then such MDT-object will be re-created
2347          * when the layout LFSCK run next time. */
2348
2349         if (fid_is_zero(pfid)) {
2350                 rc = lfsck_fid_alloc(env, lfsck, pfid, false);
2351                 if (rc != 0)
2352                         GOTO(log, rc);
2353
2354                 cobj = lfsck_object_find_by_dev(env, ltd->ltd_tgt, cfid);
2355                 if (IS_ERR(cobj))
2356                         GOTO(log, rc = PTR_ERR(cobj));
2357         }
2358
2359         pobj = lfsck_object_find_by_dev(env, dev, pfid);
2360         if (IS_ERR(pobj))
2361                 GOTO(log, rc = PTR_ERR(pobj));
2362
2363         LASSERT(infix != NULL);
2364         LASSERT(type != NULL);
2365
2366         memset(la, 0, sizeof(*la));
2367         la->la_uid = rec->lor_rec.lor_uid;
2368         la->la_gid = rec->lor_rec.lor_gid;
2369         la->la_mode = S_IFREG | S_IRUSR;
2370         la->la_valid = LA_MODE | LA_UID | LA_GID;
2371
2372         memset(dof, 0, sizeof(*dof));
2373         dof->dof_type = dt_mode_to_dft(S_IFREG);
2374         /* Because the dof->dof_reg.striped = 0, the LOD will not create
2375          * the stripe(s). The LFSCK will specify the LOV EA via
2376          * lfsck_layout_update_lovea(). */
2377
2378         size = lfsck_lovea_size(&rec->lor_layout, ea_off);
2379         if (ea_buf->lb_len < size) {
2380                 lu_buf_realloc(ea_buf, size);
2381                 if (ea_buf->lb_buf == NULL)
2382                         GOTO(log, rc = -ENOMEM);
2383         }
2384
2385 again:
2386         do {
2387                 snprintf(name, NAME_MAX, DFID"%s-%s-%d", PFID(pfid), infix,
2388                          type, idx++);
2389                 rc = dt_lookup_dir(env, lfsck->li_lpf_obj, name, tfid);
2390                 if (rc != 0 && rc != -ENOENT)
2391                         GOTO(log, rc);
2392         } while (rc == 0);
2393
2394         rc = lfsck_lock(env, lfsck, lfsck->li_lpf_obj, name, llh,
2395                         MDS_INODELOCK_UPDATE, LCK_PW);
2396         if (rc != 0)
2397                 GOTO(log, rc);
2398
2399         /* Re-check whether the name conflict with othrs after taken
2400          * the ldlm lock. */
2401         rc = dt_lookup_dir(env, lfsck->li_lpf_obj, name, tfid);
2402         if (unlikely(rc == 0)) {
2403                 lfsck_unlock(llh);
2404                 goto again;
2405         }
2406
2407         if (rc != -ENOENT)
2408                 GOTO(unlock, rc);
2409
2410         pname = lfsck_name_get_const(env, name, strlen(name));
2411         rc = linkea_links_new(&ldata, &lfsck_env_info(env)->lti_linkea_buf,
2412                               pname, lfsck_dto2fid(lfsck->li_lpf_obj));
2413         if (rc != 0)
2414                 GOTO(unlock, rc);
2415
2416         /* The 1st transaction. */
2417         th = dt_trans_create(env, dev);
2418         if (IS_ERR(th))
2419                 GOTO(unlock, rc = PTR_ERR(th));
2420
2421         rc = dt_declare_create(env, pobj, la, NULL, dof, th);
2422         if (rc != 0)
2423                 GOTO(stop, rc);
2424
2425         lfsck_buf_init(&lov_buf, ea_buf->lb_buf, size);
2426         rc = dt_declare_xattr_set(env, pobj, &lov_buf, XATTR_NAME_LOV,
2427                                   LU_XATTR_CREATE, th);
2428         if (rc != 0)
2429                 GOTO(stop, rc);
2430
2431         dtrec->rec_fid = pfid;
2432         dtrec->rec_type = S_IFREG;
2433         rc = dt_declare_insert(env, lpf,
2434                                (const struct dt_rec *)dtrec,
2435                                (const struct dt_key *)name, th);
2436         if (rc != 0)
2437                 GOTO(stop, rc);
2438
2439         lfsck_buf_init(&linkea_buf, ldata.ld_buf->lb_buf,
2440                        ldata.ld_leh->leh_len);
2441         rc = dt_declare_xattr_set(env, pobj, &linkea_buf,
2442                                   XATTR_NAME_LINK, 0, th);
2443         if (rc != 0)
2444                 GOTO(stop, rc);
2445
2446         rc = dt_trans_start_local(env, dev, th);
2447         if (rc != 0)
2448                 GOTO(stop, rc);
2449
2450         dt_write_lock(env, pobj, 0);
2451         rc = dt_create(env, pobj, la, NULL, dof, th);
2452         if (rc == 0)
2453                 rc = lfsck_layout_update_lovea(env, lfsck, th, rec, pobj, cfid,
2454                         &lov_buf, LU_XATTR_CREATE, ltd->ltd_index, ea_off);
2455         dt_write_unlock(env, pobj);
2456         if (rc < 0)
2457                 GOTO(stop, rc);
2458
2459         rc = dt_insert(env, lpf, (const struct dt_rec *)dtrec,
2460                        (const struct dt_key *)name, th);
2461         if (rc != 0)
2462                 GOTO(stop, rc);
2463
2464         rc = dt_xattr_set(env, pobj, &linkea_buf, XATTR_NAME_LINK, 0, th);
2465         if (rc == 0 && cobj != NULL) {
2466                 dt_trans_stop(env, dev, th);
2467                 th = NULL;
2468
2469                 /* The 2nd transaction. */
2470                 rc = __lfsck_layout_update_pfid(env, cobj, pfid,
2471                                                 &rec->lor_layout, ea_off,
2472                                                 rec->lor_layout_version,
2473                                                 rec->lor_range);
2474         }
2475
2476         GOTO(stop, rc);
2477
2478 stop:
2479         if (th != NULL)
2480                 dt_trans_stop(env, dev, th);
2481
2482 unlock:
2483         lfsck_unlock(llh);
2484
2485 log:
2486         if (cobj != NULL && !IS_ERR(cobj))
2487                 lfsck_object_put(env, cobj);
2488         if (pobj != NULL && !IS_ERR(pobj))
2489                 lfsck_object_put(env, pobj);
2490
2491         if (rc < 0)
2492                 CDEBUG(D_LFSCK, "%s layout LFSCK assistant failed to "
2493                        "recreate the lost MDT-object: parent "DFID
2494                        ", child "DFID", OST-index %u, stripe-index %u, "
2495                        "infix %s, type %s: rc = %d\n",
2496                        lfsck_lfsck2name(lfsck), PFID(pfid), PFID(cfid),
2497                        ltd->ltd_index, ea_off, infix, type, rc);
2498
2499         return rc >= 0 ? 1 : rc;
2500 }
2501
2502 static int lfsck_layout_master_conditional_destroy(const struct lu_env *env,
2503                                                    struct lfsck_component *com,
2504                                                    const struct lu_fid *fid,
2505                                                    __u32 index)
2506 {
2507         struct lfsck_thread_info *info  = lfsck_env_info(env);
2508         struct lfsck_request     *lr    = &info->lti_lr;
2509         struct lfsck_instance    *lfsck = com->lc_lfsck;
2510         struct lfsck_tgt_desc    *ltd;
2511         struct ptlrpc_request    *req;
2512         struct lfsck_request     *tmp;
2513         struct obd_export        *exp;
2514         int                       rc    = 0;
2515         ENTRY;
2516
2517         ltd = lfsck_tgt_get(&lfsck->li_ost_descs, index);
2518         if (unlikely(ltd == NULL))
2519                 RETURN(-ENXIO);
2520
2521         exp = ltd->ltd_exp;
2522         if (!(exp_connect_flags(exp) & OBD_CONNECT_LFSCK))
2523                 GOTO(put, rc = -EOPNOTSUPP);
2524
2525         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_LFSCK_NOTIFY);
2526         if (req == NULL)
2527                 GOTO(put, rc = -ENOMEM);
2528
2529         rc = ptlrpc_request_pack(req, LUSTRE_OBD_VERSION, LFSCK_NOTIFY);
2530         if (rc != 0) {
2531                 ptlrpc_request_free(req);
2532
2533                 GOTO(put, rc);
2534         }
2535
2536         memset(lr, 0, sizeof(*lr));
2537         lr->lr_event = LE_CONDITIONAL_DESTROY;
2538         lr->lr_active = LFSCK_TYPE_LAYOUT;
2539         lr->lr_fid = *fid;
2540
2541         tmp = req_capsule_client_get(&req->rq_pill, &RMF_LFSCK_REQUEST);
2542         *tmp = *lr;
2543         ptlrpc_request_set_replen(req);
2544
2545         rc = ptlrpc_queue_wait(req);
2546         ptlrpc_req_finished(req);
2547
2548         GOTO(put, rc);
2549
2550 put:
2551         lfsck_tgt_put(ltd);
2552
2553         return rc;
2554 }
2555
2556 static int lfsck_layout_slave_conditional_destroy(const struct lu_env *env,
2557                                                   struct lfsck_component *com,
2558                                                   struct lfsck_request *lr)
2559 {
2560         struct lfsck_thread_info        *info   = lfsck_env_info(env);
2561         struct lu_attr                  *la     = &info->lti_la;
2562         union ldlm_policy_data          *policy = &info->lti_policy;
2563         struct ldlm_res_id              *resid  = &info->lti_resid;
2564         struct lfsck_instance           *lfsck  = com->lc_lfsck;
2565         struct dt_device                *dev    = lfsck->li_bottom;
2566         struct lu_fid                   *fid    = &lr->lr_fid;
2567         struct dt_object                *obj;
2568         struct thandle                  *th     = NULL;
2569         struct lustre_handle             lh     = { 0 };
2570         __u64                            flags  = 0;
2571         int                              rc     = 0;
2572         ENTRY;
2573
2574         obj = lfsck_object_find_by_dev(env, dev, fid);
2575         if (IS_ERR(obj))
2576                 RETURN(PTR_ERR(obj));
2577
2578         dt_read_lock(env, obj, 0);
2579         if (dt_object_exists(obj) == 0 ||
2580             lfsck_is_dead_obj(obj)) {
2581                 dt_read_unlock(env, obj);
2582
2583                 GOTO(put, rc = -ENOENT);
2584         }
2585
2586         /* Get obj's attr without lock firstly. */
2587         rc = dt_attr_get(env, obj, la);
2588         dt_read_unlock(env, obj);
2589         if (rc != 0)
2590                 GOTO(put, rc);
2591
2592         if (likely(la->la_ctime != 0 || la->la_mode & S_ISUID))
2593                 GOTO(put, rc = -ETXTBSY);
2594
2595         /* Acquire extent lock on [0, EOF] to sync with all possible written. */
2596         LASSERT(lfsck->li_namespace != NULL);
2597
2598         memset(policy, 0, sizeof(*policy));
2599         policy->l_extent.end = OBD_OBJECT_EOF;
2600         ost_fid_build_resid(fid, resid);
2601         rc = ldlm_cli_enqueue_local(env, lfsck->li_namespace, resid,
2602                                     LDLM_EXTENT, policy, LCK_EX, &flags,
2603                                     ldlm_blocking_ast, ldlm_completion_ast,
2604                                     NULL, NULL, 0, LVB_T_NONE, NULL, &lh);
2605         if (rc != ELDLM_OK)
2606                 GOTO(put, rc = -EIO);
2607
2608         dt_write_lock(env, obj, 0);
2609         /* Get obj's attr within lock again. */
2610         rc = dt_attr_get(env, obj, la);
2611         if (rc != 0)
2612                 GOTO(unlock, rc);
2613
2614         if (la->la_ctime != 0)
2615                 GOTO(unlock, rc = -ETXTBSY);
2616
2617         th = dt_trans_create(env, dev);
2618         if (IS_ERR(th))
2619                 GOTO(unlock, rc = PTR_ERR(th));
2620
2621         rc = dt_declare_ref_del(env, obj, th);
2622         if (rc != 0)
2623                 GOTO(stop, rc);
2624
2625         rc = dt_declare_destroy(env, obj, th);
2626         if (rc != 0)
2627                 GOTO(stop, rc);
2628
2629         rc = dt_trans_start_local(env, dev, th);
2630         if (rc != 0)
2631                 GOTO(stop, rc);
2632
2633         rc = dt_ref_del(env, obj, th);
2634         if (rc != 0)
2635                 GOTO(stop, rc);
2636
2637         rc = dt_destroy(env, obj, th);
2638         if (rc == 0)
2639                 CDEBUG(D_LFSCK, "%s: layout LFSCK destroyed the empty "
2640                        "OST-object "DFID" that was created for reparing "
2641                        "dangling referenced case. But the original missing "
2642                        "OST-object is found now.\n",
2643                        lfsck_lfsck2name(lfsck), PFID(fid));
2644
2645         GOTO(stop, rc);
2646
2647 stop:
2648         dt_trans_stop(env, dev, th);
2649
2650 unlock:
2651         dt_write_unlock(env, obj);
2652         ldlm_lock_decref(&lh, LCK_EX);
2653
2654 put:
2655         lfsck_object_put(env, obj);
2656
2657         return rc;
2658 }
2659
2660 /**
2661  * Some OST-object has occupied the specified layout EA slot.
2662  * Such OST-object may be generated by the LFSCK when repair
2663  * dangling referenced MDT-object, which can be indicated by
2664  * attr::la_ctime == 0 but without S_ISUID in la_mode. If it
2665  * is true and such OST-object has not been modified yet, we
2666  * will replace it with the orphan OST-object; otherwise the
2667  * LFSCK will create new MDT-object to reference the orphan.
2668  *
2669  * \retval       +1: repaired
2670  * \retval        0: did nothing
2671  * \retval      -ve: on error
2672  */
2673 static int lfsck_layout_conflict_create(const struct lu_env *env,
2674                                         struct lfsck_component *com,
2675                                         struct lfsck_tgt_desc *ltd,
2676                                         struct lu_orphan_rec_v3 *rec,
2677                                         struct dt_object *parent,
2678                                         struct lu_fid *cfid,
2679                                         struct lu_buf *ea_buf,
2680                                         struct lov_mds_md_v1 *lmm,
2681                                         struct lov_ost_data_v1 *slot,
2682                                         __u32 ea_off, int lovea_size)
2683 {
2684         struct lfsck_thread_info *info          = lfsck_env_info(env);
2685         struct lu_fid            *cfid2         = &info->lti_fid2;
2686         struct ost_id            *oi            = &info->lti_oi;
2687         struct dt_device         *dev           = lfsck_obj2dev(parent);
2688         struct thandle           *th            = NULL;
2689         struct lustre_handle      lh            = { 0 };
2690         __u32                     ost_idx2      = le32_to_cpu(slot->l_ost_idx);
2691         int                       rc            = 0;
2692         ENTRY;
2693
2694         while (CFS_FAIL_TIMEOUT(OBD_FAIL_LFSCK_DELAY3, cfs_fail_val)) {
2695                 if (unlikely(!thread_is_running(&com->lc_lfsck->li_thread)))
2696                         RETURN(0);
2697         }
2698
2699         ostid_le_to_cpu(&slot->l_ost_oi, oi);
2700         rc = ostid_to_fid(cfid2, oi, ost_idx2);
2701         if (rc != 0)
2702                 GOTO(out, rc);
2703
2704         rc = lfsck_ibits_lock(env, com->lc_lfsck, parent, &lh,
2705                               MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR,
2706                               LCK_EX);
2707         if (rc != 0)
2708                 GOTO(out, rc);
2709
2710         rc = lfsck_layout_master_conditional_destroy(env, com, cfid2, ost_idx2);
2711
2712         /* If the conflict OST-obejct is not created for fixing dangling
2713          * referenced MDT-object in former LFSCK check/repair, or it has
2714          * been modified by others, then we cannot destroy it. Re-create
2715          * a new MDT-object for the orphan OST-object. */
2716         if (rc == -ETXTBSY) {
2717                 /* No need the layout lock on the original parent. */
2718                 lfsck_ibits_unlock(&lh, LCK_EX);
2719
2720                 fid_zero(&rec->lor_rec.lor_fid);
2721                 snprintf(info->lti_tmpbuf, sizeof(info->lti_tmpbuf),
2722                          "-"DFID"-%x", PFID(lu_object_fid(&parent->do_lu)),
2723                          ea_off);
2724                 rc = lfsck_layout_recreate_parent(env, com, ltd, rec, cfid,
2725                                                 info->lti_tmpbuf, "C", ea_off);
2726
2727                 RETURN(rc);
2728         }
2729
2730         if (rc != 0 && rc != -ENOENT)
2731                 GOTO(unlock, rc);
2732
2733         if (lfsck_is_dryrun(com->lc_lfsck))
2734                 GOTO(unlock, rc = 0);
2735
2736         th = dt_trans_create(env, dev);
2737         if (IS_ERR(th))
2738                 GOTO(unlock, rc = PTR_ERR(th));
2739
2740         rc = dt_declare_xattr_set(env, parent, ea_buf, XATTR_NAME_LOV,
2741                                   LU_XATTR_REPLACE, th);
2742         if (rc != 0)
2743                 GOTO(stop, rc);
2744
2745         rc = dt_trans_start_local(env, dev, th);
2746         if (rc != 0)
2747                 GOTO(stop, rc);
2748
2749         dt_write_lock(env, parent, 0);
2750         lmm->lmm_layout_gen = cpu_to_le16(le16_to_cpu(lmm->lmm_layout_gen) + 1);
2751         rc = lfsck_layout_refill_lovea(env, com->lc_lfsck, th, parent, cfid,
2752                                        ea_buf, lmm, slot, LU_XATTR_REPLACE,
2753                                        ltd->ltd_index, lovea_size);
2754         dt_write_unlock(env, parent);
2755
2756         GOTO(stop, rc);
2757
2758 stop:
2759         dt_trans_stop(env, dev, th);
2760
2761 unlock:
2762         lfsck_ibits_unlock(&lh, LCK_EX);
2763
2764 out:
2765         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant replaced the conflict "
2766                "OST-object "DFID" on the OST %x with the orphan "DFID" on "
2767                "the OST %x: parent "DFID", stripe-index %u: rc = %d\n",
2768                lfsck_lfsck2name(com->lc_lfsck), PFID(cfid2), ost_idx2,
2769                PFID(cfid), ltd->ltd_index, PFID(lfsck_dto2fid(parent)),
2770                ea_off, rc);
2771
2772         return rc >= 0 ? 1 : rc;
2773 }
2774
2775 /**
2776  * \retval       +1: repaired
2777  * \retval        0: did nothing
2778  * \retval      -ve: on error
2779  */
2780 static int lfsck_layout_recreate_lovea(const struct lu_env *env,
2781                                        struct lfsck_component *com,
2782                                        struct lfsck_tgt_desc *ltd,
2783                                        struct lu_orphan_rec_v3 *rec,
2784                                        struct dt_object *parent,
2785                                        struct lu_fid *cfid,
2786                                        __u32 ost_idx, __u32 ea_off)
2787 {
2788         struct lfsck_thread_info *info          = lfsck_env_info(env);
2789         struct lu_buf            *buf           = &info->lti_big_buf;
2790         struct lu_fid            *fid           = &info->lti_fid2;
2791         struct ost_id            *oi            = &info->lti_oi;
2792         struct lfsck_instance    *lfsck         = com->lc_lfsck;
2793         struct dt_device         *dt            = lfsck_obj2dev(parent);
2794         struct lfsck_bookmark    *bk            = &lfsck->li_bookmark_ram;
2795         struct ost_layout        *ol            = &rec->lor_layout;
2796         struct lov_comp_md_v1    *lcm           = NULL;
2797         struct lov_comp_md_entry_v1 *lcme       = NULL;
2798         struct thandle           *handle        = NULL;
2799         size_t                    lovea_size;
2800         struct lov_mds_md_v1     *lmm;
2801         struct lov_ost_data_v1   *objs;
2802         struct lustre_handle      lh            = { 0 };
2803         __u32                     magic;
2804         __u32 flags = 0;
2805         int                       fl            = 0;
2806         int                       rc            = 0;
2807         int                       rc1;
2808         int                       i;
2809         int pos = 0;
2810         __u16 count;
2811         bool locked = false;
2812         bool new_mirror = true;
2813         ENTRY;
2814
2815         if (lfsck_is_dryrun(lfsck))
2816                 RETURN(0);
2817
2818         rc = lfsck_ibits_lock(env, lfsck, parent, &lh,
2819                               MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR,
2820                               LCK_EX);
2821         if (rc != 0) {
2822                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant failed to recreate "
2823                        "LOV EA for "DFID": parent "DFID", OST-index %u, "
2824                        "stripe-index %u, comp_id %u, comp_start %llu, "
2825                        "comp_end %llu, layout version %u, range %u: rc = %d\n",
2826                        lfsck_lfsck2name(lfsck), PFID(cfid),
2827                        PFID(lfsck_dto2fid(parent)), ost_idx, ea_off,
2828                        ol->ol_comp_id, ol->ol_comp_start,
2829                        ol->ol_comp_end, rec->lor_layout_version,
2830                        rec->lor_range, rc);
2831
2832                 RETURN(rc);
2833         }
2834
2835 again:
2836         if (locked) {
2837                 dt_write_unlock(env, parent);
2838                 locked = false;
2839         }
2840
2841         if (handle != NULL) {
2842                 dt_trans_stop(env, dt, handle);
2843                 handle = NULL;
2844         }
2845
2846         if (rc < 0)
2847                 GOTO(unlock_layout, rc);
2848
2849         lovea_size = rc;
2850         if (buf->lb_len < lovea_size) {
2851                 lu_buf_realloc(buf, lovea_size);
2852                 if (buf->lb_buf == NULL)
2853                         GOTO(unlock_layout, rc = -ENOMEM);
2854         }
2855
2856         if (!(bk->lb_param & LPF_DRYRUN)) {
2857                 handle = dt_trans_create(env, dt);
2858                 if (IS_ERR(handle))
2859                         GOTO(unlock_layout, rc = PTR_ERR(handle));
2860
2861                 rc = dt_declare_xattr_set(env, parent, buf, XATTR_NAME_LOV,
2862                                           fl, handle);
2863                 if (rc != 0)
2864                         GOTO(stop, rc);
2865
2866                 rc = dt_trans_start_local(env, dt, handle);
2867                 if (rc != 0)
2868                         GOTO(stop, rc);
2869         }
2870
2871         dt_write_lock(env, parent, 0);
2872         locked = true;
2873         rc = dt_xattr_get(env, parent, buf, XATTR_NAME_LOV);
2874         if (rc == -ERANGE) {
2875                 rc = dt_xattr_get(env, parent, &LU_BUF_NULL, XATTR_NAME_LOV);
2876                 LASSERT(rc != 0);
2877                 goto again;
2878         } else if (rc == -ENODATA || rc == 0) {
2879                 lovea_size = lfsck_lovea_size(ol, ea_off);
2880                 /* If the declared is not big enough, re-try. */
2881                 if (buf->lb_len < lovea_size) {
2882                         rc = lovea_size;
2883                         goto again;
2884                 }
2885                 fl = LU_XATTR_CREATE;
2886         } else if (rc < 0) {
2887                 GOTO(unlock_parent, rc);
2888         } else if (unlikely(buf->lb_len == 0)) {
2889                 goto again;
2890         } else {
2891                 fl = LU_XATTR_REPLACE;
2892                 lovea_size = rc;
2893         }
2894
2895         if (fl == LU_XATTR_CREATE) {
2896                 if (bk->lb_param & LPF_DRYRUN)
2897                         GOTO(unlock_parent, rc = 1);
2898
2899                 LASSERT(buf->lb_len >= lovea_size);
2900
2901                 rc = lfsck_layout_update_lovea(env, lfsck, handle, rec, parent,
2902                                                cfid, buf, fl, ost_idx, ea_off);
2903
2904                 GOTO(unlock_parent, rc);
2905         }
2906
2907         lmm = buf->lb_buf;
2908         rc1 = lfsck_layout_verify_header(parent, lmm, lovea_size);
2909
2910         /* If the LOV EA crashed, the rebuild it. */
2911         if (rc1 == -EINVAL) {
2912                 if (bk->lb_param & LPF_DRYRUN)
2913                         GOTO(unlock_parent, rc = 1);
2914
2915                 LASSERT(buf->lb_len >= lovea_size);
2916
2917                 rc = lfsck_layout_update_lovea(env, lfsck, handle, rec, parent,
2918                                                cfid, buf, fl, ost_idx, ea_off);
2919
2920                 GOTO(unlock_parent, rc);
2921         }
2922
2923         /* For other unknown magic/pattern, keep the current LOV EA. */
2924         if (rc1 == -EOPNOTSUPP)
2925                 GOTO(unlock_parent, rc1 = 0);
2926
2927         if (rc1)
2928                 GOTO(unlock_parent, rc = rc1);
2929
2930         magic = le32_to_cpu(lmm->lmm_magic);
2931         if (magic == LOV_MAGIC_COMP_V1) {
2932                 __u64 start;
2933                 __u64 end;
2934                 __u16 mirror_id0 = mirror_id_of(ol->ol_comp_id);
2935                 __u16 mirror_id1;
2936
2937                 if (bk->lb_param & LPF_DRYRUN)
2938                         GOTO(unlock_parent, rc = 1);
2939
2940                 lcm = buf->lb_buf;
2941                 count = le16_to_cpu(lcm->lcm_entry_count);
2942                 for (i = 0; i < count; pos = ++i) {
2943                         lcme = &lcm->lcm_entries[i];
2944                         start = le64_to_cpu(lcme->lcme_extent.e_start);
2945                         end = le64_to_cpu(lcme->lcme_extent.e_end);
2946                         mirror_id1 = mirror_id_of(le32_to_cpu(lcme->lcme_id));
2947
2948                         if (mirror_id0 > mirror_id1)
2949                                 continue;
2950
2951                         if (mirror_id0 < mirror_id1)
2952                                 break;
2953
2954                         new_mirror = false;
2955                         if (end <= ol->ol_comp_start)
2956                                 continue;
2957
2958                         if (start >= ol->ol_comp_end)
2959                                 break;
2960
2961                         lmm = buf->lb_buf + le32_to_cpu(lcme->lcme_offset);
2962                         magic = le32_to_cpu(lmm->lmm_magic);
2963                         flags = le32_to_cpu(lcme->lcme_flags);
2964                         goto further;
2965                 }
2966
2967                 rc = lfsck_layout_add_comp(env, lfsck, handle, rec, parent,
2968                                 cfid, buf, ost_idx, ea_off, pos, new_mirror);
2969
2970                 GOTO(unlock_parent, rc);
2971         }
2972
2973 further:
2974         count = le16_to_cpu(lmm->lmm_stripe_count);
2975         if (count == 0)
2976                 GOTO(unlock_parent, rc = -EINVAL);
2977         LASSERT(count > 0);
2978
2979         /* Exceed the current end of MDT-object layout EA. Then extend it. */
2980         if (count <= ea_off) {
2981                 if (bk->lb_param & LPF_DRYRUN)
2982                         GOTO(unlock_parent, rc = 1);
2983
2984                 lovea_size = lov_mds_md_size(ea_off + 1, magic);
2985                 /* If the declared is not big enough, re-try. */
2986                 if (buf->lb_len < lovea_size) {
2987                         rc = lovea_size;
2988                         goto again;
2989                 }
2990
2991                 if (lcm) {
2992                         LASSERT(lcme);
2993
2994                         lcme->lcme_flags = cpu_to_le32(flags | LCME_FL_INIT);
2995                         lfsck_layout_update_lcm(lcm, lcme,
2996                                                 rec->lor_layout_version,
2997                                                 rec->lor_range);
2998                 }
2999
3000                 rc = lfsck_layout_extend_v1v3_lovea(env, lfsck, handle, ol,
3001                                         parent, cfid, buf, ost_idx, ea_off);
3002
3003                 GOTO(unlock_parent, rc);
3004         }
3005
3006         LASSERTF(rc > 0, "invalid rc = %d\n", rc);
3007
3008         if (magic == LOV_MAGIC_V1) {
3009                 objs = &lmm->lmm_objects[0];
3010         } else {
3011                 LASSERT(magic == LOV_MAGIC_V3);
3012                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[0];
3013         }
3014
3015         for (i = 0; i < count; i++, objs++) {
3016                 /* The MDT-object was created via lfsck_layout_recover_create()
3017                  * by others before, and we fill the dummy layout EA. */
3018                 if ((lcme && !(flags & LCME_FL_INIT)) ||
3019                      lovea_slot_is_dummy(objs)) {
3020                         if (i != ea_off)
3021                                 continue;
3022
3023                         if (bk->lb_param & LPF_DRYRUN)
3024                                 GOTO(unlock_parent, rc = 1);
3025
3026                         lmm->lmm_layout_gen =
3027                             cpu_to_le16(le16_to_cpu(lmm->lmm_layout_gen) + 1);
3028                         if (lcme) {
3029                                 LASSERT(lcm);
3030
3031                                 if (le32_to_cpu(lmm->lmm_stripe_size) !=
3032                                         ol->ol_stripe_size ||
3033                                     le16_to_cpu(lmm->lmm_stripe_count) !=
3034                                         ol->ol_stripe_count ||
3035                                     le64_to_cpu(lcme->lcme_extent.e_start) !=
3036                                         ol->ol_comp_start ||
3037                                     le64_to_cpu(lcme->lcme_extent.e_end) !=
3038                                         ol->ol_comp_end) {
3039                                         CDEBUG(D_LFSCK, "%s: found invalid "
3040                                         "component for "DFID ": parent "DFID
3041                                         ", stripe-index %u, stripe_size %u, "
3042                                         "stripe_count %u, comp_id %u, "
3043                                         "comp_start %llu, comp_end %llu, "
3044                                         "cur_stripe_size %u, "
3045                                         "cur_stripe_count %u, "
3046                                         "cur_comp_start %llu, "
3047                                         "cur_comp_end %llu\n",
3048                                         lfsck_lfsck2name(lfsck), PFID(cfid),
3049                                         PFID(lfsck_dto2fid(parent)), ea_off,
3050                                         ol->ol_stripe_size,
3051                                         ol->ol_stripe_count, ol->ol_comp_id,
3052                                         ol->ol_comp_start, ol->ol_comp_end,
3053                                         le32_to_cpu(lmm->lmm_stripe_size),
3054                                         le16_to_cpu(lmm->lmm_stripe_count),
3055                                         le64_to_cpu(lcme->lcme_extent.e_start),
3056                                         le64_to_cpu(lcme->lcme_extent.e_end));
3057
3058                                         GOTO(unlock_parent, rc = -EINVAL);
3059                                 }
3060
3061                                 lovea_size = le32_to_cpu(lcm->lcm_size);
3062                                 lcme->lcme_flags = cpu_to_le32(flags |
3063                                                                LCME_FL_INIT);
3064                                 lfsck_layout_update_lcm(lcm, lcme,
3065                                                         rec->lor_layout_version,
3066                                                         rec->lor_range);
3067                         }
3068
3069                         LASSERTF(buf->lb_len >= lovea_size,
3070                                  "buffer len %d is less than real size %d\n",
3071                                  (int)buf->lb_len, (int)lovea_size);
3072
3073                         rc = lfsck_layout_refill_lovea(env, lfsck, handle,
3074                                                 parent, cfid, buf, lmm, objs,
3075                                                 fl, ost_idx, lovea_size);
3076
3077                         CDEBUG(D_LFSCK, "%s layout LFSCK assistant fill "
3078                                "dummy layout slot for "DFID": parent "DFID
3079                                ", OST-index %u, stripe-index %u: rc = %d\n",
3080                                lfsck_lfsck2name(lfsck), PFID(cfid),
3081                                PFID(lfsck_dto2fid(parent)), ost_idx, i, rc);
3082
3083                         GOTO(unlock_parent, rc);
3084                 }
3085
3086                 ostid_le_to_cpu(&objs->l_ost_oi, oi);
3087                 rc = ostid_to_fid(fid, oi, le32_to_cpu(objs->l_ost_idx));
3088                 if (rc != 0) {
3089                         CDEBUG(D_LFSCK, "%s: the parent "DFID" contains "
3090                                "invalid layout EA at the slot %d, index %u\n",
3091                                lfsck_lfsck2name(lfsck),
3092                                PFID(lfsck_dto2fid(parent)), i,
3093                                le32_to_cpu(objs->l_ost_idx));
3094
3095                         GOTO(unlock_parent, rc);
3096                 }
3097
3098                 /* It should be rare case, the slot is there, but the LFSCK
3099                  * does not handle it during the first-phase cycle scanning. */
3100                 if (unlikely(lu_fid_eq(fid, cfid))) {
3101                         if (i == ea_off) {
3102                                 GOTO(unlock_parent, rc = 0);
3103                         } else {
3104                                 /* Rare case that the OST-object index
3105                                  * does not match the parent MDT-object
3106                                  * layout EA. We trust the later one. */
3107                                 if (bk->lb_param & LPF_DRYRUN)
3108                                         GOTO(unlock_parent, rc = 1);
3109
3110                                 dt_write_unlock(env, parent);
3111                                 if (handle != NULL)
3112                                         dt_trans_stop(env, dt, handle);
3113                                 lfsck_ibits_unlock(&lh, LCK_EX);
3114                                 rc = lfsck_layout_update_pfid(env, com, parent,
3115                                                         cfid, ltd->ltd_tgt,
3116                                                         rec, i);
3117
3118                                 CDEBUG(D_LFSCK, "%s layout LFSCK assistant "
3119                                        "updated OST-object's pfid for "DFID
3120                                        ": parent "DFID", OST-index %u, "
3121                                        "stripe-index %u: rc = %d\n",
3122                                        lfsck_lfsck2name(lfsck), PFID(cfid),
3123                                        PFID(lfsck_dto2fid(parent)),
3124                                        ltd->ltd_index, i, rc);
3125
3126                                 RETURN(rc);
3127                         }
3128                 }
3129         }
3130
3131         /* The MDT-object exists, but related layout EA slot is occupied
3132          * by others. */
3133         if (bk->lb_param & LPF_DRYRUN)
3134                 GOTO(unlock_parent, rc = 1);
3135
3136         dt_write_unlock(env, parent);
3137         if (handle != NULL)
3138                 dt_trans_stop(env, dt, handle);
3139         lfsck_ibits_unlock(&lh, LCK_EX);
3140         if (magic == LOV_MAGIC_V1)
3141                 objs = &lmm->lmm_objects[ea_off];
3142         else
3143                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[ea_off];
3144         rc = lfsck_layout_conflict_create(env, com, ltd, rec, parent, cfid,
3145                                           buf, lmm, objs, ea_off, lovea_size);
3146
3147         RETURN(rc);
3148
3149 unlock_parent:
3150         if (locked)
3151                 dt_write_unlock(env, parent);
3152
3153 stop:
3154         if (handle != NULL)
3155                 dt_trans_stop(env, dt, handle);
3156
3157 unlock_layout:
3158         lfsck_ibits_unlock(&lh, LCK_EX);
3159
3160         return rc;
3161 }
3162
3163 static int lfsck_layout_scan_orphan_one(const struct lu_env *env,
3164                                         struct lfsck_component *com,
3165                                         struct lfsck_tgt_desc *ltd,
3166                                         struct lu_orphan_rec_v3 *rec,
3167                                         struct lu_fid *cfid)
3168 {
3169         struct lfsck_layout     *lo     = com->lc_file_ram;
3170         struct lu_fid           *pfid   = &rec->lor_rec.lor_fid;
3171         struct dt_object        *parent = NULL;
3172         __u32                    ea_off = pfid->f_stripe_idx;
3173         int                      rc     = 0;
3174         ENTRY;
3175
3176         if (!fid_is_sane(cfid))
3177                 GOTO(out, rc = -EINVAL);
3178
3179         pfid->f_ver = 0;
3180         if (fid_is_zero(pfid)) {
3181                 rc = lfsck_layout_recreate_parent(env, com, ltd, rec, cfid,
3182                                                   "", "N", ea_off);
3183                 GOTO(out, rc);
3184         }
3185
3186         if (!fid_is_sane(pfid))
3187                 GOTO(out, rc = -EINVAL);
3188
3189         parent = lfsck_object_find_by_dev(env, com->lc_lfsck->li_bottom, pfid);
3190         if (IS_ERR(parent))
3191                 GOTO(out, rc = PTR_ERR(parent));
3192
3193         if (unlikely(dt_object_remote(parent) != 0))
3194                 GOTO(put, rc = -EXDEV);
3195
3196         if (dt_object_exists(parent) == 0) {
3197                 lfsck_object_put(env, parent);
3198                 rc = lfsck_layout_recreate_parent(env, com, ltd, rec, cfid,
3199                                                   "", "R", ea_off);
3200                 GOTO(out, rc);
3201         }
3202
3203         if (!S_ISREG(lu_object_attr(&parent->do_lu)))
3204                 GOTO(put, rc = -EISDIR);
3205
3206         /* The orphan OST-object claims to be the parent's stripe, then
3207          * related dangling record in the trace file is meaningless. */
3208         rc = lfsck_layout_del_dangling_rec(env, com, pfid,
3209                                            rec->lor_layout.ol_comp_id, ea_off);
3210         if (rc && rc != -ENOENT)
3211                 GOTO(put, rc);
3212
3213         rc = lfsck_layout_recreate_lovea(env, com, ltd, rec, parent, cfid,
3214                                          ltd->ltd_index, ea_off);
3215
3216         GOTO(put, rc);
3217
3218 put:
3219         if (rc <= 0)
3220                 lfsck_object_put(env, parent);
3221         else
3222                 /* The layout EA is changed, need to be reloaded next time. */
3223                 dt_object_put_nocache(env, parent);
3224
3225 out:
3226         down_write(&com->lc_sem);
3227         com->lc_new_scanned++;
3228         com->lc_new_checked++;
3229         if (rc > 0) {
3230                 lo->ll_objs_repaired[LLIT_ORPHAN - 1]++;
3231                 rc = 0;
3232         } else if (rc < 0) {
3233                 lo->ll_objs_failed_phase2++;
3234         }
3235         up_write(&com->lc_sem);
3236
3237         return rc;
3238 }
3239
3240 static int lfsck_layout_scan_orphan(const struct lu_env *env,
3241                                     struct lfsck_component *com,
3242                                     struct lfsck_tgt_desc *ltd)
3243 {
3244         struct lfsck_assistant_data     *lad    = com->lc_data;
3245         struct lfsck_instance           *lfsck  = com->lc_lfsck;
3246         struct lfsck_bookmark           *bk     = &lfsck->li_bookmark_ram;
3247         struct lfsck_thread_info        *info   = lfsck_env_info(env);
3248         struct lu_fid                   *fid    = &info->lti_fid;
3249         struct dt_object                *obj;
3250         const struct dt_it_ops          *iops;
3251         struct dt_it                    *di;
3252         int                              rc     = 0;
3253         ENTRY;
3254
3255         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant starts the orphan "
3256                "scanning for OST%04x\n",
3257                lfsck_lfsck2name(lfsck), ltd->ltd_index);
3258
3259         if (cfs_bitmap_check(lad->lad_bitmap, ltd->ltd_index)) {
3260                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant skip the orphan "
3261                        "scanning for OST%04x\n",
3262                        lfsck_lfsck2name(lfsck), ltd->ltd_index);
3263
3264                 RETURN(0);
3265         }
3266
3267         fid->f_seq = fid_idif_seq(0, ltd->ltd_index);
3268         fid->f_oid = fid->f_ver = 0;
3269
3270         obj = lfsck_object_find_by_dev(env, ltd->ltd_tgt, fid);
3271         if (unlikely(IS_ERR(obj)))
3272                 GOTO(log, rc = PTR_ERR(obj));
3273
3274         rc = obj->do_ops->do_index_try(env, obj,
3275                                        &dt_lfsck_layout_orphan_features);
3276         if (rc != 0)
3277                 GOTO(put, rc);
3278
3279         iops = &obj->do_index_ops->dio_it;
3280         di = iops->init(env, obj, 0);
3281         if (IS_ERR(di))
3282                 GOTO(put, rc = PTR_ERR(di));
3283
3284         rc = iops->load(env, di, 0);
3285         if (rc == -ESRCH) {
3286                 /* -ESRCH means that the orphan OST-objects rbtree has been
3287                  * cleanup because of the OSS server restart or other errors. */
3288                 lfsck_lad_set_bitmap(env, com, ltd->ltd_index);
3289                 GOTO(fini, rc);
3290         }
3291
3292         if (rc == 0)
3293                 rc = iops->next(env, di);
3294         else if (rc > 0)
3295                 rc = 0;
3296
3297         if (rc < 0)
3298                 GOTO(fini, rc);
3299
3300         if (rc > 0)
3301                 GOTO(fini, rc = 0);
3302
3303         do {
3304                 struct dt_key           *key;
3305                 struct lu_orphan_rec_v3 *rec = &info->lti_rec;
3306
3307                 if (CFS_FAIL_TIMEOUT(OBD_FAIL_LFSCK_DELAY3, cfs_fail_val) &&
3308                     unlikely(!thread_is_running(&lfsck->li_thread)))
3309                         break;
3310
3311                 key = iops->key(env, di);
3312                 com->lc_fid_latest_scanned_phase2 = *(struct lu_fid *)key;
3313                 /* Remote target OST may be runnning old LFSCK */
3314                 memset(rec, 0, sizeof(*rec));
3315                 rc = iops->rec(env, di, (struct dt_rec *)rec, 0);
3316                 if (rc == 0)
3317                         rc = lfsck_layout_scan_orphan_one(env, com, ltd, rec,
3318                                         &com->lc_fid_latest_scanned_phase2);
3319                 if (rc != 0 && bk->lb_param & LPF_FAILOUT)
3320                         GOTO(fini, rc);
3321
3322                 lfsck_control_speed_by_self(com);
3323                 do {
3324                         rc = iops->next(env, di);
3325                 } while (rc < 0 && !(bk->lb_param & LPF_FAILOUT));
3326         } while (rc == 0);
3327
3328         GOTO(fini, rc);
3329
3330 fini:
3331         iops->put(env, di);
3332         iops->fini(env, di);
3333 put:
3334         lfsck_object_put(env, obj);
3335
3336 log:
3337         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant finished the orphan "
3338                "scanning for OST%04x: rc = %d\n",
3339                lfsck_lfsck2name(lfsck), ltd->ltd_index, rc);
3340
3341         return rc > 0 ? 0 : rc;
3342 }
3343
3344 static int lfsck_lov2layout(struct lov_mds_md_v1 *lmm, struct filter_fid *ff,
3345                             __u32 comp_id)
3346 {
3347         struct ost_layout *ol = &ff->ff_layout;
3348         __u32 magic = le32_to_cpu(lmm->lmm_magic);
3349         int rc = 0;
3350         ENTRY;
3351
3352         if (magic == LOV_MAGIC_V1 || magic == LOV_MAGIC_V3) {
3353                 ol->ol_stripe_size = lmm->lmm_stripe_size;
3354                 ol->ol_stripe_count = lmm->lmm_stripe_count;
3355                 ol->ol_comp_start = 0;
3356                 ol->ol_comp_end = 0;
3357                 ol->ol_comp_id = 0;
3358                 ff->ff_layout_version = 0;
3359                 ff->ff_range = 0;
3360         } else if (magic == LOV_MAGIC_COMP_V1) {
3361                 struct lov_comp_md_v1 *lcm = (struct lov_comp_md_v1 *)lmm;
3362                 struct lov_comp_md_entry_v1 *lcme = NULL;
3363                 __u16 count = le16_to_cpu(lcm->lcm_entry_count);
3364                 int i;
3365
3366                 for (i = 0; i < count; i++) {
3367                         lcme = &lcm->lcm_entries[i];
3368                         if (le32_to_cpu(lcme->lcme_id) == comp_id) {
3369                                 LASSERT(le32_to_cpu(lcme->lcme_flags) &
3370                                         LCME_FL_INIT);
3371
3372                                 break;
3373                         }
3374                 }
3375
3376                 /* The comp has been removed, do nothing. */
3377                 if (i == count)
3378                         GOTO(out, rc = 1);
3379
3380                 lmm = (void *)lmm + le32_to_cpu(lcme->lcme_offset);
3381                 ol->ol_stripe_size = le32_to_cpu(lmm->lmm_stripe_size);
3382                 ol->ol_stripe_count = le32_to_cpu(lmm->lmm_stripe_count);
3383                 ol->ol_comp_start = le64_to_cpu(lcme->lcme_extent.e_start);
3384                 ol->ol_comp_end = le64_to_cpu(lcme->lcme_extent.e_end);
3385                 ol->ol_comp_id = le32_to_cpu(lcme->lcme_id);
3386                 ff->ff_layout_version = le32_to_cpu(lcme->lcme_layout_gen);
3387                 ff->ff_range = 0;
3388         } else {
3389                 GOTO(out, rc = -EINVAL);
3390         }
3391
3392         EXIT;
3393
3394 out:
3395         return rc;
3396 }
3397
3398 /**
3399  * Repair the MDT-object with dangling LOV EA reference.
3400  *
3401  * we need to repair the inconsistency according to the users' requirement:
3402  *
3403  * 1) Keep the inconsistency there and report the inconsistency case,
3404  *    then give the chance to the application to find related issues,
3405  *    and the users can make the decision about how to handle it with
3406  *    more human knownledge. (by default)
3407  *
3408  * 2) Re-create the missing OST-object with the FID/owner information.
3409  *
3410  * \param[in] env       pointer to the thread context
3411  * \param[in] com       the layout LFSCK component
3412  * \param[in] parent    the MDT-object with dangling LOV EA reference
3413  * \param[in] child     the OST-object to be created
3414  * \param[in] comp_id   the component ID of the OST-object in the LOV EA
3415  * \param[in] ea_off    the offset of the OST-object in the LOV EA
3416  * \param[in] ost_idx   the index of OST on which the OST-object resides
3417  *
3418  * \retval              +1 for repair successfully
3419  * \retval              0 for did nothing
3420  * \retval              negative error number on failure
3421  */
3422 static int __lfsck_layout_repair_dangling(const struct lu_env *env,
3423                                           struct lfsck_component *com,
3424                                           struct dt_object *parent,
3425                                           struct dt_object *child,
3426                                           __u32 comp_id, __u32 ea_off,
3427                                           __u32 ost_idx, bool log)
3428 {
3429         struct lfsck_thread_info *info = lfsck_env_info(env);
3430         struct filter_fid *ff = &info->lti_ff;
3431         struct dt_object_format *dof = &info->lti_dof;
3432         struct lu_attr *la = &info->lti_la;
3433         struct lfsck_instance *lfsck = com->lc_lfsck;
3434         struct dt_device *dev = lfsck_obj2dev(child);
3435         const struct lu_fid *pfid = lfsck_dto2fid(parent);
3436         const struct lu_fid *cfid = lfsck_dto2fid(child);
3437         struct lu_buf *tbuf = &info->lti_big_buf;
3438         struct thandle *handle;
3439         struct lu_buf *buf;
3440         struct lustre_handle lh = { 0 };
3441         int rc;
3442         ENTRY;
3443
3444         if (!(lfsck->li_bookmark_ram.lb_param & LPF_CREATE_OSTOBJ))
3445                 GOTO(log, rc = 1);
3446
3447         rc = lfsck_ibits_lock(env, lfsck, parent, &lh,
3448                               MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR,
3449                               LCK_EX);
3450         if (rc != 0)
3451                 GOTO(log, rc);
3452
3453         rc = dt_attr_get(env, parent, la);
3454         if (rc != 0)
3455                 GOTO(unlock1, rc);
3456
3457         la->la_mode = S_IFREG | 0666;
3458         la->la_atime = la->la_mtime = la->la_ctime = 0;
3459         la->la_valid = LA_TYPE | LA_MODE | LA_UID | LA_GID |
3460                        LA_ATIME | LA_MTIME | LA_CTIME;
3461         memset(dof, 0, sizeof(*dof));
3462         ff->ff_parent.f_seq = cpu_to_le64(pfid->f_seq);
3463         ff->ff_parent.f_oid = cpu_to_le32(pfid->f_oid);
3464         /* Currently, the filter_fid::ff_parent::f_ver is not the real parent
3465          * MDT-object's FID::f_ver, instead it is the OST-object index in its
3466          * parent MDT-object's layout EA. */
3467         ff->ff_parent.f_stripe_idx = cpu_to_le32(ea_off);
3468
3469         rc = lfsck_layout_get_lovea(env, parent, tbuf);
3470         if (unlikely(rc == -ENODATA))
3471                 rc = 0;
3472         if (rc <= 0)
3473                 GOTO(unlock1, rc);
3474
3475         rc = lfsck_lov2layout(tbuf->lb_buf, ff, comp_id);
3476         if (rc)
3477                 GOTO(unlock1, rc);
3478
3479         buf = lfsck_buf_get(env, ff, sizeof(struct filter_fid));
3480         handle = dt_trans_create(env, dev);
3481         if (IS_ERR(handle))
3482                 GOTO(unlock1, rc = PTR_ERR(handle));
3483
3484         rc = dt_declare_create(env, child, la, NULL, dof, handle);
3485         if (rc != 0)
3486                 GOTO(stop, rc);
3487
3488         rc = dt_declare_xattr_set(env, child, buf, XATTR_NAME_FID,
3489                                   LU_XATTR_CREATE, handle);
3490         if (rc != 0)
3491                 GOTO(stop, rc);
3492
3493         rc = dt_trans_start_local(env, dev, handle);
3494         if (rc != 0)
3495                 GOTO(stop, rc);
3496
3497         dt_read_lock(env, parent, 0);
3498         if (unlikely(lfsck_is_dead_obj(parent)))
3499                 GOTO(unlock2, rc = 0);
3500
3501         if (lfsck->li_bookmark_ram.lb_param & LPF_DELAY_CREATE_OSTOBJ) {
3502                 struct ost_id *oi = &info->lti_oi;
3503                 struct lu_fid *tfid = &info->lti_fid2;
3504                 struct lu_buf *lovea = &info->lti_big_buf;
3505                 struct lov_mds_md_v1 *lmm;
3506                 struct lov_ost_data_v1 *objs;
3507                 __u32 magic;
3508                 int count;
3509                 int idx2;
3510
3511                 rc = lfsck_layout_get_lovea(env, parent, lovea);
3512                 if (unlikely(rc == -ENODATA))
3513                         rc = 0;
3514                 if (rc <= 0)
3515                         GOTO(unlock2, rc);
3516
3517                 lmm = lovea->lb_buf;
3518                 magic = le32_to_cpu(lmm->lmm_magic);
3519                 if (magic == LOV_MAGIC_COMP_V1) {
3520                         struct lov_comp_md_v1 *lcm = buf->lb_buf;
3521                         struct lov_comp_md_entry_v1 *lcme;
3522                         __u16 count = le16_to_cpu(lcm->lcm_entry_count);
3523                         int i;
3524
3525                         for (i = 0; i < count; i++) {
3526                                 lcme = &lcm->lcm_entries[i];
3527                                 if (le32_to_cpu(lcme->lcme_id) == comp_id) {
3528                                         LASSERT(le32_to_cpu(lcme->lcme_flags) &
3529                                                 LCME_FL_INIT);
3530
3531                                         lmm = lovea->lb_buf +
3532                                                 le32_to_cpu(lcme->lcme_offset);
3533                                         magic = le32_to_cpu(lmm->lmm_magic);
3534                                         goto check;
3535                                 }
3536                         }
3537
3538                         /* Someone removed the component, do nothing. */
3539                         GOTO(unlock2, rc = 0);
3540                 }
3541
3542 check:
3543                 count = le16_to_cpu(lmm->lmm_stripe_count);
3544                 /* Someone changed the LOV EA, do nothing. */
3545                 if (count <= ea_off)
3546                         GOTO(unlock2, rc = 0);
3547
3548                 if (magic == LOV_MAGIC_V1) {
3549                         objs = &lmm->lmm_objects[ea_off];
3550                 } else {
3551                         LASSERT(magic == LOV_MAGIC_V3);
3552
3553                         objs = &((struct lov_mds_md_v3 *)lmm)->\
3554                                                         lmm_objects[ea_off];
3555                 }
3556
3557                 ostid_le_to_cpu(&objs->l_ost_oi, oi);
3558                 idx2 = le32_to_cpu(objs->l_ost_idx);
3559                 rc = ostid_to_fid(tfid, oi, idx2);
3560                 /* Someone changed the LOV EA, do nothing. */
3561                 if (rc != 0 || !lu_fid_eq(tfid, cfid))
3562                         GOTO(unlock2, rc);
3563         }
3564
3565         rc = dt_create(env, child, la, NULL, dof, handle);
3566         if (rc != 0)
3567                 GOTO(unlock2, rc);
3568
3569         rc = dt_xattr_set(env, child, buf, XATTR_NAME_FID, LU_XATTR_CREATE,
3570                           handle);
3571
3572         GOTO(unlock2, rc);
3573
3574 unlock2:
3575         dt_read_unlock(env, parent);
3576
3577 stop:
3578         rc = lfsck_layout_trans_stop(env, dev, handle, rc);
3579
3580 unlock1:
3581         lfsck_ibits_unlock(&lh, LCK_EX);
3582
3583 log:
3584         if (rc && log)
3585                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant found "
3586                        "dangling reference for: parent "DFID", child "
3587                        DFID", comp_id %u, ea_off %u, ost_idx %u, %s: "
3588                        "rc = %d\n",
3589                        lfsck_lfsck2name(lfsck), PFID(pfid), PFID(cfid),
3590                        comp_id, ea_off, ost_idx,
3591                        (lfsck->li_bookmark_ram.lb_param & LPF_CREATE_OSTOBJ) ?
3592                                 "Create the lost OST-object as required" :
3593                                 "Keep the MDT-object there by default", rc);
3594
3595         return rc;
3596 }
3597
3598 /**
3599  * Repair the MDT-object with dangling LOV EA reference.
3600  *
3601  * Prepare parameters and call __lfsck_layout_repair_dangling()
3602  * to repair the dangling LOV EA reference.
3603  *
3604  * \param[in] env       pointer to the thread context
3605  * \param[in] com       the layout LFSCK component
3606  * \param[in] pfid      the MDT-object's FID
3607  * \param[in] cfid      the FID for the OST-object to be created
3608  * \param[in] comp_id   the component ID of the OST-object in the LOV EA
3609  * \param[in] ea_off    the offset of the OST-object in the LOV EA
3610  * \param[in] ost_idx   the index of OST on which the OST-object resides
3611  *
3612  * \retval              +1 for repair successfully
3613  * \retval              0 for did nothing
3614  * \retval              negative error number on failure
3615  */
3616 static int lfsck_layout_repair_dangling(const struct lu_env *env,
3617                                         struct lfsck_component *com,
3618                                         const struct lu_fid *pfid,
3619                                         const struct lu_fid *cfid,
3620                                         __u32 comp_id, __u32 ea_off,
3621                                         __u32 ost_idx)
3622 {
3623         struct lfsck_instance *lfsck = com->lc_lfsck;
3624         struct dt_object *parent = NULL;
3625         struct dt_object *child = NULL;
3626         struct lfsck_tgt_desc *ltd;
3627         int rc;
3628         ENTRY;
3629
3630         parent = lfsck_object_find_bottom(env, lfsck, pfid);
3631         if (IS_ERR(parent))
3632                 GOTO(log, rc = PTR_ERR(parent));
3633
3634         /* The MDT-object has been removed. */
3635         if (dt_object_exists(parent) == 0)
3636                 GOTO(log, rc = 0);
3637
3638         ltd = lfsck_ltd2tgt(&lfsck->li_ost_descs, ost_idx);
3639         if (unlikely(ltd == NULL))
3640                 GOTO(log, rc = -ENODEV);
3641
3642         child = lfsck_object_find_by_dev(env, ltd->ltd_tgt, cfid);
3643         if (IS_ERR(child))
3644                 GOTO(log, rc = PTR_ERR(child));
3645
3646         /* The OST-object has been created. */
3647         if (unlikely(dt_object_exists(child) != 0))
3648                 GOTO(log, rc = 0);
3649
3650         rc = __lfsck_layout_repair_dangling(env, com, parent, child,
3651                                             comp_id, ea_off, ost_idx, false);
3652
3653         GOTO(log, rc);
3654
3655 log:
3656         if (child != NULL && !IS_ERR(child))
3657                 lfsck_object_put(env, child);
3658
3659         if (parent != NULL && !IS_ERR(parent))
3660                 lfsck_object_put(env, parent);
3661
3662         if (rc)
3663                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant found "
3664                        "dangling reference for: parent "DFID", child "
3665                        DFID", comp_id %u, ea_off %u, ost_idx %u, %s: rc = %d\n",
3666                        lfsck_lfsck2name(lfsck), PFID(pfid), PFID(cfid),
3667                        comp_id, ea_off, ost_idx,
3668                        (lfsck->li_bookmark_ram.lb_param & LPF_CREATE_OSTOBJ) ?
3669                                 "Create the lost OST-object as required" :
3670                                 "Keep the MDT-object there by default", rc);
3671
3672         return rc;
3673 }
3674
3675 /* If the OST-object does not recognize the MDT-object as its parent, and
3676  * there is no other MDT-object claims as its parent, then just trust the
3677  * given MDT-object as its parent. So update the OST-object filter_fid. */
3678 static int lfsck_layout_repair_unmatched_pair(const struct lu_env *env,
3679                                               struct lfsck_component *com,
3680                                               struct dt_object *parent,
3681                                               struct lfsck_layout_req *llr,
3682                                               struct lu_attr *la)
3683 {
3684         struct lfsck_thread_info        *info   = lfsck_env_info(env);
3685         struct filter_fid               *ff     = &info->lti_ff;
3686         struct dt_object                *child  = llr->llr_child;
3687         struct dt_device                *dev    = lfsck_obj2dev(child);
3688         const struct lu_fid             *tfid   = lu_object_fid(&parent->do_lu);
3689         struct lu_buf                   *tbuf   = &info->lti_big_buf;
3690         struct thandle                  *handle;
3691         struct lu_buf                   *buf;
3692         struct lustre_handle             lh     = { 0 };
3693         int                              rc;
3694         ENTRY;
3695
3696         rc = lfsck_ibits_lock(env, com->lc_lfsck, parent, &lh,
3697                               MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR,
3698                               LCK_EX);
3699         if (rc != 0)
3700                 GOTO(log, rc);
3701
3702         ff->ff_parent.f_seq = cpu_to_le64(tfid->f_seq);
3703         ff->ff_parent.f_oid = cpu_to_le32(tfid->f_oid);
3704         /* Currently, the filter_fid::ff_parent::f_ver is not the real parent
3705          * MDT-object's FID::f_ver, instead it is the OST-object index in its
3706          * parent MDT-object's layout EA. */
3707         ff->ff_parent.f_stripe_idx = cpu_to_le32(llr->llr_lov_idx);
3708
3709         rc = lfsck_layout_get_lovea(env, parent, tbuf);
3710         if (unlikely(rc == -ENODATA))
3711                 rc = 0;
3712         if (rc <= 0)
3713                 GOTO(unlock1, rc);
3714
3715         rc = lfsck_lov2layout(tbuf->lb_buf, ff, llr->llr_comp_id);
3716         if (rc)
3717                 GOTO(unlock1, rc);
3718
3719         buf = lfsck_buf_get(env, ff, sizeof(*ff));
3720
3721         handle = dt_trans_create(env, dev);
3722         if (IS_ERR(handle))
3723                 GOTO(unlock1, rc = PTR_ERR(handle));
3724
3725         rc = dt_declare_xattr_set(env, child, buf, XATTR_NAME_FID, 0, handle);
3726         if (rc != 0)
3727                 GOTO(stop, rc);
3728
3729         rc = dt_attr_get(env, parent, la);
3730         if (rc != 0)
3731                 GOTO(stop, rc);
3732
3733         la->la_valid = LA_UID | LA_GID;
3734         rc = dt_declare_attr_set(env, child, la, handle);
3735         if (rc != 0)
3736                 GOTO(stop, rc);
3737
3738         rc = dt_trans_start_local(env, dev, handle);
3739         if (rc != 0)
3740                 GOTO(stop, rc);
3741
3742         dt_write_lock(env, parent, 0);
3743         if (unlikely(lfsck_is_dead_obj(parent)))
3744                 GOTO(unlock2, rc = 1);
3745
3746         rc = dt_xattr_set(env, child, buf, XATTR_NAME_FID, 0, handle);
3747         if (rc != 0)
3748                 GOTO(unlock2, rc);
3749
3750         /* Get the latest parent's owner. */
3751         rc = dt_attr_get(env, parent, la);
3752         if (rc != 0)
3753                 GOTO(unlock2, rc);
3754
3755         la->la_valid = LA_UID | LA_GID;
3756         rc = dt_attr_set(env, child, la, handle);
3757
3758         GOTO(unlock2, rc);
3759
3760 unlock2:
3761         dt_write_unlock(env, parent);
3762
3763 stop:
3764         rc = lfsck_layout_trans_stop(env, dev, handle, rc);
3765
3766 unlock1:
3767         lfsck_ibits_unlock(&lh, LCK_EX);
3768
3769 log:
3770         if (rc)
3771                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant repaired "
3772                        "unmatched MDT-OST pair for: parent "DFID
3773                        ", child "DFID", comp_id %u, OST-index %u, "
3774                        "stripe-index %u, owner %u/%u: rc = %d\n",
3775                        lfsck_lfsck2name(com->lc_lfsck),
3776                        PFID(lfsck_dto2fid(parent)),
3777                        PFID(lfsck_dto2fid(child)),
3778                        llr->llr_comp_id, llr->llr_ost_idx, llr->llr_lov_idx,
3779                        la->la_uid, la->la_gid, rc);
3780
3781         return rc;
3782 }
3783
3784 /* If there are more than one MDT-objects claim as the OST-object's parent,
3785  * and the OST-object only recognizes one of them, then we need to generate
3786  * new OST-object(s) with new fid(s) for the non-recognized MDT-object(s). */
3787 static int lfsck_layout_repair_multiple_references(const struct lu_env *env,
3788                                                    struct lfsck_component *com,
3789                                                    struct dt_object *parent,
3790                                                    struct lfsck_layout_req *llr,
3791                                                    struct lu_attr *la)
3792 {
3793         struct lfsck_thread_info        *info   = lfsck_env_info(env);
3794         struct dt_allocation_hint       *hint   = &info->lti_hint;
3795         struct dt_object_format         *dof    = &info->lti_dof;
3796         struct ost_id                   *oi     = &info->lti_oi;
3797         struct lu_buf                   *buf    = &info->lti_big_buf;
3798         struct lfsck_instance           *lfsck  = com->lc_lfsck;
3799         struct dt_device                *dev;
3800         struct lu_device                *d      =
3801                                 &lfsck_obj2dev(llr->llr_child)->dd_lu_dev;
3802         struct lu_object                *o;
3803         struct lu_object                *n;
3804         struct dt_object                *child  = NULL;
3805         struct thandle                  *handle = NULL;
3806         struct lov_mds_md_v1            *lmm;
3807         struct lov_ost_data_v1          *objs;
3808         const struct lu_fid             *pfid   = lfsck_dto2fid(parent);
3809         struct lu_fid                    tfid;
3810         struct lustre_handle             lh     = { 0 };
3811         __u32                            magic;
3812         __u32                            index;
3813         int                              rc;
3814         ENTRY;
3815
3816         /* We use two separated transactions to repair the inconsistency.
3817          *
3818          * 1) create the child (OST-object).
3819          * 2) update the parent LOV EA according to the child's FID.
3820          *
3821          * If 1) succeed, but 2) failed or aborted, then such OST-object will be
3822          * handled as orphan when the layout LFSCK run next time.
3823          *
3824          * If 1) failed, but 2) succeed, then such OST-object will be re-created
3825          * as dangling referened case when the layout LFSCK run next time. */
3826
3827         /* The 1st transaction. */
3828         o = lu_object_anon(env, d, NULL);
3829         if (IS_ERR(o))
3830                 GOTO(log, rc = PTR_ERR(o));
3831
3832         n = lu_object_locate(o->lo_header, d->ld_type);
3833         if (unlikely(n == NULL)) {
3834                 lu_object_put_nocache(env, o);
3835
3836                 GOTO(log, rc = -EINVAL);
3837         }
3838
3839         child = container_of(n, struct dt_object, do_lu);
3840         memset(hint, 0, sizeof(*hint));
3841         rc = dt_attr_get(env, parent, la);
3842         if (rc != 0)
3843                 GOTO(log, rc);
3844
3845         la->la_valid = LA_UID | LA_GID;
3846         memset(dof, 0, sizeof(*dof));
3847
3848         dev = lfsck_obj2dev(child);
3849         handle = dt_trans_create(env, dev);
3850         if (IS_ERR(handle))
3851                 GOTO(log, rc = PTR_ERR(handle));
3852
3853         rc = dt_declare_create(env, child, la, hint, dof, handle);
3854         if (rc != 0)
3855                 GOTO(stop, rc);
3856
3857         rc = dt_trans_start_local(env, dev, handle);
3858         if (rc != 0)
3859                 GOTO(stop, rc);
3860
3861         rc = dt_create(env, child, la, hint, dof, handle);
3862         dt_trans_stop(env, dev, handle);
3863         handle = NULL;
3864         if (rc != 0)
3865                 GOTO(log, rc);
3866
3867         rc = lfsck_ibits_lock(env, lfsck, parent, &lh,
3868                               MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR,
3869                               LCK_EX);
3870         if (rc != 0)
3871                 GOTO(log, rc);
3872
3873         /* The 2nd transaction. */
3874
3875         /* XXX: Generally, we should use bottom device (OSD) to update parent
3876          *      LOV EA. But because the LOD-object still references the wrong
3877          *      OSP-object that should be detached after the parent's LOV EA
3878          *      refreshed. Unfortunately, there is no suitable API for that.
3879          *      So we have to make the LOD to re-load the OSP-object(s) via
3880          *      replacing the LOV EA against the LOD-object.
3881          *
3882          *      Once the DNE2 patches have been landed, we can replace the
3883          *      LOD device with the OSD device. LU-6230. */
3884
3885         dev = lfsck->li_next;
3886         parent = lfsck_object_locate(dev, parent);
3887         if (IS_ERR(parent))
3888                 GOTO(log, rc = PTR_ERR(parent));
3889
3890         handle = dt_trans_create(env, dev);
3891         if (IS_ERR(handle))
3892                 GOTO(log, rc = PTR_ERR(handle));
3893
3894         rc = dt_declare_xattr_set(env, parent, buf, XATTR_NAME_LOV,
3895                                   LU_XATTR_REPLACE, handle);
3896         if (rc != 0)
3897                 GOTO(stop, rc);
3898
3899         rc = dt_trans_start_local(env, dev, handle);
3900         if (rc != 0)
3901                 GOTO(stop, rc);
3902
3903         dt_write_lock(env, parent, 0);
3904         if (unlikely(lfsck_is_dead_obj(parent)))
3905                 GOTO(unlock, rc = 0);
3906
3907         rc = lfsck_layout_get_lovea(env, parent, buf);
3908         if (unlikely(rc == -ENODATA))
3909                 rc = 0;
3910         if (rc <= 0)
3911                 GOTO(unlock, rc);
3912
3913         lmm = buf->lb_buf;
3914         magic = le32_to_cpu(lmm->lmm_magic);
3915         if (magic == LOV_MAGIC_COMP_V1) {
3916                 struct lov_comp_md_v1 *lcm = buf->lb_buf;
3917                 struct lov_comp_md_entry_v1 *lcme;
3918                 __u16 count = le16_to_cpu(lcm->lcm_entry_count);
3919                 int i;
3920
3921                 LASSERT(llr->llr_comp_id != 0);
3922
3923                 for (i = 0; i < count; i++) {
3924                         lcme = &lcm->lcm_entries[i];
3925                         if (le32_to_cpu(lcme->lcme_id) == llr->llr_comp_id) {
3926                                 LASSERT(le32_to_cpu(lcme->lcme_flags) &
3927                                         LCME_FL_INIT);
3928
3929                                 le32_add_cpu(&lcm->lcm_layout_gen, 1);
3930                                 lmm = buf->lb_buf +
3931                                         le32_to_cpu(lcme->lcme_offset);
3932                                 magic = le32_to_cpu(lmm->lmm_magic);
3933                                 goto set;
3934                         }
3935                 }
3936
3937                 GOTO(unlock, rc = 0);
3938         }
3939
3940 set:
3941         if (magic == LOV_MAGIC_V1) {
3942                 objs = &lmm->lmm_objects[llr->llr_lov_idx];
3943         } else {
3944                 LASSERT(magic == LOV_MAGIC_V3);
3945                 objs =
3946                 &((struct lov_mds_md_v3 *)lmm)->lmm_objects[llr->llr_lov_idx];
3947         }
3948
3949         ostid_le_to_cpu(&objs->l_ost_oi, oi);
3950         index = le32_to_cpu(objs->l_ost_idx);
3951         rc = ostid_to_fid(&tfid, oi, index);
3952         /* Someone changed layout during the LFSCK, no need to repair then. */
3953         if (rc == 0 && !lu_fid_eq(&tfid, lu_object_fid(&llr->llr_child->do_lu)))
3954                 GOTO(unlock, rc = 0);
3955
3956         lmm->lmm_layout_gen = cpu_to_le16(le16_to_cpu(lmm->lmm_layout_gen) + 1);
3957         fid_to_ostid(lu_object_fid(&child->do_lu), oi);
3958         ostid_cpu_to_le(oi, &objs->l_ost_oi);
3959         objs->l_ost_gen = cpu_to_le32(0);
3960         objs->l_ost_idx = cpu_to_le32(llr->llr_ost_idx);
3961         rc = dt_xattr_set(env, parent, buf, XATTR_NAME_LOV,
3962                           LU_XATTR_REPLACE, handle);
3963
3964         GOTO(unlock, rc = (rc == 0 ? 1 : rc));
3965
3966 unlock:
3967         dt_write_unlock(env, parent);
3968
3969 stop:
3970         if (handle != NULL)
3971                 dt_trans_stop(env, dev, handle);
3972
3973 log:
3974         lfsck_ibits_unlock(&lh, LCK_EX);
3975         if (child != NULL)
3976                 lfsck_object_put(env, child);
3977
3978         if (rc)
3979                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant repaired "
3980                        "multiple references for: parent "DFID", comp_id %u, "
3981                        "OST-index %u, stripe-index %u, owner %u/%u: rc = %d\n",
3982                        lfsck_lfsck2name(lfsck), PFID(pfid),
3983                        llr->llr_comp_id, llr->llr_ost_idx, llr->llr_lov_idx,
3984                        la->la_uid, la->la_gid, rc);
3985
3986         return rc;
3987 }
3988
3989 /* If the MDT-object and the OST-object have different owner information,
3990  * then trust the MDT-object, because the normal chown/chgrp handle order
3991  * is from MDT to OST, and it is possible that some chown/chgrp operation
3992  * is partly done. */
3993 static int lfsck_layout_repair_owner(const struct lu_env *env,
3994                                      struct lfsck_component *com,
3995                                      struct dt_object *parent,
3996                                      struct lfsck_layout_req *llr,
3997                                      struct lu_attr *pla,
3998                                      const struct lu_attr *cla)
3999 {
4000         struct lfsck_thread_info        *info   = lfsck_env_info(env);
4001         struct lu_attr                  *tla    = &info->lti_la2;
4002         struct dt_object                *child  = llr->llr_child;
4003         struct dt_device                *dev    = lfsck_obj2dev(child);
4004         struct thandle                  *handle;
4005         int                              rc;
4006         dt_obj_version_t                 version;
4007         ENTRY;
4008
4009         tla->la_uid = pla->la_uid;
4010         tla->la_gid = pla->la_gid;
4011         tla->la_valid = LA_UID | LA_GID;
4012         handle = dt_trans_create(env, dev);
4013         if (IS_ERR(handle))
4014                 GOTO(log, rc = PTR_ERR(handle));
4015
4016         rc = dt_declare_attr_set(env, child, tla, handle);
4017         if (rc != 0)
4018                 GOTO(stop, rc);
4019
4020         rc = dt_trans_start_local(env, dev, handle);
4021         if (rc != 0)
4022                 GOTO(stop, rc);
4023
4024         /* Use the dt_object lock to serialize with destroy and attr_set. */
4025         dt_read_lock(env, parent, 0);
4026         if (unlikely(lfsck_is_dead_obj(parent)))
4027                 GOTO(unlock, rc = 1);
4028
4029         version = dt_version_get(env, child);
4030         if (version == -EOPNOTSUPP)
4031                 version = 0;
4032
4033         /* Get the latest parent's owner. */
4034         rc = dt_attr_get(env, parent, pla);
4035         if (rc != 0)
4036                 GOTO(unlock, rc);
4037
4038         /* Some others chown/chgrp during the LFSCK, needs to do nothing. */
4039         if (unlikely((!version && tla->la_ctime == 0) ||
4040                      tla->la_uid != pla->la_uid || tla->la_gid != pla->la_gid))
4041                 rc = 1;
4042         else
4043                 rc = dt_attr_set(env, child, tla, handle);
4044
4045         GOTO(unlock, rc);
4046
4047 unlock:
4048         dt_read_unlock(env, parent);
4049
4050 stop:
4051         rc = lfsck_layout_trans_stop(env, dev, handle, rc);
4052
4053 log:
4054         if (rc != 0)
4055                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant repaired "
4056                        "inconsistent file owner for: parent "DFID", child "DFID
4057                        ", OST-index %u, stripe-index %u, old owner %u/%u, "
4058                        "new owner %u/%u: rc = %d\n",
4059                        lfsck_lfsck2name(com->lc_lfsck),
4060                        PFID(lfsck_dto2fid(parent)), PFID(lfsck_dto2fid(child)),
4061                        llr->llr_ost_idx, llr->llr_lov_idx,
4062                        cla->la_uid, cla->la_gid, tla->la_uid, tla->la_gid, rc);
4063
4064         return rc;
4065 }
4066
4067 #define CDEBUG_UNMATCHED_PAIR(lfsck, lso, pfid, cfid, msg)               \
4068         CDEBUG(D_LFSCK, "%s:("DFID"|"DFID")/"DFID":XATTR %s: %s\n",      \
4069                lfsck_lfsck2name(lfsck), PFID(&lso->lso_fid), PFID(pfid), \
4070                PFID(cfid), XATTR_NAME_FID, msg);
4071
4072 /* Check whether the OST-object correctly back points to the
4073  * MDT-object (@parent) via the XATTR_NAME_FID xattr (@pfid). */
4074 static int lfsck_layout_check_parent(const struct lu_env *env,
4075                                      struct lfsck_component *com,
4076                                      struct lfsck_assistant_object *lso,
4077                                      struct filter_fid *ff,
4078                                      const struct lu_fid *cfid,
4079                                      const struct lu_attr *cla,
4080                                      struct lfsck_layout_req *llr)
4081 {
4082         struct lfsck_thread_info        *info   = lfsck_env_info(env);
4083         struct lu_buf                   *buf    = &info->lti_big_buf;
4084         struct lu_fid                   *pfid   = &info->lti_fid;
4085         struct dt_object                *tobj;
4086         struct lov_mds_md_v1            *lmm;
4087         struct lov_ost_data_v1          *objs;
4088         struct lustre_handle             lh     = { 0 };
4089         struct lfsck_instance           *lfsck  = com->lc_lfsck;
4090         int                              rc;
4091         int                              i;
4092         __u32                            magic;
4093         __u32                            idx;
4094         __u16                            count;
4095         ENTRY;
4096
4097         *pfid = ff->ff_parent;
4098         idx = pfid->f_stripe_idx;
4099         pfid->f_ver = 0;
4100
4101         if (unlikely(!fid_is_sane(pfid))) {
4102                 CDEBUG_UNMATCHED_PAIR(lfsck, lso, pfid, cfid,
4103                                       "the parent FID is invalid");
4104
4105                 RETURN(LLIT_UNMATCHED_PAIR);
4106         }
4107
4108         if (lu_fid_eq(pfid, &lso->lso_fid)) {
4109                 if (likely(llr->llr_lov_idx == idx))
4110                         RETURN(0);
4111
4112                 CDEBUG_UNMATCHED_PAIR(lfsck, lso, pfid, cfid,
4113                                       "the stripe index is unmatched");
4114
4115                 RETURN(LLIT_UNMATCHED_PAIR);
4116         }
4117
4118         tobj = lfsck_object_find_bottom(env, com->lc_lfsck, pfid);
4119         if (IS_ERR(tobj))
4120                 RETURN(PTR_ERR(tobj));
4121
4122         if (dt_object_exists(tobj) == 0) {
4123                 CDEBUG_UNMATCHED_PAIR(lfsck, lso, pfid, cfid,
4124                                       "the parent is nonexistent");
4125
4126                 GOTO(out, rc = LLIT_UNMATCHED_PAIR);
4127         }
4128
4129         if (lfsck_is_dead_obj(tobj)) {
4130                 CDEBUG_UNMATCHED_PAIR(lfsck, lso, pfid, cfid,
4131                                       "the parent is dead object");
4132
4133                 GOTO(out, rc = LLIT_UNMATCHED_PAIR);
4134         }
4135
4136         if (!S_ISREG(lfsck_object_type(tobj))) {
4137                 CDEBUG_UNMATCHED_PAIR(lfsck, lso, pfid, cfid,
4138                                       "the parent is not a regular file");
4139
4140                 GOTO(out, rc = LLIT_UNMATCHED_PAIR);
4141         }
4142
4143         /* Load the tobj's layout EA, in spite of it is a local MDT-object or
4144          * remote one on another MDT. Then check whether the given OST-object
4145          * is in such layout. If yes, it is multiple referenced, otherwise it
4146          * is unmatched referenced case. */
4147         rc = lfsck_layout_get_lovea(env, tobj, buf);
4148         if (rc == 0 || rc == -ENODATA || rc == -ENOENT) {
4149                 CDEBUG_UNMATCHED_PAIR(lfsck, lso, pfid, cfid,
4150                                       "the parent has no stripe data");
4151
4152                 GOTO(out, rc = LLIT_UNMATCHED_PAIR);
4153         }
4154
4155         if (unlikely(rc == -EOPNOTSUPP))
4156                 GOTO(out, rc = LLIT_NONE);
4157
4158         if (rc < 0)
4159                 GOTO(out, rc);
4160
4161         lmm = buf->lb_buf;
4162         magic = le32_to_cpu(lmm->lmm_magic);
4163         if (magic == LOV_MAGIC_COMP_V1) {
4164                 struct lov_comp_md_v1 *lcm = buf->lb_buf;
4165                 struct lov_comp_md_entry_v1 *lcme;
4166
4167                 if (ff->ff_layout.ol_comp_id == 0) {
4168                         CDEBUG_UNMATCHED_PAIR(lfsck, lso, pfid, cfid,
4169                                               "the parent has incorrect comp_id");
4170
4171                         GOTO(out, rc = LLIT_UNMATCHED_PAIR);
4172                 }
4173
4174                 count = le16_to_cpu(lcm->lcm_entry_count);
4175                 for (i = 0; i < count; i++) {
4176                         lcme = &lcm->lcm_entries[i];
4177                         if (le32_to_cpu(lcme->lcme_id) ==
4178                             ff->ff_layout.ol_comp_id) {
4179                                 lmm = buf->lb_buf +
4180                                         le32_to_cpu(lcme->lcme_offset);
4181                                 magic = le32_to_cpu(lmm->lmm_magic);
4182                                 if (!(le32_to_cpu(lcme->lcme_flags) &
4183                                       LCME_FL_INIT)) {
4184                                         CDEBUG_UNMATCHED_PAIR(lfsck, lso, pfid,
4185                                                               cfid,
4186                                                               "the parent has uninitialized component");
4187
4188                                         GOTO(out, rc = LLIT_UNMATCHED_PAIR);
4189                                 }
4190
4191                                 goto further;
4192                         }
4193                 }
4194
4195                 CDEBUG_UNMATCHED_PAIR(lfsck, lso, pfid, cfid,
4196                                       "the parent has no matched comp_id");
4197
4198                 GOTO(out, rc = LLIT_UNMATCHED_PAIR);
4199         }
4200
4201 further:
4202         if (magic == LOV_MAGIC_V1) {
4203                 objs = &lmm->lmm_objects[0];
4204         } else {
4205                 LASSERT(magic == LOV_MAGIC_V3);
4206                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[0];
4207         }
4208
4209         count = le16_to_cpu(lmm->lmm_stripe_count);
4210         for (i = 0; i < count; i++, objs++) {
4211                 struct lu_fid           *tfid   = &info->lti_fid2;
4212                 struct ost_id           *oi     = &info->lti_oi;
4213                 __u32                    idx2;
4214
4215                 if (lovea_slot_is_dummy(objs))
4216                         continue;
4217
4218                 ostid_le_to_cpu(&objs->l_ost_oi, oi);
4219                 idx2 = le32_to_cpu(objs->l_ost_idx);
4220                 rc = ostid_to_fid(tfid, oi, idx2);
4221                 if (rc != 0) {
4222                         CDEBUG(D_LFSCK, "%s: the parent "DFID" contains "
4223                                "invalid layout EA at the slot %d, index %u\n",
4224                                lfsck_lfsck2name(com->lc_lfsck),
4225                                PFID(pfid), i, idx2);
4226
4227                         GOTO(out, rc = LLIT_UNMATCHED_PAIR);
4228                 }
4229
4230                 if (lu_fid_eq(cfid, tfid)) {
4231                         rc = lfsck_ibits_lock(env, com->lc_lfsck, tobj, &lh,
4232                                               MDS_INODELOCK_UPDATE |
4233                                               MDS_INODELOCK_LAYOUT |
4234                                               MDS_INODELOCK_XATTR,
4235                                               LCK_EX);
4236                         if (rc != 0)
4237                                 GOTO(out, rc);
4238
4239                         dt_read_lock(env, tobj, 0);
4240
4241                         /* For local MDT-object, re-check existence
4242                          * after taken the lock. */
4243                         if (!dt_object_remote(tobj)) {
4244                                 if (dt_object_exists(tobj) == 0 ||
4245                                     lfsck_is_dead_obj(tobj)) {
4246                                         CDEBUG_UNMATCHED_PAIR(lfsck, lso, pfid,
4247                                                               cfid,
4248                                                               "the parent doesn't exist anymore after lock");
4249
4250                                         rc = LLIT_UNMATCHED_PAIR;
4251                                 } else {
4252                                         rc = LLIT_MULTIPLE_REFERENCED;
4253                                 }
4254
4255                                 GOTO(unlock, rc);
4256                         }
4257
4258                         /* For migration case, the new MDT-object and old
4259                          * MDT-object may reference the same OST-object at
4260                          * some migration internal time.
4261                          *
4262                          * For remote MDT-object, the local MDT may not know
4263                          * whether it has been removed or not.  Try checking
4264                          * for a non-existent xattr to check if this object
4265                          * has been been removed or not. */
4266                         rc = dt_xattr_get(env, tobj, &LU_BUF_NULL,
4267                                           XATTR_NAME_DUMMY);
4268                         if (unlikely(rc == -ENOENT || rc >= 0)) {
4269                                 CDEBUG_UNMATCHED_PAIR(lfsck, lso, pfid, cfid,
4270                                                       "the parent is remote object and nonexistent after lock");
4271
4272                                 rc = LLIT_UNMATCHED_PAIR;
4273                         } else if (rc == -ENODATA) {
4274                                 rc = LLIT_MULTIPLE_REFERENCED;
4275                         }
4276
4277                         GOTO(unlock, rc);
4278                 }
4279         }
4280
4281         CDEBUG_UNMATCHED_PAIR(lfsck, lso, pfid, cfid,
4282                               "the parent has no matched stripe");
4283
4284         GOTO(out, rc = LLIT_UNMATCHED_PAIR);
4285
4286 unlock:
4287         if (lustre_handle_is_used(&lh)) {
4288                 dt_read_unlock(env, tobj);
4289                 lfsck_ibits_unlock(&lh, LCK_EX);
4290         }
4291
4292 out:
4293         lfsck_object_put(env, tobj);
4294
4295         return rc;
4296 }
4297
4298 static int lfsck_layout_assistant_handler_p1(const struct lu_env *env,
4299                                              struct lfsck_component *com,
4300                                              struct lfsck_assistant_req *lar)
4301 {
4302         struct lfsck_layout_req              *llr    =
4303                 container_of(lar, struct lfsck_layout_req, llr_lar);
4304         struct lfsck_assistant_object        *lso    = lar->lar_parent;
4305         struct lfsck_layout                  *lo     = com->lc_file_ram;
4306         struct lfsck_thread_info             *info   = lfsck_env_info(env);
4307         struct filter_fid                    *ff     = &info->lti_ff;
4308         struct lu_buf buf = { .lb_buf = ff,
4309                               .lb_len = sizeof(*ff) };
4310         struct dt_object                     *parent = NULL;
4311         struct dt_object                     *child  = llr->llr_child;
4312         struct lu_attr                       *pla    = &lso->lso_attr;
4313         struct lu_attr                       *cla    = &info->lti_la;
4314         struct lfsck_instance                *lfsck  = com->lc_lfsck;
4315         struct lfsck_bookmark                *bk     = &lfsck->li_bookmark_ram;
4316         enum lfsck_layout_inconsistency_type  type   = LLIT_NONE;
4317         int                                   rc;
4318         ENTRY;
4319
4320         if (lso->lso_dead)
4321                 RETURN(0);
4322
4323         CFS_FAIL_TIMEOUT(OBD_FAIL_LFSCK_ENGINE_DELAY, cfs_fail_val);
4324
4325         rc = dt_attr_get(env, child, cla);
4326         if (rc == -ENOENT) {
4327                 parent = lfsck_assistant_object_load(env, lfsck, lso);
4328                 if (IS_ERR(parent)) {
4329                         rc = PTR_ERR(parent);
4330
4331                         RETURN(rc == -ENOENT ? 0 : rc);
4332                 }
4333
4334                 type = LLIT_DANGLING;
4335                 goto repair;
4336         }
4337
4338         if (rc != 0)
4339                 GOTO(out, rc);
4340
4341         lfsck_buf_init(&buf, ff, sizeof(*ff));
4342         rc = dt_xattr_get(env, child, &buf, XATTR_NAME_FID);
4343         if (unlikely(rc > 0 && rc < sizeof(struct lu_fid))) {
4344                 CDEBUG(D_LFSCK, "%s:"DFID"/"DFID": "
4345                        "the child object's %s is corrupted\n",
4346                        lfsck_lfsck2name(lfsck), PFID(&lso->lso_fid),
4347                        PFID(lu_object_fid(&child->do_lu)),
4348                        XATTR_NAME_FID);
4349
4350                 type = LLIT_UNMATCHED_PAIR;
4351                 goto repair;
4352         }
4353
4354         if (rc < 0 && rc != -ENODATA)
4355                 GOTO(out, rc);
4356
4357         if (rc == 0 || rc == -ENODATA)
4358                 GOTO(check_owner, rc = 0);
4359
4360         filter_fid_le_to_cpu(ff, ff, sizeof(*ff));
4361         rc = lfsck_layout_check_parent(env, com, lso, ff,
4362                                        lu_object_fid(&child->do_lu), cla, llr);
4363         if (rc > 0) {
4364                 type = rc;
4365                 goto repair;
4366         }
4367
4368         if (rc < 0)
4369                 GOTO(out, rc);
4370
4371 check_owner:
4372         /* Someone may has changed the owner after the parent attr pre-loaded.
4373          * It can be handled later inside the lfsck_layout_repair_owner(). */
4374         if (unlikely(cla->la_uid != pla->la_uid ||
4375                      cla->la_gid != pla->la_gid)) {
4376                 type = LLIT_INCONSISTENT_OWNER;
4377                 goto repair;
4378         }
4379
4380 repair:
4381         if (type == LLIT_NONE)
4382                 GOTO(out, rc = 0);
4383
4384         if (bk->lb_param & LPF_DRYRUN)
4385                 GOTO(out, rc = 1);
4386
4387         if (parent == NULL) {
4388                 parent = lfsck_assistant_object_load(env, lfsck, lso);
4389                 if (IS_ERR(parent)) {
4390                         rc = PTR_ERR(parent);
4391
4392                         if (rc == -ENOENT)
4393                                 RETURN(0);
4394
4395                         GOTO(out, rc);
4396                 }
4397         }
4398
4399         switch (type) {
4400         case LLIT_DANGLING:
4401                 if (bk->lb_param & LPF_DELAY_CREATE_OSTOBJ)
4402                         rc = lfsck_layout_ins_dangling_rec(env, com,
4403                                 lfsck_dto2fid(parent), lfsck_dto2fid(child),
4404                                 llr->llr_comp_id, llr->llr_lov_idx,
4405                                 llr->llr_ost_idx);
4406                 else
4407                         rc = __lfsck_layout_repair_dangling(env, com, parent,
4408                                                             llr->llr_child,
4409                                                             llr->llr_comp_id,
4410                                                             llr->llr_lov_idx,
4411                                                             llr->llr_ost_idx,
4412                                                             true);
4413                 break;
4414         case LLIT_UNMATCHED_PAIR:
4415                 rc = lfsck_layout_repair_unmatched_pair(env, com, parent,
4416                                                         llr, pla);
4417                 break;
4418         case LLIT_MULTIPLE_REFERENCED:
4419                 rc = lfsck_layout_repair_multiple_references(env, com, parent,
4420                                                              llr, pla);
4421                 break;
4422         case LLIT_INCONSISTENT_OWNER:
4423                 rc = lfsck_layout_repair_owner(env, com, parent, llr, pla, cla);
4424                 break;
4425         default:
4426                 rc = 0;
4427                 break;
4428         }
4429
4430         GOTO(out, rc);
4431
4432 out:
4433         down_write(&com->lc_sem);
4434         if (rc < 0) {
4435                 struct lfsck_assistant_data *lad = com->lc_data;
4436
4437                 if (unlikely(test_bit(LAD_EXIT, &lad->lad_flags))) {
4438                         rc = 0;
4439                 } else if (rc == -ENOTCONN || rc == -ESHUTDOWN ||
4440                            rc == -ETIMEDOUT || rc == -EHOSTDOWN ||
4441                            rc == -EHOSTUNREACH) {
4442                         /* If cannot touch the target server,
4443                          * mark the LFSCK as INCOMPLETE. */
4444                         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant fail to "
4445                                "talk with OST %x: rc = %d\n",
4446                                lfsck_lfsck2name(lfsck), llr->llr_ost_idx, rc);
4447                         lfsck_lad_set_bitmap(env, com, llr->llr_ost_idx);
4448                         lo->ll_objs_skipped++;
4449                         rc = 0;
4450                 } else {
4451                         lfsck_layout_record_failure(env, lfsck, lo);
4452                 }
4453         } else if (rc > 0 && (type != LLIT_DANGLING ||
4454                               !(bk->lb_param & LPF_DELAY_CREATE_OSTOBJ))) {
4455                 LASSERTF(type > LLIT_NONE && type <= LLIT_MAX,
4456                          "unknown type = %d\n", type);
4457
4458                 lo->ll_objs_repaired[type - 1]++;
4459                 if (bk->lb_param & LPF_DRYRUN &&
4460                     unlikely(lo->ll_pos_first_inconsistent == 0))
4461                         lo->ll_pos_first_inconsistent =
4462                         lfsck->li_obj_oit->do_index_ops->dio_it.store(env,
4463                                                         lfsck->li_di_oit);
4464         }
4465         up_write(&com->lc_sem);
4466
4467         if (parent != NULL && !IS_ERR(parent))
4468                 lfsck_object_put(env, parent);
4469
4470         return rc;
4471 }
4472
4473 static int
4474 lfsck_layout_double_scan_one_trace_file(const struct lu_env *env,
4475                                         struct lfsck_component *com,
4476                                         struct dt_object *obj, bool first)
4477 {
4478         struct lfsck_instance *lfsck = com->lc_lfsck;
4479         struct ptlrpc_thread *thread = &lfsck->li_thread;
4480         struct lfsck_bookmark *bk = &lfsck->li_bookmark_ram;
4481         struct lfsck_layout *lo = com->lc_file_ram;
4482         const struct dt_it_ops *iops = &obj->do_index_ops->dio_it;
4483         struct dt_it *di;
4484         struct dt_key *key;
4485         struct lfsck_layout_dangling_key *parent =
4486                                         &lfsck_env_info(env)->lti_lldk;
4487         struct lu_fid *cfid = &lfsck_env_info(env)->lti_fid3;
4488         __u32 ost_idx;
4489         int rc;
4490         ENTRY;
4491
4492         di = iops->init(env, obj, 0);
4493         if (IS_ERR(di))
4494                 RETURN(PTR_ERR(di));
4495
4496         if (first)
4497                 lldk_cpu_to_be(parent, &lo->ll_lldk_latest_scanned_phase2);
4498         else
4499                 memset(parent, 0, sizeof(*parent));
4500         rc = iops->get(env, di, (const struct dt_key *)parent);
4501         if (rc < 0)
4502                 GOTO(fini, rc);
4503
4504         if (first) {
4505                 /* The start one either has been processed or does not exist,
4506                  * skip it. */
4507                 rc = iops->next(env, di);
4508                 if (rc != 0)
4509                         GOTO(put, rc);
4510         }
4511
4512         do {
4513                 if (CFS_FAIL_TIMEOUT(OBD_FAIL_LFSCK_DELAY3, cfs_fail_val) &&
4514                     unlikely(!thread_is_running(thread)))
4515                         GOTO(put, rc = 0);
4516
4517                 key = iops->key(env, di);
4518                 if (IS_ERR(key)) {
4519                         rc = PTR_ERR(key);
4520                         if (rc == -ENOENT)
4521                                 GOTO(put, rc = 1);
4522
4523                         goto checkpoint;
4524                 }
4525
4526                 lldk_be_to_cpu(parent,
4527                                 (const struct lfsck_layout_dangling_key *)key);
4528                 if (!fid_is_sane(&parent->lldk_fid)) {
4529                         rc = 0;
4530                         goto checkpoint;
4531                 }
4532
4533                 rc = iops->rec(env, di, (struct dt_rec *)cfid, 0);
4534                 if (rc == 0) {
4535                         fid_be_to_cpu(cfid, cfid);
4536                         ost_idx = cfid->f_ver;
4537                         cfid->f_ver = 0;
4538                         if (!fid_is_sane(cfid)) {
4539                                 rc = 0;
4540                                 goto checkpoint;
4541                         }
4542
4543                         rc = lfsck_layout_repair_dangling(env, com,
4544                                         &parent->lldk_fid, cfid,
4545                                         parent->lldk_comp_id,
4546                                         parent->lldk_ea_off, ost_idx);
4547                 }
4548
4549 checkpoint:
4550                 down_write(&com->lc_sem);
4551                 com->lc_new_checked++;
4552                 com->lc_new_scanned++;
4553                 if (rc >= 0)
4554                         lo->ll_lldk_latest_scanned_phase2 = *parent;
4555
4556                 if (rc > 0)
4557                         lo->ll_objs_repaired[LLIT_DANGLING - 1]++;
4558                 else if (rc < 0)
4559                         lo->ll_objs_failed_phase2++;
4560                 up_write(&com->lc_sem);
4561
4562                 if (rc < 0 && bk->lb_param & LPF_FAILOUT)
4563                         GOTO(put, rc);
4564
4565                 if (unlikely(com->lc_time_next_checkpoint <=
4566                              ktime_get_seconds()) &&
4567                     com->lc_new_checked != 0) {
4568                         down_write(&com->lc_sem);
4569                         lo->ll_run_time_phase2 += ktime_get_seconds() -
4570                                                   com->lc_time_last_checkpoint;
4571                         lo->ll_time_last_checkpoint = ktime_get_real_seconds();
4572                         lo->ll_objs_checked_phase2 += com->lc_new_checked;
4573                         com->lc_new_checked = 0;
4574                         lfsck_layout_store(env, com);
4575                         up_write(&com->lc_sem);
4576
4577                         com->lc_time_last_checkpoint = ktime_get_seconds();
4578                         com->lc_time_next_checkpoint =
4579                                 com->lc_time_last_checkpoint +
4580                                 LFSCK_CHECKPOINT_INTERVAL;
4581                 }
4582
4583                 lfsck_control_speed_by_self(com);
4584                 if (unlikely(!thread_is_running(thread)))
4585                         GOTO(put, rc = 0);
4586
4587                 rc = iops->next(env, di);
4588         } while (rc == 0);
4589
4590         GOTO(put, rc);
4591
4592 put:
4593         iops->put(env, di);
4594
4595 fini:
4596         iops->fini(env, di);
4597
4598         return rc;
4599 }
4600
4601 static int lfsck_layout_assistant_handler_p2(const struct lu_env *env,
4602                                              struct lfsck_component *com)
4603 {
4604         struct lfsck_assistant_data     *lad    = com->lc_data;
4605         struct lfsck_instance           *lfsck  = com->lc_lfsck;
4606         struct lfsck_bookmark           *bk     = &lfsck->li_bookmark_ram;
4607         struct lfsck_tgt_descs          *ltds   = &lfsck->li_ost_descs;
4608         struct lfsck_tgt_desc           *ltd;
4609         int                              rc     = 0;
4610         ENTRY;
4611
4612         CDEBUG(D_LFSCK, "%s: layout LFSCK phase2 scan start\n",
4613                lfsck_lfsck2name(lfsck));
4614
4615         spin_lock(&ltds->ltd_lock);
4616         while (!list_empty(&lad->lad_ost_phase2_list)) {
4617                 ltd = list_entry(lad->lad_ost_phase2_list.next,
4618                                  struct lfsck_tgt_desc,
4619                                  ltd_layout_phase_list);
4620                 list_del_init(&ltd->ltd_layout_phase_list);
4621                 if (bk->lb_param & LPF_OST_ORPHAN) {
4622                         spin_unlock(&ltds->ltd_lock);
4623                         rc = lfsck_layout_scan_orphan(env, com, ltd);
4624                         if (rc != 0 && bk->lb_param & LPF_FAILOUT)
4625                                 RETURN(rc);
4626
4627                         if (unlikely(test_bit(LAD_EXIT, &lad->lad_flags) ||
4628                                      !thread_is_running(&lfsck->li_thread)))
4629                                 RETURN(0);
4630                         spin_lock(&ltds->ltd_lock);
4631                 }
4632         }
4633
4634         if (list_empty(&lad->lad_ost_phase1_list))
4635                 rc = 1;
4636         else
4637                 rc = 0;
4638         spin_unlock(&ltds->ltd_lock);
4639
4640         if (rc == 1 && bk->lb_param & LPF_OST_ORPHAN) {
4641                 struct lfsck_layout *lo = com->lc_file_ram;
4642                 int i;
4643
4644                 com->lc_new_checked = 0;
4645                 com->lc_new_scanned = 0;
4646                 com->lc_time_last_checkpoint = ktime_get_seconds();
4647                 com->lc_time_next_checkpoint = com->lc_time_last_checkpoint +
4648                                                LFSCK_CHECKPOINT_INTERVAL;
4649
4650                 i = lfsck_sub_trace_file_fid2idx(
4651                                 &lo->ll_lldk_latest_scanned_phase2.lldk_fid);
4652                 rc = lfsck_layout_double_scan_one_trace_file(env, com,
4653                                 com->lc_sub_trace_objs[i].lsto_obj, true);
4654                 while (rc > 0 && ++i < LFSCK_STF_COUNT)
4655                         rc = lfsck_layout_double_scan_one_trace_file(env, com,
4656                                 com->lc_sub_trace_objs[i].lsto_obj, false);
4657
4658                 CDEBUG(D_LFSCK, "%s: layout LFSCK phase2 scan dangling stop "
4659                        "at the No. %d trace file: rc = %d\n",
4660                        lfsck_lfsck2name(lfsck), i, rc);
4661         }
4662
4663         CDEBUG(D_LFSCK, "%s: layout LFSCK phase2 scan stop: rc = %d\n",
4664                lfsck_lfsck2name(lfsck), rc);
4665
4666         RETURN(rc);
4667 }
4668
4669 static int
4670 lfsck_layout_slave_async_interpret(const struct lu_env *env,
4671                                    struct ptlrpc_request *req,
4672                                    void *args, int rc)
4673 {
4674         struct lfsck_layout_slave_async_args *llsaa = args;
4675         struct obd_export *exp = llsaa->llsaa_exp;
4676         struct lfsck_component *com = llsaa->llsaa_com;
4677         struct lfsck_layout_slave_target *llst = llsaa->llsaa_llst;
4678         struct lfsck_layout_slave_data *llsd = com->lc_data;
4679         struct lfsck_reply *lr = NULL;
4680         bool done = false;
4681
4682         if (rc != 0) {
4683                 /* It is probably caused by network trouble, or target crash,
4684                  * it will try several times (depends on the obd_timeout, and
4685                  * will not less than 3 times). But to make the LFSCK can go
4686                  * ahead, we should not try for ever. After some try but still
4687                  * hit failure, it will assume that the target exit the LFSCK
4688                  * prcoessing and stop try. */
4689                 if (rc == -ENOTCONN || rc == -ESHUTDOWN) {
4690                         int max_try = max_t(int, obd_timeout / 30, 3);
4691
4692                         if (++(llst->llst_failures) > max_try)
4693                                 done = true;
4694                 } else {
4695                         done = true;
4696                 }
4697         } else {
4698                 llst->llst_failures = 0;
4699                 lr = req_capsule_server_get(&req->rq_pill, &RMF_LFSCK_REPLY);
4700                 if (lr->lr_status != LS_SCANNING_PHASE1 &&
4701                     lr->lr_status != LS_SCANNING_PHASE2)
4702                         done = true;
4703         }
4704
4705         if (done) {
4706                 CDEBUG(D_LFSCK, "%s: layout LFSCK slave gets the MDT %x "
4707                        "status %d, failures_try %d\n", lfsck_lfsck2name(com->lc_lfsck),
4708                        llst->llst_index, lr != NULL ? lr->lr_status : rc,
4709                        llst->llst_failures);
4710
4711                 lfsck_layout_llst_del(llsd, llst);
4712         }
4713
4714         lfsck_layout_llst_put(llst);
4715         lfsck_component_put(env, com);
4716         class_export_put(exp);
4717
4718         return 0;
4719 }
4720
4721 static int lfsck_layout_async_query(const struct lu_env *env,
4722                                     struct lfsck_component *com,
4723                                     struct obd_export *exp,
4724                                     struct lfsck_layout_slave_target *llst,
4725                                     struct lfsck_request *lr,
4726                                     struct ptlrpc_request_set *set)
4727 {
4728         struct lfsck_layout_slave_async_args *llsaa;
4729         struct ptlrpc_request                *req;
4730         struct lfsck_request                 *tmp;
4731         int                                   rc;
4732         ENTRY;
4733
4734         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_LFSCK_QUERY);
4735         if (req == NULL)
4736                 RETURN(-ENOMEM);
4737
4738         rc = ptlrpc_request_pack(req, LUSTRE_OBD_VERSION, LFSCK_QUERY);
4739         if (rc != 0) {
4740                 ptlrpc_request_free(req);
4741                 RETURN(rc);
4742         }
4743
4744         tmp = req_capsule_client_get(&req->rq_pill, &RMF_LFSCK_REQUEST);
4745         *tmp = *lr;
4746         ptlrpc_request_set_replen(req);
4747
4748         llsaa = ptlrpc_req_async_args(llsaa, req);
4749         llsaa->llsaa_exp = exp;
4750         llsaa->llsaa_com = lfsck_component_get(com);
4751         llsaa->llsaa_llst = llst;
4752         req->rq_interpret_reply = lfsck_layout_slave_async_interpret;
4753         req->rq_allow_intr = 1;
4754         req->rq_no_delay = 1;
4755         ptlrpc_set_add_req(set, req);
4756
4757         RETURN(0);
4758 }
4759
4760 static int lfsck_layout_async_notify(const struct lu_env *env,
4761                                      struct obd_export *exp,
4762                                      struct lfsck_request *lr,
4763                                      struct ptlrpc_request_set *set)
4764 {
4765         struct ptlrpc_request   *req;
4766         struct lfsck_request    *tmp;
4767         int                      rc;
4768         ENTRY;
4769
4770         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_LFSCK_NOTIFY);
4771         if (req == NULL)
4772                 RETURN(-ENOMEM);
4773
4774         rc = ptlrpc_request_pack(req, LUSTRE_OBD_VERSION, LFSCK_NOTIFY);
4775         if (rc != 0) {
4776                 ptlrpc_request_free(req);
4777                 RETURN(rc);
4778         }
4779
4780         tmp = req_capsule_client_get(&req->rq_pill, &RMF_LFSCK_REQUEST);
4781         *tmp = *lr;
4782         ptlrpc_request_set_replen(req);
4783         req->rq_allow_intr = 1;
4784         req->rq_no_delay = 1;
4785         ptlrpc_set_add_req(set, req);
4786
4787         RETURN(0);
4788 }
4789
4790 static int
4791 lfsck_layout_slave_query_master(const struct lu_env *env,
4792                                 struct lfsck_component *com)
4793 {
4794         struct lfsck_request             *lr    = &lfsck_env_info(env)->lti_lr;
4795         struct lfsck_instance            *lfsck = com->lc_lfsck;
4796         struct lfsck_layout_slave_data   *llsd  = com->lc_data;
4797         struct lfsck_layout_slave_target *llst;
4798         struct obd_export                *exp;
4799         struct ptlrpc_request_set        *set;
4800         int                               rc    = 0;
4801         int                               rc1   = 0;
4802         ENTRY;
4803
4804         set = ptlrpc_prep_set();
4805         if (set == NULL)
4806                 GOTO(log, rc = -ENOMEM);
4807
4808         memset(lr, 0, sizeof(*lr));
4809         lr->lr_event = LE_QUERY;
4810         lr->lr_active = LFSCK_TYPE_LAYOUT;
4811
4812         llsd->llsd_touch_gen++;
4813         spin_lock(&llsd->llsd_lock);
4814         while (!list_empty(&llsd->llsd_master_list)) {
4815                 llst = list_entry(llsd->llsd_master_list.next,
4816                                   struct lfsck_layout_slave_target,
4817                                   llst_list);
4818                 if (llst->llst_gen == llsd->llsd_touch_gen)
4819                         break;
4820
4821                 llst->llst_gen = llsd->llsd_touch_gen;
4822                 list_move_tail(&llst->llst_list,
4823                                &llsd->llsd_master_list);
4824                 atomic_inc(&llst->llst_ref);
4825                 spin_unlock(&llsd->llsd_lock);
4826
4827                 exp = lustre_find_lwp_by_index(lfsck->li_obd->obd_name,
4828                                                llst->llst_index);
4829                 if (exp == NULL) {
4830                         lfsck_layout_llst_del(llsd, llst);
4831                         lfsck_layout_llst_put(llst);
4832                         spin_lock(&llsd->llsd_lock);
4833                         continue;
4834                 }
4835
4836                 rc = lfsck_layout_async_query(env, com, exp, llst, lr, set);
4837                 if (rc != 0) {
4838                         CDEBUG(D_LFSCK, "%s: layout LFSCK slave fail to "
4839                                "query %s for layout: rc = %d\n",
4840                                lfsck_lfsck2name(lfsck),
4841                                exp->exp_obd->obd_name, rc);
4842
4843                         rc1 = rc;
4844                         lfsck_layout_llst_put(llst);
4845                         class_export_put(exp);
4846                 }
4847                 spin_lock(&llsd->llsd_lock);
4848         }
4849         spin_unlock(&llsd->llsd_lock);
4850
4851         rc = ptlrpc_set_wait(env, set);
4852         ptlrpc_set_destroy(set);
4853
4854         GOTO(log, rc = (rc1 != 0 ? rc1 : rc));
4855
4856 log:
4857         CDEBUG(D_LFSCK, "%s: layout LFSCK slave queries master: rc = %d\n",
4858                lfsck_lfsck2name(com->lc_lfsck), rc);
4859
4860         return rc;
4861 }
4862
4863 static void
4864 lfsck_layout_slave_notify_master(const struct lu_env *env,
4865                                  struct lfsck_component *com,
4866                                  enum lfsck_events event, int result)
4867 {
4868         struct lfsck_layout              *lo    = com->lc_file_ram;
4869         struct lfsck_instance            *lfsck = com->lc_lfsck;
4870         struct lfsck_layout_slave_data   *llsd  = com->lc_data;
4871         struct lfsck_request             *lr    = &lfsck_env_info(env)->lti_lr;
4872         struct lfsck_layout_slave_target *llst;
4873         struct obd_export                *exp;
4874         struct ptlrpc_request_set        *set;
4875         int                               rc;
4876         ENTRY;
4877
4878         CDEBUG(D_LFSCK, "%s: layout LFSCK slave notifies master\n",
4879                lfsck_lfsck2name(com->lc_lfsck));
4880
4881         set = ptlrpc_prep_set();
4882         if (set == NULL)
4883                 RETURN_EXIT;
4884
4885         memset(lr, 0, sizeof(*lr));
4886         lr->lr_event = event;
4887         lr->lr_flags = LEF_FROM_OST;
4888         lr->lr_status = result;
4889         lr->lr_index = lfsck_dev_idx(lfsck);
4890         lr->lr_active = LFSCK_TYPE_LAYOUT;
4891         lr->lr_flags2 = lo->ll_flags;
4892         llsd->llsd_touch_gen++;
4893         spin_lock(&llsd->llsd_lock);
4894         while (!list_empty(&llsd->llsd_master_list)) {
4895                 llst = list_entry(llsd->llsd_master_list.next,
4896                                   struct lfsck_layout_slave_target,
4897                                   llst_list);
4898                 if (llst->llst_gen == llsd->llsd_touch_gen)
4899                         break;
4900
4901                 llst->llst_gen = llsd->llsd_touch_gen;
4902                 list_move_tail(&llst->llst_list,
4903                                &llsd->llsd_master_list);
4904                 atomic_inc(&llst->llst_ref);
4905                 spin_unlock(&llsd->llsd_lock);
4906
4907                 exp = lustre_find_lwp_by_index(lfsck->li_obd->obd_name,
4908                                                llst->llst_index);
4909                 if (exp == NULL) {
4910                         lfsck_layout_llst_del(llsd, llst);
4911                         lfsck_layout_llst_put(llst);
4912                         spin_lock(&llsd->llsd_lock);
4913                         continue;
4914                 }
4915
4916                 rc = lfsck_layout_async_notify(env, exp, lr, set);
4917                 if (rc != 0)
4918                         CDEBUG(D_LFSCK, "%s: layout LFSCK slave fail to "
4919                                "notify %s for layout: rc = %d\n",
4920                                lfsck_lfsck2name(lfsck),
4921                                exp->exp_obd->obd_name, rc);
4922
4923                 lfsck_layout_llst_put(llst);
4924                 class_export_put(exp);
4925                 spin_lock(&llsd->llsd_lock);
4926         }
4927         spin_unlock(&llsd->llsd_lock);
4928
4929         ptlrpc_set_wait(env, set);
4930         ptlrpc_set_destroy(set);
4931
4932         RETURN_EXIT;
4933 }
4934
4935 /*
4936  * \ret -ENODATA: unrecognized stripe
4937  * \ret = 0     : recognized stripe
4938  * \ret < 0     : other failures
4939  */
4940 static int lfsck_layout_master_check_pairs(const struct lu_env *env,
4941                                            struct lfsck_component *com,
4942                                            struct lu_fid *cfid,
4943                                            struct lu_fid *pfid, __u32 comp_id)
4944 {
4945         struct lfsck_thread_info        *info   = lfsck_env_info(env);
4946         struct lu_buf                   *buf    = &info->lti_big_buf;
4947         struct ost_id                   *oi     = &info->lti_oi;
4948         struct dt_object                *obj;
4949         struct lov_mds_md_v1            *lmm;
4950         struct lov_ost_data_v1          *objs;
4951         __u32                            idx    = pfid->f_stripe_idx;
4952         __u32                            magic;
4953         int                              rc     = 0;
4954         int                              i;
4955         __u16                            count;
4956         ENTRY;
4957
4958         pfid->f_ver = 0;
4959         obj = lfsck_object_find_bottom(env, com->lc_lfsck, pfid);
4960         if (IS_ERR(obj))
4961                 RETURN(PTR_ERR(obj));
4962
4963         dt_read_lock(env, obj, 0);
4964         if (unlikely(dt_object_exists(obj) == 0 ||
4965                      lfsck_is_dead_obj(obj)))
4966                 GOTO(unlock, rc = -ENOENT);
4967
4968         if (!S_ISREG(lfsck_object_type(obj)))
4969                 GOTO(unlock, rc = -ENODATA);
4970
4971         rc = lfsck_layout_get_lovea(env, obj, buf);
4972         if (rc < 0)
4973                 GOTO(unlock, rc);
4974
4975         lmm = buf->lb_buf;
4976         magic = le32_to_cpu(lmm->lmm_magic);
4977         if (magic == LOV_MAGIC_COMP_V1) {
4978                 struct lov_comp_md_v1 *lcm = buf->lb_buf;
4979                 struct lov_comp_md_entry_v1 *lcme;
4980
4981                 if (comp_id == 0)
4982                         GOTO(unlock, rc = -ENODATA);
4983
4984                 count = le16_to_cpu(lcm->lcm_entry_count);
4985                 for (i = 0; i < count; i++) {
4986                         lcme = &lcm->lcm_entries[i];
4987                         if (le32_to_cpu(lcme->lcme_id) == comp_id) {
4988                                 lmm = buf->lb_buf +
4989                                         le32_to_cpu(lcme->lcme_offset);
4990                                 magic = le32_to_cpu(lmm->lmm_magic);
4991                                 if (!(le32_to_cpu(lcme->lcme_flags) &
4992                                       LCME_FL_INIT))
4993                                         GOTO(unlock, rc = -ENODATA);
4994
4995                                 goto further;
4996                         }
4997                 }
4998
4999                 GOTO(unlock, rc = -ENODATA);
5000         }
5001
5002 further:
5003         if (magic == LOV_MAGIC_V1) {
5004                 objs = &lmm->lmm_objects[0];
5005         } else {
5006                 LASSERT(magic == LOV_MAGIC_V3);
5007                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[0];
5008         }
5009
5010         fid_to_ostid(cfid, oi);
5011         count = le16_to_cpu(lmm->lmm_stripe_count);
5012         for (i = 0; i < count; i++, objs++) {
5013                 struct ost_id oi2;
5014
5015                 ostid_le_to_cpu(&objs->l_ost_oi, &oi2);
5016                 if (memcmp(oi, &oi2, sizeof(*oi)) == 0)
5017                         GOTO(unlock, rc = (i != idx ? -ENODATA : 0));
5018         }
5019
5020         GOTO(unlock, rc = -ENODATA);
5021
5022 unlock:
5023         dt_read_unlock(env, obj);
5024         lfsck_object_put(env, obj);
5025
5026         return rc;
5027 }
5028
5029 /*
5030  * The LFSCK-on-OST will ask the LFSCK-on-MDT to check whether the given
5031  * MDT-object/OST-object pairs match or not to aviod transfer MDT-object
5032  * layout EA from MDT to OST. On one hand, the OST no need to understand
5033  * the layout EA structure; on the other hand, it may cause trouble when
5034  * transfer large layout EA from MDT to OST via normal OUT RPC.
5035  *
5036  * \ret > 0: unrecognized stripe
5037  * \ret = 0: recognized stripe
5038  * \ret < 0: other failures
5039  */
5040 static int lfsck_layout_slave_check_pairs(const struct lu_env *env,
5041                                           struct lfsck_component *com,
5042                                           struct lu_fid *cfid,
5043                                           struct lu_fid *pfid, __u32 comp_id)
5044 {
5045         struct lfsck_instance    *lfsck  = com->lc_lfsck;
5046         struct obd_device        *obd    = lfsck->li_obd;
5047         struct seq_server_site   *ss     = lfsck_dev_site(lfsck);
5048         struct obd_export        *exp    = NULL;
5049         struct ptlrpc_request    *req    = NULL;
5050         struct lfsck_request     *lr;
5051         struct lu_seq_range      *range  = &lfsck_env_info(env)->lti_range;
5052         int                       rc     = 0;
5053         ENTRY;
5054
5055         if (unlikely(fid_is_idif(pfid)))
5056                 RETURN(1);
5057
5058         fld_range_set_any(range);
5059         rc = fld_server_lookup(env, ss->ss_server_fld, fid_seq(pfid), range);
5060         if (rc != 0)
5061                 RETURN(rc == -ENOENT ? 1 : rc);
5062
5063         if (unlikely(!fld_range_is_mdt(range)))
5064                 RETURN(1);
5065
5066         exp = lustre_find_lwp_by_index(obd->obd_name, range->lsr_index);
5067         if (unlikely(exp == NULL))
5068                 RETURN(1);
5069
5070         if (!(exp_connect_flags(exp) & OBD_CONNECT_LFSCK))
5071                 GOTO(out, rc = -EOPNOTSUPP);
5072
5073         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_LFSCK_NOTIFY);
5074         if (req == NULL)
5075                 GOTO(out, rc = -ENOMEM);
5076
5077         rc = ptlrpc_request_pack(req, LUSTRE_OBD_VERSION, LFSCK_NOTIFY);
5078         if (rc != 0) {
5079                 ptlrpc_request_free(req);
5080
5081                 GOTO(out, rc);
5082         }
5083
5084         lr = req_capsule_client_get(&req->rq_pill, &RMF_LFSCK_REQUEST);
5085         memset(lr, 0, sizeof(*lr));
5086         lr->lr_event = LE_PAIRS_VERIFY;
5087         lr->lr_active = LFSCK_TYPE_LAYOUT;
5088         lr->lr_fid = *cfid; /* OST-object itself FID. */
5089         lr->lr_fid2 = *pfid; /* The claimed parent FID. */
5090         lr->lr_comp_id = comp_id;
5091
5092         ptlrpc_request_set_replen(req);
5093         rc = ptlrpc_queue_wait(req);
5094         ptlrpc_req_finished(req);
5095
5096         if (rc == -ENOENT || rc == -ENODATA)
5097                 rc = 1;
5098
5099         GOTO(out, rc);
5100
5101 out:
5102         if (exp != NULL)
5103                 class_export_put(exp);
5104
5105         return rc;
5106 }
5107
5108 static int lfsck_layout_slave_repair_pfid(const struct lu_env *env,
5109                                           struct lfsck_component *com,
5110                                           struct lfsck_req_local *lrl)
5111 {
5112         struct dt_object        *obj;
5113         int                      rc     = 0;
5114         ENTRY;
5115
5116         obj = lfsck_object_find_bottom(env, com->lc_lfsck, &lrl->lrl_fid);
5117         if (IS_ERR(obj))
5118                 GOTO(log, rc = PTR_ERR(obj));
5119
5120         dt_write_lock(env, obj, 0);
5121         if (unlikely(dt_object_exists(obj) == 0 ||
5122                      lfsck_is_dead_obj(obj)))
5123                 GOTO(unlock, rc = 0);
5124
5125         rc = __lfsck_layout_update_pfid(env, obj, &lrl->lrl_ff_client.ff_parent,
5126                                         &lrl->lrl_ff_client.ff_layout,
5127                                         lrl->lrl_ff_client.ff_layout_version,
5128                                         lrl->lrl_ff_client.ff_range,
5129                                         lrl->lrl_ff_client.ff_parent.f_ver);
5130
5131         GOTO(unlock, rc);
5132
5133 unlock:
5134         dt_write_unlock(env, obj);
5135         lfsck_object_put(env, obj);
5136
5137 log:
5138         CDEBUG(D_LFSCK, "%s: layout LFSCK slave repaired pfid for "DFID
5139                ", parent "DFID": rc = %d\n", lfsck_lfsck2name(com->lc_lfsck),
5140                PFID(&lrl->lrl_fid), PFID(&lrl->lrl_ff_client.ff_parent), rc);
5141
5142         return rc;
5143 }
5144
5145 /* layout APIs */
5146
5147 static void lfsck_layout_slave_quit(const struct lu_env *env,
5148                                     struct lfsck_component *com);
5149
5150 static int lfsck_layout_reset(const struct lu_env *env,
5151                               struct lfsck_component *com, bool init)
5152 {
5153         struct lfsck_layout     *lo    = com->lc_file_ram;
5154         int                      rc;
5155
5156         down_write(&com->lc_sem);
5157         if (init) {
5158                 memset(lo, 0, com->lc_file_size);
5159         } else {
5160                 __u32 count = lo->ll_success_count;
5161                 time64_t last_time = lo->ll_time_last_complete;
5162
5163                 memset(lo, 0, com->lc_file_size);
5164                 lo->ll_success_count = count;
5165                 lo->ll_time_last_complete = last_time;
5166         }
5167
5168         lo->ll_magic = LFSCK_LAYOUT_MAGIC;
5169         lo->ll_status = LS_INIT;
5170
5171         if (com->lc_lfsck->li_master) {
5172                 struct lfsck_assistant_data *lad = com->lc_data;
5173
5174                 clear_bit(LAD_INCOMPLETE, &lad->lad_flags);
5175                 CFS_RESET_BITMAP(lad->lad_bitmap);
5176         }
5177
5178         rc = lfsck_layout_store(env, com);
5179         if (rc == 0 && com->lc_lfsck->li_master)
5180                 rc = lfsck_load_sub_trace_files(env, com,
5181                         &dt_lfsck_layout_dangling_features, LFSCK_LAYOUT, true);
5182         up_write(&com->lc_sem);
5183
5184         CDEBUG(D_LFSCK, "%s: layout LFSCK reset: rc = %d\n",
5185                lfsck_lfsck2name(com->lc_lfsck), rc);
5186
5187         return rc;
5188 }
5189
5190 static void lfsck_layout_fail(const struct lu_env *env,
5191                               struct lfsck_component *com, bool new_checked)
5192 {
5193         struct lfsck_layout *lo = com->lc_file_ram;
5194
5195         down_write(&com->lc_sem);
5196         if (new_checked)
5197                 com->lc_new_checked++;
5198         lfsck_layout_record_failure(env, com->lc_lfsck, lo);
5199         up_write(&com->lc_sem);
5200 }
5201
5202 static int lfsck_layout_master_checkpoint(const struct lu_env *env,
5203                                           struct lfsck_component *com, bool init)
5204 {
5205         struct lfsck_instance   *lfsck   = com->lc_lfsck;
5206         struct lfsck_layout     *lo      = com->lc_file_ram;
5207         int                      rc;
5208
5209         if (!init) {
5210                 rc = lfsck_checkpoint_generic(env, com);
5211                 if (rc != 0)
5212                         return rc > 0 ? 0 : rc;
5213         }
5214
5215         down_write(&com->lc_sem);
5216         if (init) {
5217                 lo->ll_pos_latest_start =
5218                                 lfsck->li_pos_checkpoint.lp_oit_cookie;
5219         } else {
5220                 lo->ll_pos_last_checkpoint =
5221                                 lfsck->li_pos_checkpoint.lp_oit_cookie;
5222                 lo->ll_run_time_phase1 += ktime_get_seconds() -
5223                                           lfsck->li_time_last_checkpoint;
5224                 lo->ll_time_last_checkpoint = ktime_get_real_seconds();
5225                 lo->ll_objs_checked_phase1 += com->lc_new_checked;
5226                 com->lc_new_checked = 0;
5227         }
5228
5229         rc = lfsck_layout_store(env, com);
5230         up_write(&com->lc_sem);
5231
5232         CDEBUG(D_LFSCK, "%s: layout LFSCK master checkpoint at the pos ["
5233                "%llu], status = %d: rc = %d\n", lfsck_lfsck2name(lfsck),
5234                lfsck->li_pos_current.lp_oit_cookie, lo->ll_status, rc);
5235
5236         return rc;
5237 }
5238
5239 static int lfsck_layout_slave_checkpoint(const struct lu_env *env,
5240                                          struct lfsck_component *com, bool init)
5241 {
5242         struct lfsck_instance   *lfsck = com->lc_lfsck;
5243         struct lfsck_layout     *lo    = com->lc_file_ram;
5244         int                      rc;
5245
5246         if (com->lc_new_checked == 0 && !init)
5247                 return 0;
5248
5249         down_write(&com->lc_sem);
5250         if (init) {
5251                 lo->ll_pos_latest_start =
5252                                 lfsck->li_pos_checkpoint.lp_oit_cookie;
5253         } else {
5254                 lo->ll_pos_last_checkpoint =
5255                                 lfsck->li_pos_checkpoint.lp_oit_cookie;
5256                 lo->ll_run_time_phase1 += ktime_get_seconds() -
5257                                           lfsck->li_time_last_checkpoint;
5258                 lo->ll_time_last_checkpoint = ktime_get_real_seconds();
5259                 lo->ll_objs_checked_phase1 += com->lc_new_checked;
5260                 com->lc_new_checked = 0;
5261         }
5262
5263         rc = lfsck_layout_store(env, com);
5264         up_write(&com->lc_sem);
5265
5266         CDEBUG(D_LFSCK, "%s: layout LFSCK slave checkpoint at the pos ["
5267                "%llu], status = %d: rc = %d\n", lfsck_lfsck2name(lfsck),
5268                lfsck->li_pos_current.lp_oit_cookie, lo->ll_status, rc);
5269
5270         return rc;
5271 }
5272
5273 static int lfsck_layout_prep(const struct lu_env *env,
5274                              struct lfsck_component *com,
5275                              struct lfsck_start *start)
5276 {
5277         struct lfsck_instance   *lfsck  = com->lc_lfsck;
5278         struct lfsck_layout     *lo     = com->lc_file_ram;
5279         struct lfsck_position   *pos    = &com->lc_pos_start;
5280
5281         fid_zero(&pos->lp_dir_parent);
5282         pos->lp_dir_cookie = 0;
5283         if (lo->ll_status == LS_COMPLETED ||
5284             lo->ll_status == LS_PARTIAL ||
5285             /* To handle orphan, must scan from the beginning. */
5286             (start != NULL && start->ls_flags & LPF_OST_ORPHAN)) {
5287                 int rc;
5288
5289                 rc = lfsck_layout_reset(env, com, false);
5290                 if (rc == 0)
5291                         rc = lfsck_set_param(env, lfsck, start, true);
5292
5293                 if (rc != 0) {
5294                         CDEBUG(D_LFSCK, "%s: layout LFSCK prep failed: "
5295                                "rc = %d\n", lfsck_lfsck2name(lfsck), rc);
5296
5297                         return rc;
5298                 }
5299         }
5300
5301         down_write(&com->lc_sem);
5302         lo->ll_time_latest_start = ktime_get_real_seconds();
5303         spin_lock(&lfsck->li_lock);
5304         if (lo->ll_flags & LF_SCANNED_ONCE) {
5305                 if (!lfsck->li_drop_dryrun ||
5306                     lo->ll_pos_first_inconsistent == 0) {
5307                         lo->ll_status = LS_SCANNING_PHASE2;
5308                         list_move_tail(&com->lc_link,
5309                                        &lfsck->li_list_double_scan);
5310                         pos->lp_oit_cookie = 0;
5311                 } else {
5312                         int i;
5313
5314                         lo->ll_status = LS_SCANNING_PHASE1;
5315                         lo->ll_run_time_phase1 = 0;
5316                         lo->ll_run_time_phase2 = 0;
5317                         lo->ll_objs_checked_phase1 = 0;
5318                         lo->ll_objs_checked_phase2 = 0;
5319                         lo->ll_objs_failed_phase1 = 0;
5320                         lo->ll_objs_failed_phase2 = 0;
5321                         for (i = 0; i < LLIT_MAX; i++)
5322                                 lo->ll_objs_repaired[i] = 0;
5323
5324                         pos->lp_oit_cookie = lo->ll_pos_first_inconsistent;
5325                         fid_zero(&com->lc_fid_latest_scanned_phase2);
5326                 }
5327         } else {
5328                 lo->ll_status = LS_SCANNING_PHASE1;
5329                 if (!lfsck->li_drop_dryrun ||
5330                     lo->ll_pos_first_inconsistent == 0)
5331                         pos->lp_oit_cookie = lo->ll_pos_last_checkpoint + 1;
5332                 else
5333                         pos->lp_oit_cookie = lo->ll_pos_first_inconsistent;
5334         }
5335         spin_unlock(&lfsck->li_lock);
5336         up_write(&com->lc_sem);
5337
5338         return 0;
5339 }
5340
5341 static int lfsck_layout_slave_prep(const struct lu_env *env,
5342                                    struct lfsck_component *com,
5343                                    struct lfsck_start_param *lsp)
5344 {
5345         struct lfsck_layout_slave_data  *llsd   = com->lc_data;
5346         struct lfsck_instance           *lfsck  = com->lc_lfsck;
5347         struct lfsck_layout             *lo     = com->lc_file_ram;
5348         struct lfsck_start              *start  = lsp->lsp_start;
5349         int                              rc;
5350
5351         rc = lfsck_layout_prep(env, com, start);
5352         if (rc != 0)
5353                 return rc;
5354
5355         if (lo->ll_flags & LF_CRASHED_LASTID &&
5356             list_empty(&llsd->llsd_master_list)) {
5357                 LASSERT(lfsck->li_out_notify != NULL);
5358
5359                 lfsck->li_out_notify(env, lfsck->li_out_notify_data,
5360                                      LE_LASTID_REBUILDING);
5361         }
5362
5363         if (!lsp->lsp_index_valid)
5364                 return 0;
5365
5366         rc = lfsck_layout_llst_add(llsd, lsp->lsp_index);
5367         if (rc == 0 && start != NULL && start->ls_flags & LPF_OST_ORPHAN) {
5368                 LASSERT(!llsd->llsd_rbtree_valid);
5369
5370                 down_write(&llsd->llsd_rb_rwsem);
5371                 rc = lfsck_rbtree_setup(env, com);
5372                 up_write(&llsd->llsd_rb_rwsem);
5373         }
5374
5375         CDEBUG(D_LFSCK, "%s: layout LFSCK slave prep done, start pos ["
5376                "%llu]\n", lfsck_lfsck2name(lfsck),
5377                com->lc_pos_start.lp_oit_cookie);
5378
5379         return rc;
5380 }
5381
5382 static int lfsck_layout_master_prep(const struct lu_env *env,
5383                                     struct lfsck_component *com,
5384                                     struct lfsck_start_param *lsp)
5385 {
5386         int rc;
5387         ENTRY;
5388
5389         rc = lfsck_layout_load_bitmap(env, com);
5390         if (rc != 0) {
5391                 rc = lfsck_layout_reset(env, com, false);
5392                 if (rc == 0)
5393                         rc = lfsck_set_param(env, com->lc_lfsck,
5394                                              lsp->lsp_start, true);
5395
5396                 if (rc != 0)
5397                         GOTO(log, rc);
5398         }
5399
5400         rc = lfsck_layout_prep(env, com, lsp->lsp_start);
5401         if (rc != 0)
5402                 RETURN(rc);
5403
5404         rc = lfsck_start_assistant(env, com, lsp);
5405
5406         GOTO(log, rc);
5407
5408 log:
5409         CDEBUG(D_LFSCK, "%s: layout LFSCK master prep done, start pos ["
5410                "%llu]\n", lfsck_lfsck2name(com->lc_lfsck),
5411                com->lc_pos_start.lp_oit_cookie);
5412
5413         return 0;
5414 }
5415
5416 /* Pre-fetch the attribute for each stripe in the given layout EA. */
5417 static int lfsck_layout_scan_stripes(const struct lu_env *env,
5418                                      struct lfsck_component *com,
5419                                      struct dt_object *parent,
5420                                      struct lov_mds_md_v1 *lmm, __u32 comp_id)
5421 {
5422         struct lfsck_thread_info        *info    = lfsck_env_info(env);
5423         struct lfsck_instance           *lfsck   = com->lc_lfsck;
5424         struct lfsck_bookmark           *bk      = &lfsck->li_bookmark_ram;
5425         struct lfsck_layout             *lo      = com->lc_file_ram;
5426         struct lfsck_assistant_data     *lad     = com->lc_data;
5427         struct lfsck_assistant_object   *lso     = NULL;
5428         struct lov_ost_data_v1          *objs;
5429         struct lfsck_tgt_descs          *ltds    = &lfsck->li_ost_descs;
5430         struct ptlrpc_thread            *mthread = &lfsck->li_thread;
5431         struct ptlrpc_thread            *athread = &lad->lad_thread;
5432         struct lu_buf                    buf;
5433         int                              rc      = 0;
5434         int                              i;
5435         __u32                            magic;
5436         __u16                            count;
5437         ENTRY;
5438
5439         lfsck_buf_init(&buf, &info->lti_ff, sizeof(struct filter_fid));
5440         magic = le32_to_cpu(lmm->lmm_magic);
5441         if (magic == LOV_MAGIC_V1) {
5442                 objs = &lmm->lmm_objects[0];
5443         } else {
5444                 LASSERT(magic == LOV_MAGIC_V3);
5445                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[0];
5446         }
5447
5448         count = le16_to_cpu(lmm->lmm_stripe_count);
5449         for (i = 0; i < count; i++, objs++) {
5450                 struct lu_fid           *fid    = &info->lti_fid;
5451                 struct ost_id           *oi     = &info->lti_oi;
5452                 struct lfsck_layout_req *llr;
5453                 struct lfsck_tgt_desc   *tgt    = NULL;
5454                 struct dt_object        *cobj   = NULL;
5455                 __u32                    index;
5456                 bool                     wakeup = false;
5457
5458                 if (unlikely(lovea_slot_is_dummy(objs)))
5459                         continue;
5460
5461                 wait_event_idle(mthread->t_ctl_waitq,
5462                                 lad->lad_prefetched < bk->lb_async_windows ||
5463                                 !thread_is_running(mthread) ||
5464                                 thread_is_stopped(athread));
5465
5466                 if (unlikely(!thread_is_running(mthread)) ||
5467                              thread_is_stopped(athread))
5468                         GOTO(out, rc = 0);
5469
5470                 if (unlikely(lfsck_is_dead_obj(parent)))
5471                         GOTO(out, rc = 0);
5472
5473                 ostid_le_to_cpu(&objs->l_ost_oi, oi);
5474                 index = le32_to_cpu(objs->l_ost_idx);
5475                 rc = ostid_to_fid(fid, oi, index);
5476                 if (rc != 0) {
5477                         CDEBUG(D_LFSCK, "%s: get invalid layout EA for "DFID
5478                                ": "DOSTID", idx %u, comp_id %u\n",
5479                                lfsck_lfsck2name(lfsck),
5480                                PFID(lfsck_dto2fid(parent)), POSTID(oi),
5481                                index, comp_id);
5482                         goto next;
5483                 }
5484
5485                 tgt = lfsck_tgt_get(ltds, index);
5486                 if (unlikely(tgt == NULL)) {
5487                         CDEBUG(D_LFSCK, "%s: cannot talk with OST %x which "
5488                                "did not join the layout LFSCK, comp_id %u\n",
5489                                lfsck_lfsck2name(lfsck), index, comp_id);
5490                         lfsck_lad_set_bitmap(env, com, index);
5491                         goto next;
5492                 }
5493
5494                 /* There is potential deadlock race condition between object
5495                  * destroy and layout LFSCK. Consider the following scenario:
5496                  *
5497                  * 1) The LFSCK thread obtained the parent object firstly, at
5498                  *    that time, the parent object has not been destroyed yet.
5499                  *
5500                  * 2) One RPC service thread destroyed the parent and all its
5501                  *    children objects. Because the LFSCK is referencing the
5502                  *    parent object, then the parent object will be marked as
5503                  *    dying in RAM. On the other hand, the parent object is
5504                  *    referencing all its children objects, then all children
5505                  *    objects will be marked as dying in RAM also.
5506                  *
5507                  * 3) The LFSCK thread tries to find some child object with
5508                  *    the parent object referenced. Then it will find that the
5509                  *    child object is dying. According to the object visibility
5510                  *    rules: the object with dying flag cannot be returned to
5511                  *    others. So the LFSCK thread has to wait until the dying
5512                  *    object has been purged from RAM, then it can allocate a
5513                  *    new object (with the same FID) in RAM. Unfortunately, the
5514                  *    LFSCK thread itself is referencing the parent object, and
5515                  *    cause the parent object cannot be purged, then cause the
5516                  *    child object cannot be purged also. So the LFSCK thread
5517                  *    will fall into deadlock.
5518                  */
5519                 cobj = lfsck_object_find_by_dev(env, tgt->ltd_tgt, fid);
5520                 if (IS_ERR(cobj)) {
5521                         if (lfsck_is_dead_obj(parent)) {
5522                                 lfsck_tgt_put(tgt);
5523
5524                                 GOTO(out, rc = 0);
5525                         }
5526
5527                         rc = PTR_ERR(cobj);
5528                         goto next;
5529                 }
5530
5531                 rc = dt_declare_attr_get(env, cobj);
5532                 if (rc)
5533                         goto next;
5534
5535                 rc = dt_declare_xattr_get(env, cobj, &buf, XATTR_NAME_FID);
5536                 if (rc)
5537                         goto next;
5538
5539                 if (lso == NULL) {
5540                         struct lu_attr *attr = &info->lti_la;
5541
5542                         rc = dt_attr_get(env, parent, attr);
5543                         if (rc != 0)
5544                                 goto next;
5545
5546                         lso = lfsck_assistant_object_init(env,
5547                                 lfsck_dto2fid(parent), attr,
5548                                 lfsck->li_pos_current.lp_oit_cookie, false);
5549                         if (IS_ERR(lso)) {
5550                                 rc = PTR_ERR(lso);
5551                                 lso = NULL;
5552
5553                                 goto next;
5554                         }
5555                 }
5556
5557                 llr = lfsck_layout_assistant_req_init(lso, cobj, comp_id,
5558                                                       index, i);
5559                 if (IS_ERR(llr)) {
5560                         rc = PTR_ERR(llr);
5561                         goto next;
5562                 }
5563
5564                 cobj = NULL;
5565                 spin_lock(&lad->lad_lock);
5566                 if (lad->lad_assistant_status < 0) {
5567                         spin_unlock(&lad->lad_lock);
5568                         lfsck_layout_assistant_req_fini(env, &llr->llr_lar);
5569                         lfsck_tgt_put(tgt);
5570                         RETURN(lad->lad_assistant_status);
5571                 }
5572
5573                 list_add_tail(&llr->llr_lar.lar_list, &lad->lad_req_list);
5574                 if (lad->lad_prefetched == 0)
5575                         wakeup = true;
5576
5577                 lad->lad_prefetched++;
5578                 spin_unlock(&lad->lad_lock);
5579                 if (wakeup)
5580                         wake_up_all(&athread->t_ctl_waitq);
5581
5582 next:
5583                 down_write(&com->lc_sem);
5584                 com->lc_new_checked++;
5585                 if (rc < 0)
5586                         lfsck_layout_record_failure(env, lfsck, lo);
5587                 up_write(&com->lc_sem);
5588
5589                 if (cobj != NULL && !IS_ERR(cobj))
5590                         lfsck_object_put(env, cobj);
5591
5592                 if (likely(tgt != NULL))
5593                         lfsck_tgt_put(tgt);
5594
5595                 if (rc < 0 && bk->lb_param & LPF_FAILOUT)
5596                         GOTO(out, rc);
5597         }
5598
5599         GOTO(out, rc = 0);
5600
5601 out:
5602         if (lso != NULL)
5603                 lfsck_assistant_object_put(env, lso);
5604
5605         return rc;
5606 }
5607
5608 /* For the given object, read its layout EA locally. For each stripe, pre-fetch
5609  * the OST-object's attribute and generate an structure lfsck_layout_req on the
5610  * list ::lad_req_list.
5611  *
5612  * For each request on above list, the lfsck_layout_assistant thread compares
5613  * the OST side attribute with local attribute, if inconsistent, then repair it.
5614  *
5615  * All above processing is async mode with pipeline. */
5616 static int lfsck_layout_master_exec_oit(const struct lu_env *env,
5617                                         struct lfsck_component *com,
5618                                         struct dt_object *obj)
5619 {
5620         struct lfsck_thread_info        *info   = lfsck_env_info(env);
5621         struct ost_id                   *oi     = &info->lti_oi;
5622         struct lfsck_layout             *lo     = com->lc_file_ram;
5623         struct lfsck_assistant_data     *lad    = com->lc_data;
5624         struct lfsck_instance           *lfsck  = com->lc_lfsck;
5625         struct lfsck_bookmark           *bk     = &lfsck->li_bookmark_ram;
5626         struct thandle                  *handle = NULL;
5627         struct lu_buf                   *buf    = &info->lti_big_buf;
5628         struct lov_mds_md_v1            *lmm    = NULL;
5629         struct dt_device                *dev    = lfsck_obj2dev(obj);
5630         struct lustre_handle             lh     = { 0 };
5631         struct lu_buf                    ea_buf = { NULL };
5632         struct lov_comp_md_v1           *lcm    = NULL;
5633         struct lov_comp_md_entry_v1     *lcme   = NULL;
5634         int                              rc     = 0;
5635         int                              size   = 0;
5636         __u32                            magic  = 0;
5637         __u16                            count  = 0;
5638         bool                             locked = false;
5639         bool                             stripe = false;
5640         bool                             bad_oi = false;
5641         ENTRY;
5642
5643         if (!S_ISREG(lfsck_object_type(obj)))
5644                 GOTO(out, rc = 0);
5645
5646         if (lad->lad_assistant_status < 0)
5647                 GOTO(out, rc = -ESRCH);
5648
5649         fid_to_lmm_oi(lfsck_dto2fid(obj), oi);
5650         lmm_oi_cpu_to_le(oi, oi);
5651         dt_read_lock(env, obj, 0);
5652         locked = true;
5653
5654 again:
5655         bad_oi = false;
5656         if (dt_object_exists(obj) == 0 ||
5657             lfsck_is_dead_obj(obj))
5658                 GOTO(out, rc = 0);
5659
5660         rc = lfsck_layout_get_lovea(env, obj, buf);
5661         if (rc == -EINVAL || rc == -ENODATA || rc == -EOPNOTSUPP)
5662                 /* Skip bad lov EA during the 1st cycle scanning, and
5663                  * try to recover it via orphan in the 2nd scanning. */
5664                 rc = 0;
5665         if (rc <= 0)
5666                 GOTO(out, rc);
5667
5668         size = rc;
5669         lmm = buf->lb_buf;
5670         magic = le32_to_cpu(lmm->lmm_magic);
5671         if (magic == LOV_MAGIC_COMP_V1) {
5672                 struct lov_mds_md_v1 *v1;
5673                 int i;
5674
5675                 lcm = buf->lb_buf;
5676                 count = le16_to_cpu(lcm->lcm_entry_count);
5677                 for (i = 0; i < count; i++) {
5678                         lcme = &lcm->lcm_entries[i];
5679                         v1 = buf->lb_buf + le32_to_cpu(lcme->lcme_offset);
5680                         if (memcmp(oi, &v1->lmm_oi, sizeof(*oi)) != 0)
5681                                 goto fix;
5682                 }
5683
5684                 GOTO(out, stripe = true);
5685         } else if (memcmp(oi, &lmm->lmm_oi, sizeof(*oi)) == 0) {
5686                 GOTO(out, stripe = true);
5687         }
5688
5689 fix:
5690         /* Inconsistent lmm_oi, should be repaired. */
5691         bad_oi = true;
5692
5693         if (bk->lb_param & LPF_DRYRUN) {
5694                 lo->ll_objs_repaired[LLIT_OTHERS - 1]++;
5695
5696                 GOTO(out, stripe = true);
5697         }
5698
5699         if (!lustre_handle_is_used(&lh)) {
5700                 dt_read_unlock(env, obj);
5701                 locked = false;
5702                 rc = lfsck_ibits_lock(env, lfsck, obj, &lh,
5703                                       MDS_INODELOCK_LAYOUT |
5704                                       MDS_INODELOCK_XATTR, LCK_EX);
5705                 if (rc != 0)
5706                         GOTO(out, rc);
5707
5708                 handle = dt_trans_create(env, dev);
5709                 if (IS_ERR(handle))
5710                         GOTO(out, rc = PTR_ERR(handle));
5711
5712                 lfsck_buf_init(&ea_buf, buf->lb_buf, size);
5713                 rc = dt_declare_xattr_set(env, obj, &ea_buf, XATTR_NAME_LOV,
5714                                           LU_XATTR_REPLACE, handle);
5715                 if (rc != 0)
5716                         GOTO(out, rc);
5717
5718                 rc = dt_trans_start_local(env, dev, handle);
5719                 if (rc != 0)
5720                         GOTO(out, rc);
5721
5722                 dt_write_lock(env, obj, 0);
5723                 locked = true;
5724
5725                 goto again;
5726         }
5727
5728         if (magic == LOV_MAGIC_COMP_V1) {
5729                 struct lov_mds_md_v1 *v1;
5730                 int i;
5731
5732                 for (i = 0; i < count; i++) {
5733                         lcme = &lcm->lcm_entries[i];
5734                         v1 = buf->lb_buf + le32_to_cpu(lcme->lcme_offset);
5735                         v1->lmm_oi = *oi;
5736                 }
5737         } else {
5738                 lmm->lmm_oi = *oi;
5739         }
5740
5741         rc = dt_xattr_set(env, obj, &ea_buf, XATTR_NAME_LOV,
5742                           LU_XATTR_REPLACE, handle);
5743         if (rc != 0)
5744                 GOTO(out, rc);
5745
5746         lo->ll_objs_repaired[LLIT_OTHERS - 1]++;
5747
5748         GOTO(out, stripe = true);
5749
5750 out:
5751         if (locked) {
5752                 if (lustre_handle_is_used(&lh))
5753                         dt_write_unlock(env, obj);
5754                 else
5755                         dt_read_unlock(env, obj);
5756         }
5757
5758         if (handle != NULL && !IS_ERR(handle))
5759                 dt_trans_stop(env, dev, handle);
5760
5761         lfsck_ibits_unlock(&lh, LCK_EX);
5762
5763         if (bad_oi)
5764                 CDEBUG(D_LFSCK, "%s: layout LFSCK master %s bad lmm_oi for "
5765                        DFID": rc = %d\n", lfsck_lfsck2name(lfsck),
5766                        bk->lb_param & LPF_DRYRUN ? "found" : "repaired",
5767                        PFID(lfsck_dto2fid(obj)), rc);
5768
5769         if (stripe) {
5770                 if (magic == LOV_MAGIC_COMP_V1) {
5771                         int i;
5772
5773                         for (i = 0; i < count; i++) {
5774                                 lcme = &lcm->lcm_entries[i];
5775                                 if (!(le32_to_cpu(lcme->lcme_flags) &
5776                                       LCME_FL_INIT))
5777                                         continue;
5778
5779                                 rc = lfsck_layout_scan_stripes(env, com, obj,
5780                                         (struct lov_mds_md_v1 *)(buf->lb_buf +
5781                                         le32_to_cpu(lcme->lcme_offset)),
5782                                         le32_to_cpu(lcme->lcme_id));
5783                         }
5784                 } else {
5785                         rc = lfsck_layout_scan_stripes(env, com, obj, lmm, 0);
5786                 }
5787         } else {
5788                 down_write(&com->lc_sem);
5789                 com->lc_new_checked++;
5790                 if (rc < 0)
5791                         lfsck_layout_record_failure(env, lfsck, lo);
5792                 up_write(&com->lc_sem);
5793         }
5794
5795         return rc;
5796 }
5797
5798 static int lfsck_layout_slave_exec_oit(const struct lu_env *env,
5799                                        struct lfsck_component *com,
5800                                        struct dt_object *obj)
5801 {
5802         struct lfsck_instance           *lfsck  = com->lc_lfsck;
5803         struct lfsck_layout             *lo     = com->lc_file_ram;
5804         const struct lu_fid             *fid    = lfsck_dto2fid(obj);
5805         struct lfsck_layout_slave_data  *llsd   = com->lc_data;
5806         struct lfsck_layout_seq         *lls;
5807         __u64                            seq;
5808         __u64                            oid;
5809         int                              rc;
5810         ENTRY;
5811
5812         LASSERT(llsd != NULL);
5813
5814         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_DELAY5) &&
5815             cfs_fail_val == lfsck_dev_idx(lfsck)) {
5816                 struct ptlrpc_thread    *thread = &lfsck->li_thread;
5817
5818                 wait_event_idle_timeout(thread->t_ctl_waitq,
5819                                         !thread_is_running(thread),
5820                                         cfs_time_seconds(1));
5821         }
5822
5823         lfsck_rbtree_update_bitmap(env, com, fid, false);
5824
5825         down_write(&com->lc_sem);
5826         if (fid_is_idif(fid))
5827                 seq = 0;
5828         else if (!fid_is_norm(fid) ||
5829                  !fid_is_for_ostobj(env, lfsck, obj, fid))
5830                 GOTO(unlock, rc = 0);
5831         else
5832                 seq = fid_seq(fid);
5833         com->lc_new_checked++;
5834
5835         lls = lfsck_layout_seq_lookup(llsd, seq);
5836         if (lls == NULL) {
5837                 OBD_ALLOC_PTR(lls);
5838                 if (unlikely(lls == NULL))
5839                         GOTO(unlock, rc = -ENOMEM);
5840
5841                 INIT_LIST_HEAD(&lls->lls_list);
5842                 lls->lls_seq = seq;
5843                 rc = lfsck_layout_lastid_load(env, com, lls);
5844                 if (rc != 0) {
5845                         CDEBUG(D_LFSCK, "%s: layout LFSCK failed to "
5846                               "load LAST_ID for %#llx: rc = %d\n",
5847                               lfsck_lfsck2name(com->lc_lfsck), seq, rc);
5848                         lo->ll_objs_failed_phase1++;
5849                         OBD_FREE_PTR(lls);
5850                         GOTO(unlock, rc);
5851                 }
5852
5853                 lfsck_layout_seq_insert(llsd, lls);
5854         }
5855
5856         if (unlikely(fid_is_last_id(fid)))
5857                 GOTO(unlock, rc = 0);
5858
5859         if (fid_is_idif(fid))
5860                 oid = fid_idif_id(fid_seq(fid), fid_oid(fid), fid_ver(fid));
5861         else
5862                 oid = fid_oid(fid);
5863
5864         if (oid > lls->lls_lastid_known)
5865                 lls->lls_lastid_known = oid;
5866
5867         if (oid > lls->lls_lastid) {
5868                 if (!(lo->ll_flags & LF_CRASHED_LASTID)) {
5869                         /* OFD may create new objects during LFSCK scanning. */
5870                         rc = lfsck_layout_lastid_reload(env, com, lls);
5871                         if (unlikely(rc != 0)) {
5872                                 CDEBUG(D_LFSCK, "%s: layout LFSCK failed to "
5873                                       "reload LAST_ID for %#llx: rc = %d\n",
5874                                       lfsck_lfsck2name(com->lc_lfsck),
5875                                       lls->lls_seq, rc);
5876
5877                                 GOTO(unlock, rc);
5878                         }
5879
5880                         if (oid <= lls->lls_lastid ||
5881                             lo->ll_flags & LF_CRASHED_LASTID)
5882                                 GOTO(unlock, rc = 0);
5883
5884                         LASSERT(lfsck->li_out_notify != NULL);
5885
5886                         lfsck->li_out_notify(env, lfsck->li_out_notify_data,
5887                                              LE_LASTID_REBUILDING);
5888                         lo->ll_flags |= LF_CRASHED_LASTID;
5889
5890                         CDEBUG(D_LFSCK, "%s: layout LFSCK finds crashed "
5891                                "LAST_ID file (2) for the sequence %#llx"
5892                                ", old value %llu, known value %llu\n",
5893                                lfsck_lfsck2name(lfsck), lls->lls_seq,
5894                                lls->lls_lastid, oid);
5895                 }
5896
5897                 lls->lls_lastid = oid;
5898                 lls->lls_dirty = 1;
5899         }
5900
5901         GOTO(unlock, rc = 0);
5902
5903 unlock:
5904         up_write(&com->lc_sem);
5905
5906         return rc;
5907 }
5908
5909 static int lfsck_layout_exec_dir(const struct lu_env *env,
5910                                  struct lfsck_component *com,
5911                                  struct lfsck_assistant_object *lso,
5912                                  struct lu_dirent *ent, __u16 type)
5913 {
5914         return 0;
5915 }
5916
5917 static int lfsck_layout_master_post(const struct lu_env *env,
5918                                     struct lfsck_component *com,
5919                                     int result, bool init)
5920 {
5921         struct lfsck_instance   *lfsck  = com->lc_lfsck;
5922         struct lfsck_layout     *lo     = com->lc_file_ram;
5923         int                      rc;
5924         ENTRY;
5925
5926         lfsck_post_generic(env, com, &result);
5927
5928         down_write(&com->lc_sem);
5929         spin_lock(&lfsck->li_lock);
5930         if (!init)
5931                 lo->ll_pos_last_checkpoint =
5932                                 lfsck->li_pos_checkpoint.lp_oit_cookie;
5933
5934         if (result > 0) {
5935                 if (lo->ll_flags & LF_INCOMPLETE)
5936                         lo->ll_status = LS_PARTIAL;
5937                 else
5938                         lo->ll_status = LS_SCANNING_PHASE2;
5939                 lo->ll_flags |= LF_SCANNED_ONCE;
5940                 lo->ll_flags &= ~LF_UPGRADE;
5941                 list_move_tail(&com->lc_link, &lfsck->li_list_double_scan);
5942         } else if (result == 0) {
5943                 if (lfsck->li_status != 0)
5944                         lo->ll_status = lfsck->li_status;
5945                 else
5946                         lo->ll_status = LS_STOPPED;
5947                 if (lo->ll_status != LS_PAUSED)
5948                         list_move_tail(&com->lc_link, &lfsck->li_list_idle);
5949         } else {
5950                 lo->ll_status = LS_FAILED;
5951                 list_move_tail(&com->lc_link, &lfsck->li_list_idle);
5952         }
5953         spin_unlock(&lfsck->li_lock);
5954
5955         if (!init) {
5956                 lo->ll_run_time_phase1 += ktime_get_seconds() -
5957                                           lfsck->li_time_last_checkpoint;
5958                 lo->ll_time_last_checkpoint = ktime_get_real_seconds();
5959                 lo->ll_objs_checked_phase1 += com->lc_new_checked;
5960                 com->lc_new_checked = 0;
5961         }
5962
5963         rc = lfsck_layout_store(env, com);
5964         up_write(&com->lc_sem);
5965
5966         CDEBUG(D_LFSCK, "%s: layout LFSCK master post done: rc = %d\n",
5967                lfsck_lfsck2name(lfsck), rc);
5968
5969         RETURN(rc);
5970 }
5971
5972 static int lfsck_layout_slave_post(const struct lu_env *env,
5973                                    struct lfsck_component *com,
5974                                    int result, bool init)
5975 {
5976         struct lfsck_instance   *lfsck = com->lc_lfsck;
5977         struct lfsck_layout     *lo    = com->lc_file_ram;
5978         int                      rc;
5979         bool                     done  = false;
5980
5981         down_write(&com->lc_sem);
5982         rc = lfsck_layout_lastid_store(env, com);
5983         if (rc != 0)
5984                 result = rc;
5985
5986         LASSERT(lfsck->li_out_notify != NULL);
5987
5988         spin_lock(&lfsck->li_lock);
5989         if (!init)
5990                 lo->ll_pos_last_checkpoint =
5991                                 lfsck->li_pos_checkpoint.lp_oit_cookie;
5992
5993         if (result > 0) {
5994                 lo->ll_status = LS_SCANNING_PHASE2;
5995                 lo->ll_flags |= LF_SCANNED_ONCE;
5996                 if (lo->ll_flags & LF_CRASHED_LASTID) {
5997                         done = true;
5998                         lo->ll_flags &= ~LF_CRASHED_LASTID;
5999
6000                         CDEBUG(D_LFSCK, "%s: layout LFSCK has rebuilt "
6001                                "crashed LAST_ID files successfully\n",
6002                                lfsck_lfsck2name(lfsck));
6003                 }
6004                 lo->ll_flags &= ~LF_UPGRADE;
6005                 list_move_tail(&com->lc_link, &lfsck->li_list_double_scan);
6006         } else if (result == 0) {
6007                 if (lfsck->li_status != 0)
6008                         lo->ll_status = lfsck->li_status;
6009                 else
6010                         lo->ll_status = LS_STOPPED;
6011                 if (lo->ll_status != LS_PAUSED)
6012                         list_move_tail(&com->lc_link, &lfsck->li_list_idle);
6013         } else {
6014                 lo->ll_status = LS_FAILED;
6015                 list_move_tail(&com->lc_link, &lfsck->li_list_idle);
6016         }
6017         spin_unlock(&lfsck->li_lock);
6018
6019         if (done)
6020                 lfsck->li_out_notify(env, lfsck->li_out_notify_data,
6021                                      LE_LASTID_REBUILT);
6022
6023         if (!init) {
6024                 lo->ll_run_time_phase1 += ktime_get_seconds() -
6025                                           lfsck->li_time_last_checkpoint;
6026                 lo->ll_time_last_checkpoint = ktime_get_real_seconds();
6027                 lo->ll_objs_checked_phase1 += com->lc_new_checked;
6028                 com->lc_new_checked = 0;
6029         }
6030
6031         rc = lfsck_layout_store(env, com);
6032         up_write(&com->lc_sem);
6033
6034         lfsck_layout_slave_notify_master(env, com, LE_PHASE1_DONE, result);
6035
6036         CDEBUG(D_LFSCK, "%s: layout LFSCK slave post done: rc = %d\n",
6037                lfsck_lfsck2name(lfsck), rc);
6038
6039         return rc;
6040 }
6041
6042 static void lfsck_layout_dump(const struct lu_env *env,
6043                               struct lfsck_component *com, struct seq_file *m)
6044 {
6045         struct lfsck_instance   *lfsck = com->lc_lfsck;
6046         struct lfsck_bookmark   *bk    = &lfsck->li_bookmark_ram;
6047         struct lfsck_layout     *lo    = com->lc_file_ram;
6048         const char *prefix;
6049
6050         down_read(&com->lc_sem);
6051         if (bk->lb_param & LPF_DRYRUN)
6052                 prefix = "inconsistent";
6053         else
6054                 prefix = "repaired";
6055
6056         seq_printf(m, "name: lfsck_layout\n"
6057                    "magic: %#x\n"
6058                    "version: %d\n"
6059                    "status: %s\n",
6060                    lo->ll_magic,
6061                    bk->lb_version,
6062                    lfsck_status2name(lo->ll_status));
6063
6064         lfsck_bits_dump(m, lo->ll_flags, lfsck_flags_names, "flags");
6065
6066         lfsck_bits_dump(m, bk->lb_param, lfsck_param_names, "param");
6067
6068         lfsck_time_dump(m, lo->ll_time_last_complete, "last_completed");
6069
6070         lfsck_time_dump(m, lo->ll_time_latest_start, "latest_start");
6071
6072         lfsck_time_dump(m, lo->ll_time_last_checkpoint, "last_checkpoint");
6073
6074         seq_printf(m, "latest_start_position: %llu\n"
6075                    "last_checkpoint_position: %llu\n"
6076                    "first_failure_position: %llu\n",
6077                    lo->ll_pos_latest_start,
6078                    lo->ll_pos_last_checkpoint,
6079                    lo->ll_pos_first_inconsistent);
6080
6081         seq_printf(m, "success_count: %u\n"
6082                    "%s_dangling: %llu\n"
6083                    "%s_unmatched_pair: %llu\n"
6084                    "%s_multiple_referenced: %llu\n"
6085                    "%s_orphan: %llu\n"
6086                    "%s_inconsistent_owner: %llu\n"
6087                    "%s_others: %llu\n"
6088                    "skipped: %llu\n"
6089                    "failed_phase1: %llu\n"
6090                    "failed_phase2: %llu\n",
6091                    lo->ll_success_count,
6092                    prefix, lo->ll_objs_repaired[LLIT_DANGLING - 1],
6093                    prefix, lo->ll_objs_repaired[LLIT_UNMATCHED_PAIR - 1],
6094                    prefix, lo->ll_objs_repaired[LLIT_MULTIPLE_REFERENCED - 1],
6095                    prefix, lo->ll_objs_repaired[LLIT_ORPHAN - 1],
6096                    prefix, lo->ll_objs_repaired[LLIT_INCONSISTENT_OWNER - 1],
6097                    prefix, lo->ll_objs_repaired[LLIT_OTHERS - 1],
6098                    lo->ll_objs_skipped,
6099                    lo->ll_objs_failed_phase1,
6100                    lo->ll_objs_failed_phase2);
6101
6102         if (lo->ll_status == LS_SCANNING_PHASE1) {
6103                 time64_t duration = ktime_get_seconds() -
6104                                     lfsck->li_time_last_checkpoint;
6105                 u64 checked = lo->ll_objs_checked_phase1 +
6106                               com->lc_new_checked;
6107                 u64 speed = checked;
6108                 u64 new_checked = com->lc_new_checked;
6109                 time64_t rtime = lo->ll_run_time_phase1 + duration;
6110                 u64 pos;
6111
6112                 if (duration != 0)
6113                         new_checked = div64_s64(new_checked, duration);
6114                 if (rtime != 0)
6115                         speed = div64_s64(speed, rtime);
6116                 seq_printf(m, "checked_phase1: %llu\n"
6117                            "checked_phase2: %llu\n"
6118                            "run_time_phase1: %lld seconds\n"
6119                            "run_time_phase2: %lld seconds\n"
6120                            "average_speed_phase1: %llu items/sec\n"
6121                            "average_speed_phase2: N/A\n"
6122                            "real_time_speed_phase1: %llu items/sec\n"
6123                            "real_time_speed_phase2: N/A\n",
6124                            checked,
6125                            lo->ll_objs_checked_phase2,
6126                            rtime,
6127                            lo->ll_run_time_phase2,
6128                            speed,
6129                            new_checked);
6130
6131                 if (likely(lfsck->li_di_oit)) {
6132                         const struct dt_it_ops *iops =
6133                                 &lfsck->li_obj_oit->do_index_ops->dio_it;
6134
6135                         /* The low layer otable-based iteration position may NOT
6136                          * exactly match the layout-based directory traversal
6137                          * cookie. Generally, it is not a serious issue. But the
6138                          * caller should NOT make assumption on that. */
6139                         pos = iops->store(env, lfsck->li_di_oit);
6140                         if (!lfsck->li_current_oit_processed)
6141                                 pos--;
6142                 } else {
6143                         pos = lo->ll_pos_last_checkpoint;
6144                 }
6145
6146                 seq_printf(m, "current_position: %llu\n", pos);
6147         } else if (lo->ll_status == LS_SCANNING_PHASE2) {
6148                 time64_t duration = ktime_get_seconds() -
6149                                     com->lc_time_last_checkpoint;
6150                 u64 checked = lo->ll_objs_checked_phase2 +
6151                               com->lc_new_checked;
6152                 u64 speed1 = lo->ll_objs_checked_phase1;
6153                 u64 speed2 = checked;
6154                 u64 new_checked = com->lc_new_checked;
6155                 time64_t rtime = lo->ll_run_time_phase2 + duration;
6156
6157                 if (duration != 0)
6158                         new_checked = div64_s64(new_checked, duration);
6159                 if (lo->ll_run_time_phase1 != 0)
6160                         speed1 = div64_s64(speed1, lo->ll_run_time_phase1);
6161                 if (rtime != 0)
6162                         speed2 = div64_s64(speed2, rtime);
6163                 seq_printf(m, "checked_phase1: %llu\n"
6164                            "checked_phase2: %llu\n"
6165                            "run_time_phase1: %lld seconds\n"
6166                            "run_time_phase2: %lld seconds\n"
6167                            "average_speed_phase1: %llu items/sec\n"
6168                            "average_speed_phase2: %llu items/sec\n"
6169                            "real_time_speed_phase1: N/A\n"
6170                            "real_time_speed_phase2: %llu items/sec\n"
6171                            "current_position: "DFID"\n",
6172                            lo->ll_objs_checked_phase1,
6173                            checked,
6174                            lo->ll_run_time_phase1,
6175                            rtime,
6176                            speed1,
6177                            speed2,
6178                            new_checked,
6179                            PFID(&com->lc_fid_latest_scanned_phase2));
6180         } else {
6181                 __u64 speed1 = lo->ll_objs_checked_phase1;
6182                 __u64 speed2 = lo->ll_objs_checked_phase2;
6183
6184                 if (lo->ll_run_time_phase1 != 0)
6185                         speed1 = div64_s64(speed1, lo->ll_run_time_phase1);
6186                 if (lo->ll_run_time_phase2 != 0)
6187                         speed2 = div64_s64(speed2, lo->ll_run_time_phase2);
6188                 seq_printf(m, "checked_phase1: %llu\n"
6189                            "checked_phase2: %llu\n"
6190                            "run_time_phase1: %lld seconds\n"
6191                            "run_time_phase2: %lld seconds\n"
6192                            "average_speed_phase1: %llu items/sec\n"
6193                            "average_speed_phase2: %llu objs/sec\n"
6194                            "real_time_speed_phase1: N/A\n"
6195                            "real_time_speed_phase2: N/A\n"
6196                            "current_position: N/A\n",
6197                            lo->ll_objs_checked_phase1,
6198                            lo->ll_objs_checked_phase2,
6199                            lo->ll_run_time_phase1,
6200                            lo->ll_run_time_phase2,
6201                            speed1,
6202                            speed2);
6203         }
6204
6205         up_read(&com->lc_sem);
6206 }
6207
6208 static int lfsck_layout_master_double_scan(const struct lu_env *env,
6209                                            struct lfsck_component *com)
6210 {
6211         struct lfsck_layout             *lo     = com->lc_file_ram;
6212         struct lfsck_assistant_data     *lad    = com->lc_data;
6213         struct lfsck_instance           *lfsck  = com->lc_lfsck;
6214         struct lfsck_tgt_descs          *ltds;
6215         struct lfsck_tgt_desc           *ltd;
6216         struct lfsck_tgt_desc           *next;
6217         int                              rc;
6218
6219         rc = lfsck_double_scan_generic(env, com, lo->ll_status);
6220
6221         if (thread_is_stopped(&lad->lad_thread)) {
6222                 LASSERT(list_empty(&lad->lad_req_list));
6223                 LASSERT(list_empty(&lad->lad_ost_phase1_list));
6224                 LASSERT(list_empty(&lad->lad_mdt_phase1_list));
6225
6226                 ltds = &lfsck->li_ost_descs;
6227                 spin_lock(&ltds->ltd_lock);
6228                 list_for_each_entry_safe(ltd, next, &lad->lad_ost_phase2_list,
6229                                          ltd_layout_phase_list) {
6230                         list_del_init(&ltd->ltd_layout_phase_list);
6231                 }
6232                 spin_unlock(&ltds->ltd_lock);
6233
6234                 ltds = &lfsck->li_mdt_descs;
6235                 spin_lock(&ltds->ltd_lock);
6236                 list_for_each_entry_safe(ltd, next, &lad->lad_mdt_phase2_list,
6237                                          ltd_layout_phase_list) {
6238                         list_del_init(&ltd->ltd_layout_phase_list);
6239                 }
6240                 spin_unlock(&ltds->ltd_lock);
6241         }
6242
6243         return rc;
6244 }
6245
6246 static int lfsck_layout_slave_double_scan(const struct lu_env *env,
6247                                           struct lfsck_component *com)
6248 {
6249         struct lfsck_instance           *lfsck  = com->lc_lfsck;
6250         struct lfsck_layout_slave_data  *llsd   = com->lc_data;
6251         struct lfsck_layout             *lo     = com->lc_file_ram;
6252         struct ptlrpc_thread            *thread = &lfsck->li_thread;
6253         int                              rc;
6254         ENTRY;
6255
6256         CDEBUG(D_LFSCK, "%s: layout LFSCK slave phase2 scan start\n",
6257                lfsck_lfsck2name(lfsck));
6258
6259         atomic_inc(&lfsck->li_double_scan_count);
6260
6261         if (lo->ll_flags & LF_INCOMPLETE)
6262                 GOTO(done, rc = 1);
6263
6264         com->lc_new_checked = 0;
6265         com->lc_new_scanned = 0;
6266         com->lc_time_last_checkpoint = ktime_get_seconds();
6267         com->lc_time_next_checkpoint = com->lc_time_last_checkpoint +
6268                                        LFSCK_CHECKPOINT_INTERVAL;
6269
6270         while (1) {
6271                 rc = lfsck_layout_slave_query_master(env, com);
6272                 if (list_empty(&llsd->llsd_master_list)) {
6273                         if (unlikely(!thread_is_running(thread)))
6274                                 rc = 0;
6275                         else
6276                                 rc = 1;
6277
6278                         GOTO(done, rc);
6279                 }
6280
6281                 if (rc < 0)
6282                         GOTO(done, rc);
6283
6284                 rc = wait_event_idle_timeout(
6285                         thread->t_ctl_waitq,
6286                         !thread_is_running(thread) ||
6287                         lo->ll_flags & LF_INCOMPLETE ||
6288                         list_empty(&llsd->llsd_master_list),
6289                         cfs_time_seconds(30));
6290                 if (unlikely(!thread_is_running(thread)))
6291                         GOTO(done, rc = 0);
6292
6293                 if (lo->ll_flags & LF_INCOMPLETE)
6294                         GOTO(done, rc = 1);
6295
6296                 if (rc == 0)
6297                         continue;
6298
6299                 GOTO(done, rc = 1);
6300         }
6301
6302 done:
6303         rc = lfsck_layout_double_scan_result(env, com, rc);
6304         lfsck_layout_slave_notify_master(env, com, LE_PHASE2_DONE,
6305                         (rc > 0 && lo->ll_flags & LF_INCOMPLETE) ? 0 : rc);
6306         lfsck_layout_slave_quit(env, com);
6307         if (atomic_dec_and_test(&lfsck->li_double_scan_count))
6308                 wake_up_all(&lfsck->li_thread.t_ctl_waitq);
6309
6310         CDEBUG(D_LFSCK, "%s: layout LFSCK slave phase2 scan finished, "
6311                "status %d: rc = %d\n",
6312                lfsck_lfsck2name(lfsck), lo->ll_status, rc);
6313
6314         return rc;
6315 }
6316
6317 static void lfsck_layout_master_data_release(const struct lu_env *env,
6318                                              struct lfsck_component *com)
6319 {
6320         struct lfsck_assistant_data     *lad    = com->lc_data;
6321         struct lfsck_instance           *lfsck  = com->lc_lfsck;
6322         struct lfsck_tgt_descs          *ltds;
6323         struct lfsck_tgt_desc           *ltd;
6324         struct lfsck_tgt_desc           *next;
6325
6326         LASSERT(lad != NULL);
6327         LASSERT(thread_is_init(&lad->lad_thread) ||
6328                 thread_is_stopped(&lad->lad_thread));
6329         LASSERT(list_empty(&lad->lad_req_list));
6330
6331         com->lc_data = NULL;
6332
6333         ltds = &lfsck->li_ost_descs;
6334         spin_lock(&ltds->ltd_lock);
6335         list_for_each_entry_safe(ltd, next, &lad->lad_ost_phase1_list,
6336                                  ltd_layout_phase_list) {
6337                 list_del_init(&ltd->ltd_layout_phase_list);
6338         }
6339         list_for_each_entry_safe(ltd, next, &lad->lad_ost_phase2_list,
6340                                  ltd_layout_phase_list) {
6341                 list_del_init(&ltd->ltd_layout_phase_list);
6342         }
6343         list_for_each_entry_safe(ltd, next, &lad->lad_ost_list,
6344                                  ltd_layout_list) {
6345                 list_del_init(&ltd->ltd_layout_list);
6346         }
6347         spin_unlock(&ltds->ltd_lock);
6348
6349         ltds = &lfsck->li_mdt_descs;
6350         spin_lock(&ltds->ltd_lock);
6351         list_for_each_entry_safe(ltd, next, &lad->lad_mdt_phase1_list,
6352                                  ltd_layout_phase_list) {
6353                 list_del_init(&ltd->ltd_layout_phase_list);
6354         }
6355         list_for_each_entry_safe(ltd, next, &lad->lad_mdt_phase2_list,
6356                                  ltd_layout_phase_list) {
6357                 list_del_init(&ltd->ltd_layout_phase_list);
6358         }
6359         list_for_each_entry_safe(ltd, next, &lad->lad_mdt_list,
6360                                  ltd_layout_list) {
6361                 list_del_init(&ltd->ltd_layout_list);
6362         }
6363         spin_unlock(&ltds->ltd_lock);
6364
6365         if (likely(lad->lad_bitmap != NULL))
6366                 CFS_FREE_BITMAP(lad->lad_bitmap);
6367
6368         OBD_FREE_PTR(lad);
6369 }
6370
6371 static void lfsck_layout_slave_data_release(const struct lu_env *env,
6372                                             struct lfsck_component *com)
6373 {
6374         struct lfsck_layout_slave_data *llsd = com->lc_data;
6375
6376         lfsck_layout_slave_quit(env, com);
6377         com->lc_data = NULL;
6378         OBD_FREE_PTR(llsd);
6379 }
6380
6381 static void lfsck_layout_master_quit(const struct lu_env *env,
6382                                      struct lfsck_component *com)
6383 {
6384         struct lfsck_assistant_data     *lad    = com->lc_data;
6385         struct lfsck_instance           *lfsck  = com->lc_lfsck;
6386         struct lfsck_tgt_descs          *ltds;
6387         struct lfsck_tgt_desc           *ltd;
6388         struct lfsck_tgt_desc           *next;
6389
6390         LASSERT(lad != NULL);
6391
6392         lfsck_quit_generic(env, com);
6393
6394         LASSERT(thread_is_init(&lad->lad_thread) ||
6395                 thread_is_stopped(&lad->lad_thread));
6396         LASSERT(list_empty(&lad->lad_req_list));
6397
6398         ltds = &lfsck->li_ost_descs;
6399         spin_lock(&ltds->ltd_lock);
6400         list_for_each_entry_safe(ltd, next, &lad->lad_ost_phase1_list,
6401                                  ltd_layout_phase_list) {
6402                 list_del_init(&ltd->ltd_layout_phase_list);
6403         }
6404         list_for_each_entry_safe(ltd, next, &lad->lad_ost_phase2_list,
6405                                  ltd_layout_phase_list) {
6406                 list_del_init(&ltd->ltd_layout_phase_list);
6407         }
6408         spin_unlock(&ltds->ltd_lock);
6409
6410         ltds = &lfsck->li_mdt_descs;
6411         spin_lock(&ltds->ltd_lock);
6412         list_for_each_entry_safe(ltd, next, &lad->lad_mdt_phase1_list,
6413                                  ltd_layout_phase_list) {
6414                 list_del_init(&ltd->ltd_layout_phase_list);
6415         }
6416         list_for_each_entry_safe(ltd, next, &lad->lad_mdt_phase2_list,
6417                                  ltd_layout_phase_list) {
6418                 list_del_init(&ltd->ltd_layout_phase_list);
6419         }
6420         spin_unlock(&ltds->ltd_lock);
6421 }
6422
6423 static void lfsck_layout_slave_quit(const struct lu_env *env,
6424                                     struct lfsck_component *com)
6425 {
6426         struct lfsck_layout_slave_data   *llsd  = com->lc_data;
6427         struct lfsck_layout_seq          *lls;
6428         struct lfsck_layout_seq          *next;
6429         struct lfsck_layout_slave_target *llst;
6430
6431         LASSERT(llsd != NULL);
6432
6433         down_write(&com->lc_sem);
6434         list_for_each_entry_safe(lls, next, &llsd->llsd_seq_list,
6435                                  lls_list) {
6436                 list_del_init(&lls->lls_list);
6437                 lfsck_object_put(env, lls->lls_lastid_obj);
6438                 OBD_FREE_PTR(lls);
6439         }
6440         up_write(&com->lc_sem);
6441
6442         spin_lock(&llsd->llsd_lock);
6443         while (!list_empty(&llsd->llsd_master_list)) {
6444                 llst = list_entry(llsd->llsd_master_list.next,
6445                                   struct lfsck_layout_slave_target, llst_list);
6446                 list_del_init(&llst->llst_list);
6447                 spin_unlock(&llsd->llsd_lock);
6448                 lfsck_layout_llst_put(llst);
6449                 spin_lock(&llsd->llsd_lock);
6450         }
6451         spin_unlock(&llsd->llsd_lock);
6452
6453         lfsck_rbtree_cleanup(env, com);
6454 }
6455
6456 static int lfsck_layout_master_in_notify(const struct lu_env *env,
6457                                          struct lfsck_component *com,
6458                                          struct lfsck_request *lr)
6459 {
6460         struct lfsck_instance           *lfsck = com->lc_lfsck;
6461         struct lfsck_layout             *lo    = com->lc_file_ram;
6462         struct lfsck_assistant_data     *lad   = com->lc_data;
6463         struct lfsck_tgt_descs          *ltds;
6464         struct lfsck_tgt_desc           *ltd;
6465         bool                             fail  = false;
6466         ENTRY;
6467
6468         if (lr->lr_event == LE_PAIRS_VERIFY) {
6469                 int rc;
6470
6471                 rc = lfsck_layout_master_check_pairs(env, com, &lr->lr_fid,
6472                                                      &lr->lr_fid2,
6473                                                      lr->lr_comp_id);
6474
6475                 RETURN(rc);
6476         }
6477
6478         CDEBUG(D_LFSCK, "%s: layout LFSCK master handles notify %u "
6479                "from %s %x, status %d, flags %x, flags2 %x\n",
6480                lfsck_lfsck2name(lfsck), lr->lr_event,
6481                (lr->lr_flags & LEF_FROM_OST) ? "OST" : "MDT",
6482                lr->lr_index, lr->lr_status, lr->lr_flags, lr->lr_flags2);
6483
6484         if (lr->lr_event != LE_PHASE1_DONE &&
6485             lr->lr_event != LE_PHASE2_DONE &&
6486             lr->lr_event != LE_PEER_EXIT)
6487                 RETURN(-EINVAL);
6488
6489         if (lr->lr_flags & LEF_FROM_OST)
6490                 ltds = &lfsck->li_ost_descs;
6491         else
6492                 ltds = &lfsck->li_mdt_descs;
6493         spin_lock(&ltds->ltd_lock);
6494         ltd = lfsck_ltd2tgt(ltds, lr->lr_index);
6495         if (ltd == NULL) {
6496                 spin_unlock(&ltds->ltd_lock);
6497
6498                 RETURN(-ENXIO);
6499         }
6500
6501         list_del_init(&ltd->ltd_layout_phase_list);
6502         switch (lr->lr_event) {
6503         case LE_PHASE1_DONE:
6504                 if (lr->lr_status <= 0 || lr->lr_flags2 & LF_INCOMPLETE) {
6505                         if (lr->lr_flags2 & LF_INCOMPLETE) {
6506                                 if (lr->lr_flags & LEF_FROM_OST)
6507                                         lfsck_lad_set_bitmap(env, com,
6508                                                              ltd->ltd_index);
6509                                 else
6510                                         lo->ll_flags |= LF_INCOMPLETE;
6511                         }
6512                         ltd->ltd_layout_done = 1;
6513                         list_del_init(&ltd->ltd_layout_list);
6514                         fail = true;
6515                         break;
6516                 }
6517
6518                 if (lr->lr_flags & LEF_FROM_OST) {
6519                         if (list_empty(&ltd->ltd_layout_list))
6520                                 list_add_tail(&ltd->ltd_layout_list,
6521                                               &lad->lad_ost_list);
6522                         list_add_tail(&ltd->ltd_layout_phase_list,
6523                                       &lad->lad_ost_phase2_list);
6524                 } else {
6525                         if (list_empty(&ltd->ltd_layout_list))
6526                                 list_add_tail(&ltd->ltd_layout_list,
6527                                               &lad->lad_mdt_list);
6528                         list_add_tail(&ltd->ltd_layout_phase_list,
6529                                       &lad->lad_mdt_phase2_list);
6530                 }
6531                 break;
6532         case LE_PHASE2_DONE:
6533                 ltd->ltd_layout_done = 1;
6534                 if (!list_empty(&ltd->ltd_layout_list))
6535                         list_del_init(&ltd->ltd_layout_list);
6536
6537                 if (lr->lr_flags2 & LF_INCOMPLETE) {
6538                         lfsck_lad_set_bitmap(env, com, ltd->ltd_index);
6539                         fail = true;
6540                 }
6541
6542                 break;
6543         case LE_PEER_EXIT:
6544                 fail = true;
6545                 ltd->ltd_layout_done = 1;
6546                 list_del_init(&ltd->ltd_layout_list);
6547                 if (!(lfsck->li_bookmark_ram.lb_param & LPF_FAILOUT) &&
6548                     !(lr->lr_flags & LEF_FROM_OST))
6549                                 lo->ll_flags |= LF_INCOMPLETE;
6550                 break;
6551         default:
6552                 break;
6553         }
6554         spin_unlock(&ltds->ltd_lock);
6555
6556         if (fail && lfsck->li_bookmark_ram.lb_param & LPF_FAILOUT) {
6557                 struct lfsck_stop *stop = &lfsck_env_info(env)->lti_stop;
6558
6559                 memset(stop, 0, sizeof(*stop));
6560                 stop->ls_status = lr->lr_status;
6561                 stop->ls_flags = lr->lr_param & ~LPF_BROADCAST;
6562                 lfsck_stop(env, lfsck->li_bottom, stop);
6563         } else if (lfsck_phase2_next_ready(lad)) {
6564                 wake_up_all(&lad->lad_thread.t_ctl_waitq);
6565         }
6566
6567         RETURN(0);
6568 }
6569
6570 static int lfsck_layout_slave_in_notify_local(const struct lu_env *env,
6571                                               struct lfsck_component *com,
6572                                               struct lfsck_req_local *lrl,
6573                                               struct thandle *th)
6574 {
6575         ENTRY;
6576
6577         switch (lrl->lrl_event) {
6578         case LEL_FID_ACCESSED:
6579                 lfsck_rbtree_update_bitmap(env, com, &lrl->lrl_fid, true);
6580                 RETURN(0);
6581         case LEL_PAIRS_VERIFY_LOCAL: {
6582                 int rc;
6583
6584                 lrl->lrl_status = LPVS_INIT;
6585                 /* Firstly, if the MDT-object which is claimed via OST-object
6586                  * local stored PFID xattr recognizes the OST-object, then it
6587                  * must be that the client given PFID is wrong. */
6588                 rc = lfsck_layout_slave_check_pairs(env, com, &lrl->lrl_fid,
6589                                 &lrl->lrl_ff_local.ff_parent,
6590                                 lrl->lrl_ff_local.ff_layout.ol_comp_id);
6591                 if (rc <= 0)
6592                         RETURN(0);
6593
6594                 lrl->lrl_status = LPVS_INCONSISTENT;
6595                 /* The OST-object local stored PFID xattr is stale. We need to
6596                  * check whether the MDT-object that is claimed via the client
6597                  * given PFID information recognizes the OST-object or not. If
6598                  * matches, then need to update the OST-object's PFID xattr. */
6599                 rc = lfsck_layout_slave_check_pairs(env, com, &lrl->lrl_fid,
6600                                 &lrl->lrl_ff_client.ff_parent,
6601                                 lrl->lrl_ff_client.ff_layout.ol_comp_id);
6602                 /* For rc < 0 case:
6603                  * We are not sure whether the client given PFID information
6604                  * is correct or not, do nothing to avoid improper fixing.
6605                  *
6606                  * For rc > 0 case:
6607                  * The client given PFID information is also invalid, we can
6608                  * NOT fix the OST-object inconsistency.
6609                  */
6610                 if (!rc) {
6611                         lrl->lrl_status = LPVS_INCONSISTENT_TOFIX;
6612                         rc = lfsck_layout_slave_repair_pfid(env, com, lrl);
6613                 }
6614
6615                 RETURN(rc);
6616         }
6617         default:
6618                 break;
6619         }
6620
6621         RETURN(-EOPNOTSUPP);
6622 }
6623
6624 static int lfsck_layout_slave_in_notify(const struct lu_env *env,
6625                                         struct lfsck_component *com,
6626                                         struct lfsck_request *lr)
6627 {
6628         struct lfsck_instance *lfsck = com->lc_lfsck;
6629         struct lfsck_layout_slave_data *llsd = com->lc_data;
6630         struct lfsck_layout_slave_target *llst;
6631         int rc;
6632         ENTRY;
6633
6634         switch (lr->lr_event) {
6635         case LE_CONDITIONAL_DESTROY:
6636                 rc = lfsck_layout_slave_conditional_destroy(env, com, lr);
6637                 RETURN(rc);
6638         case LE_PHASE1_DONE: {
6639                 if (lr->lr_flags2 & LF_INCOMPLETE) {
6640                         struct lfsck_layout *lo = com->lc_file_ram;
6641
6642                         lo->ll_flags |= LF_INCOMPLETE;
6643                         llst = lfsck_layout_llst_find_and_del(llsd,
6644                                                               lr->lr_index,
6645                                                               true);
6646                         if (llst != NULL) {
6647                                 lfsck_layout_llst_put(llst);
6648                                 wake_up_all(&lfsck->li_thread.t_ctl_waitq);
6649                         }
6650                 }
6651
6652                 RETURN(0);
6653         }
6654         case LE_PHASE2_DONE:
6655         case LE_PEER_EXIT:
6656                 CDEBUG(D_LFSCK, "%s: layout LFSCK slave handle notify %u "
6657                        "from MDT %x, status %d\n", lfsck_lfsck2name(lfsck),
6658                        lr->lr_event, lr->lr_index, lr->lr_status);
6659                 break;
6660         default:
6661                 RETURN(-EINVAL);
6662         }
6663
6664         llst = lfsck_layout_llst_find_and_del(llsd, lr->lr_index, true);
6665         if (llst == NULL)
6666                 RETURN(0);
6667
6668         lfsck_layout_llst_put(llst);
6669         if (list_empty(&llsd->llsd_master_list))
6670                 wake_up_all(&lfsck->li_thread.t_ctl_waitq);
6671
6672         if (lr->lr_event == LE_PEER_EXIT &&
6673             (lfsck->li_bookmark_ram.lb_param & LPF_FAILOUT ||
6674              (list_empty(&llsd->llsd_master_list) &&
6675               (lr->lr_status == LS_STOPPED ||
6676                lr->lr_status == LS_CO_STOPPED)))) {
6677                 struct lfsck_stop *stop = &lfsck_env_info(env)->lti_stop;
6678
6679                 memset(stop, 0, sizeof(*stop));
6680                 stop->ls_status = lr->lr_status;
6681                 stop->ls_flags = lr->lr_param & ~LPF_BROADCAST;
6682                 lfsck_stop(env, lfsck->li_bottom, stop);
6683         }
6684
6685         RETURN(0);
6686 }
6687
6688 static void lfsck_layout_repaired(struct lfsck_layout *lo, __u64 *count)
6689 {
6690         int i;
6691
6692         for (i = 0; i < LLIT_MAX; i++)
6693                 *count += lo->ll_objs_repaired[i];
6694 }
6695
6696 static int lfsck_layout_query_all(const struct lu_env *env,
6697                                   struct lfsck_component *com,
6698                                   __u32 *mdts_count, __u32 *osts_count,
6699                                   __u64 *repaired)
6700 {
6701         struct lfsck_layout *lo = com->lc_file_ram;
6702         struct lfsck_tgt_descs *ltds;
6703         struct lfsck_tgt_desc *ltd;
6704         int idx;
6705         int rc;
6706         ENTRY;
6707
6708         rc = lfsck_query_all(env, com);
6709         if (rc != 0)
6710                 RETURN(rc);
6711
6712         ltds = &com->lc_lfsck->li_mdt_descs;
6713         down_read(&ltds->ltd_rw_sem);
6714         cfs_foreach_bit(ltds->ltd_tgts_bitmap, idx) {
6715                 ltd = lfsck_ltd2tgt(ltds, idx);
6716                 LASSERT(ltd != NULL);
6717
6718                 mdts_count[ltd->ltd_layout_status]++;
6719                 *repaired += ltd->ltd_layout_repaired;
6720         }
6721         up_read(&ltds->ltd_rw_sem);
6722
6723         ltds = &com->lc_lfsck->li_ost_descs;
6724         down_read(&ltds->ltd_rw_sem);
6725         cfs_foreach_bit(ltds->ltd_tgts_bitmap, idx) {
6726                 ltd = lfsck_ltd2tgt(ltds, idx);
6727                 LASSERT(ltd != NULL);
6728
6729                 osts_count[ltd->ltd_layout_status]++;
6730                 *repaired += ltd->ltd_layout_repaired;
6731         }
6732         up_read(&ltds->ltd_rw_sem);
6733
6734         down_read(&com->lc_sem);
6735         mdts_count[lo->ll_status]++;
6736         lfsck_layout_repaired(lo, repaired);
6737         up_read(&com->lc_sem);
6738
6739         RETURN(0);
6740 }
6741
6742 static int lfsck_layout_query(const struct lu_env *env,
6743                               struct lfsck_component *com,
6744                               struct lfsck_request *req,
6745                               struct lfsck_reply *rep,
6746                               struct lfsck_query *que, int idx)
6747 {
6748         struct lfsck_layout *lo = com->lc_file_ram;
6749         int rc = 0;
6750
6751         if (que != NULL) {
6752                 LASSERT(com->lc_lfsck->li_master);
6753
6754                 rc = lfsck_layout_query_all(env, com,
6755                                             que->lu_mdts_count[idx],
6756                                             que->lu_osts_count[idx],
6757                                             &que->lu_repaired[idx]);
6758         } else {
6759                 down_read(&com->lc_sem);
6760                 rep->lr_status = lo->ll_status;
6761                 if (req->lr_flags & LEF_QUERY_ALL)
6762                         lfsck_layout_repaired(lo, &rep->lr_repaired);
6763                 up_read(&com->lc_sem);
6764         }
6765
6766         return rc;
6767 }
6768
6769 /* with lfsck::li_lock held */
6770 static int lfsck_layout_slave_join(const struct lu_env *env,
6771                                    struct lfsck_component *com,
6772                                    struct lfsck_start_param *lsp)
6773 {
6774         struct lfsck_instance            *lfsck = com->lc_lfsck;
6775         struct lfsck_layout_slave_data   *llsd  = com->lc_data;
6776         struct lfsck_layout_slave_target *llst;
6777         struct lfsck_start               *start = lsp->lsp_start;
6778         int                               rc    = 0;
6779         ENTRY;
6780
6781         if (start == NULL || !(start->ls_flags & LPF_OST_ORPHAN))
6782                 RETURN(0);
6783
6784         if (!lsp->lsp_index_valid)
6785                 RETURN(-EINVAL);
6786
6787         /* If someone is running the LFSCK without orphan handling,
6788          * it will not maintain the object accessing rbtree. So we
6789          * cannot join it for orphan handling. */
6790         if (!llsd->llsd_rbtree_valid)
6791                 RETURN(-EBUSY);
6792
6793         spin_unlock(&lfsck->li_lock);
6794         rc = lfsck_layout_llst_add(llsd, lsp->lsp_index);
6795         spin_lock(&lfsck->li_lock);
6796         if (rc == 0 && !thread_is_running(&lfsck->li_thread)) {
6797                 spin_unlock(&lfsck->li_lock);
6798                 llst = lfsck_layout_llst_find_and_del(llsd, lsp->lsp_index,
6799                                                       true);
6800                 if (llst != NULL)
6801                         lfsck_layout_llst_put(llst);
6802                 spin_lock(&lfsck->li_lock);
6803                 rc = -EAGAIN;
6804         }
6805
6806         RETURN(rc);
6807 }
6808
6809 static const struct lfsck_operations lfsck_layout_master_ops = {
6810         .lfsck_reset            = lfsck_layout_reset,
6811         .lfsck_fail             = lfsck_layout_fail,
6812         .lfsck_checkpoint       = lfsck_layout_master_checkpoint,
6813         .lfsck_prep             = lfsck_layout_master_prep,
6814         .lfsck_exec_oit         = lfsck_layout_master_exec_oit,
6815         .lfsck_exec_dir         = lfsck_layout_exec_dir,
6816         .lfsck_post             = lfsck_layout_master_post,
6817         .lfsck_dump             = lfsck_layout_dump,
6818         .lfsck_double_scan      = lfsck_layout_master_double_scan,
6819         .lfsck_data_release     = lfsck_layout_master_data_release,
6820         .lfsck_quit             = lfsck_layout_master_quit,
6821         .lfsck_in_notify        = lfsck_layout_master_in_notify,
6822         .lfsck_query            = lfsck_layout_query,
6823 };
6824
6825 static const struct lfsck_operations lfsck_layout_slave_ops = {
6826         .lfsck_reset            = lfsck_layout_reset,
6827         .lfsck_fail             = lfsck_layout_fail,
6828         .lfsck_checkpoint       = lfsck_layout_slave_checkpoint,
6829         .lfsck_prep             = lfsck_layout_slave_prep,
6830         .lfsck_exec_oit         = lfsck_layout_slave_exec_oit,
6831         .lfsck_exec_dir         = lfsck_layout_exec_dir,
6832         .lfsck_post             = lfsck_layout_slave_post,
6833         .lfsck_dump             = lfsck_layout_dump,
6834         .lfsck_double_scan      = lfsck_layout_slave_double_scan,
6835         .lfsck_data_release     = lfsck_layout_slave_data_release,
6836         .lfsck_quit             = lfsck_layout_slave_quit,
6837         .lfsck_in_notify_local  = lfsck_layout_slave_in_notify_local,
6838         .lfsck_in_notify        = lfsck_layout_slave_in_notify,
6839         .lfsck_query            = lfsck_layout_query,
6840         .lfsck_join             = lfsck_layout_slave_join,
6841 };
6842
6843 static void lfsck_layout_assistant_fill_pos(const struct lu_env *env,
6844                                             struct lfsck_component *com,
6845                                             struct lfsck_position *pos)
6846 {
6847         struct lfsck_assistant_data     *lad = com->lc_data;
6848         struct lfsck_layout_req         *llr;
6849
6850         if (((struct lfsck_layout *)(com->lc_file_ram))->ll_status !=
6851             LS_SCANNING_PHASE1)
6852                 return;
6853
6854         if (list_empty(&lad->lad_req_list))
6855                 return;
6856
6857         llr = list_entry(lad->lad_req_list.next,
6858                          struct lfsck_layout_req,
6859                          llr_lar.lar_list);
6860         pos->lp_oit_cookie = llr->llr_lar.lar_parent->lso_oit_cookie - 1;
6861 }
6862
6863 const struct lfsck_assistant_operations lfsck_layout_assistant_ops = {
6864         .la_handler_p1          = lfsck_layout_assistant_handler_p1,
6865         .la_handler_p2          = lfsck_layout_assistant_handler_p2,
6866         .la_fill_pos            = lfsck_layout_assistant_fill_pos,
6867         .la_double_scan_result  = lfsck_layout_double_scan_result,
6868         .la_req_fini            = lfsck_layout_assistant_req_fini,
6869         .la_sync_failures       = lfsck_layout_assistant_sync_failures,
6870 };
6871
6872 int lfsck_layout_setup(const struct lu_env *env, struct lfsck_instance *lfsck)
6873 {
6874         struct lfsck_component  *com;
6875         struct lfsck_layout     *lo;
6876         struct dt_object        *root = NULL;
6877         struct dt_object        *obj;
6878         int                      i;
6879         int                      rc;
6880         ENTRY;
6881
6882         OBD_ALLOC_PTR(com);
6883         if (com == NULL)
6884                 RETURN(-ENOMEM);
6885
6886         INIT_LIST_HEAD(&com->lc_link);
6887         INIT_LIST_HEAD(&com->lc_link_dir);
6888         init_rwsem(&com->lc_sem);
6889         atomic_set(&com->lc_ref, 1);
6890         com->lc_lfsck = lfsck;
6891         com->lc_type = LFSCK_TYPE_LAYOUT;
6892         if (lfsck->li_master) {
6893                 com->lc_ops = &lfsck_layout_master_ops;
6894                 com->lc_data = lfsck_assistant_data_init(
6895                                 &lfsck_layout_assistant_ops,
6896                                 LFSCK_LAYOUT);
6897                 if (com->lc_data == NULL)
6898                         GOTO(out, rc = -ENOMEM);
6899
6900                 for (i = 0; i < LFSCK_STF_COUNT; i++)
6901                         mutex_init(&com->lc_sub_trace_objs[i].lsto_mutex);
6902         } else {
6903                 struct lfsck_layout_slave_data *llsd;
6904
6905                 com->lc_ops = &lfsck_layout_slave_ops;
6906                 OBD_ALLOC_PTR(llsd);
6907                 if (llsd == NULL)
6908                         GOTO(out, rc = -ENOMEM);
6909
6910                 INIT_LIST_HEAD(&llsd->llsd_seq_list);
6911                 INIT_LIST_HEAD(&llsd->llsd_master_list);
6912                 spin_lock_init(&llsd->llsd_lock);
6913                 llsd->llsd_rb_root = RB_ROOT;
6914                 init_rwsem(&llsd->llsd_rb_rwsem);
6915                 com->lc_data = llsd;
6916         }
6917         com->lc_file_size = sizeof(*lo);
6918         OBD_ALLOC(com->lc_file_ram, com->lc_file_size);
6919         if (com->lc_file_ram == NULL)
6920                 GOTO(out, rc = -ENOMEM);
6921
6922         OBD_ALLOC(com->lc_file_disk, com->lc_file_size);
6923         if (com->lc_file_disk == NULL)
6924                 GOTO(out, rc = -ENOMEM);
6925
6926         root = dt_locate(env, lfsck->li_bottom, &lfsck->li_local_root_fid);
6927         if (IS_ERR(root))
6928                 GOTO(out, rc = PTR_ERR(root));
6929
6930         if (unlikely(!dt_try_as_dir(env, root)))
6931                 GOTO(out, rc = -ENOTDIR);
6932
6933         obj = local_file_find_or_create(env, lfsck->li_los, root,
6934                                         LFSCK_LAYOUT,
6935                                         S_IFREG | S_IRUGO | S_IWUSR);
6936         if (IS_ERR(obj))
6937                 GOTO(out, rc = PTR_ERR(obj));
6938
6939         com->lc_obj = obj;
6940         rc = lfsck_layout_load(env, com);
6941         if (rc > 0) {
6942                 rc = lfsck_layout_reset(env, com, true);
6943         } else if (rc == -ENOENT) {
6944                 rc = lfsck_layout_init(env, com);
6945         } else if (lfsck->li_master) {
6946                 rc = lfsck_load_sub_trace_files(env, com,
6947                                 &dt_lfsck_layout_dangling_features,
6948                                 LFSCK_LAYOUT, false);
6949                 if (rc)
6950                         rc = lfsck_layout_reset(env, com, true);
6951         }
6952
6953         if (rc != 0)
6954                 GOTO(out, rc);
6955
6956         lo = com->lc_file_ram;
6957         switch (lo->ll_status) {
6958         case LS_INIT:
6959         case LS_COMPLETED:
6960         case LS_FAILED:
6961         case LS_STOPPED:
6962         case LS_PARTIAL:
6963                 spin_lock(&lfsck->li_lock);
6964                 list_add_tail(&com->lc_link, &lfsck->li_list_idle);
6965                 spin_unlock(&lfsck->li_lock);
6966                 break;
6967         default:
6968                 CERROR("%s: unknown lfsck_layout status %d\n",
6969                        lfsck_lfsck2name(lfsck), lo->ll_status);
6970                 /* fall through */
6971         case LS_SCANNING_PHASE1:
6972         case LS_SCANNING_PHASE2:
6973                 /* No need to store the status to disk right now.
6974                  * If the system crashed before the status stored,
6975                  * it will be loaded back when next time. */
6976                 lo->ll_status = LS_CRASHED;
6977                 if (!lfsck->li_master)
6978                         lo->ll_flags |= LF_INCOMPLETE;
6979                 /* fall through */
6980         case LS_PAUSED:
6981         case LS_CRASHED:
6982         case LS_CO_FAILED:
6983         case LS_CO_STOPPED:
6984         case LS_CO_PAUSED:
6985                 spin_lock(&lfsck->li_lock);
6986                 list_add_tail(&com->lc_link, &lfsck->li_list_scan);
6987                 spin_unlock(&lfsck->li_lock);
6988                 break;
6989         }
6990
6991         if (lo->ll_flags & LF_CRASHED_LASTID) {
6992                 LASSERT(lfsck->li_out_notify != NULL);
6993
6994                 lfsck->li_out_notify(env, lfsck->li_out_notify_data,
6995                                      LE_LASTID_REBUILDING);
6996         }
6997
6998         GOTO(out, rc = 0);
6999
7000 out:
7001         if (root != NULL && !IS_ERR(root))
7002                 lfsck_object_put(env, root);
7003
7004         if (rc != 0) {
7005                 lfsck_component_cleanup(env, com);
7006                 CERROR("%s: fail to init layout LFSCK component: rc = %d\n",
7007                        lfsck_lfsck2name(lfsck), rc);
7008         }
7009
7010         return rc;
7011 }
7012
7013 struct lfsck_orphan_it {
7014         struct lfsck_component           *loi_com;
7015         struct lfsck_rbtree_node         *loi_lrn;
7016         struct lfsck_layout_slave_target *loi_llst;
7017         struct lu_fid                     loi_key;
7018         struct lu_orphan_rec_v3           loi_rec;
7019         __u64                             loi_hash;
7020         unsigned int                      loi_over:1;
7021 };
7022
7023 static int lfsck_fid_match_idx(const struct lu_env *env,
7024                                struct lfsck_instance *lfsck,
7025                                const struct lu_fid *fid, int idx)
7026 {
7027         struct seq_server_site  *ss;
7028         struct lu_server_fld    *sf;
7029         struct lu_seq_range     *range = &lfsck_env_info(env)->lti_range;
7030         int                      rc;
7031
7032         /* All abnormal cases will be returned to MDT0. */
7033         if (!fid_is_norm(fid)) {
7034                 if (idx == 0)
7035                         return 1;
7036
7037                 return 0;
7038         }
7039
7040         ss = lfsck_dev_site(lfsck);
7041         if (unlikely(ss == NULL))
7042                 return -ENOTCONN;
7043
7044         sf = ss->ss_server_fld;
7045         LASSERT(sf != NULL);
7046
7047         fld_range_set_any(range);
7048         rc = fld_server_lookup(env, sf, fid_seq(fid), range);
7049         if (rc != 0)
7050                 return rc;
7051
7052         if (!fld_range_is_mdt(range))
7053                 return -EINVAL;
7054
7055         if (range->lsr_index == idx)
7056                 return 1;
7057
7058         return 0;
7059 }
7060
7061 static void lfsck_layout_destroy_orphan(const struct lu_env *env,
7062                                         struct dt_object *obj)
7063 {
7064         struct dt_device        *dev    = lfsck_obj2dev(obj);
7065         struct thandle          *handle;
7066         int                      rc;
7067         ENTRY;
7068
7069         handle = dt_trans_create(env, dev);
7070         if (IS_ERR(handle))
7071                 RETURN_EXIT;
7072
7073         rc = dt_declare_ref_del(env, obj, handle);
7074         if (rc != 0)
7075                 GOTO(stop, rc);
7076
7077         rc = dt_declare_destroy(env, obj, handle);
7078         if (rc != 0)
7079                 GOTO(stop, rc);
7080
7081         rc = dt_trans_start_local(env, dev, handle);
7082         if (rc != 0)
7083                 GOTO(stop, rc);
7084
7085         dt_write_lock(env, obj, 0);
7086         rc = dt_ref_del(env, obj, handle);
7087         if (rc == 0)
7088                 rc = dt_destroy(env, obj, handle);
7089         dt_write_unlock(env, obj);
7090
7091         GOTO(stop, rc);
7092
7093 stop:
7094         dt_trans_stop(env, dev, handle);
7095
7096         CDEBUG(D_LFSCK, "destroy orphan OST-object "DFID": rc = %d\n",
7097                PFID(lfsck_dto2fid(obj)), rc);
7098
7099         RETURN_EXIT;
7100 }
7101
7102 static int lfsck_orphan_index_lookup(const struct lu_env *env,
7103                                      struct dt_object *dt,
7104                                      struct dt_rec *rec,
7105                                      const struct dt_key *key)
7106 {
7107         return -EOPNOTSUPP;
7108 }
7109
7110 static int lfsck_orphan_index_declare_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_insert(const struct lu_env *env,
7120                                      struct dt_object *dt,
7121                                      const struct dt_rec *rec,
7122                                      const struct dt_key *key,
7123                                      struct thandle *handle)
7124 {
7125         return -EOPNOTSUPP;
7126 }
7127
7128 static int lfsck_orphan_index_declare_delete(const struct lu_env *env,
7129                                              struct dt_object *dt,
7130                                              const struct dt_key *key,
7131                                              struct thandle *handle)
7132 {
7133         return -EOPNOTSUPP;
7134 }
7135
7136 static int lfsck_orphan_index_delete(const struct lu_env *env,
7137                                      struct dt_object *dt,
7138                                      const struct dt_key *key,
7139                                      struct thandle *handle)
7140 {
7141         return -EOPNOTSUPP;
7142 }
7143
7144 static struct dt_it *lfsck_orphan_it_init(const struct lu_env *env,
7145                                           struct dt_object *dt,
7146                                           __u32 attr)
7147 {
7148         struct dt_device                *dev    = lu2dt_dev(dt->do_lu.lo_dev);
7149         struct lfsck_instance           *lfsck;
7150         struct lfsck_component          *com    = NULL;
7151         struct lfsck_layout_slave_data  *llsd;
7152         struct lfsck_orphan_it          *it     = NULL;
7153         struct lfsck_layout             *lo;
7154         int                              rc     = 0;
7155         ENTRY;
7156
7157         lfsck = lfsck_instance_find(dev, true, false);
7158         if (unlikely(lfsck == NULL))
7159                 RETURN(ERR_PTR(-ENXIO));
7160
7161         com = lfsck_component_find(lfsck, LFSCK_TYPE_LAYOUT);
7162         if (unlikely(com == NULL))
7163                 GOTO(out, rc = -ENOENT);
7164
7165         lo = com->lc_file_ram;
7166         if (lo->ll_flags & LF_INCOMPLETE)
7167                 GOTO(out, rc = -ESRCH);
7168
7169         llsd = com->lc_data;
7170         if (!llsd->llsd_rbtree_valid)
7171                 GOTO(out, rc = -ESRCH);
7172
7173         OBD_ALLOC_PTR(it);
7174         if (it == NULL)
7175                 GOTO(out, rc = -ENOMEM);
7176
7177         it->loi_llst = lfsck_layout_llst_find_and_del(llsd, attr, false);
7178         if (it->loi_llst == NULL)
7179                 GOTO(out, rc = -ENXIO);
7180
7181         if (dev->dd_record_fid_accessed) {
7182                 /* The first iteration against the rbtree, scan the whole rbtree
7183                  * to remove the nodes which do NOT need to be handled. */
7184                 down_write(&llsd->llsd_rb_rwsem);
7185                 if (dev->dd_record_fid_accessed) {
7186                         struct rb_node                  *node;
7187                         struct rb_node                  *next;
7188                         struct lfsck_rbtree_node        *lrn;
7189
7190                         /* No need to record the fid accessing anymore. */
7191                         dev->dd_record_fid_accessed = 0;
7192
7193                         node = rb_first(&llsd->llsd_rb_root);
7194                         while (node != NULL) {
7195                                 next = rb_next(node);
7196                                 lrn = rb_entry(node, struct lfsck_rbtree_node,
7197                                                lrn_node);
7198                                 if (atomic_read(&lrn->lrn_known_count) <=
7199                                     atomic_read(&lrn->lrn_accessed_count)) {
7200                                         rb_erase(node, &llsd->llsd_rb_root);
7201                                         lfsck_rbtree_free(lrn);
7202                                 }
7203                                 node = next;
7204                         }
7205                 }
7206                 up_write(&llsd->llsd_rb_rwsem);
7207         }
7208
7209         /* read lock the rbtree when init, and unlock when fini */
7210         down_read(&llsd->llsd_rb_rwsem);
7211         it->loi_com = com;
7212         com = NULL;
7213
7214         GOTO(out, rc = 0);
7215
7216 out:
7217         if (com != NULL)
7218                 lfsck_component_put(env, com);
7219
7220         CDEBUG(D_LFSCK, "%s: init the orphan iteration: rc = %d\n",
7221                lfsck_lfsck2name(lfsck), rc);
7222
7223         lfsck_instance_put(env, lfsck);
7224         if (rc != 0) {
7225                 if (it != NULL)
7226                         OBD_FREE_PTR(it);
7227
7228                 it = (struct lfsck_orphan_it *)ERR_PTR(rc);
7229         }
7230
7231         return (struct dt_it *)it;
7232 }
7233
7234 static void lfsck_orphan_it_fini(const struct lu_env *env,
7235                                  struct dt_it *di)
7236 {
7237         struct lfsck_orphan_it           *it    = (struct lfsck_orphan_it *)di;
7238         struct lfsck_component           *com   = it->loi_com;
7239         struct lfsck_layout_slave_data   *llsd;
7240         struct lfsck_layout_slave_target *llst;
7241
7242         if (com != NULL) {
7243                 CDEBUG(D_LFSCK, "%s: fini the orphan iteration\n",
7244                        lfsck_lfsck2name(com->lc_lfsck));
7245
7246                 llsd = com->lc_data;
7247                 up_read(&llsd->llsd_rb_rwsem);
7248                 llst = it->loi_llst;
7249                 LASSERT(llst != NULL);
7250
7251                 /* Save the key and hash for iterate next. */
7252                 llst->llst_fid = it->loi_key;
7253                 llst->llst_hash = it->loi_hash;
7254                 lfsck_layout_llst_put(llst);
7255                 lfsck_component_put(env, com);
7256         }
7257         OBD_FREE_PTR(it);
7258 }
7259
7260 /**
7261  * \retval       +1: the iteration finished
7262  * \retval        0: on success, not finished
7263  * \retval      -ve: on error
7264  */
7265 static int lfsck_orphan_it_next(const struct lu_env *env,
7266                                 struct dt_it *di)
7267 {
7268         struct lfsck_thread_info        *info   = lfsck_env_info(env);
7269         struct filter_fid               *ff     = &info->lti_ff;
7270         struct lu_attr                  *la     = &info->lti_la;
7271         struct lfsck_orphan_it          *it     = (struct lfsck_orphan_it *)di;
7272         struct lu_fid                   *key    = &it->loi_key;
7273         struct lu_orphan_rec_v3         *rec    = &it->loi_rec;
7274         struct ost_layout               *ol     = &rec->lor_layout;
7275         struct lfsck_component          *com    = it->loi_com;
7276         struct lfsck_instance           *lfsck  = com->lc_lfsck;
7277         struct lfsck_layout_slave_data  *llsd   = com->lc_data;
7278         struct dt_object                *obj;
7279         struct lfsck_rbtree_node        *lrn;
7280         int                              pos;
7281         int                              rc;
7282         __u32                            save;
7283         __u32                            idx    = it->loi_llst->llst_index;
7284         bool                             exact  = false;
7285         ENTRY;
7286
7287         if (it->loi_over)
7288                 RETURN(1);
7289
7290 again0:
7291         lrn = it->loi_lrn;
7292         if (lrn == NULL) {
7293                 lrn = lfsck_rbtree_search(llsd, key, &exact);
7294                 if (lrn == NULL) {
7295                         it->loi_over = 1;
7296                         RETURN(1);
7297                 }
7298
7299                 it->loi_lrn = lrn;
7300                 if (!exact) {
7301                         key->f_seq = lrn->lrn_seq;
7302                         key->f_oid = lrn->lrn_first_oid;
7303                         key->f_ver = 0;
7304                 }
7305         } else {
7306                 key->f_oid++;
7307                 if (unlikely(key->f_oid == 0)) {
7308                         key->f_seq++;
7309                         it->loi_lrn = NULL;
7310                         goto again0;
7311                 }
7312
7313                 if (key->f_oid >=
7314                     lrn->lrn_first_oid + LFSCK_RBTREE_BITMAP_WIDTH) {
7315                         it->loi_lrn = NULL;
7316                         goto again0;
7317                 }
7318         }
7319
7320         if (unlikely(atomic_read(&lrn->lrn_known_count) <=
7321                      atomic_read(&lrn->lrn_accessed_count))) {
7322                 struct rb_node *next = rb_next(&lrn->lrn_node);
7323
7324                 while (next != NULL) {
7325                         lrn = rb_entry(next, struct lfsck_rbtree_node,
7326                                        lrn_node);
7327                         if (atomic_read(&lrn->lrn_known_count) >
7328                             atomic_read(&lrn->lrn_accessed_count))
7329                                 break;
7330                         next = rb_next(next);
7331                 }
7332
7333                 if (next == NULL) {
7334                         it->loi_over = 1;
7335                         RETURN(1);
7336                 }
7337
7338                 it->loi_lrn = lrn;
7339                 key->f_seq = lrn->lrn_seq;
7340                 key->f_oid = lrn->lrn_first_oid;
7341                 key->f_ver = 0;
7342         }
7343
7344         pos = key->f_oid - lrn->lrn_first_oid;
7345
7346 again1:
7347         pos = find_next_bit(lrn->lrn_known_bitmap,
7348                             LFSCK_RBTREE_BITMAP_WIDTH, pos);
7349         if (pos >= LFSCK_RBTREE_BITMAP_WIDTH) {
7350                 key->f_oid = lrn->lrn_first_oid + pos;
7351                 if (unlikely(key->f_oid < lrn->lrn_first_oid)) {
7352                         key->f_seq++;
7353                         key->f_oid = 0;
7354                 }
7355                 it->loi_lrn = NULL;
7356                 goto again0;
7357         }
7358
7359         if (test_bit(pos, lrn->lrn_accessed_bitmap)) {
7360                 pos++;
7361                 goto again1;
7362         }
7363
7364         key->f_oid = lrn->lrn_first_oid + pos;
7365         obj = lfsck_object_find_bottom(env, lfsck, key);
7366         if (IS_ERR(obj)) {
7367                 rc = PTR_ERR(obj);
7368                 if (rc == -ENOENT) {
7369                         pos++;
7370                         goto again1;
7371                 }
7372                 RETURN(rc);
7373         }
7374
7375         dt_read_lock(env, obj, 0);
7376         if (dt_object_exists(obj) == 0 ||
7377             lfsck_is_dead_obj(obj)) {
7378                 dt_read_unlock(env, obj);
7379                 lfsck_object_put(env, obj);
7380                 pos++;
7381                 goto again1;
7382         }
7383
7384         rc = dt_attr_get(env, obj, la);
7385         if (rc != 0)
7386                 GOTO(out, rc);
7387
7388         rc = dt_xattr_get(env, obj, lfsck_buf_get(env, ff, sizeof(*ff)),
7389                           XATTR_NAME_FID);
7390         if (rc == -ENODATA) {
7391                 /* For the pre-created OST-object, update the bitmap to avoid
7392                  * others LFSCK (second phase) iteration to touch it again. */
7393                 if (la->la_ctime == 0) {
7394                         if (!test_and_set_bit(pos, lrn->lrn_accessed_bitmap))
7395                                 atomic_inc(&lrn->lrn_accessed_count);
7396
7397                         /* For the race between repairing dangling referenced
7398                          * MDT-object and unlink the file, it may left orphan
7399                          * OST-object there. Destroy it now! */
7400                         if (unlikely(!(la->la_mode & S_ISUID))) {
7401                                 dt_read_unlock(env, obj);
7402                                 lfsck_layout_destroy_orphan(env, obj);
7403                                 lfsck_object_put(env, obj);
7404                                 pos++;
7405                                 goto again1;
7406                         }
7407                 } else if (idx == 0) {
7408                         /* If the orphan OST-object has no parent information,
7409                          * regard it as referenced by the MDT-object on MDT0. */
7410                         fid_zero(&rec->lor_rec.lor_fid);
7411                         rec->lor_rec.lor_uid = la->la_uid;
7412                         rec->lor_rec.lor_gid = la->la_gid;
7413                         memset(ol, 0, sizeof(*ol));
7414                         rec->lor_layout_version = 0;
7415                         rec->lor_range = 0;
7416
7417                         GOTO(out, rc = 0);
7418                 }
7419
7420                 dt_read_unlock(env, obj);
7421                 lfsck_object_put(env, obj);
7422                 pos++;
7423                 goto again1;
7424         }
7425
7426         if (rc < sizeof(struct lu_fid))
7427                 GOTO(out, rc = (rc < 0 ? rc : -EINVAL));
7428
7429         fid_le_to_cpu(&rec->lor_rec.lor_fid, &ff->ff_parent);
7430         /* Currently, the filter_fid::ff_parent::f_ver is not the real parent
7431          * MDT-object's FID::f_ver, instead it is the OST-object index in its
7432          * parent MDT-object's layout EA. */
7433         save = rec->lor_rec.lor_fid.f_stripe_idx;
7434         rec->lor_rec.lor_fid.f_ver = 0;
7435         rc = lfsck_fid_match_idx(env, lfsck, &rec->lor_rec.lor_fid, idx);
7436         /* If the orphan OST-object does not claim the MDT, then next.
7437          *
7438          * If we do not know whether it matches or not, then return it
7439          * to the MDT for further check. */
7440         if (rc == 0) {
7441                 dt_read_unlock(env, obj);
7442                 lfsck_object_put(env, obj);
7443                 pos++;
7444                 goto again1;
7445         }
7446
7447         rec->lor_rec.lor_fid.f_stripe_idx = save;
7448         rec->lor_rec.lor_uid = la->la_uid;
7449         rec->lor_rec.lor_gid = la->la_gid;
7450         ost_layout_le_to_cpu(ol, &ff->ff_layout);
7451         rec->lor_layout_version =
7452                 le32_to_cpu(ff->ff_layout_version & ~LU_LAYOUT_RESYNC);
7453         rec->lor_range = le32_to_cpu(ff->ff_range);
7454
7455         CDEBUG(D_LFSCK, "%s: return orphan "DFID", PFID "DFID", owner %u:%u, "
7456                "stripe size %u, stripe count %u, COMP id %u, COMP start %llu, "
7457                "COMP end %llu, layout version %u, range %u\n",
7458                lfsck_lfsck2name(com->lc_lfsck), PFID(key),
7459                PFID(&rec->lor_rec.lor_fid), rec->lor_rec.lor_uid,
7460                rec->lor_rec.lor_gid, ol->ol_stripe_size, ol->ol_stripe_count,
7461                ol->ol_comp_id, ol->ol_comp_start, ol->ol_comp_end,
7462                rec->lor_layout_version, rec->lor_range);
7463
7464         GOTO(out, rc = 0);
7465
7466 out:
7467         dt_read_unlock(env, obj);
7468         lfsck_object_put(env, obj);
7469         if (rc == 0)
7470                 it->loi_hash++;
7471
7472         return rc;
7473 }
7474
7475 /**
7476  * \retval       +1: locate to the exactly position
7477  * \retval        0: cannot locate to the exactly position,
7478  *                   call next() to move to a valid position.
7479  * \retval      -ve: on error
7480  */
7481 static int lfsck_orphan_it_get(const struct lu_env *env,
7482                                struct dt_it *di,
7483                                const struct dt_key *key)
7484 {
7485         struct lfsck_orphan_it  *it   = (struct lfsck_orphan_it *)di;
7486         int                      rc;
7487
7488         it->loi_key = *(struct lu_fid *)key;
7489         rc = lfsck_orphan_it_next(env, di);
7490         if (rc == 1)
7491                 return 0;
7492
7493         if (rc == 0)
7494                 return 1;
7495
7496         return rc;
7497 }
7498
7499 static void lfsck_orphan_it_put(const struct lu_env *env,
7500                                 struct dt_it *di)
7501 {
7502 }
7503
7504 static struct dt_key *lfsck_orphan_it_key(const struct lu_env *env,
7505                                           const struct dt_it *di)
7506 {
7507         struct lfsck_orphan_it *it = (struct lfsck_orphan_it *)di;
7508
7509         return (struct dt_key *)&it->loi_key;
7510 }
7511
7512 static int lfsck_orphan_it_key_size(const struct lu_env *env,
7513                                     const struct dt_it *di)
7514 {
7515         return sizeof(struct lu_fid);
7516 }
7517
7518 static int lfsck_orphan_it_rec(const struct lu_env *env,
7519                                const struct dt_it *di,
7520                                struct dt_rec *rec,
7521                                __u32 attr)
7522 {
7523         struct lfsck_orphan_it *it = (struct lfsck_orphan_it *)di;
7524
7525         *(struct lu_orphan_rec_v3 *)rec = it->loi_rec;
7526
7527         return 0;
7528 }
7529
7530 static __u64 lfsck_orphan_it_store(const struct lu_env *env,
7531                                    const struct dt_it *di)
7532 {
7533         struct lfsck_orphan_it  *it   = (struct lfsck_orphan_it *)di;
7534
7535         return it->loi_hash;
7536 }
7537
7538 /**
7539  * \retval       +1: locate to the exactly position
7540  * \retval        0: cannot locate to the exactly position,
7541  *                   call next() to move to a valid position.
7542  * \retval      -ve: on error
7543  */
7544 static int lfsck_orphan_it_load(const struct lu_env *env,
7545                                 const struct dt_it *di,
7546                                 __u64 hash)
7547 {
7548         struct lfsck_orphan_it           *it   = (struct lfsck_orphan_it *)di;
7549         struct lfsck_layout_slave_target *llst = it->loi_llst;
7550         int                               rc;
7551
7552         LASSERT(llst != NULL);
7553
7554         if (hash != llst->llst_hash) {
7555                 CDEBUG(D_LFSCK, "%s: the given hash %llu for orphan "
7556                        "iteration does not match the one when fini "
7557                        "%llu, to be reset.\n",
7558                        lfsck_lfsck2name(it->loi_com->lc_lfsck), hash,
7559                        llst->llst_hash);
7560                 fid_zero(&llst->llst_fid);
7561                 llst->llst_hash = 0;
7562         }
7563
7564         it->loi_key = llst->llst_fid;
7565         it->loi_hash = llst->llst_hash;
7566         rc = lfsck_orphan_it_next(env, (struct dt_it *)di);
7567         if (rc == 1)
7568                 return 0;
7569
7570         if (rc == 0)
7571                 return 1;
7572
7573         return rc;
7574 }
7575
7576 static int lfsck_orphan_it_key_rec(const struct lu_env *env,
7577                                    const struct dt_it *di,
7578                                    void *key_rec)
7579 {
7580         return 0;
7581 }
7582
7583 static const struct dt_index_operations lfsck_orphan_index_ops = {
7584         .dio_lookup             = lfsck_orphan_index_lookup,
7585         .dio_declare_insert     = lfsck_orphan_index_declare_insert,
7586         .dio_insert             = lfsck_orphan_index_insert,
7587         .dio_declare_delete     = lfsck_orphan_index_declare_delete,
7588         .dio_delete             = lfsck_orphan_index_delete,
7589         .dio_it = {
7590                 .init           = lfsck_orphan_it_init,
7591                 .fini           = lfsck_orphan_it_fini,
7592                 .get            = lfsck_orphan_it_get,
7593                 .put            = lfsck_orphan_it_put,
7594                 .next           = lfsck_orphan_it_next,
7595                 .key            = lfsck_orphan_it_key,
7596                 .key_size       = lfsck_orphan_it_key_size,
7597                 .rec            = lfsck_orphan_it_rec,
7598                 .store          = lfsck_orphan_it_store,
7599                 .load           = lfsck_orphan_it_load,
7600                 .key_rec        = lfsck_orphan_it_key_rec,
7601         }
7602 };