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