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