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