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