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