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