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