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