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