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