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