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