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