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