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