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