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