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