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