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