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