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