Whamcloud - gitweb
LU-6138 lfsck: NOT hold reference on pre-loaded object
[fs/lustre-release.git] / lustre / lfsck / lfsck_layout.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License version 2 for more details.  A copy is
14  * included in the COPYING file that accompanied this code.
15
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2014, Intel Corporation.
24  */
25 /*
26  * lustre/lfsck/lfsck_layout.c
27  *
28  * Author: Fan, Yong <fan.yong@intel.com>
29  */
30
31 #ifndef EXPORT_SYMTAB
32 # define EXPORT_SYMTAB
33 #endif
34 #define DEBUG_SUBSYSTEM S_LFSCK
35
36 #include <linux/bitops.h>
37 #include <linux/rbtree.h>
38
39 #include <lustre/lustre_idl.h>
40 #include <lu_object.h>
41 #include <dt_object.h>
42 #include <lustre_fid.h>
43 #include <lustre_lib.h>
44 #include <lustre_net.h>
45 #include <lustre/lustre_user.h>
46 #include <md_object.h>
47 #include <obd_class.h>
48
49 #include "lfsck_internal.h"
50
51 #define LFSCK_LAYOUT_MAGIC_V1           0xB173AE14
52 #define LFSCK_LAYOUT_MAGIC_V2           0xB1734D76
53
54 #define LFSCK_LAYOUT_MAGIC              LFSCK_LAYOUT_MAGIC_V2
55
56 struct lfsck_layout_seq {
57         struct list_head         lls_list;
58         __u64                    lls_seq;
59         __u64                    lls_lastid;
60         __u64                    lls_lastid_known;
61         struct dt_object        *lls_lastid_obj;
62         unsigned int             lls_dirty:1;
63 };
64
65 struct lfsck_layout_slave_target {
66         /* link into lfsck_layout_slave_data::llsd_master_list. */
67         struct list_head        llst_list;
68         /* The position for next record in the rbtree for iteration. */
69         struct lu_fid           llst_fid;
70         /* Dummy hash for iteration against the rbtree. */
71         __u64                   llst_hash;
72         __u64                   llst_gen;
73         atomic_t                llst_ref;
74         __u32                   llst_index;
75 };
76
77 struct lfsck_layout_slave_data {
78         /* list for lfsck_layout_seq */
79         struct list_head         llsd_seq_list;
80
81         /* list for the masters involve layout verification. */
82         struct list_head         llsd_master_list;
83         spinlock_t               llsd_lock;
84         __u64                    llsd_touch_gen;
85         struct dt_object        *llsd_rb_obj;
86         struct rb_root           llsd_rb_root;
87         rwlock_t                 llsd_rb_lock;
88         unsigned int             llsd_rbtree_valid:1;
89 };
90
91 struct lfsck_layout_object {
92         struct lu_attr           llo_attr;
93         atomic_t                 llo_ref;
94         __u64                    llo_cookie;
95         __u16                    llo_gen;
96 };
97
98 struct lfsck_layout_req {
99         struct lfsck_assistant_req       llr_lar;
100         struct lfsck_layout_object      *llr_parent;
101         struct dt_object                *llr_child;
102         __u32                            llr_ost_idx;
103         __u32                            llr_lov_idx; /* offset in LOV EA */
104 };
105
106 struct lfsck_layout_slave_async_args {
107         struct obd_export                *llsaa_exp;
108         struct lfsck_component           *llsaa_com;
109         struct lfsck_layout_slave_target *llsaa_llst;
110 };
111
112 static struct lfsck_layout_object *
113 lfsck_layout_object_init(const struct lu_env *env, struct dt_object *obj,
114                          __u64 cookie, __u16 gen)
115 {
116         struct lfsck_layout_object *llo;
117         int                         rc;
118
119         OBD_ALLOC_PTR(llo);
120         if (llo == NULL)
121                 return ERR_PTR(-ENOMEM);
122
123         rc = dt_attr_get(env, obj, &llo->llo_attr, BYPASS_CAPA);
124         if (rc != 0) {
125                 OBD_FREE_PTR(llo);
126
127                 return ERR_PTR(rc);
128         }
129
130         llo->llo_cookie = cookie;
131         /* The gen can be used to check whether some others have changed the
132          * file layout after LFSCK pre-fetching but before real verification. */
133         llo->llo_gen = gen;
134         atomic_set(&llo->llo_ref, 1);
135
136         return llo;
137 }
138
139 static inline void
140 lfsck_layout_llst_put(struct lfsck_layout_slave_target *llst)
141 {
142         if (atomic_dec_and_test(&llst->llst_ref)) {
143                 LASSERT(list_empty(&llst->llst_list));
144
145                 OBD_FREE_PTR(llst);
146         }
147 }
148
149 static inline int
150 lfsck_layout_llst_add(struct lfsck_layout_slave_data *llsd, __u32 index)
151 {
152         struct lfsck_layout_slave_target *llst;
153         struct lfsck_layout_slave_target *tmp;
154         int                               rc   = 0;
155
156         OBD_ALLOC_PTR(llst);
157         if (llst == NULL)
158                 return -ENOMEM;
159
160         INIT_LIST_HEAD(&llst->llst_list);
161         llst->llst_gen = 0;
162         llst->llst_index = index;
163         atomic_set(&llst->llst_ref, 1);
164
165         spin_lock(&llsd->llsd_lock);
166         list_for_each_entry(tmp, &llsd->llsd_master_list, llst_list) {
167                 if (tmp->llst_index == index) {
168                         rc = -EALREADY;
169                         break;
170                 }
171         }
172         if (rc == 0)
173                 list_add_tail(&llst->llst_list, &llsd->llsd_master_list);
174         spin_unlock(&llsd->llsd_lock);
175
176         if (rc != 0)
177                 OBD_FREE_PTR(llst);
178
179         return rc;
180 }
181
182 static inline void
183 lfsck_layout_llst_del(struct lfsck_layout_slave_data *llsd,
184                       struct lfsck_layout_slave_target *llst)
185 {
186         bool del = false;
187
188         spin_lock(&llsd->llsd_lock);
189         if (!list_empty(&llst->llst_list)) {
190                 list_del_init(&llst->llst_list);
191                 del = true;
192         }
193         spin_unlock(&llsd->llsd_lock);
194
195         if (del)
196                 lfsck_layout_llst_put(llst);
197 }
198
199 static inline struct lfsck_layout_slave_target *
200 lfsck_layout_llst_find_and_del(struct lfsck_layout_slave_data *llsd,
201                                __u32 index, bool unlink)
202 {
203         struct lfsck_layout_slave_target *llst;
204
205         spin_lock(&llsd->llsd_lock);
206         list_for_each_entry(llst, &llsd->llsd_master_list, llst_list) {
207                 if (llst->llst_index == index) {
208                         if (unlink)
209                                 list_del_init(&llst->llst_list);
210                         else
211                                 atomic_inc(&llst->llst_ref);
212                         spin_unlock(&llsd->llsd_lock);
213
214                         return llst;
215                 }
216         }
217         spin_unlock(&llsd->llsd_lock);
218
219         return NULL;
220 }
221
222 static inline void lfsck_layout_object_put(const struct lu_env *env,
223                                            struct lfsck_layout_object *llo)
224 {
225         if (atomic_dec_and_test(&llo->llo_ref))
226                 OBD_FREE_PTR(llo);
227 }
228
229 static struct lfsck_layout_req *
230 lfsck_layout_assistant_req_init(struct lfsck_layout_object *parent,
231                                 const struct lu_fid *pfid,
232                                 struct dt_object *child, __u32 ost_idx,
233                                 __u32 lov_idx)
234 {
235         struct lfsck_layout_req *llr;
236
237         OBD_ALLOC_PTR(llr);
238         if (llr == NULL)
239                 return ERR_PTR(-ENOMEM);
240
241         INIT_LIST_HEAD(&llr->llr_lar.lar_list);
242         llr->llr_lar.lar_fid = *pfid;
243
244         atomic_inc(&parent->llo_ref);
245         llr->llr_parent = parent;
246         llr->llr_child = child;
247         llr->llr_ost_idx = ost_idx;
248         llr->llr_lov_idx = lov_idx;
249
250         return llr;
251 }
252
253 static void lfsck_layout_assistant_req_fini(const struct lu_env *env,
254                                             struct lfsck_assistant_req *lar)
255 {
256         struct lfsck_layout_req *llr =
257                         container_of0(lar, struct lfsck_layout_req, llr_lar);
258
259         lu_object_put(env, &llr->llr_child->do_lu);
260         lfsck_layout_object_put(env, llr->llr_parent);
261         OBD_FREE_PTR(llr);
262 }
263
264 static int
265 lfsck_layout_assistant_sync_failures_interpret(const struct lu_env *env,
266                                                struct ptlrpc_request *req,
267                                                void *args, int rc)
268 {
269         if (rc == 0) {
270                 struct lfsck_async_interpret_args *laia = args;
271                 struct lfsck_tgt_desc             *ltd  = laia->laia_ltd;
272
273                 ltd->ltd_synced_failures = 1;
274                 atomic_dec(laia->laia_count);
275         }
276
277         return 0;
278 }
279
280 /**
281  * Notify remote LFSCK instances about former failures.
282  *
283  * The local LFSCK instance has recorded which OSTs have ever failed to respond
284  * some LFSCK verification requests (maybe because of network issues or the OST
285  * itself trouble). During the respond gap, the OST may missed some OST-objects
286  * verification, then the OST cannot know whether related OST-objects have been
287  * referenced by related MDT-objects or not, then in the second-stage scanning,
288  * these OST-objects will be regarded as orphan, if the OST-object contains bad
289  * parent FID for back reference, then it will misguide the LFSCK to make wrong
290  * fixing for the fake orphan.
291  *
292  * To avoid above trouble, when layout LFSCK finishes the first-stage scanning,
293  * it will scan the bitmap for the ever failed OSTs, and notify them that they
294  * have ever missed some OST-object verification and should skip the handling
295  * for orphan OST-objects on all MDTs that are in the layout LFSCK.
296  *
297  * \param[in] env       pointer to the thread context
298  * \param[in] com       pointer to the lfsck component
299  * \param[in] lr        pointer to the lfsck request
300  */
301 static void lfsck_layout_assistant_sync_failures(const struct lu_env *env,
302                                                  struct lfsck_component *com,
303                                                  struct lfsck_request *lr)
304 {
305         struct lfsck_async_interpret_args *laia  =
306                                 &lfsck_env_info(env)->lti_laia2;
307         struct lfsck_assistant_data       *lad   = com->lc_data;
308         struct lfsck_layout               *lo    = com->lc_file_ram;
309         struct lfsck_instance             *lfsck = com->lc_lfsck;
310         struct lfsck_tgt_descs            *ltds  = &lfsck->li_ost_descs;
311         struct lfsck_tgt_desc             *ltd;
312         struct ptlrpc_request_set         *set;
313         atomic_t                           count;
314         __u32                              idx;
315         int                                rc    = 0;
316         ENTRY;
317
318         if (!lad->lad_incomplete || lo->ll_flags & LF_INCOMPLETE)
319                 RETURN_EXIT;
320
321         /* If the MDT has ever failed to verfiy some OST-objects,
322          * then sync failures with them firstly. */
323         lr->lr_flags2 = lo->ll_flags | LF_INCOMPLETE;
324
325         atomic_set(&count, 0);
326         memset(laia, 0, sizeof(*laia));
327         laia->laia_count = &count;
328         set = ptlrpc_prep_set();
329         if (set == NULL)
330                 GOTO(out, rc = -ENOMEM);
331
332         down_read(&ltds->ltd_rw_sem);
333         cfs_foreach_bit(lad->lad_bitmap, idx) {
334                 ltd = LTD_TGT(ltds, idx);
335                 LASSERT(ltd != NULL);
336
337                 laia->laia_ltd = ltd;
338                 rc = lfsck_async_request(env, ltd->ltd_exp, lr, set,
339                                 lfsck_layout_assistant_sync_failures_interpret,
340                                 laia, LFSCK_NOTIFY);
341                 if (rc != 0) {
342                         CDEBUG(D_LFSCK, "%s: LFSCK assistant fail to "
343                                "notify target %x for %s phase1 done: "
344                                "rc = %d\n", lfsck_lfsck2name(com->lc_lfsck),
345                                ltd->ltd_index, lad->lad_name, rc);
346
347                         break;
348                 }
349
350                 atomic_inc(&count);
351         }
352         up_read(&ltds->ltd_rw_sem);
353
354         if (rc == 0 && atomic_read(&count) > 0)
355                 rc = ptlrpc_set_wait(set);
356
357         ptlrpc_set_destroy(set);
358
359         if (rc == 0 && atomic_read(&count) > 0)
360                 rc = -EINVAL;
361
362         GOTO(out, rc);
363
364 out:
365         if (rc != 0)
366                 /* If failed to sync failures with the OSTs, then have to
367                  * mark the whole LFSCK as LF_INCOMPLETE to skip the whole
368                  * subsequent orphan OST-object handling. */
369                 lo->ll_flags |= LF_INCOMPLETE;
370
371         lr->lr_flags2 = lo->ll_flags;
372 }
373
374 static int lfsck_layout_get_lovea(const struct lu_env *env,
375                                   struct dt_object *obj, struct lu_buf *buf)
376 {
377         int rc;
378
379 again:
380         rc = dt_xattr_get(env, obj, buf, XATTR_NAME_LOV, BYPASS_CAPA);
381         if (rc == -ERANGE) {
382                 rc = dt_xattr_get(env, obj, &LU_BUF_NULL, XATTR_NAME_LOV,
383                                   BYPASS_CAPA);
384                 if (rc <= 0)
385                         return rc;
386
387                 lu_buf_realloc(buf, rc);
388                 if (buf->lb_buf == NULL)
389                         return -ENOMEM;
390
391                 goto again;
392         }
393
394         if (rc == -ENODATA)
395                 rc = 0;
396
397         if (rc <= 0)
398                 return rc;
399
400         if (unlikely(buf->lb_buf == NULL)) {
401                 lu_buf_alloc(buf, rc);
402                 if (buf->lb_buf == NULL)
403                         return -ENOMEM;
404
405                 goto again;
406         }
407
408         return rc;
409 }
410
411 static int lfsck_layout_verify_header(struct lov_mds_md_v1 *lmm)
412 {
413         __u32 magic;
414         __u32 pattern;
415
416         magic = le32_to_cpu(lmm->lmm_magic);
417         /* If magic crashed, keep it there. Sometime later, during OST-object
418          * orphan handling, if some OST-object(s) back-point to it, it can be
419          * verified and repaired. */
420         if (magic != LOV_MAGIC_V1 && magic != LOV_MAGIC_V3) {
421                 struct ost_id   oi;
422                 int             rc;
423
424                 lmm_oi_le_to_cpu(&oi, &lmm->lmm_oi);
425                 if ((magic & LOV_MAGIC_MASK) == LOV_MAGIC_MAGIC)
426                         rc = -EOPNOTSUPP;
427                 else
428                         rc = -EINVAL;
429
430                 CDEBUG(D_LFSCK, "%s LOV EA magic %u on "DOSTID"\n",
431                        rc == -EINVAL ? "Unknown" : "Unsupported",
432                        magic, POSTID(&oi));
433
434                 return rc;
435         }
436
437         pattern = le32_to_cpu(lmm->lmm_pattern);
438         /* XXX: currently, we only support LOV_PATTERN_RAID0. */
439         if (lov_pattern(pattern) != LOV_PATTERN_RAID0) {
440                 struct ost_id oi;
441
442                 lmm_oi_le_to_cpu(&oi, &lmm->lmm_oi);
443                 CDEBUG(D_LFSCK, "Unsupported LOV EA pattern %u on "DOSTID"\n",
444                        pattern, POSTID(&oi));
445
446                 return -EOPNOTSUPP;
447         }
448
449         return 0;
450 }
451
452 #define LFSCK_RBTREE_BITMAP_SIZE        PAGE_CACHE_SIZE
453 #define LFSCK_RBTREE_BITMAP_WIDTH       (LFSCK_RBTREE_BITMAP_SIZE << 3)
454 #define LFSCK_RBTREE_BITMAP_MASK        (LFSCK_RBTREE_BITMAP_WIDTH - 1)
455
456 struct lfsck_rbtree_node {
457         struct rb_node   lrn_node;
458         __u64            lrn_seq;
459         __u32            lrn_first_oid;
460         atomic_t         lrn_known_count;
461         atomic_t         lrn_accessed_count;
462         void            *lrn_known_bitmap;
463         void            *lrn_accessed_bitmap;
464 };
465
466 static inline int lfsck_rbtree_cmp(struct lfsck_rbtree_node *lrn,
467                                    __u64 seq, __u32 oid)
468 {
469         if (seq < lrn->lrn_seq)
470                 return -1;
471
472         if (seq > lrn->lrn_seq)
473                 return 1;
474
475         if (oid < lrn->lrn_first_oid)
476                 return -1;
477
478         if (oid - lrn->lrn_first_oid >= LFSCK_RBTREE_BITMAP_WIDTH)
479                 return 1;
480
481         return 0;
482 }
483
484 /* The caller should hold llsd->llsd_rb_lock. */
485 static struct lfsck_rbtree_node *
486 lfsck_rbtree_search(struct lfsck_layout_slave_data *llsd,
487                     const struct lu_fid *fid, bool *exact)
488 {
489         struct rb_node           *node  = llsd->llsd_rb_root.rb_node;
490         struct rb_node           *prev  = NULL;
491         struct lfsck_rbtree_node *lrn   = NULL;
492         int                       rc    = 0;
493
494         if (exact != NULL)
495                 *exact = true;
496
497         while (node != NULL) {
498                 prev = node;
499                 lrn = rb_entry(node, struct lfsck_rbtree_node, lrn_node);
500                 rc = lfsck_rbtree_cmp(lrn, fid_seq(fid), fid_oid(fid));
501                 if (rc < 0)
502                         node = node->rb_left;
503                 else if (rc > 0)
504                         node = node->rb_right;
505                 else
506                         return lrn;
507         }
508
509         if (exact == NULL)
510                 return NULL;
511
512         /* If there is no exactly matched one, then to the next valid one. */
513         *exact = false;
514
515         /* The rbtree is empty. */
516         if (rc == 0)
517                 return NULL;
518
519         if (rc < 0)
520                 return lrn;
521
522         node = rb_next(prev);
523
524         /* The end of the rbtree. */
525         if (node == NULL)
526                 return NULL;
527
528         lrn = rb_entry(node, struct lfsck_rbtree_node, lrn_node);
529
530         return lrn;
531 }
532
533 static struct lfsck_rbtree_node *lfsck_rbtree_new(const struct lu_env *env,
534                                                   const struct lu_fid *fid)
535 {
536         struct lfsck_rbtree_node *lrn;
537
538         OBD_ALLOC_PTR(lrn);
539         if (lrn == NULL)
540                 return ERR_PTR(-ENOMEM);
541
542         OBD_ALLOC(lrn->lrn_known_bitmap, LFSCK_RBTREE_BITMAP_SIZE);
543         if (lrn->lrn_known_bitmap == NULL) {
544                 OBD_FREE_PTR(lrn);
545
546                 return ERR_PTR(-ENOMEM);
547         }
548
549         OBD_ALLOC(lrn->lrn_accessed_bitmap, LFSCK_RBTREE_BITMAP_SIZE);
550         if (lrn->lrn_accessed_bitmap == NULL) {
551                 OBD_FREE(lrn->lrn_known_bitmap, LFSCK_RBTREE_BITMAP_SIZE);
552                 OBD_FREE_PTR(lrn);
553
554                 return ERR_PTR(-ENOMEM);
555         }
556
557         RB_CLEAR_NODE(&lrn->lrn_node);
558         lrn->lrn_seq = fid_seq(fid);
559         lrn->lrn_first_oid = fid_oid(fid) & ~LFSCK_RBTREE_BITMAP_MASK;
560         atomic_set(&lrn->lrn_known_count, 0);
561         atomic_set(&lrn->lrn_accessed_count, 0);
562
563         return lrn;
564 }
565
566 static void lfsck_rbtree_free(struct lfsck_rbtree_node *lrn)
567 {
568         OBD_FREE(lrn->lrn_accessed_bitmap, LFSCK_RBTREE_BITMAP_SIZE);
569         OBD_FREE(lrn->lrn_known_bitmap, LFSCK_RBTREE_BITMAP_SIZE);
570         OBD_FREE_PTR(lrn);
571 }
572
573 /* The caller should hold lock. */
574 static struct lfsck_rbtree_node *
575 lfsck_rbtree_insert(struct lfsck_layout_slave_data *llsd,
576                     struct lfsck_rbtree_node *lrn)
577 {
578         struct rb_node           **pos    = &llsd->llsd_rb_root.rb_node;
579         struct rb_node            *parent = NULL;
580         struct lfsck_rbtree_node  *tmp;
581         int                        rc;
582
583         while (*pos != NULL) {
584                 parent = *pos;
585                 tmp = rb_entry(parent, struct lfsck_rbtree_node, lrn_node);
586                 rc = lfsck_rbtree_cmp(tmp, lrn->lrn_seq, lrn->lrn_first_oid);
587                 if (rc < 0)
588                         pos = &(*pos)->rb_left;
589                 else if (rc > 0)
590                         pos = &(*pos)->rb_right;
591                 else
592                         return tmp;
593         }
594
595         rb_link_node(&lrn->lrn_node, parent, pos);
596         rb_insert_color(&lrn->lrn_node, &llsd->llsd_rb_root);
597
598         return lrn;
599 }
600
601 extern const struct dt_index_operations lfsck_orphan_index_ops;
602
603 static int lfsck_rbtree_setup(const struct lu_env *env,
604                               struct lfsck_component *com)
605 {
606         struct lu_fid                   *fid    = &lfsck_env_info(env)->lti_fid;
607         struct lfsck_instance           *lfsck  = com->lc_lfsck;
608         struct dt_device                *dev    = lfsck->li_bottom;
609         struct lfsck_layout_slave_data  *llsd   = com->lc_data;
610         struct dt_object                *obj;
611
612         fid->f_seq = FID_SEQ_LAYOUT_RBTREE;
613         fid->f_oid = lfsck_dev_idx(dev);
614         fid->f_ver = 0;
615         obj = dt_locate(env, dev, fid);
616         if (IS_ERR(obj))
617                 RETURN(PTR_ERR(obj));
618
619         /* Generate an in-RAM object to stand for the layout rbtree.
620          * Scanning the layout rbtree will be via the iteration over
621          * the object. In the future, the rbtree may be written onto
622          * disk with the object.
623          *
624          * Mark the object to be as exist. */
625         obj->do_lu.lo_header->loh_attr |= LOHA_EXISTS;
626         obj->do_index_ops = &lfsck_orphan_index_ops;
627         llsd->llsd_rb_obj = obj;
628         llsd->llsd_rbtree_valid = 1;
629         dev->dd_record_fid_accessed = 1;
630
631         CDEBUG(D_LFSCK, "%s: layout LFSCK init OST-objects accessing bitmap\n",
632                lfsck_lfsck2name(lfsck));
633
634         return 0;
635 }
636
637 static void lfsck_rbtree_cleanup(const struct lu_env *env,
638                                  struct lfsck_component *com)
639 {
640         struct lfsck_instance           *lfsck = com->lc_lfsck;
641         struct lfsck_layout_slave_data  *llsd  = com->lc_data;
642         struct rb_node                  *node  = rb_first(&llsd->llsd_rb_root);
643         struct rb_node                  *next;
644         struct lfsck_rbtree_node        *lrn;
645
646         lfsck->li_bottom->dd_record_fid_accessed = 0;
647         /* Invalid the rbtree, then no others will use it. */
648         write_lock(&llsd->llsd_rb_lock);
649         llsd->llsd_rbtree_valid = 0;
650         write_unlock(&llsd->llsd_rb_lock);
651
652         while (node != NULL) {
653                 next = rb_next(node);
654                 lrn = rb_entry(node, struct lfsck_rbtree_node, lrn_node);
655                 rb_erase(node, &llsd->llsd_rb_root);
656                 lfsck_rbtree_free(lrn);
657                 node = next;
658         }
659
660         if (llsd->llsd_rb_obj != NULL) {
661                 lu_object_put(env, &llsd->llsd_rb_obj->do_lu);
662                 llsd->llsd_rb_obj = NULL;
663         }
664
665         CDEBUG(D_LFSCK, "%s: layout LFSCK fini OST-objects accessing bitmap\n",
666                lfsck_lfsck2name(lfsck));
667 }
668
669 static void lfsck_rbtree_update_bitmap(const struct lu_env *env,
670                                        struct lfsck_component *com,
671                                        const struct lu_fid *fid,
672                                        bool accessed)
673 {
674         struct lfsck_layout_slave_data  *llsd   = com->lc_data;
675         struct lfsck_rbtree_node        *lrn;
676         bool                             insert = false;
677         int                              idx;
678         int                              rc     = 0;
679         ENTRY;
680
681         if (unlikely(!fid_is_sane(fid) || fid_is_last_id(fid)))
682                 RETURN_EXIT;
683
684         if (!fid_is_idif(fid) && !fid_is_norm(fid))
685                 RETURN_EXIT;
686
687         read_lock(&llsd->llsd_rb_lock);
688         if (!llsd->llsd_rbtree_valid)
689                 GOTO(unlock, rc = 0);
690
691         lrn = lfsck_rbtree_search(llsd, fid, NULL);
692         if (lrn == NULL) {
693                 struct lfsck_rbtree_node *tmp;
694
695                 LASSERT(!insert);
696
697                 read_unlock(&llsd->llsd_rb_lock);
698                 tmp = lfsck_rbtree_new(env, fid);
699                 if (IS_ERR(tmp))
700                         GOTO(out, rc = PTR_ERR(tmp));
701
702                 insert = true;
703                 write_lock(&llsd->llsd_rb_lock);
704                 if (!llsd->llsd_rbtree_valid) {
705                         lfsck_rbtree_free(tmp);
706                         GOTO(unlock, rc = 0);
707                 }
708
709                 lrn = lfsck_rbtree_insert(llsd, tmp);
710                 if (lrn != tmp)
711                         lfsck_rbtree_free(tmp);
712         }
713
714         idx = fid_oid(fid) & LFSCK_RBTREE_BITMAP_MASK;
715         /* Any accessed object must be a known object. */
716         if (!test_and_set_bit(idx, lrn->lrn_known_bitmap))
717                 atomic_inc(&lrn->lrn_known_count);
718         if (accessed && !test_and_set_bit(idx, lrn->lrn_accessed_bitmap))
719                 atomic_inc(&lrn->lrn_accessed_count);
720
721         GOTO(unlock, rc = 0);
722
723 unlock:
724         if (insert)
725                 write_unlock(&llsd->llsd_rb_lock);
726         else
727                 read_unlock(&llsd->llsd_rb_lock);
728 out:
729         if (rc != 0 && accessed) {
730                 struct lfsck_layout *lo = com->lc_file_ram;
731
732                 CDEBUG(D_LFSCK, "%s: fail to update OST-objects accessing "
733                        "bitmap, and will cause incorrect LFSCK OST-object "
734                        "handling, so disable it to cancel orphan handling "
735                        "for related device. rc = %d\n",
736                        lfsck_lfsck2name(com->lc_lfsck), rc);
737
738                 lo->ll_flags |= LF_INCOMPLETE;
739                 lfsck_rbtree_cleanup(env, com);
740         }
741 }
742
743 static void lfsck_layout_le_to_cpu(struct lfsck_layout *des,
744                                    const struct lfsck_layout *src)
745 {
746         int i;
747
748         des->ll_magic = le32_to_cpu(src->ll_magic);
749         des->ll_status = le32_to_cpu(src->ll_status);
750         des->ll_flags = le32_to_cpu(src->ll_flags);
751         des->ll_success_count = le32_to_cpu(src->ll_success_count);
752         des->ll_run_time_phase1 = le32_to_cpu(src->ll_run_time_phase1);
753         des->ll_run_time_phase2 = le32_to_cpu(src->ll_run_time_phase2);
754         des->ll_time_last_complete = le64_to_cpu(src->ll_time_last_complete);
755         des->ll_time_latest_start = le64_to_cpu(src->ll_time_latest_start);
756         des->ll_time_last_checkpoint =
757                                 le64_to_cpu(src->ll_time_last_checkpoint);
758         des->ll_pos_latest_start = le64_to_cpu(src->ll_pos_latest_start);
759         des->ll_pos_last_checkpoint = le64_to_cpu(src->ll_pos_last_checkpoint);
760         des->ll_pos_first_inconsistent =
761                         le64_to_cpu(src->ll_pos_first_inconsistent);
762         des->ll_objs_checked_phase1 = le64_to_cpu(src->ll_objs_checked_phase1);
763         des->ll_objs_failed_phase1 = le64_to_cpu(src->ll_objs_failed_phase1);
764         des->ll_objs_checked_phase2 = le64_to_cpu(src->ll_objs_checked_phase2);
765         des->ll_objs_failed_phase2 = le64_to_cpu(src->ll_objs_failed_phase2);
766         for (i = 0; i < LLIT_MAX; i++)
767                 des->ll_objs_repaired[i] =
768                                 le64_to_cpu(src->ll_objs_repaired[i]);
769         des->ll_objs_skipped = le64_to_cpu(src->ll_objs_skipped);
770         des->ll_bitmap_size = le32_to_cpu(src->ll_bitmap_size);
771 }
772
773 static void lfsck_layout_cpu_to_le(struct lfsck_layout *des,
774                                    const struct lfsck_layout *src)
775 {
776         int i;
777
778         des->ll_magic = cpu_to_le32(src->ll_magic);
779         des->ll_status = cpu_to_le32(src->ll_status);
780         des->ll_flags = cpu_to_le32(src->ll_flags);
781         des->ll_success_count = cpu_to_le32(src->ll_success_count);
782         des->ll_run_time_phase1 = cpu_to_le32(src->ll_run_time_phase1);
783         des->ll_run_time_phase2 = cpu_to_le32(src->ll_run_time_phase2);
784         des->ll_time_last_complete = cpu_to_le64(src->ll_time_last_complete);
785         des->ll_time_latest_start = cpu_to_le64(src->ll_time_latest_start);
786         des->ll_time_last_checkpoint =
787                                 cpu_to_le64(src->ll_time_last_checkpoint);
788         des->ll_pos_latest_start = cpu_to_le64(src->ll_pos_latest_start);
789         des->ll_pos_last_checkpoint = cpu_to_le64(src->ll_pos_last_checkpoint);
790         des->ll_pos_first_inconsistent =
791                         cpu_to_le64(src->ll_pos_first_inconsistent);
792         des->ll_objs_checked_phase1 = cpu_to_le64(src->ll_objs_checked_phase1);
793         des->ll_objs_failed_phase1 = cpu_to_le64(src->ll_objs_failed_phase1);
794         des->ll_objs_checked_phase2 = cpu_to_le64(src->ll_objs_checked_phase2);
795         des->ll_objs_failed_phase2 = cpu_to_le64(src->ll_objs_failed_phase2);
796         for (i = 0; i < LLIT_MAX; i++)
797                 des->ll_objs_repaired[i] =
798                                 cpu_to_le64(src->ll_objs_repaired[i]);
799         des->ll_objs_skipped = cpu_to_le64(src->ll_objs_skipped);
800         des->ll_bitmap_size = cpu_to_le32(src->ll_bitmap_size);
801 }
802
803 /**
804  * Load the OST bitmap from the lfsck_layout trace file.
805  *
806  * \param[in] env       pointer to the thread context
807  * \param[in] com       pointer to the lfsck component
808  *
809  * \retval              0 for success
810  * \retval              negative error number on failure or data corruption
811  */
812 static int lfsck_layout_load_bitmap(const struct lu_env *env,
813                                     struct lfsck_component *com)
814 {
815         struct dt_object                *obj    = com->lc_obj;
816         struct lfsck_assistant_data     *lad    = com->lc_data;
817         struct lfsck_layout             *lo     = com->lc_file_ram;
818         cfs_bitmap_t                    *bitmap = lad->lad_bitmap;
819         loff_t                           pos    = com->lc_file_size;
820         ssize_t                          size;
821         __u32                            nbits;
822         int                              rc;
823         ENTRY;
824
825         if (com->lc_lfsck->li_ost_descs.ltd_tgts_bitmap->size >
826             lo->ll_bitmap_size)
827                 nbits = com->lc_lfsck->li_ost_descs.ltd_tgts_bitmap->size;
828         else
829                 nbits = lo->ll_bitmap_size;
830
831         if (unlikely(nbits < BITS_PER_LONG))
832                 nbits = BITS_PER_LONG;
833
834         if (nbits > bitmap->size) {
835                 __u32 new_bits = bitmap->size;
836                 cfs_bitmap_t *new_bitmap;
837
838                 while (new_bits < nbits)
839                         new_bits <<= 1;
840
841                 new_bitmap = CFS_ALLOCATE_BITMAP(new_bits);
842                 if (new_bitmap == NULL)
843                         RETURN(-ENOMEM);
844
845                 lad->lad_bitmap = new_bitmap;
846                 CFS_FREE_BITMAP(bitmap);
847                 bitmap = new_bitmap;
848         }
849
850         if (lo->ll_bitmap_size == 0) {
851                 lad->lad_incomplete = 0;
852                 CFS_RESET_BITMAP(bitmap);
853
854                 RETURN(0);
855         }
856
857         size = (lo->ll_bitmap_size + 7) >> 3;
858         rc = dt_read(env, obj, lfsck_buf_get(env, bitmap->data, size), &pos);
859         if (rc != size)
860                 RETURN(rc >= 0 ? -EINVAL : rc);
861
862         if (cfs_bitmap_check_empty(bitmap))
863                 lad->lad_incomplete = 0;
864         else
865                 lad->lad_incomplete = 1;
866
867         RETURN(0);
868 }
869
870 /**
871  * Load the layout LFSCK trace file from disk.
872  *
873  * The layout LFSCK trace file records the layout LFSCK status information
874  * and other statistics, such as how many objects have been scanned, and how
875  * many objects have been repaired, and etc. It also contains the bitmap for
876  * failed OSTs during the layout LFSCK. All these information will be loaded
877  * from disk to RAM when the layout LFSCK component setup.
878  *
879  * \param[in] env       pointer to the thread context
880  * \param[in] com       pointer to the lfsck component
881  *
882  * \retval              positive number for file data corruption, the caller
883  *                      should reset the layout LFSCK trace file
884  * \retval              0 for success
885  * \retval              negative error number on failure
886  */
887 static int lfsck_layout_load(const struct lu_env *env,
888                              struct lfsck_component *com)
889 {
890         struct lfsck_layout             *lo     = com->lc_file_ram;
891         ssize_t                          size   = com->lc_file_size;
892         loff_t                           pos    = 0;
893         int                              rc;
894
895         rc = dt_read(env, com->lc_obj,
896                      lfsck_buf_get(env, com->lc_file_disk, size), &pos);
897         if (rc == 0) {
898                 return -ENOENT;
899         } else if (rc < 0) {
900                 CDEBUG(D_LFSCK, "%s: failed to load lfsck_layout: rc = %d\n",
901                        lfsck_lfsck2name(com->lc_lfsck), rc);
902                 return rc;
903         } else if (rc != size) {
904                 CDEBUG(D_LFSCK, "%s: lfsck_layout size %u != %u; reset it\n",
905                        lfsck_lfsck2name(com->lc_lfsck), rc, (unsigned int)size);
906                 return 1;
907         }
908
909         lfsck_layout_le_to_cpu(lo, com->lc_file_disk);
910         if (lo->ll_magic != LFSCK_LAYOUT_MAGIC) {
911                 CDEBUG(D_LFSCK, "%s: invalid lfsck_layout magic %#x != %#x, "
912                        "to be reset\n", lfsck_lfsck2name(com->lc_lfsck),
913                        lo->ll_magic, LFSCK_LAYOUT_MAGIC);
914                 return 1;
915         }
916
917         return 0;
918 }
919
920 /**
921  * Store the layout LFSCK trace file on disk.
922  *
923  * The layout LFSCK trace file records the layout LFSCK status information
924  * and other statistics, such as how many objects have been scanned, and how
925  * many objects have been repaired, and etc. It also contains the bitmap for
926  * failed OSTs during the layout LFSCK. All these information will be synced
927  * from RAM to disk periodically.
928  *
929  * \param[in] env       pointer to the thread context
930  * \param[in] com       pointer to the lfsck component
931  *
932  * \retval              0 for success
933  * \retval              negative error number on failure
934  */
935 static int lfsck_layout_store(const struct lu_env *env,
936                               struct lfsck_component *com)
937 {
938         struct dt_object        *obj    = com->lc_obj;
939         struct lfsck_instance   *lfsck  = com->lc_lfsck;
940         struct lfsck_layout     *lo_ram = com->lc_file_ram;
941         struct lfsck_layout     *lo     = com->lc_file_disk;
942         struct thandle          *th;
943         struct dt_device        *dev    = lfsck->li_bottom;
944         cfs_bitmap_t            *bitmap = NULL;
945         loff_t                   pos;
946         ssize_t                  size   = com->lc_file_size;
947         __u32                    nbits  = 0;
948         int                      rc;
949         ENTRY;
950
951         if (lfsck->li_master) {
952                 struct lfsck_assistant_data *lad = com->lc_data;
953
954                 bitmap = lad->lad_bitmap;
955                 nbits = bitmap->size;
956
957                 LASSERT(nbits > 0);
958                 LASSERTF((nbits & 7) == 0, "Invalid nbits %u\n", nbits);
959         }
960
961         lo_ram->ll_bitmap_size = nbits;
962         lfsck_layout_cpu_to_le(lo, lo_ram);
963         th = dt_trans_create(env, dev);
964         if (IS_ERR(th))
965                 GOTO(log, rc = PTR_ERR(th));
966
967         rc = dt_declare_record_write(env, obj, lfsck_buf_get(env, lo, size),
968                                      (loff_t)0, th);
969         if (rc != 0)
970                 GOTO(out, rc);
971
972         if (bitmap != NULL) {
973                 rc = dt_declare_record_write(env, obj,
974                                 lfsck_buf_get(env, bitmap->data, nbits >> 3),
975                                 (loff_t)size, th);
976                 if (rc != 0)
977                         GOTO(out, rc);
978         }
979
980         rc = dt_trans_start_local(env, dev, th);
981         if (rc != 0)
982                 GOTO(out, rc);
983
984         pos = 0;
985         rc = dt_record_write(env, obj, lfsck_buf_get(env, lo, size), &pos, th);
986         if (rc != 0)
987                 GOTO(out, rc);
988
989         if (bitmap != NULL) {
990                 pos = size;
991                 rc = dt_record_write(env, obj,
992                                 lfsck_buf_get(env, bitmap->data, nbits >> 3),
993                                 &pos, th);
994         }
995
996         GOTO(out, rc);
997
998 out:
999         dt_trans_stop(env, dev, th);
1000
1001 log:
1002         if (rc != 0)
1003                 CDEBUG(D_LFSCK, "%s: fail to store lfsck_layout: rc = %d\n",
1004                        lfsck_lfsck2name(lfsck), rc);
1005
1006         return rc;
1007 }
1008
1009 static int lfsck_layout_init(const struct lu_env *env,
1010                              struct lfsck_component *com)
1011 {
1012         struct lfsck_layout *lo = com->lc_file_ram;
1013         int rc;
1014
1015         memset(lo, 0, com->lc_file_size);
1016         lo->ll_magic = LFSCK_LAYOUT_MAGIC;
1017         lo->ll_status = LS_INIT;
1018         down_write(&com->lc_sem);
1019         rc = lfsck_layout_store(env, com);
1020         up_write(&com->lc_sem);
1021
1022         return rc;
1023 }
1024
1025 static int fid_is_for_ostobj(const struct lu_env *env, struct dt_device *dt,
1026                              struct dt_object *obj, const struct lu_fid *fid)
1027 {
1028         struct seq_server_site  *ss     = lu_site2seq(dt->dd_lu_dev.ld_site);
1029         struct lu_seq_range     *range  = &lfsck_env_info(env)->lti_range;
1030         struct lustre_mdt_attrs *lma;
1031         int                      rc;
1032
1033         fld_range_set_any(range);
1034         rc = fld_server_lookup(env, ss->ss_server_fld, fid_seq(fid), range);
1035         if (rc == 0) {
1036                 if (fld_range_is_ost(range))
1037                         return 1;
1038
1039                 return 0;
1040         }
1041
1042         lma = &lfsck_env_info(env)->lti_lma;
1043         rc = dt_xattr_get(env, obj, lfsck_buf_get(env, lma, sizeof(*lma)),
1044                           XATTR_NAME_LMA, BYPASS_CAPA);
1045         if (rc == sizeof(*lma)) {
1046                 lustre_lma_swab(lma);
1047
1048                 return lma->lma_compat & LMAC_FID_ON_OST ? 1 : 0;
1049         }
1050
1051         rc = dt_xattr_get(env, obj, &LU_BUF_NULL, XATTR_NAME_FID, BYPASS_CAPA);
1052
1053         return rc > 0;
1054 }
1055
1056 static struct lfsck_layout_seq *
1057 lfsck_layout_seq_lookup(struct lfsck_layout_slave_data *llsd, __u64 seq)
1058 {
1059         struct lfsck_layout_seq *lls;
1060
1061         list_for_each_entry(lls, &llsd->llsd_seq_list, lls_list) {
1062                 if (lls->lls_seq == seq)
1063                         return lls;
1064
1065                 if (lls->lls_seq > seq)
1066                         return NULL;
1067         }
1068
1069         return NULL;
1070 }
1071
1072 static void
1073 lfsck_layout_seq_insert(struct lfsck_layout_slave_data *llsd,
1074                         struct lfsck_layout_seq *lls)
1075 {
1076         struct lfsck_layout_seq *tmp;
1077         struct list_head        *pos = &llsd->llsd_seq_list;
1078
1079         list_for_each_entry(tmp, &llsd->llsd_seq_list, lls_list) {
1080                 if (lls->lls_seq < tmp->lls_seq) {
1081                         pos = &tmp->lls_list;
1082                         break;
1083                 }
1084         }
1085         list_add_tail(&lls->lls_list, pos);
1086 }
1087
1088 static int
1089 lfsck_layout_lastid_create(const struct lu_env *env,
1090                            struct lfsck_instance *lfsck,
1091                            struct dt_object *obj)
1092 {
1093         struct lfsck_thread_info *info   = lfsck_env_info(env);
1094         struct lu_attr           *la     = &info->lti_la;
1095         struct dt_object_format  *dof    = &info->lti_dof;
1096         struct lfsck_bookmark    *bk     = &lfsck->li_bookmark_ram;
1097         struct dt_device         *dt     = lfsck->li_bottom;
1098         struct thandle           *th;
1099         __u64                     lastid = 0;
1100         loff_t                    pos    = 0;
1101         int                       rc;
1102         ENTRY;
1103
1104         if (bk->lb_param & LPF_DRYRUN)
1105                 return 0;
1106
1107         memset(la, 0, sizeof(*la));
1108         la->la_mode = S_IFREG |  S_IRUGO | S_IWUSR;
1109         la->la_valid = LA_MODE | LA_UID | LA_GID;
1110         dof->dof_type = dt_mode_to_dft(S_IFREG);
1111
1112         th = dt_trans_create(env, dt);
1113         if (IS_ERR(th))
1114                 GOTO(log, rc = PTR_ERR(th));
1115
1116         rc = dt_declare_create(env, obj, la, NULL, dof, th);
1117         if (rc != 0)
1118                 GOTO(stop, rc);
1119
1120         rc = dt_declare_record_write(env, obj,
1121                                      lfsck_buf_get(env, &lastid,
1122                                                    sizeof(lastid)),
1123                                      pos, th);
1124         if (rc != 0)
1125                 GOTO(stop, rc);
1126
1127         rc = dt_trans_start_local(env, dt, th);
1128         if (rc != 0)
1129                 GOTO(stop, rc);
1130
1131         dt_write_lock(env, obj, 0);
1132         if (likely(dt_object_exists(obj) == 0)) {
1133                 rc = dt_create(env, obj, la, NULL, dof, th);
1134                 if (rc == 0)
1135                         rc = dt_record_write(env, obj,
1136                                 lfsck_buf_get(env, &lastid, sizeof(lastid)),
1137                                 &pos, th);
1138         }
1139         dt_write_unlock(env, obj);
1140
1141         GOTO(stop, rc);
1142
1143 stop:
1144         dt_trans_stop(env, dt, th);
1145
1146 log:
1147         CDEBUG(D_LFSCK, "%s: layout LFSCK will create LAST_ID for <seq> "
1148                LPX64": rc = %d\n",
1149                lfsck_lfsck2name(lfsck), fid_seq(lfsck_dto2fid(obj)), rc);
1150
1151         return rc;
1152 }
1153
1154 static int
1155 lfsck_layout_lastid_reload(const struct lu_env *env,
1156                            struct lfsck_component *com,
1157                            struct lfsck_layout_seq *lls)
1158 {
1159         __u64   lastid;
1160         loff_t  pos     = 0;
1161         int     rc;
1162
1163         dt_read_lock(env, lls->lls_lastid_obj, 0);
1164         rc = dt_record_read(env, lls->lls_lastid_obj,
1165                             lfsck_buf_get(env, &lastid, sizeof(lastid)), &pos);
1166         dt_read_unlock(env, lls->lls_lastid_obj);
1167         if (unlikely(rc != 0))
1168                 return rc;
1169
1170         lastid = le64_to_cpu(lastid);
1171         if (lastid < lls->lls_lastid_known) {
1172                 struct lfsck_instance   *lfsck  = com->lc_lfsck;
1173                 struct lfsck_layout     *lo     = com->lc_file_ram;
1174
1175                 lls->lls_lastid = lls->lls_lastid_known;
1176                 lls->lls_dirty = 1;
1177                 if (!(lo->ll_flags & LF_CRASHED_LASTID)) {
1178                         LASSERT(lfsck->li_out_notify != NULL);
1179
1180                         lfsck->li_out_notify(env, lfsck->li_out_notify_data,
1181                                              LE_LASTID_REBUILDING);
1182                         lo->ll_flags |= LF_CRASHED_LASTID;
1183
1184                         CDEBUG(D_LFSCK, "%s: layout LFSCK finds crashed "
1185                                "LAST_ID file (1) for the sequence "LPX64
1186                                ", old value "LPU64", known value "LPU64"\n",
1187                                lfsck_lfsck2name(lfsck), lls->lls_seq,
1188                                lastid, lls->lls_lastid);
1189                 }
1190         } else if (lastid >= lls->lls_lastid) {
1191                 lls->lls_lastid = lastid;
1192                 lls->lls_dirty = 0;
1193         }
1194
1195         return 0;
1196 }
1197
1198 static int
1199 lfsck_layout_lastid_store(const struct lu_env *env,
1200                           struct lfsck_component *com)
1201 {
1202         struct lfsck_instance           *lfsck  = com->lc_lfsck;
1203         struct lfsck_bookmark           *bk     = &lfsck->li_bookmark_ram;
1204         struct dt_device                *dt     = lfsck->li_bottom;
1205         struct lfsck_layout_slave_data  *llsd   = com->lc_data;
1206         struct lfsck_layout_seq         *lls;
1207         struct thandle                  *th;
1208         __u64                            lastid;
1209         int                              rc     = 0;
1210         int                              rc1    = 0;
1211
1212         list_for_each_entry(lls, &llsd->llsd_seq_list, lls_list) {
1213                 loff_t pos = 0;
1214
1215                 if (!lls->lls_dirty)
1216                         continue;
1217
1218                 CDEBUG(D_LFSCK, "%s: layout LFSCK will sync the LAST_ID for "
1219                        "<seq> "LPX64" as <oid> "LPU64"\n",
1220                        lfsck_lfsck2name(lfsck), lls->lls_seq, lls->lls_lastid);
1221
1222                 if (bk->lb_param & LPF_DRYRUN) {
1223                         lls->lls_dirty = 0;
1224                         continue;
1225                 }
1226
1227                 th = dt_trans_create(env, dt);
1228                 if (IS_ERR(th)) {
1229                         rc1 = PTR_ERR(th);
1230                         CDEBUG(D_LFSCK, "%s: layout LFSCK failed to store "
1231                                "the LAST_ID for <seq> "LPX64"(1): rc = %d\n",
1232                                lfsck_lfsck2name(com->lc_lfsck),
1233                                lls->lls_seq, rc1);
1234                         continue;
1235                 }
1236
1237                 lastid = cpu_to_le64(lls->lls_lastid);
1238                 rc = dt_declare_record_write(env, lls->lls_lastid_obj,
1239                                              lfsck_buf_get(env, &lastid,
1240                                                            sizeof(lastid)),
1241                                              pos, th);
1242                 if (rc != 0)
1243                         goto stop;
1244
1245                 rc = dt_trans_start_local(env, dt, th);
1246                 if (rc != 0)
1247                         goto stop;
1248
1249                 dt_write_lock(env, lls->lls_lastid_obj, 0);
1250                 rc = dt_record_write(env, lls->lls_lastid_obj,
1251                                      lfsck_buf_get(env, &lastid,
1252                                      sizeof(lastid)), &pos, th);
1253                 dt_write_unlock(env, lls->lls_lastid_obj);
1254                 if (rc == 0)
1255                         lls->lls_dirty = 0;
1256
1257 stop:
1258                 dt_trans_stop(env, dt, th);
1259                 if (rc != 0) {
1260                         rc1 = rc;
1261                         CDEBUG(D_LFSCK, "%s: layout LFSCK failed to store "
1262                                "the LAST_ID for <seq> "LPX64"(2): rc = %d\n",
1263                                lfsck_lfsck2name(com->lc_lfsck),
1264                                lls->lls_seq, rc1);
1265                 }
1266         }
1267
1268         return rc1;
1269 }
1270
1271 static int
1272 lfsck_layout_lastid_load(const struct lu_env *env,
1273                          struct lfsck_component *com,
1274                          struct lfsck_layout_seq *lls)
1275 {
1276         struct lfsck_instance   *lfsck  = com->lc_lfsck;
1277         struct lfsck_layout     *lo     = com->lc_file_ram;
1278         struct lu_fid           *fid    = &lfsck_env_info(env)->lti_fid;
1279         struct dt_object        *obj;
1280         loff_t                   pos    = 0;
1281         int                      rc;
1282         ENTRY;
1283
1284         lu_last_id_fid(fid, lls->lls_seq, lfsck_dev_idx(lfsck->li_bottom));
1285         obj = dt_locate(env, lfsck->li_bottom, fid);
1286         if (IS_ERR(obj))
1287                 RETURN(PTR_ERR(obj));
1288
1289         /* LAST_ID crashed, to be rebuilt */
1290         if (dt_object_exists(obj) == 0) {
1291                 if (!(lo->ll_flags & LF_CRASHED_LASTID)) {
1292                         LASSERT(lfsck->li_out_notify != NULL);
1293
1294                         lfsck->li_out_notify(env, lfsck->li_out_notify_data,
1295                                              LE_LASTID_REBUILDING);
1296                         lo->ll_flags |= LF_CRASHED_LASTID;
1297
1298                         CDEBUG(D_LFSCK, "%s: layout LFSCK cannot find the "
1299                                "LAST_ID file for sequence "LPX64"\n",
1300                                lfsck_lfsck2name(lfsck), lls->lls_seq);
1301
1302                         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_DELAY4) &&
1303                             cfs_fail_val > 0) {
1304                                 struct l_wait_info lwi = LWI_TIMEOUT(
1305                                                 cfs_time_seconds(cfs_fail_val),
1306                                                 NULL, NULL);
1307
1308                                 /* Some others may changed the cfs_fail_val
1309                                  * as zero after above check, re-check it for
1310                                  * sure to avoid falling into wait for ever. */
1311                                 if (likely(lwi.lwi_timeout > 0)) {
1312                                         struct ptlrpc_thread *thread =
1313                                                 &lfsck->li_thread;
1314
1315                                         up_write(&com->lc_sem);
1316                                         l_wait_event(thread->t_ctl_waitq,
1317                                                      !thread_is_running(thread),
1318                                                      &lwi);
1319                                         down_write(&com->lc_sem);
1320                                 }
1321                         }
1322                 }
1323
1324                 rc = lfsck_layout_lastid_create(env, lfsck, obj);
1325         } else {
1326                 dt_read_lock(env, obj, 0);
1327                 rc = dt_read(env, obj,
1328                         lfsck_buf_get(env, &lls->lls_lastid, sizeof(__u64)),
1329                         &pos);
1330                 dt_read_unlock(env, obj);
1331                 if (rc != 0 && rc != sizeof(__u64))
1332                         GOTO(out, rc = (rc > 0 ? -EFAULT : rc));
1333
1334                 if (rc == 0 && !(lo->ll_flags & LF_CRASHED_LASTID)) {
1335                         LASSERT(lfsck->li_out_notify != NULL);
1336
1337                         lfsck->li_out_notify(env, lfsck->li_out_notify_data,
1338                                              LE_LASTID_REBUILDING);
1339                         lo->ll_flags |= LF_CRASHED_LASTID;
1340
1341                         CDEBUG(D_LFSCK, "%s: layout LFSCK finds invalid "
1342                                "LAST_ID file for the sequence "LPX64
1343                                ": rc = %d\n",
1344                                lfsck_lfsck2name(lfsck), lls->lls_seq, rc);
1345                 }
1346
1347                 lls->lls_lastid = le64_to_cpu(lls->lls_lastid);
1348                 rc = 0;
1349         }
1350
1351         GOTO(out, rc);
1352
1353 out:
1354         if (rc != 0)
1355                 lfsck_object_put(env, obj);
1356         else
1357                 lls->lls_lastid_obj = obj;
1358
1359         return rc;
1360 }
1361
1362 static void lfsck_layout_record_failure(const struct lu_env *env,
1363                                         struct lfsck_instance *lfsck,
1364                                         struct lfsck_layout *lo)
1365 {
1366         __u64 cookie;
1367
1368         lo->ll_objs_failed_phase1++;
1369         cookie = lfsck->li_obj_oit->do_index_ops->dio_it.store(env,
1370                                                         lfsck->li_di_oit);
1371         if (lo->ll_pos_first_inconsistent == 0 ||
1372             lo->ll_pos_first_inconsistent < cookie) {
1373                 lo->ll_pos_first_inconsistent = cookie;
1374
1375                 CDEBUG(D_LFSCK, "%s: layout LFSCK hit first non-repaired "
1376                        "inconsistency at the pos ["LPU64"]\n",
1377                        lfsck_lfsck2name(lfsck),
1378                        lo->ll_pos_first_inconsistent);
1379         }
1380 }
1381
1382 static int lfsck_layout_double_scan_result(const struct lu_env *env,
1383                                            struct lfsck_component *com,
1384                                            int rc)
1385 {
1386         struct lfsck_instance   *lfsck = com->lc_lfsck;
1387         struct lfsck_layout     *lo    = com->lc_file_ram;
1388
1389         down_write(&com->lc_sem);
1390         lo->ll_run_time_phase2 += cfs_duration_sec(cfs_time_current() +
1391                                 HALF_SEC - lfsck->li_time_last_checkpoint);
1392         lo->ll_time_last_checkpoint = cfs_time_current_sec();
1393         lo->ll_objs_checked_phase2 += com->lc_new_checked;
1394
1395         if (rc > 0) {
1396                 if (lo->ll_flags & LF_INCOMPLETE) {
1397                         lo->ll_status = LS_PARTIAL;
1398                 } else {
1399                         if (lfsck->li_master) {
1400                                 struct lfsck_assistant_data *lad = com->lc_data;
1401
1402                                 if (lad->lad_incomplete)
1403                                         lo->ll_status = LS_PARTIAL;
1404                                 else
1405                                         lo->ll_status = LS_COMPLETED;
1406                         } else {
1407                                 lo->ll_status = LS_COMPLETED;
1408                         }
1409                 }
1410                 if (!(lfsck->li_bookmark_ram.lb_param & LPF_DRYRUN))
1411                         lo->ll_flags &= ~(LF_SCANNED_ONCE | LF_INCONSISTENT);
1412                 lo->ll_time_last_complete = lo->ll_time_last_checkpoint;
1413                 lo->ll_success_count++;
1414         } else if (rc == 0) {
1415                 if (lfsck->li_status != 0)
1416                         lo->ll_status = lfsck->li_status;
1417                 else
1418                         lo->ll_status = LS_STOPPED;
1419         } else {
1420                 lo->ll_status = LS_FAILED;
1421         }
1422
1423         rc = lfsck_layout_store(env, com);
1424         up_write(&com->lc_sem);
1425
1426         return rc;
1427 }
1428
1429 static int lfsck_layout_trans_stop(const struct lu_env *env,
1430                                    struct dt_device *dev,
1431                                    struct thandle *handle, int result)
1432 {
1433         int rc;
1434
1435         handle->th_result = result;
1436         rc = dt_trans_stop(env, dev, handle);
1437         if (rc > 0)
1438                 rc = 0;
1439         else if (rc == 0)
1440                 rc = 1;
1441
1442         return rc;
1443 }
1444
1445 /**
1446  * Get the system default stripe size.
1447  *
1448  * \param[in] env       pointer to the thread context
1449  * \param[in] lfsck     pointer to the lfsck instance
1450  * \param[out] size     pointer to the default stripe size
1451  *
1452  * \retval              0 for success
1453  * \retval              negative error number on failure
1454  */
1455 static int lfsck_layout_get_def_stripesize(const struct lu_env *env,
1456                                            struct lfsck_instance *lfsck,
1457                                            __u32 *size)
1458 {
1459         struct lov_user_md      *lum = &lfsck_env_info(env)->lti_lum;
1460         struct dt_object        *root;
1461         int                      rc;
1462
1463         root = dt_locate(env, lfsck->li_next, &lfsck->li_local_root_fid);
1464         if (IS_ERR(root))
1465                 return PTR_ERR(root);
1466
1467         /* Get the default stripe size via xattr_get on the backend root. */
1468         rc = dt_xattr_get(env, root, lfsck_buf_get(env, lum, sizeof(*lum)),
1469                           XATTR_NAME_LOV, BYPASS_CAPA);
1470         if (rc > 0) {
1471                 /* The lum->lmm_stripe_size is LE mode. The *size also
1472                  * should be LE mode. So it is unnecessary to convert. */
1473                 *size = lum->lmm_stripe_size;
1474                 rc = 0;
1475         } else if (unlikely(rc == 0)) {
1476                 rc = -EINVAL;
1477         }
1478
1479         lfsck_object_put(env, root);
1480
1481         return rc;
1482 }
1483
1484 /**
1485  * \retval       +1: repaired
1486  * \retval        0: did nothing
1487  * \retval      -ve: on error
1488  */
1489 static int lfsck_layout_refill_lovea(const struct lu_env *env,
1490                                      struct thandle *handle,
1491                                      struct dt_object *parent,
1492                                      struct lu_fid *cfid,
1493                                      struct lu_buf *buf,
1494                                      struct lov_ost_data_v1 *slot,
1495                                      int fl, __u32 ost_idx)
1496 {
1497         struct ost_id           *oi     = &lfsck_env_info(env)->lti_oi;
1498         struct lov_mds_md_v1    *lmm    = buf->lb_buf;
1499         struct lu_buf            ea_buf;
1500         int                      rc;
1501         __u32                    magic;
1502         __u16                    count;
1503
1504         magic = le32_to_cpu(lmm->lmm_magic);
1505         count = le16_to_cpu(lmm->lmm_stripe_count);
1506
1507         fid_to_ostid(cfid, oi);
1508         ostid_cpu_to_le(oi, &slot->l_ost_oi);
1509         slot->l_ost_gen = cpu_to_le32(0);
1510         slot->l_ost_idx = cpu_to_le32(ost_idx);
1511
1512         if (le32_to_cpu(lmm->lmm_pattern) & LOV_PATTERN_F_HOLE) {
1513                 struct lov_ost_data_v1 *objs;
1514                 int                     i;
1515
1516                 if (magic == LOV_MAGIC_V1)
1517                         objs = &lmm->lmm_objects[0];
1518                 else
1519                         objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[0];
1520                 for (i = 0; i < count; i++, objs++) {
1521                         if (objs != slot && lovea_slot_is_dummy(objs))
1522                                 break;
1523                 }
1524
1525                 /* If the @slot is the last dummy slot to be refilled,
1526                  * then drop LOV_PATTERN_F_HOLE from lmm::lmm_pattern. */
1527                 if (i == count)
1528                         lmm->lmm_pattern &= ~cpu_to_le32(LOV_PATTERN_F_HOLE);
1529         }
1530
1531         lfsck_buf_init(&ea_buf, lmm, lov_mds_md_size(count, magic));
1532         rc = dt_xattr_set(env, parent, &ea_buf, XATTR_NAME_LOV, fl, handle,
1533                           BYPASS_CAPA);
1534         if (rc == 0)
1535                 rc = 1;
1536
1537         return rc;
1538 }
1539
1540 /**
1541  * \retval       +1: repaired
1542  * \retval        0: did nothing
1543  * \retval      -ve: on error
1544  */
1545 static int lfsck_layout_extend_lovea(const struct lu_env *env,
1546                                      struct lfsck_instance *lfsck,
1547                                      struct thandle *handle,
1548                                      struct dt_object *parent,
1549                                      struct lu_fid *cfid,
1550                                      struct lu_buf *buf, int fl,
1551                                      __u32 ost_idx, __u32 ea_off, bool reset)
1552 {
1553         struct lov_mds_md_v1    *lmm    = buf->lb_buf;
1554         struct lov_ost_data_v1  *objs;
1555         int                      rc;
1556         __u16                    count;
1557         bool                     hole   = false;
1558         ENTRY;
1559
1560         if (fl == LU_XATTR_CREATE || reset) {
1561                 __u32 pattern = LOV_PATTERN_RAID0;
1562
1563                 count = ea_off + 1;
1564                 LASSERT(buf->lb_len >= lov_mds_md_size(count, LOV_MAGIC_V1));
1565
1566                 if (ea_off != 0 || reset) {
1567                         pattern |= LOV_PATTERN_F_HOLE;
1568                         hole = true;
1569                 }
1570
1571                 memset(lmm, 0, buf->lb_len);
1572                 lmm->lmm_magic = cpu_to_le32(LOV_MAGIC_V1);
1573                 lmm->lmm_pattern = cpu_to_le32(pattern);
1574                 fid_to_lmm_oi(lfsck_dto2fid(parent), &lmm->lmm_oi);
1575                 lmm_oi_cpu_to_le(&lmm->lmm_oi, &lmm->lmm_oi);
1576
1577                 rc = lfsck_layout_get_def_stripesize(env, lfsck,
1578                                                      &lmm->lmm_stripe_size);
1579                 if (rc != 0)
1580                         RETURN(rc);
1581
1582                 objs = &lmm->lmm_objects[ea_off];
1583         } else {
1584                 __u32   magic = le32_to_cpu(lmm->lmm_magic);
1585                 int     gap;
1586
1587                 count = le16_to_cpu(lmm->lmm_stripe_count);
1588                 if (magic == LOV_MAGIC_V1)
1589                         objs = &lmm->lmm_objects[count];
1590                 else
1591                         objs = &((struct lov_mds_md_v3 *)lmm)->
1592                                                         lmm_objects[count];
1593
1594                 gap = ea_off - count;
1595                 if (gap >= 0)
1596                         count = ea_off + 1;
1597                 LASSERT(buf->lb_len >= lov_mds_md_size(count, magic));
1598
1599                 if (gap > 0) {
1600                         memset(objs, 0, gap * sizeof(*objs));
1601                         lmm->lmm_pattern |= cpu_to_le32(LOV_PATTERN_F_HOLE);
1602                         hole = true;
1603                 }
1604
1605                 lmm->lmm_layout_gen =
1606                             cpu_to_le16(le16_to_cpu(lmm->lmm_layout_gen) + 1);
1607                 objs += gap;
1608         }
1609
1610         lmm->lmm_stripe_count = cpu_to_le16(count);
1611         rc = lfsck_layout_refill_lovea(env, handle, parent, cfid, buf, objs,
1612                                        fl, ost_idx);
1613
1614         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant extend layout EA for "
1615                DFID": parent "DFID", OST-index %u, stripe-index %u, fl %d, "
1616                "reset %s, %s LOV EA hole: rc = %d\n",
1617                lfsck_lfsck2name(lfsck), PFID(cfid), PFID(lfsck_dto2fid(parent)),
1618                ost_idx, ea_off, fl, reset ? "yes" : "no",
1619                hole ? "with" : "without", rc);
1620
1621         RETURN(rc);
1622 }
1623
1624 /**
1625  * \retval       +1: repaired
1626  * \retval        0: did nothing
1627  * \retval      -ve: on error
1628  */
1629 static int lfsck_layout_update_pfid(const struct lu_env *env,
1630                                     struct lfsck_component *com,
1631                                     struct dt_object *parent,
1632                                     struct lu_fid *cfid,
1633                                     struct dt_device *cdev, __u32 ea_off)
1634 {
1635         struct filter_fid       *pfid   = &lfsck_env_info(env)->lti_new_pfid;
1636         struct dt_object        *child;
1637         struct thandle          *handle;
1638         const struct lu_fid     *tfid   = lu_object_fid(&parent->do_lu);
1639         struct lu_buf           *buf;
1640         int                      rc     = 0;
1641         ENTRY;
1642
1643         child = lfsck_object_find_by_dev(env, cdev, cfid);
1644         if (IS_ERR(child))
1645                 RETURN(PTR_ERR(child));
1646
1647         handle = dt_trans_create(env, cdev);
1648         if (IS_ERR(handle))
1649                 GOTO(out, rc = PTR_ERR(handle));
1650
1651         pfid->ff_parent.f_seq = cpu_to_le64(tfid->f_seq);
1652         pfid->ff_parent.f_oid = cpu_to_le32(tfid->f_oid);
1653         /* Currently, the filter_fid::ff_parent::f_ver is not the real parent
1654          * MDT-object's FID::f_ver, instead it is the OST-object index in its
1655          * parent MDT-object's layout EA. */
1656         pfid->ff_parent.f_stripe_idx = cpu_to_le32(ea_off);
1657         buf = lfsck_buf_get(env, pfid, sizeof(struct filter_fid));
1658
1659         rc = dt_declare_xattr_set(env, child, buf, XATTR_NAME_FID, 0, handle);
1660         if (rc != 0)
1661                 GOTO(stop, rc);
1662
1663         rc = dt_trans_start(env, cdev, handle);
1664         if (rc != 0)
1665                 GOTO(stop, rc);
1666
1667         rc = dt_xattr_set(env, child, buf, XATTR_NAME_FID, 0, handle,
1668                           BYPASS_CAPA);
1669
1670         GOTO(stop, rc = (rc == 0 ? 1 : rc));
1671
1672 stop:
1673         dt_trans_stop(env, cdev, handle);
1674
1675 out:
1676         lu_object_put(env, &child->do_lu);
1677
1678         return rc;
1679 }
1680
1681 /**
1682  * This function will create the MDT-object with the given (partial) LOV EA.
1683  *
1684  * Under some data corruption cases, the MDT-object of the file may be lost,
1685  * but its OST-objects, or some of them are there. The layout LFSCK needs to
1686  * re-create the MDT-object with the orphan OST-object(s) information.
1687  *
1688  * On the other hand, the LFSCK may has created some OST-object for repairing
1689  * dangling LOV EA reference, but as the LFSCK processing, it may find that
1690  * the old OST-object is there and should replace the former new created OST
1691  * object. Unfortunately, some others have modified such newly created object.
1692  * To keep the data (both new and old), the LFSCK will create MDT-object with
1693  * new FID to reference the original OST-object.
1694  *
1695  * \param[in] env       pointer to the thread context
1696  * \param[in] com       pointer to the lfsck component
1697  * \param[in] ltd       pointer to target device descriptor
1698  * \param[in] rec       pointer to the record for the orphan OST-object
1699  * \param[in] cfid      pointer to FID for the orphan OST-object
1700  * \param[in] infix     additional information, such as the FID for original
1701  *                      MDT-object and the stripe offset in the LOV EA
1702  * \param[in] type      the type for describing why the orphan MDT-object is
1703  *                      created. The rules are as following:
1704  *
1705  *  type "C":           Multiple OST-objects claim the same MDT-object and the
1706  *                      same slot in the layout EA. Then the LFSCK will create
1707  *                      new MDT-object(s) to hold the conflict OST-object(s).
1708  *
1709  *  type "N":           The orphan OST-object does not know which one was the
1710  *                      real parent MDT-object, so the LFSCK uses new FID for
1711  *                      its parent MDT-object.
1712  *
1713  *  type "R":           The orphan OST-object knows its parent MDT-object FID,
1714  *                      but does not know the position (the file name) in the
1715  *                      layout.
1716  *
1717  *  type "D":           The MDT-object is a directory, it may knows its parent
1718  *                      but because there is no valid linkEA, the LFSCK cannot
1719  *                      know where to put it back to the namespace.
1720  *  type "O":           The MDT-object has no linkEA, and there is no name
1721  *                      entry that references the MDT-object.
1722  *
1723  *  type "P":           The orphan object to be created was a parent directory
1724  *                      of some MDT-object which linkEA shows that the @orphan
1725  *                      object is missing.
1726  *
1727  * The orphan name will be like:
1728  * ${FID}-${infix}-${type}-${conflict_version}
1729  *
1730  * \param[in] ea_off    the stripe offset in the LOV EA
1731  *
1732  * \retval              positive on repaired something
1733  * \retval              0 if needs to repair nothing
1734  * \retval              negative error number on failure
1735  */
1736 static int lfsck_layout_recreate_parent(const struct lu_env *env,
1737                                         struct lfsck_component *com,
1738                                         struct lfsck_tgt_desc *ltd,
1739                                         struct lu_orphan_rec *rec,
1740                                         struct lu_fid *cfid,
1741                                         const char *infix,
1742                                         const char *type,
1743                                         __u32 ea_off)
1744 {
1745         struct lfsck_thread_info        *info   = lfsck_env_info(env);
1746         struct dt_insert_rec            *dtrec  = &info->lti_dt_rec;
1747         char                            *name   = info->lti_key;
1748         struct lu_attr                  *la     = &info->lti_la;
1749         struct dt_object_format         *dof    = &info->lti_dof;
1750         struct lfsck_instance           *lfsck  = com->lc_lfsck;
1751         struct lu_fid                   *pfid   = &rec->lor_fid;
1752         struct lu_fid                   *tfid   = &info->lti_fid3;
1753         struct dt_device                *next   = lfsck->li_next;
1754         struct dt_object                *pobj   = NULL;
1755         struct dt_object                *cobj   = NULL;
1756         struct thandle                  *th     = NULL;
1757         struct lu_buf                    pbuf   = { NULL };
1758         struct lu_buf                   *ea_buf = &info->lti_big_buf;
1759         struct lu_buf                    lov_buf;
1760         struct lustre_handle             lh     = { 0 };
1761         struct linkea_data               ldata  = { NULL };
1762         struct lu_buf                    linkea_buf;
1763         const struct lu_name            *pname;
1764         int                              size   = 0;
1765         int                              idx    = 0;
1766         int                              rc     = 0;
1767         ENTRY;
1768
1769         if (unlikely(lfsck->li_lpf_obj == NULL))
1770                 GOTO(log, rc = -ENXIO);
1771
1772         if (fid_is_zero(pfid)) {
1773                 struct filter_fid *ff = &info->lti_new_pfid;
1774
1775                 rc = lfsck_fid_alloc(env, lfsck, pfid, false);
1776                 if (rc != 0)
1777                         RETURN(rc);
1778
1779                 ff->ff_parent.f_seq = cpu_to_le64(pfid->f_seq);
1780                 ff->ff_parent.f_oid = cpu_to_le32(pfid->f_oid);
1781                 /* Currently, the filter_fid::ff_parent::f_ver is not the
1782                  * real parent MDT-object's FID::f_ver, instead it is the
1783                  * OST-object index in its parent MDT-object's layout EA. */
1784                 ff->ff_parent.f_stripe_idx = cpu_to_le32(ea_off);
1785                 lfsck_buf_init(&pbuf, ff, sizeof(struct filter_fid));
1786                 cobj = lfsck_object_find_by_dev(env, ltd->ltd_tgt, cfid);
1787                 if (IS_ERR(cobj))
1788                         GOTO(log, rc = PTR_ERR(cobj));
1789         }
1790
1791         pobj = lfsck_object_find_by_dev(env, lfsck->li_bottom, pfid);
1792         if (IS_ERR(pobj))
1793                 GOTO(put, rc = PTR_ERR(pobj));
1794
1795         LASSERT(infix != NULL);
1796         LASSERT(type != NULL);
1797
1798         do {
1799                 snprintf(name, NAME_MAX, DFID"%s-%s-%d", PFID(pfid), infix,
1800                          type, idx++);
1801                 rc = dt_lookup(env, lfsck->li_lpf_obj, (struct dt_rec *)tfid,
1802                                (const struct dt_key *)name, BYPASS_CAPA);
1803                 if (rc != 0 && rc != -ENOENT)
1804                         GOTO(put, rc);
1805         } while (rc == 0);
1806
1807         rc = linkea_data_new(&ldata,
1808                              &lfsck_env_info(env)->lti_linkea_buf);
1809         if (rc != 0)
1810                 GOTO(put, rc);
1811
1812         pname = lfsck_name_get_const(env, name, strlen(name));
1813         rc = linkea_add_buf(&ldata, pname, lfsck_dto2fid(lfsck->li_lpf_obj));
1814         if (rc != 0)
1815                 GOTO(put, rc);
1816
1817         memset(la, 0, sizeof(*la));
1818         la->la_uid = rec->lor_uid;
1819         la->la_gid = rec->lor_gid;
1820         la->la_mode = S_IFREG | S_IRUSR;
1821         la->la_valid = LA_MODE | LA_UID | LA_GID;
1822
1823         memset(dof, 0, sizeof(*dof));
1824         dof->dof_type = dt_mode_to_dft(S_IFREG);
1825
1826         size = lov_mds_md_size(ea_off + 1, LOV_MAGIC_V1);
1827         if (ea_buf->lb_len < size) {
1828                 lu_buf_realloc(ea_buf, size);
1829                 if (ea_buf->lb_buf == NULL)
1830                         GOTO(put, rc = -ENOMEM);
1831         }
1832
1833         /* Hold update lock on the .lustre/lost+found/MDTxxxx/.
1834          *
1835          * XXX: Currently, we do not grab the PDO lock as normal create cases,
1836          *      because creating MDT-object for orphan OST-object is rare, we
1837          *      do not much care about the performance. It can be improved in
1838          *      the future when needed. */
1839         rc = lfsck_ibits_lock(env, lfsck, lfsck->li_lpf_obj, &lh,
1840                               MDS_INODELOCK_UPDATE, LCK_EX);
1841         if (rc != 0)
1842                 GOTO(put, rc);
1843
1844         th = dt_trans_create(env, next);
1845         if (IS_ERR(th))
1846                 GOTO(unlock, rc = PTR_ERR(th));
1847
1848         /* 1a. Update OST-object's parent information remotely.
1849          *
1850          * If other subsequent modifications failed, then next LFSCK scanning
1851          * will process the OST-object as orphan again with known parent FID. */
1852         if (cobj != NULL) {
1853                 rc = dt_declare_xattr_set(env, cobj, &pbuf, XATTR_NAME_FID,
1854                                           0, th);
1855                 if (rc != 0)
1856                         GOTO(stop, rc);
1857         }
1858
1859         /* 2a. Create the MDT-object locally. */
1860         rc = dt_declare_create(env, pobj, la, NULL, dof, th);
1861         if (rc != 0)
1862                 GOTO(stop, rc);
1863
1864         /* 3a. Add layout EA for the MDT-object. */
1865         lfsck_buf_init(&lov_buf, ea_buf->lb_buf, size);
1866         rc = dt_declare_xattr_set(env, pobj, &lov_buf, XATTR_NAME_LOV,
1867                                   LU_XATTR_CREATE, th);
1868         if (rc != 0)
1869                 GOTO(stop, rc);
1870
1871         /* 4a. Insert the MDT-object to .lustre/lost+found/MDTxxxx/ */
1872         dtrec->rec_fid = pfid;
1873         dtrec->rec_type = S_IFREG;
1874         rc = dt_declare_insert(env, lfsck->li_lpf_obj,
1875                                (const struct dt_rec *)dtrec,
1876                                (const struct dt_key *)name, th);
1877         if (rc != 0)
1878                 GOTO(stop, rc);
1879
1880         /* 5a. insert linkEA for parent. */
1881         lfsck_buf_init(&linkea_buf, ldata.ld_buf->lb_buf,
1882                        ldata.ld_leh->leh_len);
1883         rc = dt_declare_xattr_set(env, pobj, &linkea_buf,
1884                                   XATTR_NAME_LINK, 0, th);
1885         if (rc != 0)
1886                 GOTO(stop, rc);
1887
1888         rc = dt_trans_start(env, next, th);
1889         if (rc != 0)
1890                 GOTO(stop, rc);
1891
1892         /* 1b. Update OST-object's parent information remotely. */
1893         if (cobj != NULL) {
1894                 rc = dt_xattr_set(env, cobj, &pbuf, XATTR_NAME_FID, 0, th,
1895                                   BYPASS_CAPA);
1896                 if (rc != 0)
1897                         GOTO(stop, rc);
1898         }
1899
1900         dt_write_lock(env, pobj, 0);
1901         /* 2b. Create the MDT-object locally. */
1902         rc = dt_create(env, pobj, la, NULL, dof, th);
1903         if (rc == 0)
1904                 /* 3b. Add layout EA for the MDT-object. */
1905                 rc = lfsck_layout_extend_lovea(env, lfsck, th, pobj, cfid,
1906                                                &lov_buf, LU_XATTR_CREATE,
1907                                                ltd->ltd_index, ea_off, false);
1908         dt_write_unlock(env, pobj);
1909         if (rc < 0)
1910                 GOTO(stop, rc);
1911
1912         /* 4b. Insert the MDT-object to .lustre/lost+found/MDTxxxx/ */
1913         rc = dt_insert(env, lfsck->li_lpf_obj, (const struct dt_rec *)dtrec,
1914                        (const struct dt_key *)name, th, BYPASS_CAPA, 1);
1915         if (rc != 0)
1916                 GOTO(stop, rc);
1917
1918         /* 5b. insert linkEA for parent. */
1919         rc = dt_xattr_set(env, pobj, &linkea_buf,
1920                           XATTR_NAME_LINK, 0, th, BYPASS_CAPA);
1921
1922         GOTO(stop, rc);
1923
1924 stop:
1925         dt_trans_stop(env, next, th);
1926
1927 unlock:
1928         lfsck_ibits_unlock(&lh, LCK_EX);
1929
1930 put:
1931         if (cobj != NULL && !IS_ERR(cobj))
1932                 lu_object_put(env, &cobj->do_lu);
1933         if (pobj != NULL && !IS_ERR(pobj))
1934                 lu_object_put(env, &pobj->do_lu);
1935
1936 log:
1937         if (rc < 0)
1938                 CDEBUG(D_LFSCK, "%s layout LFSCK assistant failed to "
1939                        "recreate the lost MDT-object: parent "DFID
1940                        ", child "DFID", OST-index %u, stripe-index %u, "
1941                        "infix %s, type %s: rc = %d\n",
1942                        lfsck_lfsck2name(lfsck), PFID(pfid), PFID(cfid),
1943                        ltd->ltd_index, ea_off, infix, type, rc);
1944
1945         return rc >= 0 ? 1 : rc;
1946 }
1947
1948 static int lfsck_layout_master_conditional_destroy(const struct lu_env *env,
1949                                                    struct lfsck_component *com,
1950                                                    const struct lu_fid *fid,
1951                                                    __u32 index)
1952 {
1953         struct lfsck_thread_info *info  = lfsck_env_info(env);
1954         struct lfsck_request     *lr    = &info->lti_lr;
1955         struct lfsck_instance    *lfsck = com->lc_lfsck;
1956         struct lfsck_tgt_desc    *ltd;
1957         struct ptlrpc_request    *req;
1958         struct lfsck_request     *tmp;
1959         struct obd_export        *exp;
1960         int                       rc    = 0;
1961         ENTRY;
1962
1963         ltd = lfsck_tgt_get(&lfsck->li_ost_descs, index);
1964         if (unlikely(ltd == NULL))
1965                 RETURN(-ENXIO);
1966
1967         exp = ltd->ltd_exp;
1968         if (!(exp_connect_flags(exp) & OBD_CONNECT_LFSCK))
1969                 GOTO(put, rc = -EOPNOTSUPP);
1970
1971         req = ptlrpc_request_alloc(class_exp2cliimp(exp), &RQF_LFSCK_NOTIFY);
1972         if (req == NULL)
1973                 GOTO(put, rc = -ENOMEM);
1974
1975         rc = ptlrpc_request_pack(req, LUSTRE_OBD_VERSION, LFSCK_NOTIFY);
1976         if (rc != 0) {
1977                 ptlrpc_request_free(req);
1978
1979                 GOTO(put, rc);
1980         }
1981
1982         memset(lr, 0, sizeof(*lr));
1983         lr->lr_event = LE_CONDITIONAL_DESTROY;
1984         lr->lr_active = LFSCK_TYPE_LAYOUT;
1985         lr->lr_fid = *fid;
1986
1987         tmp = req_capsule_client_get(&req->rq_pill, &RMF_LFSCK_REQUEST);
1988         *tmp = *lr;
1989         ptlrpc_request_set_replen(req);
1990
1991         rc = ptlrpc_queue_wait(req);
1992         ptlrpc_req_finished(req);
1993
1994         GOTO(put, rc);
1995
1996 put:
1997         lfsck_tgt_put(ltd);
1998
1999         return rc;
2000 }
2001
2002 static int lfsck_layout_slave_conditional_destroy(const struct lu_env *env,
2003                                                   struct lfsck_component *com,
2004                                                   struct lfsck_request *lr)
2005 {
2006         struct lfsck_thread_info        *info   = lfsck_env_info(env);
2007         struct lu_attr                  *la     = &info->lti_la;
2008         ldlm_policy_data_t              *policy = &info->lti_policy;
2009         struct ldlm_res_id              *resid  = &info->lti_resid;
2010         struct lfsck_instance           *lfsck  = com->lc_lfsck;
2011         struct dt_device                *dev    = lfsck->li_bottom;
2012         struct lu_fid                   *fid    = &lr->lr_fid;
2013         struct dt_object                *obj;
2014         struct thandle                  *th     = NULL;
2015         struct lustre_handle             lh     = { 0 };
2016         __u64                            flags  = 0;
2017         int                              rc     = 0;
2018         ENTRY;
2019
2020         obj = lfsck_object_find_by_dev(env, dev, fid);
2021         if (IS_ERR(obj))
2022                 RETURN(PTR_ERR(obj));
2023
2024         dt_read_lock(env, obj, 0);
2025         if (dt_object_exists(obj) == 0 ||
2026             lfsck_is_dead_obj(obj)) {
2027                 dt_read_unlock(env, obj);
2028
2029                 GOTO(put, rc = -ENOENT);
2030         }
2031
2032         /* Get obj's attr without lock firstly. */
2033         rc = dt_attr_get(env, obj, la, BYPASS_CAPA);
2034         dt_read_unlock(env, obj);
2035         if (rc != 0)
2036                 GOTO(put, rc);
2037
2038         if (likely(la->la_ctime != 0 || la->la_mode & S_ISUID))
2039                 GOTO(put, rc = -ETXTBSY);
2040
2041         /* Acquire extent lock on [0, EOF] to sync with all possible written. */
2042         LASSERT(lfsck->li_namespace != NULL);
2043
2044         memset(policy, 0, sizeof(*policy));
2045         policy->l_extent.end = OBD_OBJECT_EOF;
2046         ost_fid_build_resid(fid, resid);
2047         rc = ldlm_cli_enqueue_local(lfsck->li_namespace, resid, LDLM_EXTENT,
2048                                     policy, LCK_EX, &flags, ldlm_blocking_ast,
2049                                     ldlm_completion_ast, NULL, NULL, 0,
2050                                     LVB_T_NONE, NULL, &lh);
2051         if (rc != ELDLM_OK)
2052                 GOTO(put, rc = -EIO);
2053
2054         dt_write_lock(env, obj, 0);
2055         /* Get obj's attr within lock again. */
2056         rc = dt_attr_get(env, obj, la, BYPASS_CAPA);
2057         if (rc != 0)
2058                 GOTO(unlock, rc);
2059
2060         if (la->la_ctime != 0)
2061                 GOTO(unlock, rc = -ETXTBSY);
2062
2063         th = dt_trans_create(env, dev);
2064         if (IS_ERR(th))
2065                 GOTO(unlock, rc = PTR_ERR(th));
2066
2067         rc = dt_declare_ref_del(env, obj, th);
2068         if (rc != 0)
2069                 GOTO(stop, rc);
2070
2071         rc = dt_declare_destroy(env, obj, th);
2072         if (rc != 0)
2073                 GOTO(stop, rc);
2074
2075         rc = dt_trans_start_local(env, dev, th);
2076         if (rc != 0)
2077                 GOTO(stop, rc);
2078
2079         rc = dt_ref_del(env, obj, th);
2080         if (rc != 0)
2081                 GOTO(stop, rc);
2082
2083         rc = dt_destroy(env, obj, th);
2084         if (rc == 0)
2085                 CDEBUG(D_LFSCK, "%s: layout LFSCK destroyed the empty "
2086                        "OST-object "DFID" that was created for reparing "
2087                        "dangling referenced case. But the original missing "
2088                        "OST-object is found now.\n",
2089                        lfsck_lfsck2name(lfsck), PFID(fid));
2090
2091         GOTO(stop, rc);
2092
2093 stop:
2094         dt_trans_stop(env, dev, th);
2095
2096 unlock:
2097         dt_write_unlock(env, obj);
2098         ldlm_lock_decref(&lh, LCK_EX);
2099
2100 put:
2101         lu_object_put(env, &obj->do_lu);
2102
2103         return rc;
2104 }
2105
2106 /**
2107  * Some OST-object has occupied the specified layout EA slot.
2108  * Such OST-object may be generated by the LFSCK when repair
2109  * dangling referenced MDT-object, which can be indicated by
2110  * attr::la_ctime == 0 but without S_ISUID in la_mode. If it
2111  * is true and such OST-object has not been modified yet, we
2112  * will replace it with the orphan OST-object; otherwise the
2113  * LFSCK will create new MDT-object to reference the orphan.
2114  *
2115  * \retval       +1: repaired
2116  * \retval        0: did nothing
2117  * \retval      -ve: on error
2118  */
2119 static int lfsck_layout_conflict_create(const struct lu_env *env,
2120                                         struct lfsck_component *com,
2121                                         struct lfsck_tgt_desc *ltd,
2122                                         struct lu_orphan_rec *rec,
2123                                         struct dt_object *parent,
2124                                         struct lu_fid *cfid,
2125                                         struct lu_buf *ea_buf,
2126                                         struct lov_ost_data_v1 *slot,
2127                                         __u32 ea_off)
2128 {
2129         struct lfsck_thread_info *info          = lfsck_env_info(env);
2130         struct lu_fid            *cfid2         = &info->lti_fid2;
2131         struct ost_id            *oi            = &info->lti_oi;
2132         struct lov_mds_md_v1     *lmm           = ea_buf->lb_buf;
2133         struct dt_device         *dev           = com->lc_lfsck->li_bottom;
2134         struct thandle           *th            = NULL;
2135         struct lustre_handle      lh            = { 0 };
2136         __u32                     ost_idx2      = le32_to_cpu(slot->l_ost_idx);
2137         int                       rc            = 0;
2138         ENTRY;
2139
2140         ostid_le_to_cpu(&slot->l_ost_oi, oi);
2141         rc = ostid_to_fid(cfid2, oi, ost_idx2);
2142         if (rc != 0)
2143                 GOTO(out, rc);
2144
2145         /* Hold layout lock on the parent to prevent others to access. */
2146         rc = lfsck_ibits_lock(env, com->lc_lfsck, parent, &lh,
2147                               MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR,
2148                               LCK_EX);
2149         if (rc != 0)
2150                 GOTO(out, rc);
2151
2152         rc = lfsck_layout_master_conditional_destroy(env, com, cfid2, ost_idx2);
2153
2154         /* If the conflict OST-obejct is not created for fixing dangling
2155          * referenced MDT-object in former LFSCK check/repair, or it has
2156          * been modified by others, then we cannot destroy it. Re-create
2157          * a new MDT-object for the orphan OST-object. */
2158         if (rc == -ETXTBSY) {
2159                 /* No need the layout lock on the original parent. */
2160                 lfsck_ibits_unlock(&lh, LCK_EX);
2161
2162                 fid_zero(&rec->lor_fid);
2163                 snprintf(info->lti_tmpbuf, sizeof(info->lti_tmpbuf),
2164                          "-"DFID"-%x", PFID(lu_object_fid(&parent->do_lu)),
2165                          ea_off);
2166                 rc = lfsck_layout_recreate_parent(env, com, ltd, rec, cfid,
2167                                                 info->lti_tmpbuf, "C", ea_off);
2168
2169                 RETURN(rc);
2170         }
2171
2172         if (rc != 0 && rc != -ENOENT)
2173                 GOTO(unlock, rc);
2174
2175         th = dt_trans_create(env, dev);
2176         if (IS_ERR(th))
2177                 GOTO(unlock, rc = PTR_ERR(th));
2178
2179         rc = dt_declare_xattr_set(env, parent, ea_buf, XATTR_NAME_LOV,
2180                                   LU_XATTR_REPLACE, th);
2181         if (rc != 0)
2182                 GOTO(stop, rc);
2183
2184         rc = dt_trans_start_local(env, dev, th);
2185         if (rc != 0)
2186                 GOTO(stop, rc);
2187
2188         dt_write_lock(env, parent, 0);
2189         lmm->lmm_layout_gen = cpu_to_le16(le16_to_cpu(lmm->lmm_layout_gen) + 1);
2190         rc = lfsck_layout_refill_lovea(env, th, parent, cfid, ea_buf, slot,
2191                                        LU_XATTR_REPLACE, ltd->ltd_index);
2192         dt_write_unlock(env, parent);
2193
2194         GOTO(stop, rc);
2195
2196 stop:
2197         dt_trans_stop(env, dev, th);
2198
2199 unlock:
2200         lfsck_ibits_unlock(&lh, LCK_EX);
2201
2202 out:
2203         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant replaced the conflict "
2204                "OST-object "DFID" on the OST %x with the orphan "DFID" on "
2205                "the OST %x: parent "DFID", stripe-index %u: rc = %d\n",
2206                lfsck_lfsck2name(com->lc_lfsck), PFID(cfid2), ost_idx2,
2207                PFID(cfid), ltd->ltd_index, PFID(lfsck_dto2fid(parent)),
2208                ea_off, rc);
2209
2210         return rc >= 0 ? 1 : rc;
2211 }
2212
2213 /**
2214  * \retval       +1: repaired
2215  * \retval        0: did nothing
2216  * \retval      -ve: on error
2217  */
2218 static int lfsck_layout_recreate_lovea(const struct lu_env *env,
2219                                        struct lfsck_component *com,
2220                                        struct lfsck_tgt_desc *ltd,
2221                                        struct lu_orphan_rec *rec,
2222                                        struct dt_object *parent,
2223                                        struct lu_fid *cfid,
2224                                        __u32 ost_idx, __u32 ea_off)
2225 {
2226         struct lfsck_thread_info *info          = lfsck_env_info(env);
2227         struct lu_buf            *buf           = &info->lti_big_buf;
2228         struct lu_fid            *fid           = &info->lti_fid2;
2229         struct ost_id            *oi            = &info->lti_oi;
2230         struct lfsck_instance    *lfsck         = com->lc_lfsck;
2231         struct dt_device         *dt            = lfsck->li_bottom;
2232         struct lfsck_bookmark    *bk            = &lfsck->li_bookmark_ram;
2233         struct thandle            *handle       = NULL;
2234         size_t                    lovea_size;
2235         struct lov_mds_md_v1     *lmm;
2236         struct lov_ost_data_v1   *objs;
2237         struct lustre_handle      lh            = { 0 };
2238         __u32                     magic;
2239         int                       fl            = 0;
2240         int                       rc            = 0;
2241         int                       rc1;
2242         int                       i;
2243         __u16                     count;
2244         bool                      locked        = false;
2245         ENTRY;
2246
2247         rc = lfsck_ibits_lock(env, lfsck, parent, &lh,
2248                               MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR,
2249                               LCK_EX);
2250         if (rc != 0) {
2251                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant failed to recreate "
2252                        "LOV EA for "DFID": parent "DFID", OST-index %u, "
2253                        "stripe-index %u: rc = %d\n",
2254                        lfsck_lfsck2name(lfsck), PFID(cfid),
2255                        PFID(lfsck_dto2fid(parent)), ost_idx, ea_off, rc);
2256
2257                 RETURN(rc);
2258         }
2259
2260 again:
2261         if (locked) {
2262                 dt_write_unlock(env, parent);
2263                 locked = false;
2264         }
2265
2266         if (handle != NULL) {
2267                 dt_trans_stop(env, dt, handle);
2268                 handle = NULL;
2269         }
2270
2271         if (rc < 0)
2272                 GOTO(unlock_layout, rc);
2273
2274         lovea_size = rc;
2275         if (buf->lb_len < lovea_size) {
2276                 lu_buf_realloc(buf, lovea_size);
2277                 if (buf->lb_buf == NULL)
2278                         GOTO(unlock_layout, rc = -ENOMEM);
2279         }
2280
2281         if (!(bk->lb_param & LPF_DRYRUN)) {
2282                 handle = dt_trans_create(env, dt);
2283                 if (IS_ERR(handle))
2284                         GOTO(unlock_layout, rc = PTR_ERR(handle));
2285
2286                 rc = dt_declare_xattr_set(env, parent, buf, XATTR_NAME_LOV,
2287                                           fl, handle);
2288                 if (rc != 0)
2289                         GOTO(stop, rc);
2290
2291                 rc = dt_trans_start_local(env, dt, handle);
2292                 if (rc != 0)
2293                         GOTO(stop, rc);
2294         }
2295
2296         dt_write_lock(env, parent, 0);
2297         locked = true;
2298         rc = dt_xattr_get(env, parent, buf, XATTR_NAME_LOV, BYPASS_CAPA);
2299         if (rc == -ERANGE) {
2300                 rc = dt_xattr_get(env, parent, &LU_BUF_NULL, XATTR_NAME_LOV,
2301                                   BYPASS_CAPA);
2302                 LASSERT(rc != 0);
2303                 goto again;
2304         } else if (rc == -ENODATA || rc == 0) {
2305                 lovea_size = lov_mds_md_size(ea_off + 1, LOV_MAGIC_V1);
2306                 /* If the declared is not big enough, re-try. */
2307                 if (buf->lb_len < lovea_size) {
2308                         rc = lovea_size;
2309                         goto again;
2310                 }
2311                 fl = LU_XATTR_CREATE;
2312         } else if (rc < 0) {
2313                 GOTO(unlock_parent, rc);
2314         } else if (unlikely(buf->lb_len == 0)) {
2315                 goto again;
2316         } else {
2317                 fl = LU_XATTR_REPLACE;
2318                 lovea_size = rc;
2319         }
2320
2321         if (fl == LU_XATTR_CREATE) {
2322                 if (bk->lb_param & LPF_DRYRUN)
2323                         GOTO(unlock_parent, rc = 1);
2324
2325                 LASSERT(buf->lb_len >= lovea_size);
2326
2327                 rc = lfsck_layout_extend_lovea(env, lfsck, handle, parent, cfid,
2328                                                buf, fl, ost_idx, ea_off, false);
2329
2330                 GOTO(unlock_parent, rc);
2331         }
2332
2333         lmm = buf->lb_buf;
2334         rc1 = lfsck_layout_verify_header(lmm);
2335
2336         /* If the LOV EA crashed, the rebuild it. */
2337         if (rc1 == -EINVAL) {
2338                 if (bk->lb_param & LPF_DRYRUN)
2339                         GOTO(unlock_parent, rc = 1);
2340
2341                 LASSERT(buf->lb_len >= lovea_size);
2342
2343                 rc = lfsck_layout_extend_lovea(env, lfsck, handle, parent, cfid,
2344                                                buf, fl, ost_idx, ea_off, true);
2345
2346                 GOTO(unlock_parent, rc);
2347         }
2348
2349         /* For other unknown magic/pattern, keep the current LOV EA. */
2350         if (rc1 != 0)
2351                 GOTO(unlock_parent, rc = rc1);
2352
2353         /* Currently, we only support LOV_MAGIC_V1/LOV_MAGIC_V3 which has
2354          * been verified in lfsck_layout_verify_header() already. If some
2355          * new magic introduced in the future, then layout LFSCK needs to
2356          * be updated also. */
2357         magic = le32_to_cpu(lmm->lmm_magic);
2358         if (magic == LOV_MAGIC_V1) {
2359                 objs = &lmm->lmm_objects[0];
2360         } else {
2361                 LASSERT(magic == LOV_MAGIC_V3);
2362                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[0];
2363         }
2364
2365         count = le16_to_cpu(lmm->lmm_stripe_count);
2366         if (count == 0)
2367                 GOTO(unlock_parent, rc = -EINVAL);
2368         LASSERT(count > 0);
2369
2370         /* Exceed the current end of MDT-object layout EA. Then extend it. */
2371         if (count <= ea_off) {
2372                 if (bk->lb_param & LPF_DRYRUN)
2373                         GOTO(unlock_parent, rc = 1);
2374
2375                 lovea_size = lov_mds_md_size(ea_off + 1, magic);
2376                 /* If the declared is not big enough, re-try. */
2377                 if (buf->lb_len < lovea_size) {
2378                         rc = lovea_size;
2379                         goto again;
2380                 }
2381
2382                 rc = lfsck_layout_extend_lovea(env, lfsck, handle, parent, cfid,
2383                                                buf, fl, ost_idx, ea_off, false);
2384
2385                 GOTO(unlock_parent, rc);
2386         }
2387
2388         LASSERTF(rc > 0, "invalid rc = %d\n", rc);
2389
2390         for (i = 0; i < count; i++, objs++) {
2391                 /* The MDT-object was created via lfsck_layout_recover_create()
2392                  * by others before, and we fill the dummy layout EA. */
2393                 if (lovea_slot_is_dummy(objs)) {
2394                         if (i != ea_off)
2395                                 continue;
2396
2397                         if (bk->lb_param & LPF_DRYRUN)
2398                                 GOTO(unlock_parent, rc = 1);
2399
2400                         lmm->lmm_layout_gen =
2401                             cpu_to_le16(le16_to_cpu(lmm->lmm_layout_gen) + 1);
2402                         rc = lfsck_layout_refill_lovea(env, handle, parent,
2403                                                        cfid, buf, objs, fl,
2404                                                        ost_idx);
2405
2406                         CDEBUG(D_LFSCK, "%s layout LFSCK assistant fill "
2407                                "dummy layout slot for "DFID": parent "DFID
2408                                ", OST-index %u, stripe-index %u: rc = %d\n",
2409                                lfsck_lfsck2name(lfsck), PFID(cfid),
2410                                PFID(lfsck_dto2fid(parent)), ost_idx, i, rc);
2411
2412                         GOTO(unlock_parent, rc);
2413                 }
2414
2415                 ostid_le_to_cpu(&objs->l_ost_oi, oi);
2416                 rc = ostid_to_fid(fid, oi, le32_to_cpu(objs->l_ost_idx));
2417                 if (rc != 0) {
2418                         CDEBUG(D_LFSCK, "%s: the parent "DFID" contains "
2419                                "invalid layout EA at the slot %d, index %u\n",
2420                                lfsck_lfsck2name(lfsck),
2421                                PFID(lfsck_dto2fid(parent)), i,
2422                                le32_to_cpu(objs->l_ost_idx));
2423
2424                         GOTO(unlock_parent, rc);
2425                 }
2426
2427                 /* It should be rare case, the slot is there, but the LFSCK
2428                  * does not handle it during the first-phase cycle scanning. */
2429                 if (unlikely(lu_fid_eq(fid, cfid))) {
2430                         if (i == ea_off) {
2431                                 GOTO(unlock_parent, rc = 0);
2432                         } else {
2433                                 /* Rare case that the OST-object index
2434                                  * does not match the parent MDT-object
2435                                  * layout EA. We trust the later one. */
2436                                 if (bk->lb_param & LPF_DRYRUN)
2437                                         GOTO(unlock_parent, rc = 1);
2438
2439                                 dt_write_unlock(env, parent);
2440                                 if (handle != NULL)
2441                                         dt_trans_stop(env, dt, handle);
2442                                 lfsck_ibits_unlock(&lh, LCK_EX);
2443                                 rc = lfsck_layout_update_pfid(env, com, parent,
2444                                                         cfid, ltd->ltd_tgt, i);
2445
2446                                 CDEBUG(D_LFSCK, "%s layout LFSCK assistant "
2447                                        "updated OST-object's pfid for "DFID
2448                                        ": parent "DFID", OST-index %u, "
2449                                        "stripe-index %u: rc = %d\n",
2450                                        lfsck_lfsck2name(lfsck), PFID(cfid),
2451                                        PFID(lfsck_dto2fid(parent)),
2452                                        ltd->ltd_index, i, rc);
2453
2454                                 RETURN(rc);
2455                         }
2456                 }
2457         }
2458
2459         /* The MDT-object exists, but related layout EA slot is occupied
2460          * by others. */
2461         if (bk->lb_param & LPF_DRYRUN)
2462                 GOTO(unlock_parent, rc = 1);
2463
2464         dt_write_unlock(env, parent);
2465         if (handle != NULL)
2466                 dt_trans_stop(env, dt, handle);
2467         lfsck_ibits_unlock(&lh, LCK_EX);
2468         if (le32_to_cpu(lmm->lmm_magic) == LOV_MAGIC_V1)
2469                 objs = &lmm->lmm_objects[ea_off];
2470         else
2471                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[ea_off];
2472         rc = lfsck_layout_conflict_create(env, com, ltd, rec, parent, cfid,
2473                                           buf, objs, ea_off);
2474
2475         RETURN(rc);
2476
2477 unlock_parent:
2478         if (locked)
2479                 dt_write_unlock(env, parent);
2480
2481 stop:
2482         if (handle != NULL)
2483                 dt_trans_stop(env, dt, handle);
2484
2485 unlock_layout:
2486         lfsck_ibits_unlock(&lh, LCK_EX);
2487
2488         return rc;
2489 }
2490
2491 static int lfsck_layout_scan_orphan_one(const struct lu_env *env,
2492                                         struct lfsck_component *com,
2493                                         struct lfsck_tgt_desc *ltd,
2494                                         struct lu_orphan_rec *rec,
2495                                         struct lu_fid *cfid)
2496 {
2497         struct lfsck_layout     *lo     = com->lc_file_ram;
2498         struct lu_fid           *pfid   = &rec->lor_fid;
2499         struct dt_object        *parent = NULL;
2500         __u32                    ea_off = pfid->f_stripe_idx;
2501         int                      rc     = 0;
2502         ENTRY;
2503
2504         if (!fid_is_sane(cfid))
2505                 GOTO(out, rc = -EINVAL);
2506
2507         if (fid_is_zero(pfid)) {
2508                 rc = lfsck_layout_recreate_parent(env, com, ltd, rec, cfid,
2509                                                   "", "N", ea_off);
2510                 GOTO(out, rc);
2511         }
2512
2513         pfid->f_ver = 0;
2514         if (!fid_is_sane(pfid))
2515                 GOTO(out, rc = -EINVAL);
2516
2517         parent = lfsck_object_find_by_dev(env, com->lc_lfsck->li_bottom, pfid);
2518         if (IS_ERR(parent))
2519                 GOTO(out, rc = PTR_ERR(parent));
2520
2521         if (unlikely(dt_object_remote(parent) != 0))
2522                 GOTO(put, rc = -EXDEV);
2523
2524         if (dt_object_exists(parent) == 0) {
2525                 lu_object_put(env, &parent->do_lu);
2526                 rc = lfsck_layout_recreate_parent(env, com, ltd, rec, cfid,
2527                                                   "", "R", ea_off);
2528                 GOTO(out, rc);
2529         }
2530
2531         if (!S_ISREG(lu_object_attr(&parent->do_lu)))
2532                 GOTO(put, rc = -EISDIR);
2533
2534         rc = lfsck_layout_recreate_lovea(env, com, ltd, rec, parent, cfid,
2535                                          ltd->ltd_index, ea_off);
2536
2537         GOTO(put, rc);
2538
2539 put:
2540         if (rc <= 0)
2541                 lu_object_put(env, &parent->do_lu);
2542         else
2543                 /* The layout EA is changed, need to be reloaded next time. */
2544                 lu_object_put_nocache(env, &parent->do_lu);
2545
2546 out:
2547         down_write(&com->lc_sem);
2548         com->lc_new_scanned++;
2549         com->lc_new_checked++;
2550         if (rc > 0) {
2551                 lo->ll_objs_repaired[LLIT_ORPHAN - 1]++;
2552                 rc = 0;
2553         } else if (rc < 0) {
2554                 lo->ll_objs_failed_phase2++;
2555         }
2556         up_write(&com->lc_sem);
2557
2558         return rc;
2559 }
2560
2561 static int lfsck_layout_scan_orphan(const struct lu_env *env,
2562                                     struct lfsck_component *com,
2563                                     struct lfsck_tgt_desc *ltd)
2564 {
2565         struct lfsck_assistant_data     *lad    = com->lc_data;
2566         struct lfsck_instance           *lfsck  = com->lc_lfsck;
2567         struct lfsck_bookmark           *bk     = &lfsck->li_bookmark_ram;
2568         struct lfsck_thread_info        *info   = lfsck_env_info(env);
2569         struct ost_id                   *oi     = &info->lti_oi;
2570         struct lu_fid                   *fid    = &info->lti_fid;
2571         struct dt_object                *obj;
2572         const struct dt_it_ops          *iops;
2573         struct dt_it                    *di;
2574         int                              rc     = 0;
2575         ENTRY;
2576
2577         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant starts the orphan "
2578                "scanning for OST%04x\n",
2579                lfsck_lfsck2name(lfsck), ltd->ltd_index);
2580
2581         if (cfs_bitmap_check(lad->lad_bitmap, ltd->ltd_index)) {
2582                 CDEBUG(D_LFSCK, "%s: layout LFSCK assistant skip the orphan "
2583                        "scanning for OST%04x\n",
2584                        lfsck_lfsck2name(lfsck), ltd->ltd_index);
2585
2586                 RETURN(0);
2587         }
2588
2589         ostid_set_seq(oi, FID_SEQ_IDIF);
2590         ostid_set_id(oi, 0);
2591         rc = ostid_to_fid(fid, oi, ltd->ltd_index);
2592         if (rc != 0)
2593                 GOTO(log, rc);
2594
2595         obj = lfsck_object_find_by_dev(env, ltd->ltd_tgt, fid);
2596         if (unlikely(IS_ERR(obj)))
2597                 GOTO(log, rc = PTR_ERR(obj));
2598
2599         rc = obj->do_ops->do_index_try(env, obj, &dt_lfsck_orphan_features);
2600         if (rc != 0)
2601                 GOTO(put, rc);
2602
2603         iops = &obj->do_index_ops->dio_it;
2604         di = iops->init(env, obj, 0, BYPASS_CAPA);
2605         if (IS_ERR(di))
2606                 GOTO(put, rc = PTR_ERR(di));
2607
2608         rc = iops->load(env, di, 0);
2609         if (rc == -ESRCH) {
2610                 /* -ESRCH means that the orphan OST-objects rbtree has been
2611                  * cleanup because of the OSS server restart or other errors. */
2612                 lfsck_lad_set_bitmap(env, com, ltd->ltd_index);
2613                 GOTO(fini, rc);
2614         }
2615
2616         if (rc == 0)
2617                 rc = iops->next(env, di);
2618         else if (rc > 0)
2619                 rc = 0;
2620
2621         if (rc < 0)
2622                 GOTO(fini, rc);
2623
2624         if (rc > 0)
2625                 GOTO(fini, rc = 0);
2626
2627         do {
2628                 struct dt_key           *key;
2629                 struct lu_orphan_rec    *rec = &info->lti_rec;
2630
2631                 if (CFS_FAIL_TIMEOUT(OBD_FAIL_LFSCK_DELAY3, cfs_fail_val) &&
2632                     unlikely(!thread_is_running(&lfsck->li_thread)))
2633                         break;
2634
2635                 key = iops->key(env, di);
2636                 com->lc_fid_latest_scanned_phase2 = *(struct lu_fid *)key;
2637                 rc = iops->rec(env, di, (struct dt_rec *)rec, 0);
2638                 if (rc == 0)
2639                         rc = lfsck_layout_scan_orphan_one(env, com, ltd, rec,
2640                                         &com->lc_fid_latest_scanned_phase2);
2641                 if (rc != 0 && bk->lb_param & LPF_FAILOUT)
2642                         GOTO(fini, rc);
2643
2644                 lfsck_control_speed_by_self(com);
2645                 do {
2646                         rc = iops->next(env, di);
2647                 } while (rc < 0 && !(bk->lb_param & LPF_FAILOUT));
2648         } while (rc == 0);
2649
2650         GOTO(fini, rc);
2651
2652 fini:
2653         iops->put(env, di);
2654         iops->fini(env, di);
2655 put:
2656         lu_object_put(env, &obj->do_lu);
2657
2658 log:
2659         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant finished the orphan "
2660                "scanning for OST%04x: rc = %d\n",
2661                lfsck_lfsck2name(lfsck), ltd->ltd_index, rc);
2662
2663         return rc > 0 ? 0 : rc;
2664 }
2665
2666 /* For the MDT-object with dangling reference, we need to repare the
2667  * inconsistency according to the LFSCK sponsor's requirement:
2668  *
2669  * 1) Keep the inconsistency there and report the inconsistency case,
2670  *    then give the chance to the application to find related issues,
2671  *    and the users can make the decision about how to handle it with
2672  *    more human knownledge. (by default)
2673  *
2674  * 2) Re-create the missing OST-object with the FID/owner information. */
2675 static int lfsck_layout_repair_dangling(const struct lu_env *env,
2676                                         struct lfsck_component *com,
2677                                         struct dt_object *parent,
2678                                         struct lfsck_layout_req *llr,
2679                                         const struct lu_attr *pla)
2680 {
2681         struct lfsck_thread_info        *info   = lfsck_env_info(env);
2682         struct filter_fid               *pfid   = &info->lti_new_pfid;
2683         struct dt_allocation_hint       *hint   = &info->lti_hint;
2684         struct lu_attr                  *cla    = &info->lti_la2;
2685         struct dt_object                *child  = llr->llr_child;
2686         struct dt_device                *dev    = lfsck_obj2dt_dev(child);
2687         const struct lu_fid             *tfid   = lu_object_fid(&parent->do_lu);
2688         struct thandle                  *handle;
2689         struct lu_buf                   *buf;
2690         struct lustre_handle             lh     = { 0 };
2691         int                              rc;
2692         bool                             create;
2693         ENTRY;
2694
2695         if (com->lc_lfsck->li_bookmark_ram.lb_param & LPF_CREATE_OSTOBJ)
2696                 create = true;
2697         else
2698                 create = false;
2699
2700         if (!create)
2701                 GOTO(log, rc = 1);
2702
2703         memset(cla, 0, sizeof(*cla));
2704         cla->la_uid = pla->la_uid;
2705         cla->la_gid = pla->la_gid;
2706         cla->la_mode = S_IFREG | 0666;
2707         cla->la_valid = LA_TYPE | LA_MODE | LA_UID | LA_GID |
2708                         LA_ATIME | LA_MTIME | LA_CTIME;
2709
2710         rc = lfsck_ibits_lock(env, com->lc_lfsck, parent, &lh,
2711                               MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR,
2712                               LCK_EX);
2713         if (rc != 0)
2714                 GOTO(log, rc);
2715
2716         handle = dt_trans_create(env, dev);
2717         if (IS_ERR(handle))
2718                 GOTO(unlock1, rc = PTR_ERR(handle));
2719
2720         hint->dah_parent = NULL;
2721         hint->dah_mode = 0;
2722         pfid->ff_parent.f_seq = cpu_to_le64(tfid->f_seq);
2723         pfid->ff_parent.f_oid = cpu_to_le32(tfid->f_oid);
2724         /* Currently, the filter_fid::ff_parent::f_ver is not the real parent
2725          * MDT-object's FID::f_ver, instead it is the OST-object index in its
2726          * parent MDT-object's layout EA. */
2727         pfid->ff_parent.f_stripe_idx = cpu_to_le32(llr->llr_lov_idx);
2728         buf = lfsck_buf_get(env, pfid, sizeof(struct filter_fid));
2729
2730         rc = dt_declare_create(env, child, cla, hint, NULL, handle);
2731         if (rc != 0)
2732                 GOTO(stop, rc);
2733
2734         rc = dt_declare_xattr_set(env, child, buf, XATTR_NAME_FID,
2735                                   LU_XATTR_CREATE, handle);
2736         if (rc != 0)
2737                 GOTO(stop, rc);
2738
2739         rc = dt_trans_start(env, dev, handle);
2740         if (rc != 0)
2741                 GOTO(stop, rc);
2742
2743         dt_read_lock(env, parent, 0);
2744         if (unlikely(lfsck_is_dead_obj(parent)))
2745                 GOTO(unlock2, rc = 1);
2746
2747         rc = dt_create(env, child, cla, hint, NULL, handle);
2748         if (rc != 0)
2749                 GOTO(unlock2, rc);
2750
2751         rc = dt_xattr_set(env, child, buf, XATTR_NAME_FID, LU_XATTR_CREATE,
2752                           handle, BYPASS_CAPA);
2753
2754         GOTO(unlock2, rc);
2755
2756 unlock2:
2757         dt_read_unlock(env, parent);
2758
2759 stop:
2760         rc = lfsck_layout_trans_stop(env, dev, handle, rc);
2761
2762 unlock1:
2763         lfsck_ibits_unlock(&lh, LCK_EX);
2764
2765 log:
2766         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant found dangling "
2767                "reference for: parent "DFID", child "DFID", OST-index %u, "
2768                "stripe-index %u, owner %u/%u. %s: rc = %d\n",
2769                lfsck_lfsck2name(com->lc_lfsck), PFID(lfsck_dto2fid(parent)),
2770                PFID(lfsck_dto2fid(child)), llr->llr_ost_idx,
2771                llr->llr_lov_idx, pla->la_uid, pla->la_gid,
2772                create ? "Create the lost OST-object as required" :
2773                         "Keep the MDT-object there by default", rc);
2774
2775         return rc;
2776 }
2777
2778 /* If the OST-object does not recognize the MDT-object as its parent, and
2779  * there is no other MDT-object claims as its parent, then just trust the
2780  * given MDT-object as its parent. So update the OST-object filter_fid. */
2781 static int lfsck_layout_repair_unmatched_pair(const struct lu_env *env,
2782                                               struct lfsck_component *com,
2783                                               struct dt_object *parent,
2784                                               struct lfsck_layout_req *llr,
2785                                               const struct lu_attr *pla)
2786 {
2787         struct lfsck_thread_info        *info   = lfsck_env_info(env);
2788         struct filter_fid               *pfid   = &info->lti_new_pfid;
2789         struct lu_attr                  *tla    = &info->lti_la3;
2790         struct dt_object                *child  = llr->llr_child;
2791         struct dt_device                *dev    = lfsck_obj2dt_dev(child);
2792         const struct lu_fid             *tfid   = lu_object_fid(&parent->do_lu);
2793         struct thandle                  *handle;
2794         struct lu_buf                   *buf;
2795         struct lustre_handle             lh     = { 0 };
2796         int                              rc;
2797         ENTRY;
2798
2799         rc = lfsck_ibits_lock(env, com->lc_lfsck, parent, &lh,
2800                               MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR,
2801                               LCK_EX);
2802         if (rc != 0)
2803                 GOTO(log, rc);
2804
2805         handle = dt_trans_create(env, dev);
2806         if (IS_ERR(handle))
2807                 GOTO(unlock1, rc = PTR_ERR(handle));
2808
2809         pfid->ff_parent.f_seq = cpu_to_le64(tfid->f_seq);
2810         pfid->ff_parent.f_oid = cpu_to_le32(tfid->f_oid);
2811         /* Currently, the filter_fid::ff_parent::f_ver is not the real parent
2812          * MDT-object's FID::f_ver, instead it is the OST-object index in its
2813          * parent MDT-object's layout EA. */
2814         pfid->ff_parent.f_stripe_idx = cpu_to_le32(llr->llr_lov_idx);
2815         buf = lfsck_buf_get(env, pfid, sizeof(struct filter_fid));
2816
2817         rc = dt_declare_xattr_set(env, child, buf, XATTR_NAME_FID, 0, handle);
2818         if (rc != 0)
2819                 GOTO(stop, rc);
2820
2821         tla->la_valid = LA_UID | LA_GID;
2822         tla->la_uid = pla->la_uid;
2823         tla->la_gid = pla->la_gid;
2824         rc = dt_declare_attr_set(env, child, tla, handle);
2825         if (rc != 0)
2826                 GOTO(stop, rc);
2827
2828         rc = dt_trans_start(env, dev, handle);
2829         if (rc != 0)
2830                 GOTO(stop, rc);
2831
2832         dt_write_lock(env, parent, 0);
2833         if (unlikely(lfsck_is_dead_obj(parent)))
2834                 GOTO(unlock2, rc = 1);
2835
2836         rc = dt_xattr_set(env, child, buf, XATTR_NAME_FID, 0, handle,
2837                           BYPASS_CAPA);
2838         if (rc != 0)
2839                 GOTO(unlock2, rc);
2840
2841         /* Get the latest parent's owner. */
2842         rc = dt_attr_get(env, parent, tla, BYPASS_CAPA);
2843         if (rc != 0)
2844                 GOTO(unlock2, rc);
2845
2846         tla->la_valid = LA_UID | LA_GID;
2847         rc = dt_attr_set(env, child, tla, handle, BYPASS_CAPA);
2848
2849         GOTO(unlock2, rc);
2850
2851 unlock2:
2852         dt_write_unlock(env, parent);
2853
2854 stop:
2855         rc = lfsck_layout_trans_stop(env, dev, handle, rc);
2856
2857 unlock1:
2858         lfsck_ibits_unlock(&lh, LCK_EX);
2859
2860 log:
2861         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant repaired unmatched "
2862                "MDT-OST pair for: parent "DFID", child "DFID", OST-index %u, "
2863                "stripe-index %u, owner %u/%u: rc = %d\n",
2864                lfsck_lfsck2name(com->lc_lfsck), PFID(lfsck_dto2fid(parent)),
2865                PFID(lfsck_dto2fid(child)), llr->llr_ost_idx, llr->llr_lov_idx,
2866                pla->la_uid, pla->la_gid, rc);
2867
2868         return rc;
2869 }
2870
2871 /* If there are more than one MDT-objects claim as the OST-object's parent,
2872  * and the OST-object only recognizes one of them, then we need to generate
2873  * new OST-object(s) with new fid(s) for the non-recognized MDT-object(s). */
2874 static int lfsck_layout_repair_multiple_references(const struct lu_env *env,
2875                                                    struct lfsck_component *com,
2876                                                    struct dt_object *parent,
2877                                                    struct lfsck_layout_req *llr,
2878                                                    struct lu_attr *la,
2879                                                    struct lu_buf *buf)
2880 {
2881         struct lfsck_thread_info        *info   = lfsck_env_info(env);
2882         struct dt_allocation_hint       *hint   = &info->lti_hint;
2883         struct dt_object_format         *dof    = &info->lti_dof;
2884         struct dt_device                *pdev   = com->lc_lfsck->li_next;
2885         struct ost_id                   *oi     = &info->lti_oi;
2886         struct dt_device                *cdev   = lfsck_obj2dt_dev(llr->llr_child);
2887         struct dt_object                *child  = NULL;
2888         struct lu_device                *d      = &cdev->dd_lu_dev;
2889         struct lu_object                *o      = NULL;
2890         struct thandle                  *handle;
2891         struct lov_mds_md_v1            *lmm;
2892         struct lov_ost_data_v1          *objs;
2893         struct lustre_handle             lh     = { 0 };
2894         struct lu_buf                    ea_buf;
2895         __u32                            magic;
2896         int                              rc;
2897         ENTRY;
2898
2899         rc = lfsck_ibits_lock(env, com->lc_lfsck, parent, &lh,
2900                               MDS_INODELOCK_LAYOUT | MDS_INODELOCK_XATTR,
2901                               LCK_EX);
2902         if (rc != 0)
2903                 GOTO(log, rc);
2904
2905         handle = dt_trans_create(env, pdev);
2906         if (IS_ERR(handle))
2907                 GOTO(unlock1, rc = PTR_ERR(handle));
2908
2909         o = lu_object_anon(env, d, NULL);
2910         if (IS_ERR(o))
2911                 GOTO(stop, rc = PTR_ERR(o));
2912
2913         child = container_of(o, struct dt_object, do_lu);
2914         o = lu_object_locate(o->lo_header, d->ld_type);
2915         if (unlikely(o == NULL))
2916                 GOTO(stop, rc = -EINVAL);
2917
2918         child = container_of(o, struct dt_object, do_lu);
2919         la->la_valid = LA_UID | LA_GID;
2920         hint->dah_parent = NULL;
2921         hint->dah_mode = 0;
2922         dof->dof_type = DFT_REGULAR;
2923         rc = dt_declare_create(env, child, la, NULL, NULL, handle);
2924         if (rc != 0)
2925                 GOTO(stop, rc);
2926
2927         rc = dt_declare_xattr_set(env, parent, buf, XATTR_NAME_LOV,
2928                                   LU_XATTR_REPLACE, handle);
2929         if (rc != 0)
2930                 GOTO(stop, rc);
2931
2932         rc = dt_trans_start(env, pdev, handle);
2933         if (rc != 0)
2934                 GOTO(stop, rc);
2935
2936         dt_write_lock(env, parent, 0);
2937         if (unlikely(lfsck_is_dead_obj(parent)))
2938                 GOTO(unlock2, rc = 0);
2939
2940         rc = dt_xattr_get(env, parent, buf, XATTR_NAME_LOV, BYPASS_CAPA);
2941         if (unlikely(rc == 0 || rc == -ENODATA || rc == -ERANGE))
2942                 GOTO(unlock2, rc = 0);
2943
2944         lmm = buf->lb_buf;
2945         /* Someone change layout during the LFSCK, no need to repair then. */
2946         if (le16_to_cpu(lmm->lmm_layout_gen) != llr->llr_parent->llo_gen)
2947                 GOTO(unlock2, rc = 0);
2948
2949         rc = dt_create(env, child, la, hint, dof, handle);
2950         if (rc != 0)
2951                 GOTO(unlock2, rc);
2952
2953         /* Currently, we only support LOV_MAGIC_V1/LOV_MAGIC_V3 which has
2954          * been verified in lfsck_layout_verify_header() already. If some
2955          * new magic introduced in the future, then layout LFSCK needs to
2956          * be updated also. */
2957         magic = le32_to_cpu(lmm->lmm_magic);
2958         if (magic == LOV_MAGIC_V1) {
2959                 objs = &lmm->lmm_objects[0];
2960         } else {
2961                 LASSERT(magic == LOV_MAGIC_V3);
2962                 objs = &((struct lov_mds_md_v3 *)lmm)->lmm_objects[0];
2963         }
2964
2965         lmm->lmm_layout_gen = cpu_to_le16(llr->llr_parent->llo_gen + 1);
2966         fid_to_ostid(lu_object_fid(&child->do_lu), oi);
2967         ostid_cpu_to_le(oi, &objs[llr->llr_lov_idx].l_ost_oi);
2968         objs[llr->llr_lov_idx].l_ost_gen = cpu_to_le32(0);
2969         objs[llr->llr_lov_idx].l_ost_idx = cpu_to_le32(llr->llr_ost_idx);
2970         lfsck_buf_init(&ea_buf, lmm,
2971                        lov_mds_md_size(le16_to_cpu(lmm->lmm_stripe_count),
2972                                        magic));
2973         rc = dt_xattr_set(env, parent, &ea_buf, XATTR_NAME_LOV,
2974                           LU_XATTR_REPLACE, handle, BYPASS_CAPA);
2975
2976         GOTO(unlock2, rc = (rc == 0 ? 1 : rc));
2977
2978 unlock2:
2979         dt_write_unlock(env, parent);
2980
2981 stop:
2982         if (child != NULL)
2983                 lu_object_put(env, &child->do_lu);
2984
2985         dt_trans_stop(env, pdev, handle);
2986
2987 unlock1:
2988         lfsck_ibits_unlock(&lh, LCK_EX);
2989
2990 log:
2991         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant repaired multiple "
2992                "references for: parent "DFID", OST-index %u, stripe-index %u, "
2993                "owner %u/%u: rc = %d\n",
2994                lfsck_lfsck2name(com->lc_lfsck), PFID(lfsck_dto2fid(parent)),
2995                llr->llr_ost_idx, llr->llr_lov_idx, la->la_uid, la->la_gid, rc);
2996
2997         return rc;
2998 }
2999
3000 /* If the MDT-object and the OST-object have different owner information,
3001  * then trust the MDT-object, because the normal chown/chgrp handle order
3002  * is from MDT to OST, and it is possible that some chown/chgrp operation
3003  * is partly done. */
3004 static int lfsck_layout_repair_owner(const struct lu_env *env,
3005                                      struct lfsck_component *com,
3006                                      struct dt_object *parent,
3007                                      struct lfsck_layout_req *llr,
3008                                      struct lu_attr *pla)
3009 {
3010         struct lfsck_thread_info        *info   = lfsck_env_info(env);
3011         struct lu_attr                  *tla    = &info->lti_la3;
3012         struct dt_object                *child  = llr->llr_child;
3013         struct dt_device                *dev    = lfsck_obj2dt_dev(child);
3014         struct thandle                  *handle;
3015         int                              rc;
3016         ENTRY;
3017
3018         handle = dt_trans_create(env, dev);
3019         if (IS_ERR(handle))
3020                 GOTO(log, rc = PTR_ERR(handle));
3021
3022         tla->la_uid = pla->la_uid;
3023         tla->la_gid = pla->la_gid;
3024         tla->la_valid = LA_UID | LA_GID;
3025         rc = dt_declare_attr_set(env, child, tla, handle);
3026         if (rc != 0)
3027                 GOTO(stop, rc);
3028
3029         rc = dt_trans_start(env, dev, handle);
3030         if (rc != 0)
3031                 GOTO(stop, rc);
3032
3033         /* Use the dt_object lock to serialize with destroy and attr_set. */
3034         dt_read_lock(env, parent, 0);
3035         if (unlikely(lfsck_is_dead_obj(parent)))
3036                 GOTO(unlock, rc = 1);
3037
3038         /* Get the latest parent's owner. */
3039         rc = dt_attr_get(env, parent, tla, BYPASS_CAPA);
3040         if (rc != 0)
3041                 GOTO(unlock, rc);
3042
3043         /* Some others chown/chgrp during the LFSCK, needs to do nothing. */
3044         if (unlikely(tla->la_uid != pla->la_uid ||
3045                      tla->la_gid != pla->la_gid))
3046                 GOTO(unlock, rc = 1);
3047
3048         tla->la_valid = LA_UID | LA_GID;
3049         rc = dt_attr_set(env, child, tla, handle, BYPASS_CAPA);
3050
3051         GOTO(unlock, rc);
3052
3053 unlock:
3054         dt_read_unlock(env, parent);
3055
3056 stop:
3057         rc = lfsck_layout_trans_stop(env, dev, handle, rc);
3058
3059 log:
3060         CDEBUG(D_LFSCK, "%s: layout LFSCK assistant repaired inconsistent "
3061                "file owner for: parent "DFID", child "DFID", OST-index %u, "
3062                "stripe-index %u, owner %u/%u: rc = %d\n",
3063                lfsck_lfsck2name(com->lc_lfsck), PFID(lfsck_dto2fid(parent)),
3064                PFID(lfsck_dto2fid(child)), llr->llr_ost_idx, llr->llr_lov_idx,
3065                pla->la_uid, pla->la_gid, rc);
3066
3067         return rc;
3068 }
3069
3070 /* Check whether the OST-object correctly back points to the
3071  * MDT-object (@parent) via the XATTR_NAME_FID xattr (@pfid). */
3072 static int lfsck_layout_check_parent(const struct lu_env *env,
3073                                      struct lfsck_component *com,
3074                                      struct dt_object *parent,
3075                                      const struct lu_fid *pfid,
3076                                      const struct lu_fid *cfid,
3077                                      const struct lu_attr *pla,
3078                                      const struct lu_attr *cla,
3079                                      struct lfsck_layout_req *llr,
3080                                      struct lu_buf *lov_ea, __u32 idx)
3081 {
3082         struct lfsck_thread_info        *info   = lfsck_env_info(env);
3083         struct lu_buf                   *buf    = &info->lti_big_buf;
3084         struct dt_object                *tobj;
3085         struct lov_mds_md_v1            *lmm;
3086         struct lov_ost_data_v1          *objs;
3087         struct lustre_handle             lh     = { 0 };
3088         int                              rc;
3089         int                              i;
3090         __u32                            magic;
3091         __u16                            count;
3092         ENTRY;
3093
3094         if (fid_is_zero(pfid)) {
3095                 /* client never wrote. */
3096                 if (cla->la_size == 0 && cla->la_blocks == 0) {
3097                         if (unlikely(cla->la_uid != pla->la_uid ||
3098                                      cla->la_gid != pla->la_gid))
3099                                 RETURN (LLIT_INCONSISTENT_OWNER);
3100
3101                         RETURN(0);
3102                 }
3103
3104                 RETURN(LLIT_UNMATCHED_PAIR);
3105         }
3106
3107         if (unlikely(!fid_is_sane(pfid)))
3108                 RETURN(LLIT_UNMATCHED_PAIR);
3109
3110         if (lu_fid_eq(pfid, lu_object_fid(&parent->do_lu))) {
3111                 if (llr->llr_lov_idx == idx)
3112                         RETURN(0);
3113
3114                 RETURN(LLIT_UNMATCHED_PAIR);
3115         }
3116
3117         tobj = lfsck_object_find(env, com->lc_lfsck, pfid);
3118         if (IS_ERR(tobj))
3119                 RETURN(PTR_ERR(tobj));
3120
3121         if (dt_object_exists(tobj) == 0 ||
3122             lfsck_is_dead_obj(tobj))
3123                 GOT