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