Whamcloud - gitweb
LU-10134 lfsck: not add requests if engine out of work
[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             unlikely(!thread_is_running(&lfsck->li_thread) ||
3996                      !thread_is_running(&lad->lad_thread))) {
3997                 spin_unlock(&lad->lad_lock);
3998                 lfsck_namespace_assistant_req_fini(env, &lnr->lnr_lar);
3999                 ns->ln_striped_dirs_skipped++;
4000
4001                 RETURN_EXIT;
4002         }
4003
4004         list_add_tail(&lnr->lnr_lar.lar_list, &lad->lad_req_list);
4005         if (lad->lad_prefetched == 0)
4006                 wakeup = true;
4007
4008         lad->lad_prefetched++;
4009         spin_unlock(&lad->lad_lock);
4010         if (wakeup)
4011                 wake_up_all(&lad->lad_thread.t_ctl_waitq);
4012
4013         EXIT;
4014 }
4015
4016 static int lfsck_namespace_open_dir(const struct lu_env *env,
4017                                     struct lfsck_component *com)
4018 {
4019         struct lfsck_instance   *lfsck  = com->lc_lfsck;
4020         struct lfsck_namespace  *ns     = com->lc_file_ram;
4021         struct lfsck_lmv        *llmv   = lfsck->li_lmv;
4022         int                      rc     = 0;
4023         ENTRY;
4024
4025         if (llmv == NULL)
4026                 RETURN(0);
4027
4028         if (llmv->ll_lmv_master) {
4029                 struct lmv_mds_md_v1 *lmv = &llmv->ll_lmv;
4030
4031                 if (lmv->lmv_master_mdt_index != lfsck_dev_idx(lfsck)) {
4032                         lmv->lmv_master_mdt_index =
4033                                 lfsck_dev_idx(lfsck);
4034                         ns->ln_flags |= LF_INCONSISTENT;
4035                         llmv->ll_lmv_updated = 1;
4036                 }
4037         } else {
4038                 rc = lfsck_namespace_verify_stripe_slave(env, com,
4039                                         lfsck->li_obj_dir, llmv);
4040         }
4041
4042         RETURN(rc > 0 ? 0 : rc);
4043 }
4044
4045 static int lfsck_namespace_checkpoint(const struct lu_env *env,
4046                                       struct lfsck_component *com, bool init)
4047 {
4048         struct lfsck_instance   *lfsck = com->lc_lfsck;
4049         struct lfsck_namespace  *ns    = com->lc_file_ram;
4050         int                      rc;
4051
4052         if (!init) {
4053                 rc = lfsck_checkpoint_generic(env, com);
4054                 if (rc != 0)
4055                         goto log;
4056         }
4057
4058         down_write(&com->lc_sem);
4059         if (init) {
4060                 ns->ln_pos_latest_start = lfsck->li_pos_checkpoint;
4061         } else {
4062                 ns->ln_pos_last_checkpoint = lfsck->li_pos_checkpoint;
4063                 ns->ln_run_time_phase1 += ktime_get_seconds() -
4064                                           lfsck->li_time_last_checkpoint;
4065                 ns->ln_time_last_checkpoint = ktime_get_real_seconds();
4066                 ns->ln_items_checked += com->lc_new_checked;
4067                 com->lc_new_checked = 0;
4068         }
4069
4070         rc = lfsck_namespace_store(env, com);
4071         up_write(&com->lc_sem);
4072
4073 log:
4074         CDEBUG(D_LFSCK, "%s: namespace LFSCK checkpoint at the pos [%llu"
4075                ", "DFID", %#llx], status = %d: rc = %d\n",
4076                lfsck_lfsck2name(lfsck), lfsck->li_pos_current.lp_oit_cookie,
4077                PFID(&lfsck->li_pos_current.lp_dir_parent),
4078                lfsck->li_pos_current.lp_dir_cookie, ns->ln_status, rc);
4079
4080         return rc > 0 ? 0 : rc;
4081 }
4082
4083 static int lfsck_namespace_prep(const struct lu_env *env,
4084                                 struct lfsck_component *com,
4085                                 struct lfsck_start_param *lsp)
4086 {
4087         struct lfsck_instance   *lfsck  = com->lc_lfsck;
4088         struct lfsck_namespace  *ns     = com->lc_file_ram;
4089         struct lfsck_position   *pos    = &com->lc_pos_start;
4090         int                      rc;
4091
4092         rc = lfsck_namespace_load_bitmap(env, com);
4093         if (rc != 0 || ns->ln_status == LS_COMPLETED) {
4094                 rc = lfsck_namespace_reset(env, com, false);
4095                 if (rc == 0)
4096                         rc = lfsck_set_param(env, lfsck, lsp->lsp_start, true);
4097
4098                 if (rc != 0) {
4099                         CDEBUG(D_LFSCK, "%s: namespace LFSCK prep failed: "
4100                                "rc = %d\n", lfsck_lfsck2name(lfsck), rc);
4101
4102                         return rc;
4103                 }
4104         }
4105
4106         down_write(&com->lc_sem);
4107         ns->ln_time_latest_start = ktime_get_real_seconds();
4108         spin_lock(&lfsck->li_lock);
4109
4110         if (ns->ln_flags & LF_SCANNED_ONCE) {
4111                 if (!lfsck->li_drop_dryrun ||
4112                     lfsck_pos_is_zero(&ns->ln_pos_first_inconsistent)) {
4113                         ns->ln_status = LS_SCANNING_PHASE2;
4114                         list_move_tail(&com->lc_link,
4115                                        &lfsck->li_list_double_scan);
4116                         if (!list_empty(&com->lc_link_dir))
4117                                 list_del_init(&com->lc_link_dir);
4118                         lfsck_pos_set_zero(pos);
4119                 } else {
4120                         ns->ln_status = LS_SCANNING_PHASE1;
4121                         ns->ln_run_time_phase1 = 0;
4122                         ns->ln_run_time_phase2 = 0;
4123                         ns->ln_items_checked = 0;
4124                         ns->ln_items_repaired = 0;
4125                         ns->ln_items_failed = 0;
4126                         ns->ln_dirs_checked = 0;
4127                         ns->ln_objs_checked_phase2 = 0;
4128                         ns->ln_objs_repaired_phase2 = 0;
4129                         ns->ln_objs_failed_phase2 = 0;
4130                         ns->ln_objs_nlink_repaired = 0;
4131                         ns->ln_dirent_repaired = 0;
4132                         ns->ln_linkea_repaired = 0;
4133                         ns->ln_mul_linked_checked = 0;
4134                         ns->ln_mul_linked_repaired = 0;
4135                         ns->ln_unknown_inconsistency = 0;
4136                         ns->ln_unmatched_pairs_repaired = 0;
4137                         ns->ln_dangling_repaired = 0;
4138                         ns->ln_mul_ref_repaired = 0;
4139                         ns->ln_bad_type_repaired = 0;
4140                         ns->ln_lost_dirent_repaired = 0;
4141                         ns->ln_striped_dirs_scanned = 0;
4142                         ns->ln_striped_dirs_repaired = 0;
4143                         ns->ln_striped_dirs_failed = 0;
4144                         ns->ln_striped_dirs_disabled = 0;
4145                         ns->ln_striped_dirs_skipped = 0;
4146                         ns->ln_striped_shards_scanned = 0;
4147                         ns->ln_striped_shards_repaired = 0;
4148                         ns->ln_striped_shards_failed = 0;
4149                         ns->ln_striped_shards_skipped = 0;
4150                         ns->ln_name_hash_repaired = 0;
4151                         fid_zero(&ns->ln_fid_latest_scanned_phase2);
4152                         if (list_empty(&com->lc_link_dir))
4153                                 list_add_tail(&com->lc_link_dir,
4154                                               &lfsck->li_list_dir);
4155                         *pos = ns->ln_pos_first_inconsistent;
4156                 }
4157         } else {
4158                 ns->ln_status = LS_SCANNING_PHASE1;
4159                 if (list_empty(&com->lc_link_dir))
4160                         list_add_tail(&com->lc_link_dir,
4161                                       &lfsck->li_list_dir);
4162                 if (!lfsck->li_drop_dryrun ||
4163                     lfsck_pos_is_zero(&ns->ln_pos_first_inconsistent)) {
4164                         *pos = ns->ln_pos_last_checkpoint;
4165                         pos->lp_oit_cookie++;
4166                 } else {
4167                         *pos = ns->ln_pos_first_inconsistent;
4168                 }
4169         }
4170
4171         spin_unlock(&lfsck->li_lock);
4172         up_write(&com->lc_sem);
4173
4174         rc = lfsck_start_assistant(env, com, lsp);
4175
4176         CDEBUG(D_LFSCK, "%s: namespace LFSCK prep done, start pos [%llu, "
4177                DFID", %#llx]: rc = %d\n",
4178                lfsck_lfsck2name(lfsck), pos->lp_oit_cookie,
4179                PFID(&pos->lp_dir_parent), pos->lp_dir_cookie, rc);
4180
4181         return rc;
4182 }
4183
4184 static int lfsck_namespace_exec_oit(const struct lu_env *env,
4185                                     struct lfsck_component *com,
4186                                     struct dt_object *obj)
4187 {
4188         struct lfsck_thread_info *info  = lfsck_env_info(env);
4189         struct lfsck_namespace   *ns    = com->lc_file_ram;
4190         struct lfsck_instance    *lfsck = com->lc_lfsck;
4191         const struct lu_fid      *fid   = lfsck_dto2fid(obj);
4192         struct lu_fid            *pfid  = &info->lti_fid2;
4193         struct lu_name           *cname = &info->lti_name;
4194         struct lu_seq_range      *range = &info->lti_range;
4195         struct seq_server_site   *ss    = lfsck_dev_site(lfsck);
4196         struct linkea_data        ldata = { NULL };
4197         __u32                     idx   = lfsck_dev_idx(lfsck);
4198         int                       rc;
4199         ENTRY;
4200
4201         rc = lfsck_links_read(env, obj, &ldata);
4202         if (rc == -ENOENT)
4203                 GOTO(out, rc = 0);
4204
4205         /* -EINVAL means crashed linkEA, should be verified. */
4206         if (rc == -EINVAL) {
4207                 rc = lfsck_namespace_trace_update(env, com, fid,
4208                                                   LNTF_CHECK_LINKEA, true);
4209                 if (rc == 0) {
4210                         struct lustre_handle lh = { 0 };
4211
4212                         rc = lfsck_ibits_lock(env, lfsck, obj, &lh,
4213                                               MDS_INODELOCK_UPDATE |
4214                                               MDS_INODELOCK_XATTR, LCK_EX);
4215                         if (rc == 0) {
4216                                 rc = lfsck_namespace_links_remove(env, com,
4217                                                                   obj);
4218                                 lfsck_ibits_unlock(&lh, LCK_EX);
4219                         }
4220                 }
4221
4222                 GOTO(out, rc = (rc == -ENOENT ? 0 : rc));
4223         }
4224
4225         if (rc == -ENODATA || unlikely(!ldata.ld_leh->leh_reccount)) {
4226                 rc = lfsck_namespace_check_for_double_scan(env, com, obj);
4227
4228                 GOTO(out, rc);
4229         }
4230
4231         if (rc != 0)
4232                 GOTO(out, rc);
4233
4234         /* Record multiple-linked object. */
4235         if (ldata.ld_leh->leh_reccount > 1) {
4236                 rc = lfsck_namespace_trace_update(env, com, fid,
4237                                                   LNTF_CHECK_LINKEA, true);
4238
4239                 GOTO(out, rc);
4240         }
4241
4242         linkea_first_entry(&ldata);
4243         linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen, cname, pfid);
4244         if (!fid_is_sane(pfid)) {
4245                 rc = lfsck_namespace_trace_update(env, com, fid,
4246                                                   LNTF_CHECK_PARENT, true);
4247         } else {
4248                 fld_range_set_mdt(range);
4249                 rc = fld_local_lookup(env, ss->ss_server_fld,
4250                                       fid_seq(pfid), range);
4251                 if ((rc == -ENOENT) ||
4252                     (rc == 0 && range->lsr_index != idx))
4253                         rc = lfsck_namespace_trace_update(env, com, fid,
4254                                                 LNTF_CHECK_LINKEA, true);
4255                 else
4256                         rc = lfsck_namespace_check_for_double_scan(env, com,
4257                                                                    obj);
4258         }
4259
4260         GOTO(out, rc);
4261
4262 out:
4263         down_write(&com->lc_sem);
4264         if (S_ISDIR(lfsck_object_type(obj)))
4265                 ns->ln_dirs_checked++;
4266         if (rc != 0)
4267                 lfsck_namespace_record_failure(env, com->lc_lfsck, ns);
4268         up_write(&com->lc_sem);
4269
4270         return rc;
4271 }
4272
4273 static int lfsck_namespace_exec_dir(const struct lu_env *env,
4274                                     struct lfsck_component *com,
4275                                     struct lfsck_assistant_object *lso,
4276                                     struct lu_dirent *ent, __u16 type)
4277 {
4278         struct lfsck_assistant_data     *lad     = com->lc_data;
4279         struct lfsck_instance           *lfsck   = com->lc_lfsck;
4280         struct lfsck_namespace_req      *lnr;
4281         struct lfsck_bookmark           *bk      = &lfsck->li_bookmark_ram;
4282         struct ptlrpc_thread            *mthread = &lfsck->li_thread;
4283         struct ptlrpc_thread            *athread = &lad->lad_thread;
4284         struct l_wait_info               lwi     = { 0 };
4285         bool                             wakeup  = false;
4286
4287         l_wait_event(mthread->t_ctl_waitq,
4288                      lad->lad_prefetched < bk->lb_async_windows ||
4289                      !thread_is_running(mthread) ||
4290                      !thread_is_running(athread),
4291                      &lwi);
4292
4293         if (unlikely(!thread_is_running(mthread) ||
4294                      !thread_is_running(athread)))
4295                 return 0;
4296
4297         if (unlikely(lfsck_is_dead_obj(lfsck->li_obj_dir)))
4298                 return 0;
4299
4300         lnr = lfsck_namespace_assistant_req_init(com->lc_lfsck, lso, ent, type);
4301         if (IS_ERR(lnr)) {
4302                 struct lfsck_namespace *ns = com->lc_file_ram;
4303
4304                 lfsck_namespace_record_failure(env, com->lc_lfsck, ns);
4305                 return PTR_ERR(lnr);
4306         }
4307
4308         spin_lock(&lad->lad_lock);
4309         if (lad->lad_assistant_status < 0 ||
4310             unlikely(!thread_is_running(mthread) ||
4311                      !thread_is_running(athread))) {
4312                 spin_unlock(&lad->lad_lock);
4313                 lfsck_namespace_assistant_req_fini(env, &lnr->lnr_lar);
4314                 return lad->lad_assistant_status;
4315         }
4316
4317         list_add_tail(&lnr->lnr_lar.lar_list, &lad->lad_req_list);
4318         if (lad->lad_prefetched == 0)
4319                 wakeup = true;
4320
4321         lad->lad_prefetched++;
4322         spin_unlock(&lad->lad_lock);
4323         if (wakeup)
4324                 wake_up_all(&lad->lad_thread.t_ctl_waitq);
4325
4326         down_write(&com->lc_sem);
4327         com->lc_new_checked++;
4328         up_write(&com->lc_sem);
4329
4330         return 0;
4331 }
4332
4333 static int lfsck_namespace_post(const struct lu_env *env,
4334                                 struct lfsck_component *com,
4335                                 int result, bool init)
4336 {
4337         struct lfsck_instance   *lfsck = com->lc_lfsck;
4338         struct lfsck_namespace  *ns    = com->lc_file_ram;
4339         int                      rc;
4340         ENTRY;
4341
4342         lfsck_post_generic(env, com, &result);
4343
4344         down_write(&com->lc_sem);
4345         lfsck_namespace_release_lmv(env, com);
4346
4347         spin_lock(&lfsck->li_lock);
4348         if (!init)
4349                 ns->ln_pos_last_checkpoint = lfsck->li_pos_checkpoint;
4350         if (result > 0) {
4351                 ns->ln_status = LS_SCANNING_PHASE2;
4352                 ns->ln_flags |= LF_SCANNED_ONCE;
4353                 ns->ln_flags &= ~LF_UPGRADE;
4354                 list_del_init(&com->lc_link_dir);
4355                 list_move_tail(&com->lc_link, &lfsck->li_list_double_scan);
4356         } else if (result == 0) {
4357                 if (lfsck->li_status != 0)
4358                         ns->ln_status = lfsck->li_status;
4359                 else
4360                         ns->ln_status = LS_STOPPED;
4361                 if (ns->ln_status != LS_PAUSED) {
4362                         list_del_init(&com->lc_link_dir);
4363                         list_move_tail(&com->lc_link, &lfsck->li_list_idle);
4364                 }
4365         } else {
4366                 ns->ln_status = LS_FAILED;
4367                 list_del_init(&com->lc_link_dir);
4368                 list_move_tail(&com->lc_link, &lfsck->li_list_idle);
4369         }
4370         spin_unlock(&lfsck->li_lock);
4371
4372         if (!init) {
4373                 ns->ln_run_time_phase1 += ktime_get_seconds() -
4374                                           lfsck->li_time_last_checkpoint;
4375                 ns->ln_time_last_checkpoint = ktime_get_real_seconds();
4376                 ns->ln_items_checked += com->lc_new_checked;
4377                 com->lc_new_checked = 0;
4378         }
4379
4380         rc = lfsck_namespace_store(env, com);
4381         up_write(&com->lc_sem);
4382
4383         CDEBUG(D_LFSCK, "%s: namespace LFSCK post done: rc = %d\n",
4384                lfsck_lfsck2name(lfsck), rc);
4385
4386         RETURN(rc);
4387 }
4388
4389 static void
4390 lfsck_namespace_dump(const struct lu_env *env, struct lfsck_component *com,
4391                      struct seq_file *m)
4392 {
4393         struct lfsck_instance   *lfsck = com->lc_lfsck;
4394         struct lfsck_bookmark   *bk    = &lfsck->li_bookmark_ram;
4395         struct lfsck_namespace  *ns    = com->lc_file_ram;
4396
4397         down_read(&com->lc_sem);
4398         seq_printf(m, "name: lfsck_namespace\n"
4399                    "magic: %#x\n"
4400                    "version: %d\n"
4401                    "status: %s\n",
4402                    ns->ln_magic,
4403                    bk->lb_version,
4404                    lfsck_status2name(ns->ln_status));
4405
4406         lfsck_bits_dump(m, ns->ln_flags, lfsck_flags_names, "flags");
4407
4408         lfsck_bits_dump(m, bk->lb_param, lfsck_param_names, "param");
4409
4410         lfsck_time_dump(m, ns->ln_time_last_complete, "last_completed");
4411
4412         lfsck_time_dump(m, ns->ln_time_latest_start, "latest_start");
4413
4414         lfsck_time_dump(m, ns->ln_time_last_checkpoint, "last_checkpoint");
4415
4416         lfsck_pos_dump(m, &ns->ln_pos_latest_start, "latest_start_position");
4417
4418         lfsck_pos_dump(m, &ns->ln_pos_last_checkpoint,
4419                        "last_checkpoint_position");
4420
4421         lfsck_pos_dump(m, &ns->ln_pos_first_inconsistent,
4422                        "first_failure_position");
4423
4424         if (ns->ln_status == LS_SCANNING_PHASE1) {
4425                 struct lfsck_position pos;
4426                 time64_t duration = ktime_get_seconds() -
4427                                     lfsck->li_time_last_checkpoint;
4428                 u64 checked = ns->ln_items_checked + com->lc_new_checked;
4429                 u64 speed = checked;
4430                 u64 new_checked = com->lc_new_checked;
4431                 time64_t rtime = ns->ln_run_time_phase1 + duration;
4432
4433                 if (duration != 0)
4434                         new_checked = div64_s64(new_checked, duration);
4435
4436                 if (rtime != 0)
4437                         speed = div64_s64(speed, rtime);
4438
4439                 lfsck_namespace_dump_statistics(m, ns, checked, 0, rtime, 0,
4440                                                 bk->lb_param & LPF_DRYRUN);
4441                 seq_printf(m, "average_speed_phase1: %llu items/sec\n"
4442                            "average_speed_phase2: N/A\n"
4443                            "average_speed_total: %llu items/sec\n"
4444                            "real_time_speed_phase1: %llu items/sec\n"
4445                            "real_time_speed_phase2: N/A\n",
4446                            speed,
4447                            speed,
4448                            new_checked);
4449
4450                 if (likely(lfsck->li_di_oit)) {
4451                         const struct dt_it_ops *iops =
4452                                 &lfsck->li_obj_oit->do_index_ops->dio_it;
4453
4454                         /* The low layer otable-based iteration position may NOT
4455                          * exactly match the namespace-based directory traversal
4456                          * cookie. Generally, it is not a serious issue. But the
4457                          * caller should NOT make assumption on that. */
4458                         pos.lp_oit_cookie = iops->store(env, lfsck->li_di_oit);
4459                         if (!lfsck->li_current_oit_processed)
4460                                 pos.lp_oit_cookie--;
4461
4462                         spin_lock(&lfsck->li_lock);
4463                         if (lfsck->li_di_dir) {
4464                                 pos.lp_dir_cookie = lfsck->li_cookie_dir;
4465                                 if (pos.lp_dir_cookie >= MDS_DIR_END_OFF) {
4466                                         fid_zero(&pos.lp_dir_parent);
4467                                         pos.lp_dir_cookie = 0;
4468                                 } else {
4469                                         pos.lp_dir_parent =
4470                                         *lfsck_dto2fid(lfsck->li_obj_dir);
4471                                 }
4472                         } else {
4473                                 fid_zero(&pos.lp_dir_parent);
4474                                 pos.lp_dir_cookie = 0;
4475                         }
4476                         spin_unlock(&lfsck->li_lock);
4477                 } else {
4478                         pos = ns->ln_pos_last_checkpoint;
4479                 }
4480
4481                 lfsck_pos_dump(m, &pos, "current_position");
4482         } else if (ns->ln_status == LS_SCANNING_PHASE2) {
4483                 time64_t duration = ktime_get_seconds() -
4484                                     com->lc_time_last_checkpoint;
4485                 __u64 checked = ns->ln_objs_checked_phase2 +
4486                                 com->lc_new_checked;
4487                 __u64 speed1 = ns->ln_items_checked;
4488                 __u64 speed2 = checked;
4489                 __u64 speed0 = speed1 + speed2;
4490                 __u64 new_checked = com->lc_new_checked;
4491                 time64_t rtime = ns->ln_run_time_phase2 + duration;
4492                 time64_t time0 = ns->ln_run_time_phase1 + rtime;
4493
4494                 if (duration != 0)
4495                         new_checked = div64_s64(new_checked, duration);
4496
4497                 if (ns->ln_run_time_phase1 != 0)
4498                         speed1 = div64_s64(speed1, ns->ln_run_time_phase1);
4499                 else if (ns->ln_items_checked != 0)
4500                         time0++;
4501
4502                 if (rtime != 0)
4503                         speed2 = div64_s64(speed2, rtime);
4504                 else if (checked != 0)
4505                         time0++;
4506
4507                 if (time0 != 0)
4508                         speed0 = div64_s64(speed0, time0);
4509
4510                 lfsck_namespace_dump_statistics(m, ns, ns->ln_items_checked,
4511                                                 checked,
4512                                                 ns->ln_run_time_phase1, rtime,
4513                                                 bk->lb_param & LPF_DRYRUN);
4514                 seq_printf(m, "average_speed_phase1: %llu items/sec\n"
4515                            "average_speed_phase2: %llu objs/sec\n"
4516                            "average_speed_total: %llu items/sec\n"
4517                            "real_time_speed_phase1: N/A\n"
4518                            "real_time_speed_phase2: %llu objs/sec\n"
4519                            "current_position: "DFID"\n",
4520                            speed1,
4521                            speed2,
4522                            speed0,
4523                            new_checked,
4524                            PFID(&ns->ln_fid_latest_scanned_phase2));
4525         } else {
4526                 __u64 speed1 = ns->ln_items_checked;
4527                 __u64 speed2 = ns->ln_objs_checked_phase2;
4528                 __u64 speed0 = speed1 + speed2;
4529                 time64_t time0 = ns->ln_run_time_phase1 + ns->ln_run_time_phase2;
4530
4531                 if (ns->ln_run_time_phase1 != 0)
4532                         speed1 = div64_s64(speed1, ns->ln_run_time_phase1);
4533                 else if (ns->ln_items_checked != 0)
4534                         time0++;
4535
4536                 if (ns->ln_run_time_phase2 != 0)
4537                         speed2 = div64_s64(speed2, ns->ln_run_time_phase2);
4538                 else if (ns->ln_objs_checked_phase2 != 0)
4539                         time0++;
4540
4541                 if (time0 != 0)
4542                         speed0 = div64_s64(speed0, time0);
4543
4544                 lfsck_namespace_dump_statistics(m, ns, ns->ln_items_checked,
4545                                                 ns->ln_objs_checked_phase2,
4546                                                 ns->ln_run_time_phase1,
4547                                                 ns->ln_run_time_phase2,
4548                                                 bk->lb_param & LPF_DRYRUN);
4549                 seq_printf(m, "average_speed_phase1: %llu items/sec\n"
4550                            "average_speed_phase2: %llu objs/sec\n"
4551                            "average_speed_total: %llu items/sec\n"
4552                            "real_time_speed_phase1: N/A\n"
4553                            "real_time_speed_phase2: N/A\n"
4554                            "current_position: N/A\n",
4555                            speed1,
4556                            speed2,
4557                            speed0);
4558         }
4559
4560         up_read(&com->lc_sem);
4561 }
4562
4563 static int lfsck_namespace_double_scan(const struct lu_env *env,
4564                                        struct lfsck_component *com)
4565 {
4566         struct lfsck_namespace          *ns     = com->lc_file_ram;
4567         struct lfsck_assistant_data     *lad    = com->lc_data;
4568         struct lfsck_tgt_descs          *ltds   = &com->lc_lfsck->li_mdt_descs;
4569         struct lfsck_tgt_desc           *ltd;
4570         struct lfsck_tgt_desc           *next;
4571         int                              rc;
4572
4573         rc = lfsck_double_scan_generic(env, com, ns->ln_status);
4574         if (thread_is_stopped(&lad->lad_thread)) {
4575                 LASSERT(list_empty(&lad->lad_req_list));
4576                 LASSERT(list_empty(&lad->lad_mdt_phase1_list));
4577
4578                 spin_lock(&ltds->ltd_lock);
4579                 list_for_each_entry_safe(ltd, next, &lad->lad_mdt_phase2_list,
4580                                          ltd_namespace_phase_list) {
4581                         list_del_init(&ltd->ltd_namespace_phase_list);
4582                 }
4583                 spin_unlock(&ltds->ltd_lock);
4584         }
4585
4586         return rc;
4587 }
4588
4589 static void lfsck_namespace_data_release(const struct lu_env *env,
4590                                          struct lfsck_component *com)
4591 {
4592         struct lfsck_assistant_data     *lad    = com->lc_data;
4593         struct lfsck_tgt_descs          *ltds   = &com->lc_lfsck->li_mdt_descs;
4594         struct lfsck_tgt_desc           *ltd;
4595         struct lfsck_tgt_desc           *next;
4596
4597         LASSERT(lad != NULL);
4598         LASSERT(thread_is_init(&lad->lad_thread) ||
4599                 thread_is_stopped(&lad->lad_thread));
4600         LASSERT(list_empty(&lad->lad_req_list));
4601
4602         com->lc_data = NULL;
4603         lfsck_namespace_release_lmv(env, com);
4604
4605         spin_lock(&ltds->ltd_lock);
4606         list_for_each_entry_safe(ltd, next, &lad->lad_mdt_phase1_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_phase2_list,
4611                                  ltd_namespace_phase_list) {
4612                 list_del_init(&ltd->ltd_namespace_phase_list);
4613         }
4614         list_for_each_entry_safe(ltd, next, &lad->lad_mdt_list,
4615                                  ltd_namespace_list) {
4616                 list_del_init(&ltd->ltd_namespace_list);
4617         }
4618         spin_unlock(&ltds->ltd_lock);
4619
4620         if (likely(lad->lad_bitmap != NULL))
4621                 CFS_FREE_BITMAP(lad->lad_bitmap);
4622
4623         OBD_FREE_PTR(lad);
4624 }
4625
4626 static void lfsck_namespace_quit(const struct lu_env *env,
4627                                  struct lfsck_component *com)
4628 {
4629         struct lfsck_assistant_data     *lad    = com->lc_data;
4630         struct lfsck_tgt_descs          *ltds   = &com->lc_lfsck->li_mdt_descs;
4631         struct lfsck_tgt_desc           *ltd;
4632         struct lfsck_tgt_desc           *next;
4633
4634         LASSERT(lad != NULL);
4635
4636         lfsck_quit_generic(env, com);
4637
4638         LASSERT(thread_is_init(&lad->lad_thread) ||
4639                 thread_is_stopped(&lad->lad_thread));
4640         LASSERT(list_empty(&lad->lad_req_list));
4641
4642         lfsck_namespace_release_lmv(env, com);
4643
4644         spin_lock(&ltds->ltd_lock);
4645         list_for_each_entry_safe(ltd, next, &lad->lad_mdt_phase1_list,
4646                                  ltd_namespace_phase_list) {
4647                 list_del_init(&ltd->ltd_namespace_phase_list);
4648         }
4649         list_for_each_entry_safe(ltd, next, &lad->lad_mdt_phase2_list,
4650                                  ltd_namespace_phase_list) {
4651                 list_del_init(&ltd->ltd_namespace_phase_list);
4652         }
4653         spin_unlock(&ltds->ltd_lock);
4654 }
4655
4656 static int lfsck_namespace_in_notify(const struct lu_env *env,
4657                                      struct lfsck_component *com,
4658                                      struct lfsck_request *lr)
4659 {
4660         struct lfsck_instance *lfsck = com->lc_lfsck;
4661         struct lfsck_namespace *ns = com->lc_file_ram;
4662         struct lfsck_assistant_data *lad = com->lc_data;
4663         struct lfsck_tgt_descs *ltds = &lfsck->li_mdt_descs;
4664         struct lfsck_tgt_desc *ltd;
4665         int rc = 0;
4666         bool fail = false;
4667         ENTRY;
4668
4669         switch (lr->lr_event) {
4670         case LE_SET_LMV_MASTER: {
4671                 struct dt_object        *obj;
4672
4673                 obj = lfsck_object_find_bottom(env, lfsck, &lr->lr_fid);
4674                 if (IS_ERR(obj))
4675                         RETURN(PTR_ERR(obj));
4676
4677                 if (likely(dt_object_exists(obj)))
4678                         rc = lfsck_namespace_notify_lmv_master_local(env, com,
4679                                                                      obj);
4680
4681                 lfsck_object_put(env, obj);
4682
4683                 RETURN(rc > 0 ? 0 : rc);
4684         }
4685         case LE_SET_LMV_SLAVE: {
4686                 if (!(lr->lr_flags & LEF_RECHECK_NAME_HASH))
4687                         ns->ln_striped_shards_repaired++;
4688
4689                 rc = lfsck_namespace_trace_update(env, com, &lr->lr_fid,
4690                                                   LNTF_RECHECK_NAME_HASH, true);
4691
4692                 RETURN(rc > 0 ? 0 : rc);
4693         }
4694         case LE_PHASE1_DONE:
4695         case LE_PHASE2_DONE:
4696         case LE_PEER_EXIT:
4697                 break;
4698         default:
4699                 RETURN(-EINVAL);
4700         }
4701
4702         CDEBUG(D_LFSCK, "%s: namespace LFSCK handles notify %u from MDT %x, "
4703                "status %d, flags %x\n", lfsck_lfsck2name(lfsck), lr->lr_event,
4704                lr->lr_index, lr->lr_status, lr->lr_flags2);
4705
4706         spin_lock(&ltds->ltd_lock);
4707         ltd = lfsck_ltd2tgt(ltds, lr->lr_index);
4708         if (ltd == NULL) {
4709                 spin_unlock(&ltds->ltd_lock);
4710
4711                 RETURN(-ENXIO);
4712         }
4713
4714         list_del_init(&ltd->ltd_namespace_phase_list);
4715         switch (lr->lr_event) {
4716         case LE_PHASE1_DONE:
4717                 if (lr->lr_status <= 0) {
4718                         ltd->ltd_namespace_done = 1;
4719                         list_del_init(&ltd->ltd_namespace_list);
4720                         CDEBUG(D_LFSCK, "%s: MDT %x failed/stopped at "
4721                                "phase1 for namespace LFSCK: rc = %d.\n",
4722                                lfsck_lfsck2name(lfsck),
4723                                ltd->ltd_index, lr->lr_status);
4724                         ns->ln_flags |= LF_INCOMPLETE;
4725                         fail = true;
4726                         break;
4727                 }
4728
4729                 if (lr->lr_flags2 & LF_INCOMPLETE)
4730                         ns->ln_flags |= LF_INCOMPLETE;
4731
4732                 if (list_empty(&ltd->ltd_namespace_list))
4733                         list_add_tail(&ltd->ltd_namespace_list,
4734                                       &lad->lad_mdt_list);
4735                 list_add_tail(&ltd->ltd_namespace_phase_list,
4736                               &lad->lad_mdt_phase2_list);
4737                 break;
4738         case LE_PHASE2_DONE:
4739                 ltd->ltd_namespace_done = 1;
4740                 list_del_init(&ltd->ltd_namespace_list);
4741                 break;
4742         case LE_PEER_EXIT:
4743                 fail = true;
4744                 ltd->ltd_namespace_done = 1;
4745                 list_del_init(&ltd->ltd_namespace_list);
4746                 if (!(lfsck->li_bookmark_ram.lb_param & LPF_FAILOUT)) {
4747                         CDEBUG(D_LFSCK,
4748                                "%s: the peer MDT %x exit namespace LFSCK\n",
4749                                lfsck_lfsck2name(lfsck), ltd->ltd_index);
4750                         ns->ln_flags |= LF_INCOMPLETE;
4751                 }
4752                 break;
4753         default:
4754                 break;
4755         }
4756         spin_unlock(&ltds->ltd_lock);
4757
4758         if (fail && lfsck->li_bookmark_ram.lb_param & LPF_FAILOUT) {
4759                 struct lfsck_stop *stop = &lfsck_env_info(env)->lti_stop;
4760
4761                 memset(stop, 0, sizeof(*stop));
4762                 stop->ls_status = lr->lr_status;
4763                 stop->ls_flags = lr->lr_param & ~LPF_BROADCAST;
4764                 lfsck_stop(env, lfsck->li_bottom, stop);
4765         } else if (lfsck_phase2_next_ready(lad)) {
4766                 wake_up_all(&lad->lad_thread.t_ctl_waitq);
4767         }
4768
4769         RETURN(0);
4770 }
4771
4772 static void lfsck_namespace_repaired(struct lfsck_namespace *ns, __u64 *count)
4773 {
4774         *count += ns->ln_objs_nlink_repaired;
4775         *count += ns->ln_dirent_repaired;
4776         *count += ns->ln_linkea_repaired;
4777         *count += ns->ln_mul_linked_repaired;
4778         *count += ns->ln_unmatched_pairs_repaired;
4779         *count += ns->ln_dangling_repaired;
4780         *count += ns->ln_mul_ref_repaired;
4781         *count += ns->ln_bad_type_repaired;
4782         *count += ns->ln_lost_dirent_repaired;
4783         *count += ns->ln_striped_dirs_disabled;
4784         *count += ns->ln_striped_dirs_repaired;
4785         *count += ns->ln_striped_shards_repaired;
4786         *count += ns->ln_name_hash_repaired;
4787         *count += ns->ln_local_lpf_moved;
4788 }
4789
4790 static int lfsck_namespace_query_all(const struct lu_env *env,
4791                                      struct lfsck_component *com,
4792                                      __u32 *mdts_count, __u64 *repaired)
4793 {
4794         struct lfsck_namespace *ns = com->lc_file_ram;
4795         struct lfsck_tgt_descs *ltds = &com->lc_lfsck->li_mdt_descs;
4796         struct lfsck_tgt_desc *ltd;
4797         int idx;
4798         int rc;
4799         ENTRY;
4800
4801         rc = lfsck_query_all(env, com);
4802         if (rc != 0)
4803                 RETURN(rc);
4804
4805         down_read(&ltds->ltd_rw_sem);
4806         cfs_foreach_bit(ltds->ltd_tgts_bitmap, idx) {
4807                 ltd = lfsck_ltd2tgt(ltds, idx);
4808                 LASSERT(ltd != NULL);
4809
4810                 mdts_count[ltd->ltd_namespace_status]++;
4811                 *repaired += ltd->ltd_namespace_repaired;
4812         }
4813         up_read(&ltds->ltd_rw_sem);
4814
4815         down_read(&com->lc_sem);
4816         mdts_count[ns->ln_status]++;
4817         lfsck_namespace_repaired(ns, repaired);
4818         up_read(&com->lc_sem);
4819
4820         RETURN(0);
4821 }
4822
4823 static int lfsck_namespace_query(const struct lu_env *env,
4824                                  struct lfsck_component *com,
4825                                  struct lfsck_request *req,
4826                                  struct lfsck_reply *rep,
4827                                  struct lfsck_query *que, int idx)
4828 {
4829         struct lfsck_namespace *ns = com->lc_file_ram;
4830         int rc = 0;
4831
4832         if (que != NULL) {
4833                 LASSERT(com->lc_lfsck->li_master);
4834
4835                 rc = lfsck_namespace_query_all(env, com,
4836                                                que->lu_mdts_count[idx],
4837                                                &que->lu_repaired[idx]);
4838         } else {
4839                 down_read(&com->lc_sem);
4840                 rep->lr_status = ns->ln_status;
4841                 if (req->lr_flags & LEF_QUERY_ALL)
4842                         lfsck_namespace_repaired(ns, &rep->lr_repaired);
4843                 up_read(&com->lc_sem);
4844         }
4845
4846         return rc;
4847 }
4848
4849 static struct lfsck_operations lfsck_namespace_ops = {
4850         .lfsck_reset            = lfsck_namespace_reset,
4851         .lfsck_fail             = lfsck_namespace_fail,
4852         .lfsck_close_dir        = lfsck_namespace_close_dir,
4853         .lfsck_open_dir         = lfsck_namespace_open_dir,
4854         .lfsck_checkpoint       = lfsck_namespace_checkpoint,
4855         .lfsck_prep             = lfsck_namespace_prep,
4856         .lfsck_exec_oit         = lfsck_namespace_exec_oit,
4857         .lfsck_exec_dir         = lfsck_namespace_exec_dir,
4858         .lfsck_post             = lfsck_namespace_post,
4859         .lfsck_dump             = lfsck_namespace_dump,
4860         .lfsck_double_scan      = lfsck_namespace_double_scan,
4861         .lfsck_data_release     = lfsck_namespace_data_release,
4862         .lfsck_quit             = lfsck_namespace_quit,
4863         .lfsck_in_notify        = lfsck_namespace_in_notify,
4864         .lfsck_query            = lfsck_namespace_query,
4865 };
4866
4867 /**
4868  * Repair dangling name entry.
4869  *
4870  * For the name entry with dangling reference, we need to repare the
4871  * inconsistency according to the LFSCK sponsor's requirement:
4872  *
4873  * 1) Keep the inconsistency there and report the inconsistency case,
4874  *    then give the chance to the application to find related issues,
4875  *    and the users can make the decision about how to handle it with
4876  *    more human knownledge. (by default)
4877  *
4878  * 2) Re-create the missing MDT-object with the FID information.
4879  *
4880  * \param[in] env       pointer to the thread context
4881  * \param[in] com       pointer to the lfsck component
4882  * \param[in] parent    pointer to the dir object that contains the dangling
4883  *                      name entry
4884  * \param[in] child     pointer to the object corresponding to the dangling
4885  *                      name entry
4886  * \param[in] lnr       pointer to the namespace request that contains the
4887  *                      name's name, parent object, parent's LMV, and ect.
4888  *
4889  * \retval              positive number if no need to repair
4890  * \retval              zero for repaired successfully
4891  * \retval              negative error number on failure
4892  */
4893 int lfsck_namespace_repair_dangling(const struct lu_env *env,
4894                                     struct lfsck_component *com,
4895                                     struct dt_object *parent,
4896                                     struct dt_object *child,
4897                                     struct lfsck_namespace_req *lnr)
4898 {
4899         struct lfsck_thread_info        *info   = lfsck_env_info(env);
4900         struct lu_attr                  *la     = &info->lti_la;
4901         struct dt_allocation_hint       *hint   = &info->lti_hint;
4902         struct dt_object_format         *dof    = &info->lti_dof;
4903         struct dt_insert_rec            *rec    = &info->lti_dt_rec;
4904         struct lmv_mds_md_v1            *lmv2   = &info->lti_lmv2;
4905         const struct lu_name            *cname;
4906         const struct lu_fid             *pfid   = lfsck_dto2fid(parent);
4907         const struct lu_fid             *cfid   = lfsck_dto2fid(child);
4908         struct linkea_data               ldata  = { NULL };
4909         struct lfsck_lock_handle        *llh    = &info->lti_llh;
4910         struct lu_buf                    linkea_buf;
4911         struct lu_buf                    lmv_buf;
4912         struct lfsck_instance           *lfsck  = com->lc_lfsck;
4913         struct lfsck_bookmark           *bk     = &lfsck->li_bookmark_ram;
4914         struct dt_device                *dev    = lfsck->li_next;
4915         struct thandle                  *th     = NULL;
4916         int                              rc     = 0;
4917         __u16                            type   = lnr->lnr_type;
4918         bool                             create;
4919         ENTRY;
4920
4921         cname = lfsck_name_get_const(env, lnr->lnr_name, lnr->lnr_namelen);
4922         if (bk->lb_param & LPF_CREATE_MDTOBJ)
4923                 create = true;
4924         else
4925                 create = false;
4926
4927         if (!create || bk->lb_param & LPF_DRYRUN)
4928                 GOTO(log, rc = 0);
4929
4930         /* We may need to create the sub-objects of the @child via LOD,
4931          * so make the modification based on lfsck->li_next. */
4932
4933         parent = lfsck_object_locate(dev, parent);
4934         if (IS_ERR(parent))
4935                 GOTO(log, rc = PTR_ERR(parent));
4936
4937         if (unlikely(!dt_try_as_dir(env, parent)))
4938                 GOTO(log, rc = -ENOTDIR);
4939
4940         child = lfsck_object_locate(dev, child);
4941         if (IS_ERR(child))
4942                 GOTO(log, rc = PTR_ERR(child));
4943
4944         rc = linkea_links_new(&ldata, &info->lti_linkea_buf2,
4945                               cname, pfid);
4946         if (rc != 0)
4947                 GOTO(log, rc);
4948
4949         rc = lfsck_lock(env, lfsck, parent, lnr->lnr_name, llh,
4950                         MDS_INODELOCK_UPDATE, LCK_PR);
4951         if (rc != 0)
4952                 GOTO(log, rc);
4953
4954         rc = lfsck_namespace_check_exist(env, parent, child, lnr->lnr_name);
4955         if (rc != 0)
4956                 GOTO(log, rc);
4957
4958         /* Set the ctime as zero, then others can know it is created for
4959          * repairing dangling name entry by LFSCK. And if the LFSCK made
4960          * wrong decision and the real MDT-object has been found later,
4961          * then the LFSCK has chance to fix the incosistency properly. */
4962         memset(la, 0, sizeof(*la));
4963         la->la_mode = (type & S_IFMT) | 0600;
4964         la->la_valid = LA_TYPE | LA_MODE | LA_UID | LA_GID |
4965                         LA_ATIME | LA_MTIME | LA_CTIME;
4966
4967         child->do_ops->do_ah_init(env, hint, parent, child,
4968                                  la->la_mode & S_IFMT);
4969
4970         memset(dof, 0, sizeof(*dof));
4971         dof->dof_type = dt_mode_to_dft(type);
4972         /* If the target is a regular file, then the LFSCK will only create
4973          * the MDT-object without stripes (dof->dof_reg.striped = 0). related
4974          * OST-objects will be created when write open. */
4975
4976         th = dt_trans_create(env, dev);
4977         if (IS_ERR(th))
4978                 GOTO(log, rc = PTR_ERR(th));
4979
4980         /* 1a. create child. */
4981         rc = dt_declare_create(env, child, la, hint, dof, th);
4982         if (rc != 0)
4983                 GOTO(stop, rc);
4984
4985         if (S_ISDIR(type)) {
4986                 if (unlikely(!dt_try_as_dir(env, child)))
4987                         GOTO(stop, rc = -ENOTDIR);
4988
4989                 /* 2a. increase child nlink */
4990                 rc = dt_declare_ref_add(env, child, th);
4991                 if (rc != 0)
4992                         GOTO(stop, rc);
4993
4994                 /* 3a. insert dot into child dir */
4995                 rec->rec_type = S_IFDIR;
4996                 rec->rec_fid = cfid;
4997                 rc = dt_declare_insert(env, child,
4998                                        (const struct dt_rec *)rec,
4999                                        (const struct dt_key *)dot, th);
5000                 if (rc != 0)
5001                         GOTO(stop, rc);
5002
5003                 /* 4a. insert dotdot into child dir */
5004                 rec->rec_fid = pfid;
5005                 rc = dt_declare_insert(env, child,
5006                                        (const struct dt_rec *)rec,
5007                                        (const struct dt_key *)dotdot, th);
5008                 if (rc != 0)
5009                         GOTO(stop, rc);
5010
5011                 /* 5a. generate slave LMV EA. */
5012                 if (lnr->lnr_lmv != NULL && lnr->lnr_lmv->ll_lmv_master) {
5013                         int idx;
5014
5015                         idx = lfsck_shard_name_to_index(env,
5016                                         lnr->lnr_name, lnr->lnr_namelen,
5017                                         type, cfid);
5018                         if (unlikely(idx < 0))
5019                                 GOTO(stop, rc = idx);
5020
5021                         *lmv2 = lnr->lnr_lmv->ll_lmv;
5022                         lmv2->lmv_magic = LMV_MAGIC_STRIPE;
5023                         lmv2->lmv_master_mdt_index = idx;
5024
5025                         lfsck_lmv_header_cpu_to_le(lmv2, lmv2);
5026                         lfsck_buf_init(&lmv_buf, lmv2, sizeof(*lmv2));
5027                         rc = dt_declare_xattr_set(env, child, &lmv_buf,
5028                                                   XATTR_NAME_LMV, 0, th);
5029                         if (rc != 0)
5030                                 GOTO(stop, rc);
5031                 }
5032         }
5033
5034         /* 6a. insert linkEA for child */
5035         lfsck_buf_init(&linkea_buf, ldata.ld_buf->lb_buf,
5036                        ldata.ld_leh->leh_len);
5037         rc = dt_declare_xattr_set(env, child, &linkea_buf,
5038                                   XATTR_NAME_LINK, 0, th);
5039         if (rc != 0)
5040                 GOTO(stop, rc);
5041
5042         rc = dt_trans_start_local(env, dev, th);
5043         if (rc != 0)
5044                 GOTO(stop, rc = (rc == -EEXIST ? 1 : rc));
5045
5046         dt_write_lock(env, child, 0);
5047         /* 1b. create child */
5048         rc = dt_create(env, child, la, hint, dof, th);
5049         if (rc != 0)
5050                 GOTO(unlock, rc = (rc == -EEXIST ? 1 : rc));
5051
5052         if (S_ISDIR(type)) {
5053                 /* 2b. increase child nlink */
5054                 rc = dt_ref_add(env, child, th);
5055                 if (rc != 0)
5056                         GOTO(unlock, rc);
5057
5058                 /* 3b. insert dot into child dir */
5059                 rec->rec_type = S_IFDIR;
5060                 rec->rec_fid = cfid;
5061                 rc = dt_insert(env, child, (const struct dt_rec *)rec,
5062                                (const struct dt_key *)dot, th, 1);
5063                 if (rc != 0)
5064                         GOTO(unlock, rc);
5065
5066                 /* 4b. insert dotdot into child dir */
5067                 rec->rec_fid = pfid;
5068                 rc = dt_insert(env, child, (const struct dt_rec *)rec,
5069                                (const struct dt_key *)dotdot, th, 1);
5070                 if (rc != 0)
5071                         GOTO(unlock, rc);
5072
5073                 /* 5b. generate slave LMV EA. */
5074                 if (lnr->lnr_lmv != NULL && lnr->lnr_lmv->ll_lmv_master) {
5075                         rc = dt_xattr_set(env, child, &lmv_buf, XATTR_NAME_LMV,
5076                                           0, th);
5077                         if (rc != 0)
5078                                 GOTO(unlock, rc);
5079                 }
5080         }
5081
5082         /* 6b. insert linkEA for child. */
5083         rc = dt_xattr_set(env, child, &linkea_buf,
5084                           XATTR_NAME_LINK, 0, th);
5085
5086         GOTO(unlock, rc);
5087
5088 unlock:
5089         dt_write_unlock(env, child);
5090
5091 stop:
5092         dt_trans_stop(env, dev, th);
5093
5094 log:
5095         lfsck_unlock(llh);
5096         CDEBUG(D_LFSCK, "%s: namespace LFSCK assistant found dangling "
5097                "reference for: parent "DFID", child "DFID", type %u, "
5098                "name %s. %s: rc = %d\n", lfsck_lfsck2name(lfsck),
5099                PFID(pfid), PFID(cfid), type, cname->ln_name,
5100                create ? "Create the lost MDT-object as required" :
5101                         "Keep the MDT-object there by default", rc);
5102
5103         if (rc <= 0) {
5104                 struct lfsck_namespace *ns = com->lc_file_ram;
5105
5106                 ns->ln_flags |= LF_INCONSISTENT;
5107         }
5108
5109         return rc;
5110 }
5111
5112 static int lfsck_namespace_assistant_handler_p1(const struct lu_env *env,
5113                                                 struct lfsck_component *com,
5114                                                 struct lfsck_assistant_req *lar)
5115 {
5116         struct lfsck_thread_info   *info     = lfsck_env_info(env);
5117         struct lu_attr             *la       = &info->lti_la;
5118         struct lfsck_instance      *lfsck    = com->lc_lfsck;
5119         struct lfsck_bookmark      *bk       = &lfsck->li_bookmark_ram;
5120         struct lfsck_namespace     *ns       = com->lc_file_ram;
5121         struct lfsck_assistant_data *lad     = com->lc_data;
5122         struct linkea_data          ldata    = { NULL };
5123         const struct lu_name       *cname;
5124         struct thandle             *handle   = NULL;
5125         struct lfsck_namespace_req *lnr      =
5126                         container_of0(lar, struct lfsck_namespace_req, lnr_lar);
5127         struct dt_object           *dir      = NULL;
5128         struct dt_object           *obj      = NULL;
5129         struct lfsck_assistant_object *lso   = lar->lar_parent;
5130         const struct lu_fid        *pfid     = &lso->lso_fid;
5131         struct dt_device           *dev      = NULL;
5132         struct lustre_handle        lh       = { 0 };
5133         bool                        repaired = false;
5134         bool                        dtlocked = false;
5135         bool                        remove;
5136         bool                        newdata;
5137         bool                        log      = false;
5138         bool                        bad_hash = false;
5139         bool                        bad_linkea = false;
5140         int                         idx      = 0;
5141         int                         count    = 0;
5142         int                         rc       = 0;
5143         enum lfsck_namespace_inconsistency_type type = LNIT_NONE;
5144         ENTRY;
5145
5146         if (lso->lso_dead)
5147                 RETURN(0);
5148
5149         la->la_nlink = 0;
5150         if (lnr->lnr_attr & LUDA_UPGRADE) {
5151                 ns->ln_flags |= LF_UPGRADE;
5152                 ns->ln_dirent_repaired++;
5153                 repaired = true;
5154         } else if (lnr->lnr_attr & LUDA_REPAIR) {
5155                 ns->ln_flags |= LF_INCONSISTENT;
5156                 ns->ln_dirent_repaired++;
5157                 repaired = true;
5158         }
5159
5160         if (unlikely(fid_is_zero(&lnr->lnr_fid))) {
5161                 if (strcmp(lnr->lnr_name, dotdot) != 0)
5162                         LBUG();
5163                 else
5164                         rc = lfsck_namespace_trace_update(env, com, pfid,
5165                                                 LNTF_CHECK_PARENT, true);
5166
5167                 GOTO(out, rc);
5168         }
5169
5170         if (unlikely(!fid_is_sane(&lnr->lnr_fid))) {
5171                 CDEBUG(D_LFSCK, "%s: dir scan find invalid FID "DFID
5172                        " for the name entry %.*s under "DFID"\n",
5173                        lfsck_lfsck2name(lfsck), PFID(&lnr->lnr_fid),
5174                        lnr->lnr_namelen, lnr->lnr_name, PFID(pfid));
5175
5176                 if (strcmp(lnr->lnr_name, dotdot) != 0)
5177                         /* invalid FID means bad name entry, remove it. */
5178                         type = LNIT_BAD_DIRENT;
5179                 else
5180                         /* If the parent FID is invalid, we cannot remove
5181                          * the ".." entry directly. */
5182                         rc = lfsck_namespace_trace_update(env, com, pfid,
5183                                                 LNTF_CHECK_PARENT, true);
5184
5185                 GOTO(out, rc);
5186         }
5187
5188         if (unlikely(lnr->lnr_dir_cookie == MDS_DIR_END_OFF)) {
5189                 rc = lfsck_namespace_striped_dir_rescan(env, com, lnr);
5190
5191                 RETURN(rc);
5192         }
5193
5194         if (fid_seq_is_dot(fid_seq(&lnr->lnr_fid)))
5195                 GOTO(out, rc = 0);
5196
5197         if (lnr->lnr_lmv != NULL && lnr->lnr_lmv->ll_lmv_master) {
5198                 rc = lfsck_namespace_handle_striped_master(env, com, lnr);
5199
5200                 RETURN(rc);
5201         }
5202
5203         idx = lfsck_find_mdt_idx_by_fid(env, lfsck, &lnr->lnr_fid);
5204         if (idx < 0)
5205                 GOTO(out, rc = idx);
5206
5207         if (idx == lfsck_dev_idx(lfsck)) {
5208                 if (unlikely(strcmp(lnr->lnr_name, dotdot) == 0))
5209                         GOTO(out, rc = 0);
5210
5211                 dev = lfsck->li_bottom;
5212         } else {
5213                 struct lfsck_tgt_desc *ltd;
5214
5215                 /* Usually, some local filesystem consistency verification
5216                  * tools can guarantee the local namespace tree consistenct.
5217                  * So the LFSCK will only verify the remote directory. */
5218                 if (unlikely(strcmp(lnr->lnr_name, dotdot) == 0)) {
5219                         rc = lfsck_namespace_trace_update(env, com, pfid,
5220                                                 LNTF_CHECK_PARENT, true);
5221
5222                         GOTO(out, rc);
5223                 }
5224
5225                 ltd = lfsck_ltd2tgt(&lfsck->li_mdt_descs, idx);
5226                 if (unlikely(ltd == NULL)) {
5227                         CDEBUG(D_LFSCK, "%s: cannot talk with MDT %x which "
5228                                "did not join the namespace LFSCK\n",
5229                                lfsck_lfsck2name(lfsck), idx);
5230                         lfsck_lad_set_bitmap(env, com, idx);
5231
5232                         GOTO(out, rc = -ENODEV);
5233                 }
5234
5235                 dev = ltd->ltd_tgt;
5236         }
5237
5238         obj = lfsck_object_find_by_dev(env, dev, &lnr->lnr_fid);
5239         if (IS_ERR(obj))
5240                 GOTO(out, rc = PTR_ERR(obj));
5241
5242         cname = lfsck_name_get_const(env, lnr->lnr_name, lnr->lnr_namelen);
5243         if (dt_object_exists(obj) == 0) {
5244
5245 dangling:
5246                 if (dir == NULL) {
5247                         dir = lfsck_assistant_object_load(env, lfsck, lso);
5248                         if (IS_ERR(dir)) {
5249                                 rc = PTR_ERR(dir);
5250
5251                                 GOTO(trace, rc == -ENOENT ? 0 : rc);
5252                         }
5253                 }
5254
5255                 rc = lfsck_namespace_check_exist(env, dir, obj, lnr->lnr_name);
5256                 if (rc == 0) {
5257                         if (!lfsck_is_valid_slave_name_entry(env, lnr->lnr_lmv,
5258                                         lnr->lnr_name, lnr->lnr_namelen)) {
5259                                 type = LNIT_BAD_DIRENT;
5260
5261                                 GOTO(out, rc);
5262                         }
5263
5264                         type = LNIT_DANGLING;
5265                         rc = lfsck_namespace_repair_dangling(env, com, dir,
5266                                                              obj, lnr);
5267                         if (rc == 0)
5268                                 repaired = true;
5269                 }
5270
5271                 GOTO(out, rc);
5272         }
5273
5274         if (!(bk->lb_param & LPF_DRYRUN) && lad->lad_advance_lock) {
5275
5276 again:
5277                 rc = lfsck_ibits_lock(env, lfsck, obj, &lh,
5278                                       MDS_INODELOCK_UPDATE |
5279                                       MDS_INODELOCK_XATTR, LCK_EX);
5280                 if (rc != 0)
5281                         GOTO(out, rc);
5282
5283                 handle = dt_trans_create(env, dev);
5284                 if (IS_ERR(handle))
5285                         GOTO(out, rc = PTR_ERR(handle));
5286
5287                 rc = lfsck_declare_namespace_exec_dir(env, obj, handle);
5288                 if (rc != 0)
5289                         GOTO(stop, rc);
5290
5291                 rc = dt_trans_start_local(env, dev, handle);
5292                 if (rc != 0)
5293                         GOTO(stop, rc);
5294
5295                 dt_write_lock(env, obj, 0);
5296                 dtlocked = true;
5297         }
5298
5299         rc = lfsck_links_read(env, obj, &ldata);
5300         if (unlikely(rc == -ENOENT)) {
5301                 if (handle != NULL) {
5302                         dt_write_unlock(env, obj);
5303                         dtlocked = false;
5304
5305                         dt_trans_stop(env, dev, handle);
5306                         handle = NULL;
5307
5308                         lfsck_ibits_unlock(&lh, LCK_EX);
5309                 }
5310
5311                 /* It may happen when the remote object has been removed,
5312                  * but the local MDT is not aware of that. */
5313                 goto dangling;
5314         } else if (rc == 0) {
5315                 count = ldata.ld_leh->leh_reccount;
5316                 rc = linkea_links_find(&ldata, cname, pfid);
5317                 if ((rc == 0) &&
5318                     (count == 1 || !S_ISDIR(lfsck_object_type(obj)))) {
5319                         if ((lfsck_object_type(obj) & S_IFMT) !=
5320                             lnr->lnr_type) {
5321                                 ns->ln_flags |= LF_INCONSISTENT;
5322                                 type = LNIT_BAD_TYPE;
5323                         }
5324
5325                         goto stop;
5326                 }
5327
5328                 /* If the name entry hash does not match the slave striped
5329                  * directory, and the name entry does not match also, then
5330                  * it is quite possible that name entry is corrupted. */
5331                 if (!lfsck_is_valid_slave_name_entry(env, lnr->lnr_lmv,
5332                                         lnr->lnr_name, lnr->lnr_namelen)) {
5333                         ns->ln_flags |= LF_INCONSISTENT;
5334                         type = LNIT_BAD_DIRENT;
5335
5336                         GOTO(stop, rc = 0);
5337                 }
5338
5339                 /* If the file type stored in the name entry does not match
5340                  * the file type claimed by the object, and the object does
5341                  * not recognize the name entry, then it is quite possible
5342                  * that the name entry is corrupted. */
5343                 if ((lfsck_object_type(obj) & S_IFMT) != lnr->lnr_type) {
5344                         ns->ln_flags |= LF_INCONSISTENT;
5345                         type = LNIT_BAD_DIRENT;
5346
5347                         GOTO(stop, rc = 0);
5348                 }
5349
5350                 /* For sub-dir object, we cannot make sure whether the sub-dir
5351                  * back references the parent via ".." name entry correctly or
5352                  * not in the LFSCK first-stage scanning. It may be that the
5353                  * (remote) sub-dir ".." name entry has no parent FID after
5354                  * file-level backup/restore and its linkEA may be wrong.
5355                  * So under such case, we should replace the linkEA according
5356                  * to current name entry. But this needs to be done during the
5357                  * LFSCK second-stage scanning. The LFSCK will record the name
5358                  * entry for further possible using. */
5359                 remove = false;
5360                 newdata = false;
5361                 goto nodata;
5362         } else if (unlikely(rc == -EINVAL)) {
5363                 if ((lfsck_object_type(obj) & S_IFMT) != lnr->lnr_type)
5364                         type = LNIT_BAD_TYPE;
5365
5366                 count = 1;
5367                 /* The magic crashed, we are not sure whether there are more
5368                  * corrupt data in the linkea, so remove all linkea entries. */
5369                 remove = true;
5370                 newdata = true;
5371                 goto nodata;
5372         } else if (rc == -ENODATA) {
5373                 if ((lfsck_object_type(obj) & S_IFMT) != lnr->lnr_type)
5374                         type = LNIT_BAD_TYPE;
5375
5376                 count = 1;
5377                 remove = false;
5378                 newdata = true;
5379
5380 nodata:
5381                 if (bk->lb_param & LPF_DRYRUN) {
5382                         if (rc == -ENODATA)
5383                                 ns->ln_flags |= LF_UPGRADE;
5384                         else
5385                                 ns->ln_flags |= LF_INCONSISTENT;
5386                         ns->ln_linkea_repaired++;
5387                         repaired = true;
5388                         log = true;
5389                         goto stop;
5390                 }
5391
5392                 if (!lustre_handle_is_used(&lh)) {
5393                         remove = false;
5394                         newdata = false;
5395                         type = LNIT_NONE;
5396
5397                         goto again;
5398                 }
5399
5400                 LASSERT(handle != NULL);
5401
5402                 if (dir == NULL) {
5403                         dir = lfsck_assistant_object_load(env, lfsck, lso);
5404                         if (IS_ERR(dir)) {
5405                                 rc = PTR_ERR(dir);
5406
5407                                 GOTO(stop, rc == -ENOENT ? 0 : rc);
5408                         }
5409                 }
5410
5411                 rc = lfsck_namespace_check_exist(env, dir, obj, lnr->lnr_name);
5412                 if (rc != 0)
5413                         GOTO(stop, rc);
5414
5415                 bad_linkea = true;
5416                 if (!remove && newdata)
5417                         ns->ln_flags |= LF_UPGRADE;
5418                 else if (remove || !(ns->ln_flags & LF_UPGRADE))
5419                         ns->ln_flags |= LF_INCONSISTENT;
5420
5421                 if (remove) {
5422                         LASSERT(newdata);
5423
5424                         rc = dt_xattr_del(env, obj, XATTR_NAME_LINK, handle);
5425                         if (rc != 0 && rc != -ENOENT && rc != -ENODATA)
5426                                 GOTO(stop, rc);
5427                 }
5428
5429                 if (newdata) {
5430                         rc = linkea_data_new(&ldata,
5431                                         &lfsck_env_info(env)->lti_linkea_buf);
5432                         if (rc != 0)
5433                                 GOTO(stop, rc);
5434                 }
5435
5436                 rc = linkea_add_buf(&ldata, cname, pfid);
5437                 if (rc == 0)
5438                         rc = lfsck_links_write(env, obj, &ldata, handle);
5439                 if (rc != 0)
5440                         GOTO(stop, rc);
5441
5442                 count = ldata.ld_leh->leh_reccount;
5443                 if (!S_ISDIR(lfsck_object_type(obj)) ||
5444                     !dt_object_remote(obj)) {
5445                         ns->ln_linkea_repaired++;
5446                         repaired = true;
5447                         log = true;
5448                 }
5449         } else {
5450                 GOTO(stop, rc);
5451         }
5452
5453 stop:
5454         if (dtlocked)
5455                 dt_write_unlock(env, obj);
5456
5457         if (handle != NULL && !IS_ERR(handle))
5458                 dt_trans_stop(env, dev, handle);
5459
5460 out:
5461         lfsck_ibits_unlock(&lh, LCK_EX);
5462
5463         if (!name_is_dot_or_dotdot(lnr->lnr_name, lnr->lnr_namelen) &&
5464             !lfsck_is_valid_slave_name_entry(env, lnr->lnr_lmv,
5465                                              lnr->lnr_name, lnr->lnr_namelen) &&
5466             type != LNIT_BAD_DIRENT) {
5467                 ns->ln_flags |= LF_INCONSISTENT;
5468
5469                 log = false;
5470                 if (dir == NULL) {
5471                         dir = lfsck_assistant_object_load(env, lfsck, lso);
5472                         if (IS_ERR(dir)) {
5473                                 rc = PTR_ERR(dir);
5474
5475                                 GOTO(trace, rc == -ENOENT ? 0 : rc);
5476                         }
5477                 }
5478
5479                 rc = lfsck_namespace_repair_bad_name_hash(env, com, dir,
5480                                                 lnr->lnr_lmv, lnr->lnr_name);
5481                 if (rc == 0)
5482                         bad_hash = true;
5483         }
5484
5485         if (rc >= 0) {
5486                 if (type != LNIT_NONE && dir == NULL) {
5487                         dir = lfsck_assistant_object_load(env, lfsck, lso);
5488                         if (IS_ERR(dir)) {
5489                                 rc = PTR_ERR(dir);
5490
5491                                 GOTO(trace, rc == -ENOENT ? 0 : rc);
5492                         }
5493                 }
5494
5495                 switch (type) {
5496                 case LNIT_BAD_TYPE:
5497                         log = false;
5498                         rc = lfsck_namespace_repair_dirent(env, com, dir,
5499                                         obj, lnr->lnr_name, lnr->lnr_name,
5500                                         lnr->lnr_type, true, false);
5501                         if (rc > 0)
5502                                 repaired = true;
5503                         break;
5504                 case LNIT_BAD_DIRENT:
5505                         log = false;
5506                         /* XXX: This is a bad dirent, we do not know whether
5507                          *      the original name entry reference a regular
5508                          *      file or a directory, then keep the parent's
5509                          *      nlink count unchanged here. */
5510                         rc = lfsck_namespace_repair_dirent(env, com, dir,
5511                                         obj, lnr->lnr_name, lnr->lnr_name,
5512                                         lnr->lnr_type, false, false);
5513                         if (rc > 0)
5514                                 repaired = true;
5515                         break;
5516                 default:
5517                         break;
5518                 }
5519
5520                 if (obj != NULL && count == 1 &&
5521                     S_ISREG(lfsck_object_type(obj)))
5522                         dt_attr_get(env, obj, la);
5523         }
5524
5525 trace:
5526         down_write(&com->lc_sem);
5527         if (rc < 0) {
5528                 CDEBUG(D_LFSCK, "%s: namespace LFSCK assistant fail to handle "
5529                        "the entry: "DFID", parent "DFID", name %.*s: rc = %d\n",
5530                        lfsck_lfsck2name(lfsck), PFID(&lnr->lnr_fid), PFID(pfid),
5531                        lnr->lnr_namelen, lnr->lnr_name, rc);
5532
5533                 lfsck_namespace_record_failure(env, lfsck, ns);
5534                 if ((rc == -ENOTCONN || rc == -ESHUTDOWN || rc == -EREMCHG ||
5535                      rc == -ETIMEDOUT || rc == -EHOSTDOWN ||
5536                      rc == -EHOSTUNREACH || rc == -EINPROGRESS) &&
5537                     dev != NULL && dev != lfsck->li_bottom)
5538                         lfsck_lad_set_bitmap(env, com, idx);
5539
5540                 if (!(bk->lb_param & LPF_FAILOUT))
5541                         rc = 0;
5542         } else {
5543                 if (repaired) {
5544                         ns->ln_items_repaired++;
5545                         if (log)
5546                                 CDEBUG(D_LFSCK, "%s: namespace LFSCK assistant "
5547                                        "repaired the entry: "DFID", parent "DFID
5548                                        ", name %.*s, type %d\n",
5549                                        lfsck_lfsck2name(lfsck),
5550                                        PFID(&lnr->lnr_fid), PFID(pfid),
5551                                        lnr->lnr_namelen, lnr->lnr_name, type);
5552
5553                         switch (type) {
5554                         case LNIT_DANGLING:
5555                                 ns->ln_dangling_repaired++;
5556                                 break;
5557                         case LNIT_BAD_TYPE:
5558                                 ns->ln_bad_type_repaired++;
5559                                 break;
5560                         case LNIT_BAD_DIRENT:
5561                                 ns->ln_dirent_repaired++;
5562                                 break;
5563                         default:
5564                                 break;
5565                         }
5566
5567                         if (bk->lb_param & LPF_DRYRUN &&
5568                             lfsck_pos_is_zero(&ns->ln_pos_first_inconsistent))
5569                                 lfsck_pos_fill(env, lfsck,
5570                                                &ns->ln_pos_first_inconsistent,
5571                                                false);
5572                 }
5573
5574                 if (bad_hash) {
5575                         ns->ln_name_hash_repaired++;
5576
5577                         /* Not count repeatedly. */
5578                         if (!repaired) {
5579                                 ns->ln_items_repaired++;
5580                                 if (log)
5581                                         CDEBUG(D_LFSCK, "%s: namespace LFSCK "
5582                                                "assistant repaired the entry: "
5583                                                DFID", parent "DFID
5584                                                ", name %.*s\n",
5585                                                lfsck_lfsck2name(lfsck),
5586                                                PFID(&lnr->lnr_fid), PFID(pfid),
5587                                                lnr->lnr_namelen, lnr->lnr_name);
5588                         }
5589
5590                         if (bk->lb_param & LPF_DRYRUN &&
5591                             lfsck_pos_is_zero(&ns->ln_pos_first_inconsistent))
5592                                 lfsck_pos_fill(env, lfsck,
5593                                                &ns->ln_pos_first_inconsistent,
5594                                                false);
5595                 }
5596
5597                 rc = 0;
5598         }
5599
5600         if (count > 1 || la->la_nlink > 1)
5601                 ns->ln_mul_linked_checked++;
5602
5603         up_write(&com->lc_sem);
5604
5605         if (obj != NULL && !IS_ERR(obj))
5606                 lfsck_object_put(env, obj);
5607
5608         if (dir != NULL && !IS_ERR(dir))
5609                 lfsck_object_put(env, dir);
5610
5611         lad->lad_advance_lock = bad_linkea;
5612
5613         return rc;
5614 }
5615
5616 /**
5617  * Handle one orphan under the backend /lost+found directory
5618  *
5619  * Insert the orphan FID into the namespace LFSCK trace file for further
5620  * processing (via the subsequent namespace LFSCK second-stage scanning).
5621  * At the same time, remove the orphan name entry from backend /lost+found
5622  * directory. There is an interval between the orphan name entry removed
5623  * from the backend /lost+found directory and the orphan FID in the LFSCK
5624  * trace file handled. In such interval, the LFSCK can be reset, then
5625  * all the FIDs recorded in the namespace LFSCK trace file will be dropped.
5626  * To guarantee that the orphans can be found when LFSCK run next time
5627  * without e2fsck again, when remove the orphan name entry, the LFSCK
5628  * will set the orphan's ctime attribute as 1. Since normal applications
5629  * cannot change the object's ctime attribute as 1. Then when LFSCK run
5630  * next time, it can record the object (that ctime is 1) in the namespace
5631  * LFSCK trace file during the first-stage scanning.
5632  *
5633  * \param[in] env       pointer to the thread context
5634  * \param[in] com       pointer to the lfsck component
5635  * \param[in] parent    pointer to the object for the backend /lost+found
5636  * \param[in] ent       pointer to the name entry for the target under the
5637  *                      backend /lost+found
5638  *
5639  * \retval              positive for repaired
5640  * \retval              0 if needs to repair nothing
5641  * \retval              negative error number on failure
5642  */
5643 static int lfsck_namespace_scan_local_lpf_one(const struct lu_env *env,
5644                                               struct lfsck_component *com,
5645                                               struct dt_object *parent,
5646                                               struct lu_dirent *ent)
5647 {
5648         struct lfsck_thread_info        *info   = lfsck_env_info(env);
5649         struct lu_fid                   *key    = &info->lti_fid;
5650         struct lu_attr                  *la     = &info->lti_la;
5651         struct lfsck_instance           *lfsck  = com->lc_lfsck;
5652         struct dt_object                *obj;
5653         struct dt_device                *dev    = lfsck->li_bottom;
5654         struct dt_object                *child  = NULL;
5655         struct thandle                  *th     = NULL;
5656         int                              idx;
5657         int                              rc     = 0;
5658         __u8                             flags  = 0;
5659         bool                             exist  = false;
5660         ENTRY;
5661
5662         child = lfsck_object_find_by_dev(env, dev, &ent->lde_fid);
5663         if (IS_ERR(child))
5664                 RETURN(PTR_ERR(child));
5665
5666         LASSERT(dt_object_exists(child));
5667         LASSERT(!dt_object_remote(child));
5668
5669         idx = lfsck_sub_trace_file_fid2idx(&ent->lde_fid);
5670         obj = com->lc_sub_trace_objs[idx].lsto_obj;
5671         fid_cpu_to_be(key, &ent->lde_fid);
5672         rc = dt_lookup(env, obj, (struct dt_rec *)&flags,
5673                        (const struct dt_key *)key);
5674         if (rc == 0) {
5675                 exist = true;
5676                 flags |= LNTF_CHECK_ORPHAN;
5677         } else if (rc == -ENOENT) {
5678                 flags = LNTF_CHECK_ORPHAN;
5679         } else {
5680                 GOTO(out, rc);
5681         }
5682
5683         th = dt_trans_create(env, dev);
5684         if (IS_ERR(th))
5685                 GOTO(out, rc = PTR_ERR(th));
5686
5687         /* a1. remove name entry from backend /lost+found */
5688         rc = dt_declare_delete(env, parent,
5689                                (const struct dt_key *)ent->lde_name, th);
5690         if (rc != 0)
5691                 GOTO(stop, rc);
5692
5693         if (S_ISDIR(lfsck_object_type(child))) {
5694                 /* a2. decrease parent's nlink */
5695                 rc = dt_declare_ref_del(env, parent, th);
5696                 if (rc != 0)
5697                         GOTO(stop, rc);
5698         }
5699
5700         if (exist) {
5701                 /* a3. remove child's FID from the LFSCK trace file. */
5702                 rc = dt_declare_delete(env, obj,
5703                                        (const struct dt_key *)key, th);
5704                 if (rc != 0)
5705                         GOTO(stop, rc);
5706         } else {
5707                 /* a4. set child's ctime as 1 */
5708                 memset(la, 0, sizeof(*la));
5709                 la->la_ctime = 1;
5710                 la->la_valid = LA_CTIME;
5711                 rc = dt_declare_attr_set(env, child, la, th);
5712                 if (rc != 0)
5713                         GOTO(stop, rc);
5714         }
5715
5716         /* a5. insert child's FID into the LFSCK trace file. */
5717         rc = dt_declare_insert(env, obj, (const struct dt_rec *)&flags,
5718                                (const struct dt_key *)key, th);
5719         if (rc != 0)
5720                 GOTO(stop, rc);
5721
5722         rc = dt_trans_start_local(env, dev, th);
5723         if (rc != 0)
5724                 GOTO(stop, rc);
5725
5726         /* b1. remove name entry from backend /lost+found */
5727         rc = dt_delete(env, parent, (const struct dt_key *)ent->lde_name, th);
5728         if (rc != 0)
5729                 GOTO(stop, rc);
5730
5731         if (S_ISDIR(lfsck_object_type(child))) {
5732                 /* b2. decrease parent's nlink */
5733                 dt_write_lock(env, parent, 0);
5734                 rc = dt_ref_del(env, parent, th);
5735                 dt_write_unlock(env, parent);
5736                 if (rc != 0)
5737                         GOTO(stop, rc);
5738         }
5739
5740         if (exist) {
5741                 /* a3. remove child's FID from the LFSCK trace file. */
5742                 rc = dt_delete(env, obj, (const struct dt_key *)key, th);
5743                 if (rc != 0)
5744                         GOTO(stop, rc);
5745         } else {
5746                 /* b4. set child's ctime as 1 */
5747                 rc = dt_attr_set(env, child, la, th);
5748                 if (rc != 0)
5749                         GOTO(stop, rc);
5750         }
5751
5752         /* b5. insert child's FID into the LFSCK trace file. */
5753         rc = dt_insert(env, obj, (const struct dt_rec *)&flags,
5754                        (const struct dt_key *)key, th, 1);
5755
5756         GOTO(stop, rc = (rc == 0 ? 1 : rc));
5757
5758 stop:
5759         dt_trans_stop(env, dev, th);
5760
5761 out:
5762         lfsck_object_put(env, child);
5763
5764         return rc;
5765 }
5766
5767 /**
5768  * Handle orphans under the backend /lost+found directory
5769  *
5770  * Some backend checker, such as e2fsck for ldiskfs may find some orphans
5771  * and put them under the backend /lost+found directory that is invisible
5772  * to client. The LFSCK will scan such directory, for the original client
5773  * visible orphans, add their fids into the namespace LFSCK trace file,
5774  * then the subsenquent namespace LFSCK second-stage scanning can handle
5775  * them as other objects to be double scanned: either move back to normal
5776  * namespace, or to the global visible orphan directory:
5777  * /ROOT/.lustre/lost+found/MDTxxxx/
5778  *
5779  * \param[in] env       pointer to the thread context
5780  * \param[in] com       pointer to the lfsck component
5781  */
5782 static void lfsck_namespace_scan_local_lpf(const struct lu_env *env,
5783                                            struct lfsck_component *com)
5784 {
5785         struct lfsck_thread_info        *info   = lfsck_env_info(env);
5786         struct lu_dirent                *ent    =
5787                                         (struct lu_dirent *)info->lti_key;
5788         struct lu_seq_range             *range  = &info->lti_range;
5789         struct lfsck_instance           *lfsck  = com->lc_lfsck;
5790         struct ptlrpc_thread            *thread = &lfsck->li_thread;
5791         struct lfsck_bookmark           *bk     = &lfsck->li_bookmark_ram;
5792         struct lfsck_namespace          *ns     = com->lc_file_ram;
5793         struct dt_object                *parent;
5794         const struct dt_it_ops          *iops;
5795         struct dt_it                    *di;
5796         struct seq_server_site          *ss     = lfsck_dev_site(lfsck);
5797         __u64                            cookie;
5798         __u32                            idx    = lfsck_dev_idx(lfsck);
5799         int                              rc     = 0;
5800         __u16                            type;
5801         ENTRY;
5802
5803         parent = lfsck_object_find_by_dev(env, lfsck->li_bottom,
5804                                           &LU_BACKEND_LPF_FID);
5805         if (IS_ERR(parent)) {
5806                 CERROR("%s: fail to find backend /lost+found: rc = %ld\n",
5807                        lfsck_lfsck2name(lfsck), PTR_ERR(parent));
5808                 RETURN_EXIT;
5809         }
5810
5811         /* It is normal that the /lost+found does not exist for ZFS backend. */
5812         if (!dt_object_exists(parent))
5813                 GOTO(out, rc = 0);
5814
5815         if (unlikely(!dt_try_as_dir(env, parent)))
5816                 GOTO(out, rc = -ENOTDIR);
5817
5818         CDEBUG(D_LFSCK, "%s: start to scan backend /lost+found\n",
5819                lfsck_lfsck2name(lfsck));
5820
5821         com->lc_new_scanned = 0;
5822         iops = &parent->do_index_ops->dio_it;
5823         di = iops->init(env, parent, LUDA_64BITHASH | LUDA_TYPE);
5824         if (IS_ERR(di))
5825                 GOTO(out, rc = PTR_ERR(di));
5826
5827         rc = iops->load(env, di, 0);
5828         if (rc == 0)
5829                 rc = iops->next(env, di);
5830         else if (rc > 0)
5831                 rc = 0;
5832
5833         while (rc == 0) {
5834                 if (CFS_FAIL_TIMEOUT(OBD_FAIL_LFSCK_DELAY3, cfs_fail_val) &&
5835                     unlikely(!thread_is_running(thread)))
5836                         break;
5837
5838                 rc = iops->rec(env, di, (struct dt_rec *)ent,
5839                                LUDA_64BITHASH | LUDA_TYPE);
5840                 if (rc == 0)
5841                         rc = lfsck_unpack_ent(ent, &cookie, &type);
5842
5843                 if (unlikely(rc != 0)) {
5844                         CDEBUG(D_LFSCK, "%s: fail to iterate backend "
5845                                "/lost+found: rc = %d\n",
5846                                lfsck_lfsck2name(lfsck), rc);
5847
5848                         goto skip;
5849                 }
5850
5851                 /* skip dot and dotdot entries */
5852                 if (name_is_dot_or_dotdot(ent->lde_name, ent->lde_namelen))
5853                         goto next;
5854
5855                 if (!fid_seq_in_fldb(fid_seq(&ent->lde_fid)))
5856                         goto skip;
5857
5858                 if (fid_is_norm(&ent->lde_fid)) {
5859                         fld_range_set_mdt(range);
5860                         rc = fld_local_lookup(env, ss->ss_server_fld,
5861                                               fid_seq(&ent->lde_fid), range);
5862                         if (rc != 0)
5863                                 goto skip;
5864                 } else if (idx != 0) {
5865                         /* If the returned FID is IGIF, then there are three
5866                          * possible cases:
5867                          *
5868                          * 1) The object is upgraded from old Lustre-1.8 with
5869                          *    IGIF assigned to such object.
5870                          * 2) The object is a backend local object and is
5871                          *    invisible to client.
5872                          * 3) The object lost its LMV EA, and since there is
5873                          *    no FID-in-dirent for the orphan in the backend
5874                          *    /lost+found directory, then the low layer will
5875                          *    return IGIF for such object.
5876                          *
5877                          * For MDTx (x != 0), it is either case 2) or case 3),
5878                          * but from the LFSCK view, they are indistinguishable.
5879                          * To be safe, the LFSCK will keep it there and report
5880                          * some message, then the adminstrator can handle that
5881                          * furtherly.
5882                          *
5883                          * For MDT0, it is more possible the case 1). The LFSCK
5884                          * will handle the orphan as an upgraded object. */
5885                         CDEBUG(D_LFSCK, "%s: the orphan %.*s with IGIF "DFID
5886                                "in the backend /lost+found on the MDT %04x, "
5887                                "to be safe, skip it.\n",
5888                                lfsck_lfsck2name(lfsck), ent->lde_namelen,
5889                                ent->lde_name, PFID(&ent->lde_fid), idx);
5890                         goto skip;
5891                 }
5892
5893                 rc = lfsck_namespace_scan_local_lpf_one(env, com, parent, ent);
5894
5895 skip:
5896                 down_write(&com->lc_sem);
5897                 com->lc_new_scanned++;
5898                 ns->ln_local_lpf_scanned++;
5899                 if (rc > 0)
5900                         ns->ln_local_lpf_moved++;
5901                 else if (rc == 0)
5902                         ns->ln_local_lpf_skipped++;
5903                 else
5904                         ns->ln_local_lpf_failed++;
5905                 up_write(&com->lc_sem);
5906
5907                 if (rc < 0 && bk->lb_param & LPF_FAILOUT)
5908                         break;
5909
5910 next:
5911                 lfsck_control_speed_by_self(com);
5912                 if (unlikely(!thread_is_running(thread))) {
5913                         rc = 0;
5914                         break;
5915                 }
5916
5917                 rc = iops->next(env, di);
5918         }
5919
5920         iops->put(env, di);
5921         iops->fini(env, di);
5922
5923         EXIT;
5924
5925 out:
5926         CDEBUG(D_LFSCK, "%s: stop to scan backend /lost+found: rc = %d\n",
5927                lfsck_lfsck2name(lfsck), rc);
5928
5929         lfsck_object_put(env, parent);
5930 }
5931
5932 /**
5933  * Rescan the striped directory after the master LMV EA reset.
5934  *
5935  * Sometimes, the master LMV EA of the striped directory maybe lost, so when
5936  * the namespace LFSCK engine scan the striped directory for the first time,
5937  * it will be regarded as a normal directory. As the LFSCK processing, some
5938  * other LFSCK instance on other MDT will find the shard of this striped dir,
5939  * and find that the master MDT-object of the striped directory lost its LMV
5940  * EA, then such remote LFSCK instance will regenerate the master LMV EA and
5941  * notify the LFSCK instance on this MDT to rescan the striped directory.
5942  *
5943  * \param[in] env       pointer to the thread context
5944  * \param[in] com       pointer to the lfsck component
5945  * \param[in] llu       the lfsck_lmv_unit that contains the striped directory
5946  *                      to be rescanned.
5947  *
5948  * \retval              positive number for success
5949  * \retval              0 for LFSCK stopped/paused
5950  * \retval              negative error number on failure
5951  */
5952 static int lfsck_namespace_rescan_striped_dir(const struct lu_env *env,
5953                                               struct lfsck_component *com,
5954                                               struct lfsck_lmv_unit *llu)
5955 {
5956         struct lfsck_thread_info        *info   = lfsck_env_info(env);
5957         struct lfsck_instance           *lfsck  = com->lc_lfsck;
5958         struct lfsck_assistant_data     *lad    = com->lc_data;
5959         struct dt_object                *dir;
5960         const struct dt_it_ops          *iops;
5961         struct dt_it                    *di;
5962         struct lu_dirent                *ent    =
5963                         (struct lu_dirent *)info->lti_key;
5964         struct lfsck_bookmark           *bk     = &lfsck->li_bookmark_ram;
5965         struct ptlrpc_thread            *thread = &lfsck->li_thread;
5966         struct lfsck_assistant_object   *lso    = NULL;
5967         struct lfsck_namespace_req      *lnr;
5968         struct lfsck_assistant_req      *lar;
5969         int                              rc;
5970         __u16                            type;
5971         ENTRY;
5972
5973         LASSERT(list_empty(&lad->lad_req_list));
5974
5975         lfsck->li_lmv = &llu->llu_lmv;
5976         lfsck->li_obj_dir = lfsck_object_get(llu->llu_obj);
5977         rc = lfsck_open_dir(env, lfsck, 0);
5978         if (rc != 0)
5979                 RETURN(rc);
5980
5981         dir = lfsck->li_obj_dir;
5982         di = lfsck->li_di_dir;
5983         iops = &dir->do_index_ops->dio_it;
5984         do {
5985                 rc = iops->rec(env, di, (struct dt_rec *)ent,
5986                                lfsck->li_args_dir);
5987                 if (rc == 0)
5988                         rc = lfsck_unpack_ent(ent, &lfsck->li_cookie_dir,
5989                                               &type);
5990
5991                 if (rc != 0) {
5992                         if (bk->lb_param & LPF_FAILOUT)
5993                                 GOTO(out, rc);
5994
5995                         goto next;
5996                 }
5997
5998                 if (name_is_dot_or_dotdot(ent->lde_name, ent->lde_namelen))
5999                         goto next;
6000
6001                 if (lso == NULL) {
6002                         lso = lfsck_assistant_object_init(env,
6003                                 lfsck_dto2fid(dir), NULL,
6004                                 lfsck->li_pos_current.lp_oit_cookie, true);
6005                         if (IS_ERR(lso)) {
6006                                 if (bk->lb_param & LPF_FAILOUT)
6007                                         GOTO(out, rc = PTR_ERR(lso));
6008
6009                                 lso = NULL;
6010                                 goto next;
6011                         }
6012                 }
6013
6014                 lnr = lfsck_namespace_assistant_req_init(lfsck, lso, ent, type);
6015                 if (IS_ERR(lnr)) {
6016                         if (bk->lb_param & LPF_FAILOUT)
6017                                 GOTO(out, rc = PTR_ERR(lnr));
6018
6019                         goto next;
6020                 }
6021
6022                 lar = &lnr->lnr_lar;
6023                 rc = lfsck_namespace_assistant_handler_p1(env, com, lar);
6024                 lfsck_namespace_assistant_req_fini(env, lar);
6025                 if (rc != 0 && bk->lb_param & LPF_FAILOUT)
6026                         GOTO(out, rc);
6027
6028                 if (unlikely(!thread_is_running(thread)))
6029                         GOTO(out, rc = 0);
6030
6031 next:
6032                 rc = iops->next(env, di);
6033         } while (rc == 0);
6034
6035 out:
6036         if (lso != NULL && !IS_ERR(lso))
6037                 lfsck_assistant_object_put(env, lso);
6038
6039         lfsck_close_dir(env, lfsck, rc);
6040         if (rc <= 0)
6041                 RETURN(rc);
6042
6043         /* The close_dir() may insert a dummy lnr in the lad->lad_req_list. */
6044         if (list_empty(&lad->lad_req_list))
6045                 RETURN(1);
6046
6047         spin_lock(&lad->lad_lock);
6048         lar = list_entry(lad->lad_req_list.next, struct lfsck_assistant_req,
6049                           lar_list);
6050         list_del_init(&lar->lar_list);
6051         spin_unlock(&lad->lad_lock);
6052
6053         rc = lfsck_namespace_assistant_handler_p1(env, com, lar);
6054         lfsck_namespace_assistant_req_fini(env, lar);
6055
6056         RETURN(rc == 0 ? 1 : rc);
6057 }
6058
6059 static int
6060 lfsck_namespace_double_scan_one_trace_file(const struct lu_env *env,
6061                                            struct lfsck_component *com,
6062                                            struct dt_object *obj, bool first)
6063 {
6064         struct lfsck_instance   *lfsck  = com->lc_lfsck;
6065         struct ptlrpc_thread    *thread = &lfsck->li_thread;
6066         struct lfsck_bookmark   *bk     = &lfsck->li_bookmark_ram;
6067         struct lfsck_namespace  *ns     = com->lc_file_ram;
6068         const struct dt_it_ops  *iops   = &obj->do_index_ops->dio_it;
6069         struct dt_object        *target;
6070         struct dt_it            *di;
6071         struct dt_key           *key;
6072         struct lu_fid            fid;
6073         int                      rc;
6074         __u8                     flags  = 0;
6075         ENTRY;
6076
6077         di = iops->init(env, obj, 0);
6078         if (IS_ERR(di))
6079                 RETURN(PTR_ERR(di));
6080
6081         if (first)
6082                 fid_cpu_to_be(&fid, &ns->ln_fid_latest_scanned_phase2);
6083         else
6084                 fid_zero(&fid);
6085         rc = iops->get(env, di, (const struct dt_key *)&fid);
6086         if (rc < 0)
6087                 GOTO(fini, rc);
6088
6089         if (first) {
6090                 /* The start one either has been processed or does not exist,
6091                  * skip it. */
6092                 rc = iops->next(env, di);
6093                 if (rc != 0)
6094                         GOTO(put, rc);
6095         }
6096
6097         do {
6098                 if (CFS_FAIL_TIMEOUT(OBD_FAIL_LFSCK_DELAY3, cfs_fail_val) &&
6099                     unlikely(!thread_is_running(thread)))
6100                         GOTO(put, rc = 0);
6101
6102                 key = iops->key(env, di);
6103                 if (IS_ERR(key)) {
6104                         rc = PTR_ERR(key);
6105                         if (rc == -ENOENT)
6106                                 GOTO(put, rc = 1);
6107
6108                         goto checkpoint;
6109                 }
6110
6111                 fid_be_to_cpu(&fid, (const struct lu_fid *)key);
6112                 if (!fid_is_sane(&fid)) {
6113                         rc = 0;
6114                         goto checkpoint;
6115                 }
6116
6117                 target = lfsck_object_find_bottom(env, lfsck, &fid);
6118                 if (IS_ERR(target)) {
6119                         rc = PTR_ERR(target);
6120                         goto checkpoint;
6121                 }
6122
6123                 if (dt_object_exists(target)) {
6124                         rc = iops->rec(env, di, (struct dt_rec *)&flags, 0);
6125                         if (rc == 0) {
6126                                 rc = lfsck_namespace_double_scan_one(env, com,
6127                                                                 target, flags);
6128                                 if (rc == -ENOENT)
6129                                         rc = 0;
6130                         }
6131                 }
6132
6133                 lfsck_object_put(env, target);
6134
6135 checkpoint:
6136                 down_write(&com->lc_sem);
6137                 com->lc_new_checked++;
6138                 com->lc_new_scanned++;
6139                 if (rc >= 0)
6140                         ns->ln_fid_latest_scanned_phase2 = fid;
6141
6142                 if (rc > 0)
6143                         ns->ln_objs_repaired_phase2++;
6144                 else if (rc < 0)
6145                         ns->ln_objs_failed_phase2++;
6146                 up_write(&com->lc_sem);
6147
6148                 if (rc < 0 && bk->lb_param & LPF_FAILOUT)
6149                         GOTO(put, rc);
6150
6151                 if (unlikely(com->lc_time_next_checkpoint <=
6152                              ktime_get_seconds()) &&
6153                     com->lc_new_checked != 0) {
6154                         down_write(&com->lc_sem);
6155                         ns->ln_run_time_phase2 += ktime_get_seconds() -
6156                                                   com->lc_time_last_checkpoint;
6157                         ns->ln_time_last_checkpoint = ktime_get_real_seconds();
6158                         ns->ln_objs_checked_phase2 += com->lc_new_checked;
6159                         com->lc_new_checked = 0;
6160                         lfsck_namespace_store(env, com);
6161                         up_write(&com->lc_sem);
6162
6163                         com->lc_time_last_checkpoint = ktime_get_seconds();
6164                         com->lc_time_next_checkpoint =
6165                                 com->lc_time_last_checkpoint +
6166                                 LFSCK_CHECKPOINT_INTERVAL;
6167                 }
6168
6169                 lfsck_control_speed_by_self(com);
6170                 if (unlikely(!thread_is_running(thread)))
6171                         GOTO(put, rc = 0);
6172
6173                 rc = iops->next(env, di);
6174         } while (rc == 0);
6175
6176         GOTO(put, rc);
6177
6178 put:
6179         iops->put(env, di);
6180
6181 fini:
6182         iops->fini(env, di);
6183
6184         return rc;
6185 }
6186
6187 static int lfsck_namespace_assistant_handler_p2(const struct lu_env *env,
6188                                                 struct lfsck_component *com)
6189 {
6190         struct lfsck_instance   *lfsck  = com->lc_lfsck;
6191         struct lfsck_namespace  *ns     = com->lc_file_ram;
6192         int                      rc;
6193         int                      i;
6194         ENTRY;
6195
6196         while (!list_empty(&lfsck->li_list_lmv)) {
6197                 struct lfsck_lmv_unit *llu;
6198
6199                 spin_lock(&lfsck->li_lock);
6200                 llu = list_entry(lfsck->li_list_lmv.next,
6201                                  struct lfsck_lmv_unit, llu_link);
6202                 list_del_init(&llu->llu_link);
6203                 spin_unlock(&lfsck->li_lock);
6204
6205                 rc = lfsck_namespace_rescan_striped_dir(env, com, llu);
6206                 if (rc <= 0)
6207                         RETURN(rc);
6208         }
6209
6210         CDEBUG(D_LFSCK, "%s: namespace LFSCK phase2 scan start\n",
6211                lfsck_lfsck2name(lfsck));
6212
6213         lfsck_namespace_scan_local_lpf(env, com);
6214
6215         com->lc_new_checked = 0;
6216         com->lc_new_scanned = 0;
6217         com->lc_time_last_checkpoint = ktime_get_seconds();
6218         com->lc_time_next_checkpoint = com->lc_time_last_checkpoint +
6219                                        LFSCK_CHECKPOINT_INTERVAL;
6220
6221         i = lfsck_sub_trace_file_fid2idx(&ns->ln_fid_latest_scanned_phase2);
6222         rc = lfsck_namespace_double_scan_one_trace_file(env, com,
6223                                 com->lc_sub_trace_objs[i].lsto_obj, true);
6224         while (rc > 0 && ++i < LFSCK_STF_COUNT)
6225                 rc = lfsck_namespace_double_scan_one_trace_file(env, com,
6226                                 com->lc_sub_trace_objs[i].lsto_obj, false);
6227
6228         CDEBUG(D_LFSCK, "%s: namespace LFSCK phase2 scan stop at the No. %d "
6229                "trace file: rc = %d\n", lfsck_lfsck2name(lfsck), i, rc);
6230
6231         RETURN(rc);
6232 }
6233
6234 static void lfsck_namespace_assistant_fill_pos(const struct lu_env *env,
6235                                                struct lfsck_component *com,
6236                                                struct lfsck_position *pos)
6237 {
6238         struct lfsck_assistant_data     *lad = com->lc_data;
6239         struct lfsck_namespace_req      *lnr;
6240
6241         if (((struct lfsck_namespace *)(com->lc_file_ram))->ln_status !=
6242             LS_SCANNING_PHASE1)
6243                 return;
6244
6245         if (list_empty(&lad->lad_req_list))
6246                 return;
6247
6248         lnr = list_entry(lad->lad_req_list.next,
6249                          struct lfsck_namespace_req,
6250                          lnr_lar.lar_list);
6251         pos->lp_oit_cookie = lnr->lnr_lar.lar_parent->lso_oit_cookie;
6252         pos->lp_dir_cookie = lnr->lnr_dir_cookie - 1;
6253         pos->lp_dir_parent = lnr->lnr_lar.lar_parent->lso_fid;
6254 }
6255
6256 static int lfsck_namespace_double_scan_result(const struct lu_env *env,
6257                                               struct lfsck_component *com,
6258                                               int rc)
6259 {
6260         struct lfsck_instance   *lfsck  = com->lc_lfsck;
6261         struct lfsck_namespace  *ns     = com->lc_file_ram;
6262
6263         down_write(&com->lc_sem);
6264         ns->ln_run_time_phase2 += ktime_get_seconds() -
6265                                   com->lc_time_last_checkpoint;
6266         ns->ln_time_last_checkpoint = ktime_get_real_seconds();
6267         ns->ln_objs_checked_phase2 += com->lc_new_checked;
6268         com->lc_new_checked = 0;
6269
6270         if (rc > 0) {
6271                 if (ns->ln_flags & LF_INCOMPLETE)
6272                         ns->ln_status = LS_PARTIAL;
6273                 else
6274                         ns->ln_status = LS_COMPLETED;
6275                 ns->ln_flags &= ~LF_SCANNED_ONCE;
6276                 if (!(lfsck->li_bookmark_ram.lb_param & LPF_DRYRUN))
6277                         ns->ln_flags &= ~LF_INCONSISTENT;
6278                 ns->ln_time_last_complete = ns->ln_time_last_checkpoint;
6279                 ns->ln_success_count++;
6280         } else if (rc == 0) {
6281                 if (lfsck->li_status != 0)
6282                         ns->ln_status = lfsck->li_status;
6283                 else
6284                         ns->ln_status = LS_STOPPED;
6285         } else {
6286                 ns->ln_status = LS_FAILED;
6287         }
6288
6289         rc = lfsck_namespace_store(env, com);
6290         up_write(&com->lc_sem);
6291
6292         return rc;
6293 }
6294
6295 static int
6296 lfsck_namespace_assistant_sync_failures_interpret(const struct lu_env *env,
6297                                                   struct ptlrpc_request *req,
6298                                                   void *args, int rc)
6299 {
6300         if (rc == 0) {
6301                 struct lfsck_async_interpret_args *laia = args;
6302                 struct lfsck_tgt_desc             *ltd  = laia->laia_ltd;
6303
6304                 ltd->ltd_synced_failures = 1;
6305         }
6306
6307         return 0;
6308 }
6309
6310 /**
6311  * Notify remote LFSCK instances about former failures.
6312  *
6313  * The local LFSCK instance has recorded which MDTs have ever failed to respond
6314  * some LFSCK verification requests (maybe because of network issues or the MDT
6315  * itself trouble). During the respond gap the MDT may missed some name entries
6316  * verification, then the MDT cannot know whether related MDT-objects have been
6317  * referenced by related name entries or not, then in the second-stage scanning,
6318  * these MDT-objects will be regarded as orphan, if the MDT-object contains bad
6319  * linkEA for back reference, then it will misguide the LFSCK to generate wrong
6320  * name entry for repairing the orphan.
6321  *
6322  * To avoid above trouble, when layout LFSCK finishes the first-stage scanning,
6323  * it will scan the bitmap for the ever failed MDTs, and notify them that they
6324  * have ever missed some name entries verification and should skip the handling
6325  * for orphan MDT-objects.
6326  *
6327  * \param[in] env       pointer to the thread context
6328  * \param[in] com       pointer to the lfsck component
6329  * \param[in] lr        pointer to the lfsck request
6330  */
6331 static void lfsck_namespace_assistant_sync_failures(const struct lu_env *env,
6332                                                     struct lfsck_component *com,
6333                                                     struct lfsck_request *lr)
6334 {
6335         struct lfsck_async_interpret_args *laia  =
6336                                 &lfsck_env_info(env)->lti_laia2;
6337         struct lfsck_assistant_data       *lad   = com->lc_data;
6338         struct lfsck_namespace            *ns    = com->lc_file_ram;
6339         struct lfsck_instance             *lfsck = com->lc_lfsck;
6340         struct lfsck_tgt_descs            *ltds  = &lfsck->li_mdt_descs;
6341         struct lfsck_tgt_desc             *ltd;
6342         struct ptlrpc_request_set         *set;
6343         __u32                              idx;
6344         int                                rc    = 0;
6345         ENTRY;
6346
6347         if (!lad->lad_incomplete)
6348                 RETURN_EXIT;
6349
6350         set = ptlrpc_prep_set();
6351         if (set == NULL)
6352                 GOTO(out, rc = -ENOMEM);
6353
6354         lr->lr_flags2 = ns->ln_flags | LF_INCOMPLETE;
6355         memset(laia, 0, sizeof(*laia));
6356         lad->lad_touch_gen++;
6357
6358         down_read(&ltds->ltd_rw_sem);
6359         cfs_foreach_bit(lad->lad_bitmap, idx) {
6360                 ltd = lfsck_ltd2tgt(ltds, idx);
6361                 if (unlikely(!ltd))
6362                         continue;
6363
6364                 laia->laia_ltd = ltd;
6365                 rc = lfsck_async_request(env, ltd->ltd_exp, lr, set,
6366                         lfsck_namespace_assistant_sync_failures_interpret,
6367                         laia, LFSCK_NOTIFY);
6368                 if (rc != 0)
6369                         CDEBUG(D_LFSCK, "%s: namespace LFSCK assistant fail "
6370                                "to sync failure with MDT %x: rc = %d\n",
6371                                lfsck_lfsck2name(lfsck), ltd->ltd_index, rc);
6372         }
6373         up_read(&ltds->ltd_rw_sem);
6374
6375         rc = ptlrpc_set_wait(set);
6376         ptlrpc_set_destroy(set);
6377
6378         GOTO(out, rc);
6379
6380 out:
6381         if (rc != 0)
6382                 CDEBUG(D_LFSCK, "%s: namespace LFSCK assistant fail "
6383                        "to sync failure with MDTs, and related MDTs "
6384                        "may handle orphan improperly: rc = %d\n",
6385                        lfsck_lfsck2name(lfsck), rc);
6386
6387         EXIT;
6388 }
6389
6390 struct lfsck_assistant_operations lfsck_namespace_assistant_ops = {
6391         .la_handler_p1          = lfsck_namespace_assistant_handler_p1,
6392         .la_handler_p2          = lfsck_namespace_assistant_handler_p2,
6393         .la_fill_pos            = lfsck_namespace_assistant_fill_pos,
6394         .la_double_scan_result  = lfsck_namespace_double_scan_result,
6395         .la_req_fini            = lfsck_namespace_assistant_req_fini,
6396         .la_sync_failures       = lfsck_namespace_assistant_sync_failures,
6397 };
6398
6399 /**
6400  * Verify the specified linkEA entry for the given directory object.
6401  * If the object has no such linkEA entry or it has more other linkEA
6402  * entries, then re-generate the linkEA with the given information.
6403  *
6404  * \param[in] env       pointer to the thread context
6405  * \param[in] obj       pointer to the dt_object to be handled
6406  * \param[in] cname     the name for the child in the parent directory
6407  * \param[in] pfid      the parent directory's FID for the linkEA
6408  *
6409  * \retval              0 for success
6410  * \retval              negative error number on failure
6411  */
6412 int lfsck_verify_linkea(const struct lu_env *env, struct dt_object *obj,
6413                         const struct lu_name *cname, const struct lu_fid *pfid)
6414 {
6415         struct dt_device        *dev    = lfsck_obj2dev(obj);
6416         struct linkea_data       ldata  = { NULL };
6417         struct lu_buf            linkea_buf;
6418         struct thandle          *th;
6419         int                      rc;
6420         int                      fl     = LU_XATTR_CREATE;
6421         bool                     dirty  = false;
6422         ENTRY;
6423
6424         LASSERT(S_ISDIR(lfsck_object_type(obj)));
6425
6426         rc = lfsck_links_read_with_rec(env, obj, &ldata);
6427         if (rc == -ENODATA) {
6428                 dirty = true;
6429         } else if (rc == 0) {
6430                 fl = LU_XATTR_REPLACE;
6431                 if (ldata.ld_leh->leh_reccount != 1) {
6432                         dirty = true;
6433                 } else {
6434                         rc = linkea_links_find(&ldata, cname, pfid);
6435                         if (rc != 0)
6436                                 dirty = true;
6437                 }
6438         }
6439
6440         if (!dirty)
6441                 RETURN(rc);
6442
6443         rc = linkea_links_new(&ldata, &lfsck_env_info(env)->lti_linkea_buf,
6444                               cname, pfid);
6445         if (rc != 0)
6446                 RETURN(rc);
6447
6448         lfsck_buf_init(&linkea_buf, ldata.ld_buf->lb_buf,
6449                        ldata.ld_leh->leh_len);
6450         th = dt_trans_create(env, dev);
6451         if (IS_ERR(th))
6452                 RETURN(PTR_ERR(th));
6453
6454         rc = dt_declare_xattr_set(env, obj, &linkea_buf,
6455                                   XATTR_NAME_LINK, fl, th);
6456         if (rc != 0)
6457                 GOTO(stop, rc);
6458
6459         rc = dt_trans_start_local(env, dev, th);
6460         if (rc != 0)
6461                 GOTO(stop, rc);
6462
6463         dt_write_lock(env, obj, 0);
6464         rc = dt_xattr_set(env, obj, &linkea_buf,
6465                           XATTR_NAME_LINK, fl, th);
6466         dt_write_unlock(env, obj);
6467
6468         GOTO(stop, rc);
6469
6470 stop:
6471         dt_trans_stop(env, dev, th);
6472         return rc;
6473 }
6474
6475 /**
6476  * Get the name and parent directory's FID from the first linkEA entry.
6477  *
6478  * \param[in] env       pointer to the thread context
6479  * \param[in] obj       pointer to the object which get linkEA from
6480  * \param[out] name     pointer to the buffer to hold the name
6481  *                      in the first linkEA entry
6482  * \param[out] pfid     pointer to the buffer to hold the parent
6483  *                      directory's FID in the first linkEA entry
6484  *
6485  * \retval              0 for success
6486  * \retval              negative error number on failure
6487  */
6488 int lfsck_links_get_first(const struct lu_env *env, struct dt_object *obj,
6489                           char *name, struct lu_fid *pfid)
6490 {
6491         struct lu_name           *cname = &lfsck_env_info(env)->lti_name;
6492         struct linkea_data        ldata = { NULL };
6493         int                       rc;
6494
6495         rc = lfsck_links_read_with_rec(env, obj, &ldata);
6496         if (rc)
6497                 return rc;
6498
6499         linkea_first_entry(&ldata);
6500         linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen, cname, pfid);
6501         /* To guarantee the 'name' is terminated with '0'. */
6502         memcpy(name, cname->ln_name, cname->ln_namelen);
6503         name[cname->ln_namelen] = 0;
6504
6505         return 0;
6506 }
6507
6508 /**
6509  * Update the object's name entry with the given FID.
6510  *
6511  * \param[in] env       pointer to the thread context
6512  * \param[in] lfsck     pointer to the lfsck instance
6513  * \param[in] dir       pointer to the directory that holds
6514  *                      the name entry
6515  * \param[in] name      the name for the entry to be updated
6516  * \param[in] fid       the new FID for the name entry referenced
6517  * \param[in] type      the type for the name entry to be updated
6518  *
6519  * \retval              0 for success
6520  * \retval              negative error number on failure
6521  */
6522 int lfsck_update_name_entry(const struct lu_env *env,
6523                             struct lfsck_instance *lfsck,
6524                             struct dt_object *dir, const char *name,
6525                             const struct lu_fid *fid, __u32 type)
6526 {
6527         struct lfsck_thread_info *info   = lfsck_env_info(env);
6528         struct dt_insert_rec     *rec    = &info->lti_dt_rec;
6529         struct lfsck_lock_handle *llh    = &info->lti_llh;
6530         struct dt_device         *dev    = lfsck_obj2dev(dir);
6531         struct thandle           *th;
6532         int                       rc;
6533         bool                      exists = true;
6534         ENTRY;
6535
6536         rc = lfsck_lock(env, lfsck, dir, name, llh,
6537                         MDS_INODELOCK_UPDATE, LCK_PW);
6538         if (rc != 0)
6539                 RETURN(rc);
6540
6541         th = dt_trans_create(env, dev);
6542         if (IS_ERR(th))
6543                 GOTO(unlock, rc = PTR_ERR(th));
6544
6545         rc = dt_declare_delete(env, dir, (const struct dt_key *)name, th);
6546         if (rc != 0)
6547                 GOTO(stop, rc);
6548
6549         rec->rec_type = type;
6550         rec->rec_fid = fid;
6551         rc = dt_declare_insert(env, dir, (const struct dt_rec *)rec,
6552                                (const struct dt_key *)name, th);
6553         if (rc != 0)
6554                 GOTO(stop, rc);
6555
6556         rc = dt_declare_ref_add(env, dir, th);
6557         if (rc != 0)
6558                 GOTO(stop, rc);
6559
6560         rc = dt_trans_start_local(env, dev, th);
6561         if (rc != 0)
6562                 GOTO(stop, rc);
6563
6564         rc = dt_delete(env, dir, (const struct dt_key *)name, th);
6565         if (rc == -ENOENT) {
6566                 exists = false;
6567                 rc = 0;
6568         }
6569
6570         if (rc != 0)
6571                 GOTO(stop, rc);
6572
6573         rc = dt_insert(env, dir, (const struct dt_rec *)rec,
6574                        (const struct dt_key *)name, th, 1);
6575         if (rc == 0 && S_ISDIR(type) && !exists) {
6576                 dt_write_lock(env, dir, 0);
6577                 rc = dt_ref_add(env, dir, th);
6578                 dt_write_unlock(env, dir);
6579         }
6580
6581         GOTO(stop, rc);
6582
6583 stop:
6584         dt_trans_stop(env, dev, th);
6585
6586 unlock:
6587         lfsck_unlock(llh);
6588         CDEBUG(D_LFSCK, "%s: update name entry "DFID"/%s with the FID "DFID
6589                " and the type %o: rc = %d\n", lfsck_lfsck2name(lfsck),
6590                PFID(lfsck_dto2fid(dir)), name, PFID(fid), type, rc);
6591
6592         return rc;
6593 }
6594
6595 int lfsck_namespace_setup(const struct lu_env *env,
6596                           struct lfsck_instance *lfsck)
6597 {
6598         struct lfsck_component  *com;
6599         struct lfsck_namespace  *ns;
6600         struct dt_object        *root = NULL;
6601         struct dt_object        *obj;
6602         int                      i;
6603         int                      rc;
6604         ENTRY;
6605
6606         LASSERT(lfsck->li_master);
6607
6608         OBD_ALLOC_PTR(com);
6609         if (com == NULL)
6610                 RETURN(-ENOMEM);
6611
6612         INIT_LIST_HEAD(&com->lc_link);
6613         INIT_LIST_HEAD(&com->lc_link_dir);
6614         init_rwsem(&com->lc_sem);
6615         atomic_set(&com->lc_ref, 1);
6616         com->lc_lfsck = lfsck;
6617         com->lc_type = LFSCK_TYPE_NAMESPACE;
6618         com->lc_ops = &lfsck_namespace_ops;
6619         com->lc_data = lfsck_assistant_data_init(
6620                         &lfsck_namespace_assistant_ops,
6621                         LFSCK_NAMESPACE);
6622         if (com->lc_data == NULL)
6623                 GOTO(out, rc = -ENOMEM);
6624
6625         com->lc_file_size = sizeof(struct lfsck_namespace);
6626         OBD_ALLOC(com->lc_file_ram, com->lc_file_size);
6627         if (com->lc_file_ram == NULL)
6628                 GOTO(out, rc = -ENOMEM);
6629
6630         OBD_ALLOC(com->lc_file_disk, com->lc_file_size);
6631         if (com->lc_file_disk == NULL)
6632                 GOTO(out, rc = -ENOMEM);
6633
6634         for (i = 0; i < LFSCK_STF_COUNT; i++)
6635                 mutex_init(&com->lc_sub_trace_objs[i].lsto_mutex);
6636
6637         root = dt_locate(env, lfsck->li_bottom, &lfsck->li_local_root_fid);
6638         if (IS_ERR(root))
6639                 GOTO(out, rc = PTR_ERR(root));
6640
6641         if (unlikely(!dt_try_as_dir(env, root)))
6642                 GOTO(out, rc = -ENOTDIR);
6643
6644         obj = local_index_find_or_create(env, lfsck->li_los, root,
6645                                          LFSCK_NAMESPACE,
6646                                          S_IFREG | S_IRUGO | S_IWUSR,
6647                                          &dt_lfsck_namespace_features);
6648         if (IS_ERR(obj))
6649                 GOTO(out, rc = PTR_ERR(obj));
6650
6651         com->lc_obj = obj;
6652         rc = lfsck_namespace_load(env, com);
6653         if (rc == -ENODATA)
6654                 rc = lfsck_namespace_init(env, com);
6655         else if (rc < 0)
6656                 rc = lfsck_namespace_reset(env, com, true);
6657         else
6658                 rc = lfsck_load_sub_trace_files(env, com,
6659                         &dt_lfsck_namespace_features, LFSCK_NAMESPACE, false);
6660         if (rc != 0)
6661                 GOTO(out, rc);
6662
6663         ns = com->lc_file_ram;
6664         switch (ns->ln_status) {
6665         case LS_INIT:
6666         case LS_COMPLETED:
6667         case LS_FAILED:
6668         case LS_STOPPED:
6669                 spin_lock(&lfsck->li_lock);
6670                 list_add_tail(&com->lc_link, &lfsck->li_list_idle);
6671                 spin_unlock(&lfsck->li_lock);
6672                 break;
6673         default:
6674                 CERROR("%s: unknown lfsck_namespace status %d\n",
6675                        lfsck_lfsck2name(lfsck), ns->ln_status);
6676                 /* fall through */
6677         case LS_SCANNING_PHASE1:
6678         case LS_SCANNING_PHASE2:
6679                 /* No need to store the status to disk right now.
6680                  * If the system crashed before the status stored,
6681                  * it will be loaded back when next time. */
6682                 ns->ln_status = LS_CRASHED;
6683                 /* fall through */
6684         case LS_PAUSED:
6685         case LS_CRASHED:
6686                 spin_lock(&lfsck->li_lock);
6687                 list_add_tail(&com->lc_link, &lfsck->li_list_scan);
6688                 list_add_tail(&com->lc_link_dir, &lfsck->li_list_dir);
6689                 spin_unlock(&lfsck->li_lock);
6690                 break;
6691         }
6692
6693         GOTO(out, rc = 0);
6694
6695 out:
6696         if (root != NULL && !IS_ERR(root))
6697                 lfsck_object_put(env, root);
6698         if (rc != 0) {
6699                 lfsck_component_cleanup(env, com);
6700                 CERROR("%s: fail to init namespace LFSCK component: rc = %d\n",
6701                        lfsck_lfsck2name(lfsck), rc);
6702         }
6703         return rc;
6704 }