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