Whamcloud - gitweb
5a00031cb94c3eac6dfef9092c58be5834a13776
[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 ost_id                   *oi     = &info->lti_oi;
3100         struct lu_fid                   *fid    = &info->lti_fid;
3101         struct dt_object                *obj;
3102         const struct dt_it_ops          *iops;
3103         struct dt_it                    *di;
3104         int                              rc     = 0;
3105         ENTRY;
3106
3107         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant starts the orphan "
3108                "scanning for OST%04x\n",
3109                lfsck_lfsck2name(lfsck), ltd->ltd_index);
3110
3111         if (cfs_bitmap_check(lad->lad_bitmap, ltd->ltd_index)) {
3112                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant skip the orphan "
3113                        "scanning for OST%04x\n",
3114                        lfsck_lfsck2name(lfsck), ltd->ltd_index);
3115
3116                 RETURN(0);
3117         }
3118
3119         ostid_set_seq(oi, FID_SEQ_IDIF);
3120         rc = ostid_set_id(oi, 0);
3121         if (rc)
3122                 GOTO(log, rc);
3123
3124         rc = ostid_to_fid(fid, oi, ltd->ltd_index);
3125         if (rc != 0)
3126                 GOTO(log, rc);
3127
3128         obj = lfsck_object_find_by_dev(env, ltd->ltd_tgt, fid);
3129         if (unlikely(IS_ERR(obj)))
3130                 GOTO(log, rc = PTR_ERR(obj));
3131
3132         rc = obj->do_ops->do_index_try(env, obj,
3133                                        &dt_lfsck_layout_orphan_features);
3134         if (rc != 0)
3135                 GOTO(put, rc);
3136
3137         iops = &obj->do_index_ops->dio_it;
3138         di = iops->init(env, obj, 0);
3139         if (IS_ERR(di))
3140                 GOTO(put, rc = PTR_ERR(di));
3141
3142         rc = iops->load(env, di, 0);
3143         if (rc == -ESRCH) {
3144                 /* -ESRCH means that the orphan OST-objects rbtree has been
3145                  * cleanup because of the OSS server restart or other errors. */
3146                 lfsck_lad_set_bitmap(env, com, ltd->ltd_index);
3147                 GOTO(fini, rc);
3148         }
3149
3150         if (rc == 0)
3151                 rc = iops->next(env, di);
3152         else if (rc > 0)
3153                 rc = 0;
3154
3155         if (rc < 0)
3156                 GOTO(fini, rc);
3157
3158         if (rc > 0)
3159                 GOTO(fini, rc = 0);
3160
3161         do {
3162                 struct dt_key           *key;
3163                 struct lu_orphan_rec_v2 *rec = &info->lti_rec;
3164
3165                 if (CFS_FAIL_TIMEOUT(OBD_FAIL_LFSCK_DELAY3, cfs_fail_val) &&
3166                     unlikely(!thread_is_running(&lfsck->li_thread)))
3167                         break;
3168
3169                 key = iops->key(env, di);
3170                 com->lc_fid_latest_scanned_phase2 = *(struct lu_fid *)key;
3171                 /* Remote target OST may be runnning old LFSCK */
3172                 memset(rec, 0, sizeof(*rec));
3173                 rc = iops->rec(env, di, (struct dt_rec *)rec, 0);
3174                 if (rc == 0)
3175                         rc = lfsck_layout_scan_orphan_one(env, com, ltd, rec,
3176                                         &com->lc_fid_latest_scanned_phase2);
3177                 if (rc != 0 && bk->lb_param & LPF_FAILOUT)
3178                         GOTO(fini, rc);
3179
3180                 lfsck_control_speed_by_self(com);
3181                 do {
3182                         rc = iops->next(env, di);
3183                 } while (rc < 0 && !(bk->lb_param & LPF_FAILOUT));
3184         } while (rc == 0);
3185
3186         GOTO(fini, rc);
3187
3188 fini:
3189         iops->put(env, di);
3190         iops->fini(env, di);
3191 put:
3192         lfsck_object_put(env, obj);
3193
3194 log:
3195         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant finished the orphan "
3196                "scanning for OST%04x: rc = %d\n",
3197                lfsck_lfsck2name(lfsck), ltd->ltd_index, rc);
3198
3199         return rc > 0 ? 0 : rc;
3200 }
3201
3202 static int lfsck_lmm2layout(struct lov_mds_md_v1 *lmm, struct ost_layout *ol,
3203                             __u32 comp_id)
3204 {
3205         __u32 magic = le32_to_cpu(lmm->lmm_magic);
3206         int rc = 0;
3207         ENTRY;
3208
3209         if (magic == LOV_MAGIC_V1 || magic == LOV_MAGIC_V3) {
3210                 ol->ol_stripe_size = lmm->lmm_stripe_size;
3211                 ol->ol_stripe_count = lmm->lmm_stripe_count;
3212                 ol->ol_comp_start = 0;
3213                 ol->ol_comp_end = 0;
3214                 ol->ol_comp_id = 0;
3215         } else if (magic == LOV_MAGIC_COMP_V1) {
3216                 struct lov_comp_md_v1 *lcm = (struct lov_comp_md_v1 *)lmm;
3217                 struct lov_comp_md_entry_v1 *lcme = NULL;
3218                 __u16 count = le16_to_cpu(lcm->lcm_entry_count);
3219                 int i;
3220
3221                 for (i = 0; i < count; i++) {
3222                         lcme = &lcm->lcm_entries[i];
3223                         if (le32_to_cpu(lcme->lcme_id) == comp_id) {
3224                                 LASSERT(le32_to_cpu(lcme->lcme_flags) &
3225                                         LCME_FL_INIT);
3226
3227                                 break;
3228                         }
3229                 }
3230
3231                 /* The comp has been removed, do nothing. */
3232                 if (i == count)
3233                         GOTO(out, rc = 1);
3234
3235                 lmm = (void *)lmm + le32_to_cpu(lcme->lcme_offset);
3236                 ol->ol_stripe_size = le32_to_cpu(lmm->lmm_stripe_size);
3237                 ol->ol_stripe_count = le32_to_cpu(lmm->lmm_stripe_count);
3238                 ol->ol_comp_start = le64_to_cpu(lcme->lcme_extent.e_start);
3239                 ol->ol_comp_end = le64_to_cpu(lcme->lcme_extent.e_end);
3240                 ol->ol_comp_id = le32_to_cpu(lcme->lcme_id);
3241         } else {
3242                 GOTO(out, rc = -EINVAL);
3243         }
3244
3245         EXIT;
3246
3247 out:
3248         return rc;
3249 }
3250
3251 /**
3252  * Repair the MDT-object with dangling LOV EA reference.
3253  *
3254  * we need to repair the inconsistency according to the users' requirement:
3255  *
3256  * 1) Keep the inconsistency there and report the inconsistency case,
3257  *    then give the chance to the application to find related issues,
3258  *    and the users can make the decision about how to handle it with
3259  *    more human knownledge. (by default)
3260  *
3261  * 2) Re-create the missing OST-object with the FID/owner information.
3262  *
3263  * \param[in] env       pointer to the thread context
3264  * \param[in] com       the layout LFSCK component
3265  * \param[in] parent    the MDT-object with dangling LOV EA reference
3266  * \param[in] child     the OST-object to be created
3267  * \param[in] comp_id   the component ID of the OST-object in the LOV EA
3268  * \param[in] ea_off    the offset of the OST-object in the LOV EA
3269  * \param[in] ost_idx   the index of OST on which the OST-object resides
3270  *
3271  * \retval              +1 for repair successfully
3272  * \retval              0 for did nothing
3273  * \retval              negative error number on failure
3274  */
3275 static int __lfsck_layout_repair_dangling(const struct lu_env *env,
3276                                           struct lfsck_component *com,
3277                                           struct dt_object *parent,
3278                                           struct dt_object *child,
3279                                           __u32 comp_id, __u32 ea_off,
3280                                           __u32 ost_idx, bool log)
3281 {
3282         struct lfsck_thread_info *info = lfsck_env_info(env);
3283         struct filter_fid *ff = &info->lti_ff;
3284         struct ost_layout *ol = &ff->ff_layout;
3285         struct dt_object_format *dof = &info->lti_dof;
3286         struct lu_attr *la = &info->lti_la;
3287         struct lfsck_instance *lfsck = com->lc_lfsck;
3288         struct dt_device *dev = lfsck_obj2dev(child);
3289         const struct lu_fid *pfid = lfsck_dto2fid(parent);
3290         const struct lu_fid *cfid = lfsck_dto2fid(child);
3291         struct lu_buf *tbuf = &info->lti_big_buf;
3292         struct thandle *handle;
3293         struct lu_buf *buf;
3294         struct lustre_handle lh = { 0 };
3295         int rc;
3296         ENTRY;
3297
3298         if (!(lfsck->li_bookmark_ram.lb_param & LPF_CREATE_OSTOBJ))
3299                 GOTO(log, rc = 1);
3300
3301         rc = lfsck_ibits_lock(env, lfsck, parent, &lh,
3302                               MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR,
3303                               LCK_EX);
3304         if (rc != 0)
3305                 GOTO(log, rc);
3306
3307         rc = dt_attr_get(env, parent, la);
3308         if (rc != 0)
3309                 GOTO(unlock1, rc);
3310
3311         la->la_mode = S_IFREG | 0666;
3312         la->la_atime = la->la_mtime = la->la_ctime = 0;
3313         la->la_valid = LA_TYPE | LA_MODE | LA_UID | LA_GID |
3314                        LA_ATIME | LA_MTIME | LA_CTIME;
3315         memset(dof, 0, sizeof(*dof));
3316         ff->ff_parent.f_seq = cpu_to_le64(pfid->f_seq);
3317         ff->ff_parent.f_oid = cpu_to_le32(pfid->f_oid);
3318         /* Currently, the filter_fid::ff_parent::f_ver is not the real parent
3319          * MDT-object's FID::f_ver, instead it is the OST-object index in its
3320          * parent MDT-object's layout EA. */
3321         ff->ff_parent.f_stripe_idx = cpu_to_le32(ea_off);
3322
3323         rc = lfsck_layout_get_lovea(env, parent, tbuf);
3324         if (rc < 0)
3325                 GOTO(unlock1, rc);
3326
3327         rc = lfsck_lmm2layout(tbuf->lb_buf, ol, comp_id);
3328         if (rc)
3329                 GOTO(unlock1, rc);
3330
3331         buf = lfsck_buf_get(env, ff, sizeof(struct filter_fid));
3332         handle = dt_trans_create(env, dev);
3333         if (IS_ERR(handle))
3334                 GOTO(unlock1, rc = PTR_ERR(handle));
3335
3336         rc = dt_declare_create(env, child, la, NULL, dof, handle);
3337         if (rc != 0)
3338                 GOTO(stop, rc);
3339
3340         rc = dt_declare_xattr_set(env, child, buf, XATTR_NAME_FID,
3341                                   LU_XATTR_CREATE, handle);
3342         if (rc != 0)
3343                 GOTO(stop, rc);
3344
3345         rc = dt_trans_start_local(env, dev, handle);
3346         if (rc != 0)
3347                 GOTO(stop, rc);
3348
3349         dt_read_lock(env, parent, 0);
3350         if (unlikely(lfsck_is_dead_obj(parent)))
3351                 GOTO(unlock2, rc = 0);
3352
3353         if (lfsck->li_bookmark_ram.lb_param & LPF_DELAY_CREATE_OSTOBJ) {
3354                 struct ost_id *oi = &info->lti_oi;
3355                 struct lu_fid *tfid = &info->lti_fid2;
3356                 struct lu_buf *lovea = &info->lti_big_buf;
3357                 struct lov_mds_md_v1 *lmm;
3358                 struct lov_ost_data_v1 *objs;
3359                 __u32 magic;
3360                 int count;
3361                 int idx2;
3362
3363                 rc = lfsck_layout_get_lovea(env, parent, lovea);
3364                 if (rc <= 0)
3365                         GOTO(unlock2, rc);
3366
3367                 lmm = lovea->lb_buf;
3368                 magic = le32_to_cpu(lmm->lmm_magic);
3369                 if (magic == LOV_MAGIC_COMP_V1) {
3370                         struct lov_comp_md_v1 *lcm = buf->lb_buf;
3371                         struct lov_comp_md_entry_v1 *lcme;
3372                         __u16 count = le16_to_cpu(lcm->lcm_entry_count);
3373                         int i;
3374
3375                         for (i = 0; i < count; i++) {
3376                                 lcme = &lcm->lcm_entries[i];
3377                                 if (le32_to_cpu(lcme->lcme_id) == comp_id) {
3378                                         LASSERT(le32_to_cpu(lcme->lcme_flags) &
3379                                                 LCME_FL_INIT);
3380
3381                                         lmm = lovea->lb_buf +
3382                                                 le32_to_cpu(lcme->lcme_offset);
3383                                         magic = le32_to_cpu(lmm->lmm_magic);
3384                                         goto check;
3385                                 }
3386                         }
3387
3388                         /* Someone removed the component, do nothing. */
3389                         GOTO(unlock2, rc = 0);
3390                 }
3391
3392 check:
3393                 count = le16_to_cpu(lmm->lmm_stripe_count);
3394                 /* Someone changed the LOV EA, do nothing. */
3395                 if (count <= ea_off)
3396                         GOTO(unlock2, rc = 0);
3397
3398                 if (magic == LOV_MAGIC_V1) {
3399                         objs = &lmm->lmm_objects[ea_off];
3400                 } else {
3401                         LASSERT(magic == LOV_MAGIC_V3);
3402
3403                         objs = &((struct lov_mds_md_v3 *)lmm)->\
3404                                                         lmm_objects[ea_off];
3405                 }
3406
3407                 ostid_le_to_cpu(&objs->l_ost_oi, oi);
3408                 idx2 = le32_to_cpu(objs->l_ost_idx);
3409                 rc = ostid_to_fid(tfid, oi, idx2);
3410                 /* Someone changed the LOV EA, do nothing. */
3411                 if (rc != 0 || !lu_fid_eq(tfid, cfid))
3412                         GOTO(unlock2, rc);
3413         }
3414
3415         rc = dt_create(env, child, la, NULL, dof, handle);
3416         if (rc != 0)
3417                 GOTO(unlock2, rc);
3418
3419         rc = dt_xattr_set(env, child, buf, XATTR_NAME_FID, LU_XATTR_CREATE,
3420                           handle);
3421
3422         GOTO(unlock2, rc);
3423
3424 unlock2:
3425         dt_read_unlock(env, parent);
3426
3427 stop:
3428         rc = lfsck_layout_trans_stop(env, dev, handle, rc);
3429
3430 unlock1:
3431         lfsck_ibits_unlock(&lh, LCK_EX);
3432
3433 log:
3434         if (rc && log)
3435                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant found "
3436                        "dangling reference for: parent "DFID", child "
3437                        DFID", comp_id %u, ea_off %u, ost_idx %u, %s: "
3438                        "rc = %d\n",
3439                        lfsck_lfsck2name(lfsck), PFID(pfid), PFID(cfid),
3440                        comp_id, ea_off, ost_idx,
3441                        (lfsck->li_bookmark_ram.lb_param & LPF_CREATE_OSTOBJ) ?
3442                                 "Create the lost OST-object as required" :
3443                                 "Keep the MDT-object there by default", rc);
3444
3445         return rc;
3446 }
3447
3448 /**
3449  * Repair the MDT-object with dangling LOV EA reference.
3450  *
3451  * Prepare parameters and call __lfsck_layout_repair_dangling()
3452  * to repair the dangling LOV EA reference.
3453  *
3454  * \param[in] env       pointer to the thread context
3455  * \param[in] com       the layout LFSCK component
3456  * \param[in] pfid      the MDT-object's FID
3457  * \param[in] cfid      the FID for the OST-object to be created
3458  * \param[in] comp_id   the component ID of the OST-object in the LOV EA
3459  * \param[in] ea_off    the offset of the OST-object in the LOV EA
3460  * \param[in] ost_idx   the index of OST on which the OST-object resides
3461  *
3462  * \retval              +1 for repair successfully
3463  * \retval              0 for did nothing
3464  * \retval              negative error number on failure
3465  */
3466 static int lfsck_layout_repair_dangling(const struct lu_env *env,
3467                                         struct lfsck_component *com,
3468                                         const struct lu_fid *pfid,
3469                                         const struct lu_fid *cfid,
3470                                         __u32 comp_id, __u32 ea_off,
3471                                         __u32 ost_idx)
3472 {
3473         struct lfsck_instance *lfsck = com->lc_lfsck;
3474         struct dt_object *parent = NULL;
3475         struct dt_object *child = NULL;
3476         struct lfsck_tgt_desc *ltd;
3477         int rc;
3478         ENTRY;
3479
3480         parent = lfsck_object_find_bottom(env, lfsck, pfid);
3481         if (IS_ERR(parent))
3482                 GOTO(log, rc = PTR_ERR(parent));
3483
3484         /* The MDT-object has been removed. */
3485         if (dt_object_exists(parent) == 0)
3486                 GOTO(log, rc = 0);
3487
3488         ltd = lfsck_ltd2tgt(&lfsck->li_ost_descs, ost_idx);
3489         if (unlikely(ltd == NULL))
3490                 GOTO(log, rc = -ENODEV);
3491
3492         child = lfsck_object_find_by_dev(env, ltd->ltd_tgt, cfid);
3493         if (IS_ERR(child))
3494                 GOTO(log, rc = PTR_ERR(child));
3495
3496         /* The OST-object has been created. */
3497         if (unlikely(dt_object_exists(child) != 0))
3498                 GOTO(log, rc = 0);
3499
3500         rc = __lfsck_layout_repair_dangling(env, com, parent, child,
3501                                             comp_id, ea_off, ost_idx, false);
3502
3503         GOTO(log, rc);
3504
3505 log:
3506         if (child != NULL && !IS_ERR(child))
3507                 lfsck_object_put(env, child);
3508
3509         if (parent != NULL && !IS_ERR(parent))
3510                 lfsck_object_put(env, parent);
3511
3512         if (rc)
3513                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant found "
3514                        "dangling reference for: parent "DFID", child "
3515                        DFID", comp_id %u, ea_off %u, ost_idx %u, %s: rc = %d\n",
3516                        lfsck_lfsck2name(lfsck), PFID(pfid), PFID(cfid),
3517                        comp_id, ea_off, ost_idx,
3518                        (lfsck->li_bookmark_ram.lb_param & LPF_CREATE_OSTOBJ) ?
3519                                 "Create the lost OST-object as required" :
3520                                 "Keep the MDT-object there by default", rc);
3521
3522         return rc;
3523 }
3524
3525 /* If the OST-object does not recognize the MDT-object as its parent, and
3526  * there is no other MDT-object claims as its parent, then just trust the
3527  * given MDT-object as its parent. So update the OST-object filter_fid. */
3528 static int lfsck_layout_repair_unmatched_pair(const struct lu_env *env,
3529                                               struct lfsck_component *com,
3530                                               struct dt_object *parent,
3531                                               struct lfsck_layout_req *llr,
3532                                               struct lu_attr *la)
3533 {
3534         struct lfsck_thread_info        *info   = lfsck_env_info(env);
3535         struct filter_fid               *ff     = &info->lti_ff;
3536         struct ost_layout               *ol     = &ff->ff_layout;
3537         struct dt_object                *child  = llr->llr_child;
3538         struct dt_device                *dev    = lfsck_obj2dev(child);
3539         const struct lu_fid             *tfid   = lu_object_fid(&parent->do_lu);
3540         struct lu_buf                   *tbuf   = &info->lti_big_buf;
3541         struct thandle                  *handle;
3542         struct lu_buf                   *buf;
3543         struct lustre_handle             lh     = { 0 };
3544         int                              rc;
3545         ENTRY;
3546
3547         rc = lfsck_ibits_lock(env, com->lc_lfsck, parent, &lh,
3548                               MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR,
3549                               LCK_EX);
3550         if (rc != 0)
3551                 GOTO(log, rc);
3552
3553         ff->ff_parent.f_seq = cpu_to_le64(tfid->f_seq);
3554         ff->ff_parent.f_oid = cpu_to_le32(tfid->f_oid);
3555         /* Currently, the filter_fid::ff_parent::f_ver is not the real parent
3556          * MDT-object's FID::f_ver, instead it is the OST-object index in its
3557          * parent MDT-object's layout EA. */
3558         ff->ff_parent.f_stripe_idx = cpu_to_le32(llr->llr_lov_idx);
3559
3560         rc = lfsck_layout_get_lovea(env, parent, tbuf);
3561         if (rc < 0)
3562                 GOTO(unlock1, rc);
3563
3564         rc = lfsck_lmm2layout(tbuf->lb_buf, ol, llr->llr_comp_id);
3565         if (rc)
3566                 GOTO(unlock1, rc);
3567
3568         buf = lfsck_buf_get(env, ff, sizeof(*ff));
3569
3570         handle = dt_trans_create(env, dev);
3571         if (IS_ERR(handle))
3572                 GOTO(unlock1, rc = PTR_ERR(handle));
3573
3574         rc = dt_declare_xattr_set(env, child, buf, XATTR_NAME_FID, 0, handle);
3575         if (rc != 0)
3576                 GOTO(stop, rc);
3577
3578         rc = dt_attr_get(env, parent, la);
3579         if (rc != 0)
3580                 GOTO(stop, rc);
3581
3582         la->la_valid = LA_UID | LA_GID;
3583         rc = dt_declare_attr_set(env, child, la, handle);
3584         if (rc != 0)
3585                 GOTO(stop, rc);
3586
3587         rc = dt_trans_start_local(env, dev, handle);
3588         if (rc != 0)
3589                 GOTO(stop, rc);
3590
3591         dt_write_lock(env, parent, 0);
3592         if (unlikely(lfsck_is_dead_obj(parent)))
3593                 GOTO(unlock2, rc = 1);
3594
3595         rc = dt_xattr_set(env, child, buf, XATTR_NAME_FID, 0, handle);
3596         if (rc != 0)
3597                 GOTO(unlock2, rc);
3598
3599         /* Get the latest parent's owner. */
3600         rc = dt_attr_get(env, parent, la);
3601         if (rc != 0)
3602                 GOTO(unlock2, rc);
3603
3604         la->la_valid = LA_UID | LA_GID;
3605         rc = dt_attr_set(env, child, la, handle);
3606
3607         GOTO(unlock2, rc);
3608
3609 unlock2:
3610         dt_write_unlock(env, parent);
3611
3612 stop:
3613         rc = lfsck_layout_trans_stop(env, dev, handle, rc);
3614
3615 unlock1:
3616         lfsck_ibits_unlock(&lh, LCK_EX);
3617
3618 log:
3619         if (rc)
3620                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant repaired "
3621                        "unmatched MDT-OST pair for: parent "DFID
3622                        ", child "DFID", comp_id %u, OST-index %u, "
3623                        "stripe-index %u, owner %u/%u: rc = %d\n",
3624                        lfsck_lfsck2name(com->lc_lfsck),
3625                        PFID(lfsck_dto2fid(parent)),
3626                        PFID(lfsck_dto2fid(child)),
3627                        llr->llr_comp_id, llr->llr_ost_idx, llr->llr_lov_idx,
3628                        la->la_uid, la->la_gid, rc);
3629
3630         return rc;
3631 }
3632
3633 /* If there are more than one MDT-objects claim as the OST-object's parent,
3634  * and the OST-object only recognizes one of them, then we need to generate
3635  * new OST-object(s) with new fid(s) for the non-recognized MDT-object(s). */
3636 static int lfsck_layout_repair_multiple_references(const struct lu_env *env,
3637                                                    struct lfsck_component *com,
3638                                                    struct dt_object *parent,
3639                                                    struct lfsck_layout_req *llr,
3640                                                    struct lu_attr *la)
3641 {
3642         struct lfsck_thread_info        *info   = lfsck_env_info(env);
3643         struct dt_allocation_hint       *hint   = &info->lti_hint;
3644         struct dt_object_format         *dof    = &info->lti_dof;
3645         struct ost_id                   *oi     = &info->lti_oi;
3646         struct lu_buf                   *buf    = &info->lti_big_buf;
3647         struct lfsck_instance           *lfsck  = com->lc_lfsck;
3648         struct dt_device                *dev;
3649         struct lu_device                *d      =
3650                                 &lfsck_obj2dev(llr->llr_child)->dd_lu_dev;
3651         struct lu_object                *o;
3652         struct lu_object                *n;
3653         struct dt_object                *child  = NULL;
3654         struct thandle                  *handle = NULL;
3655         struct lov_mds_md_v1            *lmm;
3656         struct lov_ost_data_v1          *objs;
3657         const struct lu_fid             *pfid   = lfsck_dto2fid(parent);
3658         struct lu_fid                    tfid;
3659         struct lustre_handle             lh     = { 0 };
3660         __u32                            magic;
3661         __u32                            index;
3662         int                              rc;
3663         ENTRY;
3664
3665         /* We use two separated transactions to repair the inconsistency.
3666          *
3667          * 1) create the child (OST-object).
3668          * 2) update the parent LOV EA according to the child's FID.
3669          *
3670          * If 1) succeed, but 2) failed or aborted, then such OST-object will be
3671          * handled as orphan when the layout LFSCK run next time.
3672          *
3673          * If 1) failed, but 2) succeed, then such OST-object will be re-created
3674          * as dangling referened case when the layout LFSCK run next time. */
3675
3676         /* The 1st transaction. */
3677         o = lu_object_anon(env, d, NULL);
3678         if (IS_ERR(o))
3679                 GOTO(log, rc = PTR_ERR(o));
3680
3681         n = lu_object_locate(o->lo_header, d->ld_type);
3682         if (unlikely(n == NULL)) {
3683                 lu_object_put_nocache(env, o);
3684
3685                 GOTO(log, rc = -EINVAL);
3686         }
3687
3688         child = container_of(n, struct dt_object, do_lu);
3689         memset(hint, 0, sizeof(*hint));
3690         rc = dt_attr_get(env, parent, la);
3691         if (rc != 0)
3692                 GOTO(log, rc);
3693
3694         la->la_valid = LA_UID | LA_GID;
3695         memset(dof, 0, sizeof(*dof));
3696
3697         dev = lfsck_obj2dev(child);
3698         handle = dt_trans_create(env, dev);
3699         if (IS_ERR(handle))
3700                 GOTO(log, rc = PTR_ERR(handle));
3701
3702         rc = dt_declare_create(env, child, la, hint, dof, handle);
3703         if (rc != 0)
3704                 GOTO(stop, rc);
3705
3706         rc = dt_trans_start_local(env, dev, handle);
3707         if (rc != 0)
3708                 GOTO(stop, rc);
3709
3710         rc = dt_create(env, child, la, hint, dof, handle);
3711         dt_trans_stop(env, dev, handle);
3712         handle = NULL;
3713         if (rc != 0)
3714                 GOTO(log, rc);
3715
3716         rc = lfsck_ibits_lock(env, lfsck, parent, &lh,
3717                               MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR,
3718                               LCK_EX);
3719         if (rc != 0)
3720                 GOTO(log, rc);
3721
3722         /* The 2nd transaction. */
3723
3724         /* XXX: Generally, we should use bottom device (OSD) to update parent
3725          *      LOV EA. But because the LOD-object still references the wrong
3726          *      OSP-object that should be detached after the parent's LOV EA
3727          *      refreshed. Unfortunately, there is no suitable API for that.
3728          *      So we have to make the LOD to re-load the OSP-object(s) via
3729          *      replacing the LOV EA against the LOD-object.
3730          *
3731          *      Once the DNE2 patches have been landed, we can replace the
3732          *      LOD device with the OSD device. LU-6230. */
3733
3734         dev = lfsck->li_next;
3735         parent = lfsck_object_locate(dev, parent);
3736         if (IS_ERR(parent))
3737                 GOTO(log, rc = PTR_ERR(parent));
3738
3739         handle = dt_trans_create(env, dev);
3740         if (IS_ERR(handle))
3741                 GOTO(log, rc = PTR_ERR(handle));
3742
3743         rc = dt_declare_xattr_set(env, parent, buf, XATTR_NAME_LOV,
3744                                   LU_XATTR_REPLACE, handle);
3745         if (rc != 0)
3746                 GOTO(stop, rc);
3747
3748         rc = dt_trans_start_local(env, dev, handle);
3749         if (rc != 0)
3750                 GOTO(stop, rc);
3751
3752         dt_write_lock(env, parent, 0);
3753         if (unlikely(lfsck_is_dead_obj(parent)))
3754                 GOTO(unlock, rc = 0);
3755
3756         rc = lfsck_layout_get_lovea(env, parent, buf);
3757         if (unlikely(!rc || rc == -ENODATA))
3758                 GOTO(unlock, rc = 0);
3759
3760         lmm = buf->lb_buf;
3761         magic = le32_to_cpu(lmm->lmm_magic);
3762         if (magic == LOV_MAGIC_COMP_V1) {
3763                 struct lov_comp_md_v1 *lcm = buf->lb_buf;
3764                 struct lov_comp_md_entry_v1 *lcme;
3765                 __u16 count = le16_to_cpu(lcm->lcm_entry_count);
3766                 int i;
3767
3768                 LASSERT(llr->llr_comp_id != 0);
3769
3770                 for (i = 0; i < count; i++) {
3771                         lcme = &lcm->lcm_entries[i];
3772                         if (le32_to_cpu(lcme->lcme_id) == llr->llr_comp_id) {
3773                                 LASSERT(le32_to_cpu(lcme->lcme_flags) &
3774                                         LCME_FL_INIT);
3775
3776                                 le32_add_cpu(&lcm->lcm_layout_gen, 1);
3777                                 lmm = buf->lb_buf +
3778                                         le32_to_cpu(lcme->lcme_offset);
3779                                 magic = le32_to_cpu(lmm->lmm_magic);
3780                                 goto set;
3781                         }
3782                 }
3783
3784                 GOTO(unlock, rc = 0);
3785         }
3786
3787 set:
3788         if (magic == LOV_MAGIC_V1) {
3789                 objs = &lmm->lmm_objects[llr->llr_lov_idx];
3790         } else {
3791                 LASSERT(magic == LOV_MAGIC_V3);
3792                 objs =
3793                 &((struct lov_mds_md_v3 *)lmm)->lmm_objects[llr->llr_lov_idx];
3794         }
3795
3796         ostid_le_to_cpu(&objs->l_ost_oi, oi);
3797         index = le32_to_cpu(objs->l_ost_idx);
3798         rc = ostid_to_fid(&tfid, oi, index);
3799         /* Someone changed layout during the LFSCK, no need to repair then. */
3800         if (rc == 0 && !lu_fid_eq(&tfid, lu_object_fid(&llr->llr_child->do_lu)))
3801                 GOTO(unlock, rc = 0);
3802
3803         lmm->lmm_layout_gen = cpu_to_le16(le16_to_cpu(lmm->lmm_layout_gen) + 1);
3804         fid_to_ostid(lu_object_fid(&child->do_lu), oi);
3805         ostid_cpu_to_le(oi, &objs->l_ost_oi);
3806         objs->l_ost_gen = cpu_to_le32(0);
3807         objs->l_ost_idx = cpu_to_le32(llr->llr_ost_idx);
3808         rc = dt_xattr_set(env, parent, buf, XATTR_NAME_LOV,
3809                           LU_XATTR_REPLACE, handle);
3810
3811         GOTO(unlock, rc = (rc == 0 ? 1 : rc));
3812
3813 unlock:
3814         dt_write_unlock(env, parent);
3815
3816 stop:
3817         if (handle != NULL)
3818                 dt_trans_stop(env, dev, handle);
3819
3820 log:
3821         lfsck_ibits_unlock(&lh, LCK_EX);
3822         if (child != NULL)
3823                 lfsck_object_put(env, child);
3824
3825         if (rc)
3826                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant repaired "
3827                        "multiple references for: parent "DFID", comp_id %u, "
3828                        "OST-index %u, stripe-index %u, owner %u/%u: rc = %d\n",
3829                        lfsck_lfsck2name(lfsck), PFID(pfid),
3830                        llr->llr_comp_id, llr->llr_ost_idx, llr->llr_lov_idx,
3831                        la->la_uid, la->la_gid, rc);
3832
3833         return rc;
3834 }
3835
3836 /* If the MDT-object and the OST-object have different owner information,
3837  * then trust the MDT-object, because the normal chown/chgrp handle order
3838  * is from MDT to OST, and it is possible that some chown/chgrp operation
3839  * is partly done. */
3840 static int lfsck_layout_repair_owner(const struct lu_env *env,
3841                                      struct lfsck_component *com,
3842                                      struct dt_object *parent,
3843                                      struct lfsck_layout_req *llr,
3844                                      struct lu_attr *pla,
3845                                      const struct lu_attr *cla)
3846 {
3847         struct lfsck_thread_info        *info   = lfsck_env_info(env);
3848         struct lu_attr                  *tla    = &info->lti_la2;
3849         struct dt_object                *child  = llr->llr_child;
3850         struct dt_device                *dev    = lfsck_obj2dev(child);
3851         struct thandle                  *handle;
3852         int                              rc;
3853         ENTRY;
3854
3855         tla->la_uid = pla->la_uid;
3856         tla->la_gid = pla->la_gid;
3857         tla->la_valid = LA_UID | LA_GID;
3858         handle = dt_trans_create(env, dev);
3859         if (IS_ERR(handle))
3860                 GOTO(log, rc = PTR_ERR(handle));
3861
3862         rc = dt_declare_attr_set(env, child, tla, handle);
3863         if (rc != 0)
3864                 GOTO(stop, rc);
3865
3866         rc = dt_trans_start_local(env, dev, handle);
3867         if (rc != 0)
3868                 GOTO(stop, rc);
3869
3870         /* Use the dt_object lock to serialize with destroy and attr_set. */
3871         dt_read_lock(env, parent, 0);
3872         if (unlikely(lfsck_is_dead_obj(parent)))
3873                 GOTO(unlock, rc = 1);
3874
3875         /* Get the latest parent's owner. */
3876         rc = dt_attr_get(env, parent, pla);
3877         if (rc != 0)
3878                 GOTO(unlock, rc);
3879
3880         /* Some others chown/chgrp during the LFSCK, needs to do nothing. */
3881         if (unlikely(tla->la_uid != pla->la_uid ||
3882                      tla->la_gid != pla->la_gid))
3883                 rc = 1;
3884         else
3885                 rc = dt_attr_set(env, child, tla, handle);
3886
3887         GOTO(unlock, rc);
3888
3889 unlock:
3890         dt_read_unlock(env, parent);
3891
3892 stop:
3893         rc = lfsck_layout_trans_stop(env, dev, handle, rc);
3894
3895 log:
3896         if (rc != 0)
3897                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant repaired "
3898                        "inconsistent file owner for: parent "DFID", child "DFID
3899                        ", OST-index %u, stripe-index %u, old owner %u/%u, "
3900                        "new owner %u/%u: rc = %d\n",
3901                        lfsck_lfsck2name(com->lc_lfsck),
3902                        PFID(lfsck_dto2fid(parent)), PFID(lfsck_dto2fid(child)),
3903                        llr->llr_ost_idx, llr->llr_lov_idx,
3904                        cla->la_uid, cla->la_gid, tla->la_uid, tla->la_gid, rc);
3905
3906         return rc;
3907 }
3908
3909 /* Check whether the OST-object correctly back points to the
3910  * MDT-object (@parent) via the XATTR_NAME_FID xattr (@pfid). */
3911 static int lfsck_layout_check_parent(const struct lu_env *env,
3912                                      struct lfsck_component *com,
3913                                      struct lfsck_assistant_object *lso,
3914                                      struct filter_fid *ff,
3915                                      const struct lu_fid *cfid,
3916                                      const struct lu_attr *cla,
3917                                      struct lfsck_layout_req *llr)
3918 {
3919         struct lfsck_thread_info        *info   = lfsck_env_info(env);
3920         struct lu_buf                   *buf    = &info->lti_big_buf;
3921         struct lu_fid                   *pfid   = &info->lti_fid;
3922         struct dt_object                *tobj;
3923         struct lov_mds_md_v1            *lmm;
3924         struct lov_ost_data_v1          *objs;
3925         struct lustre_handle             lh     = { 0 };
3926         int                              rc;
3927         int                              i;
3928         __u32                            magic;
3929         __u32                            idx;
3930         __u16                            count;
3931         ENTRY;
3932
3933         *pfid = ff->ff_parent;
3934         idx = pfid->f_stripe_idx;
3935         pfid->f_ver = 0;
3936
3937         if (unlikely(!fid_is_sane(pfid)))
3938                 RETURN(LLIT_UNMATCHED_PAIR);
3939
3940         if (lu_fid_eq(pfid, &lso->lso_fid)) {
3941                 if (likely(llr->llr_lov_idx == idx))
3942                         RETURN(0);
3943
3944                 RETURN(LLIT_UNMATCHED_PAIR);
3945         }
3946
3947         tobj = lfsck_object_find_bottom(env, com->lc_lfsck, pfid);
3948         if (IS_ERR(tobj))
3949                 RETURN(PTR_ERR(tobj));
3950
3951         if (dt_object_exists(tobj) == 0 || lfsck_is_dead_obj(tobj) ||
3952             !S_ISREG(lfsck_object_type(tobj)))
3953                 GOTO(out, rc = LLIT_UNMATCHED_PAIR);
3954
3955         /* Load the tobj's layout EA, in spite of it is a local MDT-object or
3956          * remote one on another MDT. Then check whether the given OST-object
3957          * is in such layout. If yes, it is multiple referenced, otherwise it
3958          * is unmatched referenced case. */
3959         rc = lfsck_layout_get_lovea(env, tobj, buf);
3960         if (rc == 0 || rc == -ENOENT)
3961                 GOTO(out, rc = LLIT_UNMATCHED_PAIR);
3962
3963         if (rc < 0)
3964                 GOTO(out, rc);
3965
3966         lmm = buf->lb_buf;
3967         magic = le32_to_cpu(lmm->lmm_magic);
3968         if (magic == LOV_MAGIC_COMP_V1) {
3969                 struct lov_comp_md_v1 *lcm = buf->lb_buf;
3970                 struct lov_comp_md_entry_v1 *lcme;
3971
3972                 if (ff->ff_layout.ol_comp_id == 0)
3973                         GOTO(out, rc = LLIT_UNMATCHED_PAIR);
3974
3975                 count = le16_to_cpu(lcm->lcm_entry_count);
3976                 for (i = 0; i < count; i++) {
3977                         lcme = &lcm->lcm_entries[i];
3978                         if (le32_to_cpu(lcme->lcme_id) ==
3979                             ff->ff_layout.ol_comp_id) {
3980                                 lmm = buf->lb_buf +
3981                                         le32_to_cpu(lcme->lcme_offset);
3982                                 magic = le32_to_cpu(lmm->lmm_magic);
3983                                 if (!(le32_to_cpu(lcme->lcme_flags) &
3984                                       LCME_FL_INIT))
3985                                         GOTO(out, rc = LLIT_UNMATCHED_PAIR);
3986
3987                                 goto further;
3988                         }
3989                 }
3990
3991                 GOTO(out, rc = LLIT_UNMATCHED_PAIR);
3992         }
3993
3994 further:
3995         if (magic == LOV_MAGIC_V1) {
3996                 objs = &lmm->lmm_objects[0];
3997         } else {
3998                 LASSERT(magic == LOV_MAGIC_V3);
3999                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[0];
4000         }
4001
4002         count = le16_to_cpu(lmm->lmm_stripe_count);
4003         for (i = 0; i < count; i++, objs++) {
4004                 struct lu_fid           *tfid   = &info->lti_fid2;
4005                 struct ost_id           *oi     = &info->lti_oi;
4006                 __u32                    idx2;
4007
4008                 if (lovea_slot_is_dummy(objs))
4009                         continue;
4010
4011                 ostid_le_to_cpu(&objs->l_ost_oi, oi);
4012                 idx2 = le32_to_cpu(objs->l_ost_idx);
4013                 rc = ostid_to_fid(tfid, oi, idx2);
4014                 if (rc != 0) {
4015                         CDEBUG(D_LFSCK, "%s: the parent "DFID" contains "
4016                                "invalid layout EA at the slot %d, index %u\n",
4017                                lfsck_lfsck2name(com->lc_lfsck),
4018                                PFID(pfid), i, idx2);
4019
4020                         GOTO(out, rc = LLIT_UNMATCHED_PAIR);
4021                 }
4022
4023                 if (lu_fid_eq(cfid, tfid)) {
4024                         rc = lfsck_ibits_lock(env, com->lc_lfsck, tobj, &lh,
4025                                               MDS_INODELOCK_UPDATE |
4026                                               MDS_INODELOCK_LAYOUT |
4027                                               MDS_INODELOCK_XATTR,
4028                                               LCK_EX);
4029                         if (rc != 0)
4030                                 GOTO(out, rc);
4031
4032                         dt_read_lock(env, tobj, 0);
4033
4034                         /* For local MDT-object, re-check existence
4035                          * after taken the lock. */
4036                         if (!dt_object_remote(tobj)) {
4037                                 if (dt_object_exists(tobj) == 0 ||
4038                                     lfsck_is_dead_obj(tobj))
4039                                         rc = LLIT_UNMATCHED_PAIR;
4040                                 else
4041                                         rc = LLIT_MULTIPLE_REFERENCED;
4042
4043                                 GOTO(unlock, rc);
4044                         }
4045
4046                         /* For migration case, the new MDT-object and old
4047                          * MDT-object may reference the same OST-object at
4048                          * some migration internal time.
4049                          *
4050                          * For remote MDT-object, the local MDT may not know
4051                          * whether it has been removed or not.  Try checking
4052                          * for a non-existent xattr to check if this object
4053                          * has been been removed or not. */
4054                         rc = dt_xattr_get(env, tobj, &LU_BUF_NULL,
4055                                           XATTR_NAME_DUMMY);
4056                         if (unlikely(rc == -ENOENT || rc >= 0))
4057                                 rc = LLIT_UNMATCHED_PAIR;
4058                         else if (rc == -ENODATA)
4059                                 rc = LLIT_MULTIPLE_REFERENCED;
4060
4061                         GOTO(unlock, rc);
4062                 }
4063         }
4064
4065         GOTO(out, rc = LLIT_UNMATCHED_PAIR);
4066
4067 unlock:
4068         if (lustre_handle_is_used(&lh)) {
4069                 dt_read_unlock(env, tobj);
4070                 lfsck_ibits_unlock(&lh, LCK_EX);
4071         }
4072
4073 out:
4074         lfsck_object_put(env, tobj);
4075
4076         return rc;
4077 }
4078
4079 static int lfsck_layout_assistant_handler_p1(const struct lu_env *env,
4080                                              struct lfsck_component *com,
4081                                              struct lfsck_assistant_req *lar)
4082 {
4083         struct lfsck_layout_req              *llr    =
4084                         container_of0(lar, struct lfsck_layout_req, llr_lar);
4085         struct lfsck_assistant_object        *lso    = lar->lar_parent;
4086         struct lfsck_layout                  *lo     = com->lc_file_ram;
4087         struct lfsck_thread_info             *info   = lfsck_env_info(env);
4088         struct filter_fid                    *ff     = &info->lti_ff;
4089         struct lu_buf buf = { .lb_buf = ff,
4090                               .lb_len = sizeof(*ff) };
4091         struct dt_object                     *parent = NULL;
4092         struct dt_object                     *child  = llr->llr_child;
4093         struct lu_attr                       *pla    = &lso->lso_attr;
4094         struct lu_attr                       *cla    = &info->lti_la;
4095         struct lfsck_instance                *lfsck  = com->lc_lfsck;
4096         struct lfsck_bookmark                *bk     = &lfsck->li_bookmark_ram;
4097         enum lfsck_layout_inconsistency_type  type   = LLIT_NONE;
4098         int                                   rc;
4099         ENTRY;
4100
4101         if (lso->lso_dead)
4102                 RETURN(0);
4103
4104         CFS_FAIL_TIMEOUT(OBD_FAIL_LFSCK_ASSISTANT_DIRECT, cfs_fail_val);
4105
4106         rc = dt_attr_get(env, child, cla);
4107         if (rc == -ENOENT) {
4108                 parent = lfsck_assistant_object_load(env, lfsck, lso);
4109                 if (IS_ERR(parent)) {
4110                         rc = PTR_ERR(parent);
4111
4112                         RETURN(rc == -ENOENT ? 0 : rc);
4113                 }
4114
4115                 type = LLIT_DANGLING;
4116                 goto repair;
4117         }
4118
4119         if (rc != 0)
4120                 GOTO(out, rc);
4121
4122         lfsck_buf_init(&buf, ff, sizeof(*ff));
4123         rc = dt_xattr_get(env, child, &buf, XATTR_NAME_FID);
4124         if (unlikely(rc > 0 && rc < sizeof(struct lu_fid))) {
4125                 type = LLIT_UNMATCHED_PAIR;
4126                 goto repair;
4127         }
4128
4129         if (rc < 0 && rc != -ENODATA)
4130                 GOTO(out, rc);
4131
4132         if (rc == 0 || rc == -ENODATA)
4133                 GOTO(check_owner, rc = 0);
4134
4135         filter_fid_le_to_cpu(ff, ff, sizeof(*ff));
4136         rc = lfsck_layout_check_parent(env, com, lso, ff,
4137                                        lu_object_fid(&child->do_lu), cla, llr);
4138         if (rc > 0) {
4139                 type = rc;
4140                 goto repair;
4141         }
4142
4143         if (rc < 0)
4144                 GOTO(out, rc);
4145
4146 check_owner:
4147         /* Someone may has changed the owner after the parent attr pre-loaded.
4148          * It can be handled later inside the lfsck_layout_repair_owner(). */
4149         if (unlikely(cla->la_uid != pla->la_uid ||
4150                      cla->la_gid != pla->la_gid)) {
4151                 type = LLIT_INCONSISTENT_OWNER;
4152                 goto repair;
4153         }
4154
4155 repair:
4156         if (type == LLIT_NONE)
4157                 GOTO(out, rc = 0);
4158
4159         if (bk->lb_param & LPF_DRYRUN)
4160                 GOTO(out, rc = 1);
4161
4162         if (parent == NULL) {
4163                 parent = lfsck_assistant_object_load(env, lfsck, lso);
4164                 if (IS_ERR(parent)) {
4165                         rc = PTR_ERR(parent);
4166
4167                         if (rc == -ENOENT)
4168                                 RETURN(0);
4169
4170                         GOTO(out, rc);
4171                 }
4172         }
4173
4174         switch (type) {
4175         case LLIT_DANGLING:
4176                 if (bk->lb_param & LPF_DELAY_CREATE_OSTOBJ)
4177                         rc = lfsck_layout_ins_dangling_rec(env, com,
4178                                 lfsck_dto2fid(parent), lfsck_dto2fid(child),
4179                                 llr->llr_comp_id, llr->llr_lov_idx,
4180                                 llr->llr_ost_idx);
4181                 else
4182                         rc = __lfsck_layout_repair_dangling(env, com, parent,
4183                                                             llr->llr_child,
4184                                                             llr->llr_comp_id,
4185                                                             llr->llr_lov_idx,
4186                                                             llr->llr_ost_idx,
4187                                                             true);
4188                 break;
4189         case LLIT_UNMATCHED_PAIR:
4190                 rc = lfsck_layout_repair_unmatched_pair(env, com, parent,
4191                                                         llr, pla);
4192                 break;
4193         case LLIT_MULTIPLE_REFERENCED:
4194                 rc = lfsck_layout_repair_multiple_references(env, com, parent,
4195                                                              llr, pla);
4196                 break;
4197         case LLIT_INCONSISTENT_OWNER:
4198                 rc = lfsck_layout_repair_owner(env, com, parent, llr, pla, cla);
4199                 break;
4200         default:
4201                 rc = 0;
4202                 break;
4203         }
4204
4205         GOTO(out, rc);
4206
4207 out:
4208         down_write(&com->lc_sem);
4209         if (rc < 0) {
4210                 struct lfsck_assistant_data *lad = com->lc_data;
4211
4212                 if (unlikely(lad->lad_exit)) {
4213                         rc = 0;
4214                 } else if (rc == -ENOTCONN || rc == -ESHUTDOWN ||
4215                            rc == -ETIMEDOUT || rc == -EHOSTDOWN ||
4216                            rc == -EHOSTUNREACH) {
4217                         /* If cannot touch the target server,
4218                          * mark the LFSCK as INCOMPLETE. */
4219                         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant fail to "
4220                                "talk with OST %x: rc = %d\n",
4221                                lfsck_lfsck2name(lfsck), llr->llr_ost_idx, rc);
4222                         lfsck_lad_set_bitmap(env, com, llr->llr_ost_idx);
4223                         lo->ll_objs_skipped++;
4224                         rc = 0;
4225                 } else {
4226                         lfsck_layout_record_failure(env, lfsck, lo);
4227                 }
4228         } else if (rc > 0 && (type != LLIT_DANGLING ||
4229                               !(bk->lb_param & LPF_DELAY_CREATE_OSTOBJ))) {
4230                 LASSERTF(type > LLIT_NONE && type <= LLIT_MAX,
4231                          "unknown type = %d\n", type);
4232
4233                 lo->ll_objs_repaired[type - 1]++;
4234                 if (bk->lb_param & LPF_DRYRUN &&
4235                     unlikely(lo->ll_pos_first_inconsistent == 0))
4236                         lo->ll_pos_first_inconsistent =
4237                         lfsck->li_obj_oit->do_index_ops->dio_it.store(env,
4238                                                         lfsck->li_di_oit);
4239         }
4240         up_write(&com->lc_sem);
4241
4242         if (parent != NULL && !IS_ERR(parent))
4243                 lfsck_object_put(env, parent);
4244
4245         return rc;
4246 }
4247
4248 static int
4249 lfsck_layout_double_scan_one_trace_file(const struct lu_env *env,
4250                                         struct lfsck_component *com,
4251                                         struct dt_object *obj, bool first)
4252 {
4253         struct lfsck_instance *lfsck = com->lc_lfsck;
4254         struct ptlrpc_thread *thread = &lfsck->li_thread;
4255         struct lfsck_bookmark *bk = &lfsck->li_bookmark_ram;
4256         struct lfsck_layout *lo = com->lc_file_ram;
4257         const struct dt_it_ops *iops = &obj->do_index_ops->dio_it;
4258         struct dt_it *di;
4259         struct dt_key *key;
4260         struct lfsck_layout_dangling_key *parent =
4261                                         &lfsck_env_info(env)->lti_lldk;
4262         struct lu_fid *cfid = &lfsck_env_info(env)->lti_fid3;
4263         __u32 ost_idx;
4264         int rc;
4265         ENTRY;
4266
4267         di = iops->init(env, obj, 0);
4268         if (IS_ERR(di))
4269                 RETURN(PTR_ERR(di));
4270
4271         if (first)
4272                 lldk_cpu_to_be(parent, &lo->ll_lldk_latest_scanned_phase2);
4273         else
4274                 memset(parent, 0, sizeof(*parent));
4275         rc = iops->get(env, di, (const struct dt_key *)parent);
4276         if (rc < 0)
4277                 GOTO(fini, rc);
4278
4279         if (first) {
4280                 /* The start one either has been processed or does not exist,
4281                  * skip it. */
4282                 rc = iops->next(env, di);
4283                 if (rc != 0)
4284                         GOTO(put, rc);
4285         }
4286
4287         do {
4288                 if (CFS_FAIL_TIMEOUT(OBD_FAIL_LFSCK_DELAY3, cfs_fail_val) &&
4289                     unlikely(!thread_is_running(thread)))
4290                         GOTO(put, rc = 0);
4291
4292                 key = iops->key(env, di);
4293                 if (IS_ERR(key)) {
4294                         rc = PTR_ERR(key);
4295                         if (rc == -ENOENT)
4296                                 GOTO(put, rc = 1);
4297
4298                         goto checkpoint;
4299                 }
4300
4301                 lldk_be_to_cpu(parent,
4302                                 (const struct lfsck_layout_dangling_key *)key);
4303                 if (!fid_is_sane(&parent->lldk_fid)) {
4304                         rc = 0;
4305                         goto checkpoint;
4306                 }
4307
4308                 rc = iops->rec(env, di, (struct dt_rec *)cfid, 0);
4309                 if (rc == 0) {
4310                         fid_be_to_cpu(cfid, cfid);
4311                         ost_idx = cfid->f_ver;
4312                         cfid->f_ver = 0;
4313                         if (!fid_is_sane(cfid)) {
4314                                 rc = 0;
4315                                 goto checkpoint;
4316                         }
4317
4318                         rc = lfsck_layout_repair_dangling(env, com,
4319                                         &parent->lldk_fid, cfid,
4320                                         parent->lldk_comp_id,
4321                                         parent->lldk_ea_off, ost_idx);
4322                 }
4323
4324 checkpoint:
4325                 down_write(&com->lc_sem);
4326                 com->lc_new_checked++;
4327                 com->lc_new_scanned++;
4328                 if (rc >= 0)
4329                         lo->ll_lldk_latest_scanned_phase2 = *parent;
4330
4331                 if (rc > 0)
4332                         lo->ll_objs_repaired[LLIT_DANGLING - 1]++;
4333                 else if (rc < 0)
4334                         lo->ll_objs_failed_phase2++;
4335                 up_write(&com->lc_sem);
4336
4337                 if (rc < 0 && bk->lb_param & LPF_FAILOUT)
4338                         GOTO(put, rc);
4339
4340                 if (unlikely(cfs_time_beforeq(com->lc_time_next_checkpoint,
4341                                               cfs_time_current())) &&
4342                     com->lc_new_checked != 0) {
4343                         down_write(&com->lc_sem);
4344                         lo->ll_run_time_phase2 +=
4345                                 cfs_duration_sec(cfs_time_current() +
4346                                 HALF_SEC - com->lc_time_last_checkpoint);
4347                         lo->ll_time_last_checkpoint = cfs_time_current_sec();
4348                         lo->ll_objs_checked_phase2 += com->lc_new_checked;
4349                         com->lc_new_checked = 0;
4350                         lfsck_layout_store(env, com);
4351                         up_write(&com->lc_sem);
4352
4353                         com->lc_time_last_checkpoint = cfs_time_current();
4354                         com->lc_time_next_checkpoint =
4355                                 com->lc_time_last_checkpoint +
4356                                 cfs_time_seconds(LFSCK_CHECKPOINT_INTERVAL);
4357                 }
4358
4359                 lfsck_control_speed_by_self(com);
4360                 if (unlikely(!thread_is_running(thread)))
4361                         GOTO(put, rc = 0);
4362
4363                 rc = iops->next(env, di);
4364         } while (rc == 0);
4365
4366         GOTO(put, rc);
4367
4368 put:
4369         iops->put(env, di);
4370
4371 fini:
4372         iops->fini(env, di);
4373
4374         return rc;
4375 }
4376
4377 static int lfsck_layout_assistant_handler_p2(const struct lu_env *env,
4378                                              struct lfsck_component *com)
4379 {
4380         struct lfsck_assistant_data     *lad    = com->lc_data;
4381         struct lfsck_instance           *lfsck  = com->lc_lfsck;
4382         struct lfsck_bookmark           *bk     = &lfsck->li_bookmark_ram;
4383         struct lfsck_tgt_descs          *ltds   = &lfsck->li_ost_descs;
4384         struct lfsck_tgt_desc           *ltd;
4385         int                              rc     = 0;
4386         ENTRY;
4387
4388         CDEBUG(D_LFSCK, "%s: layout LFSCK phase2 scan start\n",
4389                lfsck_lfsck2name(lfsck));
4390
4391         spin_lock(&ltds->ltd_lock);
4392         while (!list_empty(&lad->lad_ost_phase2_list)) {
4393                 ltd = list_entry(lad->lad_ost_phase2_list.next,
4394                                  struct lfsck_tgt_desc,
4395                                  ltd_layout_phase_list);
4396                 list_del_init(&ltd->ltd_layout_phase_list);
4397                 if (bk->lb_param & LPF_OST_ORPHAN) {
4398                         spin_unlock(&ltds->ltd_lock);
4399                         rc = lfsck_layout_scan_orphan(env, com, ltd);
4400                         if (rc != 0 && bk->lb_param & LPF_FAILOUT)
4401                                 RETURN(rc);
4402
4403                         if (unlikely(lad->lad_exit ||
4404                                      !thread_is_running(&lfsck->li_thread)))
4405                                 RETURN(0);
4406                         spin_lock(&ltds->ltd_lock);
4407                 }
4408         }
4409
4410         if (list_empty(&lad->lad_ost_phase1_list))
4411                 rc = 1;
4412         else
4413                 rc = 0;
4414         spin_unlock(&ltds->ltd_lock);
4415
4416         if (rc == 1 && bk->lb_param & LPF_OST_ORPHAN) {
4417                 struct lfsck_layout *lo = com->lc_file_ram;
4418                 int i;
4419
4420                 com->lc_new_checked = 0;
4421                 com->lc_new_scanned = 0;
4422                 com->lc_time_last_checkpoint = cfs_time_current();
4423                 com->lc_time_next_checkpoint = com->lc_time_last_checkpoint +
4424                                 cfs_time_seconds(LFSCK_CHECKPOINT_INTERVAL);
4425
4426                 i = lfsck_sub_trace_file_fid2idx(
4427                                 &lo->ll_lldk_latest_scanned_phase2.lldk_fid);
4428                 rc = lfsck_layout_double_scan_one_trace_file(env, com,
4429                                 com->lc_sub_trace_objs[i].lsto_obj, true);
4430                 while (rc > 0 && ++i < LFSCK_STF_COUNT)
4431                         rc = lfsck_layout_double_scan_one_trace_file(env, com,
4432                                 com->lc_sub_trace_objs[i].lsto_obj, false);
4433
4434                 CDEBUG(D_LFSCK, "%s: layout LFSCK phase2 scan dangling stop "
4435                        "at the No. %d trace file: rc = %d\n",
4436                        lfsck_lfsck2name(lfsck), i, rc);
4437         }
4438
4439         CDEBUG(D_LFSCK, "%s: layout LFSCK phase2 scan stop: rc = %d\n",
4440                lfsck_lfsck2name(lfsck), rc);
4441
4442         RETURN(rc);
4443 }
4444
4445 static int
4446 lfsck_layout_slave_async_interpret(const struct lu_env *env,
4447                                    struct ptlrpc_request *req,
4448                                    void *args, int rc)
4449 {
4450         struct lfsck_layout_slave_async_args *llsaa = args;
4451         struct obd_export                    *exp   = llsaa->llsaa_exp;
4452         struct lfsck_component               *com   = llsaa->llsaa_com;
4453         struct lfsck_layout_slave_target     *llst  = llsaa->llsaa_llst;
4454         struct lfsck_layout_slave_data       *llsd  = com->lc_data;
4455         struct lfsck_reply                   *lr    = NULL;
4456         bool                                  done  = false;
4457
4458         if (rc != 0) {
4459                 /* It is probably caused by network trouble, or target crash,
4460                  * it will try several times (depends on the obd_timeout, and
4461                  * will not less than 3 times). But to make the LFSCK can go
4462                  * ahead, we should not try for ever. After some try but still
4463                  * hit failure, it will assume that the target exit the LFSCK
4464                  * prcoessing and stop try. */
4465                 if (rc == -ENOTCONN || rc == -ESHUTDOWN) {
4466                         int max_try = max_t(int, obd_timeout / 30, 3);
4467
4468                         if (++(llst->llst_failures) > max_try)
4469                                 done = true;
4470                 } else {
4471                         done = true;
4472                 }
4473         } else {
4474                 llst->llst_failures = 0;
4475                 lr = req_capsule_server_get(&req->rq_pill, &RMF_LFSCK_REPLY);
4476                 if (lr->lr_status != LS_SCANNING_PHASE1 &&
4477                     lr->lr_status != LS_SCANNING_PHASE2)
4478                         done = true;
4479         }
4480
4481         if (done) {
4482                 CDEBUG(D_LFSCK, "%s: layout LFSCK slave gets the MDT %x "
4483                        "status %d, failures_try %d\n", lfsck_lfsck2name(com->lc_lfsck),
4484                        llst->llst_index, lr != NULL ? lr->lr_status : rc,
4485                        llst->llst_failures);
4486
4487                 lfsck_layout_llst_del(llsd, llst);
4488         }
4489
4490         lfsck_layout_llst_put(llst);
4491         lfsck_component_put(env, com);
4492         class_export_put(exp);
4493
4494         return 0;
4495 }
4496
4497 static int lfsck_layout_async_query(const struct lu_env *env,
4498                                     struct lfsck_component *com,
4499                                     struct obd_export *exp,
4500                                     struct lfsck_layout_slave_target *llst,
4501                                     struct lfsck_request *lr,
4502                                     struct ptlrpc_request_set *set)
4503 {
4504         struct lfsck_layout_slave_async_args *llsaa;
4505         struct ptlrpc_request                *req;
4506         struct lfsck_request                 *tmp;
4507         int                                   rc;
4508         ENTRY;
4509
4510         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_LFSCK_QUERY);
4511         if (req == NULL)
4512                 RETURN(-ENOMEM);
4513
4514         rc = ptlrpc_request_pack(req, LUSTRE_OBD_VERSION, LFSCK_QUERY);
4515         if (rc != 0) {
4516                 ptlrpc_request_free(req);
4517                 RETURN(rc);
4518         }
4519
4520         tmp = req_capsule_client_get(&req->rq_pill, &RMF_LFSCK_REQUEST);
4521         *tmp = *lr;
4522         ptlrpc_request_set_replen(req);
4523
4524         llsaa = ptlrpc_req_async_args(req);
4525         llsaa->llsaa_exp = exp;
4526         llsaa->llsaa_com = lfsck_component_get(com);
4527         llsaa->llsaa_llst = llst;
4528         req->rq_interpret_reply = lfsck_layout_slave_async_interpret;
4529         req->rq_allow_intr = 1;
4530         ptlrpc_set_add_req(set, req);
4531
4532         RETURN(0);
4533 }
4534
4535 static int lfsck_layout_async_notify(const struct lu_env *env,
4536                                      struct obd_export *exp,
4537                                      struct lfsck_request *lr,
4538                                      struct ptlrpc_request_set *set)
4539 {
4540         struct ptlrpc_request   *req;
4541         struct lfsck_request    *tmp;
4542         int                      rc;
4543         ENTRY;
4544
4545         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_LFSCK_NOTIFY);
4546         if (req == NULL)
4547                 RETURN(-ENOMEM);
4548
4549         rc = ptlrpc_request_pack(req, LUSTRE_OBD_VERSION, LFSCK_NOTIFY);
4550         if (rc != 0) {
4551                 ptlrpc_request_free(req);
4552                 RETURN(rc);
4553         }
4554
4555         tmp = req_capsule_client_get(&req->rq_pill, &RMF_LFSCK_REQUEST);
4556         *tmp = *lr;
4557         ptlrpc_request_set_replen(req);
4558         req->rq_allow_intr = 1;
4559         ptlrpc_set_add_req(set, req);
4560
4561         RETURN(0);
4562 }
4563
4564 static int
4565 lfsck_layout_slave_query_master(const struct lu_env *env,
4566                                 struct lfsck_component *com)
4567 {
4568         struct lfsck_request             *lr    = &lfsck_env_info(env)->lti_lr;
4569         struct lfsck_instance            *lfsck = com->lc_lfsck;
4570         struct lfsck_layout_slave_data   *llsd  = com->lc_data;
4571         struct lfsck_layout_slave_target *llst;
4572         struct obd_export                *exp;
4573         struct ptlrpc_request_set        *set;
4574         int                               rc    = 0;
4575         int                               rc1   = 0;
4576         ENTRY;
4577
4578         set = ptlrpc_prep_set();
4579         if (set == NULL)
4580                 GOTO(log, rc = -ENOMEM);
4581
4582         memset(lr, 0, sizeof(*lr));
4583         lr->lr_event = LE_QUERY;
4584         lr->lr_active = LFSCK_TYPE_LAYOUT;
4585
4586         llsd->llsd_touch_gen++;
4587         spin_lock(&llsd->llsd_lock);
4588         while (!list_empty(&llsd->llsd_master_list)) {
4589                 llst = list_entry(llsd->llsd_master_list.next,
4590                                   struct lfsck_layout_slave_target,
4591                                   llst_list);
4592                 if (llst->llst_gen == llsd->llsd_touch_gen)
4593                         break;
4594
4595                 llst->llst_gen = llsd->llsd_touch_gen;
4596                 list_move_tail(&llst->llst_list,
4597                                &llsd->llsd_master_list);
4598                 atomic_inc(&llst->llst_ref);
4599                 spin_unlock(&llsd->llsd_lock);
4600
4601                 exp = lustre_find_lwp_by_index(lfsck->li_obd->obd_name,
4602                                                llst->llst_index);
4603                 if (exp == NULL) {
4604                         lfsck_layout_llst_del(llsd, llst);
4605                         lfsck_layout_llst_put(llst);
4606                         spin_lock(&llsd->llsd_lock);
4607                         continue;
4608                 }
4609
4610                 rc = lfsck_layout_async_query(env, com, exp, llst, lr, set);
4611                 if (rc != 0) {
4612                         CDEBUG(D_LFSCK, "%s: layout LFSCK slave fail to "
4613                                "query %s for layout: rc = %d\n",
4614                                lfsck_lfsck2name(lfsck),
4615                                exp->exp_obd->obd_name, rc);
4616
4617                         rc1 = rc;
4618                         lfsck_layout_llst_put(llst);
4619                         class_export_put(exp);
4620                 }
4621                 spin_lock(&llsd->llsd_lock);
4622         }
4623         spin_unlock(&llsd->llsd_lock);
4624
4625         rc = ptlrpc_set_wait(set);
4626         ptlrpc_set_destroy(set);
4627
4628         GOTO(log, rc = (rc1 != 0 ? rc1 : rc));
4629
4630 log:
4631         CDEBUG(D_LFSCK, "%s: layout LFSCK slave queries master: rc = %d\n",
4632                lfsck_lfsck2name(com->lc_lfsck), rc);
4633
4634         return rc;
4635 }
4636
4637 static void
4638 lfsck_layout_slave_notify_master(const struct lu_env *env,
4639                                  struct lfsck_component *com,
4640                                  enum lfsck_events event, int result)
4641 {
4642         struct lfsck_layout              *lo    = com->lc_file_ram;
4643         struct lfsck_instance            *lfsck = com->lc_lfsck;
4644         struct lfsck_layout_slave_data   *llsd  = com->lc_data;
4645         struct lfsck_request             *lr    = &lfsck_env_info(env)->lti_lr;
4646         struct lfsck_layout_slave_target *llst;
4647         struct obd_export                *exp;
4648         struct ptlrpc_request_set        *set;
4649         int                               rc;
4650         ENTRY;
4651
4652         CDEBUG(D_LFSCK, "%s: layout LFSCK slave notifies master\n",
4653                lfsck_lfsck2name(com->lc_lfsck));
4654
4655         set = ptlrpc_prep_set();
4656         if (set == NULL)
4657                 RETURN_EXIT;
4658
4659         memset(lr, 0, sizeof(*lr));
4660         lr->lr_event = event;
4661         lr->lr_flags = LEF_FROM_OST;
4662         lr->lr_status = result;
4663         lr->lr_index = lfsck_dev_idx(lfsck);
4664         lr->lr_active = LFSCK_TYPE_LAYOUT;
4665         lr->lr_flags2 = lo->ll_flags;
4666         llsd->llsd_touch_gen++;
4667         spin_lock(&llsd->llsd_lock);
4668         while (!list_empty(&llsd->llsd_master_list)) {
4669                 llst = list_entry(llsd->llsd_master_list.next,
4670                                   struct lfsck_layout_slave_target,
4671                                   llst_list);
4672                 if (llst->llst_gen == llsd->llsd_touch_gen)
4673                         break;
4674
4675                 llst->llst_gen = llsd->llsd_touch_gen;
4676                 list_move_tail(&llst->llst_list,
4677                                &llsd->llsd_master_list);
4678                 atomic_inc(&llst->llst_ref);
4679                 spin_unlock(&llsd->llsd_lock);
4680
4681                 exp = lustre_find_lwp_by_index(lfsck->li_obd->obd_name,
4682                                                llst->llst_index);
4683                 if (exp == NULL) {
4684                         lfsck_layout_llst_del(llsd, llst);
4685                         lfsck_layout_llst_put(llst);
4686                         spin_lock(&llsd->llsd_lock);
4687                         continue;
4688                 }
4689
4690                 rc = lfsck_layout_async_notify(env, exp, lr, set);
4691                 if (rc != 0)
4692                         CDEBUG(D_LFSCK, "%s: layout LFSCK slave fail to "
4693                                "notify %s for layout: rc = %d\n",
4694                                lfsck_lfsck2name(lfsck),
4695                                exp->exp_obd->obd_name, rc);
4696
4697                 lfsck_layout_llst_put(llst);
4698                 class_export_put(exp);
4699                 spin_lock(&llsd->llsd_lock);
4700         }
4701         spin_unlock(&llsd->llsd_lock);
4702
4703         ptlrpc_set_wait(set);
4704         ptlrpc_set_destroy(set);
4705
4706         RETURN_EXIT;
4707 }
4708
4709 /*
4710  * \ret -ENODATA: unrecognized stripe
4711  * \ret = 0     : recognized stripe
4712  * \ret < 0     : other failures
4713  */
4714 static int lfsck_layout_master_check_pairs(const struct lu_env *env,
4715                                            struct lfsck_component *com,
4716                                            struct lu_fid *cfid,
4717                                            struct lu_fid *pfid, __u32 comp_id)
4718 {
4719         struct lfsck_thread_info        *info   = lfsck_env_info(env);
4720         struct lu_buf                   *buf    = &info->lti_big_buf;
4721         struct ost_id                   *oi     = &info->lti_oi;
4722         struct dt_object                *obj;
4723         struct lov_mds_md_v1            *lmm;
4724         struct lov_ost_data_v1          *objs;
4725         __u32                            idx    = pfid->f_stripe_idx;
4726         __u32                            magic;
4727         int                              rc     = 0;
4728         int                              i;
4729         __u16                            count;
4730         ENTRY;
4731
4732         pfid->f_ver = 0;
4733         obj = lfsck_object_find_bottom(env, com->lc_lfsck, pfid);
4734         if (IS_ERR(obj))
4735                 RETURN(PTR_ERR(obj));
4736
4737         dt_read_lock(env, obj, 0);
4738         if (unlikely(dt_object_exists(obj) == 0 ||
4739                      lfsck_is_dead_obj(obj)))
4740                 GOTO(unlock, rc = -ENOENT);
4741
4742         if (!S_ISREG(lfsck_object_type(obj)))
4743                 GOTO(unlock, rc = -ENODATA);
4744
4745         rc = lfsck_layout_get_lovea(env, obj, buf);
4746         if (rc < 0)
4747                 GOTO(unlock, rc);
4748
4749         if (rc == 0)
4750                 GOTO(unlock, rc = -ENODATA);
4751
4752         lmm = buf->lb_buf;
4753         magic = le32_to_cpu(lmm->lmm_magic);
4754         if (magic == LOV_MAGIC_COMP_V1) {
4755                 struct lov_comp_md_v1 *lcm = buf->lb_buf;
4756                 struct lov_comp_md_entry_v1 *lcme;
4757
4758                 if (comp_id == 0)
4759                         GOTO(unlock, rc = -ENODATA);
4760
4761                 count = le16_to_cpu(lcm->lcm_entry_count);
4762                 for (i = 0; i < count; i++) {
4763                         lcme = &lcm->lcm_entries[i];
4764                         if (le32_to_cpu(lcme->lcme_id) == comp_id) {
4765                                 lmm = buf->lb_buf +
4766                                         le32_to_cpu(lcme->lcme_offset);
4767                                 magic = le32_to_cpu(lmm->lmm_magic);
4768                                 if (!(le32_to_cpu(lcme->lcme_flags) &
4769                                       LCME_FL_INIT))
4770                                         GOTO(unlock, rc = -ENODATA);
4771
4772                                 goto further;
4773                         }
4774                 }
4775
4776                 GOTO(unlock, rc = -ENODATA);
4777         }
4778
4779 further:
4780         if (magic == LOV_MAGIC_V1) {
4781                 objs = &lmm->lmm_objects[0];
4782         } else {
4783                 LASSERT(magic == LOV_MAGIC_V3);
4784                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[0];
4785         }
4786
4787         fid_to_ostid(cfid, oi);
4788         count = le16_to_cpu(lmm->lmm_stripe_count);
4789         for (i = 0; i < count; i++, objs++) {
4790                 struct ost_id oi2;
4791
4792                 ostid_le_to_cpu(&objs->l_ost_oi, &oi2);
4793                 if (memcmp(oi, &oi2, sizeof(*oi)) == 0)
4794                         GOTO(unlock, rc = (i != idx ? -ENODATA : 0));
4795         }
4796
4797         GOTO(unlock, rc = -ENODATA);
4798
4799 unlock:
4800         dt_read_unlock(env, obj);
4801         lfsck_object_put(env, obj);
4802
4803         return rc;
4804 }
4805
4806 /*
4807  * The LFSCK-on-OST will ask the LFSCK-on-MDT to check whether the given
4808  * MDT-object/OST-object pairs match or not to aviod transfer MDT-object
4809  * layout EA from MDT to OST. On one hand, the OST no need to understand
4810  * the layout EA structure; on the other hand, it may cause trouble when
4811  * transfer large layout EA from MDT to OST via normal OUT RPC.
4812  *
4813  * \ret > 0: unrecognized stripe
4814  * \ret = 0: recognized stripe
4815  * \ret < 0: other failures
4816  */
4817 static int lfsck_layout_slave_check_pairs(const struct lu_env *env,
4818                                           struct lfsck_component *com,
4819                                           struct lu_fid *cfid,
4820                                           struct lu_fid *pfid, __u32 comp_id)
4821 {
4822         struct lfsck_instance    *lfsck  = com->lc_lfsck;
4823         struct obd_device        *obd    = lfsck->li_obd;
4824         struct seq_server_site   *ss     = lfsck_dev_site(lfsck);
4825         struct obd_export        *exp    = NULL;
4826         struct ptlrpc_request    *req    = NULL;
4827         struct lfsck_request     *lr;
4828         struct lu_seq_range      *range  = &lfsck_env_info(env)->lti_range;
4829         int                       rc     = 0;
4830         ENTRY;
4831
4832         if (unlikely(fid_is_idif(pfid)))
4833                 RETURN(1);
4834
4835         fld_range_set_any(range);
4836         rc = fld_server_lookup(env, ss->ss_server_fld, fid_seq(pfid), range);
4837         if (rc != 0)
4838                 RETURN(rc == -ENOENT ? 1 : rc);
4839
4840         if (unlikely(!fld_range_is_mdt(range)))
4841                 RETURN(1);
4842
4843         exp = lustre_find_lwp_by_index(obd->obd_name, range->lsr_index);
4844         if (unlikely(exp == NULL))
4845                 RETURN(1);
4846
4847         if (!(exp_connect_flags(exp) & OBD_CONNECT_LFSCK))
4848                 GOTO(out, rc = -EOPNOTSUPP);
4849
4850         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_LFSCK_NOTIFY);
4851         if (req == NULL)
4852                 GOTO(out, rc = -ENOMEM);
4853
4854         rc = ptlrpc_request_pack(req, LUSTRE_OBD_VERSION, LFSCK_NOTIFY);
4855         if (rc != 0) {
4856                 ptlrpc_request_free(req);
4857
4858                 GOTO(out, rc);
4859         }
4860
4861         lr = req_capsule_client_get(&req->rq_pill, &RMF_LFSCK_REQUEST);
4862         memset(lr, 0, sizeof(*lr));
4863         lr->lr_event = LE_PAIRS_VERIFY;
4864         lr->lr_active = LFSCK_TYPE_LAYOUT;
4865         lr->lr_fid = *cfid; /* OST-object itself FID. */
4866         lr->lr_fid2 = *pfid; /* The claimed parent FID. */
4867         lr->lr_comp_id = comp_id;
4868
4869         ptlrpc_request_set_replen(req);
4870         rc = ptlrpc_queue_wait(req);
4871         ptlrpc_req_finished(req);
4872
4873         if (rc == -ENOENT || rc == -ENODATA)
4874                 rc = 1;
4875
4876         GOTO(out, rc);
4877
4878 out:
4879         if (exp != NULL)
4880                 class_export_put(exp);
4881
4882         return rc;
4883 }
4884
4885 static int lfsck_layout_slave_repair_pfid(const struct lu_env *env,
4886                                           struct lfsck_component *com,
4887                                           struct lfsck_req_local *lrl)
4888 {
4889         struct dt_object        *obj;
4890         int                      rc     = 0;
4891         ENTRY;
4892
4893         obj = lfsck_object_find_bottom(env, com->lc_lfsck, &lrl->lrl_fid);
4894         if (IS_ERR(obj))
4895                 GOTO(log, rc = PTR_ERR(obj));
4896
4897         dt_write_lock(env, obj, 0);
4898         if (unlikely(dt_object_exists(obj) == 0 ||
4899                      lfsck_is_dead_obj(obj)))
4900                 GOTO(unlock, rc = 0);
4901
4902         rc = __lfsck_layout_update_pfid(env, obj, &lrl->lrl_ff_client.ff_parent,
4903                                         &lrl->lrl_ff_client.ff_layout,
4904                                         lrl->lrl_ff_client.ff_parent.f_ver);
4905
4906         GOTO(unlock, rc);
4907
4908 unlock:
4909         dt_write_unlock(env, obj);
4910         lfsck_object_put(env, obj);
4911
4912 log:
4913         CDEBUG(D_LFSCK, "%s: layout LFSCK slave repaired pfid for "DFID
4914                ", parent "DFID": rc = %d\n", lfsck_lfsck2name(com->lc_lfsck),
4915                PFID(&lrl->lrl_fid), PFID(&lrl->lrl_ff_client.ff_parent), rc);
4916
4917         return rc;
4918 }
4919
4920 /* layout APIs */
4921
4922 static void lfsck_layout_slave_quit(const struct lu_env *env,
4923                                     struct lfsck_component *com);
4924
4925 static int lfsck_layout_reset(const struct lu_env *env,
4926                               struct lfsck_component *com, bool init)
4927 {
4928         struct lfsck_layout     *lo    = com->lc_file_ram;
4929         int                      rc;
4930
4931         down_write(&com->lc_sem);
4932         if (init) {
4933                 memset(lo, 0, com->lc_file_size);
4934         } else {
4935                 __u32 count = lo->ll_success_count;
4936                 __u64 last_time = lo->ll_time_last_complete;
4937
4938                 memset(lo, 0, com->lc_file_size);
4939                 lo->ll_success_count = count;
4940                 lo->ll_time_last_complete = last_time;
4941         }
4942
4943         lo->ll_magic = LFSCK_LAYOUT_MAGIC;
4944         lo->ll_status = LS_INIT;
4945
4946         if (com->lc_lfsck->li_master) {
4947                 struct lfsck_assistant_data *lad = com->lc_data;
4948
4949                 lad->lad_incomplete = 0;
4950                 CFS_RESET_BITMAP(lad->lad_bitmap);
4951         }
4952
4953         rc = lfsck_layout_store(env, com);
4954         if (rc == 0 && com->lc_lfsck->li_master)
4955                 rc = lfsck_load_sub_trace_files(env, com,
4956                         &dt_lfsck_layout_dangling_features, LFSCK_LAYOUT, true);
4957         up_write(&com->lc_sem);
4958
4959         CDEBUG(D_LFSCK, "%s: layout LFSCK reset: rc = %d\n",
4960                lfsck_lfsck2name(com->lc_lfsck), rc);
4961
4962         return rc;
4963 }
4964
4965 static void lfsck_layout_fail(const struct lu_env *env,
4966                               struct lfsck_component *com, bool new_checked)
4967 {
4968         struct lfsck_layout *lo = com->lc_file_ram;
4969
4970         down_write(&com->lc_sem);
4971         if (new_checked)
4972                 com->lc_new_checked++;
4973         lfsck_layout_record_failure(env, com->lc_lfsck, lo);
4974         up_write(&com->lc_sem);
4975 }
4976
4977 static int lfsck_layout_master_checkpoint(const struct lu_env *env,
4978                                           struct lfsck_component *com, bool init)
4979 {
4980         struct lfsck_instance   *lfsck   = com->lc_lfsck;
4981         struct lfsck_layout     *lo      = com->lc_file_ram;
4982         int                      rc;
4983
4984         if (!init) {
4985                 rc = lfsck_checkpoint_generic(env, com);
4986                 if (rc != 0)
4987                         return rc > 0 ? 0 : rc;
4988         }
4989
4990         down_write(&com->lc_sem);
4991         if (init) {
4992                 lo->ll_pos_latest_start =
4993                                 lfsck->li_pos_checkpoint.lp_oit_cookie;
4994         } else {
4995                 lo->ll_pos_last_checkpoint =
4996                                 lfsck->li_pos_checkpoint.lp_oit_cookie;
4997                 lo->ll_run_time_phase1 += cfs_duration_sec(cfs_time_current() +
4998                                 HALF_SEC - lfsck->li_time_last_checkpoint);
4999                 lo->ll_time_last_checkpoint = cfs_time_current_sec();
5000                 lo->ll_objs_checked_phase1 += com->lc_new_checked;
5001                 com->lc_new_checked = 0;
5002         }
5003
5004         rc = lfsck_layout_store(env, com);
5005         up_write(&com->lc_sem);
5006
5007         CDEBUG(D_LFSCK, "%s: layout LFSCK master checkpoint at the pos ["
5008                "%llu], status = %d: rc = %d\n", lfsck_lfsck2name(lfsck),
5009                lfsck->li_pos_current.lp_oit_cookie, lo->ll_status, rc);
5010
5011         return rc;
5012 }
5013
5014 static int lfsck_layout_slave_checkpoint(const struct lu_env *env,
5015                                          struct lfsck_component *com, bool init)
5016 {
5017         struct lfsck_instance   *lfsck = com->lc_lfsck;
5018         struct lfsck_layout     *lo    = com->lc_file_ram;
5019         int                      rc;
5020
5021         if (com->lc_new_checked == 0 && !init)
5022                 return 0;
5023
5024         down_write(&com->lc_sem);
5025         if (init) {
5026                 lo->ll_pos_latest_start =
5027                                 lfsck->li_pos_checkpoint.lp_oit_cookie;
5028         } else {
5029                 lo->ll_pos_last_checkpoint =
5030                                 lfsck->li_pos_checkpoint.lp_oit_cookie;
5031                 lo->ll_run_time_phase1 += cfs_duration_sec(cfs_time_current() +
5032                                 HALF_SEC - lfsck->li_time_last_checkpoint);
5033                 lo->ll_time_last_checkpoint = cfs_time_current_sec();
5034                 lo->ll_objs_checked_phase1 += com->lc_new_checked;
5035                 com->lc_new_checked = 0;
5036         }
5037
5038         rc = lfsck_layout_store(env, com);
5039         up_write(&com->lc_sem);
5040
5041         CDEBUG(D_LFSCK, "%s: layout LFSCK slave checkpoint at the pos ["
5042                "%llu], status = %d: rc = %d\n", lfsck_lfsck2name(lfsck),
5043                lfsck->li_pos_current.lp_oit_cookie, lo->ll_status, rc);
5044
5045         return rc;
5046 }
5047
5048 static int lfsck_layout_prep(const struct lu_env *env,
5049                              struct lfsck_component *com,
5050                              struct lfsck_start *start)
5051 {
5052         struct lfsck_instance   *lfsck  = com->lc_lfsck;
5053         struct lfsck_layout     *lo     = com->lc_file_ram;
5054         struct lfsck_position   *pos    = &com->lc_pos_start;
5055
5056         fid_zero(&pos->lp_dir_parent);
5057         pos->lp_dir_cookie = 0;
5058         if (lo->ll_status == LS_COMPLETED ||
5059             lo->ll_status == LS_PARTIAL ||
5060             /* To handle orphan, must scan from the beginning. */
5061             (start != NULL && start->ls_flags & LPF_OST_ORPHAN)) {
5062                 int rc;
5063
5064                 rc = lfsck_layout_reset(env, com, false);
5065                 if (rc == 0)
5066                         rc = lfsck_set_param(env, lfsck, start, true);
5067
5068                 if (rc != 0) {
5069                         CDEBUG(D_LFSCK, "%s: layout LFSCK prep failed: "
5070                                "rc = %d\n", lfsck_lfsck2name(lfsck), rc);
5071
5072                         return rc;
5073                 }
5074         }
5075
5076         down_write(&com->lc_sem);
5077         lo->ll_time_latest_start = cfs_time_current_sec();
5078         spin_lock(&lfsck->li_lock);
5079         if (lo->ll_flags & LF_SCANNED_ONCE) {
5080                 if (!lfsck->li_drop_dryrun ||
5081                     lo->ll_pos_first_inconsistent == 0) {
5082                         lo->ll_status = LS_SCANNING_PHASE2;
5083                         list_move_tail(&com->lc_link,
5084                                        &lfsck->li_list_double_scan);
5085                         pos->lp_oit_cookie = 0;
5086                 } else {
5087                         int i;
5088
5089                         lo->ll_status = LS_SCANNING_PHASE1;
5090                         lo->ll_run_time_phase1 = 0;
5091                         lo->ll_run_time_phase2 = 0;
5092                         lo->ll_objs_checked_phase1 = 0;
5093                         lo->ll_objs_checked_phase2 = 0;
5094                         lo->ll_objs_failed_phase1 = 0;
5095                         lo->ll_objs_failed_phase2 = 0;
5096                         for (i = 0; i < LLIT_MAX; i++)
5097                                 lo->ll_objs_repaired[i] = 0;
5098
5099                         pos->lp_oit_cookie = lo->ll_pos_first_inconsistent;
5100                         fid_zero(&com->lc_fid_latest_scanned_phase2);
5101                 }
5102         } else {
5103                 lo->ll_status = LS_SCANNING_PHASE1;
5104                 if (!lfsck->li_drop_dryrun ||
5105                     lo->ll_pos_first_inconsistent == 0)
5106                         pos->lp_oit_cookie = lo->ll_pos_last_checkpoint + 1;
5107                 else
5108                         pos->lp_oit_cookie = lo->ll_pos_first_inconsistent;
5109         }
5110         spin_unlock(&lfsck->li_lock);
5111         up_write(&com->lc_sem);
5112
5113         return 0;
5114 }
5115
5116 static int lfsck_layout_slave_prep(const struct lu_env *env,
5117                                    struct lfsck_component *com,
5118                                    struct lfsck_start_param *lsp)
5119 {
5120         struct lfsck_layout_slave_data  *llsd   = com->lc_data;
5121         struct lfsck_instance           *lfsck  = com->lc_lfsck;
5122         struct lfsck_layout             *lo     = com->lc_file_ram;
5123         struct lfsck_start              *start  = lsp->lsp_start;
5124         int                              rc;
5125
5126         rc = lfsck_layout_prep(env, com, start);
5127         if (rc != 0)
5128                 return rc;
5129
5130         if (lo->ll_flags & LF_CRASHED_LASTID &&
5131             list_empty(&llsd->llsd_master_list)) {
5132                 LASSERT(lfsck->li_out_notify != NULL);
5133
5134                 lfsck->li_out_notify(env, lfsck->li_out_notify_data,
5135                                      LE_LASTID_REBUILDING);
5136         }
5137
5138         if (!lsp->lsp_index_valid)
5139                 return 0;
5140
5141         rc = lfsck_layout_llst_add(llsd, lsp->lsp_index);
5142         if (rc == 0 && start != NULL && start->ls_flags & LPF_OST_ORPHAN) {
5143                 LASSERT(!llsd->llsd_rbtree_valid);
5144
5145                 write_lock(&llsd->llsd_rb_lock);
5146                 rc = lfsck_rbtree_setup(env, com);
5147                 write_unlock(&llsd->llsd_rb_lock);
5148         }
5149
5150         CDEBUG(D_LFSCK, "%s: layout LFSCK slave prep done, start pos ["
5151                "%llu]\n", lfsck_lfsck2name(lfsck),
5152                com->lc_pos_start.lp_oit_cookie);
5153
5154         return rc;
5155 }
5156
5157 static int lfsck_layout_master_prep(const struct lu_env *env,
5158                                     struct lfsck_component *com,
5159                                     struct lfsck_start_param *lsp)
5160 {
5161         int rc;
5162         ENTRY;
5163
5164         rc = lfsck_layout_load_bitmap(env, com);
5165         if (rc != 0) {
5166                 rc = lfsck_layout_reset(env, com, false);
5167                 if (rc == 0)
5168                         rc = lfsck_set_param(env, com->lc_lfsck,
5169                                              lsp->lsp_start, true);
5170
5171                 if (rc != 0)
5172                         GOTO(log, rc);
5173         }
5174
5175         rc = lfsck_layout_prep(env, com, lsp->lsp_start);
5176         if (rc != 0)
5177                 RETURN(rc);
5178
5179         rc = lfsck_start_assistant(env, com, lsp);
5180
5181         GOTO(log, rc);
5182
5183 log:
5184         CDEBUG(D_LFSCK, "%s: layout LFSCK master prep done, start pos ["
5185                "%llu]\n", lfsck_lfsck2name(com->lc_lfsck),
5186                com->lc_pos_start.lp_oit_cookie);
5187
5188         return 0;
5189 }
5190
5191 /* Pre-fetch the attribute for each stripe in the given layout EA. */
5192 static int lfsck_layout_scan_stripes(const struct lu_env *env,
5193                                      struct lfsck_component *com,
5194                                      struct dt_object *parent,
5195                                      struct lov_mds_md_v1 *lmm, __u32 comp_id)
5196 {
5197         struct lfsck_thread_info        *info    = lfsck_env_info(env);
5198         struct lfsck_instance           *lfsck   = com->lc_lfsck;
5199         struct lfsck_bookmark           *bk      = &lfsck->li_bookmark_ram;
5200         struct lfsck_layout             *lo      = com->lc_file_ram;
5201         struct lfsck_assistant_data     *lad     = com->lc_data;
5202         struct lfsck_assistant_object   *lso     = NULL;
5203         struct lov_ost_data_v1          *objs;
5204         struct lfsck_tgt_descs          *ltds    = &lfsck->li_ost_descs;
5205         struct ptlrpc_thread            *mthread = &lfsck->li_thread;
5206         struct ptlrpc_thread            *athread = &lad->lad_thread;
5207         struct l_wait_info               lwi     = { 0 };
5208         struct lu_buf                    buf;
5209         int                              rc      = 0;
5210         int                              i;
5211         __u32                            magic;
5212         __u16                            count;
5213         ENTRY;
5214
5215         lfsck_buf_init(&buf, &info->lti_ff, sizeof(struct filter_fid));
5216         magic = le32_to_cpu(lmm->lmm_magic);
5217         if (magic == LOV_MAGIC_V1) {
5218                 objs = &lmm->lmm_objects[0];
5219         } else {
5220                 LASSERT(magic == LOV_MAGIC_V3);
5221                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[0];
5222         }
5223
5224         count = le16_to_cpu(lmm->lmm_stripe_count);
5225         for (i = 0; i < count; i++, objs++) {
5226                 struct lu_fid           *fid    = &info->lti_fid;
5227                 struct ost_id           *oi     = &info->lti_oi;
5228                 struct lfsck_layout_req *llr;
5229                 struct lfsck_tgt_desc   *tgt    = NULL;
5230                 struct dt_object        *cobj   = NULL;
5231                 __u32                    index;
5232                 bool                     wakeup = false;
5233
5234                 if (unlikely(lovea_slot_is_dummy(objs)))
5235                         continue;
5236
5237                 l_wait_event(mthread->t_ctl_waitq,
5238                              lad->lad_prefetched < bk->lb_async_windows ||
5239                              !thread_is_running(mthread) ||
5240                              thread_is_stopped(athread),
5241                              &lwi);
5242
5243                 if (unlikely(!thread_is_running(mthread)) ||
5244                              thread_is_stopped(athread))
5245                         GOTO(out, rc = 0);
5246
5247                 if (unlikely(lfsck_is_dead_obj(parent)))
5248                         GOTO(out, rc = 0);
5249
5250                 ostid_le_to_cpu(&objs->l_ost_oi, oi);
5251                 index = le32_to_cpu(objs->l_ost_idx);
5252                 rc = ostid_to_fid(fid, oi, index);
5253                 if (rc != 0) {
5254                         CDEBUG(D_LFSCK, "%s: get invalid layout EA for "DFID
5255                                ": "DOSTID", idx %u, comp_id %u\n",
5256                                lfsck_lfsck2name(lfsck),
5257                                PFID(lfsck_dto2fid(parent)), POSTID(oi),
5258                                index, comp_id);
5259                         goto next;
5260                 }
5261
5262                 tgt = lfsck_tgt_get(ltds, index);
5263                 if (unlikely(tgt == NULL)) {
5264                         CDEBUG(D_LFSCK, "%s: cannot talk with OST %x which "
5265                                "did not join the layout LFSCK, comp_id %u\n",
5266                                lfsck_lfsck2name(lfsck), index, comp_id);
5267                         lfsck_lad_set_bitmap(env, com, index);
5268                         goto next;
5269                 }
5270
5271                 /* There is potential deadlock race condition between object
5272                  * destroy and layout LFSCK. Consider the following scenario:
5273                  *
5274                  * 1) The LFSCK thread obtained the parent object firstly, at
5275                  *    that time, the parent object has not been destroyed yet.
5276                  *
5277                  * 2) One RPC service thread destroyed the parent and all its
5278                  *    children objects. Because the LFSCK is referencing the
5279                  *    parent object, then the parent object will be marked as
5280                  *    dying in RAM. On the other hand, the parent object is
5281                  *    referencing all its children objects, then all children
5282                  *    objects will be marked as dying in RAM also.
5283                  *
5284                  * 3) The LFSCK thread tries to find some child object with
5285                  *    the parent object referenced. Then it will find that the
5286                  *    child object is dying. According to the object visibility
5287                  *    rules: the object with dying flag cannot be returned to
5288                  *    others. So the LFSCK thread has to wait until the dying
5289                  *    object has been purged from RAM, then it can allocate a
5290                  *    new object (with the same FID) in RAM. Unfortunately, the
5291                  *    LFSCK thread itself is referencing the parent object, and
5292                  *    cause the parent object cannot be purged, then cause the
5293                  *    child object cannot be purged also. So the LFSCK thread
5294                  *    will fall into deadlock.
5295                  */
5296                 cobj = lfsck_object_find_by_dev(env, tgt->ltd_tgt, fid);
5297                 if (IS_ERR(cobj)) {
5298                         if (lfsck_is_dead_obj(parent)) {
5299                                 lfsck_tgt_put(tgt);
5300
5301                                 GOTO(out, rc = 0);
5302                         }
5303
5304                         rc = PTR_ERR(cobj);
5305                         goto next;
5306                 }
5307
5308                 if (!OBD_FAIL_CHECK(OBD_FAIL_LFSCK_ASSISTANT_DIRECT)) {
5309                         rc = dt_declare_attr_get(env, cobj);
5310                         if (rc != 0)
5311                                 goto next;
5312
5313                         rc = dt_declare_xattr_get(env, cobj, &buf,
5314                                                   XATTR_NAME_FID);
5315                         if (rc != 0)
5316                                 goto next;
5317                 }
5318
5319                 if (lso == NULL) {
5320                         struct lu_attr *attr = &info->lti_la;
5321
5322                         rc = dt_attr_get(env, parent, attr);
5323                         if (rc != 0)
5324                                 goto next;
5325
5326                         lso = lfsck_assistant_object_init(env,
5327                                 lfsck_dto2fid(parent), attr,
5328                                 lfsck->li_pos_current.lp_oit_cookie, false);
5329                         if (IS_ERR(lso)) {
5330                                 rc = PTR_ERR(lso);
5331                                 lso = NULL;
5332
5333                                 goto next;
5334                         }
5335                 }
5336
5337                 llr = lfsck_layout_assistant_req_init(lso, cobj, comp_id,
5338                                                       index, i);
5339                 if (IS_ERR(llr)) {
5340                         rc = PTR_ERR(llr);
5341                         goto next;
5342                 }
5343
5344                 cobj = NULL;
5345                 spin_lock(&lad->lad_lock);
5346                 if (lad->lad_assistant_status < 0) {
5347                         spin_unlock(&lad->lad_lock);
5348                         lfsck_layout_assistant_req_fini(env, &llr->llr_lar);
5349                         lfsck_tgt_put(tgt);
5350                         RETURN(lad->lad_assistant_status);
5351                 }
5352
5353                 list_add_tail(&llr->llr_lar.lar_list, &lad->lad_req_list);
5354                 if (lad->lad_prefetched == 0)
5355                         wakeup = true;
5356
5357                 lad->lad_prefetched++;
5358                 spin_unlock(&lad->lad_lock);
5359                 if (wakeup)
5360                         wake_up_all(&athread->t_ctl_waitq);
5361
5362 next:
5363                 down_write(&com->lc_sem);
5364                 com->lc_new_checked++;
5365                 if (rc < 0)
5366                         lfsck_layout_record_failure(env, lfsck, lo);
5367                 up_write(&com->lc_sem);
5368
5369                 if (cobj != NULL && !IS_ERR(cobj))
5370                         lfsck_object_put(env, cobj);
5371
5372                 if (likely(tgt != NULL))
5373                         lfsck_tgt_put(tgt);
5374
5375                 if (rc < 0 && bk->lb_param & LPF_FAILOUT)
5376                         GOTO(out, rc);
5377         }
5378
5379         GOTO(out, rc = 0);
5380
5381 out:
5382         if (lso != NULL)
5383                 lfsck_assistant_object_put(env, lso);
5384
5385         return rc;
5386 }
5387
5388 /* For the given object, read its layout EA locally. For each stripe, pre-fetch
5389  * the OST-object's attribute and generate an structure lfsck_layout_req on the
5390  * list ::lad_req_list.
5391  *
5392  * For each request on above list, the lfsck_layout_assistant thread compares
5393  * the OST side attribute with local attribute, if inconsistent, then repair it.
5394  *
5395  * All above processing is async mode with pipeline. */
5396 static int lfsck_layout_master_exec_oit(const struct lu_env *env,
5397                                         struct lfsck_component *com,
5398                                         struct dt_object *obj)
5399 {
5400         struct lfsck_thread_info        *info   = lfsck_env_info(env);
5401         struct ost_id                   *oi     = &info->lti_oi;
5402         struct lfsck_layout             *lo     = com->lc_file_ram;
5403         struct lfsck_assistant_data     *lad    = com->lc_data;
5404         struct lfsck_instance           *lfsck  = com->lc_lfsck;
5405         struct lfsck_bookmark           *bk     = &lfsck->li_bookmark_ram;
5406         struct thandle                  *handle = NULL;
5407         struct lu_buf                   *buf    = &info->lti_big_buf;
5408         struct lov_mds_md_v1            *lmm    = NULL;
5409         struct dt_device                *dev    = lfsck_obj2dev(obj);
5410         struct lustre_handle             lh     = { 0 };
5411         struct lu_buf                    ea_buf = { NULL };
5412         struct lov_comp_md_v1           *lcm    = NULL;
5413         struct lov_comp_md_entry_v1     *lcme   = NULL;
5414         int                              rc     = 0;
5415         int                              size   = 0;
5416         __u32                            magic  = 0;
5417         __u16                            count  = 0;
5418         bool                             locked = false;
5419         bool                             stripe = false;
5420         bool                             bad_oi = false;
5421         ENTRY;
5422
5423         if (!S_ISREG(lfsck_object_type(obj)))
5424                 GOTO(out, rc = 0);
5425
5426         if (lad->lad_assistant_status < 0)
5427                 GOTO(out, rc = -ESRCH);
5428
5429         fid_to_lmm_oi(lfsck_dto2fid(obj), oi);
5430         lmm_oi_cpu_to_le(oi, oi);
5431         dt_read_lock(env, obj, 0);
5432         locked = true;
5433
5434 again:
5435         bad_oi = false;
5436         if (dt_object_exists(obj) == 0 ||
5437             lfsck_is_dead_obj(obj))
5438                 GOTO(out, rc = 0);
5439
5440         rc = lfsck_layout_get_lovea(env, obj, buf);
5441         if (rc <= 0)
5442                 /* Skip bad lov EA during the 1st cycle scanning, and
5443                  * try to recover it via orphan in the 2nd scanning. */
5444                 GOTO(out, rc = (rc == -EINVAL ? 0 : rc));
5445
5446         size = rc;
5447         lmm = buf->lb_buf;
5448         magic = le32_to_cpu(lmm->lmm_magic);
5449         if (magic == LOV_MAGIC_COMP_V1) {
5450                 int i;
5451
5452                 lcm = buf->lb_buf;
5453                 count = le16_to_cpu(lcm->lcm_entry_count);
5454                 for (i = 0; i < count; i++) {
5455                         lcme = &lcm->lcm_entries[i];
5456                         lmm = buf->lb_buf + le32_to_cpu(lcme->lcme_offset);
5457                         if (memcmp(oi, &lmm->lmm_oi, sizeof(*oi)) != 0)
5458                                 goto fix;
5459                 }
5460
5461                 GOTO(out, stripe = true);
5462         } else if (memcmp(oi, &lmm->lmm_oi, sizeof(*oi)) == 0) {
5463                 GOTO(out, stripe = true);
5464         }
5465
5466 fix:
5467         /* Inconsistent lmm_oi, should be repaired. */
5468         bad_oi = true;
5469
5470         if (bk->lb_param & LPF_DRYRUN) {
5471                 lo->ll_objs_repaired[LLIT_OTHERS - 1]++;
5472
5473                 GOTO(out, stripe = true);
5474         }
5475
5476         if (!lustre_handle_is_used(&lh)) {
5477                 dt_read_unlock(env, obj);
5478                 locked = false;
5479                 rc = lfsck_ibits_lock(env, lfsck, obj, &lh,
5480                                       MDS_INODELOCK_LAYOUT |
5481                                       MDS_INODELOCK_XATTR, LCK_EX);
5482                 if (rc != 0)
5483                         GOTO(out, rc);
5484
5485                 handle = dt_trans_create(env, dev);
5486                 if (IS_ERR(handle))
5487                         GOTO(out, rc = PTR_ERR(handle));
5488
5489                 lfsck_buf_init(&ea_buf, lmm, size);
5490                 rc = dt_declare_xattr_set(env, obj, &ea_buf, XATTR_NAME_LOV,
5491                                           LU_XATTR_REPLACE, handle);
5492                 if (rc != 0)
5493                         GOTO(out, rc);
5494
5495                 rc = dt_trans_start_local(env, dev, handle);
5496                 if (rc != 0)
5497                         GOTO(out, rc);
5498
5499                 dt_write_lock(env, obj, 0);
5500                 locked = true;
5501
5502                 goto again;
5503         }
5504
5505         if (magic == LOV_MAGIC_COMP_V1) {
5506                 int i;
5507
5508                 for (i = 0; i < count; i++) {
5509                         lcme = &lcm->lcm_entries[i];
5510                         lmm = buf->lb_buf + le32_to_cpu(lcme->lcme_offset);
5511                         lmm->lmm_oi = *oi;
5512                 }
5513         } else {
5514                 lmm->lmm_oi = *oi;
5515         }
5516
5517         rc = dt_xattr_set(env, obj, &ea_buf, XATTR_NAME_LOV,
5518                           LU_XATTR_REPLACE, handle);
5519         if (rc != 0)
5520                 GOTO(out, rc);
5521
5522         lo->ll_objs_repaired[LLIT_OTHERS - 1]++;
5523
5524         GOTO(out, stripe = true);
5525
5526 out:
5527         if (locked) {
5528                 if (lustre_handle_is_used(&lh))
5529                         dt_write_unlock(env, obj);
5530                 else
5531                         dt_read_unlock(env, obj);
5532         }
5533
5534         if (handle != NULL && !IS_ERR(handle))
5535                 dt_trans_stop(env, dev, handle);
5536
5537         lfsck_ibits_unlock(&lh, LCK_EX);
5538
5539         if (bad_oi)
5540                 CDEBUG(D_LFSCK, "%s: layout LFSCK master %s bad lmm_oi for "
5541                        DFID": rc = %d\n", lfsck_lfsck2name(lfsck),
5542                        bk->lb_param & LPF_DRYRUN ? "found" : "repaired",
5543                        PFID(lfsck_dto2fid(obj)), rc);
5544
5545         if (stripe) {
5546                 if (magic == LOV_MAGIC_COMP_V1) {
5547                         int i;
5548
5549                         for (i = 0; i < count; i++) {
5550                                 lcme = &lcm->lcm_entries[i];
5551                                 if (!(le32_to_cpu(lcme->lcme_flags) &
5552                                       LCME_FL_INIT))
5553                                         continue;
5554
5555                                 rc = lfsck_layout_scan_stripes(env, com, obj,
5556                                         (struct lov_mds_md_v1 *)(buf->lb_buf +
5557                                         le32_to_cpu(lcme->lcme_offset)),
5558                                         le32_to_cpu(lcme->lcme_id));
5559                         }
5560                 } else {
5561                         rc = lfsck_layout_scan_stripes(env, com, obj, lmm, 0);
5562                 }
5563         } else {
5564                 down_write(&com->lc_sem);
5565                 com->lc_new_checked++;
5566                 if (rc < 0)
5567                         lfsck_layout_record_failure(env, lfsck, lo);
5568                 up_write(&com->lc_sem);
5569         }
5570
5571         return rc;
5572 }
5573
5574 static int lfsck_layout_slave_exec_oit(const struct lu_env *env,
5575                                        struct lfsck_component *com,
5576                                        struct dt_object *obj)
5577 {
5578         struct lfsck_instance           *lfsck  = com->lc_lfsck;
5579         struct lfsck_layout             *lo     = com->lc_file_ram;
5580         const struct lu_fid             *fid    = lfsck_dto2fid(obj);
5581         struct lfsck_layout_slave_data  *llsd   = com->lc_data;
5582         struct lfsck_layout_seq         *lls;
5583         __u64                            seq;
5584         __u64                            oid;
5585         int                              rc;
5586         ENTRY;
5587
5588         LASSERT(llsd != NULL);
5589
5590         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_DELAY5) &&
5591             cfs_fail_val == lfsck_dev_idx(lfsck)) {
5592                 struct l_wait_info       lwi = LWI_TIMEOUT(cfs_time_seconds(1),
5593                                                            NULL, NULL);
5594                 struct ptlrpc_thread    *thread = &lfsck->li_thread;
5595
5596                 l_wait_event(thread->t_ctl_waitq,
5597                              !thread_is_running(thread),
5598                              &lwi);
5599         }
5600
5601         lfsck_rbtree_update_bitmap(env, com, fid, false);
5602
5603         down_write(&com->lc_sem);
5604         if (fid_is_idif(fid))
5605                 seq = 0;
5606         else if (!fid_is_norm(fid) ||
5607                  !fid_is_for_ostobj(env, lfsck, obj, fid))
5608                 GOTO(unlock, rc = 0);
5609         else
5610                 seq = fid_seq(fid);
5611         com->lc_new_checked++;
5612
5613         lls = lfsck_layout_seq_lookup(llsd, seq);
5614         if (lls == NULL) {
5615                 OBD_ALLOC_PTR(lls);
5616                 if (unlikely(lls == NULL))
5617                         GOTO(unlock, rc = -ENOMEM);
5618
5619                 INIT_LIST_HEAD(&lls->lls_list);
5620                 lls->lls_seq = seq;
5621                 rc = lfsck_layout_lastid_load(env, com, lls);
5622                 if (rc != 0) {
5623                         CDEBUG(D_LFSCK, "%s: layout LFSCK failed to "
5624                               "load LAST_ID for %#llx: rc = %d\n",
5625                               lfsck_lfsck2name(com->lc_lfsck), seq, rc);
5626                         lo->ll_objs_failed_phase1++;
5627                         OBD_FREE_PTR(lls);
5628                         GOTO(unlock, rc);
5629                 }
5630
5631                 lfsck_layout_seq_insert(llsd, lls);
5632         }
5633
5634         if (unlikely(fid_is_last_id(fid)))
5635                 GOTO(unlock, rc = 0);
5636
5637         if (fid_is_idif(fid))
5638                 oid = fid_idif_id(fid_seq(fid), fid_oid(fid), fid_ver(fid));
5639         else
5640                 oid = fid_oid(fid);
5641
5642         if (oid > lls->lls_lastid_known)
5643                 lls->lls_lastid_known = oid;
5644
5645         if (oid > lls->lls_lastid) {
5646                 if (!(lo->ll_flags & LF_CRASHED_LASTID)) {
5647                         /* OFD may create new objects during LFSCK scanning. */
5648                         rc = lfsck_layout_lastid_reload(env, com, lls);
5649                         if (unlikely(rc != 0)) {
5650                                 CDEBUG(D_LFSCK, "%s: layout LFSCK failed to "
5651                                       "reload LAST_ID for %#llx: rc = %d\n",
5652                                       lfsck_lfsck2name(com->lc_lfsck),
5653                                       lls->lls_seq, rc);
5654
5655                                 GOTO(unlock, rc);
5656                         }
5657
5658                         if (oid <= lls->lls_lastid ||
5659                             lo->ll_flags & LF_CRASHED_LASTID)
5660                                 GOTO(unlock, rc = 0);
5661
5662                         LASSERT(lfsck->li_out_notify != NULL);
5663
5664                         lfsck->li_out_notify(env, lfsck->li_out_notify_data,
5665                                              LE_LASTID_REBUILDING);
5666                         lo->ll_flags |= LF_CRASHED_LASTID;
5667
5668                         CDEBUG(D_LFSCK, "%s: layout LFSCK finds crashed "
5669                                "LAST_ID file (2) for the sequence %#llx"
5670                                ", old value %llu, known value %llu\n",
5671                                lfsck_lfsck2name(lfsck), lls->lls_seq,
5672                                lls->lls_lastid, oid);
5673                 }
5674
5675                 lls->lls_lastid = oid;
5676                 lls->lls_dirty = 1;
5677         }
5678
5679         GOTO(unlock, rc = 0);
5680
5681 unlock:
5682         up_write(&com->lc_sem);
5683
5684         return rc;
5685 }
5686
5687 static int lfsck_layout_exec_dir(const struct lu_env *env,
5688                                  struct lfsck_component *com,
5689                                  struct lfsck_assistant_object *lso,
5690                                  struct lu_dirent *ent, __u16 type)
5691 {
5692         return 0;
5693 }
5694
5695 static int lfsck_layout_master_post(const struct lu_env *env,
5696                                     struct lfsck_component *com,
5697                                     int result, bool init)
5698 {
5699         struct lfsck_instance   *lfsck  = com->lc_lfsck;
5700         struct lfsck_layout     *lo     = com->lc_file_ram;
5701         int                      rc;
5702         ENTRY;
5703
5704         lfsck_post_generic(env, com, &result);
5705
5706         down_write(&com->lc_sem);
5707         spin_lock(&lfsck->li_lock);
5708         if (!init)
5709                 lo->ll_pos_last_checkpoint =
5710                                 lfsck->li_pos_checkpoint.lp_oit_cookie;
5711
5712         if (result > 0) {
5713                 if (lo->ll_flags & LF_INCOMPLETE)
5714                         lo->ll_status = LS_PARTIAL;
5715                 else
5716                         lo->ll_status = LS_SCANNING_PHASE2;
5717                 lo->ll_flags |= LF_SCANNED_ONCE;
5718                 lo->ll_flags &= ~LF_UPGRADE;
5719                 list_move_tail(&com->lc_link, &lfsck->li_list_double_scan);
5720         } else if (result == 0) {
5721                 if (lfsck->li_status != 0)
5722                         lo->ll_status = lfsck->li_status;
5723                 else
5724                         lo->ll_status = LS_STOPPED;
5725                 if (lo->ll_status != LS_PAUSED)
5726                         list_move_tail(&com->lc_link, &lfsck->li_list_idle);
5727         } else {
5728                 lo->ll_status = LS_FAILED;
5729                 list_move_tail(&com->lc_link, &lfsck->li_list_idle);
5730         }
5731         spin_unlock(&lfsck->li_lock);
5732
5733         if (!init) {
5734                 lo->ll_run_time_phase1 += cfs_duration_sec(cfs_time_current() +
5735                                 HALF_SEC - lfsck->li_time_last_checkpoint);
5736                 lo->ll_time_last_checkpoint = cfs_time_current_sec();
5737                 lo->ll_objs_checked_phase1 += com->lc_new_checked;
5738                 com->lc_new_checked = 0;
5739         }
5740
5741         rc = lfsck_layout_store(env, com);
5742         up_write(&com->lc_sem);
5743
5744         CDEBUG(D_LFSCK, "%s: layout LFSCK master post done: rc = %d\n",
5745                lfsck_lfsck2name(lfsck), rc);
5746
5747         RETURN(rc);
5748 }
5749
5750 static int lfsck_layout_slave_post(const struct lu_env *env,
5751                                    struct lfsck_component *com,
5752                                    int result, bool init)
5753 {
5754         struct lfsck_instance   *lfsck = com->lc_lfsck;
5755         struct lfsck_layout     *lo    = com->lc_file_ram;
5756         int                      rc;
5757         bool                     done  = false;
5758
5759         down_write(&com->lc_sem);
5760         rc = lfsck_layout_lastid_store(env, com);
5761         if (rc != 0)
5762                 result = rc;
5763
5764         LASSERT(lfsck->li_out_notify != NULL);
5765
5766         spin_lock(&lfsck->li_lock);
5767         if (!init)
5768                 lo->ll_pos_last_checkpoint =
5769                                 lfsck->li_pos_checkpoint.lp_oit_cookie;
5770
5771         if (result > 0) {
5772                 lo->ll_status = LS_SCANNING_PHASE2;
5773                 lo->ll_flags |= LF_SCANNED_ONCE;
5774                 if (lo->ll_flags & LF_CRASHED_LASTID) {
5775                         done = true;
5776                         lo->ll_flags &= ~LF_CRASHED_LASTID;
5777
5778                         CDEBUG(D_LFSCK, "%s: layout LFSCK has rebuilt "
5779                                "crashed LAST_ID files successfully\n",
5780                                lfsck_lfsck2name(lfsck));
5781                 }
5782                 lo->ll_flags &= ~LF_UPGRADE;
5783                 list_move_tail(&com->lc_link, &lfsck->li_list_double_scan);
5784         } else if (result == 0) {
5785                 if (lfsck->li_status != 0)
5786                         lo->ll_status = lfsck->li_status;
5787                 else
5788                         lo->ll_status = LS_STOPPED;
5789                 if (lo->ll_status != LS_PAUSED)
5790                         list_move_tail(&com->lc_link, &lfsck->li_list_idle);
5791         } else {
5792                 lo->ll_status = LS_FAILED;
5793                 list_move_tail(&com->lc_link, &lfsck->li_list_idle);
5794         }
5795         spin_unlock(&lfsck->li_lock);
5796
5797         if (done)
5798                 lfsck->li_out_notify(env, lfsck->li_out_notify_data,
5799                                      LE_LASTID_REBUILT);
5800
5801         if (!init) {
5802                 lo->ll_run_time_phase1 += cfs_duration_sec(cfs_time_current() +
5803                                 HALF_SEC - lfsck->li_time_last_checkpoint);
5804                 lo->ll_time_last_checkpoint = cfs_time_current_sec();
5805                 lo->ll_objs_checked_phase1 += com->lc_new_checked;
5806                 com->lc_new_checked = 0;
5807         }
5808
5809         rc = lfsck_layout_store(env, com);
5810         up_write(&com->lc_sem);
5811
5812         lfsck_layout_slave_notify_master(env, com, LE_PHASE1_DONE, result);
5813
5814         CDEBUG(D_LFSCK, "%s: layout LFSCK slave post done: rc = %d\n",
5815                lfsck_lfsck2name(lfsck), rc);
5816
5817         return rc;
5818 }
5819
5820 static void lfsck_layout_dump(const struct lu_env *env,
5821                               struct lfsck_component *com, struct seq_file *m)
5822 {
5823         struct lfsck_instance   *lfsck = com->lc_lfsck;
5824         struct lfsck_bookmark   *bk    = &lfsck->li_bookmark_ram;
5825         struct lfsck_layout     *lo    = com->lc_file_ram;
5826
5827         down_read(&com->lc_sem);
5828         seq_printf(m, "name: lfsck_layout\n"
5829                    "magic: %#x\n"
5830                    "version: %d\n"
5831                    "status: %s\n",
5832                    lo->ll_magic,
5833                    bk->lb_version,
5834                    lfsck_status2name(lo->ll_status));
5835
5836         lfsck_bits_dump(m, lo->ll_flags, lfsck_flags_names, "flags");
5837
5838         lfsck_bits_dump(m, bk->lb_param, lfsck_param_names, "param");
5839
5840         lfsck_time_dump(m, lo->ll_time_last_complete, "last_completed");
5841
5842         lfsck_time_dump(m, lo->ll_time_latest_start, "latest_start");
5843
5844         lfsck_time_dump(m, lo->ll_time_last_checkpoint, "last_checkpoint");
5845
5846         seq_printf(m, "latest_start_position: %llu\n"
5847                    "last_checkpoint_position: %llu\n"
5848                    "first_failure_position: %llu\n",
5849                    lo->ll_pos_latest_start,
5850                    lo->ll_pos_last_checkpoint,
5851                    lo->ll_pos_first_inconsistent);
5852
5853         seq_printf(m, "success_count: %u\n"
5854                    "repaired_dangling: %llu\n"
5855                    "repaired_unmatched_pair: %llu\n"
5856                    "repaired_multiple_referenced: %llu\n"
5857                    "repaired_orphan: %llu\n"
5858                    "repaired_inconsistent_owner: %llu\n"
5859                    "repaired_others: %llu\n"
5860                    "skipped: %llu\n"
5861                    "failed_phase1: %llu\n"
5862                    "failed_phase2: %llu\n",
5863                    lo->ll_success_count,
5864                    lo->ll_objs_repaired[LLIT_DANGLING - 1],
5865                    lo->ll_objs_repaired[LLIT_UNMATCHED_PAIR - 1],
5866                    lo->ll_objs_repaired[LLIT_MULTIPLE_REFERENCED - 1],
5867                    lo->ll_objs_repaired[LLIT_ORPHAN - 1],
5868                    lo->ll_objs_repaired[LLIT_INCONSISTENT_OWNER - 1],
5869                    lo->ll_objs_repaired[LLIT_OTHERS - 1],
5870                    lo->ll_objs_skipped,
5871                    lo->ll_objs_failed_phase1,
5872                    lo->ll_objs_failed_phase2);
5873
5874         if (lo->ll_status == LS_SCANNING_PHASE1) {
5875                 __u64 pos;
5876                 cfs_duration_t duration = cfs_time_current() -
5877                                           lfsck->li_time_last_checkpoint;
5878                 __u64 checked = lo->ll_objs_checked_phase1 +
5879                                 com->lc_new_checked;
5880                 __u64 speed = checked;
5881                 __u64 new_checked = com->lc_new_checked *
5882                                     msecs_to_jiffies(MSEC_PER_SEC);
5883                 __u32 rtime = lo->ll_run_time_phase1 +
5884                               cfs_duration_sec(duration + HALF_SEC);
5885
5886                 if (duration != 0)
5887                         do_div(new_checked, duration);
5888                 if (rtime != 0)
5889                         do_div(speed, rtime);
5890                 seq_printf(m, "checked_phase1: %llu\n"
5891                            "checked_phase2: %llu\n"
5892                            "run_time_phase1: %u seconds\n"
5893                            "run_time_phase2: %u seconds\n"
5894                            "average_speed_phase1: %llu items/sec\n"
5895                            "average_speed_phase2: N/A\n"
5896                            "real-time_speed_phase1: %llu items/sec\n"
5897                            "real-time_speed_phase2: N/A\n",
5898                            checked,
5899                            lo->ll_objs_checked_phase2,
5900                            rtime,
5901                            lo->ll_run_time_phase2,
5902                            speed,
5903                            new_checked);
5904
5905                 if (likely(lfsck->li_di_oit)) {
5906                         const struct dt_it_ops *iops =
5907                                 &lfsck->li_obj_oit->do_index_ops->dio_it;
5908
5909                         /* The low layer otable-based iteration position may NOT
5910                          * exactly match the layout-based directory traversal
5911                          * cookie. Generally, it is not a serious issue. But the
5912                          * caller should NOT make assumption on that. */
5913                         pos = iops->store(env, lfsck->li_di_oit);
5914                         if (!lfsck->li_current_oit_processed)
5915                                 pos--;
5916                 } else {
5917                         pos = lo->ll_pos_last_checkpoint;
5918                 }
5919
5920                 seq_printf(m, "current_position: %llu\n", pos);
5921         } else if (lo->ll_status == LS_SCANNING_PHASE2) {
5922                 cfs_duration_t duration = cfs_time_current() -
5923                                           com->lc_time_last_checkpoint;
5924                 __u64 checked = lo->ll_objs_checked_phase2 +
5925                                 com->lc_new_checked;
5926                 __u64 speed1 = lo->ll_objs_checked_phase1;
5927                 __u64 speed2 = checked;
5928                 __u64 new_checked = com->lc_new_checked *
5929                                     msecs_to_jiffies(MSEC_PER_SEC);
5930                 __u32 rtime = lo->ll_run_time_phase2 +
5931                               cfs_duration_sec(duration + HALF_SEC);
5932
5933                 if (duration != 0)
5934                         do_div(new_checked, duration);
5935                 if (lo->ll_run_time_phase1 != 0)
5936                         do_div(speed1, lo->ll_run_time_phase1);
5937                 if (rtime != 0)
5938                         do_div(speed2, rtime);
5939                 seq_printf(m, "checked_phase1: %llu\n"
5940                            "checked_phase2: %llu\n"
5941                            "run_time_phase1: %u seconds\n"
5942                            "run_time_phase2: %u seconds\n"
5943                            "average_speed_phase1: %llu items/sec\n"
5944                            "average_speed_phase2: %llu items/sec\n"
5945                            "real-time_speed_phase1: N/A\n"
5946                            "real-time_speed_phase2: %llu items/sec\n"
5947                            "current_position: "DFID"\n",
5948                            lo->ll_objs_checked_phase1,
5949                            checked,
5950                            lo->ll_run_time_phase1,
5951                            rtime,
5952                            speed1,
5953                            speed2,
5954                            new_checked,
5955                            PFID(&com->lc_fid_latest_scanned_phase2));
5956         } else {
5957                 __u64 speed1 = lo->ll_objs_checked_phase1;
5958                 __u64 speed2 = lo->ll_objs_checked_phase2;
5959
5960                 if (lo->ll_run_time_phase1 != 0)
5961                         do_div(speed1, lo->ll_run_time_phase1);
5962                 if (lo->ll_run_time_phase2 != 0)
5963                         do_div(speed2, lo->ll_run_time_phase2);
5964                 seq_printf(m, "checked_phase1: %llu\n"
5965                            "checked_phase2: %llu\n"
5966                            "run_time_phase1: %u seconds\n"
5967                            "run_time_phase2: %u seconds\n"
5968                            "average_speed_phase1: %llu items/sec\n"
5969                            "average_speed_phase2: %llu objs/sec\n"
5970                            "real-time_speed_phase1: N/A\n"
5971                            "real-time_speed_phase2: N/A\n"
5972                            "current_position: N/A\n",
5973                            lo->ll_objs_checked_phase1,
5974                            lo->ll_objs_checked_phase2,
5975                            lo->ll_run_time_phase1,
5976                            lo->ll_run_time_phase2,
5977                            speed1,
5978                            speed2);
5979         }
5980
5981         up_read(&com->lc_sem);
5982 }
5983
5984 static int lfsck_layout_master_double_scan(const struct lu_env *env,
5985                                            struct lfsck_component *com)
5986 {
5987         struct lfsck_layout             *lo     = com->lc_file_ram;
5988         struct lfsck_assistant_data     *lad    = com->lc_data;
5989         struct lfsck_instance           *lfsck  = com->lc_lfsck;
5990         struct lfsck_tgt_descs          *ltds;
5991         struct lfsck_tgt_desc           *ltd;
5992         struct lfsck_tgt_desc           *next;
5993         int                              rc;
5994
5995         rc = lfsck_double_scan_generic(env, com, lo->ll_status);
5996
5997         if (thread_is_stopped(&lad->lad_thread)) {
5998                 LASSERT(list_empty(&lad->lad_req_list));
5999                 LASSERT(list_empty(&lad->lad_ost_phase1_list));
6000                 LASSERT(list_empty(&lad->lad_mdt_phase1_list));
6001
6002                 ltds = &lfsck->li_ost_descs;
6003                 spin_lock(&ltds->ltd_lock);
6004                 list_for_each_entry_safe(ltd, next, &lad->lad_ost_phase2_list,
6005                                          ltd_layout_phase_list) {
6006                         list_del_init(&ltd->ltd_layout_phase_list);
6007                 }
6008                 spin_unlock(&ltds->ltd_lock);
6009
6010                 ltds = &lfsck->li_mdt_descs;
6011                 spin_lock(&ltds->ltd_lock);
6012                 list_for_each_entry_safe(ltd, next, &lad->lad_mdt_phase2_list,
6013                                          ltd_layout_phase_list) {
6014                         list_del_init(&ltd->ltd_layout_phase_list);
6015                 }
6016                 spin_unlock(&ltds->ltd_lock);
6017         }
6018
6019         return rc;
6020 }
6021
6022 static int lfsck_layout_slave_double_scan(const struct lu_env *env,
6023                                           struct lfsck_component *com)
6024 {
6025         struct lfsck_instance           *lfsck  = com->lc_lfsck;
6026         struct lfsck_layout_slave_data  *llsd   = com->lc_data;
6027         struct lfsck_layout             *lo     = com->lc_file_ram;
6028         struct ptlrpc_thread            *thread = &lfsck->li_thread;
6029         int                              rc;
6030         ENTRY;
6031
6032         CDEBUG(D_LFSCK, "%s: layout LFSCK slave phase2 scan start\n",
6033                lfsck_lfsck2name(lfsck));
6034
6035         atomic_inc(&lfsck->li_double_scan_count);
6036
6037         if (lo->ll_flags & LF_INCOMPLETE)
6038                 GOTO(done, rc = 1);
6039
6040         com->lc_new_checked = 0;
6041         com->lc_new_scanned = 0;
6042         com->lc_time_last_checkpoint = cfs_time_current();
6043         com->lc_time_next_checkpoint = com->lc_time_last_checkpoint +
6044                                 cfs_time_seconds(LFSCK_CHECKPOINT_INTERVAL);
6045
6046         while (1) {
6047                 struct l_wait_info lwi = LWI_TIMEOUT(cfs_time_seconds(30),
6048                                                      NULL, NULL);
6049
6050                 rc = lfsck_layout_slave_query_master(env, com);
6051                 if (list_empty(&llsd->llsd_master_list)) {
6052                         if (unlikely(!thread_is_running(thread)))
6053                                 rc = 0;
6054                         else
6055                                 rc = 1;
6056
6057                         GOTO(done, rc);
6058                 }
6059
6060                 if (rc < 0)
6061                         GOTO(done, rc);
6062
6063                 rc = l_wait_event(thread->t_ctl_waitq,
6064                                   !thread_is_running(thread) ||
6065                                   lo->ll_flags & LF_INCOMPLETE ||
6066                                   list_empty(&llsd->llsd_master_list),
6067                                   &lwi);
6068                 if (unlikely(!thread_is_running(thread)))
6069                         GOTO(done, rc = 0);
6070
6071                 if (lo->ll_flags & LF_INCOMPLETE)
6072                         GOTO(done, rc = 1);
6073
6074                 if (rc == -ETIMEDOUT)
6075                         continue;
6076
6077                 GOTO(done, rc = (rc < 0 ? rc : 1));
6078         }
6079
6080 done:
6081         rc = lfsck_layout_double_scan_result(env, com, rc);
6082         lfsck_layout_slave_notify_master(env, com, LE_PHASE2_DONE,
6083                         (rc > 0 && lo->ll_flags & LF_INCOMPLETE) ? 0 : rc);
6084         lfsck_layout_slave_quit(env, com);
6085         if (atomic_dec_and_test(&lfsck->li_double_scan_count))
6086                 wake_up_all(&lfsck->li_thread.t_ctl_waitq);
6087
6088         CDEBUG(D_LFSCK, "%s: layout LFSCK slave phase2 scan finished, "
6089                "status %d: rc = %d\n",
6090                lfsck_lfsck2name(lfsck), lo->ll_status, rc);
6091
6092         return rc;
6093 }
6094
6095 static void lfsck_layout_master_data_release(const struct lu_env *env,
6096                                              struct lfsck_component *com)
6097 {
6098         struct lfsck_assistant_data     *lad    = com->lc_data;
6099         struct lfsck_instance           *lfsck  = com->lc_lfsck;
6100         struct lfsck_tgt_descs          *ltds;
6101         struct lfsck_tgt_desc           *ltd;
6102         struct lfsck_tgt_desc           *next;
6103
6104         LASSERT(lad != NULL);
6105         LASSERT(thread_is_init(&lad->lad_thread) ||
6106                 thread_is_stopped(&lad->lad_thread));
6107         LASSERT(list_empty(&lad->lad_req_list));
6108
6109         com->lc_data = NULL;
6110
6111         ltds = &lfsck->li_ost_descs;
6112         spin_lock(&ltds->ltd_lock);
6113         list_for_each_entry_safe(ltd, next, &lad->lad_ost_phase1_list,
6114                                  ltd_layout_phase_list) {
6115                 list_del_init(&ltd->ltd_layout_phase_list);
6116         }
6117         list_for_each_entry_safe(ltd, next, &lad->lad_ost_phase2_list,
6118                                  ltd_layout_phase_list) {
6119                 list_del_init(&ltd->ltd_layout_phase_list);
6120         }
6121         list_for_each_entry_safe(ltd, next, &lad->lad_ost_list,
6122                                  ltd_layout_list) {
6123                 list_del_init(&ltd->ltd_layout_list);
6124         }
6125         spin_unlock(&ltds->ltd_lock);
6126
6127         ltds = &lfsck->li_mdt_descs;
6128         spin_lock(&ltds->ltd_lock);
6129         list_for_each_entry_safe(ltd, next, &lad->lad_mdt_phase1_list,
6130                                  ltd_layout_phase_list) {
6131                 list_del_init(&ltd->ltd_layout_phase_list);
6132         }
6133         list_for_each_entry_safe(ltd, next, &lad->lad_mdt_phase2_list,
6134                                  ltd_layout_phase_list) {
6135                 list_del_init(&ltd->ltd_layout_phase_list);
6136         }
6137         list_for_each_entry_safe(ltd, next, &lad->lad_mdt_list,
6138                                  ltd_layout_list) {
6139                 list_del_init(&ltd->ltd_layout_list);
6140         }
6141         spin_unlock(&ltds->ltd_lock);
6142
6143         if (likely(lad->lad_bitmap != NULL))
6144                 CFS_FREE_BITMAP(lad->lad_bitmap);
6145
6146         OBD_FREE_PTR(lad);
6147 }
6148
6149 static void lfsck_layout_slave_data_release(const struct lu_env *env,
6150                                             struct lfsck_component *com)
6151 {
6152         struct lfsck_layout_slave_data *llsd = com->lc_data;
6153
6154         lfsck_layout_slave_quit(env, com);
6155         com->lc_data = NULL;
6156         OBD_FREE_PTR(llsd);
6157 }
6158
6159 static void lfsck_layout_master_quit(const struct lu_env *env,
6160                                      struct lfsck_component *com)
6161 {
6162         struct lfsck_assistant_data     *lad    = com->lc_data;
6163         struct lfsck_instance           *lfsck  = com->lc_lfsck;
6164         struct lfsck_tgt_descs          *ltds;
6165         struct lfsck_tgt_desc           *ltd;
6166         struct lfsck_tgt_desc           *next;
6167
6168         LASSERT(lad != NULL);
6169
6170         lfsck_quit_generic(env, com);
6171
6172         LASSERT(thread_is_init(&lad->lad_thread) ||
6173                 thread_is_stopped(&lad->lad_thread));
6174         LASSERT(list_empty(&lad->lad_req_list));
6175
6176         ltds = &lfsck->li_ost_descs;
6177         spin_lock(&ltds->ltd_lock);
6178         list_for_each_entry_safe(ltd, next, &lad->lad_ost_phase1_list,
6179                                  ltd_layout_phase_list) {
6180                 list_del_init(&ltd->ltd_layout_phase_list);
6181         }
6182         list_for_each_entry_safe(ltd, next, &lad->lad_ost_phase2_list,
6183                                  ltd_layout_phase_list) {
6184                 list_del_init(&ltd->ltd_layout_phase_list);
6185         }
6186         spin_unlock(&ltds->ltd_lock);
6187
6188         ltds = &lfsck->li_mdt_descs;
6189         spin_lock(&ltds->ltd_lock);
6190         list_for_each_entry_safe(ltd, next, &lad->lad_mdt_phase1_list,
6191                                  ltd_layout_phase_list) {
6192                 list_del_init(&ltd->ltd_layout_phase_list);
6193         }
6194         list_for_each_entry_safe(ltd, next, &lad->lad_mdt_phase2_list,
6195                                  ltd_layout_phase_list) {
6196                 list_del_init(&ltd->ltd_layout_phase_list);
6197         }
6198         spin_unlock(&ltds->ltd_lock);
6199 }
6200
6201 static void lfsck_layout_slave_quit(const struct lu_env *env,
6202                                     struct lfsck_component *com)
6203 {
6204         struct lfsck_layout_slave_data   *llsd  = com->lc_data;
6205         struct lfsck_layout_seq          *lls;
6206         struct lfsck_layout_seq          *next;
6207         struct lfsck_layout_slave_target *llst;
6208
6209         LASSERT(llsd != NULL);
6210
6211         down_write(&com->lc_sem);
6212         list_for_each_entry_safe(lls, next, &llsd->llsd_seq_list,
6213                                  lls_list) {
6214                 list_del_init(&lls->lls_list);
6215                 lfsck_object_put(env, lls->lls_lastid_obj);
6216                 OBD_FREE_PTR(lls);
6217         }
6218         up_write(&com->lc_sem);
6219
6220         spin_lock(&llsd->llsd_lock);
6221         while (!list_empty(&llsd->llsd_master_list)) {
6222                 llst = list_entry(llsd->llsd_master_list.next,
6223                                   struct lfsck_layout_slave_target, llst_list);
6224                 list_del_init(&llst->llst_list);
6225                 spin_unlock(&llsd->llsd_lock);
6226                 lfsck_layout_llst_put(llst);
6227                 spin_lock(&llsd->llsd_lock);
6228         }
6229         spin_unlock(&llsd->llsd_lock);
6230
6231         lfsck_rbtree_cleanup(env, com);
6232 }
6233
6234 static int lfsck_layout_master_in_notify(const struct lu_env *env,
6235                                          struct lfsck_component *com,
6236                                          struct lfsck_request *lr)
6237 {
6238         struct lfsck_instance           *lfsck = com->lc_lfsck;
6239         struct lfsck_layout             *lo    = com->lc_file_ram;
6240         struct lfsck_assistant_data     *lad   = com->lc_data;
6241         struct lfsck_tgt_descs          *ltds;
6242         struct lfsck_tgt_desc           *ltd;
6243         bool                             fail  = false;
6244         ENTRY;
6245
6246         if (lr->lr_event == LE_PAIRS_VERIFY) {
6247                 int rc;
6248
6249                 rc = lfsck_layout_master_check_pairs(env, com, &lr->lr_fid,
6250                                                      &lr->lr_fid2,
6251                                                      lr->lr_comp_id);
6252
6253                 RETURN(rc);
6254         }
6255
6256         CDEBUG(D_LFSCK, "%s: layout LFSCK master handles notify %u "
6257                "from %s %x, status %d, flags %x, flags2 %x\n",
6258                lfsck_lfsck2name(lfsck), lr->lr_event,
6259                (lr->lr_flags & LEF_FROM_OST) ? "OST" : "MDT",
6260                lr->lr_index, lr->lr_status, lr->lr_flags, lr->lr_flags2);
6261
6262         if (lr->lr_event != LE_PHASE1_DONE &&
6263             lr->lr_event != LE_PHASE2_DONE &&
6264             lr->lr_event != LE_PEER_EXIT)
6265                 RETURN(-EINVAL);
6266
6267         if (lr->lr_flags & LEF_FROM_OST)
6268                 ltds = &lfsck->li_ost_descs;
6269         else
6270                 ltds = &lfsck->li_mdt_descs;
6271         spin_lock(&ltds->ltd_lock);
6272         ltd = lfsck_ltd2tgt(ltds, lr->lr_index);
6273         if (ltd == NULL) {
6274                 spin_unlock(&ltds->ltd_lock);
6275
6276                 RETURN(-ENXIO);
6277         }
6278
6279         list_del_init(&ltd->ltd_layout_phase_list);
6280         switch (lr->lr_event) {
6281         case LE_PHASE1_DONE:
6282                 if (lr->lr_status <= 0 || lr->lr_flags2 & LF_INCOMPLETE) {
6283                         if (lr->lr_flags2 & LF_INCOMPLETE) {
6284                                 if (lr->lr_flags & LEF_FROM_OST)
6285                                         lfsck_lad_set_bitmap(env, com,
6286                                                              ltd->ltd_index);
6287                                 else
6288                                         lo->ll_flags |= LF_INCOMPLETE;
6289                         }
6290                         ltd->ltd_layout_done = 1;
6291                         list_del_init(&ltd->ltd_layout_list);
6292                         fail = true;
6293                         break;
6294                 }
6295
6296                 if (lr->lr_flags & LEF_FROM_OST) {
6297                         if (list_empty(&ltd->ltd_layout_list))
6298                                 list_add_tail(&ltd->ltd_layout_list,
6299                                               &lad->lad_ost_list);
6300                         list_add_tail(&ltd->ltd_layout_phase_list,
6301                                       &lad->lad_ost_phase2_list);
6302                 } else {
6303                         if (list_empty(&ltd->ltd_layout_list))
6304                                 list_add_tail(&ltd->ltd_layout_list,
6305                                               &lad->lad_mdt_list);
6306                         list_add_tail(&ltd->ltd_layout_phase_list,
6307                                       &lad->lad_mdt_phase2_list);
6308                 }
6309                 break;
6310         case LE_PHASE2_DONE:
6311                 ltd->ltd_layout_done = 1;
6312                 if (!list_empty(&ltd->ltd_layout_list)) {
6313                         list_del_init(&ltd->ltd_layout_list);
6314                         if (lr->lr_flags2 & LF_INCOMPLETE) {
6315                                 lfsck_lad_set_bitmap(env, com, ltd->ltd_index);
6316                                 fail = true;
6317                         }
6318                 }
6319
6320                 break;
6321         case LE_PEER_EXIT:
6322                 fail = true;
6323                 ltd->ltd_layout_done = 1;
6324                 list_del_init(&ltd->ltd_layout_list);
6325                 if (!(lfsck->li_bookmark_ram.lb_param & LPF_FAILOUT) &&
6326                     !(lr->lr_flags & LEF_FROM_OST))
6327                                 lo->ll_flags |= LF_INCOMPLETE;
6328                 break;
6329         default:
6330                 break;
6331         }
6332         spin_unlock(&ltds->ltd_lock);
6333
6334         if (fail && lfsck->li_bookmark_ram.lb_param & LPF_FAILOUT) {
6335                 struct lfsck_stop *stop = &lfsck_env_info(env)->lti_stop;
6336
6337                 memset(stop, 0, sizeof(*stop));
6338                 stop->ls_status = lr->lr_status;
6339                 stop->ls_flags = lr->lr_param & ~LPF_BROADCAST;
6340                 lfsck_stop(env, lfsck->li_bottom, stop);
6341         } else if (lfsck_phase2_next_ready(lad)) {
6342                 wake_up_all(&lad->lad_thread.t_ctl_waitq);
6343         }
6344
6345         RETURN(0);
6346 }
6347
6348 static int lfsck_layout_slave_in_notify_local(const struct lu_env *env,
6349                                               struct lfsck_component *com,
6350                                               struct lfsck_req_local *lrl,
6351                                               struct thandle *th)
6352 {
6353         ENTRY;
6354
6355         switch (lrl->lrl_event) {
6356         case LEL_FID_ACCESSED:
6357                 lfsck_rbtree_update_bitmap(env, com, &lrl->lrl_fid, true);
6358                 RETURN(0);
6359         case LEL_PAIRS_VERIFY_LOCAL: {
6360                 int rc;
6361
6362                 lrl->lrl_status = LPVS_INIT;
6363                 /* Firstly, if the MDT-object which is claimed via OST-object
6364                  * local stored PFID xattr recognizes the OST-object, then it
6365                  * must be that the client given PFID is wrong. */
6366                 rc = lfsck_layout_slave_check_pairs(env, com, &lrl->lrl_fid,
6367                                 &lrl->lrl_ff_local.ff_parent,
6368                                 lrl->lrl_ff_local.ff_layout.ol_comp_id);
6369                 if (rc <= 0)
6370                         RETURN(0);
6371
6372                 lrl->lrl_status = LPVS_INCONSISTENT;
6373                 /* The OST-object local stored PFID xattr is stale. We need to
6374                  * check whether the MDT-object that is claimed via the client
6375                  * given PFID information recognizes the OST-object or not. If
6376                  * matches, then need to update the OST-object's PFID xattr. */
6377                 rc = lfsck_layout_slave_check_pairs(env, com, &lrl->lrl_fid,
6378                                 &lrl->lrl_ff_client.ff_parent,
6379                                 lrl->lrl_ff_client.ff_layout.ol_comp_id);
6380                 /* For rc < 0 case:
6381                  * We are not sure whether the client given PFID information
6382                  * is correct or not, do nothing to avoid improper fixing.
6383                  *
6384                  * For rc > 0 case:
6385                  * The client given PFID information is also invalid, we can
6386                  * NOT fix the OST-object inconsistency.
6387                  */
6388                 if (!rc) {
6389                         lrl->lrl_status = LPVS_INCONSISTENT_TOFIX;
6390                         rc = lfsck_layout_slave_repair_pfid(env, com, lrl);
6391                 }
6392
6393                 RETURN(rc);
6394         }
6395         default:
6396                 break;
6397         }
6398
6399         RETURN(-EOPNOTSUPP);
6400 }
6401
6402 static int lfsck_layout_slave_in_notify(const struct lu_env *env,
6403                                         struct lfsck_component *com,
6404                                         struct lfsck_request *lr)
6405 {
6406         struct lfsck_instance *lfsck = com->lc_lfsck;
6407         struct lfsck_layout_slave_data *llsd = com->lc_data;
6408         struct lfsck_layout_slave_target *llst;
6409         int rc;
6410         ENTRY;
6411
6412         switch (lr->lr_event) {
6413         case LE_CONDITIONAL_DESTROY:
6414                 rc = lfsck_layout_slave_conditional_destroy(env, com, lr);
6415                 RETURN(rc);
6416         case LE_PHASE1_DONE: {
6417                 if (lr->lr_flags2 & LF_INCOMPLETE) {
6418                         struct lfsck_layout *lo = com->lc_file_ram;
6419
6420                         lo->ll_flags |= LF_INCOMPLETE;
6421                         llst = lfsck_layout_llst_find_and_del(llsd,
6422                                                               lr->lr_index,
6423                                                               true);
6424                         if (llst != NULL) {
6425                                 lfsck_layout_llst_put(llst);
6426                                 wake_up_all(&lfsck->li_thread.t_ctl_waitq);
6427                         }
6428                 }
6429
6430                 RETURN(0);
6431         }
6432         case LE_PHASE2_DONE:
6433         case LE_PEER_EXIT:
6434                 CDEBUG(D_LFSCK, "%s: layout LFSCK slave handle notify %u "
6435                        "from MDT %x, status %d\n", lfsck_lfsck2name(lfsck),
6436                        lr->lr_event, lr->lr_index, lr->lr_status);
6437                 break;
6438         default:
6439                 RETURN(-EINVAL);
6440         }
6441
6442         llst = lfsck_layout_llst_find_and_del(llsd, lr->lr_index, true);
6443         if (llst == NULL)
6444                 RETURN(0);
6445
6446         lfsck_layout_llst_put(llst);
6447         if (list_empty(&llsd->llsd_master_list))
6448                 wake_up_all(&lfsck->li_thread.t_ctl_waitq);
6449
6450         if (lr->lr_event == LE_PEER_EXIT &&
6451             (lfsck->li_bookmark_ram.lb_param & LPF_FAILOUT ||
6452              (list_empty(&llsd->llsd_master_list) &&
6453               (lr->lr_status == LS_STOPPED ||
6454                lr->lr_status == LS_CO_STOPPED)))) {
6455                 struct lfsck_stop *stop = &lfsck_env_info(env)->lti_stop;
6456
6457                 memset(stop, 0, sizeof(*stop));
6458                 stop->ls_status = lr->lr_status;
6459                 stop->ls_flags = lr->lr_param & ~LPF_BROADCAST;
6460                 lfsck_stop(env, lfsck->li_bottom, stop);
6461         }
6462
6463         RETURN(0);
6464 }
6465
6466 static void lfsck_layout_repaired(struct lfsck_layout *lo, __u64 *count)
6467 {
6468         int i;
6469
6470         for (i = 0; i < LLIT_MAX; i++)
6471                 *count += lo->ll_objs_repaired[i];
6472 }
6473
6474 static int lfsck_layout_query_all(const struct lu_env *env,
6475                                   struct lfsck_component *com,
6476                                   __u32 *mdts_count, __u32 *osts_count,
6477                                   __u64 *repaired)
6478 {
6479         struct lfsck_layout *lo = com->lc_file_ram;
6480         struct lfsck_tgt_descs *ltds;
6481         struct lfsck_tgt_desc *ltd;
6482         int idx;
6483         int rc;
6484         ENTRY;
6485
6486         rc = lfsck_query_all(env, com);
6487         if (rc != 0)
6488                 RETURN(rc);
6489
6490         ltds = &com->lc_lfsck->li_mdt_descs;
6491         down_read(&ltds->ltd_rw_sem);
6492         cfs_foreach_bit(ltds->ltd_tgts_bitmap, idx) {
6493                 ltd = lfsck_ltd2tgt(ltds, idx);
6494                 LASSERT(ltd != NULL);
6495
6496                 mdts_count[ltd->ltd_layout_status]++;
6497                 *repaired += ltd->ltd_layout_repaired;
6498         }
6499         up_read(&ltds->ltd_rw_sem);
6500
6501         ltds = &com->lc_lfsck->li_ost_descs;
6502         down_read(&ltds->ltd_rw_sem);
6503         cfs_foreach_bit(ltds->ltd_tgts_bitmap, idx) {
6504                 ltd = lfsck_ltd2tgt(ltds, idx);
6505                 LASSERT(ltd != NULL);
6506
6507                 osts_count[ltd->ltd_layout_status]++;
6508                 *repaired += ltd->ltd_layout_repaired;
6509         }
6510         up_read(&ltds->ltd_rw_sem);
6511
6512         down_read(&com->lc_sem);
6513         mdts_count[lo->ll_status]++;
6514         lfsck_layout_repaired(lo, repaired);
6515         up_read(&com->lc_sem);
6516
6517         RETURN(0);
6518 }
6519
6520 static int lfsck_layout_query(const struct lu_env *env,
6521                               struct lfsck_component *com,
6522                               struct lfsck_request *req,
6523                               struct lfsck_reply *rep,
6524                               struct lfsck_query *que, int idx)
6525 {
6526         struct lfsck_layout *lo = com->lc_file_ram;
6527         int rc = 0;
6528
6529         if (que != NULL) {
6530                 LASSERT(com->lc_lfsck->li_master);
6531
6532                 rc = lfsck_layout_query_all(env, com,
6533                                             que->lu_mdts_count[idx],
6534                                             que->lu_osts_count[idx],
6535                                             &que->lu_repaired[idx]);
6536         } else {
6537                 down_read(&com->lc_sem);
6538                 rep->lr_status = lo->ll_status;
6539                 if (req->lr_flags & LEF_QUERY_ALL)
6540                         lfsck_layout_repaired(lo, &rep->lr_repaired);
6541                 up_read(&com->lc_sem);
6542         }
6543
6544         return rc;
6545 }
6546
6547 /* with lfsck::li_lock held */
6548 static int lfsck_layout_slave_join(const struct lu_env *env,
6549                                    struct lfsck_component *com,
6550                                    struct lfsck_start_param *lsp)
6551 {
6552         struct lfsck_instance            *lfsck = com->lc_lfsck;
6553         struct lfsck_layout_slave_data   *llsd  = com->lc_data;
6554         struct lfsck_layout_slave_target *llst;
6555         struct lfsck_start               *start = lsp->lsp_start;
6556         int                               rc    = 0;
6557         ENTRY;
6558
6559         if (start == NULL || !(start->ls_flags & LPF_OST_ORPHAN))
6560                 RETURN(0);
6561
6562         if (!lsp->lsp_index_valid)
6563                 RETURN(-EINVAL);
6564
6565         /* If someone is running the LFSCK without orphan handling,
6566          * it will not maintain the object accessing rbtree. So we
6567          * cannot join it for orphan handling. */
6568         if (!llsd->llsd_rbtree_valid)
6569                 RETURN(-EBUSY);
6570
6571         spin_unlock(&lfsck->li_lock);
6572         rc = lfsck_layout_llst_add(llsd, lsp->lsp_index);
6573         spin_lock(&lfsck->li_lock);
6574         if (rc == 0 && !thread_is_running(&lfsck->li_thread)) {
6575                 spin_unlock(&lfsck->li_lock);
6576                 llst = lfsck_layout_llst_find_and_del(llsd, lsp->lsp_index,
6577                                                       true);
6578                 if (llst != NULL)
6579                         lfsck_layout_llst_put(llst);
6580                 spin_lock(&lfsck->li_lock);
6581                 rc = -EAGAIN;
6582         }
6583
6584         RETURN(rc);
6585 }
6586
6587 static struct lfsck_operations lfsck_layout_master_ops = {
6588         .lfsck_reset            = lfsck_layout_reset,
6589         .lfsck_fail             = lfsck_layout_fail,
6590         .lfsck_checkpoint       = lfsck_layout_master_checkpoint,
6591         .lfsck_prep             = lfsck_layout_master_prep,
6592         .lfsck_exec_oit         = lfsck_layout_master_exec_oit,
6593         .lfsck_exec_dir         = lfsck_layout_exec_dir,
6594         .lfsck_post             = lfsck_layout_master_post,
6595         .lfsck_dump             = lfsck_layout_dump,
6596         .lfsck_double_scan      = lfsck_layout_master_double_scan,
6597         .lfsck_data_release     = lfsck_layout_master_data_release,
6598         .lfsck_quit             = lfsck_layout_master_quit,
6599         .lfsck_in_notify        = lfsck_layout_master_in_notify,
6600         .lfsck_query            = lfsck_layout_query,
6601 };
6602
6603 static struct lfsck_operations lfsck_layout_slave_ops = {
6604         .lfsck_reset            = lfsck_layout_reset,
6605         .lfsck_fail             = lfsck_layout_fail,
6606         .lfsck_checkpoint       = lfsck_layout_slave_checkpoint,
6607         .lfsck_prep             = lfsck_layout_slave_prep,
6608         .lfsck_exec_oit         = lfsck_layout_slave_exec_oit,
6609         .lfsck_exec_dir         = lfsck_layout_exec_dir,
6610         .lfsck_post             = lfsck_layout_slave_post,
6611         .lfsck_dump             = lfsck_layout_dump,
6612         .lfsck_double_scan      = lfsck_layout_slave_double_scan,
6613         .lfsck_data_release     = lfsck_layout_slave_data_release,
6614         .lfsck_quit             = lfsck_layout_slave_quit,
6615         .lfsck_in_notify_local  = lfsck_layout_slave_in_notify_local,
6616         .lfsck_in_notify        = lfsck_layout_slave_in_notify,
6617         .lfsck_query            = lfsck_layout_query,
6618         .lfsck_join             = lfsck_layout_slave_join,
6619 };
6620
6621 static void lfsck_layout_assistant_fill_pos(const struct lu_env *env,
6622                                             struct lfsck_component *com,
6623                                             struct lfsck_position *pos)
6624 {
6625         struct lfsck_assistant_data     *lad = com->lc_data;
6626         struct lfsck_layout_req         *llr;
6627
6628         if (((struct lfsck_layout *)(com->lc_file_ram))->ll_status !=
6629             LS_SCANNING_PHASE1)
6630                 return;
6631
6632         if (list_empty(&lad->lad_req_list))
6633                 return;
6634
6635         llr = list_entry(lad->lad_req_list.next,
6636                          struct lfsck_layout_req,
6637                          llr_lar.lar_list);
6638         pos->lp_oit_cookie = llr->llr_lar.lar_parent->lso_oit_cookie - 1;
6639 }
6640
6641 struct lfsck_assistant_operations lfsck_layout_assistant_ops = {
6642         .la_handler_p1          = lfsck_layout_assistant_handler_p1,
6643         .la_handler_p2          = lfsck_layout_assistant_handler_p2,
6644         .la_fill_pos            = lfsck_layout_assistant_fill_pos,
6645         .la_double_scan_result  = lfsck_layout_double_scan_result,
6646         .la_req_fini            = lfsck_layout_assistant_req_fini,
6647         .la_sync_failures       = lfsck_layout_assistant_sync_failures,
6648 };
6649
6650 int lfsck_layout_setup(const struct lu_env *env, struct lfsck_instance *lfsck)
6651 {
6652         struct lfsck_component  *com;
6653         struct lfsck_layout     *lo;
6654         struct dt_object        *root = NULL;
6655         struct dt_object        *obj;
6656         int                      i;
6657         int                      rc;
6658         ENTRY;
6659
6660         OBD_ALLOC_PTR(com);
6661         if (com == NULL)
6662                 RETURN(-ENOMEM);
6663
6664         INIT_LIST_HEAD(&com->lc_link);
6665         INIT_LIST_HEAD(&com->lc_link_dir);
6666         init_rwsem(&com->lc_sem);
6667         atomic_set(&com->lc_ref, 1);
6668         com->lc_lfsck = lfsck;
6669         com->lc_type = LFSCK_TYPE_LAYOUT;
6670         if (lfsck->li_master) {
6671                 com->lc_ops = &lfsck_layout_master_ops;
6672                 com->lc_data = lfsck_assistant_data_init(
6673                                 &lfsck_layout_assistant_ops,
6674                                 LFSCK_LAYOUT);
6675                 if (com->lc_data == NULL)
6676                         GOTO(out, rc = -ENOMEM);
6677
6678                 for (i = 0; i < LFSCK_STF_COUNT; i++)
6679                         mutex_init(&com->lc_sub_trace_objs[i].lsto_mutex);
6680         } else {
6681                 struct lfsck_layout_slave_data *llsd;
6682
6683                 com->lc_ops = &lfsck_layout_slave_ops;
6684                 OBD_ALLOC_PTR(llsd);
6685                 if (llsd == NULL)
6686                         GOTO(out, rc = -ENOMEM);
6687
6688                 INIT_LIST_HEAD(&llsd->llsd_seq_list);
6689                 INIT_LIST_HEAD(&llsd->llsd_master_list);
6690                 spin_lock_init(&llsd->llsd_lock);
6691                 llsd->llsd_rb_root = RB_ROOT;
6692                 rwlock_init(&llsd->llsd_rb_lock);
6693                 com->lc_data = llsd;
6694         }
6695         com->lc_file_size = sizeof(*lo);
6696         OBD_ALLOC(com->lc_file_ram, com->lc_file_size);
6697         if (com->lc_file_ram == NULL)
6698                 GOTO(out, rc = -ENOMEM);
6699
6700         OBD_ALLOC(com->lc_file_disk, com->lc_file_size);
6701         if (com->lc_file_disk == NULL)
6702                 GOTO(out, rc = -ENOMEM);
6703
6704         root = dt_locate(env, lfsck->li_bottom, &lfsck->li_local_root_fid);
6705         if (IS_ERR(root))
6706                 GOTO(out, rc = PTR_ERR(root));
6707
6708         if (unlikely(!dt_try_as_dir(env, root)))
6709                 GOTO(out, rc = -ENOTDIR);
6710
6711         obj = local_file_find_or_create(env, lfsck->li_los, root,
6712                                         LFSCK_LAYOUT,
6713                                         S_IFREG | S_IRUGO | S_IWUSR);
6714         if (IS_ERR(obj))
6715                 GOTO(out, rc = PTR_ERR(obj));
6716
6717         com->lc_obj = obj;
6718         rc = lfsck_layout_load(env, com);
6719         if (rc > 0)
6720                 rc = lfsck_layout_reset(env, com, true);
6721         else if (rc == -ENOENT)
6722                 rc = lfsck_layout_init(env, com);
6723         else if (lfsck->li_master)
6724                 rc = lfsck_load_sub_trace_files(env, com,
6725                                 &dt_lfsck_layout_dangling_features,
6726                                 LFSCK_LAYOUT, false);
6727
6728         if (rc != 0)
6729                 GOTO(out, rc);
6730
6731         lo = com->lc_file_ram;
6732         switch (lo->ll_status) {
6733         case LS_INIT:
6734         case LS_COMPLETED:
6735         case LS_FAILED:
6736         case LS_STOPPED:
6737         case LS_PARTIAL:
6738                 spin_lock(&lfsck->li_lock);
6739                 list_add_tail(&com->lc_link, &lfsck->li_list_idle);
6740                 spin_unlock(&lfsck->li_lock);
6741                 break;
6742         default:
6743                 CERROR("%s: unknown lfsck_layout status %d\n",
6744                        lfsck_lfsck2name(lfsck), lo->ll_status);
6745                 /* fall through */
6746         case LS_SCANNING_PHASE1:
6747         case LS_SCANNING_PHASE2:
6748                 /* No need to store the status to disk right now.
6749                  * If the system crashed before the status stored,
6750                  * it will be loaded back when next time. */
6751                 lo->ll_status = LS_CRASHED;
6752                 if (!lfsck->li_master)
6753                         lo->ll_flags |= LF_INCOMPLETE;
6754                 /* fall through */
6755         case LS_PAUSED:
6756         case LS_CRASHED:
6757         case LS_CO_FAILED:
6758         case LS_CO_STOPPED:
6759         case LS_CO_PAUSED:
6760                 spin_lock(&lfsck->li_lock);
6761                 list_add_tail(&com->lc_link, &lfsck->li_list_scan);
6762                 spin_unlock(&lfsck->li_lock);
6763                 break;
6764         }
6765
6766         if (lo->ll_flags & LF_CRASHED_LASTID) {
6767                 LASSERT(lfsck->li_out_notify != NULL);
6768
6769                 lfsck->li_out_notify(env, lfsck->li_out_notify_data,
6770                                      LE_LASTID_REBUILDING);
6771         }
6772
6773         GOTO(out, rc = 0);
6774
6775 out:
6776         if (root != NULL && !IS_ERR(root))
6777                 lfsck_object_put(env, root);
6778
6779         if (rc != 0) {
6780                 lfsck_component_cleanup(env, com);
6781                 CERROR("%s: fail to init layout LFSCK component: rc = %d\n",
6782                        lfsck_lfsck2name(lfsck), rc);
6783         }
6784
6785         return rc;
6786 }
6787
6788 struct lfsck_orphan_it {
6789         struct lfsck_component           *loi_com;
6790         struct lfsck_rbtree_node         *loi_lrn;
6791         struct lfsck_layout_slave_target *loi_llst;
6792         struct lu_fid                     loi_key;
6793         struct lu_orphan_rec_v2           loi_rec;
6794         __u64                             loi_hash;
6795         unsigned int                      loi_over:1;
6796 };
6797
6798 static int lfsck_fid_match_idx(const struct lu_env *env,
6799                                struct lfsck_instance *lfsck,
6800                                const struct lu_fid *fid, int idx)
6801 {
6802         struct seq_server_site  *ss;
6803         struct lu_server_fld    *sf;
6804         struct lu_seq_range     *range = &lfsck_env_info(env)->lti_range;
6805         int                      rc;
6806
6807         /* All abnormal cases will be returned to MDT0. */
6808         if (!fid_is_norm(fid)) {
6809                 if (idx == 0)
6810                         return 1;
6811
6812                 return 0;
6813         }
6814
6815         ss = lfsck_dev_site(lfsck);
6816         if (unlikely(ss == NULL))
6817                 return -ENOTCONN;
6818
6819         sf = ss->ss_server_fld;
6820         LASSERT(sf != NULL);
6821
6822         fld_range_set_any(range);
6823         rc = fld_server_lookup(env, sf, fid_seq(fid), range);
6824         if (rc != 0)
6825                 return rc;
6826
6827         if (!fld_range_is_mdt(range))
6828                 return -EINVAL;
6829
6830         if (range->lsr_index == idx)
6831                 return 1;
6832
6833         return 0;
6834 }
6835
6836 static void lfsck_layout_destroy_orphan(const struct lu_env *env,
6837                                         struct dt_object *obj)
6838 {
6839         struct dt_device        *dev    = lfsck_obj2dev(obj);
6840         struct thandle          *handle;
6841         int                      rc;
6842         ENTRY;
6843
6844         handle = dt_trans_create(env, dev);
6845         if (IS_ERR(handle))
6846                 RETURN_EXIT;
6847
6848         rc = dt_declare_ref_del(env, obj, handle);
6849         if (rc != 0)
6850                 GOTO(stop, rc);
6851
6852         rc = dt_declare_destroy(env, obj, handle);
6853         if (rc != 0)
6854                 GOTO(stop, rc);
6855
6856         rc = dt_trans_start_local(env, dev, handle);
6857         if (rc != 0)
6858                 GOTO(stop, rc);
6859
6860         dt_write_lock(env, obj, 0);
6861         rc = dt_ref_del(env, obj, handle);
6862         if (rc == 0)
6863                 rc = dt_destroy(env, obj, handle);
6864         dt_write_unlock(env, obj);
6865
6866         GOTO(stop, rc);
6867
6868 stop:
6869         dt_trans_stop(env, dev, handle);
6870
6871         CDEBUG(D_LFSCK, "destroy orphan OST-object "DFID": rc = %d\n",
6872                PFID(lfsck_dto2fid(obj)), rc);
6873
6874         RETURN_EXIT;
6875 }
6876
6877 static int lfsck_orphan_index_lookup(const struct lu_env *env,
6878                                      struct dt_object *dt,
6879                                      struct dt_rec *rec,
6880                                      const struct dt_key *key)
6881 {
6882         return -EOPNOTSUPP;
6883 }
6884
6885 static int lfsck_orphan_index_declare_insert(const struct lu_env *env,
6886                                              struct dt_object *dt,
6887                                              const struct dt_rec *rec,
6888                                              const struct dt_key *key,
6889                                              struct thandle *handle)
6890 {
6891         return -EOPNOTSUPP;
6892 }
6893
6894 static int lfsck_orphan_index_insert(const struct lu_env *env,
6895                                      struct dt_object *dt,
6896                                      const struct dt_rec *rec,
6897                                      const struct dt_key *key,
6898                                      struct thandle *handle,
6899                                      int ignore_quota)
6900 {
6901         return -EOPNOTSUPP;
6902 }
6903
6904 static int lfsck_orphan_index_declare_delete(const struct lu_env *env,
6905                                              struct dt_object *dt,
6906                                              const struct dt_key *key,
6907                                              struct thandle *handle)
6908 {
6909         return -EOPNOTSUPP;
6910 }
6911
6912 static int lfsck_orphan_index_delete(const struct lu_env *env,
6913                                      struct dt_object *dt,
6914                                      const struct dt_key *key,
6915                                      struct thandle *handle)
6916 {
6917         return -EOPNOTSUPP;
6918 }
6919
6920 static struct dt_it *lfsck_orphan_it_init(const struct lu_env *env,
6921                                           struct dt_object *dt,
6922                                           __u32 attr)
6923 {
6924         struct dt_device                *dev    = lu2dt_dev(dt->do_lu.lo_dev);
6925         struct lfsck_instance           *lfsck;
6926         struct lfsck_component          *com    = NULL;
6927         struct lfsck_layout_slave_data  *llsd;
6928         struct lfsck_orphan_it          *it     = NULL;
6929         struct lfsck_layout             *lo;
6930         int                              rc     = 0;
6931         ENTRY;
6932
6933         lfsck = lfsck_instance_find(dev, true, false);
6934         if (unlikely(lfsck == NULL))
6935                 RETURN(ERR_PTR(-ENXIO));
6936
6937         com = lfsck_component_find(lfsck, LFSCK_TYPE_LAYOUT);
6938         if (unlikely(com == NULL))
6939                 GOTO(out, rc = -ENOENT);
6940
6941         lo = com->lc_file_ram;
6942         if (lo->ll_flags & LF_INCOMPLETE)
6943                 GOTO(out, rc = -ESRCH);
6944
6945         llsd = com->lc_data;
6946         if (!llsd->llsd_rbtree_valid)
6947                 GOTO(out, rc = -ESRCH);
6948
6949         OBD_ALLOC_PTR(it);
6950         if (it == NULL)
6951                 GOTO(out, rc = -ENOMEM);
6952
6953         it->loi_llst = lfsck_layout_llst_find_and_del(llsd, attr, false);
6954         if (it->loi_llst == NULL)
6955                 GOTO(out, rc = -ENXIO);
6956
6957         if (dev->dd_record_fid_accessed) {
6958                 /* The first iteration against the rbtree, scan the whole rbtree
6959                  * to remove the nodes which do NOT need to be handled. */
6960                 write_lock(&llsd->llsd_rb_lock);
6961                 if (dev->dd_record_fid_accessed) {
6962                         struct rb_node                  *node;
6963                         struct rb_node                  *next;
6964                         struct lfsck_rbtree_node        *lrn;
6965
6966                         /* No need to record the fid accessing anymore. */
6967                         dev->dd_record_fid_accessed = 0;
6968
6969                         node = rb_first(&llsd->llsd_rb_root);
6970                         while (node != NULL) {
6971                                 next = rb_next(node);
6972                                 lrn = rb_entry(node, struct lfsck_rbtree_node,
6973                                                lrn_node);
6974                                 if (atomic_read(&lrn->lrn_known_count) <=
6975                                     atomic_read(&lrn->lrn_accessed_count)) {
6976                                         rb_erase(node, &llsd->llsd_rb_root);
6977                                         lfsck_rbtree_free(lrn);
6978                                 }
6979                                 node = next;
6980                         }
6981                 }
6982                 write_unlock(&llsd->llsd_rb_lock);
6983         }
6984
6985         /* read lock the rbtree when init, and unlock when fini */
6986         read_lock(&llsd->llsd_rb_lock);
6987         it->loi_com = com;
6988         com = NULL;
6989
6990         GOTO(out, rc = 0);
6991
6992 out:
6993         if (com != NULL)
6994                 lfsck_component_put(env, com);
6995
6996         CDEBUG(D_LFSCK, "%s: init the orphan iteration: rc = %d\n",
6997                lfsck_lfsck2name(lfsck), rc);
6998
6999         lfsck_instance_put(env, lfsck);
7000         if (rc != 0) {
7001                 if (it != NULL)
7002                         OBD_FREE_PTR(it);
7003
7004                 it = (struct lfsck_orphan_it *)ERR_PTR(rc);
7005         }
7006
7007         return (struct dt_it *)it;
7008 }
7009
7010 static void lfsck_orphan_it_fini(const struct lu_env *env,
7011                                  struct dt_it *di)
7012 {
7013         struct lfsck_orphan_it           *it    = (struct lfsck_orphan_it *)di;
7014         struct lfsck_component           *com   = it->loi_com;
7015         struct lfsck_layout_slave_data   *llsd;
7016         struct lfsck_layout_slave_target *llst;
7017
7018         if (com != NULL) {
7019                 CDEBUG(D_LFSCK, "%s: fini the orphan iteration\n",
7020                        lfsck_lfsck2name(com->lc_lfsck));
7021
7022                 llsd = com->lc_data;
7023                 read_unlock(&llsd->llsd_rb_lock);
7024                 llst = it->loi_llst;
7025                 LASSERT(llst != NULL);
7026
7027                 /* Save the key and hash for iterate next. */
7028                 llst->llst_fid = it->loi_key;
7029                 llst->llst_hash = it->loi_hash;
7030                 lfsck_layout_llst_put(llst);
7031                 lfsck_component_put(env, com);
7032         }
7033         OBD_FREE_PTR(it);
7034 }
7035
7036 /**
7037  * \retval       +1: the iteration finished
7038  * \retval        0: on success, not finished
7039  * \retval      -ve: on error
7040  */
7041 static int lfsck_orphan_it_next(const struct lu_env *env,
7042                                 struct dt_it *di)
7043 {
7044         struct lfsck_thread_info        *info   = lfsck_env_info(env);
7045         struct filter_fid               *ff     = &info->lti_ff;
7046         struct lu_attr                  *la     = &info->lti_la;
7047         struct lfsck_orphan_it          *it     = (struct lfsck_orphan_it *)di;
7048         struct lu_fid                   *key    = &it->loi_key;
7049         struct lu_orphan_rec_v2         *rec    = &it->loi_rec;
7050         struct ost_layout               *ol     = &rec->lor_layout;
7051         struct lfsck_component          *com    = it->loi_com;
7052         struct lfsck_instance           *lfsck  = com->lc_lfsck;
7053         struct lfsck_layout_slave_data  *llsd   = com->lc_data;
7054         struct dt_object                *obj;
7055         struct lfsck_rbtree_node        *lrn;
7056         int                              pos;
7057         int                              rc;
7058         __u32                            save;
7059         __u32                            idx    = it->loi_llst->llst_index;
7060         bool                             exact  = false;
7061         ENTRY;
7062
7063         if (it->loi_over)
7064                 RETURN(1);
7065
7066 again0:
7067         lrn = it->loi_lrn;
7068         if (lrn == NULL) {
7069                 lrn = lfsck_rbtree_search(llsd, key, &exact);
7070                 if (lrn == NULL) {
7071                         it->loi_over = 1;
7072                         RETURN(1);
7073                 }
7074
7075                 it->loi_lrn = lrn;
7076                 if (!exact) {
7077                         key->f_seq = lrn->lrn_seq;
7078                         key->f_oid = lrn->lrn_first_oid;
7079                         key->f_ver = 0;
7080                 }
7081         } else {
7082                 key->f_oid++;
7083                 if (unlikely(key->f_oid == 0)) {
7084                         key->f_seq++;
7085                         it->loi_lrn = NULL;
7086                         goto again0;
7087                 }
7088
7089                 if (key->f_oid >=
7090                     lrn->lrn_first_oid + LFSCK_RBTREE_BITMAP_WIDTH) {
7091                         it->loi_lrn = NULL;
7092                         goto again0;
7093                 }
7094         }
7095
7096         if (unlikely(atomic_read(&lrn->lrn_known_count) <=
7097                      atomic_read(&lrn->lrn_accessed_count))) {
7098                 struct rb_node *next = rb_next(&lrn->lrn_node);
7099
7100                 while (next != NULL) {
7101                         lrn = rb_entry(next, struct lfsck_rbtree_node,
7102                                        lrn_node);
7103                         if (atomic_read(&lrn->lrn_known_count) >
7104                             atomic_read(&lrn->lrn_accessed_count))
7105                                 break;
7106                         next = rb_next(next);
7107                 }
7108
7109                 if (next == NULL) {
7110                         it->loi_over = 1;
7111                         RETURN(1);
7112                 }
7113
7114                 it->loi_lrn = lrn;
7115                 key->f_seq = lrn->lrn_seq;
7116                 key->f_oid = lrn->lrn_first_oid;
7117                 key->f_ver = 0;
7118         }
7119
7120         pos = key->f_oid - lrn->lrn_first_oid;
7121
7122 again1:
7123         pos = find_next_bit(lrn->lrn_known_bitmap,
7124                             LFSCK_RBTREE_BITMAP_WIDTH, pos);
7125         if (pos >= LFSCK_RBTREE_BITMAP_WIDTH) {
7126                 key->f_oid = lrn->lrn_first_oid + pos;
7127                 if (unlikely(key->f_oid < lrn->lrn_first_oid)) {
7128                         key->f_seq++;
7129                         key->f_oid = 0;
7130                 }
7131                 it->loi_lrn = NULL;
7132                 goto again0;
7133         }
7134
7135         if (test_bit(pos, lrn->lrn_accessed_bitmap)) {
7136                 pos++;
7137                 goto again1;
7138         }
7139
7140         key->f_oid = lrn->lrn_first_oid + pos;
7141         obj = lfsck_object_find_bottom(env, lfsck, key);
7142         if (IS_ERR(obj)) {
7143                 rc = PTR_ERR(obj);
7144                 if (rc == -ENOENT) {
7145                         pos++;
7146                         goto again1;
7147                 }
7148                 RETURN(rc);
7149         }
7150
7151         dt_read_lock(env, obj, 0);
7152         if (dt_object_exists(obj) == 0 ||
7153             lfsck_is_dead_obj(obj)) {
7154                 dt_read_unlock(env, obj);
7155                 lfsck_object_put(env, obj);
7156                 pos++;
7157                 goto again1;
7158         }
7159
7160         rc = dt_attr_get(env, obj, la);
7161         if (rc != 0)
7162                 GOTO(out, rc);
7163
7164         rc = dt_xattr_get(env, obj, lfsck_buf_get(env, ff, sizeof(*ff)),
7165                           XATTR_NAME_FID);
7166         if (rc == -ENODATA) {
7167                 /* For the pre-created OST-object, update the bitmap to avoid
7168                  * others LFSCK (second phase) iteration to touch it again. */
7169                 if (la->la_ctime == 0) {
7170                         if (!test_and_set_bit(pos, lrn->lrn_accessed_bitmap))
7171                                 atomic_inc(&lrn->lrn_accessed_count);
7172
7173                         /* For the race between repairing dangling referenced
7174                          * MDT-object and unlink the file, it may left orphan
7175                          * OST-object there. Destroy it now! */
7176                         if (unlikely(!(la->la_mode & S_ISUID))) {
7177                                 dt_read_unlock(env, obj);
7178                                 lfsck_layout_destroy_orphan(env, obj);
7179                                 lfsck_object_put(env, obj);
7180                                 pos++;
7181                                 goto again1;
7182                         }
7183                 } else if (idx == 0) {
7184                         /* If the orphan OST-object has no parent information,
7185                          * regard it as referenced by the MDT-object on MDT0. */
7186                         fid_zero(&rec->lor_rec.lor_fid);
7187                         rec->lor_rec.lor_uid = la->la_uid;
7188                         rec->lor_rec.lor_gid = la->la_gid;
7189                         memset(ol, 0, sizeof(*ol));
7190
7191                         GOTO(out, rc = 0);
7192                 }
7193
7194                 dt_read_unlock(env, obj);
7195                 lfsck_object_put(env, obj);
7196                 pos++;
7197                 goto again1;
7198         }
7199
7200         if (rc < sizeof(struct lu_fid))
7201                 GOTO(out, rc = (rc < 0 ? rc : -EINVAL));
7202
7203         fid_le_to_cpu(&rec->lor_rec.lor_fid, &ff->ff_parent);
7204         /* Currently, the filter_fid::ff_parent::f_ver is not the real parent
7205          * MDT-object's FID::f_ver, instead it is the OST-object index in its
7206          * parent MDT-object's layout EA. */
7207         save = rec->lor_rec.lor_fid.f_stripe_idx;
7208         rec->lor_rec.lor_fid.f_ver = 0;
7209         rc = lfsck_fid_match_idx(env, lfsck, &rec->lor_rec.lor_fid, idx);
7210         /* If the orphan OST-object does not claim the MDT, then next.
7211          *
7212          * If we do not know whether it matches or not, then return it
7213          * to the MDT for further check. */
7214         if (rc == 0) {
7215                 dt_read_unlock(env, obj);
7216                 lfsck_object_put(env, obj);
7217                 pos++;
7218                 goto again1;
7219         }
7220
7221         rec->lor_rec.lor_fid.f_stripe_idx = save;
7222         rec->lor_rec.lor_uid = la->la_uid;
7223         rec->lor_rec.lor_gid = la->la_gid;
7224         ost_layout_le_to_cpu(ol, &ff->ff_layout);
7225
7226         CDEBUG(D_LFSCK, "%s: return orphan "DFID", PFID "DFID", owner %u:%u, "
7227                "stripe size %u, stripe count %u, COMP id %u, COMP start %llu, "
7228                "COMP end %llu\n", lfsck_lfsck2name(com->lc_lfsck), PFID(key),
7229                PFID(&rec->lor_rec.lor_fid), rec->lor_rec.lor_uid,
7230                rec->lor_rec.lor_gid, ol->ol_stripe_size, ol->ol_stripe_count,
7231                ol->ol_comp_id, ol->ol_comp_start, ol->ol_comp_end);
7232
7233         GOTO(out, rc = 0);
7234
7235 out:
7236         dt_read_unlock(env, obj);
7237         lfsck_object_put(env, obj);
7238         if (rc == 0)
7239                 it->loi_hash++;
7240
7241         return rc;
7242 }
7243
7244 /**
7245  * \retval       +1: locate to the exactly position
7246  * \retval        0: cannot locate to the exactly position,
7247  *                   call next() to move to a valid position.
7248  * \retval      -ve: on error
7249  */
7250 static int lfsck_orphan_it_get(const struct lu_env *env,
7251                                struct dt_it *di,
7252                                const struct dt_key *key)
7253 {
7254         struct lfsck_orphan_it  *it   = (struct lfsck_orphan_it *)di;
7255         int                      rc;
7256
7257         it->loi_key = *(struct lu_fid *)key;
7258         rc = lfsck_orphan_it_next(env, di);
7259         if (rc == 1)
7260                 return 0;
7261
7262         if (rc == 0)
7263                 return 1;
7264
7265         return rc;
7266 }
7267
7268 static void lfsck_orphan_it_put(const struct lu_env *env,
7269                                 struct dt_it *di)
7270 {
7271 }
7272
7273 static struct dt_key *lfsck_orphan_it_key(const struct lu_env *env,
7274                                           const struct dt_it *di)
7275 {
7276         struct lfsck_orphan_it *it = (struct lfsck_orphan_it *)di;
7277
7278         return (struct dt_key *)&it->loi_key;
7279 }
7280
7281 static int lfsck_orphan_it_key_size(const struct lu_env *env,
7282                                     const struct dt_it *di)
7283 {
7284         return sizeof(struct lu_fid);
7285 }
7286
7287 static int lfsck_orphan_it_rec(const struct lu_env *env,
7288                                const struct dt_it *di,
7289                                struct dt_rec *rec,
7290                                __u32 attr)
7291 {
7292         struct lfsck_orphan_it *it = (struct lfsck_orphan_it *)di;
7293
7294         *(struct lu_orphan_rec_v2 *)rec = it->loi_rec;
7295
7296         return 0;
7297 }
7298
7299 static __u64 lfsck_orphan_it_store(const struct lu_env *env,
7300                                    const struct dt_it *di)
7301 {
7302         struct lfsck_orphan_it  *it   = (struct lfsck_orphan_it *)di;
7303
7304         return it->loi_hash;
7305 }
7306
7307 /**
7308  * \retval       +1: locate to the exactly position
7309  * \retval        0: cannot locate to the exactly position,
7310  *                   call next() to move to a valid position.
7311  * \retval      -ve: on error
7312  */
7313 static int lfsck_orphan_it_load(const struct lu_env *env,
7314                                 const struct dt_it *di,
7315                                 __u64 hash)
7316 {
7317         struct lfsck_orphan_it           *it   = (struct lfsck_orphan_it *)di;
7318         struct lfsck_layout_slave_target *llst = it->loi_llst;
7319         int                               rc;
7320
7321         LASSERT(llst != NULL);
7322
7323         if (hash != llst->llst_hash) {
7324                 CDEBUG(D_LFSCK, "%s: the given hash %llu for orphan "
7325                        "iteration does not match the one when fini "
7326                        "%llu, to be reset.\n",
7327                        lfsck_lfsck2name(it->loi_com->lc_lfsck), hash,
7328                        llst->llst_hash);
7329                 fid_zero(&llst->llst_fid);
7330                 llst->llst_hash = 0;
7331         }
7332
7333         it->loi_key = llst->llst_fid;
7334         it->loi_hash = llst->llst_hash;
7335         rc = lfsck_orphan_it_next(env, (struct dt_it *)di);
7336         if (rc == 1)
7337                 return 0;
7338
7339         if (rc == 0)
7340                 return 1;
7341
7342         return rc;
7343 }
7344
7345 static int lfsck_orphan_it_key_rec(const struct lu_env *env,
7346                                    const struct dt_it *di,
7347                                    void *key_rec)
7348 {
7349         return 0;
7350 }
7351
7352 const struct dt_index_operations lfsck_orphan_index_ops = {
7353         .dio_lookup             = lfsck_orphan_index_lookup,
7354         .dio_declare_insert     = lfsck_orphan_index_declare_insert,
7355         .dio_insert             = lfsck_orphan_index_insert,
7356         .dio_declare_delete     = lfsck_orphan_index_declare_delete,
7357         .dio_delete             = lfsck_orphan_index_delete,
7358         .dio_it = {
7359                 .init           = lfsck_orphan_it_init,
7360                 .fini           = lfsck_orphan_it_fini,
7361                 .get            = lfsck_orphan_it_get,
7362                 .put            = lfsck_orphan_it_put,
7363                 .next           = lfsck_orphan_it_next,
7364                 .key            = lfsck_orphan_it_key,
7365                 .key_size       = lfsck_orphan_it_key_size,
7366                 .rec            = lfsck_orphan_it_rec,
7367                 .store          = lfsck_orphan_it_store,
7368                 .load           = lfsck_orphan_it_load,
7369                 .key_rec        = lfsck_orphan_it_key_rec,
7370         }
7371 };