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