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