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