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