Whamcloud - gitweb
b938046a857ee0c3c53e3ca4d77a87d8fcc733a1
[fs/lustre-release.git] / lustre / lfsck / lfsck_namespace.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License version 2 for more details.  A copy is
14  * included in the COPYING file that accompanied this code.
15
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2013, 2015, Intel Corporation.
24  */
25 /*
26  * lustre/lfsck/lfsck_namespace.c
27  *
28  * Author: Fan, Yong <fan.yong@intel.com>
29  */
30
31 #define DEBUG_SUBSYSTEM S_LFSCK
32
33 #include <lustre/lustre_idl.h>
34 #include <lu_object.h>
35 #include <dt_object.h>
36 #include <md_object.h>
37 #include <lustre_fid.h>
38 #include <lustre_lib.h>
39 #include <lustre_net.h>
40 #include <lustre/lustre_user.h>
41
42 #include "lfsck_internal.h"
43
44 #define LFSCK_NAMESPACE_MAGIC_V1        0xA0629D03
45 #define LFSCK_NAMESPACE_MAGIC_V2        0xA0621A0B
46
47 /* For Lustre-2.x (x <= 6), the namespace LFSCK used LFSCK_NAMESPACE_MAGIC_V1
48  * as the trace file magic. When downgrade to such old release, the old LFSCK
49  * will not recognize the new LFSCK_NAMESPACE_MAGIC_V2 in the new trace file,
50  * then it will reset the whole LFSCK, and will not cause start failure. The
51  * similar case will happen when upgrade from such old release. */
52 #define LFSCK_NAMESPACE_MAGIC           LFSCK_NAMESPACE_MAGIC_V2
53
54 enum lfsck_nameentry_check {
55         LFSCK_NAMEENTRY_DEAD            = 1, /* The object has been unlinked. */
56         LFSCK_NAMEENTRY_REMOVED         = 2, /* The entry has been removed. */
57         LFSCK_NAMEENTRY_RECREATED       = 3, /* The entry has been recreated. */
58 };
59
60 static struct lfsck_namespace_req *
61 lfsck_namespace_assistant_req_init(struct lfsck_instance *lfsck,
62                                    struct lfsck_assistant_object *lso,
63                                    struct lu_dirent *ent, __u16 type)
64 {
65         struct lfsck_namespace_req *lnr;
66         int                         size;
67
68         size = sizeof(*lnr) + (ent->lde_namelen & ~3) + 4;
69         OBD_ALLOC(lnr, size);
70         if (lnr == NULL)
71                 return ERR_PTR(-ENOMEM);
72
73         INIT_LIST_HEAD(&lnr->lnr_lar.lar_list);
74         lnr->lnr_lar.lar_parent = lfsck_assistant_object_get(lso);
75         lnr->lnr_lmv = lfsck_lmv_get(lfsck->li_lmv);
76         lnr->lnr_fid = ent->lde_fid;
77         lnr->lnr_dir_cookie = ent->lde_hash;
78         lnr->lnr_attr = ent->lde_attrs;
79         lnr->lnr_size = size;
80         lnr->lnr_type = type;
81         lnr->lnr_namelen = ent->lde_namelen;
82         memcpy(lnr->lnr_name, ent->lde_name, ent->lde_namelen);
83
84         return lnr;
85 }
86
87 static void lfsck_namespace_assistant_req_fini(const struct lu_env *env,
88                                                struct lfsck_assistant_req *lar)
89 {
90         struct lfsck_namespace_req *lnr =
91                         container_of0(lar, struct lfsck_namespace_req, lnr_lar);
92
93         if (lnr->lnr_lmv != NULL)
94                 lfsck_lmv_put(env, lnr->lnr_lmv);
95
96         lfsck_assistant_object_put(env, lar->lar_parent);
97         OBD_FREE(lnr, lnr->lnr_size);
98 }
99
100 static void lfsck_namespace_le_to_cpu(struct lfsck_namespace *dst,
101                                       struct lfsck_namespace *src)
102 {
103         dst->ln_magic = le32_to_cpu(src->ln_magic);
104         dst->ln_status = le32_to_cpu(src->ln_status);
105         dst->ln_flags = le32_to_cpu(src->ln_flags);
106         dst->ln_success_count = le32_to_cpu(src->ln_success_count);
107         dst->ln_run_time_phase1 = le32_to_cpu(src->ln_run_time_phase1);
108         dst->ln_run_time_phase2 = le32_to_cpu(src->ln_run_time_phase2);
109         dst->ln_time_last_complete = le64_to_cpu(src->ln_time_last_complete);
110         dst->ln_time_latest_start = le64_to_cpu(src->ln_time_latest_start);
111         dst->ln_time_last_checkpoint =
112                                 le64_to_cpu(src->ln_time_last_checkpoint);
113         lfsck_position_le_to_cpu(&dst->ln_pos_latest_start,
114                                  &src->ln_pos_latest_start);
115         lfsck_position_le_to_cpu(&dst->ln_pos_last_checkpoint,
116                                  &src->ln_pos_last_checkpoint);
117         lfsck_position_le_to_cpu(&dst->ln_pos_first_inconsistent,
118                                  &src->ln_pos_first_inconsistent);
119         dst->ln_items_checked = le64_to_cpu(src->ln_items_checked);
120         dst->ln_items_repaired = le64_to_cpu(src->ln_items_repaired);
121         dst->ln_items_failed = le64_to_cpu(src->ln_items_failed);
122         dst->ln_dirs_checked = le64_to_cpu(src->ln_dirs_checked);
123         dst->ln_objs_checked_phase2 = le64_to_cpu(src->ln_objs_checked_phase2);
124         dst->ln_objs_repaired_phase2 =
125                                 le64_to_cpu(src->ln_objs_repaired_phase2);
126         dst->ln_objs_failed_phase2 = le64_to_cpu(src->ln_objs_failed_phase2);
127         dst->ln_objs_nlink_repaired = le64_to_cpu(src->ln_objs_nlink_repaired);
128         fid_le_to_cpu(&dst->ln_fid_latest_scanned_phase2,
129                       &src->ln_fid_latest_scanned_phase2);
130         dst->ln_dirent_repaired = le64_to_cpu(src->ln_dirent_repaired);
131         dst->ln_linkea_repaired = le64_to_cpu(src->ln_linkea_repaired);
132         dst->ln_mul_linked_checked = le64_to_cpu(src->ln_mul_linked_checked);
133         dst->ln_mul_linked_repaired = le64_to_cpu(src->ln_mul_linked_repaired);
134         dst->ln_unknown_inconsistency =
135                                 le64_to_cpu(src->ln_unknown_inconsistency);
136         dst->ln_unmatched_pairs_repaired =
137                                 le64_to_cpu(src->ln_unmatched_pairs_repaired);
138         dst->ln_dangling_repaired = le64_to_cpu(src->ln_dangling_repaired);
139         dst->ln_mul_ref_repaired = le64_to_cpu(src->ln_mul_ref_repaired);
140         dst->ln_bad_type_repaired = le64_to_cpu(src->ln_bad_type_repaired);
141         dst->ln_lost_dirent_repaired =
142                                 le64_to_cpu(src->ln_lost_dirent_repaired);
143         dst->ln_striped_dirs_scanned =
144                                 le64_to_cpu(src->ln_striped_dirs_scanned);
145         dst->ln_striped_dirs_repaired =
146                                 le64_to_cpu(src->ln_striped_dirs_repaired);
147         dst->ln_striped_dirs_failed =
148                                 le64_to_cpu(src->ln_striped_dirs_failed);
149         dst->ln_striped_dirs_disabled =
150                                 le64_to_cpu(src->ln_striped_dirs_disabled);
151         dst->ln_striped_dirs_skipped =
152                                 le64_to_cpu(src->ln_striped_dirs_skipped);
153         dst->ln_striped_shards_scanned =
154                                 le64_to_cpu(src->ln_striped_shards_scanned);
155         dst->ln_striped_shards_repaired =
156                                 le64_to_cpu(src->ln_striped_shards_repaired);
157         dst->ln_striped_shards_failed =
158                                 le64_to_cpu(src->ln_striped_shards_failed);
159         dst->ln_striped_shards_skipped =
160                                 le64_to_cpu(src->ln_striped_shards_skipped);
161         dst->ln_name_hash_repaired = le64_to_cpu(src->ln_name_hash_repaired);
162         dst->ln_local_lpf_scanned = le64_to_cpu(src->ln_local_lpf_scanned);
163         dst->ln_local_lpf_moved = le64_to_cpu(src->ln_local_lpf_moved);
164         dst->ln_local_lpf_skipped = le64_to_cpu(src->ln_local_lpf_skipped);
165         dst->ln_local_lpf_failed = le64_to_cpu(src->ln_local_lpf_failed);
166         dst->ln_bitmap_size = le32_to_cpu(src->ln_bitmap_size);
167 }
168
169 static void lfsck_namespace_cpu_to_le(struct lfsck_namespace *dst,
170                                       struct lfsck_namespace *src)
171 {
172         dst->ln_magic = cpu_to_le32(src->ln_magic);
173         dst->ln_status = cpu_to_le32(src->ln_status);
174         dst->ln_flags = cpu_to_le32(src->ln_flags);
175         dst->ln_success_count = cpu_to_le32(src->ln_success_count);
176         dst->ln_run_time_phase1 = cpu_to_le32(src->ln_run_time_phase1);
177         dst->ln_run_time_phase2 = cpu_to_le32(src->ln_run_time_phase2);
178         dst->ln_time_last_complete = cpu_to_le64(src->ln_time_last_complete);
179         dst->ln_time_latest_start = cpu_to_le64(src->ln_time_latest_start);
180         dst->ln_time_last_checkpoint =
181                                 cpu_to_le64(src->ln_time_last_checkpoint);
182         lfsck_position_cpu_to_le(&dst->ln_pos_latest_start,
183                                  &src->ln_pos_latest_start);
184         lfsck_position_cpu_to_le(&dst->ln_pos_last_checkpoint,
185                                  &src->ln_pos_last_checkpoint);
186         lfsck_position_cpu_to_le(&dst->ln_pos_first_inconsistent,
187                                  &src->ln_pos_first_inconsistent);
188         dst->ln_items_checked = cpu_to_le64(src->ln_items_checked);
189         dst->ln_items_repaired = cpu_to_le64(src->ln_items_repaired);
190         dst->ln_items_failed = cpu_to_le64(src->ln_items_failed);
191         dst->ln_dirs_checked = cpu_to_le64(src->ln_dirs_checked);
192         dst->ln_objs_checked_phase2 = cpu_to_le64(src->ln_objs_checked_phase2);
193         dst->ln_objs_repaired_phase2 =
194                                 cpu_to_le64(src->ln_objs_repaired_phase2);
195         dst->ln_objs_failed_phase2 = cpu_to_le64(src->ln_objs_failed_phase2);
196         dst->ln_objs_nlink_repaired = cpu_to_le64(src->ln_objs_nlink_repaired);
197         fid_cpu_to_le(&dst->ln_fid_latest_scanned_phase2,
198                       &src->ln_fid_latest_scanned_phase2);
199         dst->ln_dirent_repaired = cpu_to_le64(src->ln_dirent_repaired);
200         dst->ln_linkea_repaired = cpu_to_le64(src->ln_linkea_repaired);
201         dst->ln_mul_linked_checked = cpu_to_le64(src->ln_mul_linked_checked);
202         dst->ln_mul_linked_repaired = cpu_to_le64(src->ln_mul_linked_repaired);
203         dst->ln_unknown_inconsistency =
204                                 cpu_to_le64(src->ln_unknown_inconsistency);
205         dst->ln_unmatched_pairs_repaired =
206                                 cpu_to_le64(src->ln_unmatched_pairs_repaired);
207         dst->ln_dangling_repaired = cpu_to_le64(src->ln_dangling_repaired);
208         dst->ln_mul_ref_repaired = cpu_to_le64(src->ln_mul_ref_repaired);
209         dst->ln_bad_type_repaired = cpu_to_le64(src->ln_bad_type_repaired);
210         dst->ln_lost_dirent_repaired =
211                                 cpu_to_le64(src->ln_lost_dirent_repaired);
212         dst->ln_striped_dirs_scanned =
213                                 cpu_to_le64(src->ln_striped_dirs_scanned);
214         dst->ln_striped_dirs_repaired =
215                                 cpu_to_le64(src->ln_striped_dirs_repaired);
216         dst->ln_striped_dirs_failed =
217                                 cpu_to_le64(src->ln_striped_dirs_failed);
218         dst->ln_striped_dirs_disabled =
219                                 cpu_to_le64(src->ln_striped_dirs_disabled);
220         dst->ln_striped_dirs_skipped =
221                                 cpu_to_le64(src->ln_striped_dirs_skipped);
222         dst->ln_striped_shards_scanned =
223                                 cpu_to_le64(src->ln_striped_shards_scanned);
224         dst->ln_striped_shards_repaired =
225                                 cpu_to_le64(src->ln_striped_shards_repaired);
226         dst->ln_striped_shards_failed =
227                                 cpu_to_le64(src->ln_striped_shards_failed);
228         dst->ln_striped_shards_skipped =
229                                 cpu_to_le64(src->ln_striped_shards_skipped);
230         dst->ln_name_hash_repaired = cpu_to_le64(src->ln_name_hash_repaired);
231         dst->ln_local_lpf_scanned = cpu_to_le64(src->ln_local_lpf_scanned);
232         dst->ln_local_lpf_moved = cpu_to_le64(src->ln_local_lpf_moved);
233         dst->ln_local_lpf_skipped = cpu_to_le64(src->ln_local_lpf_skipped);
234         dst->ln_local_lpf_failed = cpu_to_le64(src->ln_local_lpf_failed);
235         dst->ln_bitmap_size = cpu_to_le32(src->ln_bitmap_size);
236 }
237
238 static void lfsck_namespace_record_failure(const struct lu_env *env,
239                                            struct lfsck_instance *lfsck,
240                                            struct lfsck_namespace *ns)
241 {
242         struct lfsck_position pos;
243
244         ns->ln_items_failed++;
245         lfsck_pos_fill(env, lfsck, &pos, false);
246         if (lfsck_pos_is_zero(&ns->ln_pos_first_inconsistent) ||
247             lfsck_pos_is_eq(&pos, &ns->ln_pos_first_inconsistent) < 0) {
248                 ns->ln_pos_first_inconsistent = pos;
249
250                 CDEBUG(D_LFSCK, "%s: namespace LFSCK hit first non-repaired "
251                        "inconsistency at the pos ["LPU64", "DFID", "LPX64"]\n",
252                        lfsck_lfsck2name(lfsck),
253                        ns->ln_pos_first_inconsistent.lp_oit_cookie,
254                        PFID(&ns->ln_pos_first_inconsistent.lp_dir_parent),
255                        ns->ln_pos_first_inconsistent.lp_dir_cookie);
256         }
257 }
258
259 /**
260  * Load the MDT bitmap from the lfsck_namespace trace file.
261  *
262  * \param[in] env       pointer to the thread context
263  * \param[in] com       pointer to the lfsck component
264  *
265  * \retval              0 for success
266  * \retval              negative error number on failure or data corruption
267  */
268 static int lfsck_namespace_load_bitmap(const struct lu_env *env,
269                                        struct lfsck_component *com)
270 {
271         struct dt_object                *obj    = com->lc_obj;
272         struct lfsck_assistant_data     *lad    = com->lc_data;
273         struct lfsck_namespace          *ns     = com->lc_file_ram;
274         struct cfs_bitmap                       *bitmap = lad->lad_bitmap;
275         ssize_t                          size;
276         __u32                            nbits;
277         int                              rc;
278         ENTRY;
279
280         if (com->lc_lfsck->li_mdt_descs.ltd_tgts_bitmap->size >
281             ns->ln_bitmap_size)
282                 nbits = com->lc_lfsck->li_mdt_descs.ltd_tgts_bitmap->size;
283         else
284                 nbits = ns->ln_bitmap_size;
285
286         if (unlikely(nbits < BITS_PER_LONG))
287                 nbits = BITS_PER_LONG;
288
289         if (nbits > bitmap->size) {
290                 __u32 new_bits = bitmap->size;
291                 struct cfs_bitmap *new_bitmap;
292
293                 while (new_bits < nbits)
294                         new_bits <<= 1;
295
296                 new_bitmap = CFS_ALLOCATE_BITMAP(new_bits);
297                 if (new_bitmap == NULL)
298                         RETURN(-ENOMEM);
299
300                 lad->lad_bitmap = new_bitmap;
301                 CFS_FREE_BITMAP(bitmap);
302                 bitmap = new_bitmap;
303         }
304
305         if (ns->ln_bitmap_size == 0) {
306                 lad->lad_incomplete = 0;
307                 CFS_RESET_BITMAP(bitmap);
308
309                 RETURN(0);
310         }
311
312         size = (ns->ln_bitmap_size + 7) >> 3;
313         rc = dt_xattr_get(env, obj,
314                           lfsck_buf_get(env, bitmap->data, size),
315                           XATTR_NAME_LFSCK_BITMAP);
316         if (rc != size)
317                 RETURN(rc >= 0 ? -EINVAL : rc);
318
319         if (cfs_bitmap_check_empty(bitmap))
320                 lad->lad_incomplete = 0;
321         else
322                 lad->lad_incomplete = 1;
323
324         RETURN(0);
325 }
326
327 /**
328  * Load namespace LFSCK statistics information from the trace file.
329  *
330  * For old release (Lustre-2.6 or older), the statistics information was
331  * stored as XATTR_NAME_LFSCK_NAMESPACE_OLD EA. But in Lustre-2.7, we need
332  * more statistics information. To avoid confusing old MDT when downgrade,
333  * Lustre-2.7 stores the namespace LFSCK statistics information as new
334  * XATTR_NAME_LFSCK_NAMESPACE EA.
335  *
336  * \param[in] env       pointer to the thread context
337  * \param[in] com       pointer to the lfsck component
338  *
339  * \retval              0 for success
340  * \retval              negative error number on failure
341  */
342 static int lfsck_namespace_load(const struct lu_env *env,
343                                 struct lfsck_component *com)
344 {
345         int len = com->lc_file_size;
346         int rc;
347
348         rc = dt_xattr_get(env, com->lc_obj,
349                           lfsck_buf_get(env, com->lc_file_disk, len),
350                           XATTR_NAME_LFSCK_NAMESPACE);
351         if (rc == len) {
352                 struct lfsck_namespace *ns = com->lc_file_ram;
353
354                 lfsck_namespace_le_to_cpu(ns,
355                                 (struct lfsck_namespace *)com->lc_file_disk);
356                 if (ns->ln_magic != LFSCK_NAMESPACE_MAGIC) {
357                         CDEBUG(D_LFSCK, "%s: invalid lfsck_namespace magic "
358                                "%#x != %#x\n", lfsck_lfsck2name(com->lc_lfsck),
359                                ns->ln_magic, LFSCK_NAMESPACE_MAGIC);
360                         rc = -ESTALE;
361                 } else {
362                         rc = 0;
363                 }
364         } else if (rc != -ENODATA) {
365                 CDEBUG(D_LFSCK, "%s: fail to load lfsck_namespace, "
366                        "expected = %d: rc = %d\n",
367                        lfsck_lfsck2name(com->lc_lfsck), len, rc);
368                 if (rc >= 0)
369                         rc = -ESTALE;
370 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 8, 53, 0)
371         } else {
372                 /* Check whether it is old trace file or not.
373                  * If yes, it should be reset via returning -ESTALE. */
374                 rc = dt_xattr_get(env, com->lc_obj,
375                                   lfsck_buf_get(env, com->lc_file_disk, len),
376                                   XATTR_NAME_LFSCK_NAMESPACE_OLD);
377                 if (rc >= 0)
378                         rc = -ESTALE;
379 #endif
380         }
381
382         return rc;
383 }
384
385 static int lfsck_namespace_store(const struct lu_env *env,
386                                  struct lfsck_component *com, bool init)
387 {
388         struct dt_object                *obj    = com->lc_obj;
389         struct lfsck_instance           *lfsck  = com->lc_lfsck;
390         struct lfsck_namespace          *ns     = com->lc_file_ram;
391         struct lfsck_assistant_data     *lad    = com->lc_data;
392         struct dt_device                *dev    = lfsck_obj2dev(obj);
393         struct cfs_bitmap               *bitmap = NULL;
394         struct thandle                  *handle;
395         __u32                            nbits  = 0;
396         int                              len    = com->lc_file_size;
397         int                              rc;
398 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 8, 53, 0)
399         struct lu_buf            tbuf   = { &len, sizeof(len) };
400 #endif
401         ENTRY;
402
403         if (lad != NULL) {
404                 bitmap = lad->lad_bitmap;
405                 nbits = bitmap->size;
406
407                 LASSERT(nbits > 0);
408                 LASSERTF((nbits & 7) == 0, "Invalid nbits %u\n", nbits);
409         }
410
411         ns->ln_bitmap_size = nbits;
412         lfsck_namespace_cpu_to_le((struct lfsck_namespace *)com->lc_file_disk,
413                                   ns);
414         handle = dt_trans_create(env, dev);
415         if (IS_ERR(handle))
416                 GOTO(log, rc = PTR_ERR(handle));
417
418         rc = dt_declare_xattr_set(env, obj,
419                                   lfsck_buf_get(env, com->lc_file_disk, len),
420                                   XATTR_NAME_LFSCK_NAMESPACE, 0, handle);
421         if (rc != 0)
422                 GOTO(out, rc);
423
424         if (bitmap != NULL) {
425                 rc = dt_declare_xattr_set(env, obj,
426                                 lfsck_buf_get(env, bitmap->data, nbits >> 3),
427                                 XATTR_NAME_LFSCK_BITMAP, 0, handle);
428                 if (rc != 0)
429                         GOTO(out, rc);
430         }
431
432 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 8, 53, 0)
433         /* To be compatible with old Lustre-2.x MDT (x <= 6), generate dummy
434          * XATTR_NAME_LFSCK_NAMESPACE_OLD EA, then when downgrade to Lustre-2.x,
435          * the old LFSCK will find "invalid" XATTR_NAME_LFSCK_NAMESPACE_OLD EA,
436          * then reset the namespace LFSCK trace file. */
437         if (init) {
438                 rc = dt_declare_xattr_set(env, obj, &tbuf,
439                                           XATTR_NAME_LFSCK_NAMESPACE_OLD,
440                                           LU_XATTR_CREATE, handle);
441                 if (rc != 0)
442                         GOTO(out, rc);
443         }
444 #endif
445
446         rc = dt_trans_start_local(env, dev, handle);
447         if (rc != 0)
448                 GOTO(out, rc);
449
450         rc = dt_xattr_set(env, obj,
451                           lfsck_buf_get(env, com->lc_file_disk, len),
452                           XATTR_NAME_LFSCK_NAMESPACE, 0, handle);
453         if (rc == 0 && bitmap != NULL)
454                 rc = dt_xattr_set(env, obj,
455                                   lfsck_buf_get(env, bitmap->data, nbits >> 3),
456                                   XATTR_NAME_LFSCK_BITMAP, 0, handle);
457
458 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 8, 53, 0)
459         if (rc == 0 && init)
460                 rc = dt_xattr_set(env, obj, &tbuf,
461                                   XATTR_NAME_LFSCK_NAMESPACE_OLD,
462                                   LU_XATTR_CREATE, handle);
463 #endif
464
465         GOTO(out, rc);
466
467 out:
468         dt_trans_stop(env, dev, handle);
469
470 log:
471         if (rc != 0)
472                 CDEBUG(D_LFSCK, "%s: fail to store lfsck_namespace: rc = %d\n",
473                        lfsck_lfsck2name(lfsck), rc);
474         return rc;
475 }
476
477 static struct dt_object *
478 lfsck_namespace_load_one_trace_file(const struct lu_env *env,
479                                     struct lfsck_component *com,
480                                     struct dt_object *parent,
481                                     const char *name, bool reset)
482 {
483         struct lfsck_instance   *lfsck = com->lc_lfsck;
484         struct dt_object        *obj;
485         int                      rc;
486
487         if (reset) {
488                 rc = local_object_unlink(env, lfsck->li_bottom, parent, name);
489                 if (rc != 0 && rc != -ENOENT)
490                         return ERR_PTR(rc);
491         }
492
493         obj = local_index_find_or_create(env, lfsck->li_los, parent, name,
494                                          S_IFREG | S_IRUGO | S_IWUSR,
495                                          &dt_lfsck_features);
496
497         return obj;
498 }
499
500 static int lfsck_namespace_load_sub_trace_files(const struct lu_env *env,
501                                                 struct lfsck_component *com,
502                                                 bool reset)
503 {
504         char                            *name = lfsck_env_info(env)->lti_key;
505         struct lfsck_sub_trace_obj      *lsto;
506         struct dt_object                *obj;
507         int                              rc;
508         int                              i;
509
510         for (i = 0, lsto = &com->lc_sub_trace_objs[0];
511              i < LFSCK_STF_COUNT; i++, lsto++) {
512                 snprintf(name, NAME_MAX, "%s_%02d", LFSCK_NAMESPACE, i);
513                 if (lsto->lsto_obj != NULL) {
514                         if (!reset)
515                                 continue;
516
517                         lfsck_object_put(env, lsto->lsto_obj);
518                         lsto->lsto_obj = NULL;
519                 }
520
521                 obj = lfsck_namespace_load_one_trace_file(env, com,
522                                 com->lc_lfsck->li_lfsck_dir, name, reset);
523                 if (IS_ERR(obj))
524                         return PTR_ERR(obj);
525
526                 lsto->lsto_obj = obj;
527                 rc = obj->do_ops->do_index_try(env, obj, &dt_lfsck_features);
528                 if (rc != 0)
529                         return rc;
530         }
531
532         return 0;
533 }
534
535 static int lfsck_namespace_init(const struct lu_env *env,
536                                 struct lfsck_component *com)
537 {
538         struct lfsck_namespace *ns = com->lc_file_ram;
539         int rc;
540
541         memset(ns, 0, sizeof(*ns));
542         ns->ln_magic = LFSCK_NAMESPACE_MAGIC;
543         ns->ln_status = LS_INIT;
544         down_write(&com->lc_sem);
545         rc = lfsck_namespace_store(env, com, true);
546         up_write(&com->lc_sem);
547         if (rc == 0)
548                 rc = lfsck_namespace_load_sub_trace_files(env, com, true);
549
550         return rc;
551 }
552
553 /**
554  * Update the namespace LFSCK trace file for the given @fid
555  *
556  * \param[in] env       pointer to the thread context
557  * \param[in] com       pointer to the lfsck component
558  * \param[in] fid       the fid which flags to be updated in the lfsck
559  *                      trace file
560  * \param[in] add       true if add new flags, otherwise remove flags
561  *
562  * \retval              0 for success or nothing to be done
563  * \retval              negative error number on failure
564  */
565 int lfsck_namespace_trace_update(const struct lu_env *env,
566                                  struct lfsck_component *com,
567                                  const struct lu_fid *fid,
568                                  const __u8 flags, bool add)
569 {
570         struct lfsck_instance   *lfsck  = com->lc_lfsck;
571         struct dt_object        *obj;
572         struct lu_fid           *key    = &lfsck_env_info(env)->lti_fid3;
573         struct dt_device        *dev;
574         struct thandle          *th     = NULL;
575         int                      idx;
576         int                      rc     = 0;
577         __u8                     old    = 0;
578         __u8                     new    = 0;
579         ENTRY;
580
581         LASSERT(flags != 0);
582
583         if (unlikely(!fid_is_sane(fid)))
584                 RETURN(0);
585
586         idx = lfsck_sub_trace_file_fid2idx(fid);
587         obj = com->lc_sub_trace_objs[idx].lsto_obj;
588         dev = lfsck_obj2dev(obj);
589         mutex_lock(&com->lc_sub_trace_objs[idx].lsto_mutex);
590         fid_cpu_to_be(key, fid);
591         rc = dt_lookup(env, obj, (struct dt_rec *)&old,
592                        (const struct dt_key *)key);
593         if (rc == -ENOENT) {
594                 if (!add)
595                         GOTO(unlock, rc = 0);
596
597                 old = 0;
598                 new = flags;
599         } else if (rc == 0) {
600                 if (add) {
601                         if ((old & flags) == flags)
602                                 GOTO(unlock, rc = 0);
603
604                         new = old | flags;
605                 } else {
606                         if ((old & flags) == 0)
607                                 GOTO(unlock, rc = 0);
608
609                         new = old & ~flags;
610                 }
611         } else {
612                 GOTO(log, rc);
613         }
614
615         th = dt_trans_create(env, dev);
616         if (IS_ERR(th))
617                 GOTO(log, rc = PTR_ERR(th));
618
619         if (old != 0) {
620                 rc = dt_declare_delete(env, obj,
621                                        (const struct dt_key *)key, th);
622                 if (rc != 0)
623                         GOTO(log, rc);
624         }
625
626         if (new != 0) {
627                 rc = dt_declare_insert(env, obj,
628                                        (const struct dt_rec *)&new,
629                                        (const struct dt_key *)key, th);
630                 if (rc != 0)
631                         GOTO(log, rc);
632         }
633
634         rc = dt_trans_start_local(env, dev, th);
635         if (rc != 0)
636                 GOTO(log, rc);
637
638         if (old != 0) {
639                 rc = dt_delete(env, obj, (const struct dt_key *)key, th);
640                 if (rc != 0)
641                         GOTO(log, rc);
642         }
643
644         if (new != 0) {
645                 rc = dt_insert(env, obj, (const struct dt_rec *)&new,
646                                (const struct dt_key *)key, th, 1);
647                 if (rc != 0)
648                         GOTO(log, rc);
649         }
650
651         GOTO(log, rc);
652
653 log:
654         if (th != NULL && !IS_ERR(th))
655                 dt_trans_stop(env, dev, th);
656
657         CDEBUG(D_LFSCK, "%s: namespace LFSCK %s flags for "DFID" in the "
658                "trace file, flags %x, old %x, new %x: rc = %d\n",
659                lfsck_lfsck2name(lfsck), add ? "add" : "del", PFID(fid),
660                (__u32)flags, (__u32)old, (__u32)new, rc);
661
662 unlock:
663         mutex_unlock(&com->lc_sub_trace_objs[idx].lsto_mutex);
664
665         return rc;
666 }
667
668 int lfsck_namespace_check_exist(const struct lu_env *env,
669                                 struct dt_object *dir,
670                                 struct dt_object *obj, const char *name)
671 {
672         struct lu_fid    *fid = &lfsck_env_info(env)->lti_fid;
673         int               rc;
674         ENTRY;
675
676         if (unlikely(lfsck_is_dead_obj(obj)))
677                 RETURN(LFSCK_NAMEENTRY_DEAD);
678
679         rc = dt_lookup(env, dir, (struct dt_rec *)fid,
680                        (const struct dt_key *)name);
681         if (rc == -ENOENT)
682                 RETURN(LFSCK_NAMEENTRY_REMOVED);
683
684         if (rc < 0)
685                 RETURN(rc);
686
687         if (!lu_fid_eq(fid, lfsck_dto2fid(obj)))
688                 RETURN(LFSCK_NAMEENTRY_RECREATED);
689
690         RETURN(0);
691 }
692
693 static int lfsck_declare_namespace_exec_dir(const struct lu_env *env,
694                                             struct dt_object *obj,
695                                             struct thandle *handle)
696 {
697         int rc;
698
699         /* For destroying all invalid linkEA entries. */
700         rc = dt_declare_xattr_del(env, obj, XATTR_NAME_LINK, handle);
701         if (rc != 0)
702                 return rc;
703
704         /* For insert new linkEA entry. */
705         rc = dt_declare_xattr_set(env, obj,
706                         lfsck_buf_get_const(env, NULL, DEFAULT_LINKEA_SIZE),
707                         XATTR_NAME_LINK, 0, handle);
708         return rc;
709 }
710
711 int __lfsck_links_read(const struct lu_env *env, struct dt_object *obj,
712                        struct linkea_data *ldata)
713 {
714         int rc;
715
716         if (ldata->ld_buf->lb_buf == NULL)
717                 return -ENOMEM;
718
719         if (!dt_object_exists(obj))
720                 return -ENOENT;
721
722         rc = dt_xattr_get(env, obj, ldata->ld_buf, XATTR_NAME_LINK);
723         if (rc == -ERANGE) {
724                 /* Buf was too small, figure out what we need. */
725                 rc = dt_xattr_get(env, obj, &LU_BUF_NULL, XATTR_NAME_LINK);
726                 if (rc <= 0)
727                         return rc;
728
729                 lu_buf_realloc(ldata->ld_buf, rc);
730                 if (ldata->ld_buf->lb_buf == NULL)
731                         return -ENOMEM;
732
733                 rc = dt_xattr_get(env, obj, ldata->ld_buf, XATTR_NAME_LINK);
734         }
735
736         if (rc > 0)
737                 rc = linkea_init(ldata);
738
739         return rc;
740 }
741
742 /**
743  * Remove linkEA for the given object.
744  *
745  * The caller should take the ldlm lock before the calling.
746  *
747  * \param[in] env       pointer to the thread context
748  * \param[in] com       pointer to the lfsck component
749  * \param[in] obj       pointer to the dt_object to be handled
750  *
751  * \retval              0 for repaired cases
752  * \retval              negative error number on failure
753  */
754 static int lfsck_namespace_links_remove(const struct lu_env *env,
755                                         struct lfsck_component *com,
756                                         struct dt_object *obj)
757 {
758         struct lfsck_instance           *lfsck  = com->lc_lfsck;
759         struct dt_device                *dev    = lfsck_obj2dev(obj);
760         struct thandle                  *th     = NULL;
761         int                              rc     = 0;
762         ENTRY;
763
764         LASSERT(dt_object_remote(obj) == 0);
765
766         th = dt_trans_create(env, dev);
767         if (IS_ERR(th))
768                 GOTO(log, rc = PTR_ERR(th));
769
770         rc = dt_declare_xattr_del(env, obj, XATTR_NAME_LINK, th);
771         if (rc != 0)
772                 GOTO(stop, rc);
773
774         rc = dt_trans_start_local(env, dev, th);
775         if (rc != 0)
776                 GOTO(stop, rc);
777
778         dt_write_lock(env, obj, 0);
779         if (unlikely(lfsck_is_dead_obj(obj)))
780                 GOTO(unlock, rc = -ENOENT);
781
782         if (lfsck->li_bookmark_ram.lb_param & LPF_DRYRUN)
783                 GOTO(unlock, rc = 0);
784
785         rc = dt_xattr_del(env, obj, XATTR_NAME_LINK, th);
786
787         GOTO(unlock, rc);
788
789 unlock:
790         dt_write_unlock(env, obj);
791
792 stop:
793         dt_trans_stop(env, dev, th);
794
795 log:
796         CDEBUG(D_LFSCK, "%s: namespace LFSCK remove invalid linkEA "
797                "for the object "DFID": rc = %d\n",
798                lfsck_lfsck2name(lfsck), PFID(lfsck_dto2fid(obj)), rc);
799
800         if (rc == 0) {
801                 struct lfsck_namespace *ns = com->lc_file_ram;
802
803                 ns->ln_flags |= LF_INCONSISTENT;
804         }
805
806         return rc;
807 }
808
809 static int lfsck_links_write(const struct lu_env *env, struct dt_object *obj,
810                              struct linkea_data *ldata, struct thandle *handle)
811 {
812         const struct lu_buf *buf = lfsck_buf_get_const(env,
813                                                        ldata->ld_buf->lb_buf,
814                                                        ldata->ld_leh->leh_len);
815
816         return dt_xattr_set(env, obj, buf, XATTR_NAME_LINK, 0, handle);
817 }
818
819 static void lfsck_namespace_unpack_linkea_entry(struct linkea_data *ldata,
820                                                 struct lu_name *cname,
821                                                 struct lu_fid *pfid,
822                                                 char *buf)
823 {
824         linkea_entry_unpack(ldata->ld_lee, &ldata->ld_reclen, cname, pfid);
825         /* To guarantee the 'name' is terminated with '0'. */
826         memcpy(buf, cname->ln_name, cname->ln_namelen);
827         buf[cname->ln_namelen] = 0;
828         cname->ln_name = buf;
829 }
830
831 static int lfsck_namespace_filter_linkea_entry(struct linkea_data *ldata,
832                                                struct lu_name *cname,
833                                                struct lu_fid *pfid,
834                                                bool remove)
835 {
836         struct link_ea_entry    *oldlee;
837         int                      oldlen;
838         int                      repeated = 0;
839
840         oldlee = ldata->ld_lee;
841         oldlen = ldata->ld_reclen;
842         linkea_next_entry(ldata);
843         while (ldata->ld_lee != NULL) {
844                 ldata->ld_reclen = (ldata->ld_lee->lee_reclen[0] << 8) |
845                                    ldata->ld_lee->lee_reclen[1];
846                 if (unlikely(ldata->ld_reclen == oldlen &&
847                              memcmp(ldata->ld_lee, oldlee, oldlen) == 0)) {
848                         repeated++;
849                         if (!remove)
850                                 break;
851
852                         linkea_del_buf(ldata, cname);
853                 } else {
854                         linkea_next_entry(ldata);
855                 }
856         }
857         ldata->ld_lee = oldlee;
858         ldata->ld_reclen = oldlen;
859
860         return repeated;
861 }
862
863 /**
864  * Insert orphan into .lustre/lost+found/MDTxxxx/ locally.
865  *
866  * Add the specified orphan MDT-object to the .lustre/lost+found/MDTxxxx/
867  * with the given type to generate the name, the detailed rules for name
868  * have been described as following.
869  *
870  * The function also generates the linkEA corresponding to the name entry
871  * under the .lustre/lost+found/MDTxxxx/ for the orphan MDT-object.
872  *
873  * \param[in] env       pointer to the thread context
874  * \param[in] com       pointer to the lfsck component
875  * \param[in] orphan    pointer to the orphan MDT-object
876  * \param[in] infix     additional information for the orphan name, such as
877  *                      the FID for original
878  * \param[in] type      the type for describing why the orphan MDT-object is
879  *                      created. The rules are as following:
880  *
881  *  type "D":           The MDT-object is a directory, it may knows its parent
882  *                      but because there is no valid linkEA, the LFSCK cannot
883  *                      know where to put it back to the namespace.
884  *  type "O":           The MDT-object has no linkEA, and there is no name
885  *                      entry that references the MDT-object.
886  *
887  *  type "S":           The orphan MDT-object is a shard of a striped directory
888  *
889  * \see lfsck_layout_recreate_parent() for more types.
890  *
891  * The orphan name will be like:
892  * ${FID}-${infix}-${type}-${conflict_version}
893  *
894  * \param[out] count    if some others inserted some linkEA entries by race,
895  *                      then return the linkEA entries count.
896  *
897  * \retval              positive number for repaired cases
898  * \retval              0 if needs to repair nothing
899  * \retval              negative error number on failure
900  */
901 static int lfsck_namespace_insert_orphan(const struct lu_env *env,
902                                          struct lfsck_component *com,
903                                          struct dt_object *orphan,
904                                          const char *infix, const char *type,
905                                          int *count)
906 {
907         struct lfsck_thread_info        *info   = lfsck_env_info(env);
908         struct lu_name                  *cname  = &info->lti_name;
909         struct dt_insert_rec            *rec    = &info->lti_dt_rec;
910         struct lu_attr                  *la     = &info->lti_la2;
911         const struct lu_fid             *cfid   = lfsck_dto2fid(orphan);
912         const struct lu_fid             *pfid;
913         struct lu_fid                    tfid;
914         struct lfsck_instance           *lfsck  = com->lc_lfsck;
915         struct dt_device                *dev    = lfsck_obj2dev(orphan);
916         struct dt_object                *parent;
917         struct thandle                  *th     = NULL;
918         struct lfsck_lock_handle        *pllh   = &info->lti_llh;
919         struct lustre_handle             clh    = { 0 };
920         struct linkea_data               ldata  = { NULL };
921         struct lu_buf                    linkea_buf;
922         int                              namelen;
923         int                              idx    = 0;
924         int                              rc     = 0;
925         bool                             exist  = false;
926         ENTRY;
927
928         cname->ln_name = NULL;
929         if (unlikely(lfsck->li_lpf_obj == NULL))
930                 GOTO(log, rc = -ENXIO);
931
932         parent = lfsck->li_lpf_obj;
933         pfid = lfsck_dto2fid(parent);
934
935 again:
936         do {
937                 namelen = snprintf(info->lti_key, NAME_MAX, DFID"%s-%s-%d",
938                                    PFID(cfid), infix, type, idx++);
939                 rc = dt_lookup(env, parent, (struct dt_rec *)&tfid,
940                                (const struct dt_key *)info->lti_key);
941                 if (rc != 0 && rc != -ENOENT)
942                         GOTO(log, rc);
943
944                 if (unlikely(rc == 0 && lu_fid_eq(cfid, &tfid)))
945                         exist = true;
946         } while (rc == 0 && !exist);
947
948         rc = lfsck_lock(env, lfsck, parent, info->lti_key, pllh,
949                         MDS_INODELOCK_UPDATE, LCK_PW);
950         if (rc != 0)
951                 GOTO(log, rc);
952
953         /* Re-check whether the name conflict with othrs after taken
954          * the ldlm lock. */
955         rc = dt_lookup(env, parent, (struct dt_rec *)&tfid,
956                        (const struct dt_key *)info->lti_key);
957         if (rc == 0) {
958                 if (!lu_fid_eq(cfid, &tfid)) {
959                         exist = false;
960                         lfsck_unlock(pllh);
961                         goto again;
962                 }
963
964                 exist = true;
965         } else if (rc != -ENOENT) {
966                 GOTO(log, rc);
967         } else {
968                 exist = false;
969         }
970
971         cname->ln_name = info->lti_key;
972         cname->ln_namelen = namelen;
973         rc = linkea_data_new(&ldata, &info->lti_linkea_buf2);
974         if (rc != 0)
975                 GOTO(log, rc);
976
977         rc = linkea_add_buf(&ldata, cname, pfid);
978         if (rc != 0)
979                 GOTO(log, rc);
980
981         rc = lfsck_ibits_lock(env, lfsck, orphan, &clh,
982                               MDS_INODELOCK_UPDATE | MDS_INODELOCK_LOOKUP |
983                               MDS_INODELOCK_XATTR, LCK_EX);
984         if (rc != 0)
985                 GOTO(log, rc);
986
987         lfsck_buf_init(&linkea_buf, ldata.ld_buf->lb_buf,
988                        ldata.ld_leh->leh_len);
989         th = dt_trans_create(env, dev);
990         if (IS_ERR(th))
991                 GOTO(log, rc = PTR_ERR(th));
992
993         if (S_ISDIR(lfsck_object_type(orphan))) {
994                 rc = dt_declare_delete(env, orphan,
995                                        (const struct dt_key *)dotdot, th);
996                 if (rc != 0)
997                         GOTO(stop, rc);
998
999                 rec->rec_type = S_IFDIR;
1000                 rec->rec_fid = pfid;
1001                 rc = dt_declare_insert(env, orphan, (const struct dt_rec *)rec,
1002                                        (const struct dt_key *)dotdot, th);
1003                 if (rc != 0)
1004                         GOTO(stop, rc);
1005         }
1006
1007         rc = dt_declare_xattr_set(env, orphan, &linkea_buf,
1008                                   XATTR_NAME_LINK, 0, th);
1009         if (rc != 0)
1010                 GOTO(stop, rc);
1011
1012         if (!exist) {
1013                 rec->rec_type = lfsck_object_type(orphan) & S_IFMT;
1014                 rec->rec_fid = cfid;
1015                 rc = dt_declare_insert(env, parent, (const struct dt_rec *)rec,
1016                                        (const struct dt_key *)cname->ln_name,
1017                                        th);
1018                 if (rc != 0)
1019                         GOTO(stop, rc);
1020
1021                 if (S_ISDIR(rec->rec_type)) {
1022                         rc = dt_declare_ref_add(env, parent, th);
1023                         if (rc != 0)
1024                                 GOTO(stop, rc);
1025                 }
1026         }
1027
1028         memset(la, 0, sizeof(*la));
1029         la->la_ctime = cfs_time_current_sec();
1030         la->la_valid = LA_CTIME;
1031         rc = dt_declare_attr_set(env, orphan, la, th);
1032         if (rc != 0)
1033                 GOTO(stop, rc);
1034
1035         rc = dt_trans_start_local(env, dev, th);
1036         if (rc != 0)
1037                 GOTO(stop, rc);
1038
1039         dt_write_lock(env, orphan, 0);
1040         rc = lfsck_links_read(env, orphan, &ldata);
1041         if (likely((rc == -ENODATA) || (rc == -EINVAL) ||
1042                    (rc == 0 && ldata.ld_leh->leh_reccount == 0))) {
1043                 if (lfsck->li_bookmark_ram.lb_param & LPF_DRYRUN)
1044                         GOTO(unlock, rc = 1);
1045
1046                 if (S_ISDIR(lfsck_object_type(orphan))) {
1047                         rc = dt_delete(env, orphan,
1048                                        (const struct dt_key *)dotdot, th);
1049                         if (rc != 0)
1050                                 GOTO(unlock, rc);
1051
1052                         rec->rec_type = S_IFDIR;
1053                         rec->rec_fid = pfid;
1054                         rc = dt_insert(env, orphan, (const struct dt_rec *)rec,
1055                                        (const struct dt_key *)dotdot, th, 1);
1056                         if (rc != 0)
1057                                 GOTO(unlock, rc);
1058                 }
1059
1060                 rc = dt_xattr_set(env, orphan, &linkea_buf, XATTR_NAME_LINK, 0,
1061                                   th);
1062         } else {
1063                 if (rc == 0 && count != NULL)
1064                         *count = ldata.ld_leh->leh_reccount;
1065
1066                 GOTO(unlock, rc);
1067         }
1068         dt_write_unlock(env, orphan);
1069
1070         if (rc == 0 && !exist) {
1071                 rec->rec_type = lfsck_object_type(orphan) & S_IFMT;
1072                 rec->rec_fid = cfid;
1073                 rc = dt_insert(env, parent, (const struct dt_rec *)rec,
1074                                (const struct dt_key *)cname->ln_name, th, 1);
1075                 if (rc == 0 && S_ISDIR(rec->rec_type)) {
1076                         dt_write_lock(env, parent, 0);
1077                         rc = dt_ref_add(env, parent, th);
1078                         dt_write_unlock(env, parent);
1079                 }
1080         }
1081
1082         if (rc == 0)
1083                 rc = dt_attr_set(env, orphan, la, th);
1084
1085         GOTO(stop, rc = (rc == 0 ? 1 : rc));
1086
1087 unlock:
1088         dt_write_unlock(env, orphan);
1089
1090 stop:
1091         dt_trans_stop(env, dev, th);
1092
1093 log:
1094         lfsck_ibits_unlock(&clh, LCK_EX);
1095         lfsck_unlock(pllh);
1096         CDEBUG(D_LFSCK, "%s: namespace LFSCK insert orphan for the "
1097                "object "DFID", name = %s: rc = %d\n",
1098                lfsck_lfsck2name(lfsck), PFID(cfid),
1099                cname->ln_name != NULL ? cname->ln_name : "<NULL>", rc);
1100
1101         if (rc != 0) {
1102                 struct lfsck_namespace *ns = com->lc_file_ram;
1103
1104                 ns->ln_flags |= LF_INCONSISTENT;
1105         }
1106
1107         return rc;
1108 }
1109
1110 /**
1111  * Add the specified name entry back to namespace.
1112  *
1113  * If there is a linkEA entry that back references a name entry under
1114  * some parent directory, but such parent directory does not have the
1115  * claimed name entry. On the other hand, the linkEA entries count is
1116  * not larger than the MDT-object's hard link count. Under such case,
1117  * it is quite possible that the name entry is lost. Then the LFSCK
1118  * should add the name entry back to the namespace.
1119  *
1120  * \param[in] env       pointer to the thread context
1121  * \param[in] com       pointer to the lfsck component
1122  * \param[in] parent    pointer to the directory under which the name entry
1123  *                      will be inserted into
1124  * \param[in] child     pointer to the object referenced by the name entry
1125  *                      that to be inserted into the parent
1126  * \param[in] name      the name for the child in the parent directory
1127  *
1128  * \retval              positive number for repaired cases
1129  * \retval              0 if nothing to be repaired
1130  * \retval              negative error number on failure
1131  */
1132 static int lfsck_namespace_insert_normal(const struct lu_env *env,
1133                                          struct lfsck_component *com,
1134                                          struct dt_object *parent,
1135                                          struct dt_object *child,
1136                                          const char *name)
1137 {
1138         struct lfsck_thread_info        *info   = lfsck_env_info(env);
1139         struct lu_attr                  *la     = &info->lti_la;
1140         struct dt_insert_rec            *rec    = &info->lti_dt_rec;
1141         struct lfsck_instance           *lfsck  = com->lc_lfsck;
1142         /* The child and its name may be on different MDTs. */
1143         const struct lu_fid             *pfid   = lfsck_dto2fid(parent);
1144         const struct lu_fid             *cfid   = lfsck_dto2fid(child);
1145         struct dt_device                *dev    = lfsck->li_next;
1146         struct thandle                  *th     = NULL;
1147         struct lfsck_lock_handle        *llh    = &info->lti_llh;
1148         int                              rc     = 0;
1149         ENTRY;
1150
1151         /* @parent/@child may be based on lfsck->li_bottom,
1152          * but here we need the object based on the lfsck->li_next. */
1153
1154         parent = lfsck_object_locate(dev, parent);
1155         if (IS_ERR(parent))
1156                 GOTO(log, rc = PTR_ERR(parent));
1157
1158         if (unlikely(!dt_try_as_dir(env, parent)))
1159                 GOTO(log, rc = -ENOTDIR);
1160
1161         child = lfsck_object_locate(dev, child);
1162         if (IS_ERR(child))
1163                 GOTO(log, rc = PTR_ERR(child));
1164
1165         if (lfsck->li_bookmark_ram.lb_param & LPF_DRYRUN)
1166                 GOTO(log, rc = 1);
1167
1168         rc = lfsck_lock(env, lfsck, parent, name, llh,
1169                         MDS_INODELOCK_UPDATE, LCK_PW);
1170         if (rc != 0)
1171                 GOTO(log, rc);
1172
1173         th = dt_trans_create(env, dev);
1174         if (IS_ERR(th))
1175                 GOTO(unlock, rc = PTR_ERR(th));
1176
1177         rec->rec_type = lfsck_object_type(child) & S_IFMT;
1178         rec->rec_fid = cfid;
1179         rc = dt_declare_insert(env, parent, (const struct dt_rec *)rec,
1180                                (const struct dt_key *)name, th);
1181         if (rc != 0)
1182                 GOTO(stop, rc);
1183
1184         if (S_ISDIR(rec->rec_type)) {
1185                 rc = dt_declare_ref_add(env, parent, th);
1186                 if (rc != 0)
1187                         GOTO(stop, rc);
1188         }
1189
1190         memset(la, 0, sizeof(*la));
1191         la->la_ctime = cfs_time_current_sec();
1192         la->la_valid = LA_CTIME;
1193         rc = dt_declare_attr_set(env, parent, la, th);
1194         if (rc != 0)
1195                 GOTO(stop, rc);
1196
1197         rc = dt_declare_attr_set(env, child, la, th);
1198         if (rc != 0)
1199                 GOTO(stop, rc);
1200
1201         rc = dt_trans_start_local(env, dev, th);
1202         if (rc != 0)
1203                 GOTO(stop, rc);
1204
1205         rc = dt_insert(env, parent, (const struct dt_rec *)rec,
1206                        (const struct dt_key *)name, th, 1);
1207         if (rc != 0)
1208                 GOTO(stop, rc);
1209
1210         if (S_ISDIR(rec->rec_type)) {
1211                 dt_write_lock(env, parent, 0);
1212                 rc = dt_ref_add(env, parent, th);
1213                 dt_write_unlock(env, parent);
1214                 if (rc != 0)
1215                         GOTO(stop, rc);
1216         }
1217
1218         la->la_ctime = cfs_time_current_sec();
1219         rc = dt_attr_set(env, parent, la, th);
1220         if (rc != 0)
1221                 GOTO(stop, rc);
1222
1223         rc = dt_attr_set(env, child, la, th);
1224
1225         GOTO(stop, rc = (rc == 0 ? 1 : rc));
1226
1227 stop:
1228         dt_trans_stop(env, dev, th);
1229
1230 unlock:
1231         lfsck_unlock(llh);
1232
1233 log:
1234         CDEBUG(D_LFSCK, "%s: namespace LFSCK insert object "DFID" with "
1235                "the name %s and type %o to the parent "DFID": rc = %d\n",
1236                lfsck_lfsck2name(lfsck), PFID(cfid), name,
1237                lfsck_object_type(child) & S_IFMT, PFID(pfid), rc);
1238
1239         if (rc != 0) {
1240                 struct lfsck_namespace *ns = com->lc_file_ram;
1241
1242                 ns->ln_flags |= LF_INCONSISTENT;
1243                 if (rc > 0)
1244                         ns->ln_lost_dirent_repaired++;
1245         }
1246
1247         return rc;
1248 }
1249
1250 /**
1251  * Create the specified orphan directory.
1252  *
1253  * For the case that the parent MDT-object stored in some MDT-object's
1254  * linkEA entry is lost, the LFSCK will re-create the parent object as
1255  * an orphan and insert it into .lustre/lost+found/MDTxxxx/ directory
1256  * with the name ${FID}-P-${conflict_version}.
1257  *
1258  * \param[in] env       pointer to the thread context
1259  * \param[in] com       pointer to the lfsck component
1260  * \param[in] orphan    pointer to the orphan MDT-object to be created
1261  * \param[in] lmv       pointer to master LMV EA that will be set to the orphan
1262  *
1263  * \retval              positive number for repaired cases
1264  * \retval              negative error number on failure
1265  */
1266 static int lfsck_namespace_create_orphan_dir(const struct lu_env *env,
1267                                              struct lfsck_component *com,
1268                                              struct dt_object *orphan,
1269                                              struct lmv_mds_md_v1 *lmv)
1270 {
1271         struct lfsck_thread_info        *info   = lfsck_env_info(env);
1272         struct lu_attr                  *la     = &info->lti_la;
1273         struct dt_allocation_hint       *hint   = &info->lti_hint;
1274         struct dt_object_format         *dof    = &info->lti_dof;
1275         struct lu_name                  *cname  = &info->lti_name2;
1276         struct dt_insert_rec            *rec    = &info->lti_dt_rec;
1277         struct lmv_mds_md_v1            *lmv2   = &info->lti_lmv2;
1278         const struct lu_fid             *cfid   = lfsck_dto2fid(orphan);
1279         struct lu_fid                    tfid;
1280         struct lfsck_instance           *lfsck  = com->lc_lfsck;
1281         struct lfsck_namespace          *ns     = com->lc_file_ram;
1282         struct dt_device                *dev    = lfsck_obj2dev(orphan);
1283         struct dt_object                *parent = NULL;
1284         struct thandle                  *th     = NULL;
1285         struct lfsck_lock_handle        *llh    = &info->lti_llh;
1286         struct linkea_data               ldata  = { NULL };
1287         struct lu_buf                    linkea_buf;
1288         struct lu_buf                    lmv_buf;
1289         char                             name[32];
1290         int                              namelen;
1291         int                              idx    = 0;
1292         int                              rc     = 0;
1293         int                              rc1    = 0;
1294         ENTRY;
1295
1296         LASSERT(!dt_object_exists(orphan));
1297
1298         cname->ln_name = NULL;
1299         if (lfsck->li_bookmark_ram.lb_param & LPF_DRYRUN)
1300                 GOTO(log, rc = 1);
1301
1302         if (dt_object_remote(orphan)) {
1303                 LASSERT(lfsck->li_lpf_root_obj != NULL);
1304
1305                 idx = lfsck_find_mdt_idx_by_fid(env, lfsck, cfid);
1306                 if (idx < 0)
1307                         GOTO(log, rc = idx);
1308
1309                 snprintf(name, 8, "MDT%04x", idx);
1310                 rc = dt_lookup(env, lfsck->li_lpf_root_obj,
1311                                (struct dt_rec *)&tfid,
1312                                (const struct dt_key *)name);
1313                 if (rc != 0)
1314                         GOTO(log, rc = (rc == -ENOENT ? -ENXIO : rc));
1315
1316                 parent = lfsck_object_find_bottom(env, lfsck, &tfid);
1317                 if (IS_ERR(parent))
1318                         GOTO(log, rc = PTR_ERR(parent));
1319
1320                 if (unlikely(!dt_try_as_dir(env, parent)))
1321                         GOTO(log, rc = -ENOTDIR);
1322         } else {
1323                 if (unlikely(lfsck->li_lpf_obj == NULL))
1324                         GOTO(log, rc = -ENXIO);
1325
1326                 parent = lfsck->li_lpf_obj;
1327         }
1328
1329         dev = lfsck_find_dev_by_fid(env, lfsck, cfid);
1330         if (IS_ERR(dev))
1331                 GOTO(log, rc = PTR_ERR(dev));
1332
1333         idx = 0;
1334
1335 again:
1336         do {
1337                 namelen = snprintf(name, 31, DFID"-P-%d",
1338                                    PFID(cfid), idx++);
1339                 rc = dt_lookup(env, parent, (struct dt_rec *)&tfid,
1340                                (const struct dt_key *)name);
1341                 if (rc != 0 && rc != -ENOENT)
1342                         GOTO(log, rc);
1343         } while (rc == 0);
1344
1345         rc = lfsck_lock(env, lfsck, parent, name, llh,
1346                         MDS_INODELOCK_UPDATE, LCK_PW);
1347         if (rc != 0)
1348                 GOTO(log, rc);
1349
1350         /* Re-check whether the name conflict with othrs after taken
1351          * the ldlm lock. */
1352         rc = dt_lookup(env, parent, (struct dt_rec *)&tfid,
1353                        (const struct dt_key *)name);
1354         if (unlikely(rc == 0)) {
1355                 lfsck_unlock(llh);
1356                 goto again;
1357         }
1358
1359         if (rc != -ENOENT)
1360                 GOTO(unlock1, rc);
1361
1362         cname->ln_name = name;
1363         cname->ln_namelen = namelen;
1364
1365         memset(la, 0, sizeof(*la));
1366         la->la_mode = S_IFDIR | 0700;
1367         la->la_valid = LA_TYPE | LA_MODE | LA_UID | LA_GID |
1368                        LA_ATIME | LA_MTIME | LA_CTIME;
1369
1370         orphan->do_ops->do_ah_init(env, hint, parent, orphan,
1371                                    la->la_mode & S_IFMT);
1372
1373         memset(dof, 0, sizeof(*dof));
1374         dof->dof_type = dt_mode_to_dft(S_IFDIR);
1375
1376         rc = linkea_data_new(&ldata, &info->lti_linkea_buf2);
1377         if (rc != 0)
1378                 GOTO(unlock1, rc);
1379
1380         rc = linkea_add_buf(&ldata, cname, lfsck_dto2fid(parent));
1381         if (rc != 0)
1382                 GOTO(unlock1, rc);
1383
1384         th = dt_trans_create(env, dev);
1385         if (IS_ERR(th))
1386                 GOTO(unlock1, rc = PTR_ERR(th));
1387
1388         /* Sync the remote transaction to guarantee that the subsequent
1389          * lock against the @orphan can find the @orphan in time. */
1390         if (dt_object_remote(orphan))
1391                 th->th_sync = 1;
1392
1393         rc = dt_declare_create(env, orphan, la, hint, dof, th);
1394         if (rc != 0)
1395                 GOTO(stop, rc);
1396
1397         if (unlikely(!dt_try_as_dir(env, orphan)))
1398                 GOTO(stop, rc = -ENOTDIR);
1399
1400         rc = dt_declare_ref_add(env, orphan, th);
1401         if (rc != 0)
1402                 GOTO(stop, rc);
1403
1404         rec->rec_type = S_IFDIR;
1405         rec->rec_fid = cfid;
1406         rc = dt_declare_insert(env, orphan, (const struct dt_rec *)rec,
1407                                (const struct dt_key *)dot, th);
1408         if (rc != 0)
1409                 GOTO(stop, rc);
1410
1411         rec->rec_fid = lfsck_dto2fid(parent);
1412         rc = dt_declare_insert(env, orphan, (const struct dt_rec *)rec,
1413                                (const struct dt_key *)dotdot, th);
1414         if (rc != 0)
1415                 GOTO(stop, rc);
1416
1417         if (lmv != NULL) {
1418                 lmv->lmv_magic = LMV_MAGIC;
1419                 lmv->lmv_master_mdt_index = lfsck_dev_idx(lfsck);
1420                 lfsck_lmv_header_cpu_to_le(lmv2, lmv);
1421                 lfsck_buf_init(&lmv_buf, lmv2, sizeof(*lmv2));
1422                 rc = dt_declare_xattr_set(env, orphan, &lmv_buf,
1423                                           XATTR_NAME_LMV, 0, th);
1424                 if (rc != 0)
1425                         GOTO(stop, rc);
1426         }
1427
1428         lfsck_buf_init(&linkea_buf, ldata.ld_buf->lb_buf,
1429                        ldata.ld_leh->leh_len);
1430         rc = dt_declare_xattr_set(env, orphan, &linkea_buf,
1431                                   XATTR_NAME_LINK, 0, th);
1432         if (rc != 0)
1433                 GOTO(stop, rc);
1434
1435         rec->rec_fid = cfid;
1436         rc = dt_declare_insert(env, parent, (const struct dt_rec *)rec,
1437                                (const struct dt_key *)name, th);
1438         if (rc == 0)
1439                 rc = dt_declare_ref_add(env, parent, th);
1440
1441         if (rc != 0)
1442                 GOTO(stop, rc);
1443
1444         rc = dt_trans_start_local(env, dev, th);
1445         if (rc != 0)
1446                 GOTO(stop, rc);
1447
1448         dt_write_lock(env, orphan, 0);
1449         rc = dt_create(env, orphan, la, hint, dof, th);
1450         if (rc != 0)
1451                 GOTO(unlock2, rc);
1452
1453         rc = dt_ref_add(env, orphan, th);
1454         if (rc != 0)
1455                 GOTO(unlock2, rc);
1456
1457         rec->rec_fid = cfid;
1458         rc = dt_insert(env, orphan, (const struct dt_rec *)rec,
1459                        (const struct dt_key *)dot, th, 1);
1460         if (rc != 0)
1461                 GOTO(unlock2, rc);
1462
1463         rec->rec_fid = lfsck_dto2fid(parent);
1464         rc = dt_insert(env, orphan, (const struct dt_rec *)rec,
1465                        (const struct dt_key *)dotdot, th, 1);
1466         if (rc != 0)
1467                 GOTO(unlock2, rc);
1468
1469         if (lmv != NULL) {
1470                 rc = dt_xattr_set(env, orphan, &lmv_buf, XATTR_NAME_LMV, 0, th);
1471                 if (rc != 0)
1472                         GOTO(unlock2, rc);
1473         }
1474
1475         rc = dt_xattr_set(env, orphan, &linkea_buf,
1476                           XATTR_NAME_LINK, 0, th);
1477         dt_write_unlock(env, orphan);
1478         if (rc != 0)
1479                 GOTO(stop, rc);
1480
1481         rec->rec_fid = cfid;
1482         rc = dt_insert(env, parent, (const struct dt_rec *)rec,
1483                        (const struct dt_key *)name, th, 1);
1484         if (rc == 0) {
1485                 dt_write_lock(env, parent, 0);
1486                 rc = dt_ref_add(env, parent, th);
1487                 dt_write_unlock(env, parent);
1488         }
1489
1490         GOTO(stop, rc = (rc == 0 ? 1 : rc));
1491
1492 unlock2:
1493         dt_write_unlock(env, orphan);
1494
1495 stop:
1496         rc1 = dt_trans_stop(env, dev, th);
1497         if (rc1 != 0 && rc > 0)
1498                 rc = rc1;
1499
1500 unlock1:
1501         lfsck_unlock(llh);
1502
1503 log:
1504         CDEBUG(D_LFSCK, "%s: namespace LFSCK create orphan dir for "
1505                "the object "DFID", name = %s: rc = %d\n",
1506                lfsck_lfsck2name(lfsck), PFID(cfid),
1507                cname->ln_name != NULL ? cname->ln_name : "<NULL>", rc);
1508
1509         if (parent != NULL && !IS_ERR(parent) && parent != lfsck->li_lpf_obj)
1510                 lfsck_object_put(env, parent);
1511
1512         if (rc != 0)
1513                 ns->ln_flags |= LF_INCONSISTENT;
1514
1515         return rc;
1516 }
1517
1518 /**
1519  * Remove the specified entry from the linkEA.
1520  *
1521  * Locate the linkEA entry with the given @cname and @pfid, then
1522  * remove this entry or the other entries those are repeated with
1523  * this entry.
1524  *
1525  * \param[in] env       pointer to the thread context
1526  * \param[in] com       pointer to the lfsck component
1527  * \param[in] obj       pointer to the dt_object to be handled
1528  * \param[in,out]ldata  pointer to the buffer that holds the linkEA
1529  * \param[in] cname     the name for the child in the parent directory
1530  * \param[in] pfid      the parent directory's FID for the linkEA
1531  * \param[in] next      if true, then remove the first found linkEA
1532  *                      entry, and move the ldata->ld_lee to next entry
1533  *
1534  * \retval              positive number for repaired cases
1535  * \retval              0 if nothing to be repaired
1536  * \retval              negative error number on failure
1537  */
1538 static int lfsck_namespace_shrink_linkea(const struct lu_env *env,
1539                                          struct lfsck_component *com,
1540                                          struct dt_object *obj,
1541                                          struct linkea_data *ldata,
1542                                          struct lu_name *cname,
1543                                          struct lu_fid *pfid,
1544                                          bool next)
1545 {
1546         struct lfsck_instance           *lfsck     = com->lc_lfsck;
1547         struct dt_device                *dev       = lfsck_obj2dev(obj);
1548         struct lfsck_bookmark           *bk        = &lfsck->li_bookmark_ram;
1549         struct thandle                  *th        = NULL;
1550         struct lustre_handle             lh        = { 0 };
1551         struct linkea_data               ldata_new = { NULL };
1552         struct lu_buf                    linkea_buf;
1553         int                              rc        = 0;
1554         ENTRY;
1555
1556         rc = lfsck_ibits_lock(env, lfsck, obj, &lh,
1557                               MDS_INODELOCK_UPDATE | MDS_INODELOCK_XATTR,
1558                               LCK_EX);
1559         if (rc != 0)
1560                 GOTO(log, rc);
1561
1562         if (next)
1563                 linkea_del_buf(ldata, cname);
1564         else
1565                 lfsck_namespace_filter_linkea_entry(ldata, cname, pfid,
1566                                                     true);
1567         lfsck_buf_init(&linkea_buf, ldata->ld_buf->lb_buf,
1568                        ldata->ld_leh->leh_len);
1569
1570 again:
1571         th = dt_trans_create(env, dev);
1572         if (IS_ERR(th))
1573                 GOTO(unlock1, rc = PTR_ERR(th));
1574
1575         rc = dt_declare_xattr_set(env, obj, &linkea_buf,
1576                                   XATTR_NAME_LINK, 0, th);
1577         if (rc != 0)
1578                 GOTO(stop, rc);
1579
1580         rc = dt_trans_start_local(env, dev, th);
1581         if (rc != 0)
1582                 GOTO(stop, rc);
1583
1584         dt_write_lock(env, obj, 0);
1585         if (unlikely(lfsck_is_dead_obj(obj)))
1586                 GOTO(unlock2, rc = -ENOENT);
1587
1588         rc = lfsck_links_read2(env, obj, &ldata_new);
1589         if (rc != 0)
1590                 GOTO(unlock2, rc);
1591
1592         /* The specified linkEA entry has been removed by race. */
1593         rc = linkea_links_find(&ldata_new, cname, pfid);
1594         if (rc != 0)
1595                 GOTO(unlock2, rc = 0);
1596
1597         if (bk->lb_param & LPF_DRYRUN)
1598                 GOTO(unlock2, rc = 1);
1599
1600         if (next)
1601                 linkea_del_buf(&ldata_new, cname);
1602         else
1603                 lfsck_namespace_filter_linkea_entry(&ldata_new, cname, pfid,
1604                                                     true);
1605
1606         if (linkea_buf.lb_len < ldata_new.ld_leh->leh_len) {
1607                 dt_write_unlock(env, obj);
1608                 dt_trans_stop(env, dev, th);
1609                 lfsck_buf_init(&linkea_buf, ldata_new.ld_buf->lb_buf,
1610                                ldata_new.ld_leh->leh_len);
1611                 goto again;
1612         }
1613
1614         lfsck_buf_init(&linkea_buf, ldata_new.ld_buf->lb_buf,
1615                        ldata_new.ld_leh->leh_len);
1616         rc = dt_xattr_set(env, obj, &linkea_buf, XATTR_NAME_LINK, 0, th);
1617
1618         GOTO(unlock2, rc = (rc == 0 ? 1 : rc));
1619
1620 unlock2:
1621         dt_write_unlock(env, obj);
1622
1623 stop:
1624         dt_trans_stop(env, dev, th);
1625
1626 unlock1:
1627         lfsck_ibits_unlock(&lh, LCK_EX);
1628
1629 log:
1630         CDEBUG(D_LFSCK, "%s: namespace LFSCK remove %s linkEA entry "
1631                "for the object: "DFID", parent "DFID", name %.*s\n",
1632                lfsck_lfsck2name(lfsck), next ? "invalid" : "redundant",
1633                PFID(lfsck_dto2fid(obj)), PFID(pfid), cname->ln_namelen,
1634                cname->ln_name);
1635
1636         if (rc != 0) {
1637                 struct lfsck_namespace *ns = com->lc_file_ram;
1638
1639                 ns->ln_flags |= LF_INCONSISTENT;
1640         }
1641
1642         return rc;
1643 }
1644
1645 /**
1646  * Conditionally remove the specified entry from the linkEA.
1647  *
1648  * Take the parent lock firstly, then check whether the specified
1649  * name entry exists or not: if yes, do nothing; otherwise, call
1650  * lfsck_namespace_shrink_linkea() to remove the linkea entry.
1651  *
1652  * \param[in] env       pointer to the thread context
1653  * \param[in] com       pointer to the lfsck component
1654  * \param[in] parent    pointer to the parent directory
1655  * \param[in] child     pointer to the child object that holds the linkEA
1656  * \param[in,out]ldata  pointer to the buffer that holds the linkEA
1657  * \param[in] cname     the name for the child in the parent directory
1658  * \param[in] pfid      the parent directory's FID for the linkEA
1659  *
1660  * \retval              positive number for repaired cases
1661  * \retval              0 if nothing to be repaired
1662  * \retval              negative error number on failure
1663  */
1664 static int lfsck_namespace_shrink_linkea_cond(const struct lu_env *env,
1665                                               struct lfsck_component *com,
1666                                               struct dt_object *parent,
1667                                               struct dt_object *child,
1668                                               struct linkea_data *ldata,
1669                                               struct lu_name *cname,
1670                                               struct lu_fid *pfid)
1671 {
1672         struct lfsck_thread_info *info  = lfsck_env_info(env);
1673         struct lu_fid            *cfid  = &info->lti_fid3;
1674         struct lfsck_lock_handle *llh   = &info->lti_llh;
1675         int                       rc;
1676         ENTRY;
1677
1678         rc = lfsck_lock(env, com->lc_lfsck, parent, cname->ln_name, llh,
1679                         MDS_INODELOCK_UPDATE, LCK_PR);
1680         if (rc != 0)
1681                 RETURN(rc);
1682
1683         dt_read_lock(env, parent, 0);
1684         if (unlikely(lfsck_is_dead_obj(parent))) {
1685                 dt_read_unlock(env, parent);
1686                 lfsck_unlock(llh);
1687                 rc = lfsck_namespace_shrink_linkea(env, com, child, ldata,
1688                                                    cname, pfid, true);
1689
1690                 RETURN(rc);
1691         }
1692
1693         rc = dt_lookup(env, parent, (struct dt_rec *)cfid,
1694                        (const struct dt_key *)cname->ln_name);
1695         dt_read_unlock(env, parent);
1696
1697         /* It is safe to release the ldlm lock, because when the logic come
1698          * here, we have got all the needed information above whether the
1699          * linkEA entry is valid or not. It is not important that others
1700          * may add new linkEA entry after the ldlm lock released. If other
1701          * has removed the specified linkEA entry by race, then it is OK,
1702          * because the subsequent lfsck_namespace_shrink_linkea() can handle
1703          * such case. */
1704         lfsck_unlock(llh);
1705         if (rc == -ENOENT) {
1706                 rc = lfsck_namespace_shrink_linkea(env, com, child, ldata,
1707                                                    cname, pfid, true);
1708
1709                 RETURN(rc);
1710         }
1711
1712         if (rc != 0)
1713                 RETURN(rc);
1714
1715         /* The LFSCK just found some internal status of cross-MDTs
1716          * create operation. That is normal. */
1717         if (lu_fid_eq(cfid, lfsck_dto2fid(child))) {
1718                 linkea_next_entry(ldata);
1719
1720                 RETURN(0);
1721         }
1722
1723         rc = lfsck_namespace_shrink_linkea(env, com, child, ldata, cname,
1724                                            pfid, true);
1725
1726         RETURN(rc);
1727 }
1728
1729 /**
1730  * Conditionally replace name entry in the parent.
1731  *
1732  * As required, the LFSCK may re-create the lost MDT-object for dangling
1733  * name entry, but such repairing may be wrong because of bad FID in the
1734  * name entry. As the LFSCK processing, the real MDT-object may be found,
1735  * then the LFSCK should check whether the former re-created MDT-object
1736  * has been modified or not, if not, then destroy it and update the name
1737  * entry in the parent to reference the real MDT-object.
1738  *
1739  * \param[in] env       pointer to the thread context
1740  * \param[in] com       pointer to the lfsck component
1741  * \param[in] parent    pointer to the parent directory
1742  * \param[in] child     pointer to the MDT-object that may be the real
1743  *                      MDT-object corresponding to the name entry in parent
1744  * \param[in] cfid      the current FID in the name entry
1745  * \param[in] cname     contains the name of the child in the parent directory
1746  *
1747  * \retval              positive number for repaired cases
1748  * \retval              0 if nothing to be repaired
1749  * \retval              negative error number on failure
1750  */
1751 static int lfsck_namespace_replace_cond(const struct lu_env *env,
1752                                         struct lfsck_component *com,
1753                                         struct dt_object *parent,
1754                                         struct dt_object *child,
1755                                         const struct lu_fid *cfid,
1756                                         const struct lu_name *cname)
1757 {
1758         struct lfsck_thread_info        *info   = lfsck_env_info(env);
1759         struct lu_attr                  *la     = &info->lti_la;
1760         struct dt_insert_rec            *rec    = &info->lti_dt_rec;
1761         struct lu_fid                    tfid;
1762         struct lfsck_instance           *lfsck  = com->lc_lfsck;
1763         /* The child and its name may be on different MDTs. */
1764         struct dt_device                *dev    = lfsck->li_next;
1765         const char                      *name   = cname->ln_name;
1766         const struct lu_fid             *pfid   = lfsck_dto2fid(parent);
1767         struct dt_object                *cobj   = NULL;
1768         struct lfsck_lock_handle        *pllh   = &info->lti_llh;
1769         struct lustre_handle             clh    = { 0 };
1770         struct linkea_data               ldata  = { NULL };
1771         struct thandle                  *th     = NULL;
1772         bool                             exist  = true;
1773         int                              rc     = 0;
1774         ENTRY;
1775
1776         /* @parent/@child may be based on lfsck->li_bottom,
1777          * but here we need the object based on the lfsck->li_next. */
1778
1779         parent = lfsck_object_locate(dev, parent);
1780         if (IS_ERR(parent))
1781                 GOTO(log, rc = PTR_ERR(parent));
1782
1783         if (unlikely(!dt_try_as_dir(env, parent)))
1784                 GOTO(log, rc = -ENOTDIR);
1785
1786         rc = lfsck_lock(env, lfsck, parent, name, pllh,
1787                         MDS_INODELOCK_UPDATE, LCK_PW);
1788         if (rc != 0)
1789                 GOTO(log, rc);
1790
1791         if (!fid_is_sane(cfid)) {
1792                 exist = false;
1793                 goto replace;
1794         }
1795
1796         cobj = lfsck_object_find_by_dev(env, dev, cfid);
1797         if (IS_ERR(cobj)) {
1798                 rc = PTR_ERR(cobj);
1799                 if (rc == -ENOENT) {
1800                         exist = false;
1801                         goto replace;
1802                 }
1803
1804                 GOTO(log, rc);
1805         }
1806
1807         if (!dt_object_exists(cobj)) {
1808                 exist = false;
1809                 goto replace;
1810         }
1811
1812         rc = dt_lookup(env, parent, (struct dt_rec *)&tfid,
1813                        (const struct dt_key *)name);
1814         if (rc == -ENOENT) {
1815                 exist = false;
1816                 goto replace;
1817         }
1818
1819         if (rc != 0)
1820                 GOTO(log, rc);
1821
1822         /* Someone changed the name entry, cannot replace it. */
1823         if (!lu_fid_eq(cfid, &tfid))
1824                 GOTO(log, rc = 0);
1825
1826         /* lock the object to be destroyed. */
1827         rc = lfsck_ibits_lock(env, lfsck, cobj, &clh,
1828                               MDS_INODELOCK_UPDATE |
1829                               MDS_INODELOCK_UPDATE | MDS_INODELOCK_XATTR,
1830                               LCK_EX);
1831         if (rc != 0)
1832                 GOTO(log, rc);
1833
1834         if (unlikely(lfsck_is_dead_obj(cobj))) {
1835                 exist = false;
1836                 goto replace;
1837         }
1838
1839         rc = dt_attr_get(env, cobj, la);
1840         if (rc != 0)
1841                 GOTO(log, rc);
1842
1843         /* The object has been modified by other(s), or it is not created by
1844          * LFSCK, the two cases are indistinguishable. So cannot replace it. */
1845         if (la->la_ctime != 0)
1846                 GOTO(log, rc);
1847
1848         if (S_ISREG(la->la_mode)) {
1849                 rc = dt_xattr_get(env, cobj, &LU_BUF_NULL, XATTR_NAME_LOV);
1850                 /* If someone has created related OST-object(s),
1851                  * then keep it. */
1852                 if ((rc > 0) || (rc < 0 && rc != -ENODATA))
1853                         GOTO(log, rc = (rc > 0 ? 0 : rc));
1854         }
1855
1856 replace:
1857         dt_read_lock(env, child, 0);
1858         rc = lfsck_links_read2(env, child, &ldata);
1859         dt_read_unlock(env, child);
1860
1861         /* Someone changed the child, no need to replace. */
1862         if (rc == -ENODATA)
1863                 GOTO(log, rc = 0);
1864
1865         if (rc != 0)
1866                 GOTO(log, rc);
1867
1868         rc = linkea_links_find(&ldata, cname, pfid);
1869         /* Someone moved the child, no need to replace. */
1870         if (rc != 0)
1871                 GOTO(log, rc = 0);
1872
1873         if (lfsck->li_bookmark_ram.lb_param & LPF_DRYRUN)
1874                 GOTO(log, rc = 1);
1875
1876         th = dt_trans_create(env, dev);
1877         if (IS_ERR(th))
1878                 GOTO(log, rc = PTR_ERR(th));
1879
1880         if (exist) {
1881                 rc = dt_declare_destroy(env, cobj, th);
1882                 if (rc != 0)
1883                         GOTO(stop, rc);
1884         }
1885
1886         rc = dt_declare_delete(env, parent, (const struct dt_key *)name, th);
1887         if (rc != 0)
1888                 GOTO(stop, rc);
1889
1890         rec->rec_type = S_IFDIR;
1891         rec->rec_fid = lfsck_dto2fid(child);
1892         rc = dt_declare_insert(env, parent, (const struct dt_rec *)rec,
1893                                (const struct dt_key *)name, th);
1894         if (rc != 0)
1895                 GOTO(stop, rc);
1896
1897         rc = dt_trans_start_local(env, dev, th);
1898         if (rc != 0)
1899                 GOTO(stop, rc);
1900
1901         if (exist) {
1902                 rc = dt_destroy(env, cobj, th);
1903                 if (rc != 0)
1904                         GOTO(stop, rc);
1905         }
1906
1907         /* The old name entry maybe not exist. */
1908         rc = dt_delete(env, parent, (const struct dt_key *)name, th);
1909         if (rc != 0 && rc != -ENOENT)
1910                 GOTO(stop, rc);
1911
1912         rc = dt_insert(env, parent, (const struct dt_rec *)rec,
1913                        (const struct dt_key *)name, th, 1);
1914
1915         GOTO(stop, rc = (rc == 0 ? 1 : rc));
1916
1917 stop:
1918         dt_trans_stop(env, dev, th);
1919
1920 log:
1921         lfsck_ibits_unlock(&clh, LCK_EX);
1922         lfsck_unlock(pllh);
1923
1924         if (cobj != NULL && !IS_ERR(cobj))
1925                 lfsck_object_put(env, cobj);
1926
1927         CDEBUG(D_LFSCK, "%s: namespace LFSCK conditionally destroy the "
1928                "object "DFID" because of conflict with the object "DFID
1929                " under the parent "DFID" with name %s: rc = %d\n",
1930                lfsck_lfsck2name(lfsck), PFID(cfid),
1931                PFID(lfsck_dto2fid(child)), PFID(pfid), name, rc);
1932
1933         return rc;
1934 }
1935
1936 /**
1937  * Overwrite the linkEA for the object with the given ldata.
1938  *
1939  * The caller should take the ldlm lock before the calling.
1940  *
1941  * \param[in] env       pointer to the thread context
1942  * \param[in] com       pointer to the lfsck component
1943  * \param[in] obj       pointer to the dt_object to be handled
1944  * \param[in] ldata     pointer to the new linkEA data
1945  *
1946  * \retval              positive number for repaired cases
1947  * \retval              0 if nothing to be repaired
1948  * \retval              negative error number on failure
1949  */
1950 int lfsck_namespace_rebuild_linkea(const struct lu_env *env,
1951                                    struct lfsck_component *com,
1952                                    struct dt_object *obj,
1953                                    struct linkea_data *ldata)
1954 {
1955         struct lfsck_instance           *lfsck  = com->lc_lfsck;
1956         struct dt_device                *dev    = lfsck_obj2dev(obj);
1957         struct thandle                  *th     = NULL;
1958         struct lu_buf                    linkea_buf;
1959         int                              rc     = 0;
1960         ENTRY;
1961
1962         th = dt_trans_create(env, dev);
1963         if (IS_ERR(th))
1964                 GOTO(log, rc = PTR_ERR(th));
1965
1966         lfsck_buf_init(&linkea_buf, ldata->ld_buf->lb_buf,
1967                        ldata->ld_leh->leh_len);
1968         rc = dt_declare_xattr_set(env, obj, &linkea_buf,
1969                                   XATTR_NAME_LINK, 0, th);
1970         if (rc != 0)
1971                 GOTO(stop, rc);
1972
1973         rc = dt_trans_start_local(env, dev, th);
1974         if (rc != 0)
1975                 GOTO(stop, rc);
1976
1977         dt_write_lock(env, obj, 0);
1978         if (unlikely(lfsck_is_dead_obj(obj)))
1979                 GOTO(unlock, rc = 0);
1980
1981         if (lfsck->li_bookmark_ram.lb_param & LPF_DRYRUN)
1982                 GOTO(unlock, rc = 1);
1983
1984         rc = dt_xattr_set(env, obj, &linkea_buf,
1985                           XATTR_NAME_LINK, 0, th);
1986
1987         GOTO(unlock, rc = (rc == 0 ? 1 : rc));
1988
1989 unlock:
1990         dt_write_unlock(env, obj);
1991
1992 stop:
1993         dt_trans_stop(env, dev, th);
1994
1995 log:
1996         CDEBUG(D_LFSCK, "%s: namespace LFSCK rebuild linkEA for the "
1997                "object "DFID": rc = %d\n",
1998                lfsck_lfsck2name(lfsck), PFID(lfsck_dto2fid(obj)), rc);
1999
2000         if (rc != 0) {
2001                 struct lfsck_namespace *ns = com->lc_file_ram;
2002
2003                 ns->ln_flags |= LF_INCONSISTENT;
2004         }
2005
2006         return rc;
2007 }
2008
2009 /**
2010  * Repair invalid name entry.
2011  *
2012  * If the name entry contains invalid information, such as bad file type
2013  * or (and) corrupted object FID, then either remove the name entry or
2014  * udpate the name entry with the given (right) information.
2015  *
2016  * \param[in] env       pointer to the thread context
2017  * \param[in] com       pointer to the lfsck component
2018  * \param[in] parent    pointer to the parent directory
2019  * \param[in] child     pointer to the object referenced by the name entry
2020  * \param[in] name      the old name of the child under the parent directory
2021  * \param[in] name2     the new name of the child under the parent directory
2022  * \param[in] type      the type claimed by the name entry
2023  * \param[in] update    update the name entry if true; otherwise, remove it
2024  * \param[in] dec       decrease the parent nlink count if true
2025  *
2026  * \retval              positive number for repaired successfully
2027  * \retval              0 if nothing to be repaired
2028  * \retval              negative error number on failure
2029  */
2030 int lfsck_namespace_repair_dirent(const struct lu_env *env,
2031                                   struct lfsck_component *com,
2032                                   struct dt_object *parent,
2033                                   struct dt_object *child,
2034                                   const char *name, const char *name2,
2035                                   __u16 type, bool update, bool dec)
2036 {
2037         struct lfsck_thread_info        *info   = lfsck_env_info(env);
2038         struct dt_insert_rec            *rec    = &info->lti_dt_rec;
2039         const struct lu_fid             *pfid   = lfsck_dto2fid(parent);
2040         const struct lu_fid             *cfid   = lfsck_dto2fid(child);
2041         struct lu_fid                    tfid;
2042         struct lfsck_instance           *lfsck  = com->lc_lfsck;
2043         struct dt_device                *dev    = lfsck->li_next;
2044         struct thandle                  *th     = NULL;
2045         struct lfsck_lock_handle        *llh    = &info->lti_llh;
2046         struct lustre_handle             lh     = { 0 };
2047         int                              rc     = 0;
2048         ENTRY;
2049
2050         parent = lfsck_object_locate(dev, parent);
2051         if (IS_ERR(parent))
2052                 GOTO(log, rc = PTR_ERR(parent));
2053
2054         if (unlikely(!dt_try_as_dir(env, parent)))
2055                 GOTO(log, rc = -ENOTDIR);
2056
2057         if (!update || strcmp(name, name2) == 0)
2058                 rc = lfsck_lock(env, lfsck, parent, name, llh,
2059                                 MDS_INODELOCK_UPDATE, LCK_PW);
2060         else
2061                 rc = lfsck_ibits_lock(env, lfsck, parent, &lh,
2062                                       MDS_INODELOCK_UPDATE, LCK_PW);
2063         if (rc != 0)
2064                 GOTO(log, rc);
2065
2066         th = dt_trans_create(env, dev);
2067         if (IS_ERR(th))
2068                 GOTO(unlock1, rc = PTR_ERR(th));
2069
2070         rc = dt_declare_delete(env, parent, (const struct dt_key *)name, th);
2071         if (rc != 0)
2072                 GOTO(stop, rc);
2073
2074         if (update) {
2075                 rec->rec_type = lfsck_object_type(child) & S_IFMT;
2076                 rec->rec_fid = cfid;
2077                 rc = dt_declare_insert(env, parent,
2078                                        (const struct dt_rec *)rec,
2079                                        (const struct dt_key *)name2, th);
2080                 if (rc != 0)
2081                         GOTO(stop, rc);
2082         }
2083
2084         if (dec) {
2085                 rc = dt_declare_ref_del(env, parent, th);
2086                 if (rc != 0)
2087                         GOTO(stop, rc);
2088         }
2089
2090         rc = dt_trans_start_local(env, dev, th);
2091         if (rc != 0)
2092                 GOTO(stop, rc);
2093
2094
2095         dt_write_lock(env, parent, 0);
2096         rc = dt_lookup(env, parent, (struct dt_rec *)&tfid,
2097                        (const struct dt_key *)name);
2098         /* Someone has removed the bad name entry by race. */
2099         if (rc == -ENOENT)
2100                 GOTO(unlock2, rc = 0);
2101
2102         if (rc != 0)
2103                 GOTO(unlock2, rc);
2104
2105         /* Someone has removed the bad name entry and reused it for other
2106          * object by race. */
2107         if (!lu_fid_eq(&tfid, cfid))
2108                 GOTO(unlock2, rc = 0);
2109
2110         if (lfsck->li_bookmark_ram.lb_param & LPF_DRYRUN)
2111                 GOTO(unlock2, rc = 1);
2112
2113         rc = dt_delete(env, parent, (const struct dt_key *)name, th);
2114         if (rc != 0)
2115                 GOTO(unlock2, rc);
2116
2117         if (update) {
2118                 rc = dt_insert(env, parent,
2119                                (const struct dt_rec *)rec,
2120                                (const struct dt_key *)name2, th, 1);
2121                 if (rc != 0)
2122                         GOTO(unlock2, rc);
2123         }
2124
2125         if (dec) {
2126                 rc = dt_ref_del(env, parent, th);
2127                 if (rc != 0)
2128                         GOTO(unlock2, rc);
2129         }
2130
2131         GOTO(unlock2, rc = (rc == 0 ? 1 : rc));
2132
2133 unlock2:
2134         dt_write_unlock(env, parent);
2135
2136 stop:
2137         dt_trans_stop(env, dev, th);
2138
2139         /* We are not sure whether the child will become orphan or not.
2140          * Record it in the LFSCK trace file for further checking in
2141          * the second-stage scanning. */
2142         if (!update && !dec && rc == 0)
2143                 lfsck_namespace_trace_update(env, com, cfid,
2144                                              LNTF_CHECK_LINKEA, true);
2145
2146 unlock1:
2147         /* It is harmless even if unlock the unused lock_handle */
2148         lfsck_ibits_unlock(&lh, LCK_PW);
2149         lfsck_unlock(llh);
2150
2151 log:
2152         CDEBUG(D_LFSCK, "%s: namespace LFSCK assistant found bad name "
2153                "entry for: parent "DFID", child "DFID", name %s, type "
2154                "in name entry %o, type claimed by child %o. repair it "
2155                "by %s with new name2 %s: rc = %d\n",
2156                lfsck_lfsck2name(lfsck), PFID(pfid), PFID(cfid),
2157                name, type, update ? lfsck_object_type(child) : 0,
2158                update ? "updating" : "removing", name2, rc);
2159
2160         if (rc != 0) {
2161                 struct lfsck_namespace *ns = com->lc_file_ram;
2162
2163                 ns->ln_flags |= LF_INCONSISTENT;
2164         }
2165
2166         return rc;
2167 }
2168
2169 /**
2170  * Update the ".." name entry for the given object.
2171  *
2172  * The object's ".." is corrupted, this function will update the ".." name
2173  * entry with the given pfid, and the linkEA with the given ldata.
2174  *
2175  * The caller should take the ldlm lock before the calling.
2176  *
2177  * \param[in] env       pointer to the thread context
2178  * \param[in] com       pointer to the lfsck component
2179  * \param[in] obj       pointer to the dt_object to be handled
2180  * \param[in] pfid      the new fid for the object's ".." name entry
2181  * \param[in] cname     the name for the @obj in the parent directory
2182  *
2183  * \retval              positive number for repaired cases
2184  * \retval              0 if nothing to be repaired
2185  * \retval              negative error number on failure
2186  */
2187 static int lfsck_namespace_repair_unmatched_pairs(const struct lu_env *env,
2188                                                   struct lfsck_component *com,
2189                                                   struct dt_object *obj,
2190                                                   const struct lu_fid *pfid,
2191                                                   struct lu_name *cname)
2192 {
2193         struct lfsck_thread_info        *info   = lfsck_env_info(env);
2194         struct dt_insert_rec            *rec    = &info->lti_dt_rec;
2195         struct lfsck_instance           *lfsck  = com->lc_lfsck;
2196         struct dt_device                *dev    = lfsck_obj2dev(obj);
2197         struct thandle                  *th     = NULL;
2198         struct linkea_data               ldata  = { NULL };
2199         struct lu_buf                    linkea_buf;
2200         int                              rc     = 0;
2201         ENTRY;
2202
2203         LASSERT(!dt_object_remote(obj));
2204         LASSERT(S_ISDIR(lfsck_object_type(obj)));
2205
2206         rc = linkea_data_new(&ldata, &info->lti_big_buf);
2207         if (rc != 0)
2208                 GOTO(log, rc);
2209
2210         rc = linkea_add_buf(&ldata, cname, pfid);
2211         if (rc != 0)
2212                 GOTO(log, rc);
2213
2214         lfsck_buf_init(&linkea_buf, ldata.ld_buf->lb_buf,
2215                        ldata.ld_leh->leh_len);
2216
2217         th = dt_trans_create(env, dev);
2218         if (IS_ERR(th))
2219                 GOTO(log, rc = PTR_ERR(th));
2220
2221         rc = dt_declare_delete(env, obj, (const struct dt_key *)dotdot, th);
2222         if (rc != 0)
2223                 GOTO(stop, rc);
2224
2225         rec->rec_type = S_IFDIR;
2226         rec->rec_fid = pfid;
2227         rc = dt_declare_insert(env, obj, (const struct dt_rec *)rec,
2228                                (const struct dt_key *)dotdot, th);
2229         if (rc != 0)
2230                 GOTO(stop, rc);
2231
2232         rc = dt_declare_xattr_set(env, obj, &linkea_buf,
2233                                   XATTR_NAME_LINK, 0, th);
2234         if (rc != 0)
2235                 GOTO(stop, rc);
2236
2237         rc = dt_trans_start_local(env, dev, th);
2238         if (rc != 0)
2239                 GOTO(stop, rc);
2240
2241         dt_write_lock(env, obj, 0);
2242         if (unlikely(lfsck_is_dead_obj(obj)))
2243                 GOTO(unlock, rc = 0);
2244
2245         if (lfsck->li_bookmark_ram.lb_param & LPF_DRYRUN)
2246                 GOTO(unlock, rc = 1);
2247
2248         /* The old ".." name entry maybe not exist. */
2249         dt_delete(env, obj, (const struct dt_key *)dotdot, th);
2250
2251         rc = dt_insert(env, obj, (const struct dt_rec *)rec,
2252                        (const struct dt_key *)dotdot, th, 1);
2253         if (rc != 0)
2254                 GOTO(unlock, rc);
2255
2256         rc = dt_xattr_set(env, obj, &linkea_buf,
2257                           XATTR_NAME_LINK, 0, th);
2258
2259         GOTO(unlock, rc = (rc == 0 ? 1 : rc));
2260
2261 unlock:
2262         dt_write_unlock(env, obj);
2263
2264 stop:
2265         dt_trans_stop(env, dev, th);
2266
2267 log:
2268         CDEBUG(D_LFSCK, "%s: namespace LFSCK rebuild dotdot name entry for "
2269                "the object "DFID", new parent "DFID": rc = %d\n",
2270                lfsck_lfsck2name(lfsck), PFID(lfsck_dto2fid(obj)),
2271                PFID(pfid), rc);
2272
2273         if (rc != 0) {
2274                 struct lfsck_namespace *ns = com->lc_file_ram;
2275
2276                 ns->ln_flags |= LF_INCONSISTENT;
2277         }
2278
2279         return rc;
2280 }
2281
2282 /**
2283  * Handle orphan @obj during Double Scan Directory.
2284  *
2285  * Remove the @obj's current (invalid) linkEA entries, and insert
2286  * it in the directory .lustre/lost+found/MDTxxxx/ with the name:
2287  * ${FID}-${PFID}-D-${conflict_version}
2288  *
2289  * The caller should take the ldlm lock before the calling.
2290  *
2291  * \param[in] env       pointer to the thread context
2292  * \param[in] com       pointer to the lfsck component
2293  * \param[in] obj       pointer to the orphan object to be handled
2294  * \param[in] pfid      the new fid for the object's ".." name entry
2295  * \param[in,out] lh    ldlm lock handler for the given @obj
2296  * \param[out] type     to tell the caller what the inconsistency is
2297  *
2298  * \retval              positive number for repaired cases
2299  * \retval              0 if nothing to be repaired
2300  * \retval              negative error number on failure
2301  */
2302 static int
2303 lfsck_namespace_dsd_orphan(const struct lu_env *env,
2304                            struct lfsck_component *com,
2305                            struct dt_object *obj,
2306                            const struct lu_fid *pfid,
2307                            struct lustre_handle *lh,
2308                            enum lfsck_namespace_inconsistency_type *type)
2309 {
2310         struct lfsck_thread_info *info = lfsck_env_info(env);
2311         struct lfsck_namespace   *ns   = com->lc_file_ram;
2312         int                       rc;
2313         ENTRY;
2314
2315         /* Remove the unrecognized linkEA. */
2316         rc = lfsck_namespace_links_remove(env, com, obj);
2317         lfsck_ibits_unlock(lh, LCK_EX);
2318         if (rc < 0 && rc != -ENODATA)
2319                 RETURN(rc);
2320
2321         *type = LNIT_MUL_REF;
2322
2323         /* If the LFSCK is marked as LF_INCOMPLETE, then means some MDT has
2324          * ever tried to verify some remote MDT-object that resides on this
2325          * MDT, but this MDT failed to respond such request. So means there
2326          * may be some remote name entry on other MDT that references this
2327          * object with another name, so we cannot know whether this linkEA
2328          * is valid or not. So keep it there and maybe resolved when next
2329          * LFSCK run. */
2330         if (ns->ln_flags & LF_INCOMPLETE)
2331                 RETURN(0);
2332
2333         /* The unique linkEA is invalid, even if the ".." name entry may be
2334          * valid, we still cannot know via which name entry this directory
2335          * will be referenced. Then handle it as pure orphan. */
2336         snprintf(info->lti_tmpbuf, sizeof(info->lti_tmpbuf),
2337                  "-"DFID, PFID(pfid));
2338         rc = lfsck_namespace_insert_orphan(env, com, obj,
2339                                            info->lti_tmpbuf, "D", NULL);
2340
2341         RETURN(rc);
2342 }
2343
2344 /**
2345  * Double Scan Directory object for single linkEA entry case.
2346  *
2347  * The given @child has unique linkEA entry. If the linkEA entry is valid,
2348  * then check whether the name is in the namespace or not, if not, add the
2349  * missing name entry back to namespace. If the linkEA entry is invalid,
2350  * then remove it and insert the @child in the .lustre/lost+found/MDTxxxx/
2351  * as an orphan.
2352  *
2353  * \param[in] env       pointer to the thread context
2354  * \param[in] com       pointer to the lfsck component
2355  * \param[in] child     pointer to the directory to be double scanned
2356  * \param[in] pfid      the FID corresponding to the ".." entry
2357  * \param[in] ldata     pointer to the linkEA data for the given @child
2358  * \param[in,out] lh    ldlm lock handler for the given @child
2359  * \param[out] type     to tell the caller what the inconsistency is
2360  * \param[in] retry     if found inconsistency, but the caller does not hold
2361  *                      ldlm lock on the @child, then set @retry as true
2362  *
2363  * \retval              positive number for repaired cases
2364  * \retval              0 if nothing to be repaired
2365  * \retval              negative error number on failure
2366  */
2367 static int
2368 lfsck_namespace_dsd_single(const struct lu_env *env,
2369                            struct lfsck_component *com,
2370                            struct dt_object *child,
2371                            const struct lu_fid *pfid,
2372                            struct linkea_data *ldata,
2373                            struct lustre_handle *lh,
2374                            enum lfsck_namespace_inconsistency_type *type,
2375                            bool *retry)
2376 {
2377         struct lfsck_thread_info *info          = lfsck_env_info(env);
2378         struct lu_name           *cname         = &info->lti_name;
2379         const struct lu_fid      *cfid          = lfsck_dto2fid(child);
2380         struct lu_fid             tfid;
2381         struct lfsck_namespace   *ns            = com->lc_file_ram;
2382         struct lfsck_instance    *lfsck         = com->lc_lfsck;
2383         struct dt_object         *parent        = NULL;
2384         struct lmv_mds_md_v1     *lmv;
2385         int                       rc            = 0;
2386         ENTRY;
2387
2388         lfsck_namespace_unpack_linkea_entry(ldata, cname, &tfid, info->lti_key);
2389         /* The unique linkEA entry with bad parent will be handled as orphan. */
2390         if (!fid_is_sane(&tfid)) {
2391                 if (!lustre_handle_is_used(lh) && retry != NULL)
2392                         *retry = true;
2393                 else
2394                         rc = lfsck_namespace_dsd_orphan(env, com, child,
2395                                                         pfid, lh, type);
2396
2397                 GOTO(out, rc);
2398         }
2399
2400         parent = lfsck_object_find_bottom(env, lfsck, &tfid);
2401         if (IS_ERR(parent))
2402                 GOTO(out, rc = PTR_ERR(parent));
2403
2404         /* We trust the unique linkEA entry in spite of whether it matches the
2405          * ".." name entry or not. Because even if the linkEA entry is wrong
2406          * and the ".." name entry is right, we still cannot know via which
2407          * name entry the child will be referenced, since all known entries
2408          * have been verified during the first-stage scanning. */
2409         if (!dt_object_exists(parent)) {
2410                 /* If the LFSCK is marked as LF_INCOMPLETE, then means some MDT
2411                  * has ever tried to verify some remote MDT-object that resides
2412                  * on this MDT, but this MDT failed to respond such request. So
2413                  * means there may be some remote name entry on other MDT that
2414                  * references this object with another name, so we cannot know
2415                  * whether this linkEA is valid or not. So keep it there and
2416                  * maybe resolved when next LFSCK run. */
2417                 if (ns->ln_flags & LF_INCOMPLETE)
2418                         GOTO(out, rc = 0);
2419
2420                 if (!lustre_handle_is_used(lh) && retry != NULL) {
2421                         *retry = true;
2422
2423                         GOTO(out, rc = 0);
2424                 }
2425
2426                 lfsck_ibits_unlock(lh, LCK_EX);
2427
2428 lost_parent:
2429                 lmv = &info->lti_lmv;
2430                 rc = lfsck_read_stripe_lmv(env, child, lmv);
2431                 if (rc != 0 && rc != -ENODATA)
2432                         GOTO(out, rc);
2433
2434                 if (rc == -ENODATA || lmv->lmv_magic != LMV_MAGIC_STRIPE) {
2435                         lmv = NULL;
2436                 } else if (lfsck_shard_name_to_index(env,
2437                                         cname->ln_name, cname->ln_namelen,
2438                                         S_IFDIR, cfid) < 0) {
2439                         /* It is an invalid name entry, we
2440                          * cannot trust the parent also. */
2441                         rc = lfsck_namespace_shrink_linkea(env, com, child,
2442                                                 ldata, cname, &tfid, true);
2443                         if (rc < 0)
2444                                 GOTO(out, rc);
2445
2446                         snprintf(info->lti_tmpbuf, sizeof(info->lti_tmpbuf),
2447                                  "-"DFID, PFID(pfid));
2448                         rc = lfsck_namespace_insert_orphan(env, com, child,
2449                                                 info->lti_tmpbuf, "S", NULL);
2450
2451                         GOTO(out, rc);
2452                 }
2453
2454                 /* Create the lost parent as an orphan. */
2455                 rc = lfsck_namespace_create_orphan_dir(env, com, parent, lmv);
2456                 if (rc >= 0) {
2457                         /* Add the missing name entry to the parent. */
2458                         rc = lfsck_namespace_insert_normal(env, com, parent,
2459                                                         child, cname->ln_name);
2460                         if (unlikely(rc == -EEXIST)) {
2461                                 /* Unfortunately, someone reused the name
2462                                  * under the parent by race. So we have
2463                                  * to remove the linkEA entry from
2464                                  * current child object. It means that the
2465                                  * LFSCK cannot recover the system
2466                                  * totally back to its original status,
2467                                  * but it is necessary to make the
2468                                  * current system to be consistent. */
2469                                 rc = lfsck_namespace_shrink_linkea(env,
2470                                                 com, child, ldata,
2471                                                 cname, &tfid, true);
2472                                 if (rc >= 0) {
2473                                         snprintf(info->lti_tmpbuf,
2474                                                  sizeof(info->lti_tmpbuf),
2475                                                  "-"DFID, PFID(pfid));
2476                                         rc = lfsck_namespace_insert_orphan(env,
2477                                                 com, child, info->lti_tmpbuf,
2478                                                 "D", NULL);
2479                                 }
2480                         }
2481                 }
2482
2483                 GOTO(out, rc);
2484         }
2485
2486         /* The unique linkEA entry with bad parent will be handled as orphan. */
2487         if (unlikely(!dt_try_as_dir(env, parent))) {
2488                 if (!lustre_handle_is_used(lh) && retry != NULL)
2489                         *retry = true;
2490                 else
2491                         rc = lfsck_namespace_dsd_orphan(env, com, child,
2492                                                         pfid, lh, type);
2493
2494                 GOTO(out, rc);
2495         }
2496
2497         rc = dt_lookup(env, parent, (struct dt_rec *)&tfid,
2498                        (const struct dt_key *)cname->ln_name);
2499         if (rc == -ENOENT) {
2500                 /* If the LFSCK is marked as LF_INCOMPLETE, then means some MDT
2501                  * has ever tried to verify some remote MDT-object that resides
2502                  * on this MDT, but this MDT failed to respond such request. So
2503                  * means there may be some remote name entry on other MDT that
2504                  * references this object with another name, so we cannot know
2505                  * whether this linkEA is valid or not. So keep it there and
2506                  * maybe resolved when next LFSCK run. */
2507                 if (ns->ln_flags & LF_INCOMPLETE)
2508                         GOTO(out, rc = 0);
2509
2510                 if (!lustre_handle_is_used(lh) && retry != NULL) {
2511                         *retry = true;
2512
2513                         GOTO(out, rc = 0);
2514                 }
2515
2516                 lfsck_ibits_unlock(lh, LCK_EX);
2517                 rc = lfsck_namespace_check_name(env, parent, child, cname);
2518                 if (rc == -ENOENT)
2519                         goto lost_parent;
2520
2521                 if (rc < 0)
2522                         GOTO(out, rc);
2523
2524                 /* It is an invalid name entry, drop it. */
2525                 if (unlikely(rc > 0)) {
2526                         rc = lfsck_namespace_shrink_linkea(env, com, child,
2527                                                 ldata, cname, &tfid, true);
2528                         if (rc >= 0) {
2529                                 snprintf(info->lti_tmpbuf,
2530                                          sizeof(info->lti_tmpbuf),
2531                                          "-"DFID, PFID(pfid));
2532                                 rc = lfsck_namespace_insert_orphan(env, com,
2533                                         child, info->lti_tmpbuf, "D", NULL);
2534                         }
2535
2536                         GOTO(out, rc);
2537                 }
2538
2539                 /* Add the missing name entry back to the namespace. */
2540                 rc = lfsck_namespace_insert_normal(env, com, parent, child,
2541                                                    cname->ln_name);
2542                 if (unlikely(rc == -ESTALE))
2543                         /* It may happen when the remote object has been
2544                          * removed, but the local MDT is not aware of that. */
2545                         goto lost_parent;
2546
2547                 if (unlikely(rc == -EEXIST)) {
2548                         /* Unfortunately, someone reused the name under the
2549                          * parent by race. So we have to remove the linkEA
2550                          * entry from current child object. It means that the
2551                          * LFSCK cannot recover the system totally back to
2552                          * its original status, but it is necessary to make
2553                          * the current system to be consistent.
2554                          *
2555                          * It also may be because of the LFSCK found some
2556                          * internal status of create operation. Under such
2557                          * case, nothing to be done. */
2558                         rc = lfsck_namespace_shrink_linkea_cond(env, com,
2559                                         parent, child, ldata, cname, &tfid);
2560                         if (rc >= 0) {
2561                                 snprintf(info->lti_tmpbuf,
2562                                          sizeof(info->lti_tmpbuf),
2563                                          "-"DFID, PFID(pfid));
2564                                 rc = lfsck_namespace_insert_orphan(env, com,
2565                                         child, info->lti_tmpbuf, "D", NULL);
2566                         }
2567                 }
2568
2569                 GOTO(out, rc);
2570         }
2571
2572         if (rc != 0)
2573                 GOTO(out, rc);
2574
2575         if (!lu_fid_eq(&tfid, cfid)) {
2576                 if (!lustre_handle_is_used(lh) && retry != NULL) {
2577                         *retry = true;
2578
2579                         GOTO(out, rc = 0);
2580                 }
2581
2582                 lfsck_ibits_unlock(lh, LCK_EX);
2583                 /* The name entry references another MDT-object that
2584                  * may be created by the LFSCK for repairing dangling
2585                  * name entry. Try to replace it. */
2586                 rc = lfsck_namespace_replace_cond(env, com, parent, child,
2587                                                   &tfid, cname);
2588                 if (rc == 0)
2589                         rc = lfsck_namespace_dsd_orphan(env, com, child,
2590                                                         pfid, lh, type);
2591
2592                 GOTO(out, rc);
2593         }
2594
2595         if (fid_is_zero(pfid))
2596                 GOTO(out, rc = 0);
2597
2598         /* The ".." name entry is wrong, update it. */
2599         if (!lu_fid_eq(pfid, lfsck_dto2fid(parent))) {
2600                 if (!lustre_handle_is_used(lh) && retry != NULL) {
2601                         *retry = true;
2602
2603                         GOTO(out, rc = 0);
2604                 }
2605
2606                 *type = LNIT_UNMATCHED_PAIRS;
2607                 rc = lfsck_namespace_repair_unmatched_pairs(env, com, child,
2608                                                 lfsck_dto2fid(parent), cname);
2609         }
2610
2611         GOTO(out, rc);
2612
2613 out:
2614         if (parent != NULL && !IS_ERR(parent))
2615                 lfsck_object_put(env, parent);
2616
2617         return rc;
2618 }
2619
2620 /**
2621  * Double Scan Directory object for multiple linkEA entries case.
2622  *
2623  * The given @child has multiple linkEA entries. There is at most one linkEA
2624  * entry will be valid, all the others will be removed. Firstly, the function
2625  * will try to find out the linkEA entry for which the name entry exists under
2626  * the given parent (@pfid). If there is no linkEA entry that matches the given
2627  * ".." name entry, then tries to find out the first linkEA entry that both the
2628  * parent and the name entry exist to rebuild a new ".." name entry.
2629  *
2630  * \param[in] env       pointer to the thread context
2631  * \param[in] com       pointer to the lfsck component
2632  * \param[in] child     pointer to the directory to be double scanned
2633  * \param[in] pfid      the FID corresponding to the ".." entry
2634  * \param[in] ldata     pointer to the linkEA data for the given @child
2635  * \param[in,out] lh    ldlm lock handler for the given @child
2636  * \param[out] type     to tell the caller what the inconsistency is
2637  * \param[in] lpf       true if the ".." entry is under lost+found/MDTxxxx/
2638  *
2639  * \retval              positive number for repaired cases
2640  * \retval              0 if nothing to be repaired
2641  * \retval              negative error number on failure
2642  */
2643 static int
2644 lfsck_namespace_dsd_multiple(const struct lu_env *env,
2645                              struct lfsck_component *com,
2646                              struct dt_object *child,
2647                              const struct lu_fid *pfid,
2648                              struct linkea_data *ldata,
2649                              struct lustre_handle *lh,
2650                              enum lfsck_namespace_inconsistency_type *type,
2651                              bool lpf)
2652 {
2653         struct lfsck_thread_info *info          = lfsck_env_info(env);
2654         struct lu_name           *cname         = &info->lti_name;
2655         const struct lu_fid      *cfid          = lfsck_dto2fid(child);
2656         struct lu_fid            *pfid2         = &info->lti_fid3;
2657         struct lu_fid             tfid;
2658         struct lfsck_namespace   *ns            = com->lc_file_ram;
2659         struct lfsck_instance    *lfsck         = com->lc_lfsck;
2660         struct lfsck_bookmark    *bk            = &lfsck->li_bookmark_ram;
2661         struct dt_object         *parent        = NULL;
2662         struct linkea_data        ldata_new     = { NULL };
2663         int                       dirent_count  = 0;
2664         int                       linkea_count  = 0;
2665         int                       rc            = 0;
2666         bool                      once          = true;
2667         ENTRY;
2668
2669 again:
2670         while (ldata->ld_lee != NULL) {
2671                 lfsck_namespace_unpack_linkea_entry(ldata, cname, &tfid,
2672                                                     info->lti_key);
2673                 /* Drop repeated linkEA entries. */
2674                 lfsck_namespace_filter_linkea_entry(ldata, cname, &tfid, true);
2675                 /* Drop invalid linkEA entry. */
2676                 if (!fid_is_sane(&tfid)) {
2677                         linkea_del_buf(ldata, cname);
2678                         linkea_count++;
2679                         continue;
2680                 }
2681
2682                 /* If current dotdot is the .lustre/lost+found/MDTxxxx/,
2683                  * then it is possible that: the directry object has ever
2684                  * been lost, but its name entry was there. In the former
2685                  * LFSCK run, during the first-stage scanning, the LFSCK
2686                  * found the dangling name entry, but it did not recreate
2687                  * the lost object, and when moved to the second-stage
2688                  * scanning, some children objects of the lost directory
2689                  * object were found, then the LFSCK recreated such lost
2690                  * directory object as an orphan.
2691                  *
2692                  * When the LFSCK runs again, if the dangling name is still
2693                  * there, the LFSCK should move the orphan directory object
2694                  * back to the normal namespace. */
2695                 if (!lpf && !lu_fid_eq(pfid, &tfid) && once) {
2696                         linkea_next_entry(ldata);
2697                         continue;
2698                 }
2699
2700                 parent = lfsck_object_find_bottom(env, lfsck, &tfid);
2701                 if (IS_ERR(parent))
2702                         RETURN(PTR_ERR(parent));
2703
2704                 if (!dt_object_exists(parent)) {
2705                         lfsck_object_put(env, parent);
2706                         if (ldata->ld_leh->leh_reccount > 1) {
2707                                 /* If it is NOT the last linkEA entry, then
2708                                  * there is still other chance to make the
2709                                  * child to be visible via other parent, then
2710                                  * remove this linkEA entry. */
2711                                 linkea_del_buf(ldata, cname);
2712                                 linkea_count++;
2713                                 continue;
2714                         }
2715
2716                         break;
2717                 }
2718
2719                 /* The linkEA entry with bad parent will be removed. */
2720                 if (unlikely(!dt_try_as_dir(env, parent))) {
2721                         lfsck_object_put(env, parent);
2722                         linkea_del_buf(ldata, cname);
2723                         linkea_count++;
2724                         continue;
2725                 }
2726
2727                 rc = dt_lookup(env, parent, (struct dt_rec *)&tfid,
2728                                (const struct dt_key *)cname->ln_name);
2729                 *pfid2 = *lfsck_dto2fid(parent);
2730                 if (rc == -ENOENT) {
2731                         lfsck_object_put(env, parent);
2732                         linkea_next_entry(ldata);
2733                         continue;
2734                 }
2735
2736                 if (rc != 0) {
2737                         lfsck_object_put(env, parent);
2738
2739                         RETURN(rc);
2740                 }
2741
2742                 if (lu_fid_eq(&tfid, cfid)) {
2743                         lfsck_object_put(env, parent);
2744                         if (!lu_fid_eq(pfid, pfid2)) {
2745                                 *type = LNIT_UNMATCHED_PAIRS;
2746                                 rc = lfsck_namespace_repair_unmatched_pairs(env,
2747                                                 com, child, pfid2, cname);
2748
2749                                 RETURN(rc);
2750                         }
2751
2752 rebuild:
2753                         /* It is the most common case that we find the
2754                          * name entry corresponding to the linkEA entry
2755                          * that matches the ".." name entry. */
2756                         rc = linkea_data_new(&ldata_new, &info->lti_big_buf);
2757                         if (rc != 0)
2758                                 RETURN(rc);
2759
2760                         rc = linkea_add_buf(&ldata_new, cname, pfid2);
2761                         if (rc != 0)
2762                                 RETURN(rc);
2763
2764                         rc = lfsck_namespace_rebuild_linkea(env, com, child,
2765                                                             &ldata_new);
2766                         if (rc < 0)
2767                                 RETURN(rc);
2768
2769                         linkea_del_buf(ldata, cname);
2770                         linkea_count++;
2771                         linkea_first_entry(ldata);
2772                         /* There may be some invalid dangling name entries under
2773                          * other parent directories, remove all of them. */
2774                         while (ldata->ld_lee != NULL) {
2775                                 lfsck_namespace_unpack_linkea_entry(ldata,
2776                                                 cname, &tfid, info->lti_key);
2777                                 if (!fid_is_sane(&tfid))
2778                                         goto next;
2779
2780                                 parent = lfsck_object_find_bottom(env, lfsck,
2781                                                                   &tfid);
2782                                 if (IS_ERR(parent)) {
2783                                         rc = PTR_ERR(parent);
2784                                         if (rc != -ENOENT &&
2785                                             bk->lb_param & LPF_FAILOUT)
2786                                                 RETURN(rc);
2787
2788                                         goto next;
2789                                 }
2790
2791                                 if (!dt_object_exists(parent)) {
2792                                         lfsck_object_put(env, parent);
2793                                         goto next;
2794                                 }
2795
2796                                 rc = lfsck_namespace_repair_dirent(env, com,
2797                                         parent, child, cname->ln_name,
2798                                         cname->ln_name, S_IFDIR, false, true);
2799                                 lfsck_object_put(env, parent);
2800                                 if (rc < 0) {
2801                                         if (bk->lb_param & LPF_FAILOUT)
2802                                                 RETURN(rc);
2803
2804                                         goto next;
2805                                 }
2806
2807                                 dirent_count += rc;
2808
2809 next:
2810                                 linkea_del_buf(ldata, cname);
2811                         }
2812
2813                         ns->ln_dirent_repaired += dirent_count;
2814
2815                         RETURN(rc);
2816                 }
2817
2818                 lfsck_ibits_unlock(lh, LCK_EX);
2819                 /* The name entry references another MDT-object that may be
2820                  * created by the LFSCK for repairing dangling name entry.
2821                  * Try to replace it. */
2822                 rc = lfsck_namespace_replace_cond(env, com, parent, child,
2823                                                   &tfid, cname);
2824                 lfsck_object_put(env, parent);
2825                 if (rc < 0)
2826                         RETURN(rc);
2827
2828                 if (rc > 0)
2829                         goto rebuild;
2830
2831                 linkea_del_buf(ldata, cname);
2832         }
2833
2834         linkea_first_entry(ldata);
2835         if (ldata->ld_leh->leh_reccount == 1) {
2836                 rc = lfsck_namespace_dsd_single(env, com, child, pfid, ldata,
2837                                                 lh, type, NULL);
2838
2839                 if (rc == 0 && fid_is_zero(pfid) && linkea_count > 0)
2840                         rc = lfsck_namespace_rebuild_linkea(env, com, child,
2841                                                             ldata);
2842
2843                 RETURN(rc);
2844         }
2845
2846         /* All linkEA entries are invalid and removed, then handle the @child
2847          * as an orphan.*/
2848         if (ldata->ld_leh->leh_reccount == 0) {
2849                 rc = lfsck_namespace_dsd_orphan(env, com, child, pfid, lh,
2850                                                 type);
2851
2852                 RETURN(rc);
2853         }
2854
2855         /* If the dangling name entry for the orphan directory object has
2856          * been remvoed, then just check whether the directory object is
2857          * still under the .lustre/lost+found/MDTxxxx/ or not. */
2858         if (lpf) {
2859                 lpf = false;
2860                 goto again;
2861         }
2862
2863         /* There is no linkEA entry that matches the ".." name entry. Find
2864          * the first linkEA entry that both parent and name entry exist to
2865          * rebuild a new ".." name entry. */
2866         if (once) {
2867                 once = false;
2868                 goto again;
2869         }
2870
2871         RETURN(rc);
2872 }
2873
2874 /**
2875  * Repair the object's nlink attribute.
2876  *
2877  * If all the known name entries have been verified, then the object's hard
2878  * link attribute should match the object's linkEA entries count unless the
2879  * object's has too much hard link to be recorded in the linkEA. Such cases
2880  * should have been marked in the LFSCK trace file. Otherwise, trust the
2881  * linkEA to update the object's nlink attribute.
2882  *
2883  * \param[in] env       pointer to the thread context
2884  * \param[in] com       pointer to the lfsck component
2885  * \param[in] obj       pointer to the dt_object to be handled
2886  * \param[in,out] la    pointer to buffer to object's attribute before
2887  *                      and after the repairing
2888  *
2889  * \retval              positive number for repaired cases
2890  * \retval              0 if nothing to be repaired
2891  * \retval              negative error number on failure
2892  */
2893 static int lfsck_namespace_repair_nlink(const struct lu_env *env,
2894                                         struct lfsck_component *com,
2895                                         struct dt_object *obj,
2896                                         struct lu_attr *la)
2897 {
2898         struct lfsck_thread_info        *info   = lfsck_env_info(env);
2899         struct lu_fid                   *tfid   = &info->lti_fid3;
2900         struct lfsck_namespace          *ns     = com->lc_file_ram;
2901         struct lfsck_instance           *lfsck  = com->lc_lfsck;
2902         struct dt_device                *dev    = lfsck_obj2dev(obj);
2903         const struct lu_fid             *cfid   = lfsck_dto2fid(obj);
2904         struct thandle                  *th     = NULL;
2905         struct linkea_data               ldata  = { NULL };
2906         struct lustre_handle             lh     = { 0 };
2907         __u32                            old    = la->la_nlink;
2908         int                              idx;
2909         int                              rc     = 0;
2910         __u8                             flags;
2911         ENTRY;
2912
2913         LASSERT(!dt_object_remote(obj));
2914         LASSERT(S_ISREG(lfsck_object_type(obj)));
2915
2916         rc = lfsck_ibits_lock(env, lfsck, obj, &lh,
2917                               MDS_INODELOCK_UPDATE, LCK_PW);
2918         if (rc != 0)
2919                 GOTO(log, rc);
2920
2921         th = dt_trans_create(env, dev);
2922         if (IS_ERR(th))
2923                 GOTO(log, rc = PTR_ERR(th));
2924
2925         la->la_valid = LA_NLINK;
2926         rc = dt_declare_attr_set(env, obj, la, th);
2927         if (rc != 0)
2928                 GOTO(stop, rc);
2929
2930         rc = dt_trans_start_local(env, dev, th);
2931         if (rc != 0)
2932                 GOTO(stop, rc);
2933
2934         dt_write_lock(env, obj, 0);
2935         /* If the LFSCK is marked as LF_INCOMPLETE, then means some MDT has
2936          * ever tried to verify some remote MDT-object that resides on this
2937          * MDT, but this MDT failed to respond such request. So means there
2938          * may be some remote name entry on other MDT that references this
2939          * object with another name, so we cannot know whether this linkEA
2940          * is valid or not. So keep it there and maybe resolved when next
2941          * LFSCK run. */
2942         if (ns->ln_flags & LF_INCOMPLETE)
2943                 GOTO(unlock, rc = 0);
2944
2945         fid_cpu_to_be(tfid, cfid);
2946         idx = lfsck_sub_trace_file_fid2idx(cfid);
2947         rc = dt_lookup(env, com->lc_sub_trace_objs[idx].lsto_obj,
2948                        (struct dt_rec *)&flags, (const struct dt_key *)tfid);
2949         if (rc != 0)
2950                 GOTO(unlock, rc);
2951
2952         if (flags & LNTF_SKIP_NLINK)
2953                 GOTO(unlock, rc = 0);
2954
2955         rc = dt_attr_get(env, obj, la);
2956         if (rc != 0)
2957                 GOTO(unlock, rc = (rc == -ENOENT ? 0 : rc));
2958
2959         rc = lfsck_links_read2(env, obj, &ldata);
2960         if (rc != 0)
2961                 GOTO(unlock, rc = (rc == -ENODATA ? 0 : rc));
2962
2963         if (la->la_nlink == ldata.ld_leh->leh_reccount ||
2964             unlikely(la->la_nlink == 0))
2965                 GOTO(unlock, rc = 0);
2966
2967         la->la_nlink = ldata.ld_leh->leh_reccount;
2968         if (lfsck->li_bookmark_ram.lb_param & LPF_DRYRUN)
2969                 GOTO(unlock, rc = 1);
2970
2971         rc = dt_attr_set(env, obj, la, th);
2972
2973         GOTO(unlock, rc = (rc == 0 ? 1 : rc));
2974
2975 unlock:
2976         dt_write_unlock(env, obj);
2977
2978 stop:
2979         dt_trans_stop(env, dev, th);
2980
2981 log:
2982         lfsck_ibits_unlock(&lh, LCK_PW);
2983         CDEBUG(D_LFSCK, "%s: namespace LFSCK repaired the object "DFID"'s "
2984                "nlink count from %u to %u: rc = %d\n",
2985                lfsck_lfsck2name(lfsck), PFID(cfid), old, la->la_nlink, rc);
2986
2987         if (rc != 0)
2988                 ns->ln_flags |= LF_INCONSISTENT;
2989
2990         return rc;
2991 }
2992
2993 /**
2994  * Double scan the directory object for namespace LFSCK.
2995  *
2996  * This function will verify the <parent, child> pairs in the namespace tree:
2997  * the parent references the child via some name entry that should be in the
2998  * child's linkEA entry, the child should back references the parent via its
2999  * ".." name entry.
3000  *
3001  * The LFSCK will scan every linkEA entry in turn until find out the first
3002  * matched pairs. If found, then all other linkEA entries will be dropped.
3003  * If all the linkEA entries cannot match the ".." name entry, then there
3004  * are serveral possible cases:
3005  *
3006  * 1) If there is only one linkEA entry, then trust it as long as the PFID
3007  *    in the linkEA entry is valid.
3008  *
3009  * 2) If there are multiple linkEA entries, then try to find the linkEA
3010  *    that matches the ".." name entry. If found, then all other entries
3011  *    are invalid; otherwise, it is quite possible that the ".." name entry
3012  *    is corrupted. Under such case, the LFSCK will rebuild the ".." name
3013  *    entry according to the first valid linkEA entry (both the parent and
3014  *    the name entry should exist).
3015  *
3016  * 3) If the directory object has no (valid) linkEA entry, then the
3017  *    directory object will be handled as pure orphan and inserted
3018  *    in the .lustre/lost+found/MDTxxxx/ with the name:
3019  *    ${self_FID}-${PFID}-D-${conflict_version}
3020  *
3021  * \param[in] env       pointer to the thread context
3022  * \param[in] com       pointer to the lfsck component
3023  * \param[in] child     pointer to the directory object to be handled
3024  * \param[in] flags     to indicate the specical checking on the @child
3025  *
3026  * \retval              positive number for repaired cases
3027  * \retval              0 if nothing to be repaired
3028  * \retval              negative error number on failure
3029  */
3030 static int lfsck_namespace_double_scan_dir(const struct lu_env *env,
3031                                            struct lfsck_component *com,
3032                                            struct dt_object *child, __u8 flags)
3033 {
3034         struct lfsck_thread_info *info          = lfsck_env_info(env);
3035         const struct lu_fid      *cfid          = lfsck_dto2fid(child);
3036         struct lu_fid            *pfid          = &info->lti_fid2;
3037         struct lfsck_namespace   *ns            = com->lc_file_ram;
3038         struct lfsck_instance    *lfsck         = com->lc_lfsck;
3039         struct lustre_handle      lh            = { 0 };
3040         struct linkea_data        ldata         = { NULL };
3041         bool                      unknown       = false;
3042         bool                      lpf           = false;
3043         bool                      retry         = false;
3044         enum lfsck_namespace_inconsistency_type type = LNIT_BAD_LINKEA;
3045         int                       rc            = 0;
3046         ENTRY;
3047
3048         LASSERT(!dt_object_remote(child));
3049
3050         if (flags & LNTF_UNCERTAIN_LMV) {
3051                 if (flags & LNTF_RECHECK_NAME_HASH) {
3052                         rc = lfsck_namespace_scan_shard(env, com, child);
3053                         if (rc < 0)
3054                                 RETURN(rc);
3055
3056                         ns->ln_striped_shards_scanned++;
3057                 } else {
3058                         ns->ln_striped_shards_skipped++;
3059                 }
3060         }
3061
3062         flags &= ~(LNTF_RECHECK_NAME_HASH | LNTF_UNCERTAIN_LMV);
3063         if (flags == 0)
3064                 RETURN(0);
3065
3066         if (flags & (LNTF_CHECK_LINKEA | LNTF_CHECK_PARENT) &&
3067             !(lfsck->li_bookmark_ram.lb_param & LPF_ALL_TGT)) {
3068                 CDEBUG(D_LFSCK, "%s: some MDT(s) maybe NOT take part in the"
3069                        "the namespace LFSCK, then the LFSCK cannot guarantee"
3070                        "all the name entries have been verified in first-stage"
3071                        "scanning. So have to skip orphan related handling for"
3072                        "the directory object "DFID" with remote name entry\n",
3073                        lfsck_lfsck2name(lfsck), PFID(cfid));
3074
3075                 RETURN(0);
3076         }
3077
3078         if (unlikely(!dt_try_as_dir(env, child)))
3079                 GOTO(out, rc = -ENOTDIR);
3080
3081         /* We only take ldlm lock on the @child when required. When the
3082          * logic comes here for the first time, it is always false. */
3083         if (0) {
3084
3085 lock:
3086                 rc = lfsck_ibits_lock(env, lfsck, child, &lh,
3087                                       MDS_INODELOCK_UPDATE |
3088                                       MDS_INODELOCK_XATTR, LCK_EX);
3089                 if (rc != 0)
3090                         GOTO(out, rc);
3091         }
3092
3093         dt_read_lock(env, child, 0);
3094         if (unlikely(lfsck_is_dead_obj(child))) {
3095                 dt_read_unlock(env, child);
3096
3097                 GOTO(out, rc = 0);
3098         }
3099
3100         rc = dt_lookup(env, child, (struct dt_rec *)pfid,
3101                        (const struct dt_key *)dotdot);
3102         if (rc != 0) {
3103                 if (rc != -ENOENT && rc != -ENODATA && rc != -EINVAL) {
3104                         dt_read_unlock(env, child);
3105
3106                         GOTO(out, rc);
3107                 }
3108
3109                 if (!lustre_handle_is_used(&lh)) {
3110                         dt_read_unlock(env, child);
3111                         goto lock;
3112                 }
3113
3114                 fid_zero(pfid);
3115         } else if (lfsck->li_lpf_obj != NULL &&
3116                    lu_fid_eq(pfid, lfsck_dto2fid(lfsck->li_lpf_obj))) {
3117                 lpf = true;
3118         } else if (unlikely(!fid_is_sane(pfid))) {
3119                 fid_zero(pfid);
3120         }
3121
3122         rc = lfsck_links_read(env, child, &ldata);
3123         dt_read_unlock(env, child);
3124         if (rc != 0) {
3125                 if (rc != -ENODATA && rc != -EINVAL)
3126                         GOTO(out, rc);
3127
3128                 if (!lustre_handle_is_used(&lh))
3129                         goto lock;
3130
3131                 if (rc == -EINVAL && !fid_is_zero(pfid)) {
3132                         /* Remove the corrupted linkEA. */
3133                         rc = lfsck_namespace_links_remove(env, com, child);
3134                         if (rc == 0)
3135                                 /* Here, because of the crashed linkEA, we
3136                                  * cannot know whether there is some parent
3137                                  * that references the child directory via
3138                                  * some name entry or not. So keep it there,
3139                                  * when the LFSCK run next time, if there is
3140                                  * some parent that references this object,
3141                                  * then the LFSCK can rebuild the linkEA;
3142                                  * otherwise, this object will be handled
3143                                  * as orphan as above. */
3144                                 unknown = true;
3145                 } else {
3146                         /* 1. If we have neither ".." nor linkEA,
3147                          *    then it is an orphan.
3148                          *
3149                          * 2. If we only have the ".." name entry,
3150                          *    but no parent references this child
3151                          *    directory, then handle it as orphan. */
3152                         lfsck_ibits_unlock(&lh, LCK_EX);
3153                         type = LNIT_MUL_REF;
3154
3155                         /* If the LFSCK is marked as LF_INCOMPLETE,
3156                          * then means some MDT has ever tried to
3157                          * verify some remote MDT-object that resides
3158                          * on this MDT, but this MDT failed to respond
3159                          * such request. So means there may be some
3160                          * remote name entry on other MDT that
3161                          * references this object with another name,
3162                          * so we cannot know whether this linkEA is
3163                          * valid or not. So keep it there and maybe
3164                          * resolved when next LFSCK run. */
3165                         if (ns->ln_flags & LF_INCOMPLETE)
3166                                 GOTO(out, rc = 0);
3167
3168                         snprintf(info->lti_tmpbuf, sizeof(info->lti_tmpbuf),
3169                                  "-"DFID, PFID(pfid));
3170                         rc = lfsck_namespace_insert_orphan(env, com, child,
3171                                                 info->lti_tmpbuf, "D", NULL);
3172                 }
3173
3174                 GOTO(out, rc);
3175         }
3176
3177         linkea_first_entry(&ldata);
3178         /* This is the most common case: the object has unique linkEA entry. */
3179         if (ldata.ld_leh->leh_reccount == 1) {
3180                 rc = lfsck_namespace_dsd_single(env, com, child, pfid, &ldata,
3181                                                 &lh, &type, &retry);
3182                 if (retry) {
3183                         LASSERT(!lustre_handle_is_used(&lh));
3184
3185                         retry = false;
3186                         goto lock;
3187                 }
3188
3189                 GOTO(out, rc);
3190         }
3191
3192         if (!lustre_handle_is_used(&lh))
3193                 goto lock;
3194
3195         if (unlikely(ldata.ld_leh->leh_reccount == 0)) {
3196                 rc = lfsck_namespace_dsd_orphan(env, com, child, pfid, &lh,
3197                                                 &type);
3198
3199                 GOTO(out, rc);
3200         }
3201
3202         /* When we come here, the cases usually like that:
3203          * 1) The directory object has a corrupted linkEA entry. During the
3204          *    first-stage scanning, the LFSCK cannot know such corruption,
3205          *    then it appends the right linkEA entry according to the found
3206          *    name entry after the bad one.
3207          *
3208          * 2) The directory object has a right linkEA entry. During the
3209          *    first-stage scanning, the LFSCK finds some bad name entry,
3210          *    but the LFSCK cannot aware that at that time, then it adds
3211          *    the bad linkEA entry for further processing. */
3212         rc = lfsck_namespace_dsd_multiple(env, com, child, pfid, &ldata,
3213                                           &lh, &type, lpf);
3214
3215         GOTO(out, rc);
3216
3217 out:
3218         lfsck_ibits_unlock(&lh, LCK_EX);
3219         if (rc > 0) {
3220                 switch (type) {
3221                 case LNIT_BAD_LINKEA:
3222                         ns->ln_linkea_repaired++;
3223                         break;
3224                 case LNIT_UNMATCHED_PAIRS:
3225                         ns->ln_unmatched_pairs_repaired++;
3226                         break;
3227                 case LNIT_MUL_REF:
3228                         ns->ln_mul_ref_repaired++;
3229                         break;
3230                 default:
3231                         break;
3232                 }
3233         }
3234
3235         if (unknown)
3236                 ns->ln_unknown_inconsistency++;
3237
3238         return rc;
3239 }
3240
3241 /**
3242  * Double scan the MDT-object for namespace LFSCK.
3243  *
3244  * If the MDT-object contains invalid or repeated linkEA entries, then drop
3245  * those entries from the linkEA; if the linkEA becomes empty or the object
3246  * has no linkEA, then it is an orphan and will be added into the directory
3247  * .lustre/lost+found/MDTxxxx/; if the remote parent is lost, then recreate
3248  * the remote parent; if the name entry corresponding to some linkEA entry
3249  * is lost, then add the name entry back to the namespace.
3250  *
3251  * \param[in] env       pointer to the thread context
3252  * \param[in] com       pointer to the lfsck component
3253  * \param[in] child     pointer to the dt_object to be handled
3254  * \param[in] flags     some hints to indicate how the @child should be handled
3255  *
3256  * \retval              positive number for repaired cases
3257  * \retval              0 if nothing to be repaired
3258  * \retval              negative error number on failure
3259  */
3260 static int lfsck_namespace_double_scan_one(const struct lu_env *env,
3261                                            struct lfsck_component *com,
3262                                            struct dt_object *child, __u8 flags)
3263 {
3264         struct lfsck_thread_info *info     = lfsck_env_info(env);
3265         struct lu_attr           *la       = &info->lti_la;
3266         struct lu_name           *cname    = &info->lti_name;
3267         struct lu_fid            *pfid     = &info->lti_fid;
3268         struct lu_fid            *cfid     = &info->lti_fid2;
3269         struct lfsck_instance    *lfsck    = com->lc_lfsck;
3270         struct lfsck_namespace   *ns       = com->lc_file_ram;
3271         struct dt_object         *parent   = NULL;
3272         struct linkea_data        ldata    = { NULL };
3273         bool                      repaired = false;
3274         int                       count    = 0;
3275         int                       rc;
3276         ENTRY;
3277
3278         dt_read_lock(env, child, 0);
3279         if (unlikely(lfsck_is_dead_obj(child))) {
3280                 dt_read_unlock(env, child);
3281
3282                 RETURN(0);
3283         }
3284
3285         if (S_ISDIR(lfsck_object_type(child))) {
3286                 dt_read_unlock(env, child);
3287                 rc = lfsck_namespace_double_scan_dir(env, com, child, flags);
3288
3289                 RETURN(rc);
3290         }
3291
3292         rc = lfsck_links_read(env, child, &ldata);
3293         dt_read_unlock(env, child);
3294         if (rc != 0)
3295                 GOTO(out, rc);
3296
3297         linkea_first_entry(&ldata);
3298         while (ldata.ld_lee != NULL) {
3299                 lfsck_namespace_unpack_linkea_entry(&ldata, cname, pfid,
3300                                                     info->lti_key);
3301                 rc = lfsck_namespace_filter_linkea_entry(&ldata, cname, pfid,
3302                                                          false);
3303                 /* Found repeated linkEA entries */
3304                 if (rc > 0) {
3305                         rc = lfsck_namespace_shrink_linkea(env, com, child,
3306                                                 &ldata, cname, pfid, false);
3307                         if (rc < 0)
3308                                 GOTO(out, rc);
3309
3310                         if (rc == 0)
3311                                 continue;
3312
3313                         repaired = true;
3314
3315                         /* fall through */
3316                 }
3317
3318                 /* Invalid PFID in the linkEA entry. */
3319                 if (!fid_is_sane(pfid)) {
3320                         rc = lfsck_namespace_shrink_linkea(env, com, child,
3321                                                 &ldata, cname, pfid, true);
3322                         if (rc < 0)
3323                                 GOTO(out, rc);
3324
3325                         if (rc > 0)
3326                                 repaired = true;
3327
3328                         continue;
3329                 }
3330
3331                 parent = lfsck_object_find_bottom(env, lfsck, pfid);
3332                 if (IS_ERR(parent))
3333                         GOTO(out, rc = PTR_ERR(parent));
3334
3335                 if (!dt_object_exists(parent)) {
3336
3337 lost_parent:
3338                         if (ldata.ld_leh->leh_reccount > 1) {
3339                                 /* If it is NOT the last linkEA entry, then
3340                                  * there is still other chance to make the
3341                                  * child to be visible via other parent, then
3342                                  * remove this linkEA entry. */
3343                                 rc = lfsck_namespace_shrink_linkea(env, com,
3344                                         child, &ldata, cname, pfid, true);
3345                         } else {
3346                                 /* If the LFSCK is marked as LF_INCOMPLETE,
3347                                  * then means some MDT has ever tried to
3348                                  * verify some remote MDT-object that resides
3349                                  * on this MDT, but this MDT failed to respond
3350                                  * such request. So means there may be some
3351                                  * remote name entry on other MDT that
3352                                  * references this object with another name,
3353                                  * so we cannot know whether this linkEA is
3354                                  * valid or not. So keep it there and maybe
3355                                  * resolved when next LFSCK run. */
3356                                 if (ns->ln_flags & LF_INCOMPLETE) {
3357                                         lfsck_object_put(env, parent);
3358
3359                                         GOTO(out, rc = 0);
3360                                 }
3361
3362                                 /* Create the lost parent as an orphan. */
3363                                 rc = lfsck_namespace_create_orphan_dir(env, com,
3364                                                                 parent, NULL);
3365                                 if (rc < 0) {
3366                                         lfsck_object_put(env, parent);
3367
3368                                         GOTO(out, rc);
3369                                 }
3370
3371                                 if (rc > 0)
3372                                         repaired = true;
3373
3374                                 /* Add the missing name entry to the parent. */
3375                                 rc = lfsck_namespace_insert_normal(env, com,
3376                                                 parent, child, cname->ln_name);
3377                                 if (unlikely(rc == -EEXIST))
3378                                         /* Unfortunately, someone reused the
3379                                          * name under the parent by race. So we
3380                                          * have to remove the linkEA entry from
3381                                          * current child object. It means that
3382                                          * the LFSCK cannot recover the system
3383                                          * totally back to its original status,
3384                                          * but it is necessary to make the
3385                                          * current system to be consistent. */
3386                                         rc = lfsck_namespace_shrink_linkea(env,
3387                                                         com, child, &ldata,
3388                                                         cname, pfid, true);
3389                                 else
3390                                         linkea_next_entry(&ldata);
3391                         }
3392
3393                         lfsck_object_put(env, parent);
3394                         if (rc < 0)
3395                                 GOTO(out, rc);
3396
3397                         if (rc > 0)
3398                                 repaired = true;
3399
3400                         continue;
3401                 }
3402
3403                 /* The linkEA entry with bad parent will be removed. */
3404                 if (unlikely(!dt_try_as_dir(env, parent))) {
3405                         lfsck_object_put(env, parent);
3406                         rc = lfsck_namespace_shrink_linkea(env, com, child,
3407                                                 &ldata, cname, pfid, true);
3408                         if (rc < 0)
3409                                 GOTO(out, rc);
3410
3411                         if (rc > 0)
3412                                 repaired = true;
3413
3414                         continue;
3415                 }
3416
3417                 rc = dt_lookup(env, parent, (struct dt_rec *)cfid,
3418                                (const struct dt_key *)cname->ln_name);
3419                 if (rc != 0 && rc != -ENOENT) {
3420                         lfsck_object_put(env, parent);
3421
3422                         GOTO(out, rc);
3423                 }
3424
3425                 if (rc == 0) {
3426                         if (lu_fid_eq(cfid, lfsck_dto2fid(child))) {
3427                                 /* It is the most common case that we
3428                                  * find the name entry corresponding
3429                                  * to the linkEA entry. */
3430                                 lfsck_object_put(env, parent);
3431                                 linkea_next_entry(&ldata);
3432                         } else {
3433                                 /* The name entry references another
3434                                  * MDT-object that may be created by
3435                                  * the LFSCK for repairing dangling
3436                                  * name entry. Try to replace it. */
3437                                 rc = lfsck_namespace_replace_cond(env, com,
3438                                                 parent, child, cfid, cname);
3439                                 lfsck_object_put(env, parent);
3440                                 if (r