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