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