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