Whamcloud - gitweb
f59dca754205ad31e50b22c46be5cb74c2567f2f
[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         char                            *name   = info->lti_key;
1983         struct lu_attr                  *la     = &info->lti_la;
1984         struct dt_object_format         *dof    = &info->lti_dof;
1985         struct lfsck_instance           *lfsck  = com->lc_lfsck;
1986         struct lu_fid                   *pfid   = &rec->lor_fid;
1987         struct lu_fid                   *tfid   = &info->lti_fid3;
1988         struct dt_device                *next   = lfsck->li_next;
1989         struct dt_object                *pobj   = NULL;
1990         struct dt_object                *cobj   = NULL;
1991         struct thandle                  *th     = NULL;
1992         struct lu_buf                   *pbuf   = NULL;
1993         struct lu_buf                   *ea_buf = &info->lti_big_buf;
1994         struct lustre_handle             lh     = { 0 };
1995         struct linkea_data               ldata  = { 0 };
1996         struct lu_buf                    linkea_buf;
1997         const struct lu_name            *pname;
1998         int                              buflen = ea_buf->lb_len;
1999         int                              idx    = 0;
2000         int                              rc     = 0;
2001         ENTRY;
2002
2003         /* Create .lustre/lost+found/MDTxxxx when needed. */
2004         if (unlikely(lfsck->li_lpf_obj == NULL)) {
2005                 rc = lfsck_create_lpf(env, lfsck);
2006                 if (rc != 0)
2007                         GOTO(log, rc);
2008         }
2009
2010         if (fid_is_zero(pfid)) {
2011                 struct filter_fid *ff = &info->lti_new_pfid;
2012
2013                 rc = lfsck_fid_alloc(env, lfsck, pfid, false);
2014                 if (rc != 0)
2015                         RETURN(rc);
2016
2017                 ff->ff_parent.f_seq = cpu_to_le64(pfid->f_seq);
2018                 ff->ff_parent.f_oid = cpu_to_le32(pfid->f_oid);
2019                 /* Currently, the filter_fid::ff_parent::f_ver is not the
2020                  * real parent MDT-object's FID::f_ver, instead it is the
2021                  * OST-object index in its parent MDT-object's layout EA. */
2022                 ff->ff_parent.f_stripe_idx = cpu_to_le32(ea_off);
2023                 pbuf = lfsck_buf_get(env, ff, sizeof(struct filter_fid));
2024                 cobj = lfsck_object_find_by_dev(env, ltd->ltd_tgt, cfid);
2025                 if (IS_ERR(cobj))
2026                         GOTO(log, rc = PTR_ERR(cobj));
2027         }
2028
2029         pobj = lfsck_object_find_by_dev(env, lfsck->li_bottom, pfid);
2030         if (IS_ERR(pobj))
2031                 GOTO(put, rc = PTR_ERR(pobj));
2032
2033         LASSERT(infix != NULL);
2034         LASSERT(type != NULL);
2035
2036         do {
2037                 snprintf(name, NAME_MAX, DFID"%s-%s-%d", PFID(pfid), infix,
2038                          type, idx++);
2039                 rc = dt_lookup(env, lfsck->li_lpf_obj, (struct dt_rec *)tfid,
2040                                (const struct dt_key *)name, BYPASS_CAPA);
2041                 if (rc != 0 && rc != -ENOENT)
2042                         GOTO(put, rc);
2043         } while (rc == 0);
2044
2045         rc = linkea_data_new(&ldata,
2046                              &lfsck_env_info(env)->lti_linkea_buf);
2047         if (rc != 0)
2048                 GOTO(put, rc);
2049
2050         pname = lfsck_name_get_const(env, name, strlen(name));
2051         rc = linkea_add_buf(&ldata, pname, lfsck_dto2fid(lfsck->li_lpf_obj));
2052         if (rc != 0)
2053                 GOTO(put, rc);
2054
2055         memset(la, 0, sizeof(*la));
2056         la->la_uid = rec->lor_uid;
2057         la->la_gid = rec->lor_gid;
2058         la->la_mode = S_IFREG | S_IRUSR;
2059         la->la_valid = LA_MODE | LA_UID | LA_GID;
2060
2061         memset(dof, 0, sizeof(*dof));
2062         dof->dof_type = dt_mode_to_dft(S_IFREG);
2063
2064         rc = lov_mds_md_size(ea_off + 1, LOV_MAGIC_V1);
2065         if (buflen < rc) {
2066                 lu_buf_realloc(ea_buf, rc);
2067                 buflen = ea_buf->lb_len;
2068                 if (ea_buf->lb_buf == NULL)
2069                         GOTO(put, rc = -ENOMEM);
2070         } else {
2071                 ea_buf->lb_len = rc;
2072         }
2073
2074         /* Hold update lock on the .lustre/lost+found/MDTxxxx/.
2075          *
2076          * XXX: Currently, we do not grab the PDO lock as normal create cases,
2077          *      because creating MDT-object for orphan OST-object is rare, we
2078          *      do not much care about the performance. It can be improved in
2079          *      the future when needed. */
2080         rc = lfsck_layout_lock(env, com, lfsck->li_lpf_obj, &lh,
2081                                MDS_INODELOCK_UPDATE);
2082         if (rc != 0)
2083                 GOTO(put, rc);
2084
2085         th = dt_trans_create(env, next);
2086         if (IS_ERR(th))
2087                 GOTO(unlock, rc = PTR_ERR(th));
2088
2089         /* 1a. Update OST-object's parent information remotely.
2090          *
2091          * If other subsequent modifications failed, then next LFSCK scanning
2092          * will process the OST-object as orphan again with known parent FID. */
2093         if (cobj != NULL) {
2094                 rc = dt_declare_xattr_set(env, cobj, pbuf, XATTR_NAME_FID, 0, th);
2095                 if (rc != 0)
2096                         GOTO(stop, rc);
2097         }
2098
2099         /* 2a. Create the MDT-object locally. */
2100         rc = dt_declare_create(env, pobj, la, NULL, dof, th);
2101         if (rc != 0)
2102                 GOTO(stop, rc);
2103
2104         /* 3a. Add layout EA for the MDT-object. */
2105         rc = dt_declare_xattr_set(env, pobj, ea_buf, XATTR_NAME_LOV,
2106                                   LU_XATTR_CREATE, th);
2107         if (rc != 0)
2108                 GOTO(stop, rc);
2109
2110         /* 4a. Insert the MDT-object to .lustre/lost+found/MDTxxxx/ */
2111         rc = dt_declare_insert(env, lfsck->li_lpf_obj,
2112                                (const struct dt_rec *)pfid,
2113                                (const struct dt_key *)name, th);
2114         if (rc != 0)
2115                 GOTO(stop, rc);
2116
2117         /* 5a. insert linkEA for parent. */
2118         linkea_buf.lb_buf = ldata.ld_buf->lb_buf;
2119         linkea_buf.lb_len = ldata.ld_leh->leh_len;
2120         rc = dt_declare_xattr_set(env, pobj, &linkea_buf,
2121                                   XATTR_NAME_LINK, 0, th);
2122         if (rc != 0)
2123                 GOTO(stop, rc);
2124
2125         rc = dt_trans_start(env, next, th);
2126         if (rc != 0)
2127                 GOTO(stop, rc);
2128
2129         /* 1b. Update OST-object's parent information remotely. */
2130         if (cobj != NULL) {
2131                 rc = dt_xattr_set(env, cobj, pbuf, XATTR_NAME_FID, 0, th,
2132                                   BYPASS_CAPA);
2133                 if (rc != 0)
2134                         GOTO(stop, rc);
2135         }
2136
2137         dt_write_lock(env, pobj, 0);
2138         /* 2b. Create the MDT-object locally. */
2139         rc = dt_create(env, pobj, la, NULL, dof, th);
2140         if (rc == 0)
2141                 /* 3b. Add layout EA for the MDT-object. */
2142                 rc = lfsck_layout_extend_lovea(env, lfsck, th, pobj, cfid,
2143                                                ea_buf, LU_XATTR_CREATE,
2144                                                ltd->ltd_index, ea_off, false);
2145         dt_write_unlock(env, pobj);
2146         if (rc < 0)
2147                 GOTO(stop, rc);
2148
2149         /* 4b. Insert the MDT-object to .lustre/lost+found/MDTxxxx/ */
2150         rc = dt_insert(env, lfsck->li_lpf_obj,
2151                        (const struct dt_rec *)pfid,
2152                        (const struct dt_key *)name, th, BYPASS_CAPA, 1);
2153         if (rc != 0)
2154                 GOTO(stop, rc);
2155
2156         /* 5b. insert linkEA for parent. */
2157         rc = dt_xattr_set(env, pobj, &linkea_buf,
2158                           XATTR_NAME_LINK, 0, th, BYPASS_CAPA);
2159
2160         GOTO(stop, rc);
2161
2162 stop:
2163         dt_trans_stop(env, next, th);
2164
2165 unlock:
2166         lfsck_layout_unlock(&lh);
2167
2168 put:
2169         if (cobj != NULL && !IS_ERR(cobj))
2170                 lu_object_put(env, &cobj->do_lu);
2171         if (pobj != NULL && !IS_ERR(pobj))
2172                 lu_object_put(env, &pobj->do_lu);
2173         ea_buf->lb_len = buflen;
2174
2175 log:
2176         if (rc < 0)
2177                 CDEBUG(D_LFSCK, "%s layout LFSCK assistant failed to "
2178                        "recreate the lost MDT-object: parent "DFID
2179                        ", child "DFID", OST-index %u, stripe-index %u, "
2180                        "infix %s, type %s: rc = %d\n",
2181                        lfsck_lfsck2name(lfsck), PFID(pfid), PFID(cfid),
2182                        ltd->ltd_index, ea_off, infix, type, rc);
2183
2184         return rc >= 0 ? 1 : rc;
2185 }
2186
2187 static int lfsck_layout_master_conditional_destroy(const struct lu_env *env,
2188                                                    struct lfsck_component *com,
2189                                                    const struct lu_fid *fid,
2190                                                    __u32 index)
2191 {
2192         struct lfsck_thread_info *info  = lfsck_env_info(env);
2193         struct lfsck_request     *lr    = &info->lti_lr;
2194         struct lfsck_instance    *lfsck = com->lc_lfsck;
2195         struct lfsck_tgt_desc    *ltd;
2196         struct ptlrpc_request    *req;
2197         struct lfsck_request     *tmp;
2198         struct obd_export        *exp;
2199         int                       rc    = 0;
2200         ENTRY;
2201
2202         ltd = lfsck_tgt_get(&lfsck->li_ost_descs, index);
2203         if (unlikely(ltd == NULL))
2204                 RETURN(-ENXIO);
2205
2206         exp = ltd->ltd_exp;
2207         if (!(exp_connect_flags(exp) & OBD_CONNECT_LFSCK))
2208                 GOTO(put, rc = -EOPNOTSUPP);
2209
2210         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_LFSCK_NOTIFY);
2211         if (req == NULL)
2212                 GOTO(put, rc = -ENOMEM);
2213
2214         rc = ptlrpc_request_pack(req, LUSTRE_OBD_VERSION, LFSCK_NOTIFY);
2215         if (rc != 0) {
2216                 ptlrpc_request_free(req);
2217
2218                 GOTO(put, rc);
2219         }
2220
2221         memset(lr, 0, sizeof(*lr));
2222         lr->lr_event = LE_CONDITIONAL_DESTROY;
2223         lr->lr_active = LFSCK_TYPE_LAYOUT;
2224         lr->lr_fid = *fid;
2225
2226         tmp = req_capsule_client_get(&req->rq_pill, &RMF_LFSCK_REQUEST);
2227         *tmp = *lr;
2228         ptlrpc_request_set_replen(req);
2229
2230         rc = ptlrpc_queue_wait(req);
2231         ptlrpc_req_finished(req);
2232
2233         GOTO(put, rc);
2234
2235 put:
2236         lfsck_tgt_put(ltd);
2237
2238         return rc;
2239 }
2240
2241 static int lfsck_layout_slave_conditional_destroy(const struct lu_env *env,
2242                                                   struct lfsck_component *com,
2243                                                   struct lfsck_request *lr)
2244 {
2245         struct lfsck_thread_info        *info   = lfsck_env_info(env);
2246         struct lu_attr                  *la     = &info->lti_la;
2247         ldlm_policy_data_t              *policy = &info->lti_policy;
2248         struct ldlm_res_id              *resid  = &info->lti_resid;
2249         struct lfsck_instance           *lfsck  = com->lc_lfsck;
2250         struct dt_device                *dev    = lfsck->li_bottom;
2251         struct lu_fid                   *fid    = &lr->lr_fid;
2252         struct dt_object                *obj;
2253         struct thandle                  *th     = NULL;
2254         struct lustre_handle             lh     = { 0 };
2255         __u64                            flags  = 0;
2256         int                              rc     = 0;
2257         ENTRY;
2258
2259         obj = lfsck_object_find_by_dev(env, dev, fid);
2260         if (IS_ERR(obj))
2261                 RETURN(PTR_ERR(obj));
2262
2263         dt_read_lock(env, obj, 0);
2264         if (dt_object_exists(obj) == 0) {
2265                 dt_read_unlock(env, obj);
2266
2267                 GOTO(put, rc = -ENOENT);
2268         }
2269
2270         /* Get obj's attr without lock firstly. */
2271         rc = dt_attr_get(env, obj, la, BYPASS_CAPA);
2272         dt_read_unlock(env, obj);
2273         if (rc != 0)
2274                 GOTO(put, rc);
2275
2276         if (likely(la->la_ctime != 0 || la->la_mode & S_ISUID))
2277                 GOTO(put, rc = -ETXTBSY);
2278
2279         /* Acquire extent lock on [0, EOF] to sync with all possible written. */
2280         LASSERT(lfsck->li_namespace != NULL);
2281
2282         memset(policy, 0, sizeof(*policy));
2283         policy->l_extent.end = OBD_OBJECT_EOF;
2284         ost_fid_build_resid(fid, resid);
2285         rc = ldlm_cli_enqueue_local(lfsck->li_namespace, resid, LDLM_EXTENT,
2286                                     policy, LCK_EX, &flags, ldlm_blocking_ast,
2287                                     ldlm_completion_ast, NULL, NULL, 0,
2288                                     LVB_T_NONE, NULL, &lh);
2289         if (rc != ELDLM_OK)
2290                 GOTO(put, rc = -EIO);
2291
2292         dt_write_lock(env, obj, 0);
2293         /* Get obj's attr within lock again. */
2294         rc = dt_attr_get(env, obj, la, BYPASS_CAPA);
2295         if (rc != 0)
2296                 GOTO(unlock, rc);
2297
2298         if (la->la_ctime != 0)
2299                 GOTO(unlock, rc = -ETXTBSY);
2300
2301         th = dt_trans_create(env, dev);
2302         if (IS_ERR(th))
2303                 GOTO(unlock, rc = PTR_ERR(th));
2304
2305         rc = dt_declare_ref_del(env, obj, th);
2306         if (rc != 0)
2307                 GOTO(stop, rc);
2308
2309         rc = dt_declare_destroy(env, obj, th);
2310         if (rc != 0)
2311                 GOTO(stop, rc);
2312
2313         rc = dt_trans_start_local(env, dev, th);
2314         if (rc != 0)
2315                 GOTO(stop, rc);
2316
2317         rc = dt_ref_del(env, obj, th);
2318         if (rc != 0)
2319                 GOTO(stop, rc);
2320
2321         rc = dt_destroy(env, obj, th);
2322         if (rc == 0)
2323                 CDEBUG(D_LFSCK, "%s: layout LFSCK destroyed the empty "
2324                        "OST-object "DFID" that was created for reparing "
2325                        "dangling referenced case. But the original missed "
2326                        "OST-object is found now.\n",
2327                        lfsck_lfsck2name(lfsck), PFID(fid));
2328
2329         GOTO(stop, rc);
2330
2331 stop:
2332         dt_trans_stop(env, dev, th);
2333
2334 unlock:
2335         dt_write_unlock(env, obj);
2336         ldlm_lock_decref(&lh, LCK_EX);
2337
2338 put:
2339         lu_object_put(env, &obj->do_lu);
2340
2341         return rc;
2342 }
2343
2344 /**
2345  * Some OST-object has occupied the specified layout EA slot.
2346  * Such OST-object may be generated by the LFSCK when repair
2347  * dangling referenced MDT-object, which can be indicated by
2348  * attr::la_ctime == 0 but without S_ISUID in la_mode. If it
2349  * is true and such OST-object has not been modified yet, we
2350  * will replace it with the orphan OST-object; otherwise the
2351  * LFSCK will create new MDT-object to reference the orphan.
2352  *
2353  * \retval       +1: repaired
2354  * \retval        0: did nothing
2355  * \retval      -ve: on error
2356  */
2357 static int lfsck_layout_conflict_create(const struct lu_env *env,
2358                                         struct lfsck_component *com,
2359                                         struct lfsck_tgt_desc *ltd,
2360                                         struct lu_orphan_rec *rec,
2361                                         struct dt_object *parent,
2362                                         struct lu_fid *cfid,
2363                                         struct lu_buf *ea_buf,
2364                                         struct lov_ost_data_v1 *slot,
2365                                         __u32 ea_off, __u32 ori_len)
2366 {
2367         struct lfsck_thread_info *info          = lfsck_env_info(env);
2368         struct lu_fid            *cfid2         = &info->lti_fid2;
2369         struct ost_id            *oi            = &info->lti_oi;
2370         char                     *infix         = info->lti_tmpbuf;
2371         struct lov_mds_md_v1     *lmm           = ea_buf->lb_buf;
2372         struct dt_device         *dev           = com->lc_lfsck->li_bottom;
2373         struct thandle           *th            = NULL;
2374         struct lustre_handle      lh            = { 0 };
2375         __u32                     ost_idx2      = le32_to_cpu(slot->l_ost_idx);
2376         int                       rc            = 0;
2377         ENTRY;
2378
2379         ostid_le_to_cpu(&slot->l_ost_oi, oi);
2380         ostid_to_fid(cfid2, oi, ost_idx2);
2381
2382         /* Hold layout lock on the parent to prevent others to access. */
2383         rc = lfsck_layout_lock(env, com, parent, &lh,
2384                                MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR);
2385         if (rc != 0)
2386                 GOTO(out, rc);
2387
2388         rc = lfsck_layout_master_conditional_destroy(env, com, cfid2, ost_idx2);
2389
2390         /* If the conflict OST-obejct is not created for fixing dangling
2391          * referenced MDT-object in former LFSCK check/repair, or it has
2392          * been modified by others, then we cannot destroy it. Re-create
2393          * a new MDT-object for the orphan OST-object. */
2394         if (rc == -ETXTBSY) {
2395                 /* No need the layout lock on the original parent. */
2396                 lfsck_layout_unlock(&lh);
2397                 ea_buf->lb_len = ori_len;
2398
2399                 fid_zero(&rec->lor_fid);
2400                 snprintf(infix, LFSCK_TMPBUF_LEN, "-"DFID"-%x",
2401                          PFID(lu_object_fid(&parent->do_lu)), ea_off);
2402                 rc = lfsck_layout_recreate_parent(env, com, ltd, rec, cfid,
2403                                                   infix, "C", ea_off);
2404
2405                 RETURN(rc);
2406         }
2407
2408         if (rc != 0 && rc != -ENOENT)
2409                 GOTO(unlock, rc);
2410
2411         th = dt_trans_create(env, dev);
2412         if (IS_ERR(th))
2413                 GOTO(unlock, rc = PTR_ERR(th));
2414
2415         rc = dt_declare_xattr_set(env, parent, ea_buf, XATTR_NAME_LOV,
2416                                   LU_XATTR_REPLACE, th);
2417         if (rc != 0)
2418                 GOTO(stop, rc);
2419
2420         rc = dt_trans_start_local(env, dev, th);
2421         if (rc != 0)
2422                 GOTO(stop, rc);
2423
2424         dt_write_lock(env, parent, 0);
2425         lmm->lmm_layout_gen = cpu_to_le16(le16_to_cpu(lmm->lmm_layout_gen) + 1);
2426         rc = lfsck_layout_refill_lovea(env, th, parent, cfid, ea_buf, slot,
2427                                        LU_XATTR_REPLACE, ltd->ltd_index);
2428         dt_write_unlock(env, parent);
2429
2430         GOTO(stop, rc);
2431
2432 stop:
2433         dt_trans_stop(env, dev, th);
2434
2435 unlock:
2436         lfsck_layout_unlock(&lh);
2437
2438 out:
2439         ea_buf->lb_len = ori_len;
2440
2441         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant replaced the conflict "
2442                "OST-object "DFID" on the OST %x with the orphan "DFID" on "
2443                "the OST %x: parent "DFID", stripe-index %u: rc = %d\n",
2444                lfsck_lfsck2name(com->lc_lfsck), PFID(cfid2), ost_idx2,
2445                PFID(cfid), ltd->ltd_index, PFID(lfsck_dto2fid(parent)),
2446                ea_off, rc);
2447
2448         return rc >= 0 ? 1 : rc;
2449 }
2450
2451 /**
2452  * \retval       +1: repaired
2453  * \retval        0: did nothing
2454  * \retval      -ve: on error
2455  */
2456 static int lfsck_layout_recreate_lovea(const struct lu_env *env,
2457                                        struct lfsck_component *com,
2458                                        struct lfsck_tgt_desc *ltd,
2459                                        struct lu_orphan_rec *rec,
2460                                        struct dt_object *parent,
2461                                        struct lu_fid *cfid,
2462                                        __u32 ost_idx, __u32 ea_off)
2463 {
2464         struct lfsck_thread_info *info          = lfsck_env_info(env);
2465         struct lu_buf            *buf           = &info->lti_big_buf;
2466         struct lu_fid            *fid           = &info->lti_fid2;
2467         struct ost_id            *oi            = &info->lti_oi;
2468         struct lfsck_instance    *lfsck         = com->lc_lfsck;
2469         struct dt_device         *dt            = lfsck->li_bottom;
2470         struct lfsck_bookmark    *bk            = &lfsck->li_bookmark_ram;
2471         struct thandle            *handle       = NULL;
2472         size_t                    buflen        = buf->lb_len;
2473         struct lov_mds_md_v1     *lmm;
2474         struct lov_ost_data_v1   *objs;
2475         struct lustre_handle      lh            = { 0 };
2476         __u32                     magic;
2477         int                       fl            = 0;
2478         int                       rc            = 0;
2479         int                       rc1;
2480         int                       i;
2481         __u16                     count;
2482         bool                      locked        = false;
2483         ENTRY;
2484
2485         rc = lfsck_layout_lock(env, com, parent, &lh,
2486                                MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR);
2487         if (rc != 0) {
2488                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant failed to recreate "
2489                        "LOV EA for "DFID": parent "DFID", OST-index %u, "
2490                        "stripe-index %u: rc = %d\n",
2491                        lfsck_lfsck2name(lfsck), PFID(cfid),
2492                        PFID(lfsck_dto2fid(parent)), ost_idx, ea_off, rc);
2493
2494                 RETURN(rc);
2495         }
2496
2497 again:
2498         if (locked) {
2499                 dt_write_unlock(env, parent);
2500                 locked = false;
2501         }
2502
2503         if (handle != NULL) {
2504                 dt_trans_stop(env, dt, handle);
2505                 handle = NULL;
2506         }
2507
2508         if (rc < 0)
2509                 GOTO(unlock_layout, rc);
2510
2511         if (buf->lb_len < rc) {
2512                 lu_buf_realloc(buf, rc);
2513                 buflen = buf->lb_len;
2514                 if (buf->lb_buf == NULL)
2515                         GOTO(unlock_layout, rc = -ENOMEM);
2516         }
2517
2518         if (!(bk->lb_param & LPF_DRYRUN)) {
2519                 handle = dt_trans_create(env, dt);
2520                 if (IS_ERR(handle))
2521                         GOTO(unlock_layout, rc = PTR_ERR(handle));
2522
2523                 rc = dt_declare_xattr_set(env, parent, buf, XATTR_NAME_LOV,
2524                                           fl, handle);
2525                 if (rc != 0)
2526                         GOTO(stop, rc);
2527
2528                 rc = dt_trans_start_local(env, dt, handle);
2529                 if (rc != 0)
2530                         GOTO(stop, rc);
2531         }
2532
2533         dt_write_lock(env, parent, 0);
2534         locked = true;
2535         rc = dt_xattr_get(env, parent, buf, XATTR_NAME_LOV, BYPASS_CAPA);
2536         if (rc == -ERANGE) {
2537                 rc = dt_xattr_get(env, parent, &LU_BUF_NULL, XATTR_NAME_LOV,
2538                                   BYPASS_CAPA);
2539                 LASSERT(rc != 0);
2540                 goto again;
2541         } else if (rc == -ENODATA || rc == 0) {
2542                 rc = lov_mds_md_size(ea_off + 1, LOV_MAGIC_V1);
2543                 /* If the declared is not big enough, re-try. */
2544                 if (buf->lb_len < rc)
2545                         goto again;
2546
2547                 fl = LU_XATTR_CREATE;
2548         } else if (rc < 0) {
2549                 GOTO(unlock_parent, rc);
2550         } else if (unlikely(buf->lb_len == 0)) {
2551                 goto again;
2552         } else {
2553                 fl = LU_XATTR_REPLACE;
2554         }
2555
2556         if (fl == LU_XATTR_CREATE) {
2557                 if (bk->lb_param & LPF_DRYRUN)
2558                         GOTO(unlock_parent, rc = 1);
2559
2560                 LASSERT(buf->lb_len >= rc);
2561
2562                 buf->lb_len = rc;
2563                 rc = lfsck_layout_extend_lovea(env, lfsck, handle, parent, cfid,
2564                                                buf, fl, ost_idx, ea_off, false);
2565
2566                 GOTO(unlock_parent, rc);
2567         }
2568
2569         lmm = buf->lb_buf;
2570         rc1 = lfsck_layout_verify_header(lmm);
2571
2572         /* If the LOV EA crashed, the rebuild it. */
2573         if (rc1 == -EINVAL) {
2574                 if (bk->lb_param & LPF_DRYRUN)
2575                         GOTO(unlock_parent, rc = 1);
2576
2577                 LASSERT(buf->lb_len >= rc);
2578
2579                 buf->lb_len = rc;
2580                 memset(lmm, 0, buf->lb_len);
2581                 rc = lfsck_layout_extend_lovea(env, lfsck, handle, parent, cfid,
2582                                                buf, fl, ost_idx, ea_off, true);
2583
2584                 GOTO(unlock_parent, rc);
2585         }
2586
2587         /* For other unknown magic/pattern, keep the current LOV EA. */
2588         if (rc1 != 0)
2589                 GOTO(unlock_parent, rc = rc1);
2590
2591         /* Currently, we only support LOV_MAGIC_V1/LOV_MAGIC_V3 which has
2592          * been verified in lfsck_layout_verify_header() already. If some
2593          * new magic introduced in the future, then layout LFSCK needs to
2594          * be updated also. */
2595         magic = le32_to_cpu(lmm->lmm_magic);
2596         if (magic == LOV_MAGIC_V1) {
2597                 objs = &lmm->lmm_objects[0];
2598         } else {
2599                 LASSERT(magic == LOV_MAGIC_V3);
2600                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[0];
2601         }
2602
2603         count = le16_to_cpu(lmm->lmm_stripe_count);
2604         if (count == 0)
2605                 GOTO(unlock_parent, rc = -EINVAL);
2606         LASSERT(count > 0);
2607
2608         /* Exceed the current end of MDT-object layout EA. Then extend it. */
2609         if (count <= ea_off) {
2610                 if (bk->lb_param & LPF_DRYRUN)
2611                         GOTO(unlock_parent, rc = 1);
2612
2613                 rc = lov_mds_md_size(ea_off + 1, magic);
2614                 /* If the declared is not big enough, re-try. */
2615                 if (buf->lb_len < rc)
2616                         goto again;
2617
2618                 buf->lb_len = rc;
2619                 rc = lfsck_layout_extend_lovea(env, lfsck, handle, parent, cfid,
2620                                                buf, fl, ost_idx, ea_off, false);
2621
2622                 GOTO(unlock_parent, rc);
2623         }
2624
2625         LASSERTF(rc > 0, "invalid rc = %d\n", rc);
2626
2627         buf->lb_len = rc;
2628         for (i = 0; i < count; i++, objs++) {
2629                 /* The MDT-object was created via lfsck_layout_recover_create()
2630                  * by others before, and we fill the dummy layout EA. */
2631                 if (lovea_slot_is_dummy(objs)) {
2632                         if (i != ea_off)
2633                                 continue;
2634
2635                         if (bk->lb_param & LPF_DRYRUN)
2636                                 GOTO(unlock_parent, rc = 1);
2637
2638                         lmm->lmm_layout_gen =
2639                             cpu_to_le16(le16_to_cpu(lmm->lmm_layout_gen) + 1);
2640                         rc = lfsck_layout_refill_lovea(env, handle, parent,
2641                                                        cfid, buf, objs, fl,
2642                                                        ost_idx);
2643
2644                         CDEBUG(D_LFSCK, "%s layout LFSCK assistant fill "
2645                                "dummy layout slot for "DFID": parent "DFID
2646                                ", OST-index %u, stripe-index %u: rc = %d\n",
2647                                lfsck_lfsck2name(lfsck), PFID(cfid),
2648                                PFID(lfsck_dto2fid(parent)), ost_idx, i, rc);
2649
2650                         GOTO(unlock_parent, rc);
2651                 }
2652
2653                 ostid_le_to_cpu(&objs->l_ost_oi, oi);
2654                 ostid_to_fid(fid, oi, le32_to_cpu(objs->l_ost_idx));
2655                 /* It should be rare case, the slot is there, but the LFSCK
2656                  * does not handle it during the first-phase cycle scanning. */
2657                 if (unlikely(lu_fid_eq(fid, cfid))) {
2658                         if (i == ea_off) {
2659                                 GOTO(unlock_parent, rc = 0);
2660                         } else {
2661                                 /* Rare case that the OST-object index
2662                                  * does not match the parent MDT-object
2663                                  * layout EA. We trust the later one. */
2664                                 if (bk->lb_param & LPF_DRYRUN)
2665                                         GOTO(unlock_parent, rc = 1);
2666
2667                                 dt_write_unlock(env, parent);
2668                                 if (handle != NULL)
2669                                         dt_trans_stop(env, dt, handle);
2670                                 lfsck_layout_unlock(&lh);
2671                                 buf->lb_len = buflen;
2672                                 rc = lfsck_layout_update_pfid(env, com, parent,
2673                                                         cfid, ltd->ltd_tgt, i);
2674
2675                                 CDEBUG(D_LFSCK, "%s layout LFSCK assistant "
2676                                        "updated OST-object's pfid for "DFID
2677                                        ": parent "DFID", OST-index %u, "
2678                                        "stripe-index %u: rc = %d\n",
2679                                        lfsck_lfsck2name(lfsck), PFID(cfid),
2680                                        PFID(lfsck_dto2fid(parent)),
2681                                        ltd->ltd_index, i, rc);
2682
2683                                 RETURN(rc);
2684                         }
2685                 }
2686         }
2687
2688         /* The MDT-object exists, but related layout EA slot is occupied
2689          * by others. */
2690         if (bk->lb_param & LPF_DRYRUN)
2691                 GOTO(unlock_parent, rc = 1);
2692
2693         dt_write_unlock(env, parent);
2694         if (handle != NULL)
2695                 dt_trans_stop(env, dt, handle);
2696         lfsck_layout_unlock(&lh);
2697         if (le32_to_cpu(lmm->lmm_magic) == LOV_MAGIC_V1)
2698                 objs = &lmm->lmm_objects[ea_off];
2699         else
2700                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[ea_off];
2701         rc = lfsck_layout_conflict_create(env, com, ltd, rec, parent, cfid,
2702                                           buf, objs, ea_off, buflen);
2703
2704         RETURN(rc);
2705
2706 unlock_parent:
2707         if (locked)
2708                 dt_write_unlock(env, parent);
2709
2710 stop:
2711         if (handle != NULL)
2712                 dt_trans_stop(env, dt, handle);
2713
2714 unlock_layout:
2715         lfsck_layout_unlock(&lh);
2716         buf->lb_len = buflen;
2717
2718         return rc;
2719 }
2720
2721 static int lfsck_layout_scan_orphan_one(const struct lu_env *env,
2722                                         struct lfsck_component *com,
2723                                         struct lfsck_tgt_desc *ltd,
2724                                         struct lu_orphan_rec *rec,
2725                                         struct lu_fid *cfid)
2726 {
2727         struct lfsck_layout     *lo     = com->lc_file_ram;
2728         struct lu_fid           *pfid   = &rec->lor_fid;
2729         struct dt_object        *parent = NULL;
2730         __u32                    ea_off = pfid->f_stripe_idx;
2731         int                      rc     = 0;
2732         ENTRY;
2733
2734         if (!fid_is_sane(cfid))
2735                 GOTO(out, rc = -EINVAL);
2736
2737         if (fid_is_zero(pfid)) {
2738                 rc = lfsck_layout_recreate_parent(env, com, ltd, rec, cfid,
2739                                                   "", "N", ea_off);
2740                 GOTO(out, rc);
2741         }
2742
2743         pfid->f_ver = 0;
2744         if (!fid_is_sane(pfid))
2745                 GOTO(out, rc = -EINVAL);
2746
2747         parent = lfsck_object_find_by_dev(env, com->lc_lfsck->li_bottom, pfid);
2748         if (IS_ERR(parent))
2749                 GOTO(out, rc = PTR_ERR(parent));
2750
2751         if (unlikely(dt_object_remote(parent) != 0))
2752                 GOTO(put, rc = -EXDEV);
2753
2754         if (dt_object_exists(parent) == 0) {
2755                 lu_object_put(env, &parent->do_lu);
2756                 rc = lfsck_layout_recreate_parent(env, com, ltd, rec, cfid,
2757                                                   "", "R", ea_off);
2758                 GOTO(out, rc);
2759         }
2760
2761         if (!S_ISREG(lu_object_attr(&parent->do_lu)))
2762                 GOTO(put, rc = -EISDIR);
2763
2764         rc = lfsck_layout_recreate_lovea(env, com, ltd, rec, parent, cfid,
2765                                          ltd->ltd_index, ea_off);
2766
2767         GOTO(put, rc);
2768
2769 put:
2770         if (rc <= 0)
2771                 lu_object_put(env, &parent->do_lu);
2772         else
2773                 /* The layout EA is changed, need to be reloaded next time. */
2774                 lu_object_put_nocache(env, &parent->do_lu);
2775
2776 out:
2777         down_write(&com->lc_sem);
2778         com->lc_new_scanned++;
2779         com->lc_new_checked++;
2780         if (rc > 0) {
2781                 lo->ll_objs_repaired[LLIT_ORPHAN - 1]++;
2782                 rc = 0;
2783         } else if (rc < 0) {
2784                 lo->ll_objs_failed_phase2++;
2785         }
2786         up_write(&com->lc_sem);
2787
2788         return rc;
2789 }
2790
2791 static int lfsck_layout_scan_orphan(const struct lu_env *env,
2792                                     struct lfsck_component *com,
2793                                     struct lfsck_tgt_desc *ltd)
2794 {
2795         struct lfsck_layout             *lo     = com->lc_file_ram;
2796         struct lfsck_instance           *lfsck  = com->lc_lfsck;
2797         struct lfsck_bookmark           *bk     = &lfsck->li_bookmark_ram;
2798         struct lfsck_thread_info        *info   = lfsck_env_info(env);
2799         struct ost_id                   *oi     = &info->lti_oi;
2800         struct lu_fid                   *fid    = &info->lti_fid;
2801         struct dt_object                *obj;
2802         const struct dt_it_ops          *iops;
2803         struct dt_it                    *di;
2804         int                              rc     = 0;
2805         ENTRY;
2806
2807         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant starts the orphan "
2808                "scanning for OST%04x\n",
2809                lfsck_lfsck2name(lfsck), ltd->ltd_index);
2810
2811         ostid_set_seq(oi, FID_SEQ_IDIF);
2812         ostid_set_id(oi, 0);
2813         ostid_to_fid(fid, oi, ltd->ltd_index);
2814         obj = lfsck_object_find_by_dev(env, ltd->ltd_tgt, fid);
2815         if (unlikely(IS_ERR(obj)))
2816                 GOTO(log, rc = PTR_ERR(obj));
2817
2818         rc = obj->do_ops->do_index_try(env, obj, &dt_lfsck_orphan_features);
2819         if (rc != 0)
2820                 GOTO(put, rc);
2821
2822         iops = &obj->do_index_ops->dio_it;
2823         di = iops->init(env, obj, 0, BYPASS_CAPA);
2824         if (IS_ERR(di))
2825                 GOTO(put, rc = PTR_ERR(di));
2826
2827         rc = iops->load(env, di, 0);
2828         if (rc == -ESRCH) {
2829                 /* -ESRCH means that the orphan OST-objects rbtree has been
2830                  * cleanup because of the OSS server restart or other errors. */
2831                 lo->ll_flags |= LF_INCOMPLETE;
2832                 GOTO(fini, rc);
2833         }
2834
2835         if (rc == 0)
2836                 rc = iops->next(env, di);
2837         else if (rc > 0)
2838                 rc = 0;
2839
2840         if (rc < 0)
2841                 GOTO(fini, rc);
2842
2843         if (rc > 0)
2844                 GOTO(fini, rc = 0);
2845
2846         do {
2847                 struct dt_key           *key;
2848                 struct lu_orphan_rec    *rec = &info->lti_rec;
2849
2850                 if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_DELAY3) &&
2851                     cfs_fail_val > 0) {
2852                         struct ptlrpc_thread    *thread = &lfsck->li_thread;
2853                         struct l_wait_info       lwi;
2854
2855                         lwi = LWI_TIMEOUT(cfs_time_seconds(cfs_fail_val),
2856                                           NULL, NULL);
2857                         l_wait_event(thread->t_ctl_waitq,
2858                                      !thread_is_running(thread),
2859                                      &lwi);
2860                 }
2861
2862                 key = iops->key(env, di);
2863                 com->lc_fid_latest_scanned_phase2 = *(struct lu_fid *)key;
2864                 rc = iops->rec(env, di, (struct dt_rec *)rec, 0);
2865                 if (rc == 0)
2866                         rc = lfsck_layout_scan_orphan_one(env, com, ltd, rec,
2867                                         &com->lc_fid_latest_scanned_phase2);
2868                 if (rc != 0 && bk->lb_param & LPF_FAILOUT)
2869                         GOTO(fini, rc);
2870
2871                 lfsck_control_speed_by_self(com);
2872                 do {
2873                         rc = iops->next(env, di);
2874                 } while (rc < 0 && !(bk->lb_param & LPF_FAILOUT));
2875         } while (rc == 0);
2876
2877         GOTO(fini, rc);
2878
2879 fini:
2880         iops->put(env, di);
2881         iops->fini(env, di);
2882 put:
2883         lu_object_put(env, &obj->do_lu);
2884
2885 log:
2886         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant finished the orphan "
2887                "scanning for OST%04x: rc = %d\n",
2888                lfsck_lfsck2name(lfsck), ltd->ltd_index, rc);
2889
2890         return rc > 0 ? 0 : rc;
2891 }
2892
2893 /* For the MDT-object with dangling reference, we need to repare the
2894  * inconsistency according to the LFSCK sponsor's requirement:
2895  *
2896  * 1) Keep the inconsistency there and report the inconsistency case,
2897  *    then give the chance to the application to find related issues,
2898  *    and the users can make the decision about how to handle it with
2899  *    more human knownledge. (by default)
2900  *
2901  * 2) Re-create the missed OST-object with the FID/owner information. */
2902 static int lfsck_layout_repair_dangling(const struct lu_env *env,
2903                                         struct lfsck_component *com,
2904                                         struct lfsck_layout_req *llr,
2905                                         const struct lu_attr *pla)
2906 {
2907         struct lfsck_thread_info        *info   = lfsck_env_info(env);
2908         struct filter_fid               *pfid   = &info->lti_new_pfid;
2909         struct dt_allocation_hint       *hint   = &info->lti_hint;
2910         struct lu_attr                  *cla    = &info->lti_la2;
2911         struct dt_object                *parent = llr->llr_parent->llo_obj;
2912         struct dt_object                *child  = llr->llr_child;
2913         struct dt_device                *dev    = lfsck_obj2dt_dev(child);
2914         const struct lu_fid             *tfid   = lu_object_fid(&parent->do_lu);
2915         struct thandle                  *handle;
2916         struct lu_buf                   *buf;
2917         struct lustre_handle             lh     = { 0 };
2918         int                              rc;
2919         bool                             create;
2920         ENTRY;
2921
2922         if (com->lc_lfsck->li_bookmark_ram.lb_param & LPF_CREATE_OSTOBJ)
2923                 create = true;
2924         else
2925                 create = false;
2926
2927         if (!create)
2928                 GOTO(log, rc = 1);
2929
2930         memset(cla, 0, sizeof(*cla));
2931         cla->la_uid = pla->la_uid;
2932         cla->la_gid = pla->la_gid;
2933         cla->la_mode = S_IFREG | 0666;
2934         cla->la_valid = LA_TYPE | LA_MODE | LA_UID | LA_GID |
2935                         LA_ATIME | LA_MTIME | LA_CTIME;
2936
2937         rc = lfsck_layout_lock(env, com, parent, &lh,
2938                                MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR);
2939         if (rc != 0)
2940                 GOTO(log, rc);
2941
2942         handle = dt_trans_create(env, dev);
2943         if (IS_ERR(handle))
2944                 GOTO(unlock1, rc = PTR_ERR(handle));
2945
2946         hint->dah_parent = NULL;
2947         hint->dah_mode = 0;
2948         pfid->ff_parent.f_seq = cpu_to_le64(tfid->f_seq);
2949         pfid->ff_parent.f_oid = cpu_to_le32(tfid->f_oid);
2950         /* Currently, the filter_fid::ff_parent::f_ver is not the real parent
2951          * MDT-object's FID::f_ver, instead it is the OST-object index in its
2952          * parent MDT-object's layout EA. */
2953         pfid->ff_parent.f_stripe_idx = cpu_to_le32(llr->llr_lov_idx);
2954         buf = lfsck_buf_get(env, pfid, sizeof(struct filter_fid));
2955
2956         rc = dt_declare_create(env, child, cla, hint, NULL, handle);
2957         if (rc != 0)
2958                 GOTO(stop, rc);
2959
2960         rc = dt_declare_xattr_set(env, child, buf, XATTR_NAME_FID,
2961                                   LU_XATTR_CREATE, handle);
2962         if (rc != 0)
2963                 GOTO(stop, rc);
2964
2965         rc = dt_trans_start(env, dev, handle);
2966         if (rc != 0)
2967                 GOTO(stop, rc);
2968
2969         dt_read_lock(env, parent, 0);
2970         if (unlikely(lu_object_is_dying(parent->do_lu.lo_header)))
2971                 GOTO(unlock2, rc = 1);
2972
2973         rc = dt_create(env, child, cla, hint, NULL, handle);
2974         if (rc != 0)
2975                 GOTO(unlock2, rc);
2976
2977         rc = dt_xattr_set(env, child, buf, XATTR_NAME_FID, LU_XATTR_CREATE,
2978                           handle, BYPASS_CAPA);
2979
2980         GOTO(unlock2, rc);
2981
2982 unlock2:
2983         dt_read_unlock(env, parent);
2984
2985 stop:
2986         rc = lfsck_layout_trans_stop(env, dev, handle, rc);
2987
2988 unlock1:
2989         lfsck_layout_unlock(&lh);
2990
2991 log:
2992         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant found dangling "
2993                "reference for: parent "DFID", child "DFID", OST-index %u, "
2994                "stripe-index %u, owner %u/%u. %s: rc = %d\n",
2995                lfsck_lfsck2name(com->lc_lfsck), PFID(lfsck_dto2fid(parent)),
2996                PFID(lfsck_dto2fid(child)), llr->llr_ost_idx,
2997                llr->llr_lov_idx, pla->la_uid, pla->la_gid,
2998                create ? "Create the lost OST-object as required" :
2999                         "Keep the MDT-object there by default", rc);
3000
3001         return rc;
3002 }
3003
3004 /* If the OST-object does not recognize the MDT-object as its parent, and
3005  * there is no other MDT-object claims as its parent, then just trust the
3006  * given MDT-object as its parent. So update the OST-object filter_fid. */
3007 static int lfsck_layout_repair_unmatched_pair(const struct lu_env *env,
3008                                               struct lfsck_component *com,
3009                                               struct lfsck_layout_req *llr,
3010                                               const struct lu_attr *pla)
3011 {
3012         struct lfsck_thread_info        *info   = lfsck_env_info(env);
3013         struct filter_fid               *pfid   = &info->lti_new_pfid;
3014         struct lu_attr                  *tla    = &info->lti_la3;
3015         struct dt_object                *parent = llr->llr_parent->llo_obj;
3016         struct dt_object                *child  = llr->llr_child;
3017         struct dt_device                *dev    = lfsck_obj2dt_dev(child);
3018         const struct lu_fid             *tfid   = lu_object_fid(&parent->do_lu);
3019         struct thandle                  *handle;
3020         struct lu_buf                   *buf;
3021         struct lustre_handle             lh     = { 0 };
3022         int                              rc;
3023         ENTRY;
3024
3025         rc = lfsck_layout_lock(env, com, parent, &lh,
3026                                MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR);
3027         if (rc != 0)
3028                 GOTO(log, rc);
3029
3030         handle = dt_trans_create(env, dev);
3031         if (IS_ERR(handle))
3032                 GOTO(unlock1, rc = PTR_ERR(handle));
3033
3034         pfid->ff_parent.f_seq = cpu_to_le64(tfid->f_seq);
3035         pfid->ff_parent.f_oid = cpu_to_le32(tfid->f_oid);
3036         /* Currently, the filter_fid::ff_parent::f_ver is not the real parent
3037          * MDT-object's FID::f_ver, instead it is the OST-object index in its
3038          * parent MDT-object's layout EA. */
3039         pfid->ff_parent.f_stripe_idx = cpu_to_le32(llr->llr_lov_idx);
3040         buf = lfsck_buf_get(env, pfid, sizeof(struct filter_fid));
3041
3042         rc = dt_declare_xattr_set(env, child, buf, XATTR_NAME_FID, 0, handle);
3043         if (rc != 0)
3044                 GOTO(stop, rc);
3045
3046         tla->la_valid = LA_UID | LA_GID;
3047         tla->la_uid = pla->la_uid;
3048         tla->la_gid = pla->la_gid;
3049         rc = dt_declare_attr_set(env, child, tla, handle);
3050         if (rc != 0)
3051                 GOTO(stop, rc);
3052
3053         rc = dt_trans_start(env, dev, handle);
3054         if (rc != 0)
3055                 GOTO(stop, rc);
3056
3057         dt_write_lock(env, parent, 0);
3058         if (unlikely(lu_object_is_dying(parent->do_lu.lo_header)))
3059                 GOTO(unlock2, rc = 1);
3060
3061         rc = dt_xattr_set(env, child, buf, XATTR_NAME_FID, 0, handle,
3062                           BYPASS_CAPA);
3063         if (rc != 0)
3064                 GOTO(unlock2, rc);
3065
3066         /* Get the latest parent's owner. */
3067         rc = dt_attr_get(env, parent, tla, BYPASS_CAPA);
3068         if (rc != 0)
3069                 GOTO(unlock2, rc);
3070
3071         tla->la_valid = LA_UID | LA_GID;
3072         rc = dt_attr_set(env, child, tla, handle, BYPASS_CAPA);
3073
3074         GOTO(unlock2, rc);
3075
3076 unlock2:
3077         dt_write_unlock(env, parent);
3078
3079 stop:
3080         rc = lfsck_layout_trans_stop(env, dev, handle, rc);
3081
3082 unlock1:
3083         lfsck_layout_unlock(&lh);
3084
3085 log:
3086         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant repaired unmatched "
3087                "MDT-OST pair for: parent "DFID", child "DFID", OST-index %u, "
3088                "stripe-index %u, owner %u/%u: rc = %d\n",
3089                lfsck_lfsck2name(com->lc_lfsck), PFID(lfsck_dto2fid(parent)),
3090                PFID(lfsck_dto2fid(child)), llr->llr_ost_idx, llr->llr_lov_idx,
3091                pla->la_uid, pla->la_gid, rc);
3092
3093         return rc;
3094 }
3095
3096 /* If there are more than one MDT-objects claim as the OST-object's parent,
3097  * and the OST-object only recognizes one of them, then we need to generate
3098  * new OST-object(s) with new fid(s) for the non-recognized MDT-object(s). */
3099 static int lfsck_layout_repair_multiple_references(const struct lu_env *env,
3100                                                    struct lfsck_component *com,
3101                                                    struct lfsck_layout_req *llr,
3102                                                    struct lu_attr *la,
3103                                                    struct lu_buf *buf)
3104 {
3105         struct lfsck_thread_info        *info   = lfsck_env_info(env);
3106         struct dt_allocation_hint       *hint   = &info->lti_hint;
3107         struct dt_object_format         *dof    = &info->lti_dof;
3108         struct dt_device                *pdev   = com->lc_lfsck->li_next;
3109         struct ost_id                   *oi     = &info->lti_oi;
3110         struct dt_object                *parent = llr->llr_parent->llo_obj;
3111         struct dt_device                *cdev   = lfsck_obj2dt_dev(llr->llr_child);
3112         struct dt_object                *child  = NULL;
3113         struct lu_device                *d      = &cdev->dd_lu_dev;
3114         struct lu_object                *o      = NULL;
3115         struct thandle                  *handle;
3116         struct lov_mds_md_v1            *lmm;
3117         struct lov_ost_data_v1          *objs;
3118         struct lustre_handle             lh     = { 0 };
3119         __u32                            magic;
3120         int                              rc;
3121         ENTRY;
3122
3123         rc = lfsck_layout_lock(env, com, parent, &lh,
3124                                MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR);
3125         if (rc != 0)
3126                 GOTO(log, rc);
3127
3128         handle = dt_trans_create(env, pdev);
3129         if (IS_ERR(handle))
3130                 GOTO(unlock1, rc = PTR_ERR(handle));
3131
3132         o = lu_object_anon(env, d, NULL);
3133         if (IS_ERR(o))
3134                 GOTO(stop, rc = PTR_ERR(o));
3135
3136         child = container_of(o, struct dt_object, do_lu);
3137         o = lu_object_locate(o->lo_header, d->ld_type);
3138         if (unlikely(o == NULL))
3139                 GOTO(stop, rc = -EINVAL);
3140
3141         child = container_of(o, struct dt_object, do_lu);
3142         la->la_valid = LA_UID | LA_GID;
3143         hint->dah_parent = NULL;
3144         hint->dah_mode = 0;
3145         dof->dof_type = DFT_REGULAR;
3146         rc = dt_declare_create(env, child, la, NULL, NULL, handle);
3147         if (rc != 0)
3148                 GOTO(stop, rc);
3149
3150         rc = dt_declare_xattr_set(env, parent, buf, XATTR_NAME_LOV,
3151                                   LU_XATTR_REPLACE, handle);
3152         if (rc != 0)
3153                 GOTO(stop, rc);
3154
3155         rc = dt_trans_start(env, pdev, handle);
3156         if (rc != 0)
3157                 GOTO(stop, rc);
3158
3159         dt_write_lock(env, parent, 0);
3160         if (unlikely(lu_object_is_dying(parent->do_lu.lo_header)))
3161                 GOTO(unlock2, rc = 0);
3162
3163         rc = dt_xattr_get(env, parent, buf, XATTR_NAME_LOV, BYPASS_CAPA);
3164         if (unlikely(rc == 0 || rc == -ENODATA || rc == -ERANGE))
3165                 GOTO(unlock2, rc = 0);
3166
3167         lmm = buf->lb_buf;
3168         /* Someone change layout during the LFSCK, no need to repair then. */
3169         if (le16_to_cpu(lmm->lmm_layout_gen) != llr->llr_parent->llo_gen)
3170                 GOTO(unlock2, rc = 0);
3171
3172         rc = dt_create(env, child, la, hint, dof, handle);
3173         if (rc != 0)
3174                 GOTO(unlock2, rc);
3175
3176         /* Currently, we only support LOV_MAGIC_V1/LOV_MAGIC_V3 which has
3177          * been verified in lfsck_layout_verify_header() already. If some
3178          * new magic introduced in the future, then layout LFSCK needs to
3179          * be updated also. */
3180         magic = le32_to_cpu(lmm->lmm_magic);
3181         if (magic == LOV_MAGIC_V1) {
3182                 objs = &lmm->lmm_objects[0];
3183         } else {
3184                 LASSERT(magic == LOV_MAGIC_V3);
3185                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[0];
3186         }
3187
3188         lmm->lmm_layout_gen = cpu_to_le16(llr->llr_parent->llo_gen + 1);
3189         fid_to_ostid(lu_object_fid(&child->do_lu), oi);
3190         ostid_cpu_to_le(oi, &objs[llr->llr_lov_idx].l_ost_oi);
3191         objs[llr->llr_lov_idx].l_ost_gen = cpu_to_le32(0);
3192         objs[llr->llr_lov_idx].l_ost_idx = cpu_to_le32(llr->llr_ost_idx);
3193         rc = dt_xattr_set(env, parent, buf, XATTR_NAME_LOV,
3194                           LU_XATTR_REPLACE, handle, BYPASS_CAPA);
3195
3196         GOTO(unlock2, rc = (rc == 0 ? 1 : rc));
3197
3198 unlock2:
3199         dt_write_unlock(env, parent);
3200
3201 stop:
3202         if (child != NULL)
3203                 lu_object_put(env, &child->do_lu);
3204
3205         dt_trans_stop(env, pdev, handle);
3206
3207 unlock1:
3208         lfsck_layout_unlock(&lh);
3209
3210 log:
3211         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant repaired multiple "
3212                "references for: parent "DFID", OST-index %u, stripe-index %u, "
3213                "owner %u/%u: rc = %d\n",
3214                lfsck_lfsck2name(com->lc_lfsck), PFID(lfsck_dto2fid(parent)),
3215                llr->llr_ost_idx, llr->llr_lov_idx, la->la_uid, la->la_gid, rc);
3216
3217         return rc;
3218 }
3219
3220 /* If the MDT-object and the OST-object have different owner information,
3221  * then trust the MDT-object, because the normal chown/chgrp handle order
3222  * is from MDT to OST, and it is possible that some chown/chgrp operation
3223  * is partly done. */
3224 static int lfsck_layout_repair_owner(const struct lu_env *env,
3225                                      struct lfsck_component *com,
3226                                      struct lfsck_layout_req *llr,
3227                                      struct lu_attr *pla)
3228 {
3229         struct lfsck_thread_info        *info   = lfsck_env_info(env);
3230         struct lu_attr                  *tla    = &info->lti_la3;
3231         struct dt_object                *parent = llr->llr_parent->llo_obj;
3232         struct dt_object                *child  = llr->llr_child;
3233         struct dt_device                *dev    = lfsck_obj2dt_dev(child);
3234         struct thandle                  *handle;
3235         int                              rc;
3236         ENTRY;
3237
3238         handle = dt_trans_create(env, dev);
3239         if (IS_ERR(handle))
3240                 GOTO(log, rc = PTR_ERR(handle));
3241
3242         tla->la_uid = pla->la_uid;
3243         tla->la_gid = pla->la_gid;
3244         tla->la_valid = LA_UID | LA_GID;
3245         rc = dt_declare_attr_set(env, child, tla, handle);
3246         if (rc != 0)
3247                 GOTO(stop, rc);
3248
3249         rc = dt_trans_start(env, dev, handle);
3250         if (rc != 0)
3251                 GOTO(stop, rc);
3252
3253         /* Use the dt_object lock to serialize with destroy and attr_set. */
3254         dt_read_lock(env, parent, 0);
3255         if (unlikely(lu_object_is_dying(parent->do_lu.lo_header)))
3256                 GOTO(unlock, rc = 1);
3257
3258         /* Get the latest parent's owner. */
3259         rc = dt_attr_get(env, parent, tla, BYPASS_CAPA);
3260         if (rc != 0)
3261                 GOTO(unlock, rc);
3262
3263         /* Some others chown/chgrp during the LFSCK, needs to do nothing. */
3264         if (unlikely(tla->la_uid != pla->la_uid ||
3265                      tla->la_gid != pla->la_gid))
3266                 GOTO(unlock, rc = 1);
3267
3268         tla->la_valid = LA_UID | LA_GID;
3269         rc = dt_attr_set(env, child, tla, handle, BYPASS_CAPA);
3270
3271         GOTO(unlock, rc);
3272
3273 unlock:
3274         dt_read_unlock(env, parent);
3275
3276 stop:
3277         rc = lfsck_layout_trans_stop(env, dev, handle, rc);
3278
3279 log:
3280         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant repaired inconsistent "
3281                "file owner for: parent "DFID", child "DFID", OST-index %u, "
3282                "stripe-index %u, owner %u/%u: rc = %d\n",
3283                lfsck_lfsck2name(com->lc_lfsck), PFID(lfsck_dto2fid(parent)),
3284                PFID(lfsck_dto2fid(child)), llr->llr_ost_idx, llr->llr_lov_idx,
3285                pla->la_uid, pla->la_gid, rc);
3286
3287         return rc;
3288 }
3289
3290 /* Check whether the OST-object correctly back points to the
3291  * MDT-object (@parent) via the XATTR_NAME_FID xattr (@pfid). */
3292 static int lfsck_layout_check_parent(const struct lu_env *env,
3293                                      struct lfsck_component *com,
3294                                      struct dt_object *parent,
3295                                      const struct lu_fid *pfid,
3296                                      const struct lu_fid *cfid,
3297                                      const struct lu_attr *pla,
3298                                      const struct lu_attr *cla,
3299                                      struct lfsck_layout_req *llr,
3300                                      struct lu_buf *lov_ea, __u32 idx)
3301 {
3302         struct lfsck_thread_info        *info   = lfsck_env_info(env);
3303         struct lu_buf                   *buf    = &info->lti_big_buf;
3304         struct dt_object                *tobj;
3305         struct lov_mds_md_v1            *lmm;
3306         struct lov_ost_data_v1          *objs;
3307         int                              rc;
3308         int                              i;
3309         __u32                            magic;
3310         __u16                            count;
3311         ENTRY;
3312
3313         if (fid_is_zero(pfid)) {
3314                 /* client never wrote. */
3315                 if (cla->la_size == 0 && cla->la_blocks == 0) {
3316                         if (unlikely(cla->la_uid != pla->la_uid ||
3317                                      cla->la_gid != pla->la_gid))
3318                                 RETURN (LLIT_INCONSISTENT_OWNER);
3319
3320                         RETURN(0);
3321                 }
3322
3323                 RETURN(LLIT_UNMATCHED_PAIR);
3324         }
3325
3326         if (unlikely(!fid_is_sane(pfid)))
3327                 RETURN(LLIT_UNMATCHED_PAIR);
3328
3329         if (lu_fid_eq(pfid, lu_object_fid(&parent->do_lu))) {
3330                 if (llr->llr_lov_idx == idx)
3331                         RETURN(0);
3332
3333                 RETURN(LLIT_UNMATCHED_PAIR);
3334         }
3335
3336         tobj = lfsck_object_find(env, com->lc_lfsck, pfid);
3337         if (tobj == NULL)
3338                 RETURN(LLIT_UNMATCHED_PAIR);
3339
3340         if (IS_ERR(tobj))
3341                 RETURN(PTR_ERR(tobj));
3342
3343         if (!dt_object_exists(tobj))
3344                 GOTO(out, rc = LLIT_UNMATCHED_PAIR);
3345
3346         /* Load the tobj's layout EA, in spite of it is a local MDT-object or
3347          * remote one on another MDT. Then check whether the given OST-object
3348          * is in such layout. If yes, it is multiple referenced, otherwise it
3349          * is unmatched referenced case. */
3350         rc = lfsck_layout_get_lovea(env, tobj, buf, NULL);
3351         if (rc == 0)
3352                 GOTO(out, rc = LLIT_UNMATCHED_PAIR);
3353
3354         if (rc < 0)
3355                 GOTO(out, rc);
3356
3357         lmm = buf->lb_buf;
3358         magic = le32_to_cpu(lmm->lmm_magic);
3359         if (magic == LOV_MAGIC_V1) {
3360                 objs = &lmm->lmm_objects[0];
3361         } else {
3362                 LASSERT(magic == LOV_MAGIC_V3);
3363                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[0];
3364         }
3365
3366         count = le16_to_cpu(lmm->lmm_stripe_count);
3367         for (i = 0; i < count; i++, objs++) {
3368                 struct lu_fid           *tfid   = &info->lti_fid2;
3369                 struct ost_id           *oi     = &info->lti_oi;
3370
3371                 if (lovea_slot_is_dummy(objs))
3372                         continue;
3373
3374                 ostid_le_to_cpu(&objs->l_ost_oi, oi);
3375                 ostid_to_fid(tfid, oi, le32_to_cpu(objs->l_ost_idx));
3376                 if (lu_fid_eq(cfid, tfid)) {
3377                         *lov_ea = *buf;
3378
3379                         GOTO(out, rc = LLIT_MULTIPLE_REFERENCED);
3380                 }
3381         }
3382
3383         GOTO(out, rc = LLIT_UNMATCHED_PAIR);
3384
3385 out:
3386         lfsck_object_put(env, tobj);
3387
3388         return rc;
3389 }
3390
3391 static int lfsck_layout_assistant_handle_one(const struct lu_env *env,
3392                                              struct lfsck_component *com,
3393                                              struct lfsck_layout_req *llr)
3394 {
3395         struct lfsck_layout                  *lo     = com->lc_file_ram;
3396         struct lfsck_thread_info             *info   = lfsck_env_info(env);
3397         struct filter_fid_old                *pea    = &info->lti_old_pfid;
3398         struct lu_fid                        *pfid   = &info->lti_fid;
3399         struct lu_buf                        *buf    = NULL;
3400         struct dt_object                     *parent = llr->llr_parent->llo_obj;
3401         struct dt_object                     *child  = llr->llr_child;
3402         struct lu_attr                       *pla    = &info->lti_la;
3403         struct lu_attr                       *cla    = &info->lti_la2;
3404         struct lfsck_instance                *lfsck  = com->lc_lfsck;
3405         struct lfsck_bookmark                *bk     = &lfsck->li_bookmark_ram;
3406         enum lfsck_layout_inconsistency_type  type   = LLIT_NONE;
3407         __u32                                 idx    = 0;
3408         int                                   rc;
3409         ENTRY;
3410
3411         rc = dt_attr_get(env, parent, pla, BYPASS_CAPA);
3412         if (rc != 0) {
3413                 if (lu_object_is_dying(parent->do_lu.lo_header))
3414                         RETURN(0);
3415
3416                 GOTO(out, rc);
3417         }
3418
3419         rc = dt_attr_get(env, child, cla, BYPASS_CAPA);
3420         if (rc == -ENOENT) {
3421                 if (lu_object_is_dying(parent->do_lu.lo_header))
3422                         RETURN(0);
3423
3424                 type = LLIT_DANGLING;
3425                 goto repair;
3426         }
3427
3428         if (rc != 0)
3429                 GOTO(out, rc);
3430
3431         buf = lfsck_buf_get(env, pea, sizeof(struct filter_fid_old));
3432         rc= dt_xattr_get(env, child, buf, XATTR_NAME_FID, BYPASS_CAPA);
3433         if (unlikely(rc >= 0 && rc != sizeof(struct filter_fid_old) &&
3434                      rc != sizeof(struct filter_fid))) {
3435                 type = LLIT_UNMATCHED_PAIR;
3436                 goto repair;
3437         }
3438
3439         if (rc < 0 && rc != -ENODATA)
3440                 GOTO(out, rc);
3441
3442         if (rc == -ENODATA) {
3443                 fid_zero(pfid);
3444         } else {
3445                 fid_le_to_cpu(pfid, &pea->ff_parent);
3446                 /* Currently, the filter_fid::ff_parent::f_ver is not the
3447                  * real parent MDT-object's FID::f_ver, instead it is the
3448                  * OST-object index in its parent MDT-object's layout EA. */
3449                 idx = pfid->f_stripe_idx;
3450                 pfid->f_ver = 0;
3451         }
3452
3453         rc = lfsck_layout_check_parent(env, com, parent, pfid,
3454                                        lu_object_fid(&child->do_lu),
3455                                        pla, cla, llr, buf, idx);
3456         if (rc > 0) {
3457                 type = rc;
3458                 goto repair;
3459         }
3460
3461         if (rc < 0)
3462                 GOTO(out, rc);
3463
3464         if (unlikely(cla->la_uid != pla->la_uid ||
3465                      cla->la_gid != pla->la_gid)) {
3466                 type = LLIT_INCONSISTENT_OWNER;
3467                 goto repair;
3468         }
3469
3470 repair:
3471         if (bk->lb_param & LPF_DRYRUN) {
3472                 if (type != LLIT_NONE)
3473                         GOTO(out, rc = 1);
3474                 else
3475                         GOTO(out, rc = 0);
3476         }
3477
3478         switch (type) {
3479         case LLIT_DANGLING:
3480                 rc = lfsck_layout_repair_dangling(env, com, llr, pla);
3481                 break;
3482         case LLIT_UNMATCHED_PAIR:
3483                 rc = lfsck_layout_repair_unmatched_pair(env, com, llr, pla);
3484                 break;
3485         case LLIT_MULTIPLE_REFERENCED:
3486                 rc = lfsck_layout_repair_multiple_references(env, com, llr,
3487                                                              pla, buf);
3488                 break;
3489         case LLIT_INCONSISTENT_OWNER:
3490                 rc = lfsck_layout_repair_owner(env, com, llr, pla);
3491                 break;
3492         default:
3493                 rc = 0;
3494                 break;
3495         }
3496
3497         GOTO(out, rc);
3498
3499 out:
3500         down_write(&com->lc_sem);
3501         if (rc < 0) {
3502                 struct lfsck_layout_master_data *llmd = com->lc_data;
3503
3504                 if (unlikely(llmd->llmd_exit)) {
3505                         rc = 0;
3506                 } else if (rc == -ENOTCONN || rc == -ESHUTDOWN ||
3507                            rc == -ETIMEDOUT || rc == -EHOSTDOWN ||
3508                            rc == -EHOSTUNREACH) {
3509                         /* If cannot touch the target server,
3510                          * mark the LFSCK as INCOMPLETE. */
3511                         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant fail to "
3512                                "talk with OST %x: rc = %d\n",
3513                                lfsck_lfsck2name(lfsck), llr->llr_ost_idx, rc);
3514                         lo->ll_flags |= LF_INCOMPLETE;
3515                         lo->ll_objs_skipped++;
3516                         rc = 0;
3517                 } else {
3518                         lfsck_layout_record_failure(env, lfsck, lo);
3519                 }
3520         } else if (rc > 0) {
3521                 LASSERTF(type > LLIT_NONE && type <= LLIT_MAX,
3522                          "unknown type = %d\n", type);
3523
3524                 lo->ll_objs_repaired[type - 1]++;
3525                 if (bk->lb_param & LPF_DRYRUN &&
3526                     unlikely(lo->ll_pos_first_inconsistent == 0))
3527                         lo->ll_pos_first_inconsistent =
3528                         lfsck->li_obj_oit->do_index_ops->dio_it.store(env,
3529                                                         lfsck->li_di_oit);
3530         }
3531         up_write(&com->lc_sem);
3532
3533         return rc;
3534 }
3535
3536 static int lfsck_layout_assistant(void *args)
3537 {
3538         struct lfsck_thread_args        *lta     = args;
3539         struct lu_env                   *env     = &lta->lta_env;
3540         struct lfsck_component          *com     = lta->lta_com;
3541         struct lfsck_instance           *lfsck   = lta->lta_lfsck;
3542         struct lfsck_bookmark           *bk      = &lfsck->li_bookmark_ram;
3543         struct lfsck_position           *pos     = &com->lc_pos_start;
3544         struct lfsck_thread_info        *info    = lfsck_env_info(env);
3545         struct lfsck_request            *lr      = &info->lti_lr;
3546         struct lfsck_layout_master_data *llmd    = com->lc_data;
3547         struct ptlrpc_thread            *mthread = &lfsck->li_thread;
3548         struct ptlrpc_thread            *athread = &llmd->llmd_thread;
3549         struct lfsck_layout_req         *llr;
3550         struct l_wait_info               lwi     = { 0 };
3551         int                              rc      = 0;
3552         int                              rc1     = 0;
3553         ENTRY;
3554
3555         memset(lr, 0, sizeof(*lr));
3556         lr->lr_event = LE_START;
3557         lr->lr_valid = LSV_SPEED_LIMIT | LSV_ERROR_HANDLE | LSV_DRYRUN |
3558                        LSV_ASYNC_WINDOWS | LSV_CREATE_OSTOBJ;
3559         lr->lr_speed = bk->lb_speed_limit;
3560         lr->lr_version = bk->lb_version;
3561         lr->lr_param = bk->lb_param;
3562         lr->lr_async_windows = bk->lb_async_windows;
3563         lr->lr_flags = LEF_TO_OST;
3564         if (pos->lp_oit_cookie <= 1)
3565                 lr->lr_param |= LPF_RESET;
3566
3567         rc = lfsck_layout_master_notify_others(env, com, lr);
3568         if (rc != 0) {
3569                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant failed to notify "
3570                        "others for LFSCK start: rc = %d\n",
3571                        lfsck_lfsck2name(lfsck), rc);
3572                 GOTO(fini, rc);
3573         }
3574
3575         spin_lock(&llmd->llmd_lock);
3576         thread_set_flags(athread, SVC_RUNNING);
3577         spin_unlock(&llmd->llmd_lock);
3578         wake_up_all(&mthread->t_ctl_waitq);
3579
3580         while (1) {
3581                 while (!list_empty(&llmd->llmd_req_list)) {
3582                         bool wakeup = false;
3583
3584                         if (unlikely(llmd->llmd_exit ||
3585                                      !thread_is_running(mthread)))
3586                                 GOTO(cleanup1, rc = llmd->llmd_post_result);
3587
3588                         llr = list_entry(llmd->llmd_req_list.next,
3589                                          struct lfsck_layout_req,
3590                                          llr_list);
3591                         /* Only the lfsck_layout_assistant thread itself can
3592                          * remove the "llr" from the head of the list, LFSCK
3593                          * engine thread only inserts other new "lld" at the
3594                          * end of the list. So it is safe to handle current
3595                          * "llr" without the spin_lock. */
3596                         rc = lfsck_layout_assistant_handle_one(env, com, llr);
3597                         spin_lock(&llmd->llmd_lock);
3598                         list_del_init(&llr->llr_list);
3599                         llmd->llmd_prefetched--;
3600                         /* Wake up the main engine thread only when the list
3601                          * is empty or half of the prefetched items have been
3602                          * handled to avoid too frequent thread schedule. */
3603                         if (llmd->llmd_prefetched == 0 ||
3604                             (bk->lb_async_windows != 0 &&
3605                              bk->lb_async_windows / 2 ==
3606                              llmd->llmd_prefetched))
3607                                 wakeup = true;
3608                         spin_unlock(&llmd->llmd_lock);
3609                         if (wakeup)
3610                                 wake_up_all(&mthread->t_ctl_waitq);
3611
3612                         lfsck_layout_req_fini(env, llr);
3613                         if (rc < 0 && bk->lb_param & LPF_FAILOUT)
3614                                 GOTO(cleanup1, rc);
3615                 }
3616
3617                 l_wait_event(athread->t_ctl_waitq,
3618                              !lfsck_layout_req_empty(llmd) ||
3619                              llmd->llmd_exit ||
3620                              llmd->llmd_to_post ||
3621                              llmd->llmd_to_double_scan,
3622                              &lwi);
3623
3624                 if (unlikely(llmd->llmd_exit))
3625                         GOTO(cleanup1, rc = llmd->llmd_post_result);
3626
3627                 if (!list_empty(&llmd->llmd_req_list))
3628                         continue;
3629
3630                 if (llmd->llmd_to_post) {
3631                         llmd->llmd_to_post = 0;
3632                         LASSERT(llmd->llmd_post_result > 0);
3633
3634                         memset(lr, 0, sizeof(*lr));
3635                         lr->lr_event = LE_PHASE1_DONE;
3636                         lr->lr_status = llmd->llmd_post_result;
3637                         rc = lfsck_layout_master_notify_others(env, com, lr);
3638                         if (rc != 0)
3639                                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant "
3640                                        "failed to notify others for LFSCK "
3641                                        "post: rc = %d\n",
3642                                        lfsck_lfsck2name(lfsck), rc);
3643
3644                         /* Wakeup the master engine to go ahead. */
3645                         wake_up_all(&mthread->t_ctl_waitq);
3646                 }
3647
3648                 if (llmd->llmd_to_double_scan) {
3649                         llmd->llmd_to_double_scan = 0;
3650                         atomic_inc(&lfsck->li_double_scan_count);
3651                         llmd->llmd_in_double_scan = 1;
3652                         wake_up_all(&mthread->t_ctl_waitq);
3653
3654                         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant phase2 "
3655                                "scan start\n", lfsck_lfsck2name(lfsck));
3656
3657                         com->lc_new_checked = 0;
3658                         com->lc_new_scanned = 0;
3659                         com->lc_time_last_checkpoint = cfs_time_current();
3660                         com->lc_time_next_checkpoint =
3661                                 com->lc_time_last_checkpoint +
3662                                 cfs_time_seconds(LFSCK_CHECKPOINT_INTERVAL);
3663
3664                         /* flush all async updating before handling orphan. */
3665                         dt_sync(env, lfsck->li_next);
3666
3667                         while (llmd->llmd_in_double_scan) {
3668                                 struct lfsck_tgt_descs  *ltds =
3669                                                         &lfsck->li_ost_descs;
3670                                 struct lfsck_tgt_desc   *ltd;
3671
3672                                 rc = lfsck_layout_master_query_others(env, com);
3673                                 if (lfsck_layout_master_to_orphan(llmd))
3674                                         goto orphan;
3675
3676                                 if (rc < 0)
3677                                         GOTO(cleanup2, rc);
3678
3679                                 /* Pull LFSCK status on related targets once
3680                                  * per 30 seconds if we are not notified. */
3681                                 lwi = LWI_TIMEOUT_INTERVAL(cfs_time_seconds(30),
3682                                                            cfs_time_seconds(1),
3683                                                            NULL, NULL);
3684                                 rc = l_wait_event(athread->t_ctl_waitq,
3685                                         lfsck_layout_master_to_orphan(llmd) ||
3686                                         llmd->llmd_exit ||
3687                                         !thread_is_running(mthread),
3688                                         &lwi);
3689
3690                                 if (unlikely(llmd->llmd_exit ||
3691                                              !thread_is_running(mthread)))
3692                                         GOTO(cleanup2, rc = 0);
3693
3694                                 if (rc == -ETIMEDOUT)
3695                                         continue;
3696
3697                                 if (rc < 0)
3698                                         GOTO(cleanup2, rc);
3699
3700 orphan:
3701                                 spin_lock(&ltds->ltd_lock);
3702                                 while (!list_empty(
3703                                                 &llmd->llmd_ost_phase2_list)) {
3704                                         ltd = list_entry(
3705                                               llmd->llmd_ost_phase2_list.next,
3706                                               struct lfsck_tgt_desc,
3707                                               ltd_layout_phase_list);
3708                                         list_del_init(
3709                                                 &ltd->ltd_layout_phase_list);
3710                                         spin_unlock(&ltds->ltd_lock);
3711
3712                                         if (bk->lb_param & LPF_ALL_TGT) {
3713                                                 rc = lfsck_layout_scan_orphan(
3714                                                                 env, com, ltd);
3715                                                 if (rc != 0 &&
3716                                                     bk->lb_param & LPF_FAILOUT)
3717                                                         GOTO(cleanup2, rc);
3718                                         }
3719
3720                                         if (unlikely(llmd->llmd_exit ||
3721                                                 !thread_is_running(mthread)))
3722                                                 GOTO(cleanup2, rc = 0);
3723
3724                                         spin_lock(&ltds->ltd_lock);
3725                                 }
3726
3727                                 if (list_empty(&llmd->llmd_ost_phase1_list)) {
3728                                         spin_unlock(&ltds->ltd_lock);
3729                                         GOTO(cleanup2, rc = 1);
3730                                 }
3731                                 spin_unlock(&ltds->ltd_lock);
3732                         }
3733                 }
3734         }
3735
3736 cleanup1:
3737         /* Cleanup the unfinished requests. */
3738         spin_lock(&llmd->llmd_lock);
3739         if (rc < 0)
3740                 llmd->llmd_assistant_status = rc;
3741
3742         while (!list_empty(&llmd->llmd_req_list)) {
3743                 llr = list_entry(llmd->llmd_req_list.next,
3744                                  struct lfsck_layout_req,
3745                                  llr_list);
3746                 list_del_init(&llr->llr_list);
3747                 llmd->llmd_prefetched--;
3748                 spin_unlock(&llmd->llmd_lock);
3749                 lfsck_layout_req_fini(env, llr);
3750                 spin_lock(&llmd->llmd_lock);
3751         }
3752         spin_unlock(&llmd->llmd_lock);
3753
3754         LASSERTF(llmd->llmd_prefetched == 0, "unmatched prefeteched objs %d\n",
3755                  llmd->llmd_prefetched);
3756
3757 cleanup2:
3758         memset(lr, 0, sizeof(*lr));
3759         if (rc > 0) {
3760                 lr->lr_event = LE_PHASE2_DONE;
3761                 lr->lr_status = rc;
3762         } else if (rc == 0) {
3763                 if (lfsck->li_flags & LPF_ALL_TGT) {
3764                         lr->lr_event = LE_STOP;
3765                         lr->lr_status = LS_STOPPED;
3766                 } else {
3767                         lr->lr_event = LE_PEER_EXIT;
3768                         switch (lfsck->li_status) {
3769                         case LS_PAUSED:
3770                         case LS_CO_PAUSED:
3771                                 lr->lr_status = LS_CO_PAUSED;
3772                                 break;
3773                         case LS_STOPPED:
3774                         case LS_CO_STOPPED:
3775                                 lr->lr_status = LS_CO_STOPPED;
3776                                 break;
3777                         default:
3778                                 CDEBUG(D_LFSCK, "%s: unknown status: rc = %d\n",
3779                                        lfsck_lfsck2name(lfsck),
3780                                        lfsck->li_status);
3781                                 lr->lr_status = LS_CO_FAILED;
3782                                 break;
3783                         }
3784                 }
3785         } else {
3786                 if (lfsck->li_flags & LPF_ALL_TGT) {
3787                         lr->lr_event = LE_STOP;
3788                         lr->lr_status = LS_FAILED;
3789                 } else {
3790                         lr->lr_event = LE_PEER_EXIT;
3791                         lr->lr_status = LS_CO_FAILED;
3792                 }
3793         }
3794
3795         rc1 = lfsck_layout_master_notify_others(env, com, lr);
3796         if (rc1 != 0) {
3797                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant failed to "
3798                        "notify others for LFSCK quit: rc = %d\n",
3799                        lfsck_lfsck2name(lfsck), rc1);
3800                 rc = rc1;
3801         }
3802
3803         /* Under force exit case, some requests may be just freed without
3804          * verification, those objects should be re-handled when next run.
3805          * So not update the on-disk tracing file under such case. */
3806         if (llmd->llmd_in_double_scan) {
3807                 struct lfsck_layout *lo = com->lc_file_ram;
3808
3809                 if (!llmd->llmd_exit)
3810                         rc1 = lfsck_layout_double_scan_result(env, com, rc);
3811
3812                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant phase2 scan "
3813                        "finished, status %d: rc = %d\n",
3814                        lfsck_lfsck2name(lfsck), lo->ll_status, rc1);
3815         }
3816
3817 fini:
3818         if (llmd->llmd_in_double_scan)
3819                 atomic_dec(&lfsck->li_double_scan_count);
3820
3821         spin_lock(&llmd->llmd_lock);
3822         llmd->llmd_assistant_status = (rc1 != 0 ? rc1 : rc);
3823         thread_set_flags(athread, SVC_STOPPED);
3824         wake_up_all(&mthread->t_ctl_waitq);
3825         spin_unlock(&llmd->llmd_lock);
3826         lfsck_thread_args_fini(lta);
3827
3828         return rc;
3829 }
3830
3831 static int
3832 lfsck_layout_slave_async_interpret(const struct lu_env *env,
3833                                    struct ptlrpc_request *req,
3834                                    void *args, int rc)
3835 {
3836         struct lfsck_layout_slave_async_args *llsaa = args;
3837         struct obd_export                    *exp   = llsaa->llsaa_exp;
3838         struct lfsck_component               *com   = llsaa->llsaa_com;
3839         struct lfsck_layout_slave_target     *llst  = llsaa->llsaa_llst;
3840         struct lfsck_layout_slave_data       *llsd  = com->lc_data;
3841         struct lfsck_reply                   *lr    = NULL;
3842         bool                                  done  = false;
3843
3844         if (rc != 0) {
3845                 /* It is quite probably caused by target crash,
3846                  * to make the LFSCK can go ahead, assume that
3847                  * the target finished the LFSCK prcoessing. */
3848                 done = true;
3849         } else {
3850                 lr = req_capsule_server_get(&req->rq_pill, &RMF_LFSCK_REPLY);
3851                 if (lr->lr_status != LS_SCANNING_PHASE1 &&
3852                     lr->lr_status != LS_SCANNING_PHASE2)
3853                         done = true;
3854         }
3855
3856         if (done) {
3857                 CDEBUG(D_LFSCK, "%s: layout LFSCK slave gets the MDT %x "
3858                        "status %d\n", lfsck_lfsck2name(com->lc_lfsck),
3859                        llst->llst_index, lr != NULL ? lr->lr_status : rc);
3860
3861                 lfsck_layout_llst_del(llsd, llst);
3862         }
3863
3864         lfsck_layout_llst_put(llst);
3865         lfsck_component_put(env, com);
3866         class_export_put(exp);
3867
3868         return 0;
3869 }
3870
3871 static int lfsck_layout_async_query(const struct lu_env *env,
3872                                     struct lfsck_component *com,
3873                                     struct obd_export *exp,
3874                                     struct lfsck_layout_slave_target *llst,
3875                                     struct lfsck_request *lr,
3876                                     struct ptlrpc_request_set *set)
3877 {
3878         struct lfsck_layout_slave_async_args *llsaa;
3879         struct ptlrpc_request                *req;
3880         struct lfsck_request                 *tmp;
3881         int                                   rc;
3882         ENTRY;
3883
3884         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_LFSCK_QUERY);
3885         if (req == NULL)
3886                 RETURN(-ENOMEM);
3887
3888         rc = ptlrpc_request_pack(req, LUSTRE_OBD_VERSION, LFSCK_QUERY);
3889         if (rc != 0) {
3890                 ptlrpc_request_free(req);
3891                 RETURN(rc);
3892         }
3893
3894         tmp = req_capsule_client_get(&req->rq_pill, &RMF_LFSCK_REQUEST);
3895         *tmp = *lr;
3896         ptlrpc_request_set_replen(req);
3897
3898         llsaa = ptlrpc_req_async_args(req);
3899         llsaa->llsaa_exp = exp;
3900         llsaa->llsaa_com = lfsck_component_get(com);
3901         llsaa->llsaa_llst = llst;
3902         req->rq_interpret_reply = lfsck_layout_slave_async_interpret;
3903         ptlrpc_set_add_req(set, req);
3904
3905         RETURN(0);
3906 }
3907
3908 static int lfsck_layout_async_notify(const struct lu_env *env,
3909                                      struct obd_export *exp,
3910                                      struct lfsck_request *lr,
3911                                      struct ptlrpc_request_set *set)
3912 {
3913         struct ptlrpc_request   *req;
3914         struct lfsck_request    *tmp;
3915         int                      rc;
3916         ENTRY;
3917
3918         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_LFSCK_NOTIFY);
3919         if (req == NULL)
3920                 RETURN(-ENOMEM);
3921
3922         rc = ptlrpc_request_pack(req, LUSTRE_OBD_VERSION, LFSCK_NOTIFY);
3923         if (rc != 0) {
3924                 ptlrpc_request_free(req);
3925                 RETURN(rc);
3926         }
3927
3928         tmp = req_capsule_client_get(&req->rq_pill, &RMF_LFSCK_REQUEST);
3929         *tmp = *lr;
3930         ptlrpc_request_set_replen(req);
3931         ptlrpc_set_add_req(set, req);
3932
3933         RETURN(0);
3934 }
3935
3936 static int
3937 lfsck_layout_slave_query_master(const struct lu_env *env,
3938                                 struct lfsck_component *com)
3939 {
3940         struct lfsck_request             *lr    = &lfsck_env_info(env)->lti_lr;
3941         struct lfsck_instance            *lfsck = com->lc_lfsck;
3942         struct lfsck_layout_slave_data   *llsd  = com->lc_data;
3943         struct lfsck_layout_slave_target *llst;
3944         struct obd_export                *exp;
3945         struct ptlrpc_request_set        *set;
3946         int                               rc    = 0;
3947         int                               rc1   = 0;
3948         ENTRY;
3949
3950         set = ptlrpc_prep_set();
3951         if (set == NULL)
3952                 GOTO(log, rc = -ENOMEM);
3953
3954         memset(lr, 0, sizeof(*lr));
3955         lr->lr_index = lfsck_dev_idx(lfsck->li_bottom);
3956         lr->lr_event = LE_QUERY;
3957         lr->lr_active = LFSCK_TYPE_LAYOUT;
3958
3959         llsd->llsd_touch_gen++;
3960         spin_lock(&llsd->llsd_lock);
3961         while (!list_empty(&llsd->llsd_master_list)) {
3962                 llst = list_entry(llsd->llsd_master_list.next,
3963                                   struct lfsck_layout_slave_target,
3964                                   llst_list);
3965                 if (llst->llst_gen == llsd->llsd_touch_gen)
3966                         break;
3967
3968                 llst->llst_gen = llsd->llsd_touch_gen;
3969                 list_del(&llst->llst_list);
3970                 list_add_tail(&llst->llst_list,
3971                               &llsd->llsd_master_list);
3972                 atomic_inc(&llst->llst_ref);
3973                 spin_unlock(&llsd->llsd_lock);
3974
3975                 exp = lustre_find_lwp_by_index(lfsck->li_obd->obd_name,
3976                                                llst->llst_index);
3977                 if (exp == NULL) {
3978                         lfsck_layout_llst_del(llsd, llst);
3979                         lfsck_layout_llst_put(llst);
3980                         spin_lock(&llsd->llsd_lock);
3981                         continue;
3982                 }
3983
3984                 rc = lfsck_layout_async_query(env, com, exp, llst, lr, set);
3985                 if (rc != 0) {
3986                         CDEBUG(D_LFSCK, "%s: layout LFSCK slave fail to "
3987                                "query %s for layout: rc = %d\n",
3988                                lfsck_lfsck2name(lfsck),
3989                                exp->exp_obd->obd_name, rc);
3990
3991                         rc1 = rc;
3992                         lfsck_layout_llst_put(llst);
3993                         class_export_put(exp);
3994                 }
3995                 spin_lock(&llsd->llsd_lock);
3996         }
3997         spin_unlock(&llsd->llsd_lock);
3998
3999         rc = ptlrpc_set_wait(set);
4000         ptlrpc_set_destroy(set);
4001
4002         GOTO(log, rc = (rc1 != 0 ? rc1 : rc));
4003
4004 log:
4005         CDEBUG(D_LFSCK, "%s: layout LFSCK slave queries master: rc = %d\n",
4006                lfsck_lfsck2name(com->lc_lfsck), rc);
4007
4008         return rc;
4009 }
4010
4011 static void
4012 lfsck_layout_slave_notify_master(const struct lu_env *env,
4013                                  struct lfsck_component *com,
4014                                  enum lfsck_events event, int result)
4015 {
4016         struct lfsck_instance            *lfsck = com->lc_lfsck;
4017         struct lfsck_layout_slave_data   *llsd  = com->lc_data;
4018         struct lfsck_request             *lr    = &lfsck_env_info(env)->lti_lr;
4019         struct lfsck_layout_slave_target *llst;
4020         struct obd_export                *exp;
4021         struct ptlrpc_request_set        *set;
4022         int                               rc;
4023         ENTRY;
4024
4025         CDEBUG(D_LFSCK, "%s: layout LFSCK slave notifies master\n",
4026                lfsck_lfsck2name(com->lc_lfsck));
4027
4028         set = ptlrpc_prep_set();
4029         if (set == NULL)
4030                 RETURN_EXIT;
4031
4032         memset(lr, 0, sizeof(*lr));
4033         lr->lr_event = event;
4034         lr->lr_flags = LEF_FROM_OST;
4035         lr->lr_status = result;
4036         lr->lr_index = lfsck_dev_idx(lfsck->li_bottom);
4037         lr->lr_active = LFSCK_TYPE_LAYOUT;
4038         llsd->llsd_touch_gen++;
4039         spin_lock(&llsd->llsd_lock);
4040         while (!list_empty(&llsd->llsd_master_list)) {
4041                 llst = list_entry(llsd->llsd_master_list.next,
4042                                   struct lfsck_layout_slave_target,
4043                                   llst_list);
4044                 if (llst->llst_gen == llsd->llsd_touch_gen)
4045                         break;
4046
4047                 llst->llst_gen = llsd->llsd_touch_gen;
4048                 list_del(&llst->llst_list);
4049                 list_add_tail(&llst->llst_list,
4050                               &llsd->llsd_master_list);
4051                 atomic_inc(&llst->llst_ref);
4052                 spin_unlock(&llsd->llsd_lock);
4053
4054                 exp = lustre_find_lwp_by_index(lfsck->li_obd->obd_name,
4055                                                llst->llst_index);
4056                 if (exp == NULL) {
4057                         lfsck_layout_llst_del(llsd, llst);
4058                         lfsck_layout_llst_put(llst);
4059                         spin_lock(&llsd->llsd_lock);
4060                         continue;
4061                 }
4062
4063                 rc = lfsck_layout_async_notify(env, exp, lr, set);
4064                 if (rc != 0)
4065                         CDEBUG(D_LFSCK, "%s: layout LFSCK slave fail to "
4066                                "notify %s for layout: rc = %d\n",
4067                                lfsck_lfsck2name(lfsck),
4068                                exp->exp_obd->obd_name, rc);
4069
4070                 lfsck_layout_llst_put(llst);
4071                 class_export_put(exp);
4072                 spin_lock(&llsd->llsd_lock);
4073         }
4074         spin_unlock(&llsd->llsd_lock);
4075
4076         ptlrpc_set_wait(set);
4077         ptlrpc_set_destroy(set);
4078
4079         RETURN_EXIT;
4080 }
4081
4082 /*
4083  * \ret -ENODATA: unrecognized stripe
4084  * \ret = 0     : recognized stripe
4085  * \ret < 0     : other failures
4086  */
4087 static int lfsck_layout_master_check_pairs(const struct lu_env *env,
4088                                            struct lfsck_component *com,
4089                                            struct lu_fid *cfid,
4090                                            struct lu_fid *pfid)
4091 {
4092         struct lfsck_thread_info        *info   = lfsck_env_info(env);
4093         struct lu_buf                   *buf    = &info->lti_big_buf;
4094         struct ost_id                   *oi     = &info->lti_oi;
4095         struct dt_object                *obj;
4096         struct lov_mds_md_v1            *lmm;
4097         struct lov_ost_data_v1          *objs;
4098         __u32                            idx    = pfid->f_stripe_idx;
4099         __u32                            magic;
4100         int                              rc     = 0;
4101         int                              i;
4102         __u16                            count;
4103         ENTRY;
4104
4105         pfid->f_ver = 0;
4106         obj = lfsck_object_find_by_dev(env, com->lc_lfsck->li_bottom, pfid);
4107         if (IS_ERR(obj))
4108                 RETURN(PTR_ERR(obj));
4109
4110         dt_read_lock(env, obj, 0);
4111         if (unlikely(!dt_object_exists(obj)))
4112                 GOTO(unlock, rc = -ENOENT);
4113
4114         rc = lfsck_layout_get_lovea(env, obj, buf, NULL);
4115         if (rc < 0)
4116                 GOTO(unlock, rc);
4117
4118         if (rc == 0)
4119                 GOTO(unlock, rc = -ENODATA);
4120
4121         lmm = buf->lb_buf;
4122         rc = lfsck_layout_verify_header(lmm);
4123         if (rc != 0)
4124                 GOTO(unlock, rc);
4125
4126         /* Currently, we only support LOV_MAGIC_V1/LOV_MAGIC_V3 which has
4127          * been verified in lfsck_layout_verify_header() already. If some
4128          * new magic introduced in the future, then layout LFSCK needs to
4129          * be updated also. */
4130         magic = le32_to_cpu(lmm->lmm_magic);
4131         if (magic == LOV_MAGIC_V1) {
4132                 objs = &lmm->lmm_objects[0];
4133         } else {
4134                 LASSERT(magic == LOV_MAGIC_V3);
4135                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[0];
4136         }
4137
4138         fid_to_ostid(cfid, oi);
4139         count = le16_to_cpu(lmm->lmm_stripe_count);
4140         for (i = 0; i < count; i++, objs++) {
4141                 struct ost_id oi2;
4142
4143                 ostid_le_to_cpu(&objs->l_ost_oi, &oi2);
4144                 if (memcmp(oi, &oi2, sizeof(*oi)) == 0)
4145                         GOTO(unlock, rc = (i != idx ? -ENODATA : 0));
4146         }
4147
4148         GOTO(unlock, rc = -ENODATA);
4149
4150 unlock:
4151         dt_read_unlock(env, obj);
4152         lu_object_put(env, &obj->do_lu);
4153
4154         return rc;
4155 }
4156
4157 /*
4158  * The LFSCK-on-OST will ask the LFSCK-on-MDT to check whether the given
4159  * MDT-object/OST-object pairs match or not to aviod transfer MDT-object
4160  * layout EA from MDT to OST. On one hand, the OST no need to understand
4161  * the layout EA structure; on the other hand, it may cause trouble when
4162  * transfer large layout EA from MDT to OST via normal OUT RPC.
4163  *
4164  * \ret > 0: unrecognized stripe
4165  * \ret = 0: recognized stripe
4166  * \ret < 0: other failures
4167  */
4168 static int lfsck_layout_slave_check_pairs(const struct lu_env *env,
4169                                           struct lfsck_component *com,
4170                                           struct lu_fid *cfid,
4171                                           struct lu_fid *pfid)
4172 {
4173         struct lfsck_instance    *lfsck  = com->lc_lfsck;
4174         struct obd_device        *obd    = lfsck->li_obd;
4175         struct seq_server_site   *ss     =
4176                         lu_site2seq(lfsck->li_bottom->dd_lu_dev.ld_site);
4177         struct obd_export        *exp    = NULL;
4178         struct ptlrpc_request    *req    = NULL;
4179         struct lfsck_request     *lr;
4180         struct lu_seq_range       range  = { 0 };
4181         int                       rc     = 0;
4182         ENTRY;
4183
4184         if (unlikely(fid_is_idif(pfid)))
4185                 RETURN(1);
4186
4187         fld_range_set_any(&range);
4188         rc = fld_server_lookup(env, ss->ss_server_fld, fid_seq(pfid), &range);
4189         if (rc != 0)
4190                 RETURN(rc == -ENOENT ? 1 : rc);
4191
4192         if (unlikely(!fld_range_is_mdt(&range)))
4193                 RETURN(1);
4194
4195         exp = lustre_find_lwp_by_index(obd->obd_name, range.lsr_index);
4196         if (unlikely(exp == NULL))
4197                 RETURN(1);
4198
4199         if (!(exp_connect_flags(exp) & OBD_CONNECT_LFSCK))
4200                 GOTO(out, rc = -EOPNOTSUPP);
4201
4202         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_LFSCK_NOTIFY);
4203         if (req == NULL)
4204                 GOTO(out, rc = -ENOMEM);
4205
4206         rc = ptlrpc_request_pack(req, LUSTRE_OBD_VERSION, LFSCK_NOTIFY);
4207         if (rc != 0) {
4208                 ptlrpc_request_free(req);
4209
4210                 GOTO(out, rc);
4211         }
4212
4213         lr = req_capsule_client_get(&req->rq_pill, &RMF_LFSCK_REQUEST);
4214         memset(lr, 0, sizeof(*lr));
4215         lr->lr_event = LE_PAIRS_VERIFY;
4216         lr->lr_active = LFSCK_TYPE_LAYOUT;
4217         lr->lr_fid = *cfid; /* OST-object itself FID. */
4218         lr->lr_fid2 = *pfid; /* The claimed parent FID. */
4219
4220         ptlrpc_request_set_replen(req);
4221         rc = ptlrpc_queue_wait(req);
4222         ptlrpc_req_finished(req);
4223
4224         if (rc == -ENOENT || rc == -ENODATA)
4225                 rc = 1;
4226
4227         GOTO(out, rc);
4228
4229 out:
4230         if (exp != NULL)
4231                 class_export_put(exp);
4232
4233         return rc;
4234 }
4235
4236 static int lfsck_layout_slave_repair_pfid(const struct lu_env *env,
4237                                           struct lfsck_component *com,
4238                                           struct lfsck_request *lr)
4239 {
4240         struct lfsck_thread_info        *info   = lfsck_env_info(env);
4241         struct filter_fid               *ff     = &info->lti_new_pfid;
4242         struct lu_buf                   *buf;
4243         struct dt_device                *dev    = com->lc_lfsck->li_bottom;
4244         struct dt_object                *obj;
4245         struct thandle                  *th     = NULL;
4246         int                              rc     = 0;
4247         ENTRY;
4248
4249         obj = lfsck_object_find_by_dev(env, dev, &lr->lr_fid);
4250         if (IS_ERR(obj))
4251                 GOTO(log, rc = PTR_ERR(obj));
4252
4253         fid_cpu_to_le(&ff->ff_parent, &lr->lr_fid2);
4254         buf = lfsck_buf_get(env, ff, sizeof(*ff));
4255         dt_write_lock(env, obj, 0);
4256         if (unlikely(!dt_object_exists(obj)))
4257                 GOTO(unlock, rc = 0);
4258
4259         th = dt_trans_create(env, dev);
4260         if (IS_ERR(th))
4261                 GOTO(unlock, rc = PTR_ERR(th));
4262
4263         rc = dt_declare_xattr_set(env, obj, buf, XATTR_NAME_FID, 0, th);
4264         if (rc != 0)
4265                 GOTO(stop, rc);
4266
4267         rc = dt_trans_start_local(env, dev, th);
4268         if (rc != 0)
4269                 GOTO(stop, rc);
4270
4271         rc = dt_xattr_set(env, obj, buf, XATTR_NAME_FID, 0, th, BYPASS_CAPA);
4272
4273         GOTO(stop, rc);
4274
4275 stop:
4276         dt_trans_stop(env, dev, th);
4277
4278 unlock:
4279         dt_write_unlock(env, obj);
4280         lu_object_put(env, &obj->do_lu);
4281
4282 log:
4283         CDEBUG(D_LFSCK, "%s: layout LFSCK slave repaired pfid for "DFID
4284                ", parent "DFID": rc = %d\n", lfsck_lfsck2name(com->lc_lfsck),
4285                PFID(&lr->lr_fid), PFID(&lr->lr_fid2), rc);
4286
4287         return rc;
4288 }
4289
4290 /* layout APIs */
4291
4292 static int lfsck_layout_reset(const struct lu_env *env,
4293                               struct lfsck_component *com, bool init)
4294 {
4295         struct lfsck_layout     *lo    = com->lc_file_ram;
4296         int                      rc;
4297
4298         down_write(&com->lc_sem);
4299         if (init) {
4300                 memset(lo, 0, com->lc_file_size);
4301         } else {
4302                 __u32 count = lo->ll_success_count;
4303                 __u64 last_time = lo->ll_time_last_complete;
4304
4305                 memset(lo, 0, com->lc_file_size);
4306                 lo->ll_success_count = count;
4307                 lo->ll_time_last_complete = last_time;
4308         }
4309
4310         lo->ll_magic = LFSCK_LAYOUT_MAGIC;
4311         lo->ll_status = LS_INIT;
4312
4313         rc = lfsck_layout_store(env, com);
4314         up_write(&com->lc_sem);
4315
4316         CDEBUG(D_LFSCK, "%s: layout LFSCK reset: rc = %d\n",
4317                lfsck_lfsck2name(com->lc_lfsck), rc);
4318
4319         return rc;
4320 }
4321
4322 static void lfsck_layout_fail(const struct lu_env *env,
4323                               struct lfsck_component *com, bool new_checked)
4324 {
4325         struct lfsck_layout *lo = com->lc_file_ram;
4326
4327         down_write(&com->lc_sem);
4328         if (new_checked)
4329                 com->lc_new_checked++;
4330         lfsck_layout_record_failure(env, com->lc_lfsck, lo);
4331         up_write(&com->lc_sem);
4332 }
4333
4334 static int lfsck_layout_master_checkpoint(const struct lu_env *env,
4335                                           struct lfsck_component *com, bool init)
4336 {
4337         struct lfsck_instance           *lfsck   = com->lc_lfsck;
4338         struct lfsck_layout             *lo      = com->lc_file_ram;
4339         struct lfsck_layout_master_data *llmd    = com->lc_data;
4340         struct ptlrpc_thread            *mthread = &lfsck->li_thread;
4341         struct ptlrpc_thread            *athread = &llmd->llmd_thread;
4342         struct l_wait_info               lwi     = { 0 };
4343         int                              rc;
4344
4345         if (com->lc_new_checked == 0 && !init)
4346                 return 0;
4347
4348         l_wait_event(mthread->t_ctl_waitq,
4349                      list_empty(&llmd->llmd_req_list) ||
4350                      !thread_is_running(mthread) ||
4351                      thread_is_stopped(athread),
4352                      &lwi);
4353
4354         if (!thread_is_running(mthread) || thread_is_stopped(athread))
4355                 return 0;
4356
4357         down_write(&com->lc_sem);
4358         if (init) {
4359                 lo->ll_pos_latest_start = lfsck->li_pos_current.lp_oit_cookie;
4360         } else {
4361                 lo->ll_pos_last_checkpoint =
4362                                         lfsck->li_pos_current.lp_oit_cookie;
4363                 lo->ll_run_time_phase1 += cfs_duration_sec(cfs_time_current() +
4364                                 HALF_SEC - lfsck->li_time_last_checkpoint);
4365                 lo->ll_time_last_checkpoint = cfs_time_current_sec();
4366                 lo->ll_objs_checked_phase1 += com->lc_new_checked;
4367                 com->lc_new_checked = 0;
4368         }
4369
4370         rc = lfsck_layout_store(env, com);
4371         up_write(&com->lc_sem);
4372
4373         CDEBUG(D_LFSCK, "%s: layout LFSCK master checkpoint at the pos ["
4374                LPU64"]: rc = %d\n", lfsck_lfsck2name(lfsck),
4375                lfsck->li_pos_current.lp_oit_cookie, rc);
4376
4377         return rc;
4378 }
4379
4380 static int lfsck_layout_slave_checkpoint(const struct lu_env *env,
4381                                          struct lfsck_component *com, bool init)
4382 {
4383         struct lfsck_instance   *lfsck = com->lc_lfsck;
4384         struct lfsck_layout     *lo    = com->lc_file_ram;
4385         int                      rc;
4386
4387         if (com->lc_new_checked == 0 && !init)
4388                 return 0;
4389
4390         down_write(&com->lc_sem);
4391         if (init) {
4392                 lo->ll_pos_latest_start = lfsck->li_pos_current.lp_oit_cookie;
4393         } else {
4394                 lo->ll_pos_last_checkpoint =
4395                                         lfsck->li_pos_current.lp_oit_cookie;
4396                 lo->ll_run_time_phase1 += cfs_duration_sec(cfs_time_current() +
4397                                 HALF_SEC - lfsck->li_time_last_checkpoint);
4398                 lo->ll_time_last_checkpoint = cfs_time_current_sec();
4399                 lo->ll_objs_checked_phase1 += com->lc_new_checked;
4400                 com->lc_new_checked = 0;
4401         }
4402
4403         rc = lfsck_layout_store(env, com);
4404         up_write(&com->lc_sem);
4405
4406         CDEBUG(D_LFSCK, "%s: layout LFSCK slave checkpoint at the pos ["
4407                LPU64"]: rc = %d\n", lfsck_lfsck2name(lfsck),
4408                lfsck->li_pos_current.lp_oit_cookie, rc);
4409
4410         return rc;
4411 }
4412
4413 static int lfsck_layout_prep(const struct lu_env *env,
4414                              struct lfsck_component *com,
4415                              struct lfsck_start *start)
4416 {
4417         struct lfsck_instance   *lfsck  = com->lc_lfsck;
4418         struct lfsck_layout     *lo     = com->lc_file_ram;
4419         struct lfsck_position   *pos    = &com->lc_pos_start;
4420
4421         fid_zero(&pos->lp_dir_parent);
4422         pos->lp_dir_cookie = 0;
4423         if (lo->ll_status == LS_COMPLETED ||
4424             lo->ll_status == LS_PARTIAL ||
4425             /* To handle orphan, must scan from the beginning. */
4426             (start != NULL && start->ls_flags & LPF_ORPHAN)) {
4427                 int rc;
4428
4429                 rc = lfsck_layout_reset(env, com, false);
4430                 if (rc == 0)
4431                         rc = lfsck_set_param(env, lfsck, start, true);
4432
4433                 if (rc != 0) {
4434                         CDEBUG(D_LFSCK, "%s: layout LFSCK prep failed: "
4435                                "rc = %d\n", lfsck_lfsck2name(lfsck), rc);
4436
4437                         return rc;
4438                 }
4439         }
4440
4441         down_write(&com->lc_sem);
4442         lo->ll_time_latest_start = cfs_time_current_sec();
4443         spin_lock(&lfsck->li_lock);
4444         if (lo->ll_flags & LF_SCANNED_ONCE) {
4445                 if (!lfsck->li_drop_dryrun ||
4446                     lo->ll_pos_first_inconsistent == 0) {
4447                         lo->ll_status = LS_SCANNING_PHASE2;
4448                         list_del_init(&com->lc_link);
4449                         list_add_tail(&com->lc_link,
4450                                       &lfsck->li_list_double_scan);
4451                         pos->lp_oit_cookie = 0;
4452                 } else {
4453                         int i;
4454
4455                         lo->ll_status = LS_SCANNING_PHASE1;
4456                         lo->ll_run_time_phase1 = 0;
4457                         lo->ll_run_time_phase2 = 0;
4458                         lo->ll_objs_checked_phase1 = 0;
4459                         lo->ll_objs_checked_phase2 = 0;
4460                         lo->ll_objs_failed_phase1 = 0;
4461                         lo->ll_objs_failed_phase2 = 0;
4462                         for (i = 0; i < LLIT_MAX; i++)
4463                                 lo->ll_objs_repaired[i] = 0;
4464
4465                         pos->lp_oit_cookie = lo->ll_pos_first_inconsistent;
4466                         fid_zero(&com->lc_fid_latest_scanned_phase2);
4467                 }
4468         } else {
4469                 lo->ll_status = LS_SCANNING_PHASE1;
4470                 if (!lfsck->li_drop_dryrun ||
4471                     lo->ll_pos_first_inconsistent == 0)
4472                         pos->lp_oit_cookie = lo->ll_pos_last_checkpoint + 1;
4473                 else
4474                         pos->lp_oit_cookie = lo->ll_pos_first_inconsistent;
4475         }
4476         spin_unlock(&lfsck->li_lock);
4477         up_write(&com->lc_sem);
4478
4479         return 0;
4480 }
4481
4482 static int lfsck_layout_slave_prep(const struct lu_env *env,
4483                                    struct lfsck_component *com,
4484                                    struct lfsck_start_param *lsp)
4485 {
4486         struct lfsck_layout_slave_data  *llsd   = com->lc_data;
4487         struct lfsck_instance           *lfsck  = com->lc_lfsck;
4488         struct lfsck_layout             *lo     = com->lc_file_ram;
4489         struct lfsck_start              *start  = lsp->lsp_start;
4490         int                              rc;
4491
4492         rc = lfsck_layout_prep(env, com, start);
4493         if (rc != 0)
4494                 return rc;
4495
4496         if (lo->ll_flags & LF_CRASHED_LASTID &&
4497             list_empty(&llsd->llsd_master_list)) {
4498                 LASSERT(lfsck->li_out_notify != NULL);
4499
4500                 lfsck->li_out_notify(env, lfsck->li_out_notify_data,
4501                                      LE_LASTID_REBUILDING);
4502         }
4503
4504         if (!lsp->lsp_index_valid)
4505                 return 0;
4506
4507         rc = lfsck_layout_llst_add(llsd, lsp->lsp_index);
4508         if (rc == 0 && start != NULL && start->ls_flags & LPF_ORPHAN) {
4509                 LASSERT(!llsd->llsd_rbtree_valid);
4510
4511                 write_lock(&llsd->llsd_rb_lock);
4512                 rc = lfsck_rbtree_setup(env, com);
4513                 write_unlock(&llsd->llsd_rb_lock);
4514         }
4515
4516         CDEBUG(D_LFSCK, "%s: layout LFSCK slave prep done, start pos ["
4517                LPU64"]\n", lfsck_lfsck2name(lfsck),
4518                com->lc_pos_start.lp_oit_cookie);
4519
4520         return rc;
4521 }
4522
4523 static int lfsck_layout_master_prep(const struct lu_env *env,
4524                                     struct lfsck_component *com,
4525                                     struct lfsck_start_param *lsp)
4526 {
4527         struct lfsck_instance           *lfsck   = com->lc_lfsck;
4528         struct lfsck_layout_master_data *llmd    = com->lc_data;
4529         struct ptlrpc_thread            *mthread = &lfsck->li_thread;
4530         struct ptlrpc_thread            *athread = &llmd->llmd_thread;
4531         struct lfsck_thread_args        *lta;
4532         struct task_struct              *task;
4533         int                              rc;
4534         ENTRY;
4535
4536         rc = lfsck_layout_prep(env, com, lsp->lsp_start);
4537         if (rc != 0)
4538                 RETURN(rc);
4539
4540         llmd->llmd_assistant_status = 0;
4541         llmd->llmd_post_result = 0;
4542         llmd->llmd_to_post = 0;
4543         llmd->llmd_to_double_scan = 0;
4544         llmd->llmd_in_double_scan = 0;
4545         llmd->llmd_exit = 0;
4546         thread_set_flags(athread, 0);
4547
4548         lta = lfsck_thread_args_init(lfsck, com, lsp);
4549         if (IS_ERR(lta))
4550                 RETURN(PTR_ERR(lta));
4551
4552         task = kthread_run(lfsck_layout_assistant, lta, "lfsck_layout");
4553         if (IS_ERR(task)) {
4554                 rc = PTR_ERR(task);
4555                 CERROR("%s: cannot start LFSCK layout assistant thread: "
4556                        "rc = %d\n", lfsck_lfsck2name(lfsck), rc);
4557                 lfsck_thread_args_fini(lta);
4558         } else {
4559                 struct l_wait_info lwi = { 0 };
4560
4561                 l_wait_event(mthread->t_ctl_waitq,
4562                              thread_is_running(athread) ||
4563                              thread_is_stopped(athread),
4564                              &lwi);
4565                 if (unlikely(!thread_is_running(athread)))
4566                         rc = llmd->llmd_assistant_status;
4567                 else
4568                         rc = 0;
4569         }
4570
4571         CDEBUG(D_LFSCK, "%s: layout LFSCK master prep done, start pos ["
4572                LPU64"\n", lfsck_lfsck2name(lfsck),
4573                com->lc_pos_start.lp_oit_cookie);
4574
4575         RETURN(rc);
4576 }
4577
4578 /* Pre-fetch the attribute for each stripe in the given layout EA. */
4579 static int lfsck_layout_scan_stripes(const struct lu_env *env,
4580                                      struct lfsck_component *com,
4581                                      struct dt_object *parent,
4582                                      struct lov_mds_md_v1 *lmm)
4583 {
4584         struct lfsck_thread_info        *info    = lfsck_env_info(env);
4585         struct lfsck_instance           *lfsck   = com->lc_lfsck;
4586         struct lfsck_bookmark           *bk      = &lfsck->li_bookmark_ram;
4587         struct lfsck_layout             *lo      = com->lc_file_ram;
4588         struct lfsck_layout_master_data *llmd    = com->lc_data;
4589         struct lfsck_layout_object      *llo     = NULL;
4590         struct lov_ost_data_v1          *objs;
4591         struct lfsck_tgt_descs          *ltds    = &lfsck->li_ost_descs;
4592         struct ptlrpc_thread            *mthread = &lfsck->li_thread;
4593         struct ptlrpc_thread            *athread = &llmd->llmd_thread;
4594                 struct l_wait_info       lwi     = { 0 };
4595         struct lu_buf                   *buf;
4596         int                              rc      = 0;
4597         int                              i;
4598         __u32                            magic;
4599         __u16                            count;
4600         __u16                            gen;
4601         ENTRY;
4602
4603         buf = lfsck_buf_get(env, &info->lti_old_pfid,
4604                             sizeof(struct filter_fid_old));
4605         count = le16_to_cpu(lmm->lmm_stripe_count);
4606         gen = le16_to_cpu(lmm->lmm_layout_gen);
4607         /* Currently, we only support LOV_MAGIC_V1/LOV_MAGIC_V3 which has
4608          * been verified in lfsck_layout_verify_header() already. If some
4609          * new magic introduced in the future, then layout LFSCK needs to
4610          * be updated also. */
4611         magic = le32_to_cpu(lmm->lmm_magic);
4612         if (magic == LOV_MAGIC_V1) {
4613                 objs = &lmm->lmm_objects[0];
4614         } else {
4615                 LASSERT(magic == LOV_MAGIC_V3);
4616                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[0];
4617         }
4618
4619         for (i = 0; i < count; i++, objs++) {
4620                 struct lu_fid           *fid    = &info->lti_fid;
4621                 struct ost_id           *oi     = &info->lti_oi;
4622                 struct lfsck_layout_req *llr;
4623                 struct lfsck_tgt_desc   *tgt    = NULL;
4624                 struct dt_object        *cobj   = NULL;
4625                 __u32                    index  =
4626                                         le32_to_cpu(objs->l_ost_idx);
4627                 bool                     wakeup = false;
4628
4629                 if (unlikely(lovea_slot_is_dummy(objs)))
4630                         continue;
4631
4632                 l_wait_event(mthread->t_ctl_waitq,
4633                              bk->lb_async_windows == 0 ||
4634                              llmd->llmd_prefetched < bk->lb_async_windows ||
4635                              !thread_is_running(mthread) ||
4636                              thread_is_stopped(athread),
4637                              &lwi);
4638
4639                 if (unlikely(!thread_is_running(mthread)) ||
4640                              thread_is_stopped(athread))
4641                         GOTO(out, rc = 0);
4642
4643                 ostid_le_to_cpu(&objs->l_ost_oi, oi);
4644                 ostid_to_fid(fid, oi, index);
4645                 tgt = lfsck_tgt_get(ltds, index);
4646                 if (unlikely(tgt == NULL)) {
4647                         CDEBUG(D_LFSCK, "%s: cannot talk with OST %x which "
4648                                "did not join the layout LFSCK\n",
4649                                lfsck_lfsck2name(lfsck), index);
4650                         lo->ll_flags |= LF_INCOMPLETE;
4651                         goto next;
4652                 }
4653
4654                 cobj = lfsck_object_find_by_dev(env, tgt->ltd_tgt, fid);
4655                 if (IS_ERR(cobj)) {
4656                         rc = PTR_ERR(cobj);
4657                         goto next;
4658                 }
4659
4660                 rc = dt_declare_attr_get(env, cobj, BYPASS_CAPA);
4661                 if (rc != 0)
4662                         goto next;
4663
4664                 rc = dt_declare_xattr_get(env, cobj, buf, XATTR_NAME_FID,
4665                                           BYPASS_CAPA);
4666                 if (rc != 0)
4667                         goto next;
4668
4669                 if (llo == NULL) {
4670                         llo = lfsck_layout_object_init(env, parent, gen);
4671                         if (IS_ERR(llo)) {
4672                                 rc = PTR_ERR(llo);
4673                                 goto next;
4674                         }
4675                 }
4676
4677                 llr = lfsck_layout_req_init(llo, cobj, index, i);
4678                 if (IS_ERR(llr)) {
4679                         rc = PTR_ERR(llr);
4680                         goto next;
4681                 }
4682
4683                 cobj = NULL;
4684                 spin_lock(&llmd->llmd_lock);
4685                 if (llmd->llmd_assistant_status < 0) {
4686                         spin_unlock(&llmd->llmd_lock);
4687                         lfsck_layout_req_fini(env, llr);
4688                         lfsck_tgt_put(tgt);
4689                         RETURN(llmd->llmd_assistant_status);
4690                 }
4691
4692                 list_add_tail(&llr->llr_list, &llmd->llmd_req_list);
4693                 if (llmd->llmd_prefetched == 0)
4694                         wakeup = true;
4695
4696                 llmd->llmd_prefetched++;
4697                 spin_unlock(&llmd->llmd_lock);
4698                 if (wakeup)
4699                         wake_up_all(&athread->t_ctl_waitq);
4700
4701 next:
4702                 down_write(&com->lc_sem);
4703                 com->lc_new_checked++;
4704                 if (rc < 0)
4705                         lfsck_layout_record_failure(env, lfsck, lo);
4706                 up_write(&com->lc_sem);
4707
4708                 if (cobj != NULL && !IS_ERR(cobj))
4709                         lu_object_put(env, &cobj->do_lu);
4710
4711                 if (likely(tgt != NULL))
4712                         lfsck_tgt_put(tgt);
4713
4714                 if (rc < 0 && bk->lb_param & LPF_FAILOUT)
4715                         GOTO(out, rc);
4716         }
4717
4718         GOTO(out, rc = 0);
4719
4720 out:
4721         if (llo != NULL && !IS_ERR(llo))
4722                 lfsck_layout_object_put(env, llo);
4723
4724         return rc;
4725 }
4726
4727 /* For the given object, read its layout EA locally. For each stripe, pre-fetch
4728  * the OST-object's attribute and generate an structure lfsck_layout_req on the
4729  * list ::llmd_req_list.
4730  *
4731  * For each request on above list, the lfsck_layout_assistant thread compares
4732  * the OST side attribute with local attribute, if inconsistent, then repair it.
4733  *
4734  * All above processing is async mode with pipeline. */
4735 static int lfsck_layout_master_exec_oit(const struct lu_env *env,
4736                                         struct lfsck_component *com,
4737                                         struct dt_object *obj)
4738 {
4739         struct lfsck_thread_info        *info   = lfsck_env_info(env);
4740         struct ost_id                   *oi     = &info->lti_oi;
4741         struct lfsck_layout             *lo     = com->lc_file_ram;
4742         struct lfsck_layout_master_data *llmd   = com->lc_data;
4743         struct lfsck_instance           *lfsck  = com->lc_lfsck;
4744         struct lfsck_bookmark           *bk     = &lfsck->li_bookmark_ram;
4745         struct thandle                  *handle = NULL;
4746         struct lu_buf                   *buf    = &info->lti_big_buf;
4747         struct lov_mds_md_v1            *lmm    = NULL;
4748         struct dt_device                *dev    = lfsck->li_bottom;
4749         struct lustre_handle             lh     = { 0 };
4750         ssize_t                          buflen = buf->lb_len;
4751         int                              rc     = 0;
4752         bool                             locked = false;
4753         bool                             stripe = false;
4754         bool                             bad_oi = false;
4755         ENTRY;
4756
4757         if (!S_ISREG(lfsck_object_type(obj)))
4758                 GOTO(out, rc = 0);
4759
4760         if (llmd->llmd_assistant_status < 0)
4761                 GOTO(out, rc = -ESRCH);
4762
4763         fid_to_lmm_oi(lfsck_dto2fid(obj), oi);
4764         lmm_oi_cpu_to_le(oi, oi);
4765         dt_read_lock(env, obj, 0);
4766         locked = true;
4767
4768 again:
4769         rc = lfsck_layout_get_lovea(env, obj, buf, &buflen);
4770         if (rc <= 0)
4771                 GOTO(out, rc);
4772
4773         buf->lb_len = rc;
4774         lmm = buf->lb_buf;
4775         rc = lfsck_layout_verify_header(lmm);
4776         /* If the LOV EA crashed, then it is possible to be rebuilt later
4777          * when handle orphan OST-objects. */
4778         if (rc != 0)
4779                 GOTO(out, rc);
4780
4781         if (memcmp(oi, &lmm->lmm_oi, sizeof(*oi)) == 0)
4782                 GOTO(out, stripe = true);
4783
4784         /* Inconsistent lmm_oi, should be repaired. */
4785         bad_oi = true;
4786
4787         if (bk->lb_param & LPF_DRYRUN) {
4788                 down_write(&com->lc_sem);
4789                 lo->ll_objs_repaired[LLIT_OTHERS - 1]++;
4790                 up_write(&com->lc_sem);
4791
4792                 GOTO(out, stripe = true);
4793         }
4794
4795         if (!lustre_handle_is_used(&lh)) {
4796                 dt_read_unlock(env, obj);
4797                 locked = false;
4798                 buf->lb_len = buflen;
4799                 rc = lfsck_layout_lock(env, com, obj, &lh,
4800                                        MDS_INODELOCK_LAYOUT |
4801                                        MDS_INODELOCK_XATTR);
4802                 if (rc != 0)
4803                         GOTO(out, rc);
4804
4805                 handle = dt_trans_create(env, dev);
4806                 if (IS_ERR(handle))
4807                         GOTO(out, rc = PTR_ERR(handle));
4808
4809                 rc = dt_declare_xattr_set(env, obj, buf, XATTR_NAME_LOV,
4810                                           LU_XATTR_REPLACE, handle);
4811                 if (rc != 0)
4812                         GOTO(out, rc);
4813
4814                 rc = dt_trans_start_local(env, dev, handle);
4815                 if (rc != 0)
4816                         GOTO(out, rc);
4817
4818                 dt_write_lock(env, obj, 0);
4819                 locked = true;
4820
4821                 goto again;
4822         }
4823
4824         lmm->lmm_oi = *oi;
4825         rc = dt_xattr_set(env, obj, buf, XATTR_NAME_LOV,
4826                           LU_XATTR_REPLACE, handle, BYPASS_CAPA);
4827         if (rc != 0)
4828                 GOTO(out, rc);
4829
4830         down_write(&com->lc_sem);
4831         lo->ll_objs_repaired[LLIT_OTHERS - 1]++;
4832         up_write(&com->lc_sem);
4833
4834         GOTO(out, stripe = true);
4835
4836 out:
4837         if (locked) {
4838                 if (lustre_handle_is_used(&lh))
4839                         dt_write_unlock(env, obj);
4840                 else
4841                         dt_read_unlock(env, obj);
4842         }
4843
4844         if (handle != NULL && !IS_ERR(handle))
4845                 dt_trans_stop(env, dev, handle);
4846
4847         lfsck_layout_unlock(&lh);
4848
4849         if (bad_oi)
4850                 CDEBUG(D_LFSCK, "%s: layout LFSCK master %s bad lmm_oi for "
4851                        DFID": rc = %d\n", lfsck_lfsck2name(lfsck),
4852                        bk->lb_param & LPF_DRYRUN ? "found" : "repaired",
4853                        PFID(lfsck_dto2fid(obj)), rc);
4854
4855         if (stripe) {
4856                 rc = lfsck_layout_scan_stripes(env, com, obj, lmm);
4857         } else {
4858                 down_write(&com->lc_sem);
4859                 com->lc_new_checked++;
4860                 if (rc < 0)
4861                         lfsck_layout_record_failure(env, lfsck, lo);
4862                 up_write(&com->lc_sem);
4863         }
4864         buf->lb_len = buflen;
4865
4866         return rc;
4867 }
4868
4869 static int lfsck_layout_slave_exec_oit(const struct lu_env *env,
4870                                        struct lfsck_component *com,
4871                                        struct dt_object *obj)
4872 {
4873         struct lfsck_instance           *lfsck  = com->lc_lfsck;
4874         struct lfsck_layout             *lo     = com->lc_file_ram;
4875         const struct lu_fid             *fid    = lfsck_dto2fid(obj);
4876         struct lfsck_layout_slave_data  *llsd   = com->lc_data;
4877         struct lfsck_layout_seq         *lls;
4878         __u64                            seq;
4879         __u64                            oid;
4880         int                              rc;
4881         ENTRY;
4882
4883         LASSERT(llsd != NULL);
4884
4885         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_DELAY5) &&
4886             cfs_fail_val == lfsck_dev_idx(lfsck->li_bottom)) {
4887                 struct l_wait_info       lwi = LWI_TIMEOUT(cfs_time_seconds(1),
4888                                                            NULL, NULL);
4889                 struct ptlrpc_thread    *thread = &lfsck->li_thread;
4890
4891                 l_wait_event(thread->t_ctl_waitq,
4892                              !thread_is_running(thread),
4893                              &lwi);
4894         }
4895
4896         lfsck_rbtree_update_bitmap(env, com, fid, false);
4897
4898         down_write(&com->lc_sem);
4899         if (fid_is_idif(fid))
4900                 seq = 0;
4901         else if (!fid_is_norm(fid) ||
4902                  !fid_is_for_ostobj(env, lfsck->li_next, obj, fid))
4903                 GOTO(unlock, rc = 0);
4904         else
4905                 seq = fid_seq(fid);
4906         com->lc_new_checked++;
4907
4908         lls = lfsck_layout_seq_lookup(llsd, seq);
4909         if (lls == NULL) {
4910                 OBD_ALLOC_PTR(lls);
4911                 if (unlikely(lls == NULL))
4912                         GOTO(unlock, rc = -ENOMEM);
4913
4914                 INIT_LIST_HEAD(&lls->lls_list);
4915                 lls->lls_seq = seq;
4916                 rc = lfsck_layout_lastid_load(env, com, lls);
4917                 if (rc != 0) {
4918                         CDEBUG(D_LFSCK, "%s: layout LFSCK failed to "
4919                               "load LAST_ID for "LPX64": rc = %d\n",
4920                               lfsck_lfsck2name(com->lc_lfsck), seq, rc);
4921                         lo->ll_objs_failed_phase1++;
4922                         OBD_FREE_PTR(lls);
4923                         GOTO(unlock, rc);
4924                 }
4925
4926                 lfsck_layout_seq_insert(llsd, lls);
4927         }
4928
4929         if (unlikely(fid_is_last_id(fid)))
4930                 GOTO(unlock, rc = 0);
4931
4932         oid = fid_oid(fid);
4933         if (oid > lls->lls_lastid_known)
4934                 lls->lls_lastid_known = oid;
4935
4936         if (oid > lls->lls_lastid) {
4937                 if (!(lo->ll_flags & LF_CRASHED_LASTID)) {
4938                         /* OFD may create new objects during LFSCK scanning. */
4939                         rc = lfsck_layout_lastid_reload(env, com, lls);
4940                         if (unlikely(rc != 0))
4941                                 CDEBUG(D_LFSCK, "%s: layout LFSCK failed to "
4942                                       "reload LAST_ID for "LPX64": rc = %d\n",
4943                                       lfsck_lfsck2name(com->lc_lfsck),
4944                                       lls->lls_seq, rc);
4945                         if (oid <= lls->lls_lastid)
4946                                 GOTO(unlock, rc = 0);
4947
4948                         LASSERT(lfsck->li_out_notify != NULL);
4949
4950                         lfsck->li_out_notify(env, lfsck->li_out_notify_data,
4951                                              LE_LASTID_REBUILDING);
4952                         lo->ll_flags |= LF_CRASHED_LASTID;
4953                 }
4954
4955                 lls->lls_lastid = oid;
4956                 lls->lls_dirty = 1;
4957         }
4958
4959         GOTO(unlock, rc = 0);
4960
4961 unlock:
4962         up_write(&com->lc_sem);
4963
4964         return rc;
4965 }
4966
4967 static int lfsck_layout_exec_dir(const struct lu_env *env,
4968                                  struct lfsck_component *com,
4969                                  struct dt_object *obj,
4970                                  struct lu_dirent *ent)
4971 {
4972         return 0;
4973 }
4974
4975 static int lfsck_layout_master_post(const struct lu_env *env,
4976                                     struct lfsck_component *com,
4977                                     int result, bool init)
4978 {
4979         struct lfsck_instance           *lfsck   = com->lc_lfsck;
4980         struct lfsck_layout             *lo      = com->lc_file_ram;
4981         struct lfsck_layout_master_data *llmd    = com->lc_data;
4982         struct ptlrpc_thread            *mthread = &lfsck->li_thread;
4983         struct ptlrpc_thread            *athread = &llmd->llmd_thread;
4984         struct l_wait_info               lwi     = { 0 };
4985         int                              rc;
4986         ENTRY;
4987
4988
4989         llmd->llmd_post_result = result;
4990         llmd->llmd_to_post = 1;
4991         if (llmd->llmd_post_result <= 0)
4992                 llmd->llmd_exit = 1;
4993
4994         wake_up_all(&athread->t_ctl_waitq);
4995         l_wait_event(mthread->t_ctl_waitq,
4996                      (result > 0 && list_empty(&llmd->llmd_req_list)) ||
4997                      thread_is_stopped(athread),
4998                      &lwi);
4999
5000         if (llmd->llmd_assistant_status < 0)
5001                 result = llmd->llmd_assistant_status;
5002
5003         down_write(&com->lc_sem);
5004         spin_lock(&lfsck->li_lock);
5005         /* When LFSCK failed, there may be some prefetched objects those are
5006          * not been processed yet, we do not know the exactly position, then
5007          * just restart from last check-point next time. */
5008         if (!init && !llmd->llmd_exit)
5009                 lo->ll_pos_last_checkpoint =
5010                                         lfsck->li_pos_current.lp_oit_cookie;
5011
5012         if (result > 0) {
5013                 lo->ll_status = LS_SCANNING_PHASE2;
5014                 lo->ll_flags |= LF_SCANNED_ONCE;
5015                 lo->ll_flags &= ~LF_UPGRADE;
5016                 list_del_init(&com->lc_link);
5017                 list_add_tail(&com->lc_link, &lfsck->li_list_double_scan);
5018         } else if (result == 0) {
5019                 lo->ll_status = lfsck->li_status;
5020                 if (lo->ll_status == 0)
5021                         lo->ll_status = LS_STOPPED;
5022                 if (lo->ll_status != LS_PAUSED) {
5023                         list_del_init(&com->lc_link);
5024                         list_add_tail(&com->lc_link, &lfsck->li_list_idle);
5025                 }
5026         } else {
5027                 lo->ll_status = LS_FAILED;
5028                 list_del_init(&com->lc_link);
5029                 list_add_tail(&com->lc_link, &lfsck->li_list_idle);
5030         }
5031         spin_unlock(&lfsck->li_lock);
5032
5033         if (!init) {
5034                 lo->ll_run_time_phase1 += cfs_duration_sec(cfs_time_current() +
5035                                 HALF_SEC - lfsck->li_time_last_checkpoint);
5036                 lo->ll_time_last_checkpoint = cfs_time_current_sec();
5037                 lo->ll_objs_checked_phase1 += com->lc_new_checked;
5038                 com->lc_new_checked = 0;
5039         }
5040
5041         rc = lfsck_layout_store(env, com);
5042         up_write(&com->lc_sem);
5043
5044         CDEBUG(D_LFSCK, "%s: layout LFSCK master post done: rc = %d\n",
5045                lfsck_lfsck2name(lfsck), rc);
5046
5047         RETURN(rc);
5048 }
5049
5050 static int lfsck_layout_slave_post(const struct lu_env *env,
5051                                    struct lfsck_component *com,
5052                                    int result, bool init)
5053 {
5054         struct lfsck_instance   *lfsck = com->lc_lfsck;
5055         struct lfsck_layout     *lo    = com->lc_file_ram;
5056         int                      rc;
5057         bool                     done  = false;
5058
5059         rc = lfsck_layout_lastid_store(env, com);
5060         if (rc != 0)
5061                 result = rc;
5062
5063         LASSERT(lfsck->li_out_notify != NULL);
5064
5065         down_write(&com->lc_sem);
5066         spin_lock(&lfsck->li_lock);
5067         if (!init)
5068                 lo->ll_pos_last_checkpoint =
5069                                         lfsck->li_pos_current.lp_oit_cookie;
5070         if (result > 0) {
5071                 lo->ll_status = LS_SCANNING_PHASE2;
5072                 lo->ll_flags |= LF_SCANNED_ONCE;
5073                 if (lo->ll_flags & LF_CRASHED_LASTID) {
5074                         done = true;
5075                         lo->ll_flags &= ~LF_CRASHED_LASTID;
5076                 }
5077                 lo->ll_flags &= ~LF_UPGRADE;
5078                 list_del_init(&com->lc_link);
5079                 list_add_tail(&com->lc_link, &lfsck->li_list_double_scan);
5080         } else if (result == 0) {
5081                 lo->ll_status = lfsck->li_status;
5082                 if (lo->ll_status == 0)
5083                         lo->ll_status = LS_STOPPED;
5084                 if (lo->ll_status != LS_PAUSED) {
5085                         list_del_init(&com->lc_link);
5086                         list_add_tail(&com->lc_link, &lfsck->li_list_idle);
5087                 }
5088         } else {
5089                 lo->ll_status = LS_FAILED;
5090                 list_del_init(&com->lc_link);
5091                 list_add_tail(&com->lc_link, &lfsck->li_list_idle);
5092         }
5093         spin_unlock(&lfsck->li_lock);
5094
5095         if (done)
5096                 lfsck->li_out_notify(env, lfsck->li_out_notify_data,
5097                                      LE_LASTID_REBUILT);
5098
5099         if (!init) {
5100                 lo->ll_run_time_phase1 += cfs_duration_sec(cfs_time_current() +
5101                                 HALF_SEC - lfsck->li_time_last_checkpoint);
5102                 lo->ll_time_last_checkpoint = cfs_time_current_sec();
5103                 lo->ll_objs_checked_phase1 += com->lc_new_checked;
5104                 com->lc_new_checked = 0;
5105         }
5106
5107         rc = lfsck_layout_store(env, com);
5108         up_write(&com->lc_sem);
5109
5110         lfsck_layout_slave_notify_master(env, com, LE_PHASE1_DONE, result);
5111
5112         if (result <= 0)
5113                 lfsck_rbtree_cleanup(env, com);
5114
5115         CDEBUG(D_LFSCK, "%s: layout LFSCK slave post done: rc = %d\n",
5116                lfsck_lfsck2name(lfsck), rc);
5117
5118         return rc;
5119 }
5120
5121 static int lfsck_layout_dump(const struct lu_env *env,
5122                              struct lfsck_component *com, struct seq_file *m)
5123 {
5124         struct lfsck_instance   *lfsck = com->lc_lfsck;
5125         struct lfsck_bookmark   *bk    = &lfsck->li_bookmark_ram;
5126         struct lfsck_layout     *lo    = com->lc_file_ram;
5127         int                      rc;
5128
5129         down_read(&com->lc_sem);
5130         seq_printf(m, "name: lfsck_layout\n"
5131                       "magic: %#x\n"
5132                       "version: %d\n"
5133                       "status: %s\n",
5134                       lo->ll_magic,
5135                       bk->lb_version,
5136                       lfsck_status2names(lo->ll_status));
5137
5138         rc = lfsck_bits_dump(m, lo->ll_flags, lfsck_flags_names, "flags");
5139         if (rc < 0)
5140                 goto out;
5141
5142         rc = lfsck_bits_dump(m, bk->lb_param, lfsck_param_names, "param");
5143         if (rc < 0)
5144                 goto out;
5145
5146         rc = lfsck_time_dump(m, lo->ll_time_last_complete,
5147                              "time_since_last_completed");
5148         if (rc < 0)
5149                 goto out;
5150
5151         rc = lfsck_time_dump(m, lo->ll_time_latest_start,
5152                              "time_since_latest_start");
5153         if (rc < 0)
5154                 goto out;
5155
5156         rc = lfsck_time_dump(m, lo->ll_time_last_checkpoint,
5157                              "time_since_last_checkpoint");
5158         if (rc < 0)
5159                 goto out;
5160
5161         seq_printf(m, "latest_start_position: "LPU64"\n"
5162                       "last_checkpoint_position: "LPU64"\n"
5163                       "first_failure_position: "LPU64"\n",
5164                       lo->ll_pos_latest_start,
5165                       lo->ll_pos_last_checkpoint,
5166                       lo->ll_pos_first_inconsistent);
5167
5168         seq_printf(m, "success_count: %u\n"
5169                       "repaired_dangling: "LPU64"\n"
5170                       "repaired_unmatched_pair: "LPU64"\n"
5171                       "repaired_multiple_referenced: "LPU64"\n"
5172                       "repaired_orphan: "LPU64"\n"
5173                       "repaired_inconsistent_owner: "LPU64"\n"
5174                       "repaired_others: "LPU64"\n"
5175                       "skipped: "LPU64"\n"
5176                       "failed_phase1: "LPU64"\n"
5177                       "failed_phase2: "LPU64"\n",
5178                       lo->ll_success_count,
5179                       lo->ll_objs_repaired[LLIT_DANGLING - 1],
5180                       lo->ll_objs_repaired[LLIT_UNMATCHED_PAIR - 1],
5181                       lo->ll_objs_repaired[LLIT_MULTIPLE_REFERENCED - 1],
5182                       lo->ll_objs_repaired[LLIT_ORPHAN - 1],
5183                       lo->ll_objs_repaired[LLIT_INCONSISTENT_OWNER - 1],
5184                       lo->ll_objs_repaired[LLIT_OTHERS - 1],
5185                       lo->ll_objs_skipped,
5186                       lo->ll_objs_failed_phase1,
5187                       lo->ll_objs_failed_phase2);
5188
5189         if (lo->ll_status == LS_SCANNING_PHASE1) {
5190                 __u64 pos;
5191                 const struct dt_it_ops *iops;
5192                 cfs_duration_t duration = cfs_time_current() -
5193                                           lfsck->li_time_last_checkpoint;
5194                 __u64 checked = lo->ll_objs_checked_phase1 +
5195                                 com->lc_new_checked;
5196                 __u64 speed = checked;
5197                 __u64 new_checked = com->lc_new_checked * HZ;
5198                 __u32 rtime = lo->ll_run_time_phase1 +
5199                               cfs_duration_sec(duration + HALF_SEC);
5200
5201                 if (duration != 0)
5202                         do_div(new_checked, duration);
5203                 if (rtime != 0)
5204                         do_div(speed, rtime);
5205                 seq_printf(m, "checked_phase1: "LPU64"\n"
5206                               "checked_phase2: "LPU64"\n"
5207                               "run_time_phase1: %u seconds\n"
5208                               "run_time_phase2: %u seconds\n"
5209                               "average_speed_phase1: "LPU64" items/sec\n"
5210                               "average_speed_phase2: N/A\n"
5211                               "real-time_speed_phase1: "LPU64" items/sec\n"
5212                               "real-time_speed_phase2: N/A\n",
5213                               checked,
5214                               lo->ll_objs_checked_phase2,
5215                               rtime,
5216                               lo->ll_run_time_phase2,
5217                               speed,
5218                               new_checked);
5219
5220                 LASSERT(lfsck->li_di_oit != NULL);
5221
5222                 iops = &lfsck->li_obj_oit->do_index_ops->dio_it;
5223
5224                 /* The low layer otable-based iteration position may NOT
5225                  * exactly match the layout-based directory traversal
5226                  * cookie. Generally, it is not a serious issue. But the
5227                  * caller should NOT make assumption on that. */
5228                 pos = iops->store(env, lfsck->li_di_oit);
5229                 if (!lfsck->li_current_oit_processed)
5230                         pos--;
5231                 seq_printf(m, "current_position: "LPU64"\n", pos);
5232
5233         } else if (lo->ll_status == LS_SCANNING_PHASE2) {
5234                 cfs_duration_t duration = cfs_time_current() -
5235                                           lfsck->li_time_last_checkpoint;
5236                 __u64 checked = lo->ll_objs_checked_phase2 +
5237                                 com->lc_new_checked;
5238                 __u64 speed1 = lo->ll_objs_checked_phase1;
5239                 __u64 speed2 = checked;
5240                 __u64 new_checked = com->lc_new_checked * HZ;
5241                 __u32 rtime = lo->ll_run_time_phase2 +
5242                               cfs_duration_sec(duration + HALF_SEC);
5243
5244                 if (duration != 0)
5245                         do_div(new_checked, duration);
5246                 if (lo->ll_run_time_phase1 != 0)
5247                         do_div(speed1, lo->ll_run_time_phase1);
5248                 if (rtime != 0)
5249                         do_div(speed2, rtime);
5250                 rc = seq_printf(m, "checked_phase1: "LPU64"\n"
5251                                 "checked_phase2: "LPU64"\n"
5252                                 "run_time_phase1: %u seconds\n"
5253                                 "run_time_phase2: %u seconds\n"
5254                                 "average_speed_phase1: "LPU64" items/sec\n"
5255                                 "average_speed_phase2: "LPU64" items/sec\n"
5256                                 "real-time_speed_phase1: N/A\n"
5257                                 "real-time_speed_phase2: "LPU64" items/sec\n"
5258                                 "current_position: "DFID"\n",
5259                                 lo->ll_objs_checked_phase1,
5260                                 checked,
5261                                 lo->ll_run_time_phase1,
5262                                 rtime,
5263                                 speed1,
5264                                 speed2,
5265                                 new_checked,
5266                                 PFID(&com->lc_fid_latest_scanned_phase2));
5267                 if (rc <= 0)
5268                         goto out;
5269
5270         } else {
5271                 __u64 speed1 = lo->ll_objs_checked_phase1;
5272                 __u64 speed2 = lo->ll_objs_checked_phase2;
5273
5274                 if (lo->ll_run_time_phase1 != 0)
5275                         do_div(speed1, lo->ll_run_time_phase1);
5276                 if (lo->ll_run_time_phase2 != 0)
5277                         do_div(speed2, lo->ll_run_time_phase2);
5278                 seq_printf(m, "checked_phase1: "LPU64"\n"
5279                            "checked_phase2: "LPU64"\n"
5280                            "run_time_phase1: %u seconds\n"
5281                            "run_time_phase2: %u seconds\n"
5282                            "average_speed_phase1: "LPU64" items/sec\n"
5283                            "average_speed_phase2: "LPU64" objs/sec\n"
5284                            "real-time_speed_phase1: N/A\n"
5285                            "real-time_speed_phase2: N/A\n"
5286                            "current_position: N/A\n",
5287                            lo->ll_objs_checked_phase1,
5288                            lo->ll_objs_checked_phase2,
5289                            lo->ll_run_time_phase1,
5290                            lo->ll_run_time_phase2,
5291                            speed1,
5292                            speed2);
5293         }
5294 out:
5295         up_read(&com->lc_sem);
5296
5297         return rc;
5298 }
5299
5300 static int lfsck_layout_master_double_scan(const struct lu_env *env,
5301                                            struct lfsck_component *com)
5302 {
5303         struct lfsck_layout_master_data *llmd    = com->lc_data;
5304         struct ptlrpc_thread            *mthread = &com->lc_lfsck->li_thread;
5305         struct ptlrpc_thread            *athread = &llmd->llmd_thread;
5306         struct lfsck_layout             *lo      = com->lc_file_ram;
5307         struct l_wait_info               lwi     = { 0 };
5308
5309         if (unlikely(lo->ll_status != LS_SCANNING_PHASE2))
5310                 return 0;
5311
5312         llmd->llmd_to_double_scan = 1;
5313         wake_up_all(&athread->t_ctl_waitq);
5314         l_wait_event(mthread->t_ctl_waitq,
5315                      llmd->llmd_in_double_scan ||
5316                      thread_is_stopped(athread),
5317                      &lwi);
5318         if (llmd->llmd_assistant_status < 0)
5319                 return llmd->llmd_assistant_status;
5320
5321         return 0;
5322 }
5323
5324 static int lfsck_layout_slave_double_scan(const struct lu_env *env,
5325                                           struct lfsck_component *com)
5326 {
5327         struct lfsck_instance           *lfsck  = com->lc_lfsck;
5328         struct lfsck_layout_slave_data  *llsd   = com->lc_data;
5329         struct lfsck_layout             *lo     = com->lc_file_ram;
5330         struct ptlrpc_thread            *thread = &lfsck->li_thread;
5331         int                              rc;
5332         ENTRY;
5333
5334         if (unlikely(lo->ll_status != LS_SCANNING_PHASE2)) {
5335                 lfsck_rbtree_cleanup(env, com);
5336                 lfsck_layout_slave_notify_master(env, com, LE_PHASE2_DONE, 0);
5337                 RETURN(0);
5338         }
5339
5340         CDEBUG(D_LFSCK, "%s: layout LFSCK slave phase2 scan start\n",
5341                lfsck_lfsck2name(lfsck));
5342
5343         atomic_inc(&lfsck->li_double_scan_count);
5344
5345         com->lc_new_checked = 0;
5346         com->lc_new_scanned = 0;
5347         com->lc_time_last_checkpoint = cfs_time_current();
5348         com->lc_time_next_checkpoint = com->lc_time_last_checkpoint +
5349                                 cfs_time_seconds(LFSCK_CHECKPOINT_INTERVAL);
5350
5351         while (1) {
5352                 struct l_wait_info lwi = LWI_TIMEOUT(cfs_time_seconds(30),
5353                                                      NULL, NULL);
5354
5355                 rc = lfsck_layout_slave_query_master(env, com);
5356                 if (list_empty(&llsd->llsd_master_list)) {
5357                         if (unlikely(!thread_is_running(thread)))
5358                                 rc = 0;
5359                         else
5360                                 rc = 1;
5361
5362                         GOTO(done, rc);
5363                 }
5364
5365                 if (rc < 0)
5366                         GOTO(done, rc);
5367
5368                 rc = l_wait_event(thread->t_ctl_waitq,
5369                                   !thread_is_running(thread) ||
5370                                   list_empty(&llsd->llsd_master_list),
5371                                   &lwi);
5372                 if (unlikely(!thread_is_running(thread)))
5373                         GOTO(done, rc = 0);
5374
5375                 if (rc == -ETIMEDOUT)
5376                         continue;
5377
5378                 GOTO(done, rc = (rc < 0 ? rc : 1));
5379         }
5380
5381 done:
5382         rc = lfsck_layout_double_scan_result(env, com, rc);
5383
5384         lfsck_rbtree_cleanup(env, com);
5385         lfsck_layout_slave_notify_master(env, com, LE_PHASE2_DONE, rc);
5386         if (atomic_dec_and_test(&lfsck->li_double_scan_count))
5387                 wake_up_all(&lfsck->li_thread.t_ctl_waitq);
5388
5389         CDEBUG(D_LFSCK, "%s: layout LFSCK slave phase2 scan finished, "
5390                "status %d: rc = %d\n",
5391                lfsck_lfsck2name(lfsck), lo->ll_status, rc);
5392
5393         return rc;
5394 }
5395
5396 static void lfsck_layout_master_data_release(const struct lu_env *env,
5397                                              struct lfsck_component *com)
5398 {
5399         struct lfsck_layout_master_data *llmd   = com->lc_data;
5400         struct lfsck_instance           *lfsck  = com->lc_lfsck;
5401         struct lfsck_tgt_descs          *ltds;
5402         struct lfsck_tgt_desc           *ltd;
5403         struct lfsck_tgt_desc           *next;
5404
5405         LASSERT(llmd != NULL);
5406         LASSERT(thread_is_init(&llmd->llmd_thread) ||
5407                 thread_is_stopped(&llmd->llmd_thread));
5408         LASSERT(list_empty(&llmd->llmd_req_list));
5409
5410         com->lc_data = NULL;
5411
5412         ltds = &lfsck->li_ost_descs;
5413         spin_lock(&ltds->ltd_lock);
5414         list_for_each_entry_safe(ltd, next, &llmd->llmd_ost_phase1_list,
5415                                  ltd_layout_phase_list) {
5416                 list_del_init(&ltd->ltd_layout_phase_list);
5417         }
5418         list_for_each_entry_safe(ltd, next, &llmd->llmd_ost_phase2_list,
5419                                  ltd_layout_phase_list) {
5420                 list_del_init(&ltd->ltd_layout_phase_list);
5421         }
5422         list_for_each_entry_safe(ltd, next, &llmd->llmd_ost_list,
5423                                  ltd_layout_list) {
5424                 list_del_init(&ltd->ltd_layout_list);
5425         }
5426         spin_unlock(&ltds->ltd_lock);
5427
5428         ltds = &lfsck->li_mdt_descs;
5429         spin_lock(&ltds->ltd_lock);
5430         list_for_each_entry_safe(ltd, next, &llmd->llmd_mdt_phase1_list,
5431                                  ltd_layout_phase_list) {
5432                 list_del_init(&ltd->ltd_layout_phase_list);
5433         }
5434         list_for_each_entry_safe(ltd, next, &llmd->llmd_mdt_phase2_list,
5435                                  ltd_layout_phase_list) {
5436                 list_del_init(&ltd->ltd_layout_phase_list);
5437         }
5438         list_for_each_entry_safe(ltd, next, &llmd->llmd_mdt_list,
5439                                  ltd_layout_list) {
5440                 list_del_init(&ltd->ltd_layout_list);
5441         }
5442         spin_unlock(&ltds->ltd_lock);
5443
5444         OBD_FREE_PTR(llmd);
5445 }
5446
5447 static void lfsck_layout_slave_data_release(const struct lu_env *env,
5448                                             struct lfsck_component *com)
5449 {
5450         struct lfsck_layout_slave_data   *llsd  = com->lc_data;
5451         struct lfsck_layout_seq          *lls;
5452         struct lfsck_layout_seq          *next;
5453         struct lfsck_layout_slave_target *llst;
5454         struct lfsck_layout_slave_target *tmp;
5455
5456         LASSERT(llsd != NULL);
5457
5458         list_for_each_entry_safe(lls, next, &llsd->llsd_seq_list,
5459                                      lls_list) {
5460                 list_del_init(&lls->lls_list);
5461                 lfsck_object_put(env, lls->lls_lastid_obj);
5462                 OBD_FREE_PTR(lls);
5463         }
5464
5465         list_for_each_entry_safe(llst, tmp, &llsd->llsd_master_list,
5466                                  llst_list) {
5467                 list_del_init(&llst->llst_list);
5468                 OBD_FREE_PTR(llst);
5469         }
5470
5471         lfsck_rbtree_cleanup(env, com);
5472         com->lc_data = NULL;
5473         OBD_FREE_PTR(llsd);
5474 }
5475
5476 static void lfsck_layout_master_quit(const struct lu_env *env,
5477                                      struct lfsck_component *com)
5478 {
5479         struct lfsck_layout_master_data *llmd    = com->lc_data;
5480         struct ptlrpc_thread            *mthread = &com->lc_lfsck->li_thread;
5481         struct ptlrpc_thread            *athread = &llmd->llmd_thread;
5482         struct l_wait_info               lwi     = { 0 };
5483
5484         llmd->llmd_exit = 1;
5485         wake_up_all(&athread->t_ctl_waitq);
5486         l_wait_event(mthread->t_ctl_waitq,
5487                      thread_is_init(athread) ||
5488                      thread_is_stopped(athread),
5489                      &lwi);
5490 }
5491
5492 static void lfsck_layout_slave_quit(const struct lu_env *env,
5493                                     struct lfsck_component *com)
5494 {
5495         lfsck_rbtree_cleanup(env, com);
5496 }
5497
5498 static int lfsck_layout_master_in_notify(const struct lu_env *env,
5499                                          struct lfsck_component *com,
5500                                          struct lfsck_request *lr)
5501 {
5502         struct lfsck_instance           *lfsck = com->lc_lfsck;
5503         struct lfsck_layout             *lo    = com->lc_file_ram;
5504         struct lfsck_layout_master_data *llmd  = com->lc_data;
5505         struct lfsck_tgt_descs          *ltds;
5506         struct lfsck_tgt_desc           *ltd;
5507         bool                             fail  = false;
5508         ENTRY;
5509
5510         if (lr->lr_event == LE_PAIRS_VERIFY) {
5511                 int rc;
5512
5513                 rc = lfsck_layout_master_check_pairs(env, com, &lr->lr_fid,
5514                                                      &lr->lr_fid2);
5515
5516                 RETURN(rc);
5517         }
5518
5519         CDEBUG(D_LFSCK, "%s: layout LFSCK master handle notify %u "
5520                "from %s %x, status %d\n", lfsck_lfsck2name(lfsck),
5521                lr->lr_event, (lr->lr_flags & LEF_TO_OST) ? "OST" : "MDT",
5522                lr->lr_index, lr->lr_status);
5523
5524         if (lr->lr_event != LE_PHASE1_DONE &&
5525             lr->lr_event != LE_PHASE2_DONE &&
5526             lr->lr_event != LE_PEER_EXIT)
5527                 RETURN(-EINVAL);
5528
5529         if (lr->lr_flags & LEF_FROM_OST)
5530                 ltds = &lfsck->li_ost_descs;
5531         else
5532                 ltds = &lfsck->li_mdt_descs;
5533         spin_lock(&ltds->ltd_lock);
5534         ltd = LTD_TGT(ltds, lr->lr_index);
5535         if (ltd == NULL) {
5536                 spin_unlock(&ltds->ltd_lock);
5537
5538                 RETURN(-ENXIO);
5539         }
5540
5541         list_del_init(&ltd->ltd_layout_phase_list);
5542         switch (lr->lr_event) {
5543         case LE_PHASE1_DONE:
5544                 if (lr->lr_status <= 0) {
5545                         ltd->ltd_layout_done = 1;
5546                         list_del_init(&ltd->ltd_layout_list);
5547                         lo->ll_flags |= LF_INCOMPLETE;
5548                         fail = true;
5549                         break;
5550                 }
5551
5552                 if (lr->lr_flags & LEF_FROM_OST) {
5553                         if (list_empty(&ltd->ltd_layout_list))
5554                                 list_add_tail(&ltd->ltd_layout_list,
5555                                               &llmd->llmd_ost_list);
5556                         list_add_tail(&ltd->ltd_layout_phase_list,
5557                                       &llmd->llmd_ost_phase2_list);
5558                 } else {
5559                         if (list_empty(&ltd->ltd_layout_list))
5560                                 list_add_tail(&ltd->ltd_layout_list,
5561                                               &llmd->llmd_mdt_list);
5562                         list_add_tail(&ltd->ltd_layout_phase_list,
5563                                       &llmd->llmd_mdt_phase2_list);
5564                 }
5565                 break;
5566         case LE_PHASE2_DONE:
5567                 ltd->ltd_layout_done = 1;
5568                 list_del_init(&ltd->ltd_layout_list);
5569                 break;
5570         case LE_PEER_EXIT:
5571                 fail = true;
5572                 ltd->ltd_layout_done = 1;
5573                 list_del_init(&ltd->ltd_layout_list);
5574                 if (!(lfsck->li_bookmark_ram.lb_param & LPF_FAILOUT))
5575                         lo->ll_flags |= LF_INCOMPLETE;
5576                 break;
5577         default:
5578                 break;
5579         }
5580         spin_unlock(&ltds->ltd_lock);
5581
5582         if (fail && lfsck->li_bookmark_ram.lb_param & LPF_FAILOUT) {
5583                 struct lfsck_stop *stop = &lfsck_env_info(env)->lti_stop;
5584
5585                 memset(stop, 0, sizeof(*stop));
5586                 stop->ls_status = lr->lr_status;
5587                 stop->ls_flags = lr->lr_param & ~LPF_BROADCAST;
5588                 lfsck_stop(env, lfsck->li_bottom, stop);
5589         } else if (lfsck_layout_master_to_orphan(llmd)) {
5590                 wake_up_all(&llmd->llmd_thread.t_ctl_waitq);
5591         }
5592
5593         RETURN(0);
5594 }
5595
5596 static int lfsck_layout_slave_in_notify(const struct lu_env *env,
5597                                         struct lfsck_component *com,
5598                                         struct lfsck_request *lr)
5599 {
5600         struct lfsck_instance            *lfsck = com->lc_lfsck;
5601         struct lfsck_layout_slave_data   *llsd  = com->lc_data;
5602         struct lfsck_layout_slave_target *llst;
5603         int                               rc;
5604         ENTRY;
5605
5606         switch (lr->lr_event) {
5607         case LE_FID_ACCESSED:
5608                 lfsck_rbtree_update_bitmap(env, com, &lr->lr_fid, true);
5609                 RETURN(0);
5610         case LE_CONDITIONAL_DESTROY:
5611                 rc = lfsck_layout_slave_conditional_destroy(env, com, lr);
5612                 RETURN(rc);
5613         case LE_PAIRS_VERIFY: {
5614                 lr->lr_status = LPVS_INIT;
5615                 /* Firstly, if the MDT-object which is claimed via OST-object
5616                  * local stored PFID xattr recognizes the OST-object, then it
5617                  * must be that the client given PFID is wrong. */
5618                 rc = lfsck_layout_slave_check_pairs(env, com, &lr->lr_fid,
5619                                                     &lr->lr_fid3);
5620                 if (rc <= 0)
5621                         RETURN(0);
5622
5623                 lr->lr_status = LPVS_INCONSISTENT;
5624                 /* The OST-object local stored PFID xattr is stale. We need to
5625                  * check whether the MDT-object that is claimed via the client
5626                  * given PFID information recognizes the OST-object or not. If
5627                  * matches, then need to update the OST-object's PFID xattr. */
5628                 rc = lfsck_layout_slave_check_pairs(env, com, &lr->lr_fid,
5629                                                     &lr->lr_fid2);
5630                 /* For rc < 0 case:
5631                  * We are not sure whether the client given PFID information
5632                  * is correct or not, do nothing to avoid improper fixing.
5633                  *
5634                  * For rc > 0 case:
5635                  * The client given PFID information is also invalid, we can
5636                  * NOT fix the OST-object inconsistency.
5637                  */
5638                 if (rc != 0)
5639                         RETURN(rc);
5640
5641                 lr->lr_status = LPVS_INCONSISTENT_TOFIX;
5642                 rc = lfsck_layout_slave_repair_pfid(env, com, lr);
5643
5644                 RETURN(rc);
5645         }
5646         case LE_PHASE2_DONE:
5647         case LE_PEER_EXIT:
5648                 CDEBUG(D_LFSCK, "%s: layout LFSCK slave handle notify %u "
5649                        "from MDT %x, status %d\n", lfsck_lfsck2name(lfsck),
5650                        lr->lr_event, lr->lr_index, lr->lr_status);
5651                 break;
5652         default:
5653                 RETURN(-EINVAL);
5654         }
5655
5656         llst = lfsck_layout_llst_find_and_del(llsd, lr->lr_index, true);
5657         if (llst == NULL)
5658                 RETURN(-ENXIO);
5659
5660         lfsck_layout_llst_put(llst);
5661         if (list_empty(&llsd->llsd_master_list))
5662                 wake_up_all(&lfsck->li_thread.t_ctl_waitq);
5663
5664         if (lr->lr_event == LE_PEER_EXIT &&
5665             lfsck->li_bookmark_ram.lb_param & LPF_FAILOUT) {
5666                 struct lfsck_stop *stop = &lfsck_env_info(env)->lti_stop;
5667
5668                 memset(stop, 0, sizeof(*stop));
5669                 stop->ls_status = lr->lr_status;
5670                 stop->ls_flags = lr->lr_param & ~LPF_BROADCAST;
5671                 lfsck_stop(env, lfsck->li_bottom, stop);
5672         }
5673
5674         RETURN(0);
5675 }
5676
5677 static int lfsck_layout_query(const struct lu_env *env,
5678                               struct lfsck_component *com)
5679 {
5680         struct lfsck_layout *lo = com->lc_file_ram;
5681
5682         return lo->ll_status;
5683 }
5684
5685 static int lfsck_layout_master_stop_notify(const struct lu_env *env,
5686                                            struct lfsck_component *com,
5687                                            struct lfsck_tgt_descs *ltds,
5688                                            struct lfsck_tgt_desc *ltd,
5689                                            struct ptlrpc_request_set *set)
5690 {
5691         struct lfsck_thread_info          *info  = lfsck_env_info(env);
5692         struct lfsck_async_interpret_args *laia  = &info->lti_laia;
5693         struct lfsck_request              *lr    = &info->lti_lr;
5694         struct lfsck_instance             *lfsck = com->lc_lfsck;
5695         int                                rc;
5696
5697         spin_lock(&ltds->ltd_lock);
5698         if (list_empty(&ltd->ltd_layout_list)) {
5699                 LASSERT(list_empty(&ltd->ltd_layout_phase_list));
5700                 spin_unlock(&ltds->ltd_lock);
5701
5702                 return 0;
5703         }
5704
5705         list_del_init(&ltd->ltd_layout_phase_list);
5706         list_del_init(&ltd->ltd_layout_list);
5707         spin_unlock(&ltds->ltd_lock);
5708
5709         memset(lr, 0, sizeof(*lr));
5710         lr->lr_index = lfsck_dev_idx(lfsck->li_bottom);
5711         lr->lr_event = LE_PEER_EXIT;
5712         lr->lr_active = LFSCK_TYPE_LAYOUT;
5713         lr->lr_status = LS_CO_PAUSED;
5714         if (ltds == &lfsck->li_ost_descs)
5715                 lr->lr_flags = LEF_TO_OST;
5716
5717         laia->laia_com = com;
5718         laia->laia_ltds = ltds;
5719         atomic_inc(&ltd->ltd_ref);
5720         laia->laia_ltd = ltd;
5721         laia->laia_lr = lr;
5722         laia->laia_shared = 0;
5723
5724         rc = lfsck_async_request(env, ltd->ltd_exp, lr, set,
5725                                  lfsck_layout_master_async_interpret,
5726                                  laia, LFSCK_NOTIFY);
5727         if (rc != 0) {
5728                 CDEBUG(D_LFSCK, "%s: layout LFSCK fail to notify %s %x "
5729                        "for co-stop: rc = %d\n",
5730                        lfsck_lfsck2name(lfsck),
5731                        (lr->lr_flags & LEF_TO_OST) ? "OST" : "MDT",
5732                        ltd->ltd_index, rc);
5733                 lfsck_tgt_put(ltd);
5734         }
5735
5736         return rc;
5737 }
5738
5739 /* with lfsck::li_lock held */
5740 static int lfsck_layout_slave_join(const struct lu_env *env,
5741                                    struct lfsck_component *com,
5742                                    struct lfsck_start_param *lsp)
5743 {
5744         struct lfsck_instance            *lfsck = com->lc_lfsck;
5745         struct lfsck_layout_slave_data   *llsd  = com->lc_data;
5746         struct lfsck_layout_slave_target *llst;
5747         struct lfsck_start               *start = lsp->lsp_start;
5748         int                               rc    = 0;
5749         ENTRY;
5750
5751         if (start == NULL || !(start->ls_flags & LPF_ORPHAN))
5752                 RETURN(0);
5753
5754         if (!lsp->lsp_index_valid)
5755                 RETURN(-EINVAL);
5756
5757         /* If someone is running the LFSCK without orphan handling,
5758          * it will not maintain the object accessing rbtree. So we
5759          * cannot join it for orphan handling. */
5760         if (!llsd->llsd_rbtree_valid)
5761                 RETURN(-EBUSY);
5762
5763         spin_unlock(&lfsck->li_lock);
5764         rc = lfsck_layout_llst_add(llsd, lsp->lsp_index);
5765         spin_lock(&lfsck->li_lock);
5766         if (rc == 0 && !thread_is_running(&lfsck->li_thread)) {
5767                 spin_unlock(&lfsck->li_lock);
5768                 llst = lfsck_layout_llst_find_and_del(llsd, lsp->lsp_index,
5769                                                       true);
5770                 if (llst != NULL)
5771                         lfsck_layout_llst_put(llst);
5772                 spin_lock(&lfsck->li_lock);
5773                 rc = -EAGAIN;
5774         }
5775
5776         RETURN(rc);
5777 }
5778
5779 static struct lfsck_operations lfsck_layout_master_ops = {
5780         .lfsck_reset            = lfsck_layout_reset,
5781         .lfsck_fail             = lfsck_layout_fail,
5782         .lfsck_checkpoint       = lfsck_layout_master_checkpoint,
5783         .lfsck_prep             = lfsck_layout_master_prep,
5784         .lfsck_exec_oit         = lfsck_layout_master_exec_oit,
5785         .lfsck_exec_dir         = lfsck_layout_exec_dir,
5786         .lfsck_post             = lfsck_layout_master_post,
5787         .lfsck_interpret        = lfsck_layout_master_async_interpret,
5788         .lfsck_dump             = lfsck_layout_dump,
5789         .lfsck_double_scan      = lfsck_layout_master_double_scan,
5790         .lfsck_data_release     = lfsck_layout_master_data_release,
5791         .lfsck_quit             = lfsck_layout_master_quit,
5792         .lfsck_in_notify        = lfsck_layout_master_in_notify,
5793         .lfsck_query            = lfsck_layout_query,
5794         .lfsck_stop_notify      = lfsck_layout_master_stop_notify,
5795 };
5796
5797 static struct lfsck_operations lfsck_layout_slave_ops = {
5798         .lfsck_reset            = lfsck_layout_reset,
5799         .lfsck_fail             = lfsck_layout_fail,
5800         .lfsck_checkpoint       = lfsck_layout_slave_checkpoint,
5801         .lfsck_prep             = lfsck_layout_slave_prep,
5802         .lfsck_exec_oit         = lfsck_layout_slave_exec_oit,
5803         .lfsck_exec_dir         = lfsck_layout_exec_dir,
5804         .lfsck_post             = lfsck_layout_slave_post,
5805         .lfsck_dump             = lfsck_layout_dump,
5806         .lfsck_double_scan      = lfsck_layout_slave_double_scan,
5807         .lfsck_data_release     = lfsck_layout_slave_data_release,
5808         .lfsck_quit             = lfsck_layout_slave_quit,
5809         .lfsck_in_notify        = lfsck_layout_slave_in_notify,
5810         .lfsck_query            = lfsck_layout_query,
5811         .lfsck_join             = lfsck_layout_slave_join,
5812 };
5813
5814 int lfsck_layout_setup(const struct lu_env *env, struct lfsck_instance *lfsck)
5815 {
5816         struct lfsck_component  *com;
5817         struct lfsck_layout     *lo;
5818         struct dt_object        *root = NULL;
5819         struct dt_object        *obj;
5820         int                      rc;
5821         ENTRY;
5822
5823         OBD_ALLOC_PTR(com);
5824         if (com == NULL)
5825                 RETURN(-ENOMEM);
5826
5827         INIT_LIST_HEAD(&com->lc_link);
5828         INIT_LIST_HEAD(&com->lc_link_dir);
5829         init_rwsem(&com->lc_sem);
5830         atomic_set(&com->lc_ref, 1);
5831         com->lc_lfsck = lfsck;
5832         com->lc_type = LFSCK_TYPE_LAYOUT;
5833         if (lfsck->li_master) {
5834                 struct lfsck_layout_master_data *llmd;
5835
5836                 com->lc_ops = &lfsck_layout_master_ops;
5837                 OBD_ALLOC_PTR(llmd);
5838                 if (llmd == NULL)
5839                         GOTO(out, rc = -ENOMEM);
5840
5841                 INIT_LIST_HEAD(&llmd->llmd_req_list);
5842                 spin_lock_init(&llmd->llmd_lock);
5843                 INIT_LIST_HEAD(&llmd->llmd_ost_list);
5844                 INIT_LIST_HEAD(&llmd->llmd_ost_phase1_list);
5845                 INIT_LIST_HEAD(&llmd->llmd_ost_phase2_list);
5846                 INIT_LIST_HEAD(&llmd->llmd_mdt_list);
5847                 INIT_LIST_HEAD(&llmd->llmd_mdt_phase1_list);
5848                 INIT_LIST_HEAD(&llmd->llmd_mdt_phase2_list);
5849                 init_waitqueue_head(&llmd->llmd_thread.t_ctl_waitq);
5850                 com->lc_data = llmd;
5851         } else {
5852                 struct lfsck_layout_slave_data *llsd;
5853
5854                 com->lc_ops = &lfsck_layout_slave_ops;
5855                 OBD_ALLOC_PTR(llsd);
5856                 if (llsd == NULL)
5857                         GOTO(out, rc = -ENOMEM);
5858
5859                 INIT_LIST_HEAD(&llsd->llsd_seq_list);
5860                 INIT_LIST_HEAD(&llsd->llsd_master_list);
5861                 spin_lock_init(&llsd->llsd_lock);
5862                 llsd->llsd_rb_root = RB_ROOT;
5863                 rwlock_init(&llsd->llsd_rb_lock);
5864                 com->lc_data = llsd;
5865         }
5866         com->lc_file_size = sizeof(*lo);
5867         OBD_ALLOC(com->lc_file_ram, com->lc_file_size);
5868         if (com->lc_file_ram == NULL)
5869                 GOTO(out, rc = -ENOMEM);
5870
5871         OBD_ALLOC(com->lc_file_disk, com->lc_file_size);
5872         if (com->lc_file_disk == NULL)
5873                 GOTO(out, rc = -ENOMEM);
5874
5875         root = dt_locate(env, lfsck->li_bottom, &lfsck->li_local_root_fid);
5876         if (IS_ERR(root))
5877                 GOTO(out, rc = PTR_ERR(root));
5878
5879         if (unlikely(!dt_try_as_dir(env, root)))
5880                 GOTO(out, rc = -ENOTDIR);
5881
5882         obj = local_file_find_or_create(env, lfsck->li_los, root,
5883                                         lfsck_layout_name,
5884                                         S_IFREG | S_IRUGO | S_IWUSR);
5885         if (IS_ERR(obj))
5886                 GOTO(out, rc = PTR_ERR(obj));
5887
5888         com->lc_obj = obj;
5889         rc = lfsck_layout_load(env, com);
5890         if (rc > 0)
5891                 rc = lfsck_layout_reset(env, com, true);
5892         else if (rc == -ENOENT)
5893                 rc = lfsck_layout_init(env, com);
5894
5895         if (rc != 0)
5896                 GOTO(out, rc);
5897
5898         lo = com->lc_file_ram;
5899         switch (lo->ll_status) {
5900         case LS_INIT:
5901         case LS_COMPLETED:
5902         case LS_FAILED:
5903         case LS_STOPPED:
5904         case LS_PARTIAL:
5905                 spin_lock(&lfsck->li_lock);
5906                 list_add_tail(&com->lc_link, &lfsck->li_list_idle);
5907                 spin_unlock(&lfsck->li_lock);
5908                 break;
5909         default:
5910                 CERROR("%s: unknown lfsck_layout status %d\n",
5911                        lfsck_lfsck2name(lfsck), lo->ll_status);
5912                 /* fall through */
5913         case LS_SCANNING_PHASE1:
5914         case LS_SCANNING_PHASE2:
5915                 /* No need to store the status to disk right now.
5916                  * If the system crashed before the status stored,
5917                  * it will be loaded back when next time. */
5918                 lo->ll_status = LS_CRASHED;
5919                 lo->ll_flags |= LF_INCOMPLETE;
5920                 /* fall through */
5921         case LS_PAUSED:
5922         case LS_CRASHED:
5923         case LS_CO_FAILED:
5924         case LS_CO_STOPPED:
5925         case LS_CO_PAUSED:
5926                 spin_lock(&lfsck->li_lock);
5927                 list_add_tail(&com->lc_link, &lfsck->li_list_scan);
5928                 spin_unlock(&lfsck->li_lock);
5929                 break;
5930         }
5931
5932         if (lo->ll_flags & LF_CRASHED_LASTID) {
5933                 LASSERT(lfsck->li_out_notify != NULL);
5934
5935                 lfsck->li_out_notify(env, lfsck->li_out_notify_data,
5936                                      LE_LASTID_REBUILDING);
5937         }
5938
5939         GOTO(out, rc = 0);
5940
5941 out:
5942         if (root != NULL && !IS_ERR(root))
5943                 lu_object_put(env, &root->do_lu);
5944
5945         if (rc != 0) {
5946                 lfsck_component_cleanup(env, com);
5947                 CERROR("%s: fail to init layout LFSCK component: rc = %d\n",
5948                        lfsck_lfsck2name(lfsck), rc);
5949         }
5950
5951         return rc;
5952 }
5953
5954 struct lfsck_orphan_it {
5955         struct lfsck_component           *loi_com;
5956         struct lfsck_rbtree_node         *loi_lrn;
5957         struct lfsck_layout_slave_target *loi_llst;
5958         struct lu_fid                     loi_key;
5959         struct lu_orphan_rec              loi_rec;
5960         __u64                             loi_hash;
5961         unsigned int                      loi_over:1;
5962 };
5963
5964 static int lfsck_fid_match_idx(const struct lu_env *env,
5965                                struct lfsck_instance *lfsck,
5966                                const struct lu_fid *fid, int idx)
5967 {
5968         struct seq_server_site  *ss;
5969         struct lu_server_fld    *sf;
5970         struct lu_seq_range      range  = { 0 };
5971         int                      rc;
5972
5973         /* All abnormal cases will be returned to MDT0. */
5974         if (!fid_is_norm(fid)) {
5975                 if (idx == 0)
5976                         return 1;
5977
5978                 return 0;
5979         }
5980
5981         ss = lu_site2seq(lfsck->li_bottom->dd_lu_dev.ld_site);
5982         if (unlikely(ss == NULL))
5983                 return -ENOTCONN;
5984
5985         sf = ss->ss_server_fld;
5986         LASSERT(sf != NULL);
5987
5988         fld_range_set_any(&range);
5989         rc = fld_server_lookup(env, sf, fid_seq(fid), &range);
5990         if (rc != 0)
5991                 return rc;
5992
5993         if (!fld_range_is_mdt(&range))
5994                 return -EINVAL;
5995
5996         if (range.lsr_index == idx)
5997                 return 1;
5998
5999         return 0;
6000 }
6001
6002 static void lfsck_layout_destroy_orphan(const struct lu_env *env,
6003                                         struct dt_device *dev,
6004                                         struct dt_object *obj)
6005 {
6006         struct thandle *handle;
6007         int             rc;
6008         ENTRY;
6009
6010         handle = dt_trans_create(env, dev);
6011         if (IS_ERR(handle))
6012                 RETURN_EXIT;
6013
6014         rc = dt_declare_ref_del(env, obj, handle);
6015         if (rc != 0)
6016                 GOTO(stop, rc);
6017
6018         rc = dt_declare_destroy(env, obj, handle);
6019         if (rc != 0)
6020                 GOTO(stop, rc);
6021
6022         rc = dt_trans_start_local(env, dev, handle);
6023         if (rc != 0)
6024                 GOTO(stop, rc);
6025
6026         dt_write_lock(env, obj, 0);
6027         rc = dt_ref_del(env, obj, handle);
6028         if (rc == 0)
6029                 rc = dt_destroy(env, obj, handle);
6030         dt_write_unlock(env, obj);
6031
6032         GOTO(stop, rc);
6033
6034 stop:
6035         dt_trans_stop(env, dev, handle);
6036
6037         CDEBUG(D_LFSCK, "destroy orphan OST-object "DFID": rc = %d\n",
6038                PFID(lfsck_dto2fid(obj)), rc);
6039
6040         RETURN_EXIT;
6041 }
6042
6043 static int lfsck_orphan_index_lookup(const struct lu_env *env,
6044                                      struct dt_object *dt,
6045                                      struct dt_rec *rec,
6046                                      const struct dt_key *key,
6047                                      struct lustre_capa *capa)
6048 {
6049         return -EOPNOTSUPP;
6050 }
6051
6052 static int lfsck_orphan_index_declare_insert(const struct lu_env *env,
6053                                              struct dt_object *dt,
6054                                              const struct dt_rec *rec,
6055                                              const struct dt_key *key,
6056                                              struct thandle *handle)
6057 {
6058         return -EOPNOTSUPP;
6059 }
6060
6061 static int lfsck_orphan_index_insert(const struct lu_env *env,
6062                                      struct dt_object *dt,
6063                                      const struct dt_rec *rec,
6064                                      const struct dt_key *key,
6065                                      struct thandle *handle,
6066                                      struct lustre_capa *capa,
6067                                      int ignore_quota)
6068 {
6069         return -EOPNOTSUPP;
6070 }
6071
6072 static int lfsck_orphan_index_declare_delete(const struct lu_env *env,
6073                                              struct dt_object *dt,
6074                                              const struct dt_key *key,
6075                                              struct thandle *handle)
6076 {
6077         return -EOPNOTSUPP;
6078 }
6079
6080 static int lfsck_orphan_index_delete(const struct lu_env *env,
6081                                      struct dt_object *dt,
6082                                      const struct dt_key *key,
6083                                      struct thandle *handle,
6084                                      struct lustre_capa *capa)
6085 {
6086         return -EOPNOTSUPP;
6087 }
6088
6089 static struct dt_it *lfsck_orphan_it_init(const struct lu_env *env,
6090                                           struct dt_object *dt,
6091                                           __u32 attr,
6092                                           struct lustre_capa *capa)
6093 {
6094         struct dt_device                *dev    = lu2dt_dev(dt->do_lu.lo_dev);
6095         struct lfsck_instance           *lfsck;
6096         struct lfsck_component          *com    = NULL;
6097         struct lfsck_layout_slave_data  *llsd;
6098         struct lfsck_orphan_it          *it     = NULL;
6099         int                              rc     = 0;
6100         ENTRY;
6101
6102         lfsck = lfsck_instance_find(dev, true, false);
6103         if (unlikely(lfsck == NULL))
6104                 RETURN(ERR_PTR(-ENXIO));
6105
6106         com = lfsck_component_find(lfsck, LFSCK_TYPE_LAYOUT);
6107         if (unlikely(com == NULL))
6108                 GOTO(out, rc = -ENOENT);
6109
6110         llsd = com->lc_data;
6111         if (!llsd->llsd_rbtree_valid)
6112                 GOTO(out, rc = -ESRCH);
6113
6114         OBD_ALLOC_PTR(it);
6115         if (it == NULL)
6116                 GOTO(out, rc = -ENOMEM);
6117
6118         it->loi_llst = lfsck_layout_llst_find_and_del(llsd, attr, false);
6119         if (it->loi_llst == NULL)
6120                 GOTO(out, rc = -ENXIO);
6121
6122         if (dev->dd_record_fid_accessed) {
6123                 /* The first iteration against the rbtree, scan the whole rbtree
6124                  * to remove the nodes which do NOT need to be handled. */
6125                 write_lock(&llsd->llsd_rb_lock);
6126                 if (dev->dd_record_fid_accessed) {
6127                         struct rb_node                  *node;
6128                         struct rb_node                  *next;
6129                         struct lfsck_rbtree_node        *lrn;
6130
6131                         /* No need to record the fid accessing anymore. */
6132                         dev->dd_record_fid_accessed = 0;
6133
6134                         node = rb_first(&llsd->llsd_rb_root);
6135                         while (node != NULL) {
6136                                 next = rb_next(node);
6137                                 lrn = rb_entry(node, struct lfsck_rbtree_node,
6138                                                lrn_node);
6139                                 if (atomic_read(&lrn->lrn_known_count) <=
6140                                     atomic_read(&lrn->lrn_accessed_count)) {
6141                                         rb_erase(node, &llsd->llsd_rb_root);
6142                                         lfsck_rbtree_free(lrn);
6143                                 }
6144                                 node = next;
6145                         }
6146                 }
6147                 write_unlock(&llsd->llsd_rb_lock);
6148         }
6149
6150         /* read lock the rbtree when init, and unlock when fini */
6151         read_lock(&llsd->llsd_rb_lock);
6152         it->loi_com = com;
6153         com = NULL;
6154
6155         GOTO(out, rc = 0);
6156
6157 out:
6158         if (com != NULL)
6159                 lfsck_component_put(env, com);
6160
6161         CDEBUG(D_LFSCK, "%s: init the orphan iteration: rc = %d\n",
6162                lfsck_lfsck2name(lfsck), rc);
6163
6164         lfsck_instance_put(env, lfsck);
6165         if (rc != 0) {
6166                 if (it != NULL)
6167                         OBD_FREE_PTR(it);
6168
6169                 it = (struct lfsck_orphan_it *)ERR_PTR(rc);
6170         }
6171
6172         return (struct dt_it *)it;
6173 }
6174
6175 static void lfsck_orphan_it_fini(const struct lu_env *env,
6176                                  struct dt_it *di)
6177 {
6178         struct lfsck_orphan_it           *it    = (struct lfsck_orphan_it *)di;
6179         struct lfsck_component           *com   = it->loi_com;
6180         struct lfsck_layout_slave_data   *llsd;
6181         struct lfsck_layout_slave_target *llst;
6182
6183         if (com != NULL) {
6184                 CDEBUG(D_LFSCK, "%s: fini the orphan iteration\n",
6185                        lfsck_lfsck2name(com->lc_lfsck));
6186
6187                 llsd = com->lc_data;
6188                 read_unlock(&llsd->llsd_rb_lock);
6189                 llst = it->loi_llst;
6190                 LASSERT(llst != NULL);
6191
6192                 /* Save the key and hash for iterate next. */
6193                 llst->llst_fid = it->loi_key;
6194                 llst->llst_hash = it->loi_hash;
6195                 lfsck_layout_llst_put(llst);
6196                 lfsck_component_put(env, com);
6197         }
6198         OBD_FREE_PTR(it);
6199 }
6200
6201 /**
6202  * \retval       +1: the iteration finished
6203  * \retval        0: on success, not finished
6204  * \retval      -ve: on error
6205  */
6206 static int lfsck_orphan_it_next(const struct lu_env *env,
6207                                 struct dt_it *di)
6208 {
6209         struct lfsck_thread_info        *info   = lfsck_env_info(env);
6210         struct filter_fid_old           *pfid   = &info->lti_old_pfid;
6211         struct lu_attr                  *la     = &info->lti_la;
6212         struct lfsck_orphan_it          *it     = (struct lfsck_orphan_it *)di;
6213         struct lu_fid                   *key    = &it->loi_key;
6214         struct lu_orphan_rec            *rec    = &it->loi_rec;
6215         struct lfsck_component          *com    = it->loi_com;
6216         struct lfsck_instance           *lfsck  = com->lc_lfsck;
6217         struct lfsck_layout_slave_data  *llsd   = com->lc_data;
6218         struct dt_object                *obj;
6219         struct lfsck_rbtree_node        *lrn;
6220         int                              pos;
6221         int                              rc;
6222         __u32                            save;
6223         __u32                            idx    = it->loi_llst->llst_index;
6224         bool                             exact  = false;
6225         ENTRY;
6226
6227         if (it->loi_over)
6228                 RETURN(1);
6229
6230 again0:
6231         lrn = it->loi_lrn;
6232         if (lrn == NULL) {
6233                 lrn = lfsck_rbtree_search(llsd, key, &exact);
6234                 if (lrn == NULL) {
6235                         it->loi_over = 1;
6236                         RETURN(1);
6237                 }
6238
6239                 it->loi_lrn = lrn;
6240                 if (!exact) {
6241                         key->f_seq = lrn->lrn_seq;
6242                         key->f_oid = lrn->lrn_first_oid;
6243                         key->f_ver = 0;
6244                 }
6245         } else {
6246                 key->f_oid++;
6247                 if (unlikely(key->f_oid == 0)) {
6248                         key->f_seq++;
6249                         it->loi_lrn = NULL;
6250                         goto again0;
6251                 }
6252
6253                 if (key->f_oid >=
6254                     lrn->lrn_first_oid + LFSCK_RBTREE_BITMAP_WIDTH) {
6255                         it->loi_lrn = NULL;
6256                         goto again0;
6257                 }
6258         }
6259
6260         if (unlikely(atomic_read(&lrn->lrn_known_count) <=
6261                      atomic_read(&lrn->lrn_accessed_count))) {
6262                 struct rb_node *next = rb_next(&lrn->lrn_node);
6263
6264                 while (next != NULL) {
6265                         lrn = rb_entry(next, struct lfsck_rbtree_node,
6266                                        lrn_node);
6267                         if (atomic_read(&lrn->lrn_known_count) >
6268                             atomic_read(&lrn->lrn_accessed_count))
6269                                 break;
6270                         next = rb_next(next);
6271                 }
6272
6273                 if (next == NULL) {
6274                         it->loi_over = 1;
6275                         RETURN(1);
6276                 }
6277
6278                 it->loi_lrn = lrn;
6279                 key->f_seq = lrn->lrn_seq;
6280                 key->f_oid = lrn->lrn_first_oid;
6281                 key->f_ver = 0;
6282         }
6283
6284         pos = key->f_oid - lrn->lrn_first_oid;
6285
6286 again1:
6287         pos = find_next_bit(lrn->lrn_known_bitmap,
6288                             LFSCK_RBTREE_BITMAP_WIDTH, pos);
6289         if (pos >= LFSCK_RBTREE_BITMAP_WIDTH) {
6290                 key->f_oid = lrn->lrn_first_oid + pos;
6291                 if (unlikely(key->f_oid < lrn->lrn_first_oid)) {
6292                         key->f_seq++;
6293                         key->f_oid = 0;
6294                 }
6295                 it->loi_lrn = NULL;
6296                 goto again0;
6297         }
6298
6299         if (test_bit(pos, lrn->lrn_accessed_bitmap)) {
6300                 pos++;
6301                 goto again1;
6302         }
6303
6304         key->f_oid = lrn->lrn_first_oid + pos;
6305         obj = lfsck_object_find(env, lfsck, key);
6306         if (IS_ERR(obj)) {
6307                 rc = PTR_ERR(obj);
6308                 if (rc == -ENOENT) {
6309                         pos++;
6310                         goto again1;
6311                 }
6312                 RETURN(rc);
6313         }
6314
6315         dt_read_lock(env, obj, 0);
6316         if (!dt_object_exists(obj)) {
6317                 dt_read_unlock(env, obj);
6318                 lfsck_object_put(env, obj);
6319                 pos++;
6320                 goto again1;
6321         }
6322
6323         rc = dt_attr_get(env, obj, la, BYPASS_CAPA);
6324         if (rc != 0)
6325                 GOTO(out, rc);
6326
6327         rc = dt_xattr_get(env, obj, lfsck_buf_get(env, pfid, sizeof(*pfid)),
6328                           XATTR_NAME_FID, BYPASS_CAPA);
6329         if (rc == -ENODATA) {
6330                 /* For the pre-created OST-object, update the bitmap to avoid
6331                  * others LFSCK (second phase) iteration to touch it again. */
6332                 if (la->la_ctime == 0) {
6333                         if (!test_and_set_bit(pos, lrn->lrn_accessed_bitmap))
6334                                 atomic_inc(&lrn->lrn_accessed_count);
6335
6336                         /* For the race between repairing dangling referenced
6337                          * MDT-object and unlink the file, it may left orphan
6338                          * OST-object there. Destroy it now! */
6339                         if (unlikely(!(la->la_mode & S_ISUID))) {
6340                                 dt_read_unlock(env, obj);
6341                                 lfsck_layout_destroy_orphan(env,
6342                                                             lfsck->li_bottom,
6343                                                             obj);
6344                                 lfsck_object_put(env, obj);
6345                                 pos++;
6346                                 goto again1;
6347                         }
6348                 } else if (idx == 0) {
6349                         /* If the orphan OST-object has no parent information,
6350                          * regard it as referenced by the MDT-object on MDT0. */
6351                         fid_zero(&rec->lor_fid);
6352                         rec->lor_uid = la->la_uid;
6353                         rec->lor_gid = la->la_gid;
6354                         GOTO(out, rc = 0);
6355                 }
6356
6357                 dt_read_unlock(env, obj);
6358                 lfsck_object_put(env, obj);
6359                 pos++;
6360                 goto again1;
6361         }
6362
6363         if (rc < 0)
6364                 GOTO(out, rc);
6365
6366         if (rc != sizeof(struct filter_fid) &&
6367             rc != sizeof(struct filter_fid_old))
6368                 GOTO(out, rc = -EINVAL);
6369
6370         fid_le_to_cpu(&rec->lor_fid, &pfid->ff_parent);
6371         /* Currently, the filter_fid::ff_parent::f_ver is not the real parent
6372          * MDT-object's FID::f_ver, instead it is the OST-object index in its
6373          * parent MDT-object's layout EA. */
6374         save = rec->lor_fid.f_stripe_idx;
6375         rec->lor_fid.f_ver = 0;
6376         rc = lfsck_fid_match_idx(env, lfsck, &rec->lor_fid, idx);
6377         /* If the orphan OST-object does not claim the MDT, then next.
6378          *
6379          * If we do not know whether it matches or not, then return it
6380          * to the MDT for further check. */
6381         if (rc == 0) {
6382                 dt_read_unlock(env, obj);
6383                 lfsck_object_put(env, obj);
6384                 pos++;
6385                 goto again1;
6386         }
6387
6388         rec->lor_fid.f_stripe_idx = save;
6389         rec->lor_uid = la->la_uid;
6390         rec->lor_gid = la->la_gid;
6391
6392         CDEBUG(D_LFSCK, "%s: return orphan "DFID", PFID "DFID", owner %u:%u\n",
6393                lfsck_lfsck2name(com->lc_lfsck), PFID(key), PFID(&rec->lor_fid),
6394                rec->lor_uid, rec->lor_gid);
6395
6396         GOTO(out, rc = 0);
6397
6398 out:
6399         dt_read_unlock(env, obj);
6400         lfsck_object_put(env, obj);
6401         if (rc == 0)
6402                 it->loi_hash++;
6403
6404         return rc;
6405 }
6406
6407 /**
6408  * \retval       +1: locate to the exactly position
6409  * \retval        0: cannot locate to the exactly position,
6410  *                   call next() to move to a valid position.
6411  * \retval      -ve: on error
6412  */
6413 static int lfsck_orphan_it_get(const struct lu_env *env,
6414                                struct dt_it *di,
6415                                const struct dt_key *key)
6416 {
6417         struct lfsck_orphan_it  *it   = (struct lfsck_orphan_it *)di;
6418         int                      rc;
6419
6420         it->loi_key = *(struct lu_fid *)key;
6421         rc = lfsck_orphan_it_next(env, di);
6422         if (rc == 1)
6423                 return 0;
6424
6425         if (rc == 0)
6426                 return 1;
6427
6428         return rc;
6429 }
6430
6431 static void lfsck_orphan_it_put(const struct lu_env *env,
6432                                 struct dt_it *di)
6433 {
6434 }
6435
6436 static struct dt_key *lfsck_orphan_it_key(const struct lu_env *env,
6437                                           const struct dt_it *di)
6438 {
6439         struct lfsck_orphan_it *it = (struct lfsck_orphan_it *)di;
6440
6441         return (struct dt_key *)&it->loi_key;
6442 }
6443
6444 static int lfsck_orphan_it_key_size(const struct lu_env *env,
6445                                     const struct dt_it *di)
6446 {
6447         return sizeof(struct lu_fid);
6448 }
6449
6450 static int lfsck_orphan_it_rec(const struct lu_env *env,
6451                                const struct dt_it *di,
6452                                struct dt_rec *rec,
6453                                __u32 attr)
6454 {
6455         struct lfsck_orphan_it *it = (struct lfsck_orphan_it *)di;
6456
6457         *(struct lu_orphan_rec *)rec = it->loi_rec;
6458
6459         return 0;
6460 }
6461
6462 static __u64 lfsck_orphan_it_store(const struct lu_env *env,
6463                                    const struct dt_it *di)
6464 {
6465         struct lfsck_orphan_it  *it   = (struct lfsck_orphan_it *)di;
6466
6467         return it->loi_hash;
6468 }
6469
6470 /**
6471  * \retval       +1: locate to the exactly position
6472  * \retval        0: cannot locate to the exactly position,
6473  *                   call next() to move to a valid position.
6474  * \retval      -ve: on error
6475  */
6476 static int lfsck_orphan_it_load(const struct lu_env *env,
6477                                 const struct dt_it *di,
6478                                 __u64 hash)
6479 {
6480         struct lfsck_orphan_it           *it   = (struct lfsck_orphan_it *)di;
6481         struct lfsck_layout_slave_target *llst = it->loi_llst;
6482         int                               rc;
6483
6484         LASSERT(llst != NULL);
6485
6486         if (hash != llst->llst_hash) {
6487                 CDEBUG(D_LFSCK, "%s: the given hash "LPU64" for orphan "
6488                        "iteration does not match the one when fini "
6489                        LPU64", to be reset.\n",
6490                        lfsck_lfsck2name(it->loi_com->lc_lfsck), hash,
6491                        llst->llst_hash);
6492                 fid_zero(&llst->llst_fid);
6493                 llst->llst_hash = 0;
6494         }
6495
6496         it->loi_key = llst->llst_fid;
6497         it->loi_hash = llst->llst_hash;
6498         rc = lfsck_orphan_it_next(env, (struct dt_it *)di);
6499         if (rc == 1)
6500                 return 0;
6501
6502         if (rc == 0)
6503                 return 1;
6504
6505         return rc;
6506 }
6507
6508 static int lfsck_orphan_it_key_rec(const struct lu_env *env,
6509                                    const struct dt_it *di,
6510                                    void *key_rec)
6511 {
6512         return 0;
6513 }
6514
6515 const struct dt_index_operations lfsck_orphan_index_ops = {
6516         .dio_lookup             = lfsck_orphan_index_lookup,
6517         .dio_declare_insert     = lfsck_orphan_index_declare_insert,
6518         .dio_insert             = lfsck_orphan_index_insert,
6519         .dio_declare_delete     = lfsck_orphan_index_declare_delete,
6520         .dio_delete             = lfsck_orphan_index_delete,
6521         .dio_it = {
6522                 .init           = lfsck_orphan_it_init,
6523                 .fini           = lfsck_orphan_it_fini,
6524                 .get            = lfsck_orphan_it_get,
6525                 .put            = lfsck_orphan_it_put,
6526                 .next           = lfsck_orphan_it_next,
6527                 .key            = lfsck_orphan_it_key,
6528                 .key_size       = lfsck_orphan_it_key_size,
6529                 .rec            = lfsck_orphan_it_rec,
6530                 .store          = lfsck_orphan_it_store,
6531                 .load           = lfsck_orphan_it_load,
6532                 .key_rec        = lfsck_orphan_it_key_rec,
6533         }
6534 };