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