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