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