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