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