Whamcloud - gitweb
c44530340d0360b55bd1ac28fc37b58028bcb714
[fs/lustre-release.git] / lustre / lfsck / lfsck_layout.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License version 2 for more details.  A copy is
14  * included in the COPYING file that accompanied this code.
15
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2014, 2016, Intel Corporation.
24  */
25 /*
26  * lustre/lfsck/lfsck_layout.c
27  *
28  * Author: Fan, Yong <fan.yong@intel.com>
29  */
30
31 #ifndef EXPORT_SYMTAB
32 # define EXPORT_SYMTAB
33 #endif
34 #define DEBUG_SUBSYSTEM S_LFSCK
35
36 #include <linux/bitops.h>
37 #include <linux/rbtree.h>
38
39 #include <lustre/lustre_idl.h>
40 #include <lu_object.h>
41 #include <dt_object.h>
42 #include <lustre_fid.h>
43 #include <lustre_lib.h>
44 #include <lustre_net.h>
45 #include <lustre/lustre_user.h>
46 #include <md_object.h>
47 #include <obd_class.h>
48
49 #include "lfsck_internal.h"
50
51 #define LFSCK_LAYOUT_MAGIC_V1           0xB173AE14
52 #define LFSCK_LAYOUT_MAGIC_V2           0xB1734D76
53 #define LFSCK_LAYOUT_MAGIC_V3           0xB17371B9
54
55 #define LFSCK_LAYOUT_MAGIC              LFSCK_LAYOUT_MAGIC_V3
56
57 struct lfsck_layout_seq {
58         struct list_head         lls_list;
59         __u64                    lls_seq;
60         __u64                    lls_lastid;
61         __u64                    lls_lastid_known;
62         struct dt_object        *lls_lastid_obj;
63         unsigned int             lls_dirty:1;
64 };
65
66 struct lfsck_layout_slave_target {
67         /* link into lfsck_layout_slave_data::llsd_master_list. */
68         struct list_head        llst_list;
69         /* The position for next record in the rbtree for iteration. */
70         struct lu_fid           llst_fid;
71         /* Dummy hash for iteration against the rbtree. */
72         __u64                   llst_hash;
73         __u64                   llst_gen;
74         atomic_t                llst_ref;
75         __u32                   llst_index;
76         /* How many times we have failed to get the master status. */
77         int                     llst_failures;
78 };
79
80 struct lfsck_layout_slave_data {
81         /* list for lfsck_layout_seq */
82         struct list_head         llsd_seq_list;
83
84         /* list for the masters involve layout verification. */
85         struct list_head         llsd_master_list;
86         spinlock_t               llsd_lock;
87         __u64                    llsd_touch_gen;
88         struct dt_object        *llsd_rb_obj;
89         struct rb_root           llsd_rb_root;
90         rwlock_t                 llsd_rb_lock;
91         unsigned int             llsd_rbtree_valid:1;
92 };
93
94 struct lfsck_layout_slave_async_args {
95         struct obd_export                *llsaa_exp;
96         struct lfsck_component           *llsaa_com;
97         struct lfsck_layout_slave_target *llsaa_llst;
98 };
99
100 static inline bool lfsck_comp_extent_aligned(__u64 size)
101 {
102          return (size & (LOV_MIN_STRIPE_SIZE - 1)) == 0;
103 }
104
105 static inline void
106 lfsck_layout_llst_put(struct lfsck_layout_slave_target *llst)
107 {
108         if (atomic_dec_and_test(&llst->llst_ref)) {
109                 LASSERT(list_empty(&llst->llst_list));
110
111                 OBD_FREE_PTR(llst);
112         }
113 }
114
115 static inline int
116 lfsck_layout_llst_add(struct lfsck_layout_slave_data *llsd, __u32 index)
117 {
118         struct lfsck_layout_slave_target *llst;
119         struct lfsck_layout_slave_target *tmp;
120         int                               rc   = 0;
121
122         OBD_ALLOC_PTR(llst);
123         if (llst == NULL)
124                 return -ENOMEM;
125
126         INIT_LIST_HEAD(&llst->llst_list);
127         llst->llst_gen = 0;
128         llst->llst_index = index;
129         atomic_set(&llst->llst_ref, 1);
130
131         spin_lock(&llsd->llsd_lock);
132         list_for_each_entry(tmp, &llsd->llsd_master_list, llst_list) {
133                 if (tmp->llst_index == index) {
134                         rc = -EALREADY;
135                         break;
136                 }
137         }
138         if (rc == 0)
139                 list_add_tail(&llst->llst_list, &llsd->llsd_master_list);
140         spin_unlock(&llsd->llsd_lock);
141
142         if (rc != 0)
143                 OBD_FREE_PTR(llst);
144
145         return rc;
146 }
147
148 static inline void
149 lfsck_layout_llst_del(struct lfsck_layout_slave_data *llsd,
150                       struct lfsck_layout_slave_target *llst)
151 {
152         bool del = false;
153
154         spin_lock(&llsd->llsd_lock);
155         if (!list_empty(&llst->llst_list)) {
156                 list_del_init(&llst->llst_list);
157                 del = true;
158         }
159         spin_unlock(&llsd->llsd_lock);
160
161         if (del)
162                 lfsck_layout_llst_put(llst);
163 }
164
165 static inline struct lfsck_layout_slave_target *
166 lfsck_layout_llst_find_and_del(struct lfsck_layout_slave_data *llsd,
167                                __u32 index, bool unlink)
168 {
169         struct lfsck_layout_slave_target *llst;
170
171         spin_lock(&llsd->llsd_lock);
172         list_for_each_entry(llst, &llsd->llsd_master_list, llst_list) {
173                 if (llst->llst_index == index) {
174                         if (unlink)
175                                 list_del_init(&llst->llst_list);
176                         else
177                                 atomic_inc(&llst->llst_ref);
178                         spin_unlock(&llsd->llsd_lock);
179
180                         return llst;
181                 }
182         }
183         spin_unlock(&llsd->llsd_lock);
184
185         return NULL;
186 }
187
188 static struct lfsck_layout_req *
189 lfsck_layout_assistant_req_init(struct lfsck_assistant_object *lso,
190                                 struct dt_object *child, __u32 comp_id,
191                                 __u32 ost_idx, __u32 lov_idx)
192 {
193         struct lfsck_layout_req *llr;
194
195         OBD_ALLOC_PTR(llr);
196         if (llr == NULL)
197                 return ERR_PTR(-ENOMEM);
198
199         INIT_LIST_HEAD(&llr->llr_lar.lar_list);
200         llr->llr_lar.lar_parent = lfsck_assistant_object_get(lso);
201         llr->llr_child = child;
202         llr->llr_comp_id = comp_id;
203         llr->llr_ost_idx = ost_idx;
204         llr->llr_lov_idx = lov_idx;
205
206         return llr;
207 }
208
209 static void lfsck_layout_assistant_req_fini(const struct lu_env *env,
210                                             struct lfsck_assistant_req *lar)
211 {
212         struct lfsck_layout_req *llr =
213                         container_of0(lar, struct lfsck_layout_req, llr_lar);
214
215         lfsck_object_put(env, llr->llr_child);
216         lfsck_assistant_object_put(env, lar->lar_parent);
217         OBD_FREE_PTR(llr);
218 }
219
220 static int
221 lfsck_layout_assistant_sync_failures_interpret(const struct lu_env *env,
222                                                struct ptlrpc_request *req,
223                                                void *args, int rc)
224 {
225         if (rc == 0) {
226                 struct lfsck_async_interpret_args *laia = args;
227                 struct lfsck_tgt_desc             *ltd  = laia->laia_ltd;
228
229                 ltd->ltd_synced_failures = 1;
230                 atomic_dec(laia->laia_count);
231         }
232
233         return 0;
234 }
235
236 /**
237  * Notify remote LFSCK instances about former failures.
238  *
239  * The local LFSCK instance has recorded which OSTs have ever failed to respond
240  * some LFSCK verification requests (maybe because of network issues or the OST
241  * itself trouble). During the respond gap, the OST may missed some OST-objects
242  * verification, then the OST cannot know whether related OST-objects have been
243  * referenced by related MDT-objects or not, then in the second-stage scanning,
244  * these OST-objects will be regarded as orphan, if the OST-object contains bad
245  * parent FID for back reference, then it will misguide the LFSCK to make wrong
246  * fixing for the fake orphan.
247  *
248  * To avoid above trouble, when layout LFSCK finishes the first-stage scanning,
249  * it will scan the bitmap for the ever failed OSTs, and notify them that they
250  * have ever missed some OST-object verification and should skip the handling
251  * for orphan OST-objects on all MDTs that are in the layout LFSCK.
252  *
253  * \param[in] env       pointer to the thread context
254  * \param[in] com       pointer to the lfsck component
255  * \param[in] lr        pointer to the lfsck request
256  */
257 static void lfsck_layout_assistant_sync_failures(const struct lu_env *env,
258                                                  struct lfsck_component *com,
259                                                  struct lfsck_request *lr)
260 {
261         struct lfsck_async_interpret_args *laia  =
262                                 &lfsck_env_info(env)->lti_laia2;
263         struct lfsck_assistant_data       *lad   = com->lc_data;
264         struct lfsck_layout               *lo    = com->lc_file_ram;
265         struct lfsck_instance             *lfsck = com->lc_lfsck;
266         struct lfsck_tgt_descs            *ltds  = &lfsck->li_ost_descs;
267         struct lfsck_tgt_desc             *ltd;
268         struct ptlrpc_request_set         *set;
269         atomic_t                           count;
270         __u32                              idx;
271         int                                rc    = 0;
272         ENTRY;
273
274         if (!lad->lad_incomplete)
275                 RETURN_EXIT;
276
277         /* If the MDT has ever failed to verfiy some OST-objects,
278          * then sync failures with them firstly. */
279         lr->lr_flags2 = lo->ll_flags | LF_INCOMPLETE;
280
281         atomic_set(&count, 0);
282         memset(laia, 0, sizeof(*laia));
283         laia->laia_count = &count;
284         set = ptlrpc_prep_set();
285         if (set == NULL)
286                 GOTO(out, rc = -ENOMEM);
287
288         down_read(&ltds->ltd_rw_sem);
289         cfs_foreach_bit(lad->lad_bitmap, idx) {
290                 ltd = lfsck_ltd2tgt(ltds, idx);
291                 if (unlikely(!ltd))
292                         continue;
293
294                 laia->laia_ltd = ltd;
295                 rc = lfsck_async_request(env, ltd->ltd_exp, lr, set,
296                                 lfsck_layout_assistant_sync_failures_interpret,
297                                 laia, LFSCK_NOTIFY);
298                 if (rc != 0) {
299                         CDEBUG(D_LFSCK, "%s: LFSCK assistant fail to "
300                                "notify target %x for %s phase1 done: "
301                                "rc = %d\n", lfsck_lfsck2name(com->lc_lfsck),
302                                ltd->ltd_index, lad->lad_name, rc);
303
304                         break;
305                 }
306
307                 atomic_inc(&count);
308         }
309         up_read(&ltds->ltd_rw_sem);
310
311         if (rc == 0 && atomic_read(&count) > 0)
312                 rc = ptlrpc_set_wait(set);
313
314         ptlrpc_set_destroy(set);
315
316         if (rc == 0 && atomic_read(&count) > 0)
317                 rc = -EINVAL;
318
319         GOTO(out, rc);
320
321 out:
322         if (rc != 0)
323                 /* If failed to sync failures with the OSTs, then have to
324                  * mark the whole LFSCK as LF_INCOMPLETE to skip the whole
325                  * subsequent orphan OST-object handling. */
326                 lo->ll_flags |= LF_INCOMPLETE;
327
328         lr->lr_flags2 = lo->ll_flags;
329 }
330
331 static int lfsck_layout_verify_header_v1v3(struct dt_object *obj,
332                                            struct lov_mds_md_v1 *lmm)
333 {
334         __u32 magic;
335         __u32 pattern;
336
337         magic = le32_to_cpu(lmm->lmm_magic);
338         /* If magic crashed, keep it there. Sometime later, during OST-object
339          * orphan handling, if some OST-object(s) back-point to it, it can be
340          * verified and repaired. */
341         if (magic != LOV_MAGIC_V1 && magic != LOV_MAGIC_V3) {
342                 int rc;
343
344                 if ((magic & LOV_MAGIC_MASK) == LOV_MAGIC_MAGIC)
345                         rc = -EOPNOTSUPP;
346                 else
347                         rc = -EINVAL;
348
349                 CDEBUG(D_LFSCK, "%s LOV EA magic %u for the file "DFID"\n",
350                        rc == -EINVAL ? "Unknown" : "Unsupported",
351                        magic, PFID(lfsck_dto2fid(obj)));
352
353                 return rc;
354         }
355
356         pattern = le32_to_cpu(lmm->lmm_pattern);
357         /* XXX: currently, we only support LOV_PATTERN_RAID0. */
358         if (lov_pattern(pattern) != LOV_PATTERN_RAID0) {
359                 CDEBUG(D_LFSCK, "Unsupported LOV EA pattern %u for the file "
360                        DFID"\n", pattern, PFID(lfsck_dto2fid(obj)));
361
362                 return -EOPNOTSUPP;
363         }
364
365         return 0;
366 }
367
368 static int lfsck_layout_verify_header(struct dt_object *obj,
369                                       struct lov_mds_md_v1 *lmm)
370 {
371         int rc = 0;
372
373         if (le32_to_cpu(lmm->lmm_magic) == LOV_MAGIC_COMP_V1) {
374                 struct lov_comp_md_v1 *lcm = (struct lov_comp_md_v1 *)lmm;
375                 int i;
376                 __u16 count = le16_to_cpu(lcm->lcm_entry_count);
377
378                 if (unlikely(count == 0)) {
379                         CDEBUG(D_LFSCK, "the PFL file "DFID" contains invalid "
380                                "components count 0\n",
381                                PFID(lfsck_dto2fid(obj)));
382
383                         return -EINVAL;
384                 }
385
386                 for (i = 0; i < count; i++) {
387                         struct lov_comp_md_entry_v1 *lcme =
388                                                 &lcm->lcm_entries[i];
389                         __u64 start = le64_to_cpu(lcme->lcme_extent.e_start);
390                         __u64 end = le64_to_cpu(lcme->lcme_extent.e_end);
391                         __u32 comp_id = le32_to_cpu(lcme->lcme_id);
392
393                         if (unlikely(comp_id == LCME_ID_INVAL ||
394                                      comp_id > LCME_ID_MAX)) {
395                                 CDEBUG(D_LFSCK, "found invalid FPL ID %u "
396                                        "for the file "DFID" at idx %d\n",
397                                        comp_id, PFID(lfsck_dto2fid(obj)), i);
398
399                                 return -EINVAL;
400                         }
401
402                         if (unlikely(start >= end ||
403                                      !lfsck_comp_extent_aligned(start) ||
404                                      (!lfsck_comp_extent_aligned(end) &&
405                                       end != LUSTRE_EOF))) {
406                                 CDEBUG(D_LFSCK, "found invalid FPL extent "
407                                        "range [%llu - %llu) for the file "
408                                        DFID" at idx %d\n",
409                                        start, end, PFID(lfsck_dto2fid(obj)), i);
410
411                                 return -EINVAL;
412                         }
413
414                         rc = lfsck_layout_verify_header_v1v3(obj,
415                                 (struct lov_mds_md_v1 *)((char *)lmm +
416                                 le32_to_cpu(lcme->lcme_offset)));
417                         if (rc)
418                                 return rc;
419                 }
420         } else {
421                 rc = lfsck_layout_verify_header_v1v3(obj, lmm);
422         }
423
424         return rc;
425 }
426
427 static int lfsck_layout_get_lovea(const struct lu_env *env,
428                                   struct dt_object *obj, struct lu_buf *buf)
429 {
430         int rc;
431         int rc1;
432
433 again:
434         rc = dt_xattr_get(env, obj, buf, XATTR_NAME_LOV);
435         if (rc == -ERANGE) {
436                 rc = dt_xattr_get(env, obj, &LU_BUF_NULL, XATTR_NAME_LOV);
437                 if (rc <= 0)
438                         return rc;
439
440                 lu_buf_realloc(buf, rc);
441                 if (buf->lb_buf == NULL)
442                         return -ENOMEM;
443
444                 goto again;
445         }
446
447         if (rc == -ENODATA)
448                 rc = 0;
449
450         if (rc <= 0)
451                 return rc;
452
453         if (unlikely(buf->lb_buf == NULL)) {
454                 lu_buf_alloc(buf, rc);
455                 if (buf->lb_buf == NULL)
456                         return -ENOMEM;
457
458                 goto again;
459         }
460
461         rc1 = lfsck_layout_verify_header(obj, buf->lb_buf);
462
463         return rc1 ? rc1 : rc;
464 }
465
466 #define LFSCK_RBTREE_BITMAP_SIZE        PAGE_SIZE
467 #define LFSCK_RBTREE_BITMAP_WIDTH       (LFSCK_RBTREE_BITMAP_SIZE << 3)
468 #define LFSCK_RBTREE_BITMAP_MASK        (LFSCK_RBTREE_BITMAP_WIDTH - 1)
469
470 struct lfsck_rbtree_node {
471         struct rb_node   lrn_node;
472         __u64            lrn_seq;
473         __u32            lrn_first_oid;
474         atomic_t         lrn_known_count;
475         atomic_t         lrn_accessed_count;
476         void            *lrn_known_bitmap;
477         void            *lrn_accessed_bitmap;
478 };
479
480 static inline int lfsck_rbtree_cmp(struct lfsck_rbtree_node *lrn,
481                                    __u64 seq, __u32 oid)
482 {
483         if (seq < lrn->lrn_seq)
484                 return -1;
485
486         if (seq > lrn->lrn_seq)
487                 return 1;
488
489         if (oid < lrn->lrn_first_oid)
490                 return -1;
491
492         if (oid - lrn->lrn_first_oid >= LFSCK_RBTREE_BITMAP_WIDTH)
493                 return 1;
494
495         return 0;
496 }
497
498 /* The caller should hold llsd->llsd_rb_lock. */
499 static struct lfsck_rbtree_node *
500 lfsck_rbtree_search(struct lfsck_layout_slave_data *llsd,
501                     const struct lu_fid *fid, bool *exact)
502 {
503         struct rb_node           *node  = llsd->llsd_rb_root.rb_node;
504         struct rb_node           *prev  = NULL;
505         struct lfsck_rbtree_node *lrn   = NULL;
506         int                       rc    = 0;
507
508         if (exact != NULL)
509                 *exact = true;
510
511         while (node != NULL) {
512                 prev = node;
513                 lrn = rb_entry(node, struct lfsck_rbtree_node, lrn_node);
514                 rc = lfsck_rbtree_cmp(lrn, fid_seq(fid), fid_oid(fid));
515                 if (rc < 0)
516                         node = node->rb_left;
517                 else if (rc > 0)
518                         node = node->rb_right;
519                 else
520                         return lrn;
521         }
522
523         if (exact == NULL)
524                 return NULL;
525
526         /* If there is no exactly matched one, then to the next valid one. */
527         *exact = false;
528
529         /* The rbtree is empty. */
530         if (rc == 0)
531                 return NULL;
532
533         if (rc < 0)
534                 return lrn;
535
536         node = rb_next(prev);
537
538         /* The end of the rbtree. */
539         if (node == NULL)
540                 return NULL;
541
542         lrn = rb_entry(node, struct lfsck_rbtree_node, lrn_node);
543
544         return lrn;
545 }
546
547 static struct lfsck_rbtree_node *lfsck_rbtree_new(const struct lu_env *env,
548                                                   const struct lu_fid *fid)
549 {
550         struct lfsck_rbtree_node *lrn;
551
552         OBD_ALLOC_PTR(lrn);
553         if (lrn == NULL)
554                 return ERR_PTR(-ENOMEM);
555
556         OBD_ALLOC(lrn->lrn_known_bitmap, LFSCK_RBTREE_BITMAP_SIZE);
557         if (lrn->lrn_known_bitmap == NULL) {
558                 OBD_FREE_PTR(lrn);
559
560                 return ERR_PTR(-ENOMEM);
561         }
562
563         OBD_ALLOC(lrn->lrn_accessed_bitmap, LFSCK_RBTREE_BITMAP_SIZE);
564         if (lrn->lrn_accessed_bitmap == NULL) {
565                 OBD_FREE(lrn->lrn_known_bitmap, LFSCK_RBTREE_BITMAP_SIZE);
566                 OBD_FREE_PTR(lrn);
567
568                 return ERR_PTR(-ENOMEM);
569         }
570
571         RB_CLEAR_NODE(&lrn->lrn_node);
572         lrn->lrn_seq = fid_seq(fid);
573         lrn->lrn_first_oid = fid_oid(fid) & ~LFSCK_RBTREE_BITMAP_MASK;
574         atomic_set(&lrn->lrn_known_count, 0);
575         atomic_set(&lrn->lrn_accessed_count, 0);
576
577         return lrn;
578 }
579
580 static void lfsck_rbtree_free(struct lfsck_rbtree_node *lrn)
581 {
582         OBD_FREE(lrn->lrn_accessed_bitmap, LFSCK_RBTREE_BITMAP_SIZE);
583         OBD_FREE(lrn->lrn_known_bitmap, LFSCK_RBTREE_BITMAP_SIZE);
584         OBD_FREE_PTR(lrn);
585 }
586
587 /* The caller should hold lock. */
588 static struct lfsck_rbtree_node *
589 lfsck_rbtree_insert(struct lfsck_layout_slave_data *llsd,
590                     struct lfsck_rbtree_node *lrn)
591 {
592         struct rb_node           **pos    = &llsd->llsd_rb_root.rb_node;
593         struct rb_node            *parent = NULL;
594         struct lfsck_rbtree_node  *tmp;
595         int                        rc;
596
597         while (*pos != NULL) {
598                 parent = *pos;
599                 tmp = rb_entry(parent, struct lfsck_rbtree_node, lrn_node);
600                 rc = lfsck_rbtree_cmp(tmp, lrn->lrn_seq, lrn->lrn_first_oid);
601                 if (rc < 0)
602                         pos = &(*pos)->rb_left;
603                 else if (rc > 0)
604                         pos = &(*pos)->rb_right;
605                 else
606                         return tmp;
607         }
608
609         rb_link_node(&lrn->lrn_node, parent, pos);
610         rb_insert_color(&lrn->lrn_node, &llsd->llsd_rb_root);
611
612         return lrn;
613 }
614
615 extern const struct dt_index_operations lfsck_orphan_index_ops;
616
617 static int lfsck_rbtree_setup(const struct lu_env *env,
618                               struct lfsck_component *com)
619 {
620         struct lu_fid                   *fid    = &lfsck_env_info(env)->lti_fid;
621         struct lfsck_instance           *lfsck  = com->lc_lfsck;
622         struct dt_device                *dev    = lfsck->li_bottom;
623         struct lfsck_layout_slave_data  *llsd   = com->lc_data;
624         struct dt_object                *obj;
625
626         fid->f_seq = FID_SEQ_LAYOUT_RBTREE;
627         fid->f_oid = lfsck_dev_idx(lfsck);
628         fid->f_ver = 0;
629         obj = dt_locate(env, dev, fid);
630         if (IS_ERR(obj))
631                 RETURN(PTR_ERR(obj));
632
633         /* Generate an in-RAM object to stand for the layout rbtree.
634          * Scanning the layout rbtree will be via the iteration over
635          * the object. In the future, the rbtree may be written onto
636          * disk with the object.
637          *
638          * Mark the object to be as exist. */
639         obj->do_lu.lo_header->loh_attr |= LOHA_EXISTS;
640         obj->do_index_ops = &lfsck_orphan_index_ops;
641         llsd->llsd_rb_obj = obj;
642         llsd->llsd_rbtree_valid = 1;
643         dev->dd_record_fid_accessed = 1;
644
645         CDEBUG(D_LFSCK, "%s: layout LFSCK init OST-objects accessing bitmap\n",
646                lfsck_lfsck2name(lfsck));
647
648         return 0;
649 }
650
651 static void lfsck_rbtree_cleanup(const struct lu_env *env,
652                                  struct lfsck_component *com)
653 {
654         struct lfsck_instance           *lfsck = com->lc_lfsck;
655         struct lfsck_layout_slave_data  *llsd  = com->lc_data;
656         struct rb_node                  *node  = rb_first(&llsd->llsd_rb_root);
657         struct rb_node                  *next;
658         struct lfsck_rbtree_node        *lrn;
659
660         lfsck->li_bottom->dd_record_fid_accessed = 0;
661         /* Invalid the rbtree, then no others will use it. */
662         write_lock(&llsd->llsd_rb_lock);
663         llsd->llsd_rbtree_valid = 0;
664         write_unlock(&llsd->llsd_rb_lock);
665
666         while (node != NULL) {
667                 next = rb_next(node);
668                 lrn = rb_entry(node, struct lfsck_rbtree_node, lrn_node);
669                 rb_erase(node, &llsd->llsd_rb_root);
670                 lfsck_rbtree_free(lrn);
671                 node = next;
672         }
673
674         if (llsd->llsd_rb_obj != NULL) {
675                 lfsck_object_put(env, llsd->llsd_rb_obj);
676                 llsd->llsd_rb_obj = NULL;
677         }
678
679         CDEBUG(D_LFSCK, "%s: layout LFSCK fini OST-objects accessing bitmap\n",
680                lfsck_lfsck2name(lfsck));
681 }
682
683 static void lfsck_rbtree_update_bitmap(const struct lu_env *env,
684                                        struct lfsck_component *com,
685                                        const struct lu_fid *fid,
686                                        bool accessed)
687 {
688         struct lfsck_layout_slave_data  *llsd   = com->lc_data;
689         struct lfsck_rbtree_node        *lrn;
690         bool                             insert = false;
691         int                              idx;
692         int                              rc     = 0;
693         ENTRY;
694
695         if (unlikely(!fid_is_sane(fid) || fid_is_last_id(fid)))
696                 RETURN_EXIT;
697
698         if (!fid_is_idif(fid) && !fid_is_norm(fid))
699                 RETURN_EXIT;
700
701         read_lock(&llsd->llsd_rb_lock);
702         if (!llsd->llsd_rbtree_valid)
703                 GOTO(unlock, rc = 0);
704
705         lrn = lfsck_rbtree_search(llsd, fid, NULL);
706         if (lrn == NULL) {
707                 struct lfsck_rbtree_node *tmp;
708
709                 LASSERT(!insert);
710
711                 read_unlock(&llsd->llsd_rb_lock);
712                 tmp = lfsck_rbtree_new(env, fid);
713                 if (IS_ERR(tmp))
714                         GOTO(out, rc = PTR_ERR(tmp));
715
716                 insert = true;
717                 write_lock(&llsd->llsd_rb_lock);
718                 if (!llsd->llsd_rbtree_valid) {
719                         lfsck_rbtree_free(tmp);
720                         GOTO(unlock, rc = 0);
721                 }
722
723                 lrn = lfsck_rbtree_insert(llsd, tmp);
724                 if (lrn != tmp)
725                         lfsck_rbtree_free(tmp);
726         }
727
728         idx = fid_oid(fid) & LFSCK_RBTREE_BITMAP_MASK;
729         /* Any accessed object must be a known object. */
730         if (!test_and_set_bit(idx, lrn->lrn_known_bitmap))
731                 atomic_inc(&lrn->lrn_known_count);
732         if (accessed && !test_and_set_bit(idx, lrn->lrn_accessed_bitmap))
733                 atomic_inc(&lrn->lrn_accessed_count);
734
735         GOTO(unlock, rc = 0);
736
737 unlock:
738         if (insert)
739                 write_unlock(&llsd->llsd_rb_lock);
740         else
741                 read_unlock(&llsd->llsd_rb_lock);
742 out:
743         if (rc != 0 && accessed) {
744                 struct lfsck_layout *lo = com->lc_file_ram;
745
746                 CDEBUG(D_LFSCK, "%s: fail to update OST-objects accessing "
747                        "bitmap, and will cause incorrect LFSCK OST-object "
748                        "handling, so disable it to cancel orphan handling "
749                        "for related device. rc = %d\n",
750                        lfsck_lfsck2name(com->lc_lfsck), rc);
751
752                 lo->ll_flags |= LF_INCOMPLETE;
753                 lfsck_rbtree_cleanup(env, com);
754         }
755 }
756
757 static inline void lldk_le_to_cpu(struct lfsck_layout_dangling_key *des,
758                                   const struct lfsck_layout_dangling_key *src)
759 {
760         fid_le_to_cpu(&des->lldk_fid, &src->lldk_fid);
761         des->lldk_comp_id = le32_to_cpu(src->lldk_comp_id);
762         des->lldk_ea_off = le32_to_cpu(src->lldk_ea_off);
763 }
764
765 static inline void lldk_cpu_to_le(struct lfsck_layout_dangling_key *des,
766                                   const struct lfsck_layout_dangling_key *src)
767 {
768         fid_cpu_to_le(&des->lldk_fid, &src->lldk_fid);
769         des->lldk_comp_id = cpu_to_le32(src->lldk_comp_id);
770         des->lldk_ea_off = cpu_to_le32(src->lldk_ea_off);
771 }
772
773 static inline void lldk_be_to_cpu(struct lfsck_layout_dangling_key *des,
774                                   const struct lfsck_layout_dangling_key *src)
775 {
776         fid_be_to_cpu(&des->lldk_fid, &src->lldk_fid);
777         des->lldk_comp_id = be32_to_cpu(src->lldk_comp_id);
778         des->lldk_ea_off = be32_to_cpu(src->lldk_ea_off);
779 }
780
781 static inline void lldk_cpu_to_be(struct lfsck_layout_dangling_key *des,
782                                   const struct lfsck_layout_dangling_key *src)
783 {
784         fid_cpu_to_be(&des->lldk_fid, &src->lldk_fid);
785         des->lldk_comp_id = cpu_to_be32(src->lldk_comp_id);
786         des->lldk_ea_off = cpu_to_be32(src->lldk_ea_off);
787 }
788
789 static void lfsck_layout_le_to_cpu(struct lfsck_layout *des,
790                                    const struct lfsck_layout *src)
791 {
792         int i;
793
794         des->ll_magic = le32_to_cpu(src->ll_magic);
795         des->ll_status = le32_to_cpu(src->ll_status);
796         des->ll_flags = le32_to_cpu(src->ll_flags);
797         des->ll_success_count = le32_to_cpu(src->ll_success_count);
798         des->ll_run_time_phase1 = le32_to_cpu(src->ll_run_time_phase1);
799         des->ll_run_time_phase2 = le32_to_cpu(src->ll_run_time_phase2);
800         des->ll_time_last_complete = le64_to_cpu(src->ll_time_last_complete);
801         des->ll_time_latest_start = le64_to_cpu(src->ll_time_latest_start);
802         des->ll_time_last_checkpoint =
803                                 le64_to_cpu(src->ll_time_last_checkpoint);
804         des->ll_pos_latest_start = le64_to_cpu(src->ll_pos_latest_start);
805         des->ll_pos_last_checkpoint = le64_to_cpu(src->ll_pos_last_checkpoint);
806         des->ll_pos_first_inconsistent =
807                         le64_to_cpu(src->ll_pos_first_inconsistent);
808         des->ll_objs_checked_phase1 = le64_to_cpu(src->ll_objs_checked_phase1);
809         des->ll_objs_failed_phase1 = le64_to_cpu(src->ll_objs_failed_phase1);
810         des->ll_objs_checked_phase2 = le64_to_cpu(src->ll_objs_checked_phase2);
811         des->ll_objs_failed_phase2 = le64_to_cpu(src->ll_objs_failed_phase2);
812         for (i = 0; i < LLIT_MAX; i++)
813                 des->ll_objs_repaired[i] =
814                                 le64_to_cpu(src->ll_objs_repaired[i]);
815         des->ll_objs_skipped = le64_to_cpu(src->ll_objs_skipped);
816         des->ll_bitmap_size = le32_to_cpu(src->ll_bitmap_size);
817         lldk_le_to_cpu(&des->ll_lldk_latest_scanned_phase2,
818                        &src->ll_lldk_latest_scanned_phase2);
819 }
820
821 static void lfsck_layout_cpu_to_le(struct lfsck_layout *des,
822                                    const struct lfsck_layout *src)
823 {
824         int i;
825
826         des->ll_magic = cpu_to_le32(src->ll_magic);
827         des->ll_status = cpu_to_le32(src->ll_status);
828         des->ll_flags = cpu_to_le32(src->ll_flags);
829         des->ll_success_count = cpu_to_le32(src->ll_success_count);
830         des->ll_run_time_phase1 = cpu_to_le32(src->ll_run_time_phase1);
831         des->ll_run_time_phase2 = cpu_to_le32(src->ll_run_time_phase2);
832         des->ll_time_last_complete = cpu_to_le64(src->ll_time_last_complete);
833         des->ll_time_latest_start = cpu_to_le64(src->ll_time_latest_start);
834         des->ll_time_last_checkpoint =
835                                 cpu_to_le64(src->ll_time_last_checkpoint);
836         des->ll_pos_latest_start = cpu_to_le64(src->ll_pos_latest_start);
837         des->ll_pos_last_checkpoint = cpu_to_le64(src->ll_pos_last_checkpoint);
838         des->ll_pos_first_inconsistent =
839                         cpu_to_le64(src->ll_pos_first_inconsistent);
840         des->ll_objs_checked_phase1 = cpu_to_le64(src->ll_objs_checked_phase1);
841         des->ll_objs_failed_phase1 = cpu_to_le64(src->ll_objs_failed_phase1);
842         des->ll_objs_checked_phase2 = cpu_to_le64(src->ll_objs_checked_phase2);
843         des->ll_objs_failed_phase2 = cpu_to_le64(src->ll_objs_failed_phase2);
844         for (i = 0; i < LLIT_MAX; i++)
845                 des->ll_objs_repaired[i] =
846                                 cpu_to_le64(src->ll_objs_repaired[i]);
847         des->ll_objs_skipped = cpu_to_le64(src->ll_objs_skipped);
848         des->ll_bitmap_size = cpu_to_le32(src->ll_bitmap_size);
849         lldk_cpu_to_le(&des->ll_lldk_latest_scanned_phase2,
850                        &src->ll_lldk_latest_scanned_phase2);
851 }
852
853 /**
854  * Load the OST bitmap from the lfsck_layout trace file.
855  *
856  * \param[in] env       pointer to the thread context
857  * \param[in] com       pointer to the lfsck component
858  *
859  * \retval              0 for success
860  * \retval              negative error number on failure or data corruption
861  */
862 static int lfsck_layout_load_bitmap(const struct lu_env *env,
863                                     struct lfsck_component *com)
864 {
865         struct dt_object                *obj    = com->lc_obj;
866         struct lfsck_assistant_data     *lad    = com->lc_data;
867         struct lfsck_layout             *lo     = com->lc_file_ram;
868         struct cfs_bitmap                       *bitmap = lad->lad_bitmap;
869         loff_t                           pos    = com->lc_file_size;
870         ssize_t                          size;
871         __u32                            nbits;
872         int                              rc;
873         ENTRY;
874
875         if (com->lc_lfsck->li_ost_descs.ltd_tgts_bitmap->size >
876             lo->ll_bitmap_size)
877                 nbits = com->lc_lfsck->li_ost_descs.ltd_tgts_bitmap->size;
878         else
879                 nbits = lo->ll_bitmap_size;
880
881         if (unlikely(nbits < BITS_PER_LONG))
882                 nbits = BITS_PER_LONG;
883
884         if (nbits > bitmap->size) {
885                 __u32 new_bits = bitmap->size;
886                 struct cfs_bitmap *new_bitmap;
887
888                 while (new_bits < nbits)
889                         new_bits <<= 1;
890
891                 new_bitmap = CFS_ALLOCATE_BITMAP(new_bits);
892                 if (new_bitmap == NULL)
893                         RETURN(-ENOMEM);
894
895                 lad->lad_bitmap = new_bitmap;
896                 CFS_FREE_BITMAP(bitmap);
897                 bitmap = new_bitmap;
898         }
899
900         if (lo->ll_bitmap_size == 0) {
901                 lad->lad_incomplete = 0;
902                 CFS_RESET_BITMAP(bitmap);
903
904                 RETURN(0);
905         }
906
907         size = (lo->ll_bitmap_size + 7) >> 3;
908         rc = dt_read(env, obj, lfsck_buf_get(env, bitmap->data, size), &pos);
909         if (rc != size)
910                 RETURN(rc >= 0 ? -EINVAL : rc);
911
912         if (cfs_bitmap_check_empty(bitmap))
913                 lad->lad_incomplete = 0;
914         else
915                 lad->lad_incomplete = 1;
916
917         RETURN(0);
918 }
919
920 /**
921  * Load the layout LFSCK trace file from disk.
922  *
923  * The layout LFSCK trace file records the layout LFSCK status information
924  * and other statistics, such as how many objects have been scanned, and how
925  * many objects have been repaired, and etc. It also contains the bitmap for
926  * failed OSTs during the layout LFSCK. All these information will be loaded
927  * from disk to RAM when the layout LFSCK component setup.
928  *
929  * \param[in] env       pointer to the thread context
930  * \param[in] com       pointer to the lfsck component
931  *
932  * \retval              positive number for file data corruption, the caller
933  *                      should reset the layout LFSCK trace file
934  * \retval              0 for success
935  * \retval              negative error number on failure
936  */
937 static int lfsck_layout_load(const struct lu_env *env,
938                              struct lfsck_component *com)
939 {
940         struct lfsck_layout             *lo     = com->lc_file_ram;
941         ssize_t                          size   = com->lc_file_size;
942         loff_t                           pos    = 0;
943         int                              rc;
944
945         rc = dt_read(env, com->lc_obj,
946                      lfsck_buf_get(env, com->lc_file_disk, size), &pos);
947         if (rc == 0) {
948                 return -ENOENT;
949         } else if (rc < 0) {
950                 CDEBUG(D_LFSCK, "%s: failed to load lfsck_layout: rc = %d\n",
951                        lfsck_lfsck2name(com->lc_lfsck), rc);
952                 return rc;
953         } else if (rc != size) {
954                 CDEBUG(D_LFSCK, "%s: lfsck_layout size %u != %u; reset it\n",
955                        lfsck_lfsck2name(com->lc_lfsck), rc, (unsigned int)size);
956                 return 1;
957         }
958
959         lfsck_layout_le_to_cpu(lo, com->lc_file_disk);
960         if (lo->ll_magic != LFSCK_LAYOUT_MAGIC) {
961                 CDEBUG(D_LFSCK, "%s: invalid lfsck_layout magic %#x != %#x, "
962                        "to be reset\n", lfsck_lfsck2name(com->lc_lfsck),
963                        lo->ll_magic, LFSCK_LAYOUT_MAGIC);
964                 return 1;
965         }
966
967         return 0;
968 }
969
970 /**
971  * Store the layout LFSCK trace file on disk.
972  *
973  * The layout LFSCK trace file records the layout LFSCK status information
974  * and other statistics, such as how many objects have been scanned, and how
975  * many objects have been repaired, and etc. It also contains the bitmap for
976  * failed OSTs during the layout LFSCK. All these information will be synced
977  * from RAM to disk periodically.
978  *
979  * \param[in] env       pointer to the thread context
980  * \param[in] com       pointer to the lfsck component
981  *
982  * \retval              0 for success
983  * \retval              negative error number on failure
984  */
985 static int lfsck_layout_store(const struct lu_env *env,
986                               struct lfsck_component *com)
987 {
988         struct dt_object        *obj    = com->lc_obj;
989         struct lfsck_instance   *lfsck  = com->lc_lfsck;
990         struct lfsck_layout     *lo_ram = com->lc_file_ram;
991         struct lfsck_layout     *lo     = com->lc_file_disk;
992         struct thandle          *th;
993         struct dt_device        *dev    = lfsck_obj2dev(obj);
994         struct cfs_bitmap       *bitmap = NULL;
995         loff_t                   pos;
996         ssize_t                  size   = com->lc_file_size;
997         __u32                    nbits  = 0;
998         int                      rc;
999         ENTRY;
1000
1001         if (lfsck->li_master) {
1002                 struct lfsck_assistant_data *lad = com->lc_data;
1003
1004                 bitmap = lad->lad_bitmap;
1005                 nbits = bitmap->size;
1006
1007                 LASSERT(nbits > 0);
1008                 LASSERTF((nbits & 7) == 0, "Invalid nbits %u\n", nbits);
1009         }
1010
1011         lo_ram->ll_bitmap_size = nbits;
1012         lfsck_layout_cpu_to_le(lo, lo_ram);
1013         th = dt_trans_create(env, dev);
1014         if (IS_ERR(th))
1015                 GOTO(log, rc = PTR_ERR(th));
1016
1017         rc = dt_declare_record_write(env, obj, lfsck_buf_get(env, lo, size),
1018                                      (loff_t)0, th);
1019         if (rc != 0)
1020                 GOTO(out, rc);
1021
1022         if (bitmap != NULL) {
1023                 rc = dt_declare_record_write(env, obj,
1024                                 lfsck_buf_get(env, bitmap->data, nbits >> 3),
1025                                 (loff_t)size, th);
1026                 if (rc != 0)
1027                         GOTO(out, rc);
1028         }
1029
1030         rc = dt_trans_start_local(env, dev, th);
1031         if (rc != 0)
1032                 GOTO(out, rc);
1033
1034         pos = 0;
1035         rc = dt_record_write(env, obj, lfsck_buf_get(env, lo, size), &pos, th);
1036         if (rc != 0)
1037                 GOTO(out, rc);
1038
1039         if (bitmap != NULL) {
1040                 pos = size;
1041                 rc = dt_record_write(env, obj,
1042                                 lfsck_buf_get(env, bitmap->data, nbits >> 3),
1043                                 &pos, th);
1044         }
1045
1046         GOTO(out, rc);
1047
1048 out:
1049         dt_trans_stop(env, dev, th);
1050
1051 log:
1052         if (rc != 0)
1053                 CDEBUG(D_LFSCK, "%s: fail to store lfsck_layout: rc = %d\n",
1054                        lfsck_lfsck2name(lfsck), rc);
1055
1056         return rc;
1057 }
1058
1059 static int lfsck_layout_init(const struct lu_env *env,
1060                              struct lfsck_component *com)
1061 {
1062         struct lfsck_layout *lo = com->lc_file_ram;
1063         int rc;
1064
1065         memset(lo, 0, com->lc_file_size);
1066         lo->ll_magic = LFSCK_LAYOUT_MAGIC;
1067         lo->ll_status = LS_INIT;
1068         down_write(&com->lc_sem);
1069         rc = lfsck_layout_store(env, com);
1070         if (rc == 0 && com->lc_lfsck->li_master)
1071                 rc = lfsck_load_sub_trace_files(env, com,
1072                         &dt_lfsck_layout_dangling_features, LFSCK_LAYOUT, true);
1073         up_write(&com->lc_sem);
1074
1075         return rc;
1076 }
1077
1078 static int fid_is_for_ostobj(const struct lu_env *env,
1079                              struct lfsck_instance *lfsck,
1080                              struct dt_object *obj, const struct lu_fid *fid)
1081 {
1082         struct seq_server_site  *ss     = lfsck_dev_site(lfsck);
1083         struct lu_seq_range     *range  = &lfsck_env_info(env)->lti_range;
1084         struct lustre_ost_attrs *loa;
1085         int                      rc;
1086
1087         fld_range_set_any(range);
1088         rc = fld_server_lookup(env, ss->ss_server_fld, fid_seq(fid), range);
1089         if (rc == 0) {
1090                 if (fld_range_is_ost(range))
1091                         return 1;
1092
1093                 return 0;
1094         }
1095
1096         loa = &lfsck_env_info(env)->lti_loa;
1097         rc = dt_xattr_get(env, obj, lfsck_buf_get(env, loa, sizeof(*loa)),
1098                           XATTR_NAME_LMA);
1099         if (rc >= sizeof(struct lustre_mdt_attrs)) {
1100                 lustre_lma_swab(&loa->loa_lma);
1101
1102                 return loa->loa_lma.lma_compat & LMAC_FID_ON_OST ? 1 : 0;
1103         }
1104
1105         rc = dt_xattr_get(env, obj, &LU_BUF_NULL, XATTR_NAME_FID);
1106
1107         return rc > 0;
1108 }
1109
1110 static struct lfsck_layout_seq *
1111 lfsck_layout_seq_lookup(struct lfsck_layout_slave_data *llsd, __u64 seq)
1112 {
1113         struct lfsck_layout_seq *lls;
1114
1115         list_for_each_entry(lls, &llsd->llsd_seq_list, lls_list) {
1116                 if (lls->lls_seq == seq)
1117                         return lls;
1118
1119                 if (lls->lls_seq > seq)
1120                         return NULL;
1121         }
1122
1123         return NULL;
1124 }
1125
1126 static void
1127 lfsck_layout_seq_insert(struct lfsck_layout_slave_data *llsd,
1128                         struct lfsck_layout_seq *lls)
1129 {
1130         struct lfsck_layout_seq *tmp;
1131         struct list_head        *pos = &llsd->llsd_seq_list;
1132
1133         list_for_each_entry(tmp, &llsd->llsd_seq_list, lls_list) {
1134                 if (lls->lls_seq < tmp->lls_seq) {
1135                         pos = &tmp->lls_list;
1136                         break;
1137                 }
1138         }
1139         list_add_tail(&lls->lls_list, pos);
1140 }
1141
1142 static int
1143 lfsck_layout_lastid_create(const struct lu_env *env,
1144                            struct lfsck_instance *lfsck,
1145                            struct dt_object *obj)
1146 {
1147         struct lfsck_thread_info *info   = lfsck_env_info(env);
1148         struct lu_attr           *la     = &info->lti_la;
1149         struct dt_object_format  *dof    = &info->lti_dof;
1150         struct lfsck_bookmark    *bk     = &lfsck->li_bookmark_ram;
1151         struct dt_device         *dt     = lfsck_obj2dev(obj);
1152         struct thandle           *th;
1153         __u64                     lastid = 0;
1154         loff_t                    pos    = 0;
1155         int                       rc;
1156         ENTRY;
1157
1158         if (bk->lb_param & LPF_DRYRUN)
1159                 return 0;
1160
1161         memset(la, 0, sizeof(*la));
1162         la->la_mode = S_IFREG |  S_IRUGO | S_IWUSR;
1163         la->la_valid = LA_MODE | LA_UID | LA_GID;
1164         memset(dof, 0, sizeof(*dof));
1165         dof->dof_type = dt_mode_to_dft(S_IFREG);
1166
1167         th = dt_trans_create(env, dt);
1168         if (IS_ERR(th))
1169                 GOTO(log, rc = PTR_ERR(th));
1170
1171         rc = dt_declare_create(env, obj, la, NULL, dof, th);
1172         if (rc != 0)
1173                 GOTO(stop, rc);
1174
1175         rc = dt_declare_record_write(env, obj,
1176                                      lfsck_buf_get(env, &lastid,
1177                                                    sizeof(lastid)),
1178                                      pos, th);
1179         if (rc != 0)
1180                 GOTO(stop, rc);
1181
1182         rc = dt_trans_start_local(env, dt, th);
1183         if (rc != 0)
1184                 GOTO(stop, rc);
1185
1186         dt_write_lock(env, obj, 0);
1187         if (likely(dt_object_exists(obj) == 0)) {
1188                 rc = dt_create(env, obj, la, NULL, dof, th);
1189                 if (rc == 0)
1190                         rc = dt_record_write(env, obj,
1191                                 lfsck_buf_get(env, &lastid, sizeof(lastid)),
1192                                 &pos, th);
1193         }
1194         dt_write_unlock(env, obj);
1195
1196         GOTO(stop, rc);
1197
1198 stop:
1199         dt_trans_stop(env, dt, th);
1200
1201 log:
1202         CDEBUG(D_LFSCK, "%s: layout LFSCK will create LAST_ID for <seq> "
1203                "%#llx: rc = %d\n",
1204                lfsck_lfsck2name(lfsck), fid_seq(lfsck_dto2fid(obj)), rc);
1205
1206         return rc;
1207 }
1208
1209 static int
1210 lfsck_layout_lastid_reload(const struct lu_env *env,
1211                            struct lfsck_component *com,
1212                            struct lfsck_layout_seq *lls)
1213 {
1214         __u64   lastid;
1215         loff_t  pos     = 0;
1216         int     rc;
1217
1218         dt_read_lock(env, lls->lls_lastid_obj, 0);
1219         rc = dt_record_read(env, lls->lls_lastid_obj,
1220                             lfsck_buf_get(env, &lastid, sizeof(lastid)), &pos);
1221         dt_read_unlock(env, lls->lls_lastid_obj);
1222         if (unlikely(rc != 0))
1223                 return rc;
1224
1225         lastid = le64_to_cpu(lastid);
1226         if (lastid < lls->lls_lastid_known) {
1227                 struct lfsck_instance   *lfsck  = com->lc_lfsck;
1228                 struct lfsck_layout     *lo     = com->lc_file_ram;
1229
1230                 lls->lls_lastid = lls->lls_lastid_known;
1231                 lls->lls_dirty = 1;
1232                 if (!(lo->ll_flags & LF_CRASHED_LASTID)) {
1233                         LASSERT(lfsck->li_out_notify != NULL);
1234
1235                         lfsck->li_out_notify(env, lfsck->li_out_notify_data,
1236                                              LE_LASTID_REBUILDING);
1237                         lo->ll_flags |= LF_CRASHED_LASTID;
1238
1239                         CDEBUG(D_LFSCK, "%s: layout LFSCK finds crashed "
1240                                "LAST_ID file (1) for the sequence %#llx"
1241                                ", old value %llu, known value %llu\n",
1242                                lfsck_lfsck2name(lfsck), lls->lls_seq,
1243                                lastid, lls->lls_lastid);
1244                 }
1245         } else if (lastid >= lls->lls_lastid) {
1246                 lls->lls_lastid = lastid;
1247                 lls->lls_dirty = 0;
1248         }
1249
1250         return 0;
1251 }
1252
1253 static int
1254 lfsck_layout_lastid_store(const struct lu_env *env,
1255                           struct lfsck_component *com)
1256 {
1257         struct lfsck_instance           *lfsck  = com->lc_lfsck;
1258         struct lfsck_bookmark           *bk     = &lfsck->li_bookmark_ram;
1259         struct dt_device                *dt     = lfsck->li_bottom;
1260         struct lfsck_layout_slave_data  *llsd   = com->lc_data;
1261         struct lfsck_layout_seq         *lls;
1262         struct thandle                  *th;
1263         __u64                            lastid;
1264         int                              rc     = 0;
1265         int                              rc1    = 0;
1266
1267         list_for_each_entry(lls, &llsd->llsd_seq_list, lls_list) {
1268                 loff_t pos = 0;
1269
1270                 if (!lls->lls_dirty)
1271                         continue;
1272
1273                 CDEBUG(D_LFSCK, "%s: layout LFSCK will sync the LAST_ID for "
1274                        "<seq> %#llx as <oid> %llu\n",
1275                        lfsck_lfsck2name(lfsck), lls->lls_seq, lls->lls_lastid);
1276
1277                 if (bk->lb_param & LPF_DRYRUN) {
1278                         lls->lls_dirty = 0;
1279                         continue;
1280                 }
1281
1282                 th = dt_trans_create(env, dt);
1283                 if (IS_ERR(th)) {
1284                         rc1 = PTR_ERR(th);
1285                         CDEBUG(D_LFSCK, "%s: layout LFSCK failed to store "
1286                                "the LAST_ID for <seq> %#llx(1): rc = %d\n",
1287                                lfsck_lfsck2name(com->lc_lfsck),
1288                                lls->lls_seq, rc1);
1289                         continue;
1290                 }
1291
1292                 lastid = cpu_to_le64(lls->lls_lastid);
1293                 rc = dt_declare_record_write(env, lls->lls_lastid_obj,
1294                                              lfsck_buf_get(env, &lastid,
1295                                                            sizeof(lastid)),
1296                                              pos, th);
1297                 if (rc != 0)
1298                         goto stop;
1299
1300                 rc = dt_trans_start_local(env, dt, th);
1301                 if (rc != 0)
1302                         goto stop;
1303
1304                 dt_write_lock(env, lls->lls_lastid_obj, 0);
1305                 rc = dt_record_write(env, lls->lls_lastid_obj,
1306                                      lfsck_buf_get(env, &lastid,
1307                                      sizeof(lastid)), &pos, th);
1308                 dt_write_unlock(env, lls->lls_lastid_obj);
1309                 if (rc == 0)
1310                         lls->lls_dirty = 0;
1311
1312 stop:
1313                 dt_trans_stop(env, dt, th);
1314                 if (rc != 0) {
1315                         rc1 = rc;
1316                         CDEBUG(D_LFSCK, "%s: layout LFSCK failed to store "
1317                                "the LAST_ID for <seq> %#llx(2): rc = %d\n",
1318                                lfsck_lfsck2name(com->lc_lfsck),
1319                                lls->lls_seq, rc1);
1320                 }
1321         }
1322
1323         return rc1;
1324 }
1325
1326 static int
1327 lfsck_layout_lastid_load(const struct lu_env *env,
1328                          struct lfsck_component *com,
1329                          struct lfsck_layout_seq *lls)
1330 {
1331         struct lfsck_instance   *lfsck  = com->lc_lfsck;
1332         struct lfsck_layout     *lo     = com->lc_file_ram;
1333         struct lu_fid           *fid    = &lfsck_env_info(env)->lti_fid;
1334         struct dt_object        *obj;
1335         loff_t                   pos    = 0;
1336         int                      rc;
1337         ENTRY;
1338
1339         lu_last_id_fid(fid, lls->lls_seq, lfsck_dev_idx(lfsck));
1340         obj = dt_locate(env, lfsck->li_bottom, fid);
1341         if (IS_ERR(obj))
1342                 RETURN(PTR_ERR(obj));
1343
1344         /* LAST_ID crashed, to be rebuilt */
1345         if (dt_object_exists(obj) == 0) {
1346                 if (!(lo->ll_flags & LF_CRASHED_LASTID)) {
1347                         LASSERT(lfsck->li_out_notify != NULL);
1348
1349                         lfsck->li_out_notify(env, lfsck->li_out_notify_data,
1350                                              LE_LASTID_REBUILDING);
1351                         lo->ll_flags |= LF_CRASHED_LASTID;
1352
1353                         CDEBUG(D_LFSCK, "%s: layout LFSCK cannot find the "
1354                                "LAST_ID file for sequence %#llx\n",
1355                                lfsck_lfsck2name(lfsck), lls->lls_seq);
1356
1357                         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_DELAY4) &&
1358                             cfs_fail_val > 0) {
1359                                 struct l_wait_info lwi = LWI_TIMEOUT(
1360                                                 cfs_time_seconds(cfs_fail_val),
1361                                                 NULL, NULL);
1362
1363                                 /* Some others may changed the cfs_fail_val
1364                                  * as zero after above check, re-check it for
1365                                  * sure to avoid falling into wait for ever. */
1366                                 if (likely(lwi.lwi_timeout > 0)) {
1367                                         struct ptlrpc_thread *thread =
1368                                                 &lfsck->li_thread;
1369
1370                                         up_write(&com->lc_sem);
1371                                         l_wait_event(thread->t_ctl_waitq,
1372                                                      !thread_is_running(thread),
1373                                                      &lwi);
1374                                         down_write(&com->lc_sem);
1375                                 }
1376                         }
1377                 }
1378
1379                 rc = lfsck_layout_lastid_create(env, lfsck, obj);
1380         } else {
1381                 dt_read_lock(env, obj, 0);
1382                 rc = dt_read(env, obj,
1383                         lfsck_buf_get(env, &lls->lls_lastid, sizeof(__u64)),
1384                         &pos);
1385                 dt_read_unlock(env, obj);
1386                 if (rc != 0 && rc != sizeof(__u64))
1387                         GOTO(out, rc = (rc > 0 ? -EFAULT : rc));
1388
1389                 if (rc == 0 && !(lo->ll_flags & LF_CRASHED_LASTID)) {
1390                         LASSERT(lfsck->li_out_notify != NULL);
1391
1392                         lfsck->li_out_notify(env, lfsck->li_out_notify_data,
1393                                              LE_LASTID_REBUILDING);
1394                         lo->ll_flags |= LF_CRASHED_LASTID;
1395
1396                         CDEBUG(D_LFSCK, "%s: layout LFSCK finds invalid "
1397                                "LAST_ID file for the sequence %#llx"
1398                                ": rc = %d\n",
1399                                lfsck_lfsck2name(lfsck), lls->lls_seq, rc);
1400                 }
1401
1402                 lls->lls_lastid = le64_to_cpu(lls->lls_lastid);
1403                 rc = 0;
1404         }
1405
1406         GOTO(out, rc);
1407
1408 out:
1409         if (rc != 0)
1410                 lfsck_object_put(env, obj);
1411         else
1412                 lls->lls_lastid_obj = obj;
1413
1414         return rc;
1415 }
1416
1417 static void lfsck_layout_record_failure(const struct lu_env *env,
1418                                         struct lfsck_instance *lfsck,
1419                                         struct lfsck_layout *lo)
1420 {
1421         __u64 cookie;
1422
1423         lo->ll_objs_failed_phase1++;
1424         cookie = lfsck->li_obj_oit->do_index_ops->dio_it.store(env,
1425                                                         lfsck->li_di_oit);
1426         if (lo->ll_pos_first_inconsistent == 0 ||
1427             lo->ll_pos_first_inconsistent < cookie) {
1428                 lo->ll_pos_first_inconsistent = cookie;
1429
1430                 CDEBUG(D_LFSCK, "%s: layout LFSCK hit first non-repaired "
1431                        "inconsistency at the pos [%llu]\n",
1432                        lfsck_lfsck2name(lfsck),
1433                        lo->ll_pos_first_inconsistent);
1434         }
1435 }
1436
1437 static int lfsck_layout_double_scan_result(const struct lu_env *env,
1438                                            struct lfsck_component *com,
1439                                            int rc)
1440 {
1441         struct lfsck_instance   *lfsck = com->lc_lfsck;
1442         struct lfsck_layout     *lo    = com->lc_file_ram;
1443
1444         down_write(&com->lc_sem);
1445         lo->ll_run_time_phase2 += cfs_duration_sec(cfs_time_current() +
1446                                   HALF_SEC - com->lc_time_last_checkpoint);
1447         lo->ll_time_last_checkpoint = cfs_time_current_sec();
1448         lo->ll_objs_checked_phase2 += com->lc_new_checked;
1449
1450         if (rc > 0) {
1451                 if (lo->ll_flags & LF_INCOMPLETE) {
1452                         lo->ll_status = LS_PARTIAL;
1453                 } else {
1454                         if (lfsck->li_master) {
1455                                 struct lfsck_assistant_data *lad = com->lc_data;
1456
1457                                 if (lad->lad_incomplete)
1458                                         lo->ll_status = LS_PARTIAL;
1459                                 else
1460                                         lo->ll_status = LS_COMPLETED;
1461                         } else {
1462                                 lo->ll_status = LS_COMPLETED;
1463                         }
1464                 }
1465                 lo->ll_flags &= ~LF_SCANNED_ONCE;
1466                 if (!(lfsck->li_bookmark_ram.lb_param & LPF_DRYRUN))
1467                         lo->ll_flags &= ~LF_INCONSISTENT;
1468                 lo->ll_time_last_complete = lo->ll_time_last_checkpoint;
1469                 lo->ll_success_count++;
1470         } else if (rc == 0) {
1471                 if (lfsck->li_status != 0)
1472                         lo->ll_status = lfsck->li_status;
1473                 else
1474                         lo->ll_status = LS_STOPPED;
1475         } else {
1476                 lo->ll_status = LS_FAILED;
1477         }
1478
1479         rc = lfsck_layout_store(env, com);
1480         up_write(&com->lc_sem);
1481
1482         return rc;
1483 }
1484
1485 static int lfsck_layout_trans_stop(const struct lu_env *env,
1486                                    struct dt_device *dev,
1487                                    struct thandle *handle, int result)
1488 {
1489         int rc;
1490
1491         /* XXX: If there is something worng or it needs to repair nothing,
1492          *      then notify the lower to stop the modification. Currently,
1493          *      we use th_result for such purpose, that may be replaced by
1494          *      some rollback mechanism in the future. */
1495         handle->th_result = result;
1496         rc = dt_trans_stop(env, dev, handle);
1497         if (result != 0)
1498                 return result > 0 ? 0 : result;
1499
1500         return rc == 0 ? 1 : rc;
1501 }
1502
1503 static int lfsck_layout_ins_dangling_rec(const struct lu_env *env,
1504                                          struct lfsck_component *com,
1505                                          const struct lu_fid *pfid,
1506                                          const struct lu_fid *cfid,
1507                                          __u32 comp_id, __u32 ea_off,
1508                                          __u32 ost_idx)
1509 {
1510         struct lfsck_layout_dangling_key *key = &lfsck_env_info(env)->lti_lldk;
1511         struct lu_fid *rec = &lfsck_env_info(env)->lti_fid3;
1512         struct dt_device *dev;
1513         struct dt_object *obj;
1514         struct thandle *th = NULL;
1515         int idx;
1516         int rc = 0;
1517         ENTRY;
1518
1519         idx = lfsck_sub_trace_file_fid2idx(pfid);
1520         obj = com->lc_sub_trace_objs[idx].lsto_obj;
1521         dev = lfsck_obj2dev(obj);
1522
1523         fid_cpu_to_be(&key->lldk_fid, pfid);
1524         key->lldk_comp_id = cpu_to_be32(comp_id);
1525         key->lldk_ea_off = cpu_to_be32(ea_off);
1526
1527         fid_cpu_to_be(rec, cfid);
1528         rec->f_ver = cpu_to_be32(ost_idx);
1529
1530         mutex_lock(&com->lc_sub_trace_objs[idx].lsto_mutex);
1531
1532         th = dt_trans_create(env, dev);
1533         if (IS_ERR(th))
1534                 GOTO(unlock, rc = PTR_ERR(th));
1535
1536         rc = dt_declare_insert(env, obj,
1537                                (const struct dt_rec *)rec,
1538                                (const struct dt_key *)key, th);
1539         if (rc)
1540                 GOTO(unlock, rc);
1541
1542         rc = dt_trans_start_local(env, dev, th);
1543         if (rc)
1544                 GOTO(unlock, rc);
1545
1546         rc = dt_insert(env, obj, (const struct dt_rec *)rec,
1547                        (const struct dt_key *)key, th, 1);
1548
1549         GOTO(unlock, rc);
1550
1551 unlock:
1552         if (th && !IS_ERR(th))
1553                 dt_trans_stop(env, dev, th);
1554
1555         mutex_unlock(&com->lc_sub_trace_objs[idx].lsto_mutex);
1556
1557         CDEBUG(D_LFSCK, "%s: insert the paris "DFID" => "DFID", comp_id = %u, "
1558                "ea_off = %u, ost_idx = %u, into the trace file for further "
1559                "dangling check: rc = %d\n", lfsck_lfsck2name(com->lc_lfsck),
1560                PFID(pfid), PFID(cfid), comp_id, ea_off, ost_idx, rc);
1561
1562         return rc;
1563 }
1564
1565 static int lfsck_layout_del_dangling_rec(const struct lu_env *env,
1566                                          struct lfsck_component *com,
1567                                          const struct lu_fid *fid,
1568                                          __u32 comp_id, __u32 ea_off)
1569 {
1570         struct lfsck_layout_dangling_key *key = &lfsck_env_info(env)->lti_lldk;
1571         struct dt_device *dev;
1572         struct dt_object *obj;
1573         struct thandle *th = NULL;
1574         int idx;
1575         int rc = 0;
1576         ENTRY;
1577
1578         idx = lfsck_sub_trace_file_fid2idx(fid);
1579         obj = com->lc_sub_trace_objs[idx].lsto_obj;
1580         dev = lfsck_obj2dev(obj);
1581
1582         fid_cpu_to_be(&key->lldk_fid, fid);
1583         key->lldk_comp_id = cpu_to_be32(comp_id);
1584         key->lldk_ea_off = cpu_to_be32(ea_off);
1585
1586         mutex_lock(&com->lc_sub_trace_objs[idx].lsto_mutex);
1587
1588         th = dt_trans_create(env, dev);
1589         if (IS_ERR(th))
1590                 GOTO(unlock, rc = PTR_ERR(th));
1591
1592         rc = dt_declare_delete(env, obj, (const struct dt_key *)key, th);
1593         if (rc)
1594                 GOTO(unlock, rc);
1595
1596         rc = dt_trans_start_local(env, dev, th);
1597         if (rc)
1598                 GOTO(unlock, rc);
1599
1600         rc = dt_delete(env, obj, (const struct dt_key *)key, th);
1601
1602         GOTO(unlock, rc);
1603
1604 unlock:
1605         if (th && !IS_ERR(th))
1606                 dt_trans_stop(env, dev, th);
1607
1608         mutex_unlock(&com->lc_sub_trace_objs[idx].lsto_mutex);
1609
1610         CDEBUG(D_LFSCK, "%s: delete the dangling record for "DFID
1611                ", comp_id = %u, ea_off = %u from the trace file: rc = %d\n",
1612                lfsck_lfsck2name(com->lc_lfsck), PFID(fid), comp_id, ea_off, rc);
1613
1614         return rc;
1615 }
1616
1617 /**
1618  * Get the system default stripe size.
1619  *
1620  * \param[in] env       pointer to the thread context
1621  * \param[in] lfsck     pointer to the lfsck instance
1622  * \param[out] size     pointer to the default stripe size
1623  *
1624  * \retval              0 for success
1625  * \retval              negative error number on failure
1626  */
1627 static int lfsck_layout_get_def_stripesize(const struct lu_env *env,
1628                                            struct lfsck_instance *lfsck,
1629                                            __u32 *size)
1630 {
1631         struct lov_user_md      *lum = &lfsck_env_info(env)->lti_lum;
1632         struct dt_object        *root;
1633         int                      rc;
1634
1635         root = dt_locate(env, lfsck->li_next, &lfsck->li_local_root_fid);
1636         if (IS_ERR(root))
1637                 return PTR_ERR(root);
1638
1639         /* Get the default stripe size via xattr_get on the backend root. */
1640         rc = dt_xattr_get(env, root, lfsck_buf_get(env, lum, sizeof(*lum)),
1641                           XATTR_NAME_LOV);
1642         if (rc > 0) {
1643                 /* The lum->lmm_stripe_size is LE mode. The *size also
1644                  * should be LE mode. So it is unnecessary to convert. */
1645                 *size = lum->lmm_stripe_size;
1646                 rc = 0;
1647         } else if (unlikely(rc == 0)) {
1648                 rc = -EINVAL;
1649         }
1650
1651         lfsck_object_put(env, root);
1652
1653         return rc;
1654 }
1655
1656 /**
1657  * \retval       +1: repaired
1658  * \retval        0: did nothing
1659  * \retval      -ve: on error
1660  */
1661 static int lfsck_layout_refill_lovea(const struct lu_env *env,
1662                                      struct lfsck_instance *lfsck,
1663                                      struct thandle *handle,
1664                                      struct dt_object *parent,
1665                                      const struct lu_fid *cfid,
1666                                      struct lu_buf *buf,
1667                                      struct lov_mds_md_v1 *lmm,
1668                                      struct lov_ost_data_v1 *slot,
1669                                      int fl, __u32 ost_idx, int size)
1670 {
1671         struct ost_id           *oi     = &lfsck_env_info(env)->lti_oi;
1672         struct lu_buf            ea_buf;
1673         int                      rc;
1674         __u32                    magic;
1675         __u32                    pattern;
1676         __u16                    count;
1677         ENTRY;
1678
1679         magic = le32_to_cpu(lmm->lmm_magic);
1680         pattern = le32_to_cpu(lmm->lmm_pattern);
1681         count = le16_to_cpu(lmm->lmm_stripe_count);
1682
1683         fid_to_ostid(cfid, oi);
1684         ostid_cpu_to_le(oi, &slot->l_ost_oi);
1685         slot->l_ost_gen = cpu_to_le32(0);
1686         slot->l_ost_idx = cpu_to_le32(ost_idx);
1687
1688         if (pattern & LOV_PATTERN_F_HOLE) {
1689                 struct lov_ost_data_v1 *objs;
1690                 int                     i;
1691
1692                 if (magic == LOV_MAGIC_V1)
1693                         objs = &lmm->lmm_objects[0];
1694                 else
1695                         objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[0];
1696                 for (i = 0; i < count; i++, objs++) {
1697                         if (lovea_slot_is_dummy(objs))
1698                                 break;
1699                 }
1700
1701                 /* If the @slot is the last dummy slot to be refilled,
1702                  * then drop LOV_PATTERN_F_HOLE from lmm::lmm_pattern. */
1703                 if (i == count) {
1704                         lmm->lmm_pattern =
1705                                 cpu_to_le32(pattern & ~LOV_PATTERN_F_HOLE);
1706
1707                         CDEBUG(D_LFSCK, "%s: remove layout HOLE for "DFID
1708                                ": parent "DFID"\n", lfsck_lfsck2name(lfsck),
1709                                PFID(cfid), PFID(lfsck_dto2fid(parent)));
1710                 }
1711         }
1712
1713         lfsck_buf_init(&ea_buf, buf->lb_buf, size);
1714         rc = dt_xattr_set(env, parent, &ea_buf, XATTR_NAME_LOV, fl, handle);
1715         if (rc == 0)
1716                 rc = 1;
1717
1718         RETURN(rc);
1719 }
1720
1721 static struct lov_ost_data_v1 *
1722 __lfsck_layout_new_v1_lovea(struct lov_mds_md_v1 *lmm,
1723                             const struct lu_fid *pfid,
1724                             __u32 stripe_size, __u32 ea_off,
1725                             __u32 pattern, __u16 count)
1726 {
1727         lmm->lmm_magic = cpu_to_le32(LOV_MAGIC_V1);
1728         lmm->lmm_pattern = cpu_to_le32(pattern);
1729         fid_to_lmm_oi(pfid, &lmm->lmm_oi);
1730         lmm_oi_cpu_to_le(&lmm->lmm_oi, &lmm->lmm_oi);
1731         lmm->lmm_stripe_size = cpu_to_le32(stripe_size);
1732         lmm->lmm_stripe_count = cpu_to_le16(count);
1733         lmm->lmm_layout_gen = cpu_to_le16(1);
1734         memset(&lmm->lmm_objects[0], 0,
1735                sizeof(struct lov_ost_data_v1) * count);
1736
1737         return &lmm->lmm_objects[ea_off];
1738 }
1739
1740 static int lfsck_layout_new_v1_lovea(const struct lu_env *env,
1741                                      struct lfsck_instance *lfsck,
1742                                      struct ost_layout *ol,
1743                                      struct dt_object *parent,
1744                                      struct lu_buf *buf, __u32 ea_off,
1745                                      struct lov_mds_md_v1 **lmm,
1746                                      struct lov_ost_data_v1 **objs)
1747 {
1748         int size;
1749         __u32 stripe_size = ol->ol_stripe_size;
1750         __u32 pattern = LOV_PATTERN_RAID0;
1751         __u16 count;
1752
1753         if (ol->ol_stripe_count != 0)
1754                 count = ol->ol_stripe_count;
1755         else
1756                 count = ea_off + 1;
1757
1758         size = lov_mds_md_size(count, LOV_MAGIC_V1);
1759         LASSERTF(buf->lb_len >= size,
1760                  "buffer len %d is less than real size %d\n",
1761                  (int)buf->lb_len, size);
1762
1763         if (stripe_size == 0) {
1764                 int rc;
1765
1766                 rc = lfsck_layout_get_def_stripesize(env, lfsck, &stripe_size);
1767                 if (rc)
1768                         return rc;
1769         }
1770
1771         *lmm = buf->lb_buf;
1772         if (ol->ol_stripe_count > 1 ||
1773             (ol->ol_stripe_count == 0 && ea_off != 0)) {
1774                 pattern |= LOV_PATTERN_F_HOLE;
1775                 memset(&(*lmm)->lmm_objects[0], 0,
1776                        count * sizeof(struct lov_ost_data_v1));
1777         }
1778
1779         *objs = __lfsck_layout_new_v1_lovea(*lmm, lfsck_dto2fid(parent),
1780                                 stripe_size, ea_off, pattern, count);
1781
1782         return size;
1783 }
1784
1785 static int lfsck_layout_new_comp_lovea(const struct lu_env *env,
1786                                       struct ost_layout *ol,
1787                                       struct dt_object *parent,
1788                                       struct lu_buf *buf, __u32 ea_off,
1789                                       struct lov_mds_md_v1 **lmm,
1790                                       struct lov_ost_data_v1 **objs)
1791 {
1792         struct lov_comp_md_v1 *lcm;
1793         struct lov_comp_md_entry_v1 *lcme;
1794         __u32 pattern = LOV_PATTERN_RAID0;
1795         __u32 offset = sizeof(*lcm) + sizeof(*lcme);
1796         int lcme_size = lov_mds_md_size(ol->ol_stripe_count, LOV_MAGIC_V1);
1797         int size = offset + lcme_size;
1798
1799         LASSERTF(buf->lb_len >= size,
1800                  "buffer len %d is less than real size %d\n",
1801                  (int)buf->lb_len, size);
1802
1803         lcm = buf->lb_buf;
1804         lcm->lcm_magic = cpu_to_le32(LOV_MAGIC_COMP_V1);
1805         lcm->lcm_size = cpu_to_le32(size);
1806         lcm->lcm_layout_gen = cpu_to_le32(1);
1807         lcm->lcm_flags = 0;
1808         lcm->lcm_entry_count = cpu_to_le16(1);
1809
1810         lcme = &lcm->lcm_entries[0];
1811         lcme->lcme_id = cpu_to_le32(ol->ol_comp_id);
1812         lcme->lcme_flags = cpu_to_le32(LCME_FL_INIT);
1813         lcme->lcme_extent.e_start = cpu_to_le64(ol->ol_comp_start);
1814         lcme->lcme_extent.e_end = cpu_to_le64(ol->ol_comp_end);
1815         lcme->lcme_offset = cpu_to_le32(offset);
1816         lcme->lcme_size = cpu_to_le32(lcme_size);
1817         if (ol->ol_stripe_count > 1)
1818                 pattern |= LOV_PATTERN_F_HOLE;
1819
1820         *lmm = buf->lb_buf + offset;
1821         *objs = __lfsck_layout_new_v1_lovea(*lmm, lfsck_dto2fid(parent),
1822                                             ol->ol_stripe_size, ea_off,
1823                                             pattern, ol->ol_stripe_count);
1824
1825         return size;
1826 }
1827
1828 static int lfsck_layout_add_comp_comp(const struct lu_env *env,
1829                                      struct lfsck_instance *lfsck,
1830                                      struct thandle *handle,
1831                                      struct ost_layout *ol,
1832                                      struct dt_object *parent,
1833                                      const struct lu_fid *cfid,
1834                                      struct lu_buf *buf, __u32 ost_idx,
1835                                      __u32 ea_off, int pos)
1836 {
1837         struct lov_comp_md_v1 *lcm = buf->lb_buf;
1838         struct lov_comp_md_entry_v1 *lcme;
1839         struct lov_mds_md_v1 *lmm;
1840         struct lov_ost_data_v1 *objs;
1841         int added = sizeof(*lcme) +
1842                     lov_mds_md_size(ol->ol_stripe_count, LOV_MAGIC_V1);
1843         int size = le32_to_cpu(lcm->lcm_size) + added;
1844         int rc;
1845         int i;
1846         __u32 offset;
1847         __u32 pattern = LOV_PATTERN_RAID0;
1848         __u16 count = le16_to_cpu(lcm->lcm_entry_count);
1849         ENTRY;
1850
1851         lu_buf_check_and_grow(buf, size);
1852         /* set the lcm again because lu_buf_check_and_grow() may
1853          * have reallocated the buf. */
1854         lcm = buf->lb_buf;
1855         lcm->lcm_size = cpu_to_le32(size);
1856         le32_add_cpu(&lcm->lcm_layout_gen, 1);
1857         lcm->lcm_entry_count = cpu_to_le16(count + 1);
1858
1859         /* 1. Move the component bodies from [pos, count-1] to [pos+1, count]
1860          *    with distance of 'added'. */
1861         if (pos < count) {
1862                 size = 0;
1863                 for (i = pos; i < count; i++) {
1864                         lcme = &lcm->lcm_entries[i];
1865                         size += le32_to_cpu(lcme->lcme_size);
1866                 }
1867
1868                 offset = le32_to_cpu(lcm->lcm_entries[pos].lcme_offset);
1869                 memmove(buf->lb_buf + offset + added,
1870                         buf->lb_buf + offset, size);
1871         }
1872
1873         size = 0;
1874         /* 2. Move the component header [0, pos-1] to [0, pos-1] with distance
1875          *    of 'sizeof(struct lov_comp_md_entry_v1)' */
1876         if (pos > 0) {
1877                 for (i = 0; i < pos; i++) {
1878                         lcme = &lcm->lcm_entries[i];
1879                         size += le32_to_cpu(lcme->lcme_size);
1880                 }
1881
1882                 offset = le32_to_cpu(lcm->lcm_entries[0].lcme_offset);
1883                 memmove(buf->lb_buf + offset + sizeof(*lcme),
1884                         buf->lb_buf + offset, size);
1885         }
1886
1887         /* 3. Recalculate the enter offset for the component [pos, count-1] */
1888         for (i = count - 1; i >= pos; i--) {
1889                 lcm->lcm_entries[i + 1] = lcm->lcm_entries[i];
1890                 lcm->lcm_entries[i + 1].lcme_offset =
1891                         cpu_to_le32(le32_to_cpu(lcm->lcm_entries[i + 1].
1892                                                 lcme_offset) + added);
1893         }
1894
1895         /* 4. Recalculate the enter offset for the component [0, pos) */
1896         for (i = 0; i < pos; i++) {
1897                 lcm->lcm_entries[i].lcme_offset =
1898                         cpu_to_le32(le32_to_cpu(lcm->lcm_entries[i].
1899                                                 lcme_offset) + sizeof(*lcme));
1900         }
1901
1902         offset = sizeof(*lcm) + sizeof(*lcme) * (count + 1) + size;
1903         /* 4. Insert the new component header (entry) at the slot 'pos'. */
1904         lcme = &lcm->lcm_entries[pos];
1905         lcme->lcme_id = cpu_to_le32(ol->ol_comp_id);
1906         lcme->lcme_flags = cpu_to_le32(LCME_FL_INIT);
1907         lcme->lcme_extent.e_start = cpu_to_le64(ol->ol_comp_start);
1908         lcme->lcme_extent.e_end = cpu_to_le64(ol->ol_comp_end);
1909         lcme->lcme_offset = cpu_to_le32(offset);
1910         lcme->lcme_size = cpu_to_le32(lov_mds_md_size(ol->ol_stripe_count,
1911                                                       LOV_MAGIC_V1));
1912
1913         if (ol->ol_stripe_count > 1)
1914                 pattern |= LOV_PATTERN_F_HOLE;
1915
1916         lmm = buf->lb_buf + offset;
1917         /* 5. Insert teh new component body at the 'offset'. */
1918         objs = __lfsck_layout_new_v1_lovea(lmm, lfsck_dto2fid(parent),
1919                                            ol->ol_stripe_size, ea_off,
1920                                            pattern, ol->ol_stripe_count);
1921
1922         rc = lfsck_layout_refill_lovea(env, lfsck, handle, parent, cfid, buf,
1923                                        lmm, objs, LU_XATTR_REPLACE, ost_idx,
1924                                        le32_to_cpu(lcm->lcm_size));
1925
1926         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant add new COMP for "
1927                DFID": parent "DFID", OST-index %u, stripe-index %u, "
1928                "stripe_size %u, stripe_count %u, comp_id %u, comp_start %llu, "
1929                "comp_end %llu, %s LOV EA hole: rc = %d\n",
1930                lfsck_lfsck2name(lfsck), PFID(cfid), PFID(lfsck_dto2fid(parent)),
1931                ost_idx, ea_off, ol->ol_stripe_size, ol->ol_stripe_count,
1932                ol->ol_comp_id, ol->ol_comp_start, ol->ol_comp_end,
1933                le32_to_cpu(lmm->lmm_pattern) & LOV_PATTERN_F_HOLE ?
1934                "with" : "without", rc);
1935
1936         RETURN(rc);
1937 }
1938
1939 static int lfsck_layout_extend_v1v3_lovea(const struct lu_env *env,
1940                                           struct lfsck_instance *lfsck,
1941                                           struct thandle *handle,
1942                                           struct ost_layout *ol,
1943                                           struct dt_object *parent,
1944                                           const struct lu_fid *cfid,
1945                                           struct lu_buf *buf, __u32 ost_idx,
1946                                           __u32 ea_off)
1947 {
1948         struct lov_mds_md_v1 *lmm = buf->lb_buf;
1949         struct lov_ost_data_v1 *objs;
1950         __u16 count = le16_to_cpu(lmm->lmm_stripe_count);
1951         __u32 magic = le32_to_cpu(lmm->lmm_magic);
1952         int size;
1953         int gap;
1954         int rc;
1955         ENTRY;
1956
1957         /* The original LOVEA maybe re-generated via old filter_fid, at
1958          * that time, we do not know the stripe count and stripe size. */
1959         if (ol->ol_stripe_count > count)
1960                 count = ol->ol_stripe_count;
1961         if (ol->ol_stripe_size != 0 &&
1962             ol->ol_stripe_size != le32_to_cpu(lmm->lmm_stripe_size))
1963                 lmm->lmm_stripe_size = cpu_to_le32(ol->ol_stripe_size);
1964
1965         if (magic == LOV_MAGIC_V1)
1966                 objs = &lmm->lmm_objects[count];
1967         else
1968                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[count];
1969
1970         gap = ea_off - count;
1971         if (gap >= 0)
1972                 count = ea_off + 1;
1973
1974         size = lov_mds_md_size(count, magic);
1975         LASSERTF(buf->lb_len >= size,
1976                  "buffer len %d is less than real size %d\n",
1977                  (int)buf->lb_len, size);
1978
1979         if (gap > 0) {
1980                 memset(objs, 0, gap * sizeof(*objs));
1981                 lmm->lmm_pattern |= cpu_to_le32(LOV_PATTERN_F_HOLE);
1982         }
1983
1984         lmm->lmm_layout_gen = cpu_to_le16(le16_to_cpu(lmm->lmm_layout_gen) + 1);
1985         lmm->lmm_stripe_count = cpu_to_le16(count);
1986         objs += gap;
1987
1988         rc = lfsck_layout_refill_lovea(env, lfsck, handle, parent, cfid, buf,
1989                                 lmm, objs, LU_XATTR_REPLACE, ost_idx, size);
1990
1991         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant extend layout EA for "
1992                DFID": parent "DFID", OST-index %u, stripe-index %u, "
1993                "stripe_size %u, stripe_count %u, comp_id %u, comp_start %llu, "
1994                "comp_end %llu, %s LOV EA hole: rc = %d\n",
1995                lfsck_lfsck2name(lfsck), PFID(cfid), PFID(lfsck_dto2fid(parent)),
1996                ost_idx, ea_off, ol->ol_stripe_size, ol->ol_stripe_count,
1997                ol->ol_comp_id, ol->ol_comp_start, ol->ol_comp_end,
1998                le32_to_cpu(lmm->lmm_pattern) & LOV_PATTERN_F_HOLE ?
1999                "with" : "without", rc);
2000
2001         RETURN(rc);
2002 }
2003
2004 /**
2005  * \retval       +1: repaired
2006  * \retval        0: did nothing
2007  * \retval      -ve: on error
2008  */
2009 static int lfsck_layout_update_lovea(const struct lu_env *env,
2010                                      struct lfsck_instance *lfsck,
2011                                      struct thandle *handle,
2012                                      struct ost_layout *ol,
2013                                      struct dt_object *parent,
2014                                      const struct lu_fid *cfid,
2015                                      struct lu_buf *buf, int fl,
2016                                      __u32 ost_idx, __u32 ea_off)
2017 {
2018         struct lov_mds_md_v1 *lmm = NULL;
2019         struct lov_ost_data_v1 *objs = NULL;
2020         int rc = 0;
2021         ENTRY;
2022
2023         if (ol->ol_comp_id != 0)
2024                 rc = lfsck_layout_new_comp_lovea(env, ol, parent, buf, ea_off,
2025                                                 &lmm, &objs);
2026         else
2027                 rc = lfsck_layout_new_v1_lovea(env, lfsck, ol, parent, buf,
2028                                                ea_off, &lmm, &objs);
2029
2030         if (rc > 0)
2031                 rc = lfsck_layout_refill_lovea(env, lfsck, handle, parent, cfid,
2032                                                buf, lmm, objs, fl, ost_idx, rc);
2033
2034         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant created layout EA for "
2035                DFID": parent "DFID", OST-index %u, stripe-index %u, "
2036                "stripe_size %u, stripe_count %u, comp_id %u, comp_start %llu, "
2037                "comp_end %llu, fl %d, %s LOV EA hole: rc = %d\n",
2038                lfsck_lfsck2name(lfsck), PFID(cfid), PFID(lfsck_dto2fid(parent)),
2039                ost_idx, ea_off, ol->ol_stripe_size, ol->ol_stripe_count,
2040                ol->ol_comp_id, ol->ol_comp_start, ol->ol_comp_end, fl,
2041                le32_to_cpu(lmm->lmm_pattern) & LOV_PATTERN_F_HOLE ?
2042                "with" : "without", rc);
2043
2044         RETURN(rc);
2045 }
2046
2047 static int __lfsck_layout_update_pfid(const struct lu_env *env,
2048                                       struct dt_object *child,
2049                                       const struct lu_fid *pfid,
2050                                       const struct ost_layout *ol, __u32 offset)
2051 {
2052         struct dt_device        *dev    = lfsck_obj2dev(child);
2053         struct filter_fid       *ff     = &lfsck_env_info(env)->lti_ff;
2054         struct thandle          *handle;
2055         struct lu_buf            buf    = { NULL };
2056         int                      rc;
2057
2058         ff->ff_parent.f_seq = cpu_to_le64(pfid->f_seq);
2059         ff->ff_parent.f_oid = cpu_to_le32(pfid->f_oid);
2060         /* Currently, the filter_fid::ff_parent::f_ver is not the real parent
2061          * MDT-object's FID::f_ver, instead it is the OST-object index in its
2062          * parent MDT-object's layout EA. */
2063         ff->ff_parent.f_stripe_idx = cpu_to_le32(offset);
2064         ost_layout_cpu_to_le(&ff->ff_layout, ol);
2065         lfsck_buf_init(&buf, ff, sizeof(*ff));
2066
2067         handle = dt_trans_create(env, dev);
2068         if (IS_ERR(handle))
2069                 RETURN(PTR_ERR(handle));
2070
2071         rc = dt_declare_xattr_set(env, child, &buf, XATTR_NAME_FID, 0, handle);
2072         if (rc != 0)
2073                 GOTO(stop, rc);
2074
2075         rc = dt_trans_start_local(env, dev, handle);
2076         if (rc != 0)
2077                 GOTO(stop, rc);
2078
2079         rc = dt_xattr_set(env, child, &buf, XATTR_NAME_FID, 0, handle);
2080
2081         GOTO(stop, rc);
2082
2083 stop:
2084         dt_trans_stop(env, dev, handle);
2085
2086         return rc;
2087 }
2088
2089 /**
2090  * \retval       +1: repaired
2091  * \retval        0: did nothing
2092  * \retval      -ve: on error
2093  */
2094 static int lfsck_layout_update_pfid(const struct lu_env *env,
2095                                     struct lfsck_component *com,
2096                                     struct dt_object *parent,
2097                                     struct lu_fid *cfid,
2098                                     struct dt_device *cdev,
2099                                     struct ost_layout *ol, __u32 ea_off)
2100 {
2101         struct dt_object        *child;
2102         int                      rc     = 0;
2103         ENTRY;
2104
2105         child = lfsck_object_find_by_dev(env, cdev, cfid);
2106         if (IS_ERR(child))
2107                 RETURN(PTR_ERR(child));
2108
2109         rc = __lfsck_layout_update_pfid(env, child,
2110                                         lu_object_fid(&parent->do_lu),
2111                                         ol, ea_off);
2112         lfsck_object_put(env, child);
2113
2114         RETURN(rc == 0 ? 1 : rc);
2115 }
2116
2117 static int lfsck_lovea_size(struct ost_layout *ol, __u32 ea_off)
2118 {
2119         if (ol->ol_comp_id != 0)
2120                 return sizeof(struct lov_comp_md_v1) +
2121                        sizeof(struct lov_comp_md_entry_v1) +
2122                        lov_mds_md_size(ol->ol_stripe_count, LOV_MAGIC_V1);
2123
2124         if (ol->ol_stripe_count != 0)
2125                 return lov_mds_md_size(ol->ol_stripe_count, LOV_MAGIC_V1);
2126
2127         return lov_mds_md_size(ea_off + 1, LOV_MAGIC_V1);
2128 }
2129
2130 /**
2131  * This function will create the MDT-object with the given (partial) LOV EA.
2132  *
2133  * Under some data corruption cases, the MDT-object of the file may be lost,
2134  * but its OST-objects, or some of them are there. The layout LFSCK needs to
2135  * re-create the MDT-object with the orphan OST-object(s) information.
2136  *
2137  * On the other hand, the LFSCK may has created some OST-object for repairing
2138  * dangling LOV EA reference, but as the LFSCK processing, it may find that
2139  * the old OST-object is there and should replace the former new created OST
2140  * object. Unfortunately, some others have modified such newly created object.
2141  * To keep the data (both new and old), the LFSCK will create MDT-object with
2142  * new FID to reference the original OST-object.
2143  *
2144  * \param[in] env       pointer to the thread context
2145  * \param[in] com       pointer to the lfsck component
2146  * \param[in] ltd       pointer to target device descriptor
2147  * \param[in] rec       pointer to the record for the orphan OST-object
2148  * \param[in] cfid      pointer to FID for the orphan OST-object
2149  * \param[in] infix     additional information, such as the FID for original
2150  *                      MDT-object and the stripe offset in the LOV EA
2151  * \param[in] type      the type for describing why the orphan MDT-object is
2152  *                      created. The rules are as following:
2153  *
2154  *  type "C":           Multiple OST-objects claim the same MDT-object and the
2155  *                      same slot in the layout EA. Then the LFSCK will create
2156  *                      new MDT-object(s) to hold the conflict OST-object(s).
2157  *
2158  *  type "N":           The orphan OST-object does not know which one was the
2159  *                      real parent MDT-object, so the LFSCK uses new FID for
2160  *                      its parent MDT-object.
2161  *
2162  *  type "R":           The orphan OST-object knows its parent MDT-object FID,
2163  *                      but does not know the position (the file name) in the
2164  *                      layout.
2165  *
2166  *  type "D":           The MDT-object is a directory, it may knows its parent
2167  *                      but because there is no valid linkEA, the LFSCK cannot
2168  *                      know where to put it back to the namespace.
2169  *  type "O":           The MDT-object has no linkEA, and there is no name
2170  *                      entry that references the MDT-object.
2171  *
2172  *  type "P":           The orphan object to be created was a parent directory
2173  *                      of some MDT-object which linkEA shows that the @orphan
2174  *                      object is missing.
2175  *
2176  * The orphan name will be like:
2177  * ${FID}-${infix}-${type}-${conflict_version}
2178  *
2179  * \param[in] ea_off    the stripe offset in the LOV EA
2180  *
2181  * \retval              positive on repaired something
2182  * \retval              0 if needs to repair nothing
2183  * \retval              negative error number on failure
2184  */
2185 static int lfsck_layout_recreate_parent(const struct lu_env *env,
2186                                         struct lfsck_component *com,
2187                                         struct lfsck_tgt_desc *ltd,
2188                                         struct lu_orphan_rec_v2 *rec,
2189                                         struct lu_fid *cfid,
2190                                         const char *infix,
2191                                         const char *type,
2192                                         __u32 ea_off)
2193 {
2194         struct lfsck_thread_info        *info   = lfsck_env_info(env);
2195         struct dt_insert_rec            *dtrec  = &info->lti_dt_rec;
2196         char                            *name   = info->lti_key;
2197         struct lu_attr                  *la     = &info->lti_la2;
2198         struct dt_object_format         *dof    = &info->lti_dof;
2199         struct lfsck_instance           *lfsck  = com->lc_lfsck;
2200         struct ost_layout               *ol     = &rec->lor_layout;
2201         struct lu_fid                   *pfid   = &rec->lor_rec.lor_fid;
2202         struct lu_fid                   *tfid   = &info->lti_fid3;
2203         struct dt_device                *dev    = lfsck->li_bottom;
2204         struct dt_object                *lpf    = lfsck->li_lpf_obj;
2205         struct dt_object                *pobj   = NULL;
2206         struct dt_object                *cobj   = NULL;
2207         struct thandle                  *th     = NULL;
2208         struct lu_buf                   *ea_buf = &info->lti_big_buf;
2209         struct lu_buf                    lov_buf;
2210         struct lfsck_lock_handle        *llh    = &info->lti_llh;
2211         struct linkea_data               ldata  = { NULL };
2212         struct lu_buf                    linkea_buf;
2213         const struct lu_name            *pname;
2214         int                              size   = 0;
2215         int                              idx    = 0;
2216         int                              rc     = 0;
2217         ENTRY;
2218
2219         if (unlikely(lpf == NULL))
2220                 GOTO(log, rc = -ENXIO);
2221
2222         /* We use two separated transactions to repair the inconsistency.
2223          *
2224          * 1) create the MDT-object locally.
2225          * 2) update the OST-object's PFID EA if necessary.
2226          *
2227          * If 1) succeed, but 2) failed, then the OST-object's PFID EA will be
2228          * updated when the layout LFSCK run next time.
2229          *
2230          * If 1) failed, but 2) succeed, then such MDT-object will be re-created
2231          * when the layout LFSCK run next time. */
2232
2233         if (fid_is_zero(pfid)) {
2234                 rc = lfsck_fid_alloc(env, lfsck, pfid, false);
2235                 if (rc != 0)
2236                         GOTO(log, rc);
2237
2238                 cobj = lfsck_object_find_by_dev(env, ltd->ltd_tgt, cfid);
2239                 if (IS_ERR(cobj))
2240                         GOTO(log, rc = PTR_ERR(cobj));
2241         }
2242
2243         pobj = lfsck_object_find_by_dev(env, dev, pfid);
2244         if (IS_ERR(pobj))
2245                 GOTO(log, rc = PTR_ERR(pobj));
2246
2247         LASSERT(infix != NULL);
2248         LASSERT(type != NULL);
2249
2250         memset(la, 0, sizeof(*la));
2251         la->la_uid = rec->lor_rec.lor_uid;
2252         la->la_gid = rec->lor_rec.lor_gid;
2253         la->la_mode = S_IFREG | S_IRUSR;
2254         la->la_valid = LA_MODE | LA_UID | LA_GID;
2255
2256         memset(dof, 0, sizeof(*dof));
2257         dof->dof_type = dt_mode_to_dft(S_IFREG);
2258         /* Because the dof->dof_reg.striped = 0, the LOD will not create
2259          * the stripe(s). The LFSCK will specify the LOV EA via
2260          * lfsck_layout_update_lovea(). */
2261
2262         size = lfsck_lovea_size(ol, ea_off);
2263         if (ea_buf->lb_len < size) {
2264                 lu_buf_realloc(ea_buf, size);
2265                 if (ea_buf->lb_buf == NULL)
2266                         GOTO(log, rc = -ENOMEM);
2267         }
2268
2269 again:
2270         do {
2271                 snprintf(name, NAME_MAX, DFID"%s-%s-%d", PFID(pfid), infix,
2272                          type, idx++);
2273                 rc = dt_lookup(env, lfsck->li_lpf_obj, (struct dt_rec *)tfid,
2274                                (const struct dt_key *)name);
2275                 if (rc != 0 && rc != -ENOENT)
2276                         GOTO(log, rc);
2277         } while (rc == 0);
2278
2279         rc = lfsck_lock(env, lfsck, lfsck->li_lpf_obj, name, llh,
2280                         MDS_INODELOCK_UPDATE, LCK_PW);
2281         if (rc != 0)
2282                 GOTO(log, rc);
2283
2284         /* Re-check whether the name conflict with othrs after taken
2285          * the ldlm lock. */
2286         rc = dt_lookup(env, lfsck->li_lpf_obj, (struct dt_rec *)tfid,
2287                        (const struct dt_key *)name);
2288         if (unlikely(rc == 0)) {
2289                 lfsck_unlock(llh);
2290                 goto again;
2291         }
2292
2293         if (rc != -ENOENT)
2294                 GOTO(unlock, rc);
2295
2296         pname = lfsck_name_get_const(env, name, strlen(name));
2297         rc = linkea_links_new(&ldata, &lfsck_env_info(env)->lti_linkea_buf,
2298                               pname, lfsck_dto2fid(lfsck->li_lpf_obj));
2299         if (rc != 0)
2300                 GOTO(unlock, rc);
2301
2302         /* The 1st transaction. */
2303         th = dt_trans_create(env, dev);
2304         if (IS_ERR(th))
2305                 GOTO(unlock, rc = PTR_ERR(th));
2306
2307         rc = dt_declare_create(env, pobj, la, NULL, dof, th);
2308         if (rc != 0)
2309                 GOTO(stop, rc);
2310
2311         lfsck_buf_init(&lov_buf, ea_buf->lb_buf, size);
2312         rc = dt_declare_xattr_set(env, pobj, &lov_buf, XATTR_NAME_LOV,
2313                                   LU_XATTR_CREATE, th);
2314         if (rc != 0)
2315                 GOTO(stop, rc);
2316
2317         dtrec->rec_fid = pfid;
2318         dtrec->rec_type = S_IFREG;
2319         rc = dt_declare_insert(env, lpf,
2320                                (const struct dt_rec *)dtrec,
2321                                (const struct dt_key *)name, th);
2322         if (rc != 0)
2323                 GOTO(stop, rc);
2324
2325         lfsck_buf_init(&linkea_buf, ldata.ld_buf->lb_buf,
2326                        ldata.ld_leh->leh_len);
2327         rc = dt_declare_xattr_set(env, pobj, &linkea_buf,
2328                                   XATTR_NAME_LINK, 0, th);
2329         if (rc != 0)
2330                 GOTO(stop, rc);
2331
2332         rc = dt_trans_start_local(env, dev, th);
2333         if (rc != 0)
2334                 GOTO(stop, rc);
2335
2336         dt_write_lock(env, pobj, 0);
2337         rc = dt_create(env, pobj, la, NULL, dof, th);
2338         if (rc == 0)
2339                 rc = lfsck_layout_update_lovea(env, lfsck, th, ol, pobj, cfid,
2340                         &lov_buf, LU_XATTR_CREATE, ltd->ltd_index, ea_off);
2341         dt_write_unlock(env, pobj);
2342         if (rc < 0)
2343                 GOTO(stop, rc);
2344
2345         rc = dt_insert(env, lpf, (const struct dt_rec *)dtrec,
2346                        (const struct dt_key *)name, th, 1);
2347         if (rc != 0)
2348                 GOTO(stop, rc);
2349
2350         rc = dt_xattr_set(env, pobj, &linkea_buf, XATTR_NAME_LINK, 0, th);
2351         if (rc == 0 && cobj != NULL) {
2352                 dt_trans_stop(env, dev, th);
2353                 th = NULL;
2354
2355                 /* The 2nd transaction. */
2356                 rc = __lfsck_layout_update_pfid(env, cobj, pfid, ol, ea_off);
2357         }
2358
2359         GOTO(stop, rc);
2360
2361 stop:
2362         if (th != NULL)
2363                 dt_trans_stop(env, dev, th);
2364
2365 unlock:
2366         lfsck_unlock(llh);
2367
2368 log:
2369         if (cobj != NULL && !IS_ERR(cobj))
2370                 lfsck_object_put(env, cobj);
2371         if (pobj != NULL && !IS_ERR(pobj))
2372                 lfsck_object_put(env, pobj);
2373
2374         if (rc < 0)
2375                 CDEBUG(D_LFSCK, "%s layout LFSCK assistant failed to "
2376                        "recreate the lost MDT-object: parent "DFID
2377                        ", child "DFID", OST-index %u, stripe-index %u, "
2378                        "infix %s, type %s: rc = %d\n",
2379                        lfsck_lfsck2name(lfsck), PFID(pfid), PFID(cfid),
2380                        ltd->ltd_index, ea_off, infix, type, rc);
2381
2382         return rc >= 0 ? 1 : rc;
2383 }
2384
2385 static int lfsck_layout_master_conditional_destroy(const struct lu_env *env,
2386                                                    struct lfsck_component *com,
2387                                                    const struct lu_fid *fid,
2388                                                    __u32 index)
2389 {
2390         struct lfsck_thread_info *info  = lfsck_env_info(env);
2391         struct lfsck_request     *lr    = &info->lti_lr;
2392         struct lfsck_instance    *lfsck = com->lc_lfsck;
2393         struct lfsck_tgt_desc    *ltd;
2394         struct ptlrpc_request    *req;
2395         struct lfsck_request     *tmp;
2396         struct obd_export        *exp;
2397         int                       rc    = 0;
2398         ENTRY;
2399
2400         ltd = lfsck_tgt_get(&lfsck->li_ost_descs, index);
2401         if (unlikely(ltd == NULL))
2402                 RETURN(-ENXIO);
2403
2404         exp = ltd->ltd_exp;
2405         if (!(exp_connect_flags(exp) & OBD_CONNECT_LFSCK))
2406                 GOTO(put, rc = -EOPNOTSUPP);
2407
2408         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_LFSCK_NOTIFY);
2409         if (req == NULL)
2410                 GOTO(put, rc = -ENOMEM);
2411
2412         rc = ptlrpc_request_pack(req, LUSTRE_OBD_VERSION, LFSCK_NOTIFY);
2413         if (rc != 0) {
2414                 ptlrpc_request_free(req);
2415
2416                 GOTO(put, rc);
2417         }
2418
2419         memset(lr, 0, sizeof(*lr));
2420         lr->lr_event = LE_CONDITIONAL_DESTROY;
2421         lr->lr_active = LFSCK_TYPE_LAYOUT;
2422         lr->lr_fid = *fid;
2423
2424         tmp = req_capsule_client_get(&req->rq_pill, &RMF_LFSCK_REQUEST);
2425         *tmp = *lr;
2426         ptlrpc_request_set_replen(req);
2427
2428         rc = ptlrpc_queue_wait(req);
2429         ptlrpc_req_finished(req);
2430
2431         GOTO(put, rc);
2432
2433 put:
2434         lfsck_tgt_put(ltd);
2435
2436         return rc;
2437 }
2438
2439 static int lfsck_layout_slave_conditional_destroy(const struct lu_env *env,
2440                                                   struct lfsck_component *com,
2441                                                   struct lfsck_request *lr)
2442 {
2443         struct lfsck_thread_info        *info   = lfsck_env_info(env);
2444         struct lu_attr                  *la     = &info->lti_la;
2445         union ldlm_policy_data          *policy = &info->lti_policy;
2446         struct ldlm_res_id              *resid  = &info->lti_resid;
2447         struct lfsck_instance           *lfsck  = com->lc_lfsck;
2448         struct dt_device                *dev    = lfsck->li_bottom;
2449         struct lu_fid                   *fid    = &lr->lr_fid;
2450         struct dt_object                *obj;
2451         struct thandle                  *th     = NULL;
2452         struct lustre_handle             lh     = { 0 };
2453         __u64                            flags  = 0;
2454         int                              rc     = 0;
2455         ENTRY;
2456
2457         obj = lfsck_object_find_by_dev(env, dev, fid);
2458         if (IS_ERR(obj))
2459                 RETURN(PTR_ERR(obj));
2460
2461         dt_read_lock(env, obj, 0);
2462         if (dt_object_exists(obj) == 0 ||
2463             lfsck_is_dead_obj(obj)) {
2464                 dt_read_unlock(env, obj);
2465
2466                 GOTO(put, rc = -ENOENT);
2467         }
2468
2469         /* Get obj's attr without lock firstly. */
2470         rc = dt_attr_get(env, obj, la);
2471         dt_read_unlock(env, obj);
2472         if (rc != 0)
2473                 GOTO(put, rc);
2474
2475         if (likely(la->la_ctime != 0 || la->la_mode & S_ISUID))
2476                 GOTO(put, rc = -ETXTBSY);
2477
2478         /* Acquire extent lock on [0, EOF] to sync with all possible written. */
2479         LASSERT(lfsck->li_namespace != NULL);
2480
2481         memset(policy, 0, sizeof(*policy));
2482         policy->l_extent.end = OBD_OBJECT_EOF;
2483         ost_fid_build_resid(fid, resid);
2484         rc = ldlm_cli_enqueue_local(lfsck->li_namespace, resid, LDLM_EXTENT,
2485                                     policy, LCK_EX, &flags, ldlm_blocking_ast,
2486                                     ldlm_completion_ast, NULL, NULL, 0,
2487                                     LVB_T_NONE, NULL, &lh);
2488         if (rc != ELDLM_OK)
2489                 GOTO(put, rc = -EIO);
2490
2491         dt_write_lock(env, obj, 0);
2492         /* Get obj's attr within lock again. */
2493         rc = dt_attr_get(env, obj, la);
2494         if (rc != 0)
2495                 GOTO(unlock, rc);
2496
2497         if (la->la_ctime != 0)
2498                 GOTO(unlock, rc = -ETXTBSY);
2499
2500         th = dt_trans_create(env, dev);
2501         if (IS_ERR(th))
2502                 GOTO(unlock, rc = PTR_ERR(th));
2503
2504         rc = dt_declare_ref_del(env, obj, th);
2505         if (rc != 0)
2506                 GOTO(stop, rc);
2507
2508         rc = dt_declare_destroy(env, obj, th);
2509         if (rc != 0)
2510                 GOTO(stop, rc);
2511
2512         rc = dt_trans_start_local(env, dev, th);
2513         if (rc != 0)
2514                 GOTO(stop, rc);
2515
2516         rc = dt_ref_del(env, obj, th);
2517         if (rc != 0)
2518                 GOTO(stop, rc);
2519
2520         rc = dt_destroy(env, obj, th);
2521         if (rc == 0)
2522                 CDEBUG(D_LFSCK, "%s: layout LFSCK destroyed the empty "
2523                        "OST-object "DFID" that was created for reparing "
2524                        "dangling referenced case. But the original missing "
2525                        "OST-object is found now.\n",
2526                        lfsck_lfsck2name(lfsck), PFID(fid));
2527
2528         GOTO(stop, rc);
2529
2530 stop:
2531         dt_trans_stop(env, dev, th);
2532
2533 unlock:
2534         dt_write_unlock(env, obj);
2535         ldlm_lock_decref(&lh, LCK_EX);
2536
2537 put:
2538         lfsck_object_put(env, obj);
2539
2540         return rc;
2541 }
2542
2543 /**
2544  * Some OST-object has occupied the specified layout EA slot.
2545  * Such OST-object may be generated by the LFSCK when repair
2546  * dangling referenced MDT-object, which can be indicated by
2547  * attr::la_ctime == 0 but without S_ISUID in la_mode. If it
2548  * is true and such OST-object has not been modified yet, we
2549  * will replace it with the orphan OST-object; otherwise the
2550  * LFSCK will create new MDT-object to reference the orphan.
2551  *
2552  * \retval       +1: repaired
2553  * \retval        0: did nothing
2554  * \retval      -ve: on error
2555  */
2556 static int lfsck_layout_conflict_create(const struct lu_env *env,
2557                                         struct lfsck_component *com,
2558                                         struct lfsck_tgt_desc *ltd,
2559                                         struct lu_orphan_rec_v2 *rec,
2560                                         struct dt_object *parent,
2561                                         struct lu_fid *cfid,
2562                                         struct lu_buf *ea_buf,
2563                                         struct lov_mds_md_v1 *lmm,
2564                                         struct lov_ost_data_v1 *slot,
2565                                         __u32 ea_off, int lovea_size)
2566 {
2567         struct lfsck_thread_info *info          = lfsck_env_info(env);
2568         struct lu_fid            *cfid2         = &info->lti_fid2;
2569         struct ost_id            *oi            = &info->lti_oi;
2570         struct dt_device         *dev           = lfsck_obj2dev(parent);
2571         struct thandle           *th            = NULL;
2572         struct lustre_handle      lh            = { 0 };
2573         __u32                     ost_idx2      = le32_to_cpu(slot->l_ost_idx);
2574         int                       rc            = 0;
2575         ENTRY;
2576
2577         while (CFS_FAIL_TIMEOUT(OBD_FAIL_LFSCK_DELAY3, cfs_fail_val)) {
2578                 if (unlikely(!thread_is_running(&com->lc_lfsck->li_thread)))
2579                         RETURN(0);
2580         }
2581
2582         ostid_le_to_cpu(&slot->l_ost_oi, oi);
2583         rc = ostid_to_fid(cfid2, oi, ost_idx2);
2584         if (rc != 0)
2585                 GOTO(out, rc);
2586
2587         rc = lfsck_ibits_lock(env, com->lc_lfsck, parent, &lh,
2588                               MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR,
2589                               LCK_EX);
2590         if (rc != 0)
2591                 GOTO(out, rc);
2592
2593         rc = lfsck_layout_master_conditional_destroy(env, com, cfid2, ost_idx2);
2594
2595         /* If the conflict OST-obejct is not created for fixing dangling
2596          * referenced MDT-object in former LFSCK check/repair, or it has
2597          * been modified by others, then we cannot destroy it. Re-create
2598          * a new MDT-object for the orphan OST-object. */
2599         if (rc == -ETXTBSY) {
2600                 /* No need the layout lock on the original parent. */
2601                 lfsck_ibits_unlock(&lh, LCK_EX);
2602
2603                 fid_zero(&rec->lor_rec.lor_fid);
2604                 snprintf(info->lti_tmpbuf, sizeof(info->lti_tmpbuf),
2605                          "-"DFID"-%x", PFID(lu_object_fid(&parent->do_lu)),
2606                          ea_off);
2607                 rc = lfsck_layout_recreate_parent(env, com, ltd, rec, cfid,
2608                                                 info->lti_tmpbuf, "C", ea_off);
2609
2610                 RETURN(rc);
2611         }
2612
2613         if (rc != 0 && rc != -ENOENT)
2614                 GOTO(unlock, rc);
2615
2616         th = dt_trans_create(env, dev);
2617         if (IS_ERR(th))
2618                 GOTO(unlock, rc = PTR_ERR(th));
2619
2620         rc = dt_declare_xattr_set(env, parent, ea_buf, XATTR_NAME_LOV,
2621                                   LU_XATTR_REPLACE, th);
2622         if (rc != 0)
2623                 GOTO(stop, rc);
2624
2625         rc = dt_trans_start_local(env, dev, th);
2626         if (rc != 0)
2627                 GOTO(stop, rc);
2628
2629         dt_write_lock(env, parent, 0);
2630         lmm->lmm_layout_gen = cpu_to_le16(le16_to_cpu(lmm->lmm_layout_gen) + 1);
2631         rc = lfsck_layout_refill_lovea(env, com->lc_lfsck, th, parent, cfid,
2632                                        ea_buf, lmm, slot, LU_XATTR_REPLACE,
2633                                        ltd->ltd_index, lovea_size);
2634         dt_write_unlock(env, parent);
2635
2636         GOTO(stop, rc);
2637
2638 stop:
2639         dt_trans_stop(env, dev, th);
2640
2641 unlock:
2642         lfsck_ibits_unlock(&lh, LCK_EX);
2643
2644 out:
2645         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant replaced the conflict "
2646                "OST-object "DFID" on the OST %x with the orphan "DFID" on "
2647                "the OST %x: parent "DFID", stripe-index %u: rc = %d\n",
2648                lfsck_lfsck2name(com->lc_lfsck), PFID(cfid2), ost_idx2,
2649                PFID(cfid), ltd->ltd_index, PFID(lfsck_dto2fid(parent)),
2650                ea_off, rc);
2651
2652         return rc >= 0 ? 1 : rc;
2653 }
2654
2655 /**
2656  * \retval       +1: repaired
2657  * \retval        0: did nothing
2658  * \retval      -ve: on error
2659  */
2660 static int lfsck_layout_recreate_lovea(const struct lu_env *env,
2661                                        struct lfsck_component *com,
2662                                        struct lfsck_tgt_desc *ltd,
2663                                        struct lu_orphan_rec_v2 *rec,
2664                                        struct dt_object *parent,
2665                                        struct lu_fid *cfid,
2666                                        __u32 ost_idx, __u32 ea_off)
2667 {
2668         struct lfsck_thread_info *info          = lfsck_env_info(env);
2669         struct lu_buf            *buf           = &info->lti_big_buf;
2670         struct lu_fid            *fid           = &info->lti_fid2;
2671         struct ost_id            *oi            = &info->lti_oi;
2672         struct lfsck_instance    *lfsck         = com->lc_lfsck;
2673         struct dt_device         *dt            = lfsck_obj2dev(parent);
2674         struct lfsck_bookmark    *bk            = &lfsck->li_bookmark_ram;
2675         struct ost_layout        *ol            = &rec->lor_layout;
2676         struct lov_comp_md_v1    *lcm           = NULL;
2677         struct lov_comp_md_entry_v1 *lcme       = NULL;
2678         struct thandle           *handle        = NULL;
2679         size_t                    lovea_size;
2680         struct lov_mds_md_v1     *lmm;
2681         struct lov_ost_data_v1   *objs;
2682         struct lustre_handle      lh            = { 0 };
2683         __u32                     magic;
2684         __u32 flags = 0;
2685         int                       fl            = 0;
2686         int                       rc            = 0;
2687         int                       rc1;
2688         int                       i;
2689         __u16                     count;
2690         bool                      locked        = false;
2691         ENTRY;
2692
2693         rc = lfsck_ibits_lock(env, lfsck, parent, &lh,
2694                               MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR,
2695                               LCK_EX);
2696         if (rc != 0) {
2697                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant failed to recreate "
2698                        "LOV EA for "DFID": parent "DFID", OST-index %u, "
2699                        "stripe-index %u, comp_id %u, comp_start %llu, "
2700                        "comp_end %llu: rc = %d\n",
2701                        lfsck_lfsck2name(lfsck), PFID(cfid),
2702                        PFID(lfsck_dto2fid(parent)), ost_idx, ea_off,
2703                        ol->ol_comp_id, ol->ol_comp_start,
2704                        ol->ol_comp_end, rc);
2705
2706                 RETURN(rc);
2707         }
2708
2709 again:
2710         if (locked) {
2711                 dt_write_unlock(env, parent);
2712                 locked = false;
2713         }
2714
2715         if (handle != NULL) {
2716                 dt_trans_stop(env, dt, handle);
2717                 handle = NULL;
2718         }
2719
2720         if (rc < 0)
2721                 GOTO(unlock_layout, rc);
2722
2723         lovea_size = rc;
2724         if (buf->lb_len < lovea_size) {
2725                 lu_buf_realloc(buf, lovea_size);
2726                 if (buf->lb_buf == NULL)
2727                         GOTO(unlock_layout, rc = -ENOMEM);
2728         }
2729
2730         if (!(bk->lb_param & LPF_DRYRUN)) {
2731                 handle = dt_trans_create(env, dt);
2732                 if (IS_ERR(handle))
2733                         GOTO(unlock_layout, rc = PTR_ERR(handle));
2734
2735                 rc = dt_declare_xattr_set(env, parent, buf, XATTR_NAME_LOV,
2736                                           fl, handle);
2737                 if (rc != 0)
2738                         GOTO(stop, rc);
2739
2740                 rc = dt_trans_start_local(env, dt, handle);
2741                 if (rc != 0)
2742                         GOTO(stop, rc);
2743         }
2744
2745         dt_write_lock(env, parent, 0);
2746         locked = true;
2747         rc = dt_xattr_get(env, parent, buf, XATTR_NAME_LOV);
2748         if (rc == -ERANGE) {
2749                 rc = dt_xattr_get(env, parent, &LU_BUF_NULL, XATTR_NAME_LOV);
2750                 LASSERT(rc != 0);
2751                 goto again;
2752         } else if (rc == -ENODATA || rc == 0) {
2753                 lovea_size = lfsck_lovea_size(ol, ea_off);
2754                 /* If the declared is not big enough, re-try. */
2755                 if (buf->lb_len < lovea_size) {
2756                         rc = lovea_size;
2757                         goto again;
2758                 }
2759                 fl = LU_XATTR_CREATE;
2760         } else if (rc < 0) {
2761                 GOTO(unlock_parent, rc);
2762         } else if (unlikely(buf->lb_len == 0)) {
2763                 goto again;
2764         } else {
2765                 fl = LU_XATTR_REPLACE;
2766                 lovea_size = rc;
2767         }
2768
2769         if (fl == LU_XATTR_CREATE) {
2770                 if (bk->lb_param & LPF_DRYRUN)
2771                         GOTO(unlock_parent, rc = 1);
2772
2773                 LASSERT(buf->lb_len >= lovea_size);
2774
2775                 rc = lfsck_layout_update_lovea(env, lfsck, handle, ol, parent,
2776                                                cfid, buf, fl, ost_idx, ea_off);
2777
2778                 GOTO(unlock_parent, rc);
2779         }
2780
2781         lmm = buf->lb_buf;
2782         rc1 = lfsck_layout_verify_header(parent, lmm);
2783
2784         /* If the LOV EA crashed, the rebuild it. */
2785         if (rc1 == -EINVAL) {
2786                 if (bk->lb_param & LPF_DRYRUN)
2787                         GOTO(unlock_parent, rc = 1);
2788
2789                 LASSERT(buf->lb_len >= lovea_size);
2790
2791                 rc = lfsck_layout_update_lovea(env, lfsck, handle, ol, parent,
2792                                                cfid, buf, fl, ost_idx, ea_off);
2793
2794                 GOTO(unlock_parent, rc);
2795         }
2796
2797         /* For other unknown magic/pattern, keep the current LOV EA. */
2798         if (rc1 != 0)
2799                 GOTO(unlock_parent, rc = rc1);
2800
2801         magic = le32_to_cpu(lmm->lmm_magic);
2802         if (magic == LOV_MAGIC_COMP_V1) {
2803                 __u64 start;
2804                 __u64 end;
2805
2806                 lcm = buf->lb_buf;
2807                 count = le16_to_cpu(lcm->lcm_entry_count);
2808                 for (i = 0; i < count; i++) {
2809                         lcme = &lcm->lcm_entries[i];
2810                         start = le64_to_cpu(lcme->lcme_extent.e_start);
2811                         end = le64_to_cpu(lcme->lcme_extent.e_end);
2812
2813                         if (end <= ol->ol_comp_start)
2814                                 continue;
2815
2816                         if (start >= ol->ol_comp_end)
2817                                 break;
2818
2819                         lmm = buf->lb_buf + le32_to_cpu(lcme->lcme_offset);
2820                         magic = le32_to_cpu(lmm->lmm_magic);
2821                         flags = le32_to_cpu(lcme->lcme_flags);
2822                         goto further;
2823                 }
2824
2825                 rc = lfsck_layout_add_comp_comp(env, lfsck, handle, ol, parent,
2826                                                cfid, buf, ost_idx, ea_off, i);
2827
2828                 GOTO(unlock_parent, rc);
2829         }
2830
2831 further:
2832         count = le16_to_cpu(lmm->lmm_stripe_count);
2833         if (count == 0)
2834                 GOTO(unlock_parent, rc = -EINVAL);
2835         LASSERT(count > 0);
2836
2837         /* Exceed the current end of MDT-object layout EA. Then extend it. */
2838         if (count <= ea_off) {
2839                 if (bk->lb_param & LPF_DRYRUN)
2840                         GOTO(unlock_parent, rc = 1);
2841
2842                 lovea_size = lov_mds_md_size(ea_off + 1, magic);
2843                 /* If the declared is not big enough, re-try. */
2844                 if (buf->lb_len < lovea_size) {
2845                         rc = lovea_size;
2846                         goto again;
2847                 }
2848
2849                 if (lcme && !(flags & LCME_FL_INIT))
2850                         lcme->lcme_flags = cpu_to_le32(flags | LCME_FL_INIT);
2851
2852                 rc = lfsck_layout_extend_v1v3_lovea(env, lfsck, handle, ol,
2853                                         parent, cfid, buf, ost_idx, ea_off);
2854
2855                 GOTO(unlock_parent, rc);
2856         }
2857
2858         LASSERTF(rc > 0, "invalid rc = %d\n", rc);
2859
2860         if (magic == LOV_MAGIC_V1) {
2861                 objs = &lmm->lmm_objects[0];
2862         } else {
2863                 LASSERT(magic == LOV_MAGIC_V3);
2864                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[0];
2865         }
2866
2867         for (i = 0; i < count; i++, objs++) {
2868                 /* The MDT-object was created via lfsck_layout_recover_create()
2869                  * by others before, and we fill the dummy layout EA. */
2870                 if ((lcme && !(flags & LCME_FL_INIT)) ||
2871                      lovea_slot_is_dummy(objs)) {
2872                         if (i != ea_off)
2873                                 continue;
2874
2875                         if (bk->lb_param & LPF_DRYRUN)
2876                                 GOTO(unlock_parent, rc = 1);
2877
2878                         lmm->lmm_layout_gen =
2879                             cpu_to_le16(le16_to_cpu(lmm->lmm_layout_gen) + 1);
2880                         if (lcme) {
2881                                 LASSERT(lcm);
2882
2883                                 if (le32_to_cpu(lmm->lmm_stripe_size) !=
2884                                         ol->ol_stripe_size ||
2885                                     le16_to_cpu(lmm->lmm_stripe_count) !=
2886                                         ol->ol_stripe_count ||
2887                                     le64_to_cpu(lcme->lcme_extent.e_start) !=
2888                                         ol->ol_comp_start ||
2889                                     le64_to_cpu(lcme->lcme_extent.e_end) !=
2890                                         ol->ol_comp_end) {
2891                                         CDEBUG(D_LFSCK, "%s: found invalid "
2892                                         "component for "DFID ": parent "DFID
2893                                         ", stripe-index %u, stripe_size %u, "
2894                                         "stripe_count %u, comp_id %u, "
2895                                         "comp_start %llu, comp_end %llu, "
2896                                         "cur_stripe_size %u, "
2897                                         "cur_stripe_count %u, "
2898                                         "cur_comp_start %llu, "
2899                                         "cur_comp_end %llu\n",
2900                                         lfsck_lfsck2name(lfsck), PFID(cfid),
2901                                         PFID(lfsck_dto2fid(parent)), ea_off,
2902                                         ol->ol_stripe_size,
2903                                         ol->ol_stripe_count, ol->ol_comp_id,
2904                                         ol->ol_comp_start, ol->ol_comp_end,
2905                                         le32_to_cpu(lmm->lmm_stripe_size),
2906                                         le16_to_cpu(lmm->lmm_stripe_count),
2907                                         le64_to_cpu(lcme->lcme_extent.e_start),
2908                                         le64_to_cpu(lcme->lcme_extent.e_end));
2909
2910                                         GOTO(unlock_parent, rc = -EINVAL);
2911                                 }
2912
2913                                 le32_add_cpu(&lcm->lcm_layout_gen, 1);
2914                                 lovea_size = le32_to_cpu(lcm->lcm_size);
2915                                 if (!(flags & LCME_FL_INIT))
2916                                         lcme->lcme_flags = cpu_to_le32(flags |
2917                                                                 LCME_FL_INIT);
2918                         }
2919
2920                         LASSERTF(buf->lb_len >= lovea_size,
2921                                  "buffer len %d is less than real size %d\n",
2922                                  (int)buf->lb_len, (int)lovea_size);
2923
2924                         rc = lfsck_layout_refill_lovea(env, lfsck, handle,
2925                                                 parent, cfid, buf, lmm, objs,
2926                                                 fl, ost_idx, lovea_size);
2927
2928                         CDEBUG(D_LFSCK, "%s layout LFSCK assistant fill "
2929                                "dummy layout slot for "DFID": parent "DFID
2930                                ", OST-index %u, stripe-index %u: rc = %d\n",
2931                                lfsck_lfsck2name(lfsck), PFID(cfid),
2932                                PFID(lfsck_dto2fid(parent)), ost_idx, i, rc);
2933
2934                         GOTO(unlock_parent, rc);
2935                 }
2936
2937                 ostid_le_to_cpu(&objs->l_ost_oi, oi);
2938                 rc = ostid_to_fid(fid, oi, le32_to_cpu(objs->l_ost_idx));
2939                 if (rc != 0) {
2940                         CDEBUG(D_LFSCK, "%s: the parent "DFID" contains "
2941                                "invalid layout EA at the slot %d, index %u\n",
2942                                lfsck_lfsck2name(lfsck),
2943                                PFID(lfsck_dto2fid(parent)), i,
2944                                le32_to_cpu(objs->l_ost_idx));
2945
2946                         GOTO(unlock_parent, rc);
2947                 }
2948
2949                 /* It should be rare case, the slot is there, but the LFSCK
2950                  * does not handle it during the first-phase cycle scanning. */
2951                 if (unlikely(lu_fid_eq(fid, cfid))) {
2952                         if (i == ea_off) {
2953                                 GOTO(unlock_parent, rc = 0);
2954                         } else {
2955                                 /* Rare case that the OST-object index
2956                                  * does not match the parent MDT-object
2957                                  * layout EA. We trust the later one. */
2958                                 if (bk->lb_param & LPF_DRYRUN)
2959                                         GOTO(unlock_parent, rc = 1);
2960
2961                                 dt_write_unlock(env, parent);
2962                                 if (handle != NULL)
2963                                         dt_trans_stop(env, dt, handle);
2964                                 lfsck_ibits_unlock(&lh, LCK_EX);
2965                                 rc = lfsck_layout_update_pfid(env, com, parent,
2966                                                         cfid, ltd->ltd_tgt,
2967                                                         ol, i);
2968
2969                                 CDEBUG(D_LFSCK, "%s layout LFSCK assistant "
2970                                        "updated OST-object's pfid for "DFID
2971                                        ": parent "DFID", OST-index %u, "
2972                                        "stripe-index %u: rc = %d\n",
2973                                        lfsck_lfsck2name(lfsck), PFID(cfid),
2974                                        PFID(lfsck_dto2fid(parent)),
2975                                        ltd->ltd_index, i, rc);
2976
2977                                 RETURN(rc);
2978                         }
2979                 }
2980         }
2981
2982         /* The MDT-object exists, but related layout EA slot is occupied
2983          * by others. */
2984         if (bk->lb_param & LPF_DRYRUN)
2985                 GOTO(unlock_parent, rc = 1);
2986
2987         dt_write_unlock(env, parent);
2988         if (handle != NULL)
2989                 dt_trans_stop(env, dt, handle);
2990         lfsck_ibits_unlock(&lh, LCK_EX);
2991         if (magic == LOV_MAGIC_V1)
2992                 objs = &lmm->lmm_objects[ea_off];
2993         else
2994                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[ea_off];
2995         rc = lfsck_layout_conflict_create(env, com, ltd, rec, parent, cfid,
2996                                           buf, lmm, objs, ea_off, lovea_size);
2997
2998         RETURN(rc);
2999
3000 unlock_parent:
3001         if (locked)
3002                 dt_write_unlock(env, parent);
3003
3004 stop:
3005         if (handle != NULL)
3006                 dt_trans_stop(env, dt, handle);
3007
3008 unlock_layout:
3009         lfsck_ibits_unlock(&lh, LCK_EX);
3010
3011         return rc;
3012 }
3013
3014 static int lfsck_layout_scan_orphan_one(const struct lu_env *env,
3015                                         struct lfsck_component *com,
3016                                         struct lfsck_tgt_desc *ltd,
3017                                         struct lu_orphan_rec_v2 *rec,
3018                                         struct lu_fid *cfid)
3019 {
3020         struct lfsck_layout     *lo     = com->lc_file_ram;
3021         struct lu_fid           *pfid   = &rec->lor_rec.lor_fid;
3022         struct dt_object        *parent = NULL;
3023         __u32                    ea_off = pfid->f_stripe_idx;
3024         int                      rc     = 0;
3025         ENTRY;
3026
3027         if (!fid_is_sane(cfid))
3028                 GOTO(out, rc = -EINVAL);
3029
3030         pfid->f_ver = 0;
3031         if (fid_is_zero(pfid)) {
3032                 rc = lfsck_layout_recreate_parent(env, com, ltd, rec, cfid,
3033                                                   "", "N", ea_off);
3034                 GOTO(out, rc);
3035         }
3036
3037         if (!fid_is_sane(pfid))
3038                 GOTO(out, rc = -EINVAL);
3039
3040         parent = lfsck_object_find_by_dev(env, com->lc_lfsck->li_bottom, pfid);
3041         if (IS_ERR(parent))
3042                 GOTO(out, rc = PTR_ERR(parent));
3043
3044         if (unlikely(dt_object_remote(parent) != 0))
3045                 GOTO(put, rc = -EXDEV);
3046
3047         if (dt_object_exists(parent) == 0) {
3048                 lfsck_object_put(env, parent);
3049                 rc = lfsck_layout_recreate_parent(env, com, ltd, rec, cfid,
3050                                                   "", "R", ea_off);
3051                 GOTO(out, rc);
3052         }
3053
3054         if (!S_ISREG(lu_object_attr(&parent->do_lu)))
3055                 GOTO(put, rc = -EISDIR);
3056
3057         /* The orphan OST-object claims to be the parent's stripe, then
3058          * related dangling record in the trace file is meaningless. */
3059         rc = lfsck_layout_del_dangling_rec(env, com, pfid,
3060                                            rec->lor_layout.ol_comp_id, ea_off);
3061         if (rc && rc != -ENOENT)
3062                 GOTO(put, rc);
3063
3064         rc = lfsck_layout_recreate_lovea(env, com, ltd, rec, parent, cfid,
3065                                          ltd->ltd_index, ea_off);
3066
3067         GOTO(put, rc);
3068
3069 put:
3070         if (rc <= 0)
3071                 lfsck_object_put(env, parent);
3072         else
3073                 /* The layout EA is changed, need to be reloaded next time. */
3074                 dt_object_put_nocache(env, parent);
3075
3076 out:
3077         down_write(&com->lc_sem);
3078         com->lc_new_scanned++;
3079         com->lc_new_checked++;
3080         if (rc > 0) {
3081                 lo->ll_objs_repaired[LLIT_ORPHAN - 1]++;
3082                 rc = 0;
3083         } else if (rc < 0) {
3084                 lo->ll_objs_failed_phase2++;
3085         }
3086         up_write(&com->lc_sem);
3087
3088         return rc;
3089 }
3090
3091 static int lfsck_layout_scan_orphan(const struct lu_env *env,
3092                                     struct lfsck_component *com,
3093                                     struct lfsck_tgt_desc *ltd)
3094 {
3095         struct lfsck_assistant_data     *lad    = com->lc_data;
3096         struct lfsck_instance           *lfsck  = com->lc_lfsck;
3097         struct lfsck_bookmark           *bk     = &lfsck->li_bookmark_ram;
3098         struct lfsck_thread_info        *info   = lfsck_env_info(env);
3099         struct lu_fid                   *fid    = &info->lti_fid;
3100         struct dt_object                *obj;
3101         const struct dt_it_ops          *iops;
3102         struct dt_it                    *di;
3103         int                              rc     = 0;
3104         ENTRY;
3105
3106         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant starts the orphan "
3107                "scanning for OST%04x\n",
3108                lfsck_lfsck2name(lfsck), ltd->ltd_index);
3109
3110         if (cfs_bitmap_check(lad->lad_bitmap, ltd->ltd_index)) {
3111                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant skip the orphan "
3112                        "scanning for OST%04x\n",
3113                        lfsck_lfsck2name(lfsck), ltd->ltd_index);
3114
3115                 RETURN(0);
3116         }
3117
3118         fid->f_seq = fid_idif_seq(0, ltd->ltd_index);
3119         fid->f_oid = fid->f_ver = 0;
3120
3121         obj = lfsck_object_find_by_dev(env, ltd->ltd_tgt, fid);
3122         if (unlikely(IS_ERR(obj)))
3123                 GOTO(log, rc = PTR_ERR(obj));
3124
3125         rc = obj->do_ops->do_index_try(env, obj,
3126                                        &dt_lfsck_layout_orphan_features);
3127         if (rc != 0)
3128                 GOTO(put, rc);
3129
3130         iops = &obj->do_index_ops->dio_it;
3131         di = iops->init(env, obj, 0);
3132         if (IS_ERR(di))
3133                 GOTO(put, rc = PTR_ERR(di));
3134
3135         rc = iops->load(env, di, 0);
3136         if (rc == -ESRCH) {
3137                 /* -ESRCH means that the orphan OST-objects rbtree has been
3138                  * cleanup because of the OSS server restart or other errors. */
3139                 lfsck_lad_set_bitmap(env, com, ltd->ltd_index);
3140                 GOTO(fini, rc);
3141         }
3142
3143         if (rc == 0)
3144                 rc = iops->next(env, di);
3145         else if (rc > 0)
3146                 rc = 0;
3147
3148         if (rc < 0)
3149                 GOTO(fini, rc);
3150
3151         if (rc > 0)
3152                 GOTO(fini, rc = 0);
3153
3154         do {
3155                 struct dt_key           *key;
3156                 struct lu_orphan_rec_v2 *rec = &info->lti_rec;
3157
3158                 if (CFS_FAIL_TIMEOUT(OBD_FAIL_LFSCK_DELAY3, cfs_fail_val) &&
3159                     unlikely(!thread_is_running(&lfsck->li_thread)))
3160                         break;
3161
3162                 key = iops->key(env, di);
3163                 com->lc_fid_latest_scanned_phase2 = *(struct lu_fid *)key;
3164                 /* Remote target OST may be runnning old LFSCK */
3165                 memset(rec, 0, sizeof(*rec));
3166                 rc = iops->rec(env, di, (struct dt_rec *)rec, 0);
3167                 if (rc == 0)
3168                         rc = lfsck_layout_scan_orphan_one(env, com, ltd, rec,
3169                                         &com->lc_fid_latest_scanned_phase2);
3170                 if (rc != 0 && bk->lb_param & LPF_FAILOUT)
3171                         GOTO(fini, rc);
3172
3173                 lfsck_control_speed_by_self(com);
3174                 do {
3175                         rc = iops->next(env, di);
3176                 } while (rc < 0 && !(bk->lb_param & LPF_FAILOUT));
3177         } while (rc == 0);
3178
3179         GOTO(fini, rc);
3180
3181 fini:
3182         iops->put(env, di);
3183         iops->fini(env, di);
3184 put:
3185         lfsck_object_put(env, obj);
3186
3187 log:
3188         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant finished the orphan "
3189                "scanning for OST%04x: rc = %d\n",
3190                lfsck_lfsck2name(lfsck), ltd->ltd_index, rc);
3191
3192         return rc > 0 ? 0 : rc;
3193 }
3194
3195 static int lfsck_lmm2layout(struct lov_mds_md_v1 *lmm, struct ost_layout *ol,
3196                             __u32 comp_id)
3197 {
3198         __u32 magic = le32_to_cpu(lmm->lmm_magic);
3199         int rc = 0;
3200         ENTRY;
3201
3202         if (magic == LOV_MAGIC_V1 || magic == LOV_MAGIC_V3) {
3203                 ol->ol_stripe_size = lmm->lmm_stripe_size;
3204                 ol->ol_stripe_count = lmm->lmm_stripe_count;
3205                 ol->ol_comp_start = 0;
3206                 ol->ol_comp_end = 0;
3207                 ol->ol_comp_id = 0;
3208         } else if (magic == LOV_MAGIC_COMP_V1) {
3209                 struct lov_comp_md_v1 *lcm = (struct lov_comp_md_v1 *)lmm;
3210                 struct lov_comp_md_entry_v1 *lcme = NULL;
3211                 __u16 count = le16_to_cpu(lcm->lcm_entry_count);
3212                 int i;
3213
3214                 for (i = 0; i < count; i++) {
3215                         lcme = &lcm->lcm_entries[i];
3216                         if (le32_to_cpu(lcme->lcme_id) == comp_id) {
3217                                 LASSERT(le32_to_cpu(lcme->lcme_flags) &
3218                                         LCME_FL_INIT);
3219
3220                                 break;
3221                         }
3222                 }
3223
3224                 /* The comp has been removed, do nothing. */
3225                 if (i == count)
3226                         GOTO(out, rc = 1);
3227
3228                 lmm = (void *)lmm + le32_to_cpu(lcme->lcme_offset);
3229                 ol->ol_stripe_size = le32_to_cpu(lmm->lmm_stripe_size);
3230                 ol->ol_stripe_count = le32_to_cpu(lmm->lmm_stripe_count);
3231                 ol->ol_comp_start = le64_to_cpu(lcme->lcme_extent.e_start);
3232                 ol->ol_comp_end = le64_to_cpu(lcme->lcme_extent.e_end);
3233                 ol->ol_comp_id = le32_to_cpu(lcme->lcme_id);
3234         } else {
3235                 GOTO(out, rc = -EINVAL);
3236         }
3237
3238         EXIT;
3239
3240 out:
3241         return rc;
3242 }
3243
3244 /**
3245  * Repair the MDT-object with dangling LOV EA reference.
3246  *
3247  * we need to repair the inconsistency according to the users' requirement:
3248  *
3249  * 1) Keep the inconsistency there and report the inconsistency case,
3250  *    then give the chance to the application to find related issues,
3251  *    and the users can make the decision about how to handle it with
3252  *    more human knownledge. (by default)
3253  *
3254  * 2) Re-create the missing OST-object with the FID/owner information.
3255  *
3256  * \param[in] env       pointer to the thread context
3257  * \param[in] com       the layout LFSCK component
3258  * \param[in] parent    the MDT-object with dangling LOV EA reference
3259  * \param[in] child     the OST-object to be created
3260  * \param[in] comp_id   the component ID of the OST-object in the LOV EA
3261  * \param[in] ea_off    the offset of the OST-object in the LOV EA
3262  * \param[in] ost_idx   the index of OST on which the OST-object resides
3263  *
3264  * \retval              +1 for repair successfully
3265  * \retval              0 for did nothing
3266  * \retval              negative error number on failure
3267  */
3268 static int __lfsck_layout_repair_dangling(const struct lu_env *env,
3269                                           struct lfsck_component *com,
3270                                           struct dt_object *parent,
3271                                           struct dt_object *child,
3272                                           __u32 comp_id, __u32 ea_off,
3273                                           __u32 ost_idx, bool log)
3274 {
3275         struct lfsck_thread_info *info = lfsck_env_info(env);
3276         struct filter_fid *ff = &info->lti_ff;
3277         struct ost_layout *ol = &ff->ff_layout;
3278         struct dt_object_format *dof = &info->lti_dof;
3279         struct lu_attr *la = &info->lti_la;
3280         struct lfsck_instance *lfsck = com->lc_lfsck;
3281         struct dt_device *dev = lfsck_obj2dev(child);
3282         const struct lu_fid *pfid = lfsck_dto2fid(parent);
3283         const struct lu_fid *cfid = lfsck_dto2fid(child);
3284         struct lu_buf *tbuf = &info->lti_big_buf;
3285         struct thandle *handle;
3286         struct lu_buf *buf;
3287         struct lustre_handle lh = { 0 };
3288         int rc;
3289         ENTRY;
3290
3291         if (!(lfsck->li_bookmark_ram.lb_param & LPF_CREATE_OSTOBJ))
3292                 GOTO(log, rc = 1);
3293
3294         rc = lfsck_ibits_lock(env, lfsck, parent, &lh,
3295                               MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR,
3296                               LCK_EX);
3297         if (rc != 0)
3298                 GOTO(log, rc);
3299
3300         rc = dt_attr_get(env, parent, la);
3301         if (rc != 0)
3302                 GOTO(unlock1, rc);
3303
3304         la->la_mode = S_IFREG | 0666;
3305         la->la_atime = la->la_mtime = la->la_ctime = 0;
3306         la->la_valid = LA_TYPE | LA_MODE | LA_UID | LA_GID |
3307                        LA_ATIME | LA_MTIME | LA_CTIME;
3308         memset(dof, 0, sizeof(*dof));
3309         ff->ff_parent.f_seq = cpu_to_le64(pfid->f_seq);
3310         ff->ff_parent.f_oid = cpu_to_le32(pfid->f_oid);
3311         /* Currently, the filter_fid::ff_parent::f_ver is not the real parent
3312          * MDT-object's FID::f_ver, instead it is the OST-object index in its
3313          * parent MDT-object's layout EA. */
3314         ff->ff_parent.f_stripe_idx = cpu_to_le32(ea_off);
3315
3316         rc = lfsck_layout_get_lovea(env, parent, tbuf);
3317         if (rc < 0)
3318                 GOTO(unlock1, rc);
3319
3320         rc = lfsck_lmm2layout(tbuf->lb_buf, ol, comp_id);
3321         if (rc)
3322                 GOTO(unlock1, rc);
3323
3324         buf = lfsck_buf_get(env, ff, sizeof(struct filter_fid));
3325         handle = dt_trans_create(env, dev);
3326         if (IS_ERR(handle))
3327                 GOTO(unlock1, rc = PTR_ERR(handle));
3328
3329         rc = dt_declare_create(env, child, la, NULL, dof, handle);
3330         if (rc != 0)
3331                 GOTO(stop, rc);
3332
3333         rc = dt_declare_xattr_set(env, child, buf, XATTR_NAME_FID,
3334                                   LU_XATTR_CREATE, handle);
3335         if (rc != 0)
3336                 GOTO(stop, rc);
3337
3338         rc = dt_trans_start_local(env, dev, handle);
3339         if (rc != 0)
3340                 GOTO(stop, rc);
3341
3342         dt_read_lock(env, parent, 0);
3343         if (unlikely(lfsck_is_dead_obj(parent)))
3344                 GOTO(unlock2, rc = 0);
3345
3346         if (lfsck->li_bookmark_ram.lb_param & LPF_DELAY_CREATE_OSTOBJ) {
3347                 struct ost_id *oi = &info->lti_oi;
3348                 struct lu_fid *tfid = &info->lti_fid2;
3349                 struct lu_buf *lovea = &info->lti_big_buf;
3350                 struct lov_mds_md_v1 *lmm;
3351                 struct lov_ost_data_v1 *objs;
3352                 __u32 magic;
3353                 int count;
3354                 int idx2;
3355
3356                 rc = lfsck_layout_get_lovea(env, parent, lovea);
3357                 if (rc <= 0)
3358                         GOTO(unlock2, rc);
3359
3360                 lmm = lovea->lb_buf;
3361                 magic = le32_to_cpu(lmm->lmm_magic);
3362                 if (magic == LOV_MAGIC_COMP_V1) {
3363                         struct lov_comp_md_v1 *lcm = buf->lb_buf;
3364                         struct lov_comp_md_entry_v1 *lcme;
3365                         __u16 count = le16_to_cpu(lcm->lcm_entry_count);
3366                         int i;
3367
3368                         for (i = 0; i < count; i++) {
3369                                 lcme = &lcm->lcm_entries[i];
3370                                 if (le32_to_cpu(lcme->lcme_id) == comp_id) {
3371                                         LASSERT(le32_to_cpu(lcme->lcme_flags) &
3372                                                 LCME_FL_INIT);
3373
3374                                         lmm = lovea->lb_buf +
3375                                                 le32_to_cpu(lcme->lcme_offset);
3376                                         magic = le32_to_cpu(lmm->lmm_magic);
3377                                         goto check;
3378                                 }
3379                         }
3380
3381                         /* Someone removed the component, do nothing. */
3382                         GOTO(unlock2, rc = 0);
3383                 }
3384
3385 check:
3386                 count = le16_to_cpu(lmm->lmm_stripe_count);
3387                 /* Someone changed the LOV EA, do nothing. */
3388                 if (count <= ea_off)
3389                         GOTO(unlock2, rc = 0);
3390
3391                 if (magic == LOV_MAGIC_V1) {
3392                         objs = &lmm->lmm_objects[ea_off];
3393                 } else {
3394                         LASSERT(magic == LOV_MAGIC_V3);
3395
3396                         objs = &((struct lov_mds_md_v3 *)lmm)->\
3397                                                         lmm_objects[ea_off];
3398                 }
3399
3400                 ostid_le_to_cpu(&objs->l_ost_oi, oi);
3401                 idx2 = le32_to_cpu(objs->l_ost_idx);
3402                 rc = ostid_to_fid(tfid, oi, idx2);
3403                 /* Someone changed the LOV EA, do nothing. */
3404                 if (rc != 0 || !lu_fid_eq(tfid, cfid))
3405                         GOTO(unlock2, rc);
3406         }
3407
3408         rc = dt_create(env, child, la, NULL, dof, handle);
3409         if (rc != 0)
3410                 GOTO(unlock2, rc);
3411
3412         rc = dt_xattr_set(env, child, buf, XATTR_NAME_FID, LU_XATTR_CREATE,
3413                           handle);
3414
3415         GOTO(unlock2, rc);
3416
3417 unlock2:
3418         dt_read_unlock(env, parent);
3419
3420 stop:
3421         rc = lfsck_layout_trans_stop(env, dev, handle, rc);
3422
3423 unlock1:
3424         lfsck_ibits_unlock(&lh, LCK_EX);
3425
3426 log:
3427         if (rc && log)
3428                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant found "
3429                        "dangling reference for: parent "DFID", child "
3430                        DFID", comp_id %u, ea_off %u, ost_idx %u, %s: "
3431                        "rc = %d\n",
3432                        lfsck_lfsck2name(lfsck), PFID(pfid), PFID(cfid),
3433                        comp_id, ea_off, ost_idx,
3434                        (lfsck->li_bookmark_ram.lb_param & LPF_CREATE_OSTOBJ) ?
3435                                 "Create the lost OST-object as required" :
3436                                 "Keep the MDT-object there by default", rc);
3437
3438         return rc;
3439 }
3440
3441 /**
3442  * Repair the MDT-object with dangling LOV EA reference.
3443  *
3444  * Prepare parameters and call __lfsck_layout_repair_dangling()
3445  * to repair the dangling LOV EA reference.
3446  *
3447  * \param[in] env       pointer to the thread context
3448  * \param[in] com       the layout LFSCK component
3449  * \param[in] pfid      the MDT-object's FID
3450  * \param[in] cfid      the FID for the OST-object to be created
3451  * \param[in] comp_id   the component ID of the OST-object in the LOV EA
3452  * \param[in] ea_off    the offset of the OST-object in the LOV EA
3453  * \param[in] ost_idx   the index of OST on which the OST-object resides
3454  *
3455  * \retval              +1 for repair successfully
3456  * \retval              0 for did nothing
3457  * \retval              negative error number on failure
3458  */
3459 static int lfsck_layout_repair_dangling(const struct lu_env *env,
3460                                         struct lfsck_component *com,
3461                                         const struct lu_fid *pfid,
3462                                         const struct lu_fid *cfid,
3463                                         __u32 comp_id, __u32 ea_off,
3464                                         __u32 ost_idx)
3465 {
3466         struct lfsck_instance *lfsck = com->lc_lfsck;
3467         struct dt_object *parent = NULL;
3468         struct dt_object *child = NULL;
3469         struct lfsck_tgt_desc *ltd;
3470         int rc;
3471         ENTRY;
3472
3473         parent = lfsck_object_find_bottom(env, lfsck, pfid);
3474         if (IS_ERR(parent))
3475                 GOTO(log, rc = PTR_ERR(parent));
3476
3477         /* The MDT-object has been removed. */
3478         if (dt_object_exists(parent) == 0)
3479                 GOTO(log, rc = 0);
3480
3481         ltd = lfsck_ltd2tgt(&lfsck->li_ost_descs, ost_idx);
3482         if (unlikely(ltd == NULL))
3483                 GOTO(log, rc = -ENODEV);
3484
3485         child = lfsck_object_find_by_dev(env, ltd->ltd_tgt, cfid);
3486         if (IS_ERR(child))
3487                 GOTO(log, rc = PTR_ERR(child));
3488
3489         /* The OST-object has been created. */
3490         if (unlikely(dt_object_exists(child) != 0))
3491                 GOTO(log, rc = 0);
3492
3493         rc = __lfsck_layout_repair_dangling(env, com, parent, child,
3494                                             comp_id, ea_off, ost_idx, false);
3495
3496         GOTO(log, rc);
3497
3498 log:
3499         if (child != NULL && !IS_ERR(child))
3500                 lfsck_object_put(env, child);
3501
3502         if (parent != NULL && !IS_ERR(parent))
3503                 lfsck_object_put(env, parent);
3504
3505         if (rc)
3506                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant found "
3507                        "dangling reference for: parent "DFID", child "
3508                        DFID", comp_id %u, ea_off %u, ost_idx %u, %s: rc = %d\n",
3509                        lfsck_lfsck2name(lfsck), PFID(pfid), PFID(cfid),
3510                        comp_id, ea_off, ost_idx,
3511                        (lfsck->li_bookmark_ram.lb_param & LPF_CREATE_OSTOBJ) ?
3512                                 "Create the lost OST-object as required" :
3513                                 "Keep the MDT-object there by default", rc);
3514
3515         return rc;
3516 }
3517
3518 /* If the OST-object does not recognize the MDT-object as its parent, and
3519  * there is no other MDT-object claims as its parent, then just trust the
3520  * given MDT-object as its parent. So update the OST-object filter_fid. */
3521 static int lfsck_layout_repair_unmatched_pair(const struct lu_env *env,
3522                                               struct lfsck_component *com,
3523                                               struct dt_object *parent,
3524                                               struct lfsck_layout_req *llr,
3525                                               struct lu_attr *la)
3526 {
3527         struct lfsck_thread_info        *info   = lfsck_env_info(env);
3528         struct filter_fid               *ff     = &info->lti_ff;
3529         struct ost_layout               *ol     = &ff->ff_layout;
3530         struct dt_object                *child  = llr->llr_child;
3531         struct dt_device                *dev    = lfsck_obj2dev(child);
3532         const struct lu_fid             *tfid   = lu_object_fid(&parent->do_lu);
3533         struct lu_buf                   *tbuf   = &info->lti_big_buf;
3534         struct thandle                  *handle;
3535         struct lu_buf                   *buf;
3536         struct lustre_handle             lh     = { 0 };
3537         int                              rc;
3538         ENTRY;
3539
3540         rc = lfsck_ibits_lock(env, com->lc_lfsck, parent, &lh,
3541                               MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR,
3542                               LCK_EX);
3543         if (rc != 0)
3544                 GOTO(log, rc);
3545
3546         ff->ff_parent.f_seq = cpu_to_le64(tfid->f_seq);
3547         ff->ff_parent.f_oid = cpu_to_le32(tfid->f_oid);
3548         /* Currently, the filter_fid::ff_parent::f_ver is not the real parent
3549          * MDT-object's FID::f_ver, instead it is the OST-object index in its
3550          * parent MDT-object's layout EA. */
3551         ff->ff_parent.f_stripe_idx = cpu_to_le32(llr->llr_lov_idx);
3552
3553         rc = lfsck_layout_get_lovea(env, parent, tbuf);
3554         if (rc < 0)
3555                 GOTO(unlock1, rc);
3556
3557         rc = lfsck_lmm2layout(tbuf->lb_buf, ol, llr->llr_comp_id);
3558         if (rc)
3559                 GOTO(unlock1, rc);
3560
3561         buf = lfsck_buf_get(env, ff, sizeof(*ff));
3562