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