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