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