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