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