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