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