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