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