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