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