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