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