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