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