Whamcloud - gitweb
LU-6146 tests: race condition for check/use cfs_fail_val
[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                                 /* Some others may changed the cfs_fail_val
1314                                  * as zero after above check, re-check it for
1315                                  * sure to avoid falling into wait for ever. */
1316                                 if (likely(lwi.lwi_timeout > 0)) {
1317                                         struct ptlrpc_thread *thread =
1318                                                 &lfsck->li_thread;
1319
1320                                         up_write(&com->lc_sem);
1321                                         l_wait_event(thread->t_ctl_waitq,
1322                                                      !thread_is_running(thread),
1323                                                      &lwi);
1324                                         down_write(&com->lc_sem);
1325                                 }
1326                         }
1327                 }
1328
1329                 rc = lfsck_layout_lastid_create(env, lfsck, obj);
1330         } else {
1331                 dt_read_lock(env, obj, 0);
1332                 rc = dt_read(env, obj,
1333                         lfsck_buf_get(env, &lls->lls_lastid, sizeof(__u64)),
1334                         &pos);
1335                 dt_read_unlock(env, obj);
1336                 if (rc != 0 && rc != sizeof(__u64))
1337                         GOTO(out, rc = (rc > 0 ? -EFAULT : rc));
1338
1339                 if (rc == 0 && !(lo->ll_flags & LF_CRASHED_LASTID)) {
1340                         LASSERT(lfsck->li_out_notify != NULL);
1341
1342                         lfsck->li_out_notify(env, lfsck->li_out_notify_data,
1343                                              LE_LASTID_REBUILDING);
1344                         lo->ll_flags |= LF_CRASHED_LASTID;
1345
1346                         CDEBUG(D_LFSCK, "%s: layout LFSCK finds invalid "
1347                                "LAST_ID file for the sequence "LPX64
1348                                ": rc = %d\n",
1349                                lfsck_lfsck2name(lfsck), lls->lls_seq, rc);
1350                 }
1351
1352                 lls->lls_lastid = le64_to_cpu(lls->lls_lastid);
1353                 rc = 0;
1354         }
1355
1356         GOTO(out, rc);
1357
1358 out:
1359         if (rc != 0)
1360                 lfsck_object_put(env, obj);
1361         else
1362                 lls->lls_lastid_obj = obj;
1363
1364         return rc;
1365 }
1366
1367 static void lfsck_layout_record_failure(const struct lu_env *env,
1368                                         struct lfsck_instance *lfsck,
1369                                         struct lfsck_layout *lo)
1370 {
1371         __u64 cookie;
1372
1373         lo->ll_objs_failed_phase1++;
1374         cookie = lfsck->li_obj_oit->do_index_ops->dio_it.store(env,
1375                                                         lfsck->li_di_oit);
1376         if (lo->ll_pos_first_inconsistent == 0 ||
1377             lo->ll_pos_first_inconsistent < cookie) {
1378                 lo->ll_pos_first_inconsistent = cookie;
1379
1380                 CDEBUG(D_LFSCK, "%s: layout LFSCK hit first non-repaired "
1381                        "inconsistency at the pos ["LPU64"]\n",
1382                        lfsck_lfsck2name(lfsck),
1383                        lo->ll_pos_first_inconsistent);
1384         }
1385 }
1386
1387 static int lfsck_layout_double_scan_result(const struct lu_env *env,
1388                                            struct lfsck_component *com,
1389                                            int rc)
1390 {
1391         struct lfsck_instance   *lfsck = com->lc_lfsck;
1392         struct lfsck_layout     *lo    = com->lc_file_ram;
1393
1394         down_write(&com->lc_sem);
1395         lo->ll_run_time_phase2 += cfs_duration_sec(cfs_time_current() +
1396                                 HALF_SEC - lfsck->li_time_last_checkpoint);
1397         lo->ll_time_last_checkpoint = cfs_time_current_sec();
1398         lo->ll_objs_checked_phase2 += com->lc_new_checked;
1399
1400         if (rc > 0) {
1401                 if (lo->ll_flags & LF_INCOMPLETE) {
1402                         lo->ll_status = LS_PARTIAL;
1403                 } else {
1404                         if (lfsck->li_master) {
1405                                 struct lfsck_assistant_data *lad = com->lc_data;
1406
1407                                 if (lad->lad_incomplete)
1408                                         lo->ll_status = LS_PARTIAL;
1409                                 else
1410                                         lo->ll_status = LS_COMPLETED;
1411                         } else {
1412                                 lo->ll_status = LS_COMPLETED;
1413                         }
1414                 }
1415                 if (!(lfsck->li_bookmark_ram.lb_param & LPF_DRYRUN))
1416                         lo->ll_flags &= ~(LF_SCANNED_ONCE | LF_INCONSISTENT);
1417                 lo->ll_time_last_complete = lo->ll_time_last_checkpoint;
1418                 lo->ll_success_count++;
1419         } else if (rc == 0) {
1420                 if (lfsck->li_status != 0)
1421                         lo->ll_status = lfsck->li_status;
1422                 else
1423                         lo->ll_status = LS_STOPPED;
1424         } else {
1425                 lo->ll_status = LS_FAILED;
1426         }
1427
1428         rc = lfsck_layout_store(env, com);
1429         up_write(&com->lc_sem);
1430
1431         return rc;
1432 }
1433
1434 static int lfsck_layout_trans_stop(const struct lu_env *env,
1435                                    struct dt_device *dev,
1436                                    struct thandle *handle, int result)
1437 {
1438         int rc;
1439
1440         handle->th_result = result;
1441         rc = dt_trans_stop(env, dev, handle);
1442         if (rc > 0)
1443                 rc = 0;
1444         else if (rc == 0)
1445                 rc = 1;
1446
1447         return rc;
1448 }
1449
1450 /**
1451  * Get the system default stripe size.
1452  *
1453  * \param[in] env       pointer to the thread context
1454  * \param[in] lfsck     pointer to the lfsck instance
1455  * \param[out] size     pointer to the default stripe size
1456  *
1457  * \retval              0 for success
1458  * \retval              negative error number on failure
1459  */
1460 static int lfsck_layout_get_def_stripesize(const struct lu_env *env,
1461                                            struct lfsck_instance *lfsck,
1462                                            __u32 *size)
1463 {
1464         struct lov_user_md      *lum = &lfsck_env_info(env)->lti_lum;
1465         struct dt_object        *root;
1466         int                      rc;
1467
1468         root = dt_locate(env, lfsck->li_next, &lfsck->li_local_root_fid);
1469         if (IS_ERR(root))
1470                 return PTR_ERR(root);
1471
1472         /* Get the default stripe size via xattr_get on the backend root. */
1473         rc = dt_xattr_get(env, root, lfsck_buf_get(env, lum, sizeof(*lum)),
1474                           XATTR_NAME_LOV, BYPASS_CAPA);
1475         if (rc > 0) {
1476                 /* The lum->lmm_stripe_size is LE mode. The *size also
1477                  * should be LE mode. So it is unnecessary to convert. */
1478                 *size = lum->lmm_stripe_size;
1479                 rc = 0;
1480         } else if (unlikely(rc == 0)) {
1481                 rc = -EINVAL;
1482         }
1483
1484         lfsck_object_put(env, root);
1485
1486         return rc;
1487 }
1488
1489 /**
1490  * \retval       +1: repaired
1491  * \retval        0: did nothing
1492  * \retval      -ve: on error
1493  */
1494 static int lfsck_layout_refill_lovea(const struct lu_env *env,
1495                                      struct thandle *handle,
1496                                      struct dt_object *parent,
1497                                      struct lu_fid *cfid,
1498                                      struct lu_buf *buf,
1499                                      struct lov_ost_data_v1 *slot,
1500                                      int fl, __u32 ost_idx)
1501 {
1502         struct ost_id           *oi     = &lfsck_env_info(env)->lti_oi;
1503         struct lov_mds_md_v1    *lmm    = buf->lb_buf;
1504         struct lu_buf            ea_buf;
1505         int                      rc;
1506         __u32                    magic;
1507         __u16                    count;
1508
1509         magic = le32_to_cpu(lmm->lmm_magic);
1510         count = le16_to_cpu(lmm->lmm_stripe_count);
1511
1512         fid_to_ostid(cfid, oi);
1513         ostid_cpu_to_le(oi, &slot->l_ost_oi);
1514         slot->l_ost_gen = cpu_to_le32(0);
1515         slot->l_ost_idx = cpu_to_le32(ost_idx);
1516
1517         if (le32_to_cpu(lmm->lmm_pattern) & LOV_PATTERN_F_HOLE) {
1518                 struct lov_ost_data_v1 *objs;
1519                 int                     i;
1520
1521                 if (magic == LOV_MAGIC_V1)
1522                         objs = &lmm->lmm_objects[0];
1523                 else
1524                         objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[0];
1525                 for (i = 0; i < count; i++, objs++) {
1526                         if (objs != slot && lovea_slot_is_dummy(objs))
1527                                 break;
1528                 }
1529
1530                 /* If the @slot is the last dummy slot to be refilled,
1531                  * then drop LOV_PATTERN_F_HOLE from lmm::lmm_pattern. */
1532                 if (i == count)
1533                         lmm->lmm_pattern &= ~cpu_to_le32(LOV_PATTERN_F_HOLE);
1534         }
1535
1536         lfsck_buf_init(&ea_buf, lmm, lov_mds_md_size(count, magic));
1537         rc = dt_xattr_set(env, parent, &ea_buf, XATTR_NAME_LOV, fl, handle,
1538                           BYPASS_CAPA);
1539         if (rc == 0)
1540                 rc = 1;
1541
1542         return rc;
1543 }
1544
1545 /**
1546  * \retval       +1: repaired
1547  * \retval        0: did nothing
1548  * \retval      -ve: on error
1549  */
1550 static int lfsck_layout_extend_lovea(const struct lu_env *env,
1551                                      struct lfsck_instance *lfsck,
1552                                      struct thandle *handle,
1553                                      struct dt_object *parent,
1554                                      struct lu_fid *cfid,
1555                                      struct lu_buf *buf, int fl,
1556                                      __u32 ost_idx, __u32 ea_off, bool reset)
1557 {
1558         struct lov_mds_md_v1    *lmm    = buf->lb_buf;
1559         struct lov_ost_data_v1  *objs;
1560         int                      rc;
1561         __u16                    count;
1562         bool                     hole   = false;
1563         ENTRY;
1564
1565         if (fl == LU_XATTR_CREATE || reset) {
1566                 __u32 pattern = LOV_PATTERN_RAID0;
1567
1568                 count = ea_off + 1;
1569                 LASSERT(buf->lb_len >= lov_mds_md_size(count, LOV_MAGIC_V1));
1570
1571                 if (ea_off != 0 || reset) {
1572                         pattern |= LOV_PATTERN_F_HOLE;
1573                         hole = true;
1574                 }
1575
1576                 memset(lmm, 0, buf->lb_len);
1577                 lmm->lmm_magic = cpu_to_le32(LOV_MAGIC_V1);
1578                 lmm->lmm_pattern = cpu_to_le32(pattern);
1579                 fid_to_lmm_oi(lfsck_dto2fid(parent), &lmm->lmm_oi);
1580                 lmm_oi_cpu_to_le(&lmm->lmm_oi, &lmm->lmm_oi);
1581
1582                 rc = lfsck_layout_get_def_stripesize(env, lfsck,
1583                                                      &lmm->lmm_stripe_size);
1584                 if (rc != 0)
1585                         RETURN(rc);
1586
1587                 objs = &lmm->lmm_objects[ea_off];
1588         } else {
1589                 __u32   magic = le32_to_cpu(lmm->lmm_magic);
1590                 int     gap;
1591
1592                 count = le16_to_cpu(lmm->lmm_stripe_count);
1593                 if (magic == LOV_MAGIC_V1)
1594                         objs = &lmm->lmm_objects[count];
1595                 else
1596                         objs = &((struct lov_mds_md_v3 *)lmm)->
1597                                                         lmm_objects[count];
1598
1599                 gap = ea_off - count;
1600                 if (gap >= 0)
1601                         count = ea_off + 1;
1602                 LASSERT(buf->lb_len >= lov_mds_md_size(count, magic));
1603
1604                 if (gap > 0) {
1605                         memset(objs, 0, gap * sizeof(*objs));
1606                         lmm->lmm_pattern |= cpu_to_le32(LOV_PATTERN_F_HOLE);
1607                         hole = true;
1608                 }
1609
1610                 lmm->lmm_layout_gen =
1611                             cpu_to_le16(le16_to_cpu(lmm->lmm_layout_gen) + 1);
1612                 objs += gap;
1613         }
1614
1615         lmm->lmm_stripe_count = cpu_to_le16(count);
1616         rc = lfsck_layout_refill_lovea(env, handle, parent, cfid, buf, objs,
1617                                        fl, ost_idx);
1618
1619         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant extend layout EA for "
1620                DFID": parent "DFID", OST-index %u, stripe-index %u, fl %d, "
1621                "reset %s, %s LOV EA hole: rc = %d\n",
1622                lfsck_lfsck2name(lfsck), PFID(cfid), PFID(lfsck_dto2fid(parent)),
1623                ost_idx, ea_off, fl, reset ? "yes" : "no",
1624                hole ? "with" : "without", rc);
1625
1626         RETURN(rc);
1627 }
1628
1629 /**
1630  * \retval       +1: repaired
1631  * \retval        0: did nothing
1632  * \retval      -ve: on error
1633  */
1634 static int lfsck_layout_update_pfid(const struct lu_env *env,
1635                                     struct lfsck_component *com,
1636                                     struct dt_object *parent,
1637                                     struct lu_fid *cfid,
1638                                     struct dt_device *cdev, __u32 ea_off)
1639 {
1640         struct filter_fid       *pfid   = &lfsck_env_info(env)->lti_new_pfid;
1641         struct dt_object        *child;
1642         struct thandle          *handle;
1643         const struct lu_fid     *tfid   = lu_object_fid(&parent->do_lu);
1644         struct lu_buf           *buf;
1645         int                      rc     = 0;
1646         ENTRY;
1647
1648         child = lfsck_object_find_by_dev(env, cdev, cfid);
1649         if (IS_ERR(child))
1650                 RETURN(PTR_ERR(child));
1651
1652         handle = dt_trans_create(env, cdev);
1653         if (IS_ERR(handle))
1654                 GOTO(out, rc = PTR_ERR(handle));
1655
1656         pfid->ff_parent.f_seq = cpu_to_le64(tfid->f_seq);
1657         pfid->ff_parent.f_oid = cpu_to_le32(tfid->f_oid);
1658         /* Currently, the filter_fid::ff_parent::f_ver is not the real parent
1659          * MDT-object's FID::f_ver, instead it is the OST-object index in its
1660          * parent MDT-object's layout EA. */
1661         pfid->ff_parent.f_stripe_idx = cpu_to_le32(ea_off);
1662         buf = lfsck_buf_get(env, pfid, sizeof(struct filter_fid));
1663
1664         rc = dt_declare_xattr_set(env, child, buf, XATTR_NAME_FID, 0, handle);
1665         if (rc != 0)
1666                 GOTO(stop, rc);
1667
1668         rc = dt_trans_start(env, cdev, handle);
1669         if (rc != 0)
1670                 GOTO(stop, rc);
1671
1672         rc = dt_xattr_set(env, child, buf, XATTR_NAME_FID, 0, handle,
1673                           BYPASS_CAPA);
1674
1675         GOTO(stop, rc = (rc == 0 ? 1 : rc));
1676
1677 stop:
1678         dt_trans_stop(env, cdev, handle);
1679
1680 out:
1681         lu_object_put(env, &child->do_lu);
1682
1683         return rc;
1684 }
1685
1686 /**
1687  * This function will create the MDT-object with the given (partial) LOV EA.
1688  *
1689  * Under some data corruption cases, the MDT-object of the file may be lost,
1690  * but its OST-objects, or some of them are there. The layout LFSCK needs to
1691  * re-create the MDT-object with the orphan OST-object(s) information.
1692  *
1693  * On the other hand, the LFSCK may has created some OST-object for repairing
1694  * dangling LOV EA reference, but as the LFSCK processing, it may find that
1695  * the old OST-object is there and should replace the former new created OST
1696  * object. Unfortunately, some others have modified such newly created object.
1697  * To keep the data (both new and old), the LFSCK will create MDT-object with
1698  * new FID to reference the original OST-object.
1699  *
1700  * \param[in] env       pointer to the thread context
1701  * \param[in] com       pointer to the lfsck component
1702  * \param[in] ltd       pointer to target device descriptor
1703  * \param[in] rec       pointer to the record for the orphan OST-object
1704  * \param[in] cfid      pointer to FID for the orphan OST-object
1705  * \param[in] infix     additional information, such as the FID for original
1706  *                      MDT-object and the stripe offset in the LOV EA
1707  * \param[in] type      the type for describing why the orphan MDT-object is
1708  *                      created. The rules are as following:
1709  *
1710  *  type "C":           Multiple OST-objects claim the same MDT-object and the
1711  *                      same slot in the layout EA. Then the LFSCK will create
1712  *                      new MDT-object(s) to hold the conflict OST-object(s).
1713  *
1714  *  type "N":           The orphan OST-object does not know which one was the
1715  *                      real parent MDT-object, so the LFSCK uses new FID for
1716  *                      its parent MDT-object.
1717  *
1718  *  type "R":           The orphan OST-object knows its parent MDT-object FID,
1719  *                      but does not know the position (the file name) in the
1720  *                      layout.
1721  *
1722  *  type "D":           The MDT-object is a directory, it may knows its parent
1723  *                      but because there is no valid linkEA, the LFSCK cannot
1724  *                      know where to put it back to the namespace.
1725  *  type "O":           The MDT-object has no linkEA, and there is no name
1726  *                      entry that references the MDT-object.
1727  *
1728  *  type "P":           The orphan object to be created was a parent directory
1729  *                      of some MDT-object which linkEA shows that the @orphan
1730  *                      object is missing.
1731  *
1732  * The orphan name will be like:
1733  * ${FID}-${infix}-${type}-${conflict_version}
1734  *
1735  * \param[in] ea_off    the stripe offset in the LOV EA
1736  *
1737  * \retval              positive on repaired something
1738  * \retval              0 if needs to repair nothing
1739  * \retval              negative error number on failure
1740  */
1741 static int lfsck_layout_recreate_parent(const struct lu_env *env,
1742                                         struct lfsck_component *com,
1743                                         struct lfsck_tgt_desc *ltd,
1744                                         struct lu_orphan_rec *rec,
1745                                         struct lu_fid *cfid,
1746                                         const char *infix,
1747                                         const char *type,
1748                                         __u32 ea_off)
1749 {
1750         struct lfsck_thread_info        *info   = lfsck_env_info(env);
1751         struct dt_insert_rec            *dtrec  = &info->lti_dt_rec;
1752         char                            *name   = info->lti_key;
1753         struct lu_attr                  *la     = &info->lti_la;
1754         struct dt_object_format         *dof    = &info->lti_dof;
1755         struct lfsck_instance           *lfsck  = com->lc_lfsck;
1756         struct lu_fid                   *pfid   = &rec->lor_fid;
1757         struct lu_fid                   *tfid   = &info->lti_fid3;
1758         struct dt_device                *next   = lfsck->li_next;
1759         struct dt_object                *pobj   = NULL;
1760         struct dt_object                *cobj   = NULL;
1761         struct thandle                  *th     = NULL;
1762         struct lu_buf                    pbuf   = { NULL };
1763         struct lu_buf                   *ea_buf = &info->lti_big_buf;
1764         struct lu_buf                    lov_buf;
1765         struct lustre_handle             lh     = { 0 };
1766         struct linkea_data               ldata  = { NULL };
1767         struct lu_buf                    linkea_buf;
1768         const struct lu_name            *pname;
1769         int                              size   = 0;
1770         int                              idx    = 0;
1771         int                              rc     = 0;
1772         ENTRY;
1773
1774         if (unlikely(lfsck->li_lpf_obj == NULL))
1775                 GOTO(log, rc = -ENXIO);
1776
1777         if (fid_is_zero(pfid)) {
1778                 struct filter_fid *ff = &info->lti_new_pfid;
1779
1780                 rc = lfsck_fid_alloc(env, lfsck, pfid, false);
1781                 if (rc != 0)
1782                         RETURN(rc);
1783
1784                 ff->ff_parent.f_seq = cpu_to_le64(pfid->f_seq);
1785                 ff->ff_parent.f_oid = cpu_to_le32(pfid->f_oid);
1786                 /* Currently, the filter_fid::ff_parent::f_ver is not the
1787                  * real parent MDT-object's FID::f_ver, instead it is the
1788                  * OST-object index in its parent MDT-object's layout EA. */
1789                 ff->ff_parent.f_stripe_idx = cpu_to_le32(ea_off);
1790                 lfsck_buf_init(&pbuf, ff, sizeof(struct filter_fid));
1791                 cobj = lfsck_object_find_by_dev(env, ltd->ltd_tgt, cfid);
1792                 if (IS_ERR(cobj))
1793                         GOTO(log, rc = PTR_ERR(cobj));
1794         }
1795
1796         pobj = lfsck_object_find_by_dev(env, lfsck->li_bottom, pfid);
1797         if (IS_ERR(pobj))
1798                 GOTO(put, rc = PTR_ERR(pobj));
1799
1800         LASSERT(infix != NULL);
1801         LASSERT(type != NULL);
1802
1803         do {
1804                 snprintf(name, NAME_MAX, DFID"%s-%s-%d", PFID(pfid), infix,
1805                          type, idx++);
1806                 rc = dt_lookup(env, lfsck->li_lpf_obj, (struct dt_rec *)tfid,
1807                                (const struct dt_key *)name, BYPASS_CAPA);
1808                 if (rc != 0 && rc != -ENOENT)
1809                         GOTO(put, rc);
1810         } while (rc == 0);
1811
1812         rc = linkea_data_new(&ldata,
1813                              &lfsck_env_info(env)->lti_linkea_buf);
1814         if (rc != 0)
1815                 GOTO(put, rc);
1816
1817         pname = lfsck_name_get_const(env, name, strlen(name));
1818         rc = linkea_add_buf(&ldata, pname, lfsck_dto2fid(lfsck->li_lpf_obj));
1819         if (rc != 0)
1820                 GOTO(put, rc);
1821
1822         memset(la, 0, sizeof(*la));
1823         la->la_uid = rec->lor_uid;
1824         la->la_gid = rec->lor_gid;
1825         la->la_mode = S_IFREG | S_IRUSR;
1826         la->la_valid = LA_MODE | LA_UID | LA_GID;
1827
1828         memset(dof, 0, sizeof(*dof));
1829         dof->dof_type = dt_mode_to_dft(S_IFREG);
1830
1831         size = lov_mds_md_size(ea_off + 1, LOV_MAGIC_V1);
1832         if (ea_buf->lb_len < size) {
1833                 lu_buf_realloc(ea_buf, size);
1834                 if (ea_buf->lb_buf == NULL)
1835                         GOTO(put, rc = -ENOMEM);
1836         }
1837
1838         /* Hold update lock on the .lustre/lost+found/MDTxxxx/.
1839          *
1840          * XXX: Currently, we do not grab the PDO lock as normal create cases,
1841          *      because creating MDT-object for orphan OST-object is rare, we
1842          *      do not much care about the performance. It can be improved in
1843          *      the future when needed. */
1844         rc = lfsck_ibits_lock(env, lfsck, lfsck->li_lpf_obj, &lh,
1845                               MDS_INODELOCK_UPDATE, LCK_EX);
1846         if (rc != 0)
1847                 GOTO(put, rc);
1848
1849         th = dt_trans_create(env, next);
1850         if (IS_ERR(th))
1851                 GOTO(unlock, rc = PTR_ERR(th));
1852
1853         /* 1a. Update OST-object's parent information remotely.
1854          *
1855          * If other subsequent modifications failed, then next LFSCK scanning
1856          * will process the OST-object as orphan again with known parent FID. */
1857         if (cobj != NULL) {
1858                 rc = dt_declare_xattr_set(env, cobj, &pbuf, XATTR_NAME_FID,
1859                                           0, th);
1860                 if (rc != 0)
1861                         GOTO(stop, rc);
1862         }
1863
1864         /* 2a. Create the MDT-object locally. */
1865         rc = dt_declare_create(env, pobj, la, NULL, dof, th);
1866         if (rc != 0)
1867                 GOTO(stop, rc);
1868
1869         /* 3a. Add layout EA for the MDT-object. */
1870         lfsck_buf_init(&lov_buf, ea_buf->lb_buf, size);
1871         rc = dt_declare_xattr_set(env, pobj, &lov_buf, XATTR_NAME_LOV,
1872                                   LU_XATTR_CREATE, th);
1873         if (rc != 0)
1874                 GOTO(stop, rc);
1875
1876         /* 4a. Insert the MDT-object to .lustre/lost+found/MDTxxxx/ */
1877         dtrec->rec_fid = pfid;
1878         dtrec->rec_type = S_IFREG;
1879         rc = dt_declare_insert(env, lfsck->li_lpf_obj,
1880                                (const struct dt_rec *)dtrec,
1881                                (const struct dt_key *)name, th);
1882         if (rc != 0)
1883                 GOTO(stop, rc);
1884
1885         /* 5a. insert linkEA for parent. */
1886         lfsck_buf_init(&linkea_buf, ldata.ld_buf->lb_buf,
1887                        ldata.ld_leh->leh_len);
1888         rc = dt_declare_xattr_set(env, pobj, &linkea_buf,
1889                                   XATTR_NAME_LINK, 0, th);
1890         if (rc != 0)
1891                 GOTO(stop, rc);
1892
1893         rc = dt_trans_start(env, next, th);
1894         if (rc != 0)
1895                 GOTO(stop, rc);
1896
1897         /* 1b. Update OST-object's parent information remotely. */
1898         if (cobj != NULL) {
1899                 rc = dt_xattr_set(env, cobj, &pbuf, XATTR_NAME_FID, 0, th,
1900                                   BYPASS_CAPA);
1901                 if (rc != 0)
1902                         GOTO(stop, rc);
1903         }
1904
1905         dt_write_lock(env, pobj, 0);
1906         /* 2b. Create the MDT-object locally. */
1907         rc = dt_create(env, pobj, la, NULL, dof, th);
1908         if (rc == 0)
1909                 /* 3b. Add layout EA for the MDT-object. */
1910                 rc = lfsck_layout_extend_lovea(env, lfsck, th, pobj, cfid,
1911                                                &lov_buf, LU_XATTR_CREATE,
1912                                                ltd->ltd_index, ea_off, false);
1913         dt_write_unlock(env, pobj);
1914         if (rc < 0)
1915                 GOTO(stop, rc);
1916
1917         /* 4b. Insert the MDT-object to .lustre/lost+found/MDTxxxx/ */
1918         rc = dt_insert(env, lfsck->li_lpf_obj, (const struct dt_rec *)dtrec,
1919                        (const struct dt_key *)name, th, BYPASS_CAPA, 1);
1920         if (rc != 0)
1921                 GOTO(stop, rc);
1922
1923         /* 5b. insert linkEA for parent. */
1924         rc = dt_xattr_set(env, pobj, &linkea_buf,
1925                           XATTR_NAME_LINK, 0, th, BYPASS_CAPA);
1926
1927         GOTO(stop, rc);
1928
1929 stop:
1930         dt_trans_stop(env, next, th);
1931
1932 unlock:
1933         lfsck_ibits_unlock(&lh, LCK_EX);
1934
1935 put:
1936         if (cobj != NULL && !IS_ERR(cobj))
1937                 lu_object_put(env, &cobj->do_lu);
1938         if (pobj != NULL && !IS_ERR(pobj))
1939                 lu_object_put(env, &pobj->do_lu);
1940
1941 log:
1942         if (rc < 0)
1943                 CDEBUG(D_LFSCK, "%s layout LFSCK assistant failed to "
1944                        "recreate the lost MDT-object: parent "DFID
1945                        ", child "DFID", OST-index %u, stripe-index %u, "
1946                        "infix %s, type %s: rc = %d\n",
1947                        lfsck_lfsck2name(lfsck), PFID(pfid), PFID(cfid),
1948                        ltd->ltd_index, ea_off, infix, type, rc);
1949
1950         return rc >= 0 ? 1 : rc;
1951 }
1952
1953 static int lfsck_layout_master_conditional_destroy(const struct lu_env *env,
1954                                                    struct lfsck_component *com,
1955                                                    const struct lu_fid *fid,
1956                                                    __u32 index)
1957 {
1958         struct lfsck_thread_info *info  = lfsck_env_info(env);
1959         struct lfsck_request     *lr    = &info->lti_lr;
1960         struct lfsck_instance    *lfsck = com->lc_lfsck;
1961         struct lfsck_tgt_desc    *ltd;
1962         struct ptlrpc_request    *req;
1963         struct lfsck_request     *tmp;
1964         struct obd_export        *exp;
1965         int                       rc    = 0;
1966         ENTRY;
1967
1968         ltd = lfsck_tgt_get(&lfsck->li_ost_descs, index);
1969         if (unlikely(ltd == NULL))
1970                 RETURN(-ENXIO);
1971
1972         exp = ltd->ltd_exp;
1973         if (!(exp_connect_flags(exp) & OBD_CONNECT_LFSCK))
1974                 GOTO(put, rc = -EOPNOTSUPP);
1975
1976         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_LFSCK_NOTIFY);
1977         if (req == NULL)
1978                 GOTO(put, rc = -ENOMEM);
1979
1980         rc = ptlrpc_request_pack(req, LUSTRE_OBD_VERSION, LFSCK_NOTIFY);
1981         if (rc != 0) {
1982                 ptlrpc_request_free(req);
1983
1984                 GOTO(put, rc);
1985         }
1986
1987         memset(lr, 0, sizeof(*lr));
1988         lr->lr_event = LE_CONDITIONAL_DESTROY;
1989         lr->lr_active = LFSCK_TYPE_LAYOUT;
1990         lr->lr_fid = *fid;
1991
1992         tmp = req_capsule_client_get(&req->rq_pill, &RMF_LFSCK_REQUEST);
1993         *tmp = *lr;
1994         ptlrpc_request_set_replen(req);
1995
1996         rc = ptlrpc_queue_wait(req);
1997         ptlrpc_req_finished(req);
1998
1999         GOTO(put, rc);
2000
2001 put:
2002         lfsck_tgt_put(ltd);
2003
2004         return rc;
2005 }
2006
2007 static int lfsck_layout_slave_conditional_destroy(const struct lu_env *env,
2008                                                   struct lfsck_component *com,
2009                                                   struct lfsck_request *lr)
2010 {
2011         struct lfsck_thread_info        *info   = lfsck_env_info(env);
2012         struct lu_attr                  *la     = &info->lti_la;
2013         ldlm_policy_data_t              *policy = &info->lti_policy;
2014         struct ldlm_res_id              *resid  = &info->lti_resid;
2015         struct lfsck_instance           *lfsck  = com->lc_lfsck;
2016         struct dt_device                *dev    = lfsck->li_bottom;
2017         struct lu_fid                   *fid    = &lr->lr_fid;
2018         struct dt_object                *obj;
2019         struct thandle                  *th     = NULL;
2020         struct lustre_handle             lh     = { 0 };
2021         __u64                            flags  = 0;
2022         int                              rc     = 0;
2023         ENTRY;
2024
2025         obj = lfsck_object_find_by_dev(env, dev, fid);
2026         if (IS_ERR(obj))
2027                 RETURN(PTR_ERR(obj));
2028
2029         dt_read_lock(env, obj, 0);
2030         if (dt_object_exists(obj) == 0 ||
2031             lfsck_is_dead_obj(obj)) {
2032                 dt_read_unlock(env, obj);
2033
2034                 GOTO(put, rc = -ENOENT);
2035         }
2036
2037         /* Get obj's attr without lock firstly. */
2038         rc = dt_attr_get(env, obj, la, BYPASS_CAPA);
2039         dt_read_unlock(env, obj);
2040         if (rc != 0)
2041                 GOTO(put, rc);
2042
2043         if (likely(la->la_ctime != 0 || la->la_mode & S_ISUID))
2044                 GOTO(put, rc = -ETXTBSY);
2045
2046         /* Acquire extent lock on [0, EOF] to sync with all possible written. */
2047         LASSERT(lfsck->li_namespace != NULL);
2048
2049         memset(policy, 0, sizeof(*policy));
2050         policy->l_extent.end = OBD_OBJECT_EOF;
2051         ost_fid_build_resid(fid, resid);
2052         rc = ldlm_cli_enqueue_local(lfsck->li_namespace, resid, LDLM_EXTENT,
2053                                     policy, LCK_EX, &flags, ldlm_blocking_ast,
2054                                     ldlm_completion_ast, NULL, NULL, 0,
2055                                     LVB_T_NONE, NULL, &lh);
2056         if (rc != ELDLM_OK)
2057                 GOTO(put, rc = -EIO);
2058
2059         dt_write_lock(env, obj, 0);
2060         /* Get obj's attr within lock again. */
2061         rc = dt_attr_get(env, obj, la, BYPASS_CAPA);
2062         if (rc != 0)
2063                 GOTO(unlock, rc);
2064
2065         if (la->la_ctime != 0)
2066                 GOTO(unlock, rc = -ETXTBSY);
2067
2068         th = dt_trans_create(env, dev);
2069         if (IS_ERR(th))
2070                 GOTO(unlock, rc = PTR_ERR(th));
2071
2072         rc = dt_declare_ref_del(env, obj, th);
2073         if (rc != 0)
2074                 GOTO(stop, rc);
2075
2076         rc = dt_declare_destroy(env, obj, th);
2077         if (rc != 0)
2078                 GOTO(stop, rc);
2079
2080         rc = dt_trans_start_local(env, dev, th);
2081         if (rc != 0)
2082                 GOTO(stop, rc);
2083
2084         rc = dt_ref_del(env, obj, th);
2085         if (rc != 0)
2086                 GOTO(stop, rc);
2087
2088         rc = dt_destroy(env, obj, th);
2089         if (rc == 0)
2090                 CDEBUG(D_LFSCK, "%s: layout LFSCK destroyed the empty "
2091                        "OST-object "DFID" that was created for reparing "
2092                        "dangling referenced case. But the original missing "
2093                        "OST-object is found now.\n",
2094                        lfsck_lfsck2name(lfsck), PFID(fid));
2095
2096         GOTO(stop, rc);
2097
2098 stop:
2099         dt_trans_stop(env, dev, th);
2100
2101 unlock:
2102         dt_write_unlock(env, obj);
2103         ldlm_lock_decref(&lh, LCK_EX);
2104
2105 put:
2106         lu_object_put(env, &obj->do_lu);
2107
2108         return rc;
2109 }
2110
2111 /**
2112  * Some OST-object has occupied the specified layout EA slot.
2113  * Such OST-object may be generated by the LFSCK when repair
2114  * dangling referenced MDT-object, which can be indicated by
2115  * attr::la_ctime == 0 but without S_ISUID in la_mode. If it
2116  * is true and such OST-object has not been modified yet, we
2117  * will replace it with the orphan OST-object; otherwise the
2118  * LFSCK will create new MDT-object to reference the orphan.
2119  *
2120  * \retval       +1: repaired
2121  * \retval        0: did nothing
2122  * \retval      -ve: on error
2123  */
2124 static int lfsck_layout_conflict_create(const struct lu_env *env,
2125                                         struct lfsck_component *com,
2126                                         struct lfsck_tgt_desc *ltd,
2127                                         struct lu_orphan_rec *rec,
2128                                         struct dt_object *parent,
2129                                         struct lu_fid *cfid,
2130                                         struct lu_buf *ea_buf,
2131                                         struct lov_ost_data_v1 *slot,
2132                                         __u32 ea_off)
2133 {
2134         struct lfsck_thread_info *info          = lfsck_env_info(env);
2135         struct lu_fid            *cfid2         = &info->lti_fid2;
2136         struct ost_id            *oi            = &info->lti_oi;
2137         struct lov_mds_md_v1     *lmm           = ea_buf->lb_buf;
2138         struct dt_device         *dev           = com->lc_lfsck->li_bottom;
2139         struct thandle           *th            = NULL;
2140         struct lustre_handle      lh            = { 0 };
2141         __u32                     ost_idx2      = le32_to_cpu(slot->l_ost_idx);
2142         int                       rc            = 0;
2143         ENTRY;
2144
2145         ostid_le_to_cpu(&slot->l_ost_oi, oi);
2146         rc = ostid_to_fid(cfid2, oi, ost_idx2);
2147         if (rc != 0)
2148                 GOTO(out, rc);
2149
2150         /* Hold layout lock on the parent to prevent others to access. */
2151         rc = lfsck_ibits_lock(env, com->lc_lfsck, parent, &lh,
2152                               MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR,
2153                               LCK_EX);
2154         if (rc != 0)
2155                 GOTO(out, rc);
2156
2157         rc = lfsck_layout_master_conditional_destroy(env, com, cfid2, ost_idx2);
2158
2159         /* If the conflict OST-obejct is not created for fixing dangling
2160          * referenced MDT-object in former LFSCK check/repair, or it has
2161          * been modified by others, then we cannot destroy it. Re-create
2162          * a new MDT-object for the orphan OST-object. */
2163         if (rc == -ETXTBSY) {
2164                 /* No need the layout lock on the original parent. */
2165                 lfsck_ibits_unlock(&lh, LCK_EX);
2166
2167                 fid_zero(&rec->lor_fid);
2168                 snprintf(info->lti_tmpbuf, sizeof(info->lti_tmpbuf),
2169                          "-"DFID"-%x", PFID(lu_object_fid(&parent->do_lu)),
2170                          ea_off);
2171                 rc = lfsck_layout_recreate_parent(env, com, ltd, rec, cfid,
2172                                                 info->lti_tmpbuf, "C", ea_off);
2173
2174                 RETURN(rc);
2175         }
2176
2177         if (rc != 0 && rc != -ENOENT)
2178                 GOTO(unlock, rc);
2179
2180         th = dt_trans_create(env, dev);
2181         if (IS_ERR(th))
2182                 GOTO(unlock, rc = PTR_ERR(th));
2183
2184         rc = dt_declare_xattr_set(env, parent, ea_buf, XATTR_NAME_LOV,
2185                                   LU_XATTR_REPLACE, th);
2186         if (rc != 0)
2187                 GOTO(stop, rc);
2188
2189         rc = dt_trans_start_local(env, dev, th);
2190         if (rc != 0)
2191                 GOTO(stop, rc);
2192
2193         dt_write_lock(env, parent, 0);
2194         lmm->lmm_layout_gen = cpu_to_le16(le16_to_cpu(lmm->lmm_layout_gen) + 1);
2195         rc = lfsck_layout_refill_lovea(env, th, parent, cfid, ea_buf, slot,
2196                                        LU_XATTR_REPLACE, ltd->ltd_index);
2197         dt_write_unlock(env, parent);
2198
2199         GOTO(stop, rc);
2200
2201 stop:
2202         dt_trans_stop(env, dev, th);
2203
2204 unlock:
2205         lfsck_ibits_unlock(&lh, LCK_EX);
2206
2207 out:
2208         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant replaced the conflict "
2209                "OST-object "DFID" on the OST %x with the orphan "DFID" on "
2210                "the OST %x: parent "DFID", stripe-index %u: rc = %d\n",
2211                lfsck_lfsck2name(com->lc_lfsck), PFID(cfid2), ost_idx2,
2212                PFID(cfid), ltd->ltd_index, PFID(lfsck_dto2fid(parent)),
2213                ea_off, rc);
2214
2215         return rc >= 0 ? 1 : rc;
2216 }
2217
2218 /**
2219  * \retval       +1: repaired
2220  * \retval        0: did nothing
2221  * \retval      -ve: on error
2222  */
2223 static int lfsck_layout_recreate_lovea(const struct lu_env *env,
2224                                        struct lfsck_component *com,
2225                                        struct lfsck_tgt_desc *ltd,
2226                                        struct lu_orphan_rec *rec,
2227                                        struct dt_object *parent,
2228                                        struct lu_fid *cfid,
2229                                        __u32 ost_idx, __u32 ea_off)
2230 {
2231         struct lfsck_thread_info *info          = lfsck_env_info(env);
2232         struct lu_buf            *buf           = &info->lti_big_buf;
2233         struct lu_fid            *fid           = &info->lti_fid2;
2234         struct ost_id            *oi            = &info->lti_oi;
2235         struct lfsck_instance    *lfsck         = com->lc_lfsck;
2236         struct dt_device         *dt            = lfsck->li_bottom;
2237         struct lfsck_bookmark    *bk            = &lfsck->li_bookmark_ram;
2238         struct thandle            *handle       = NULL;
2239         size_t                    lovea_size;
2240         struct lov_mds_md_v1     *lmm;
2241         struct lov_ost_data_v1   *objs;
2242         struct lustre_handle      lh            = { 0 };
2243         __u32                     magic;
2244         int                       fl            = 0;
2245         int                       rc            = 0;
2246         int                       rc1;
2247         int                       i;
2248         __u16                     count;
2249         bool                      locked        = false;
2250         ENTRY;
2251
2252         rc = lfsck_ibits_lock(env, lfsck, parent, &lh,
2253                               MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR,
2254                               LCK_EX);
2255         if (rc != 0) {
2256                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant failed to recreate "
2257                        "LOV EA for "DFID": parent "DFID", OST-index %u, "
2258                        "stripe-index %u: rc = %d\n",
2259                        lfsck_lfsck2name(lfsck), PFID(cfid),
2260                        PFID(lfsck_dto2fid(parent)), ost_idx, ea_off, rc);
2261
2262                 RETURN(rc);
2263         }
2264
2265 again:
2266         if (locked) {
2267                 dt_write_unlock(env, parent);
2268                 locked = false;
2269         }
2270
2271         if (handle != NULL) {
2272                 dt_trans_stop(env, dt, handle);
2273                 handle = NULL;
2274         }
2275
2276         if (rc < 0)
2277                 GOTO(unlock_layout, rc);
2278
2279         lovea_size = rc;
2280         if (buf->lb_len < lovea_size) {
2281                 lu_buf_realloc(buf, lovea_size);
2282                 if (buf->lb_buf == NULL)
2283                         GOTO(unlock_layout, rc = -ENOMEM);
2284         }
2285
2286         if (!(bk->lb_param & LPF_DRYRUN)) {
2287                 handle = dt_trans_create(env, dt);
2288                 if (IS_ERR(handle))
2289                         GOTO(unlock_layout, rc = PTR_ERR(handle));
2290
2291                 rc = dt_declare_xattr_set(env, parent, buf, XATTR_NAME_LOV,
2292                                           fl, handle);
2293                 if (rc != 0)
2294                         GOTO(stop, rc);
2295
2296                 rc = dt_trans_start_local(env, dt, handle);
2297                 if (rc != 0)
2298                         GOTO(stop, rc);
2299         }
2300
2301         dt_write_lock(env, parent, 0);
2302         locked = true;
2303         rc = dt_xattr_get(env, parent, buf, XATTR_NAME_LOV, BYPASS_CAPA);
2304         if (rc == -ERANGE) {
2305                 rc = dt_xattr_get(env, parent, &LU_BUF_NULL, XATTR_NAME_LOV,
2306                                   BYPASS_CAPA);
2307                 LASSERT(rc != 0);
2308                 goto again;
2309         } else if (rc == -ENODATA || rc == 0) {
2310                 lovea_size = lov_mds_md_size(ea_off + 1, LOV_MAGIC_V1);
2311                 /* If the declared is not big enough, re-try. */
2312                 if (buf->lb_len < lovea_size) {
2313                         rc = lovea_size;
2314                         goto again;
2315                 }
2316                 fl = LU_XATTR_CREATE;
2317         } else if (rc < 0) {
2318                 GOTO(unlock_parent, rc);
2319         } else if (unlikely(buf->lb_len == 0)) {
2320                 goto again;
2321         } else {
2322                 fl = LU_XATTR_REPLACE;
2323                 lovea_size = rc;
2324         }
2325
2326         if (fl == LU_XATTR_CREATE) {
2327                 if (bk->lb_param & LPF_DRYRUN)
2328                         GOTO(unlock_parent, rc = 1);
2329
2330                 LASSERT(buf->lb_len >= lovea_size);
2331
2332                 rc = lfsck_layout_extend_lovea(env, lfsck, handle, parent, cfid,
2333                                                buf, fl, ost_idx, ea_off, false);
2334
2335                 GOTO(unlock_parent, rc);
2336         }
2337
2338         lmm = buf->lb_buf;
2339         rc1 = lfsck_layout_verify_header(lmm);
2340
2341         /* If the LOV EA crashed, the rebuild it. */
2342         if (rc1 == -EINVAL) {
2343                 if (bk->lb_param & LPF_DRYRUN)
2344                         GOTO(unlock_parent, rc = 1);
2345
2346                 LASSERT(buf->lb_len >= lovea_size);
2347
2348                 rc = lfsck_layout_extend_lovea(env, lfsck, handle, parent, cfid,
2349                                                buf, fl, ost_idx, ea_off, true);
2350
2351                 GOTO(unlock_parent, rc);
2352         }
2353
2354         /* For other unknown magic/pattern, keep the current LOV EA. */
2355         if (rc1 != 0)
2356                 GOTO(unlock_parent, rc = rc1);
2357
2358         /* Currently, we only support LOV_MAGIC_V1/LOV_MAGIC_V3 which has
2359          * been verified in lfsck_layout_verify_header() already. If some
2360          * new magic introduced in the future, then layout LFSCK needs to
2361          * be updated also. */
2362         magic = le32_to_cpu(lmm->lmm_magic);
2363         if (magic == LOV_MAGIC_V1) {
2364                 objs = &lmm->lmm_objects[0];
2365         } else {
2366                 LASSERT(magic == LOV_MAGIC_V3);
2367                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[0];
2368         }
2369
2370         count = le16_to_cpu(lmm->lmm_stripe_count);
2371         if (count == 0)
2372                 GOTO(unlock_parent, rc = -EINVAL);
2373         LASSERT(count > 0);
2374
2375         /* Exceed the current end of MDT-object layout EA. Then extend it. */
2376         if (count <= ea_off) {
2377                 if (bk->lb_param & LPF_DRYRUN)
2378                         GOTO(unlock_parent, rc = 1);
2379
2380                 lovea_size = lov_mds_md_size(ea_off + 1, magic);
2381                 /* If the declared is not big enough, re-try. */
2382                 if (buf->lb_len < lovea_size) {
2383                         rc = lovea_size;
2384                         goto again;
2385                 }
2386
2387                 rc = lfsck_layout_extend_lovea(env, lfsck, handle, parent, cfid,
2388                                                buf, fl, ost_idx, ea_off, false);
2389
2390                 GOTO(unlock_parent, rc);
2391         }
2392
2393         LASSERTF(rc > 0, "invalid rc = %d\n", rc);
2394
2395         for (i = 0; i < count; i++, objs++) {
2396                 /* The MDT-object was created via lfsck_layout_recover_create()
2397                  * by others before, and we fill the dummy layout EA. */
2398                 if (lovea_slot_is_dummy(objs)) {
2399                         if (i != ea_off)
2400                                 continue;
2401
2402                         if (bk->lb_param & LPF_DRYRUN)
2403                                 GOTO(unlock_parent, rc = 1);
2404
2405                         lmm->lmm_layout_gen =
2406                             cpu_to_le16(le16_to_cpu(lmm->lmm_layout_gen) + 1);
2407                         rc = lfsck_layout_refill_lovea(env, handle, parent,
2408                                                        cfid, buf, objs, fl,
2409                                                        ost_idx);
2410
2411                         CDEBUG(D_LFSCK, "%s layout LFSCK assistant fill "
2412                                "dummy layout slot for "DFID": parent "DFID
2413                                ", OST-index %u, stripe-index %u: rc = %d\n",
2414                                lfsck_lfsck2name(lfsck), PFID(cfid),
2415                                PFID(lfsck_dto2fid(parent)), ost_idx, i, rc);
2416
2417                         GOTO(unlock_parent, rc);
2418                 }
2419
2420                 ostid_le_to_cpu(&objs->l_ost_oi, oi);
2421                 rc = ostid_to_fid(fid, oi, le32_to_cpu(objs->l_ost_idx));
2422                 if (rc != 0) {
2423                         CDEBUG(D_LFSCK, "%s: the parent "DFID" contains "
2424                                "invalid layout EA at the slot %d, index %u\n",
2425                                lfsck_lfsck2name(lfsck),
2426                                PFID(lfsck_dto2fid(parent)), i,
2427                                le32_to_cpu(objs->l_ost_idx));
2428
2429                         GOTO(unlock_parent, rc);
2430                 }
2431
2432                 /* It should be rare case, the slot is there, but the LFSCK
2433                  * does not handle it during the first-phase cycle scanning. */
2434                 if (unlikely(lu_fid_eq(fid, cfid))) {
2435                         if (i == ea_off) {
2436                                 GOTO(unlock_parent, rc = 0);
2437                         } else {
2438                                 /* Rare case that the OST-object index
2439                                  * does not match the parent MDT-object
2440                                  * layout EA. We trust the later one. */
2441                                 if (bk->lb_param & LPF_DRYRUN)
2442                                         GOTO(unlock_parent, rc = 1);
2443
2444                                 dt_write_unlock(env, parent);
2445                                 if (handle != NULL)
2446                                         dt_trans_stop(env, dt, handle);
2447                                 lfsck_ibits_unlock(&lh, LCK_EX);
2448                                 rc = lfsck_layout_update_pfid(env, com, parent,
2449                                                         cfid, ltd->ltd_tgt, i);
2450
2451                                 CDEBUG(D_LFSCK, "%s layout LFSCK assistant "
2452                                        "updated OST-object's pfid for "DFID
2453                                        ": parent "DFID", OST-index %u, "
2454                                        "stripe-index %u: rc = %d\n",
2455                                        lfsck_lfsck2name(lfsck), PFID(cfid),
2456                                        PFID(lfsck_dto2fid(parent)),
2457                                        ltd->ltd_index, i, rc);
2458
2459                                 RETURN(rc);
2460                         }
2461                 }
2462         }
2463
2464         /* The MDT-object exists, but related layout EA slot is occupied
2465          * by others. */
2466         if (bk->lb_param & LPF_DRYRUN)
2467                 GOTO(unlock_parent, rc = 1);
2468
2469         dt_write_unlock(env, parent);
2470         if (handle != NULL)
2471                 dt_trans_stop(env, dt, handle);
2472         lfsck_ibits_unlock(&lh, LCK_EX);
2473         if (le32_to_cpu(lmm->lmm_magic) == LOV_MAGIC_V1)
2474                 objs = &lmm->lmm_objects[ea_off];
2475         else
2476                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[ea_off];
2477         rc = lfsck_layout_conflict_create(env, com, ltd, rec, parent, cfid,
2478                                           buf, objs, ea_off);
2479
2480         RETURN(rc);
2481
2482 unlock_parent:
2483         if (locked)
2484                 dt_write_unlock(env, parent);
2485
2486 stop:
2487         if (handle != NULL)
2488                 dt_trans_stop(env, dt, handle);
2489
2490 unlock_layout:
2491         lfsck_ibits_unlock(&lh, LCK_EX);
2492
2493         return rc;
2494 }
2495
2496 static int lfsck_layout_scan_orphan_one(const struct lu_env *env,
2497                                         struct lfsck_component *com,
2498                                         struct lfsck_tgt_desc *ltd,
2499                                         struct lu_orphan_rec *rec,
2500                                         struct lu_fid *cfid)
2501 {
2502         struct lfsck_layout     *lo     = com->lc_file_ram;
2503         struct lu_fid           *pfid   = &rec->lor_fid;
2504         struct dt_object        *parent = NULL;
2505         __u32                    ea_off = pfid->f_stripe_idx;
2506         int                      rc     = 0;
2507         ENTRY;
2508
2509         if (!fid_is_sane(cfid))
2510                 GOTO(out, rc = -EINVAL);
2511
2512         if (fid_is_zero(pfid)) {
2513                 rc = lfsck_layout_recreate_parent(env, com, ltd, rec, cfid,
2514                                                   "", "N", ea_off);
2515                 GOTO(out, rc);
2516         }
2517
2518         pfid->f_ver = 0;
2519         if (!fid_is_sane(pfid))
2520                 GOTO(out, rc = -EINVAL);
2521
2522         parent = lfsck_object_find_by_dev(env, com->lc_lfsck->li_bottom, pfid);
2523         if (IS_ERR(parent))
2524                 GOTO(out, rc = PTR_ERR(parent));
2525
2526         if (unlikely(dt_object_remote(parent) != 0))
2527                 GOTO(put, rc = -EXDEV);
2528
2529         if (dt_object_exists(parent) == 0) {
2530                 lu_object_put(env, &parent->do_lu);
2531                 rc = lfsck_layout_recreate_parent(env, com, ltd, rec, cfid,
2532                                                   "", "R", ea_off);
2533                 GOTO(out, rc);
2534         }
2535
2536         if (!S_ISREG(lu_object_attr(&parent->do_lu)))
2537                 GOTO(put, rc = -EISDIR);
2538
2539         rc = lfsck_layout_recreate_lovea(env, com, ltd, rec, parent, cfid,
2540                                          ltd->ltd_index, ea_off);
2541
2542         GOTO(put, rc);
2543
2544 put:
2545         if (rc <= 0)
2546                 lu_object_put(env, &parent->do_lu);
2547         else
2548                 /* The layout EA is changed, need to be reloaded next time. */
2549                 lu_object_put_nocache(env, &parent->do_lu);
2550
2551 out:
2552         down_write(&com->lc_sem);
2553         com->lc_new_scanned++;
2554         com->lc_new_checked++;
2555         if (rc > 0) {
2556                 lo->ll_objs_repaired[LLIT_ORPHAN - 1]++;
2557                 rc = 0;
2558         } else if (rc < 0) {
2559                 lo->ll_objs_failed_phase2++;
2560         }
2561         up_write(&com->lc_sem);
2562
2563         return rc;
2564 }
2565
2566 static int lfsck_layout_scan_orphan(const struct lu_env *env,
2567                                     struct lfsck_component *com,
2568                                     struct lfsck_tgt_desc *ltd)
2569 {
2570         struct lfsck_assistant_data     *lad    = com->lc_data;
2571         struct lfsck_instance           *lfsck  = com->lc_lfsck;
2572         struct lfsck_bookmark           *bk     = &lfsck->li_bookmark_ram;
2573         struct lfsck_thread_info        *info   = lfsck_env_info(env);
2574         struct ost_id                   *oi     = &info->lti_oi;
2575         struct lu_fid                   *fid    = &info->lti_fid;
2576         struct dt_object                *obj;
2577         const struct dt_it_ops          *iops;
2578         struct dt_it                    *di;
2579         int                              rc     = 0;
2580         ENTRY;
2581
2582         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant starts the orphan "
2583                "scanning for OST%04x\n",
2584                lfsck_lfsck2name(lfsck), ltd->ltd_index);
2585
2586         if (cfs_bitmap_check(lad->lad_bitmap, ltd->ltd_index)) {
2587                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant skip the orphan "
2588                        "scanning for OST%04x\n",
2589                        lfsck_lfsck2name(lfsck), ltd->ltd_index);
2590
2591                 RETURN(0);
2592         }
2593
2594         ostid_set_seq(oi, FID_SEQ_IDIF);
2595         ostid_set_id(oi, 0);
2596         rc = ostid_to_fid(fid, oi, ltd->ltd_index);
2597         if (rc != 0)
2598                 GOTO(log, rc);
2599
2600         obj = lfsck_object_find_by_dev(env, ltd->ltd_tgt, fid);
2601         if (unlikely(IS_ERR(obj)))
2602                 GOTO(log, rc = PTR_ERR(obj));
2603
2604         rc = obj->do_ops->do_index_try(env, obj, &dt_lfsck_orphan_features);
2605         if (rc != 0)
2606                 GOTO(put, rc);
2607
2608         iops = &obj->do_index_ops->dio_it;
2609         di = iops->init(env, obj, 0, BYPASS_CAPA);
2610         if (IS_ERR(di))
2611                 GOTO(put, rc = PTR_ERR(di));
2612
2613         rc = iops->load(env, di, 0);
2614         if (rc == -ESRCH) {
2615                 /* -ESRCH means that the orphan OST-objects rbtree has been
2616                  * cleanup because of the OSS server restart or other errors. */
2617                 lfsck_lad_set_bitmap(env, com, ltd->ltd_index);
2618                 GOTO(fini, rc);
2619         }
2620
2621         if (rc == 0)
2622                 rc = iops->next(env, di);
2623         else if (rc > 0)
2624                 rc = 0;
2625
2626         if (rc < 0)
2627                 GOTO(fini, rc);
2628
2629         if (rc > 0)
2630                 GOTO(fini, rc = 0);
2631
2632         do {
2633                 struct dt_key           *key;
2634                 struct lu_orphan_rec    *rec = &info->lti_rec;
2635
2636                 if (CFS_FAIL_TIMEOUT(OBD_FAIL_LFSCK_DELAY3, cfs_fail_val) &&
2637                     unlikely(!thread_is_running(&lfsck->li_thread)))
2638                         break;
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 };