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