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