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