Whamcloud - gitweb
LU-5515 lfsck: repair bad file type in name entry
[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         dst->ln_objs_lost_found = le64_to_cpu(src->ln_objs_lost_found);
120         fid_le_to_cpu(&dst->ln_fid_latest_scanned_phase2,
121                       &src->ln_fid_latest_scanned_phase2);
122         dst->ln_dirent_repaired = le64_to_cpu(src->ln_dirent_repaired);
123         dst->ln_linkea_repaired = le64_to_cpu(src->ln_linkea_repaired);
124         dst->ln_mul_linked_checked = le64_to_cpu(src->ln_mul_linked_checked);
125         dst->ln_mul_linked_repaired = le64_to_cpu(src->ln_mul_linked_repaired);
126         dst->ln_unknown_inconsistency =
127                                 le64_to_cpu(src->ln_unknown_inconsistency);
128         dst->ln_unmatched_pairs_repaired =
129                                 le64_to_cpu(src->ln_unmatched_pairs_repaired);
130         dst->ln_dangling_repaired = le64_to_cpu(src->ln_dangling_repaired);
131         dst->ln_mul_ref_repaired = le64_to_cpu(src->ln_mul_ref_repaired);
132         dst->ln_bad_type_repaired = le64_to_cpu(src->ln_bad_type_repaired);
133 }
134
135 static void lfsck_namespace_cpu_to_le(struct lfsck_namespace *dst,
136                                       struct lfsck_namespace *src)
137 {
138         dst->ln_magic = cpu_to_le32(src->ln_magic);
139         dst->ln_status = cpu_to_le32(src->ln_status);
140         dst->ln_flags = cpu_to_le32(src->ln_flags);
141         dst->ln_success_count = cpu_to_le32(src->ln_success_count);
142         dst->ln_run_time_phase1 = cpu_to_le32(src->ln_run_time_phase1);
143         dst->ln_run_time_phase2 = cpu_to_le32(src->ln_run_time_phase2);
144         dst->ln_time_last_complete = cpu_to_le64(src->ln_time_last_complete);
145         dst->ln_time_latest_start = cpu_to_le64(src->ln_time_latest_start);
146         dst->ln_time_last_checkpoint =
147                                 cpu_to_le64(src->ln_time_last_checkpoint);
148         lfsck_position_cpu_to_le(&dst->ln_pos_latest_start,
149                                  &src->ln_pos_latest_start);
150         lfsck_position_cpu_to_le(&dst->ln_pos_last_checkpoint,
151                                  &src->ln_pos_last_checkpoint);
152         lfsck_position_cpu_to_le(&dst->ln_pos_first_inconsistent,
153                                  &src->ln_pos_first_inconsistent);
154         dst->ln_items_checked = cpu_to_le64(src->ln_items_checked);
155         dst->ln_items_repaired = cpu_to_le64(src->ln_items_repaired);
156         dst->ln_items_failed = cpu_to_le64(src->ln_items_failed);
157         dst->ln_dirs_checked = cpu_to_le64(src->ln_dirs_checked);
158         dst->ln_objs_checked_phase2 = cpu_to_le64(src->ln_objs_checked_phase2);
159         dst->ln_objs_repaired_phase2 =
160                                 cpu_to_le64(src->ln_objs_repaired_phase2);
161         dst->ln_objs_failed_phase2 = cpu_to_le64(src->ln_objs_failed_phase2);
162         dst->ln_objs_nlink_repaired = cpu_to_le64(src->ln_objs_nlink_repaired);
163         dst->ln_objs_lost_found = cpu_to_le64(src->ln_objs_lost_found);
164         fid_cpu_to_le(&dst->ln_fid_latest_scanned_phase2,
165                       &src->ln_fid_latest_scanned_phase2);
166         dst->ln_dirent_repaired = cpu_to_le64(src->ln_dirent_repaired);
167         dst->ln_linkea_repaired = cpu_to_le64(src->ln_linkea_repaired);
168         dst->ln_mul_linked_checked = cpu_to_le64(src->ln_mul_linked_checked);
169         dst->ln_mul_linked_repaired = cpu_to_le64(src->ln_mul_linked_repaired);
170         dst->ln_unknown_inconsistency =
171                                 cpu_to_le64(src->ln_unknown_inconsistency);
172         dst->ln_unmatched_pairs_repaired =
173                                 cpu_to_le64(src->ln_unmatched_pairs_repaired);
174         dst->ln_dangling_repaired = cpu_to_le64(src->ln_dangling_repaired);
175         dst->ln_mul_ref_repaired = cpu_to_le64(src->ln_mul_ref_repaired);
176         dst->ln_bad_type_repaired = cpu_to_le64(src->ln_bad_type_repaired);
177 }
178
179 static void lfsck_namespace_record_failure(const struct lu_env *env,
180                                            struct lfsck_instance *lfsck,
181                                            struct lfsck_namespace *ns)
182 {
183         struct lfsck_position pos;
184
185         ns->ln_items_failed++;
186         lfsck_pos_fill(env, lfsck, &pos, false);
187         if (lfsck_pos_is_zero(&ns->ln_pos_first_inconsistent) ||
188             lfsck_pos_is_eq(&pos, &ns->ln_pos_first_inconsistent) < 0) {
189                 ns->ln_pos_first_inconsistent = pos;
190
191                 CDEBUG(D_LFSCK, "%s: namespace LFSCK hit first non-repaired "
192                        "inconsistency at the pos ["LPU64", "DFID", "LPX64"]\n",
193                        lfsck_lfsck2name(lfsck),
194                        ns->ln_pos_first_inconsistent.lp_oit_cookie,
195                        PFID(&ns->ln_pos_first_inconsistent.lp_dir_parent),
196                        ns->ln_pos_first_inconsistent.lp_dir_cookie);
197         }
198 }
199
200 /**
201  * \retval +ve: the lfsck_namespace is broken, the caller should reset it.
202  * \retval 0: succeed.
203  * \retval -ve: failed cases.
204  */
205 static int lfsck_namespace_load(const struct lu_env *env,
206                                 struct lfsck_component *com)
207 {
208         int len = com->lc_file_size;
209         int rc;
210
211         rc = dt_xattr_get(env, com->lc_obj,
212                           lfsck_buf_get(env, com->lc_file_disk, len),
213                           XATTR_NAME_LFSCK_NAMESPACE, BYPASS_CAPA);
214         if (rc == len) {
215                 struct lfsck_namespace *ns = com->lc_file_ram;
216
217                 lfsck_namespace_le_to_cpu(ns,
218                                 (struct lfsck_namespace *)com->lc_file_disk);
219                 if (ns->ln_magic != LFSCK_NAMESPACE_MAGIC) {
220                         CDEBUG(D_LFSCK, "%s: invalid lfsck_namespace magic "
221                                "%#x != %#x\n", lfsck_lfsck2name(com->lc_lfsck),
222                                ns->ln_magic, LFSCK_NAMESPACE_MAGIC);
223                         rc = 1;
224                 } else {
225                         rc = 0;
226                 }
227         } else if (rc != -ENODATA) {
228                 CDEBUG(D_LFSCK, "%s: fail to load lfsck_namespace, "
229                        "expected = %d: rc = %d\n",
230                        lfsck_lfsck2name(com->lc_lfsck), len, rc);
231                 if (rc >= 0)
232                         rc = 1;
233         }
234         return rc;
235 }
236
237 static int lfsck_namespace_store(const struct lu_env *env,
238                                  struct lfsck_component *com, bool init)
239 {
240         struct dt_object        *obj    = com->lc_obj;
241         struct lfsck_instance   *lfsck  = com->lc_lfsck;
242         struct thandle          *handle;
243         int                      len    = com->lc_file_size;
244         int                      rc;
245         ENTRY;
246
247         lfsck_namespace_cpu_to_le((struct lfsck_namespace *)com->lc_file_disk,
248                                   (struct lfsck_namespace *)com->lc_file_ram);
249         handle = dt_trans_create(env, lfsck->li_bottom);
250         if (IS_ERR(handle))
251                 GOTO(log, rc = PTR_ERR(handle));
252
253         rc = dt_declare_xattr_set(env, obj,
254                                   lfsck_buf_get(env, com->lc_file_disk, len),
255                                   XATTR_NAME_LFSCK_NAMESPACE, 0, handle);
256         if (rc != 0)
257                 GOTO(out, rc);
258
259         rc = dt_trans_start_local(env, lfsck->li_bottom, handle);
260         if (rc != 0)
261                 GOTO(out, rc);
262
263         rc = dt_xattr_set(env, obj,
264                           lfsck_buf_get(env, com->lc_file_disk, len),
265                           XATTR_NAME_LFSCK_NAMESPACE,
266                           init ? LU_XATTR_CREATE : LU_XATTR_REPLACE,
267                           handle, BYPASS_CAPA);
268
269         GOTO(out, rc);
270
271 out:
272         dt_trans_stop(env, lfsck->li_bottom, handle);
273
274 log:
275         if (rc != 0)
276                 CDEBUG(D_LFSCK, "%s: fail to store lfsck_namespace: rc = %d\n",
277                        lfsck_lfsck2name(lfsck), rc);
278         return rc;
279 }
280
281 static int lfsck_namespace_init(const struct lu_env *env,
282                                 struct lfsck_component *com)
283 {
284         struct lfsck_namespace *ns = com->lc_file_ram;
285         int rc;
286
287         memset(ns, 0, sizeof(*ns));
288         ns->ln_magic = LFSCK_NAMESPACE_MAGIC;
289         ns->ln_status = LS_INIT;
290         down_write(&com->lc_sem);
291         rc = lfsck_namespace_store(env, com, true);
292         up_write(&com->lc_sem);
293         return rc;
294 }
295
296 /**
297  * Update the namespace LFSCK tracing file for the given @fid
298  *
299  * \param[in] env       pointer to the thread context
300  * \param[in] com       pointer to the lfsck component
301  * \param[in] fid       the fid which flags to be updated in the lfsck
302  *                      tracing file
303  * \param[in] add       true if add new flags, otherwise remove flags
304  *
305  * \retval              0 for succeed or nothing to be done
306  * \retval              negative error number on failure
307  */
308 int lfsck_namespace_trace_update(const struct lu_env *env,
309                                  struct lfsck_component *com,
310                                  const struct lu_fid *fid,
311                                  const __u8 flags, bool add)
312 {
313         struct lfsck_instance   *lfsck  = com->lc_lfsck;
314         struct dt_object        *obj    = com->lc_obj;
315         struct lu_fid           *key    = &lfsck_env_info(env)->lti_fid3;
316         struct dt_device        *dev    = lfsck->li_bottom;
317         struct thandle          *th     = NULL;
318         int                      rc     = 0;
319         __u8                     old    = 0;
320         __u8                     new    = 0;
321         ENTRY;
322
323         LASSERT(flags != 0);
324
325         down_write(&com->lc_sem);
326         fid_cpu_to_be(key, fid);
327         rc = dt_lookup(env, obj, (struct dt_rec *)&old,
328                        (const struct dt_key *)key, BYPASS_CAPA);
329         if (rc == -ENOENT) {
330                 if (!add)
331                         GOTO(unlock, rc = 0);
332
333                 old = 0;
334                 new = flags;
335         } else if (rc == 0) {
336                 if (add) {
337                         if ((old & flags) == flags)
338                                 GOTO(unlock, rc = 0);
339
340                         new = old | flags;
341                 } else {
342                         if ((old & flags) == 0)
343                                 GOTO(unlock, rc = 0);
344
345                         new = old & ~flags;
346                 }
347         } else {
348                 GOTO(log, rc);
349         }
350
351         th = dt_trans_create(env, dev);
352         if (IS_ERR(th))
353                 GOTO(log, rc = PTR_ERR(th));
354
355         if (old != 0) {
356                 rc = dt_declare_delete(env, obj,
357                                        (const struct dt_key *)key, th);
358                 if (rc != 0)
359                         GOTO(log, rc);
360         }
361
362         if (new != 0) {
363                 rc = dt_declare_insert(env, obj,
364                                        (const struct dt_rec *)&new,
365                                        (const struct dt_key *)key, th);
366                 if (rc != 0)
367                         GOTO(log, rc);
368         }
369
370         rc = dt_trans_start_local(env, dev, th);
371         if (rc != 0)
372                 GOTO(log, rc);
373
374         if (old != 0) {
375                 rc = dt_delete(env, obj, (const struct dt_key *)key,
376                                th, BYPASS_CAPA);
377                 if (rc != 0)
378                         GOTO(log, rc);
379         }
380
381         if (new != 0) {
382                 rc = dt_insert(env, obj, (const struct dt_rec *)&new,
383                                (const struct dt_key *)key, th, BYPASS_CAPA, 1);
384                 if (rc != 0)
385                         GOTO(log, rc);
386         }
387
388         GOTO(log, rc);
389
390 log:
391         if (th != NULL && !IS_ERR(th))
392                 dt_trans_stop(env, dev, th);
393
394         CDEBUG(D_LFSCK, "%s: namespace LFSCK %s flags for "DFID" in the "
395                "tracing file, flags %x, old %x, new %x: rc = %d\n",
396                lfsck_lfsck2name(lfsck), add ? "add" : "del", PFID(fid),
397                (__u32)flags, (__u32)old, (__u32)new, rc);
398
399 unlock:
400         up_write(&com->lc_sem);
401
402         return rc;
403 }
404
405 static int lfsck_namespace_check_exist(const struct lu_env *env,
406                                        struct dt_object *dir,
407                                        struct dt_object *obj, const char *name)
408 {
409         struct lu_fid    *fid = &lfsck_env_info(env)->lti_fid;
410         int               rc;
411         ENTRY;
412
413         if (unlikely(lfsck_is_dead_obj(obj)))
414                 RETURN(LFSCK_NAMEENTRY_DEAD);
415
416         rc = dt_lookup(env, dir, (struct dt_rec *)fid,
417                        (const struct dt_key *)name, BYPASS_CAPA);
418         if (rc == -ENOENT)
419                 RETURN(LFSCK_NAMEENTRY_REMOVED);
420
421         if (rc < 0)
422                 RETURN(rc);
423
424         if (!lu_fid_eq(fid, lfsck_dto2fid(obj)))
425                 RETURN(LFSCK_NAMEENTRY_RECREATED);
426
427         RETURN(0);
428 }
429
430 static int lfsck_declare_namespace_exec_dir(const struct lu_env *env,
431                                             struct dt_object *obj,
432                                             struct thandle *handle)
433 {
434         int rc;
435
436         /* For destroying all invalid linkEA entries. */
437         rc = dt_declare_xattr_del(env, obj, XATTR_NAME_LINK, handle);
438         if (rc != 0)
439                 return rc;
440
441         /* For insert new linkEA entry. */
442         rc = dt_declare_xattr_set(env, obj,
443                         lfsck_buf_get_const(env, NULL, DEFAULT_LINKEA_SIZE),
444                         XATTR_NAME_LINK, 0, handle);
445         return rc;
446 }
447
448 int __lfsck_links_read(const struct lu_env *env, struct dt_object *obj,
449                        struct linkea_data *ldata)
450 {
451         int rc;
452
453         if (ldata->ld_buf->lb_buf == NULL)
454                 return -ENOMEM;
455
456         if (!dt_object_exists(obj))
457                 return -ENOENT;
458
459         rc = dt_xattr_get(env, obj, ldata->ld_buf, XATTR_NAME_LINK, BYPASS_CAPA);
460         if (rc == -ERANGE) {
461                 /* Buf was too small, figure out what we need. */
462                 rc = dt_xattr_get(env, obj, &LU_BUF_NULL, XATTR_NAME_LINK,
463                                   BYPASS_CAPA);
464                 if (rc <= 0)
465                         return rc;
466
467                 lu_buf_realloc(ldata->ld_buf, rc);
468                 if (ldata->ld_buf->lb_buf == NULL)
469                         return -ENOMEM;
470
471                 rc = dt_xattr_get(env, obj, ldata->ld_buf, XATTR_NAME_LINK,
472                                   BYPASS_CAPA);
473         }
474
475         if (rc > 0)
476                 rc = linkea_init(ldata);
477
478         return rc;
479 }
480
481 /**
482  * Remove linkEA for the given object.
483  *
484  * The caller should take the ldlm lock before the calling.
485  *
486  * \param[in] env       pointer to the thread context
487  * \param[in] com       pointer to the lfsck component
488  * \param[in] obj       pointer to the dt_object to be handled
489  *
490  * \retval              0 for repaired cases
491  * \retval              negative error number on failure
492  */
493 static int lfsck_namespace_links_remove(const struct lu_env *env,
494                                         struct lfsck_component *com,
495                                         struct dt_object *obj)
496 {
497         struct lfsck_instance           *lfsck  = com->lc_lfsck;
498         struct dt_device                *dev    = lfsck->li_bottom;
499         struct thandle                  *th     = NULL;
500         int                              rc     = 0;
501         ENTRY;
502
503         LASSERT(dt_object_remote(obj) == 0);
504
505         th = dt_trans_create(env, dev);
506         if (IS_ERR(th))
507                 GOTO(log, rc = PTR_ERR(th));
508
509         rc = dt_declare_xattr_del(env, obj, XATTR_NAME_LINK, th);
510         if (rc != 0)
511                 GOTO(stop, rc);
512
513         rc = dt_trans_start_local(env, dev, th);
514         if (rc != 0)
515                 GOTO(stop, rc);
516
517         dt_write_lock(env, obj, 0);
518         if (unlikely(lfsck_is_dead_obj(obj)))
519                 GOTO(unlock, rc = -ENOENT);
520
521         if (lfsck->li_bookmark_ram.lb_param & LPF_DRYRUN)
522                 GOTO(unlock, rc = 0);
523
524         rc = dt_xattr_del(env, obj, XATTR_NAME_LINK, th, BYPASS_CAPA);
525
526         GOTO(unlock, rc);
527
528 unlock:
529         dt_write_unlock(env, obj);
530
531 stop:
532         dt_trans_stop(env, dev, th);
533
534 log:
535         CDEBUG(D_LFSCK, "%s: namespace LFSCK remove invalid linkEA "
536                "for the object "DFID": rc = %d\n",
537                lfsck_lfsck2name(lfsck), PFID(lfsck_dto2fid(obj)), rc);
538
539         if (rc == 0) {
540                 struct lfsck_namespace *ns = com->lc_file_ram;
541
542                 ns->ln_flags |= LF_INCONSISTENT;
543         }
544
545         return rc;
546 }
547
548 static int lfsck_links_write(const struct lu_env *env, struct dt_object *obj,
549                              struct linkea_data *ldata, struct thandle *handle)
550 {
551         const struct lu_buf *buf = lfsck_buf_get_const(env,
552                                                        ldata->ld_buf->lb_buf,
553                                                        ldata->ld_leh->leh_len);
554
555         return dt_xattr_set(env, obj, buf, XATTR_NAME_LINK, 0, handle,
556                             BYPASS_CAPA);
557 }
558
559 static void lfsck_namespace_unpack_linkea_entry(struct linkea_data *ldata,
560                                                 struct lu_name *cname,
561                                                 struct lu_fid *pfid,
562                                                 char *buf)
563 {
564         linkea_entry_unpack(ldata->ld_lee, &ldata->ld_reclen, cname, pfid);
565         /* To guarantee the 'name' is terminated with '0'. */
566         memcpy(buf, cname->ln_name, cname->ln_namelen);
567         buf[cname->ln_namelen] = 0;
568         cname->ln_name = buf;
569 }
570
571 static int lfsck_namespace_filter_linkea_entry(struct linkea_data *ldata,
572                                                struct lu_name *cname,
573                                                struct lu_fid *pfid,
574                                                bool remove)
575 {
576         struct link_ea_entry    *oldlee;
577         int                      oldlen;
578         int                      repeated = 0;
579
580         oldlee = ldata->ld_lee;
581         oldlen = ldata->ld_reclen;
582         linkea_next_entry(ldata);
583         while (ldata->ld_lee != NULL) {
584                 ldata->ld_reclen = (ldata->ld_lee->lee_reclen[0] << 8) |
585                                    ldata->ld_lee->lee_reclen[1];
586                 if (unlikely(ldata->ld_reclen == oldlen &&
587                              memcmp(ldata->ld_lee, oldlee, oldlen) == 0)) {
588                         repeated++;
589                         if (!remove)
590                                 break;
591
592                         linkea_del_buf(ldata, cname);
593                 } else {
594                         linkea_next_entry(ldata);
595                 }
596         }
597         ldata->ld_lee = oldlee;
598         ldata->ld_reclen = oldlen;
599
600         return repeated;
601 }
602
603 /**
604  * Insert orphan into .lustre/lost+found/MDTxxxx/ locally.
605  *
606  * Add the specified orphan MDT-object to the .lustre/lost+found/MDTxxxx/
607  * with the given type to generate the name, the detailed rules for name
608  * have been described as following.
609  *
610  * The function also generates the linkEA corresponding to the name entry
611  * under the .lustre/lost+found/MDTxxxx/ for the orphan MDT-object.
612  *
613  * \param[in] env       pointer to the thread context
614  * \param[in] com       pointer to the lfsck component
615  * \param[in] orphan    pointer to the orphan MDT-object
616  * \param[in] infix     additional information for the orphan name, such as
617  *                      the FID for original
618  * \param[in] type      the type for describing why the orphan MDT-object is
619  *                      created. The rules are as following:
620  *
621  *  type "D":           The MDT-object is a directory, it may knows its parent
622  *                      but because there is no valid linkEA, the LFSCK cannot
623  *                      know where to put it back to the namespace.
624  *  type "O":           The MDT-object has no linkEA, and there is no name
625  *                      entry that references the MDT-object.
626  *
627  * \see lfsck_layout_recreate_parent() for more types.
628  *
629  * The orphan name will be like:
630  * ${FID}-${infix}-${type}-${conflict_version}
631  *
632  * \param[out] count    if some others inserted some linkEA entries by race,
633  *                      then return the linkEA entries count.
634  *
635  * \retval              positive number for repaired cases
636  * \retval              0 if needs to repair nothing
637  * \retval              negative error number on failure
638  */
639 static int lfsck_namespace_insert_orphan(const struct lu_env *env,
640                                          struct lfsck_component *com,
641                                          struct dt_object *orphan,
642                                          const char *infix, const char *type,
643                                          int *count)
644 {
645         struct lfsck_thread_info        *info   = lfsck_env_info(env);
646         struct lu_name                  *cname  = &info->lti_name;
647         struct dt_insert_rec            *rec    = &info->lti_dt_rec;
648         struct lu_fid                   *tfid   = &info->lti_fid5;
649         const struct lu_fid             *cfid   = lfsck_dto2fid(orphan);
650         const struct lu_fid             *pfid;
651         struct lfsck_instance           *lfsck  = com->lc_lfsck;
652         struct dt_device                *dev    = lfsck->li_bottom;
653         struct dt_object                *parent;
654         struct thandle                  *th     = NULL;
655         struct lustre_handle             plh    = { 0 };
656         struct lustre_handle             clh    = { 0 };
657         struct linkea_data               ldata  = { 0 };
658         struct lu_buf                    linkea_buf;
659         int                              namelen;
660         int                              idx    = 0;
661         int                              rc     = 0;
662         bool                             exist  = false;
663         ENTRY;
664
665         cname->ln_name = NULL;
666         /* Create .lustre/lost+found/MDTxxxx when needed. */
667         if (unlikely(lfsck->li_lpf_obj == NULL)) {
668                 rc = lfsck_create_lpf(env, lfsck);
669                 if (rc != 0)
670                         GOTO(log, rc);
671         }
672
673         parent = lfsck->li_lpf_obj;
674         pfid = lfsck_dto2fid(parent);
675
676         /* Hold update lock on the parent to prevent others to access. */
677         rc = lfsck_ibits_lock(env, lfsck, parent, &plh,
678                               MDS_INODELOCK_UPDATE, LCK_EX);
679         if (rc != 0)
680                 GOTO(log, rc);
681
682         do {
683                 namelen = snprintf(info->lti_key, NAME_MAX, DFID"%s-%s-%d",
684                                    PFID(cfid), infix, type, idx++);
685                 rc = dt_lookup(env, parent, (struct dt_rec *)tfid,
686                                (const struct dt_key *)info->lti_key,
687                                BYPASS_CAPA);
688                 if (rc != 0 && rc != -ENOENT)
689                         GOTO(log, rc);
690
691                 if (unlikely(rc == 0 && lu_fid_eq(cfid, tfid)))
692                         exist = true;
693         } while (rc == 0 && !exist);
694
695         cname->ln_name = info->lti_key;
696         cname->ln_namelen = namelen;
697         rc = linkea_data_new(&ldata, &info->lti_linkea_buf2);
698         if (rc != 0)
699                 GOTO(log, rc);
700
701         rc = linkea_add_buf(&ldata, cname, pfid);
702         if (rc != 0)
703                 GOTO(log, rc);
704
705         rc = lfsck_ibits_lock(env, lfsck, orphan, &clh,
706                               MDS_INODELOCK_UPDATE | MDS_INODELOCK_LOOKUP,
707                               LCK_EX);
708         if (rc != 0)
709                 GOTO(log, rc);
710
711         lfsck_buf_init(&linkea_buf, ldata.ld_buf->lb_buf,
712                        ldata.ld_leh->leh_len);
713         th = dt_trans_create(env, dev);
714         if (IS_ERR(th))
715                 GOTO(log, rc = PTR_ERR(th));
716
717         if (S_ISDIR(lfsck_object_type(orphan))) {
718                 rc = dt_declare_delete(env, orphan,
719                                        (const struct dt_key *)dotdot, th);
720                 if (rc != 0)
721                         GOTO(stop, rc);
722
723                 rec->rec_type = S_IFDIR;
724                 rec->rec_fid = pfid;
725                 rc = dt_declare_insert(env, orphan, (const struct dt_rec *)rec,
726                                        (const struct dt_key *)dotdot, th);
727                 if (rc != 0)
728                         GOTO(stop, rc);
729         }
730
731         rc = dt_declare_xattr_set(env, orphan, &linkea_buf,
732                                   XATTR_NAME_LINK, 0, th);
733         if (rc != 0)
734                 GOTO(stop, rc);
735
736         if (!exist) {
737                 rec->rec_type = lfsck_object_type(orphan) & S_IFMT;
738                 rec->rec_fid = cfid;
739                 rc = dt_declare_insert(env, parent, (const struct dt_rec *)rec,
740                                        (const struct dt_key *)cname->ln_name,
741                                        th);
742                 if (rc != 0)
743                         GOTO(stop, rc);
744
745                 if (S_ISDIR(rec->rec_type)) {
746                         rc = dt_declare_ref_add(env, parent, th);
747                         if (rc != 0)
748                                 GOTO(stop, rc);
749                 }
750         }
751
752         rc = dt_trans_start_local(env, dev, th);
753         if (rc != 0)
754                 GOTO(stop, rc);
755
756         dt_write_lock(env, orphan, 0);
757         rc = lfsck_links_read(env, orphan, &ldata);
758         if (likely((rc == -ENODATA) || (rc == -EINVAL) ||
759                    (rc == 0 && ldata.ld_leh->leh_reccount == 0))) {
760                 if (lfsck->li_bookmark_ram.lb_param & LPF_DRYRUN)
761                         GOTO(unlock, rc = 1);
762
763                 if (S_ISDIR(lfsck_object_type(orphan))) {
764                         rc = dt_delete(env, orphan,
765                                        (const struct dt_key *)dotdot, th,
766                                        BYPASS_CAPA);
767                         if (rc != 0)
768                                 GOTO(unlock, rc);
769
770                         rec->rec_type = S_IFDIR;
771                         rec->rec_fid = pfid;
772                         rc = dt_insert(env, orphan, (const struct dt_rec *)rec,
773                                        (const struct dt_key *)dotdot, th,
774                                        BYPASS_CAPA, 1);
775                         if (rc != 0)
776                                 GOTO(unlock, rc);
777                 }
778
779                 rc = dt_xattr_set(env, orphan, &linkea_buf, XATTR_NAME_LINK, 0,
780                                   th, BYPASS_CAPA);
781         } else {
782                 if (rc == 0 && count != NULL)
783                         *count = ldata.ld_leh->leh_reccount;
784
785                 GOTO(unlock, rc);
786         }
787         dt_write_unlock(env, orphan);
788
789         if (rc == 0 && !exist) {
790                 rec->rec_type = lfsck_object_type(orphan) & S_IFMT;
791                 rec->rec_fid = cfid;
792                 rc = dt_insert(env, parent, (const struct dt_rec *)rec,
793                                (const struct dt_key *)cname->ln_name,
794                                th, BYPASS_CAPA, 1);
795                 if (rc == 0 && S_ISDIR(rec->rec_type)) {
796                         dt_write_lock(env, parent, 0);
797                         rc = dt_ref_add(env, parent, th);
798                         dt_write_unlock(env, parent);
799                 }
800         }
801
802         GOTO(stop, rc = (rc == 0 ? 1 : rc));
803
804 unlock:
805         dt_write_unlock(env, orphan);
806
807 stop:
808         dt_trans_stop(env, dev, th);
809
810 log:
811         lfsck_ibits_unlock(&clh, LCK_EX);
812         lfsck_ibits_unlock(&plh, LCK_EX);
813         CDEBUG(D_LFSCK, "%s: namespace LFSCK insert orphan for the "
814                "object "DFID", name = %s: rc = %d\n",
815                lfsck_lfsck2name(lfsck), PFID(cfid),
816                cname->ln_name != NULL ? cname->ln_name : "<NULL>", rc);
817
818         if (rc != 0) {
819                 struct lfsck_namespace *ns = com->lc_file_ram;
820
821                 ns->ln_flags |= LF_INCONSISTENT;
822         }
823
824         return rc;
825 }
826
827 static int lfsck_namespace_insert_normal(const struct lu_env *env,
828                                          struct lfsck_component *com,
829                                          struct dt_object *parent,
830                                          struct dt_object *child,
831                                          const char *name)
832 {
833         /* XXX: TBD */
834         return 0;
835 }
836
837 static int lfsck_namespace_create_orphan(const struct lu_env *env,
838                                          struct lfsck_component *com,
839                                          struct dt_object *orphan)
840 {
841         /* XXX: TBD */
842         return 0;
843 }
844
845 /**
846  * Remove the specified entry from the linkEA.
847  *
848  * Locate the linkEA entry with the given @cname and @pfid, then
849  * remove this entry or the other entries those are repeated with
850  * this entry.
851  *
852  * \param[in] env       pointer to the thread context
853  * \param[in] com       pointer to the lfsck component
854  * \param[in] obj       pointer to the dt_object to be handled
855  * \param[in,out]ldata  pointer to the buffer that holds the linkEA
856  * \param[in] cname     the name for the child in the parent directory
857  * \param[in] pfid      the parent directory's FID for the linkEA
858  * \param[in] next      if true, then remove the first found linkEA
859  *                      entry, and move the ldata->ld_lee to next entry
860  *
861  * \retval              positive number for repaired cases
862  * \retval              0 if nothing to be repaired
863  * \retval              negative error number on failure
864  */
865 static int lfsck_namespace_shrink_linkea(const struct lu_env *env,
866                                          struct lfsck_component *com,
867                                          struct dt_object *obj,
868                                          struct linkea_data *ldata,
869                                          struct lu_name *cname,
870                                          struct lu_fid *pfid,
871                                          bool next)
872 {
873         struct lfsck_instance           *lfsck     = com->lc_lfsck;
874         struct dt_device                *dev       = lfsck->li_bottom;
875         struct lfsck_bookmark           *bk        = &lfsck->li_bookmark_ram;
876         struct thandle                  *th        = NULL;
877         struct lustre_handle             lh        = { 0 };
878         struct linkea_data               ldata_new = { 0 };
879         struct lu_buf                    linkea_buf;
880         int                              rc        = 0;
881         ENTRY;
882
883         rc = lfsck_ibits_lock(env, lfsck, obj, &lh,
884                               MDS_INODELOCK_UPDATE |
885                               MDS_INODELOCK_XATTR, LCK_EX);
886         if (rc != 0)
887                 GOTO(log, rc);
888
889         if (next)
890                 linkea_del_buf(ldata, cname);
891         else
892                 lfsck_namespace_filter_linkea_entry(ldata, cname, pfid,
893                                                     true);
894         lfsck_buf_init(&linkea_buf, ldata->ld_buf->lb_buf,
895                        ldata->ld_leh->leh_len);
896
897 again:
898         th = dt_trans_create(env, dev);
899         if (IS_ERR(th))
900                 GOTO(unlock1, rc = PTR_ERR(th));
901
902         rc = dt_declare_xattr_set(env, obj, &linkea_buf,
903                                   XATTR_NAME_LINK, 0, th);
904         if (rc != 0)
905                 GOTO(stop, rc);
906
907         rc = dt_trans_start_local(env, dev, th);
908         if (rc != 0)
909                 GOTO(stop, rc);
910
911         dt_write_lock(env, obj, 0);
912         if (unlikely(lfsck_is_dead_obj(obj)))
913                 GOTO(unlock2, rc = -ENOENT);
914
915         rc = lfsck_links_read2(env, obj, &ldata_new);
916         if (rc != 0)
917                 GOTO(unlock2, rc);
918
919         /* The specified linkEA entry has been removed by race. */
920         rc = linkea_links_find(&ldata_new, cname, pfid);
921         if (rc != 0)
922                 GOTO(unlock2, rc = 0);
923
924         if (bk->lb_param & LPF_DRYRUN)
925                 GOTO(unlock2, rc = 1);
926
927         if (next)
928                 linkea_del_buf(&ldata_new, cname);
929         else
930                 lfsck_namespace_filter_linkea_entry(&ldata_new, cname, pfid,
931                                                     true);
932
933         if (linkea_buf.lb_len < ldata_new.ld_leh->leh_len) {
934                 dt_write_unlock(env, obj);
935                 dt_trans_stop(env, dev, th);
936                 lfsck_buf_init(&linkea_buf, ldata_new.ld_buf->lb_buf,
937                                ldata_new.ld_leh->leh_len);
938                 goto again;
939         }
940
941         lfsck_buf_init(&linkea_buf, ldata_new.ld_buf->lb_buf,
942                        ldata_new.ld_leh->leh_len);
943         rc = dt_xattr_set(env, obj, &linkea_buf,
944                           XATTR_NAME_LINK, 0, th, BYPASS_CAPA);
945
946         GOTO(unlock2, rc = (rc == 0 ? 1 : rc));
947
948 unlock2:
949         dt_write_unlock(env, obj);
950
951 stop:
952         dt_trans_stop(env, dev, th);
953
954 unlock1:
955         lfsck_ibits_unlock(&lh, LCK_EX);
956
957 log:
958         CDEBUG(D_LFSCK, "%s: namespace LFSCK remove %s linkEA entry "
959                "for the object: "DFID", parent "DFID", name %.*s\n",
960                lfsck_lfsck2name(lfsck), next ? "invalid" : "redundant",
961                PFID(lfsck_dto2fid(obj)), PFID(pfid), cname->ln_namelen,
962                cname->ln_name);
963
964         if (rc != 0) {
965                 struct lfsck_namespace *ns = com->lc_file_ram;
966
967                 ns->ln_flags |= LF_INCONSISTENT;
968         }
969
970         return rc;
971 }
972
973 /**
974  * Conditionally remove the specified entry from the linkEA.
975  *
976  * Take the parent lock firstly, then check whether the specified
977  * name entry exists or not: if yes, do nothing; otherwise, call
978  * lfsck_namespace_shrink_linkea() to remove the linkea entry.
979  *
980  * \param[in] env       pointer to the thread context
981  * \param[in] com       pointer to the lfsck component
982  * \param[in] parent    pointer to the parent directory
983  * \param[in] child     pointer to the child object that holds the linkEA
984  * \param[in,out]ldata  pointer to the buffer that holds the linkEA
985  * \param[in] cname     the name for the child in the parent directory
986  * \param[in] pfid      the parent directory's FID for the linkEA
987  *
988  * \retval              positive number for repaired cases
989  * \retval              0 if nothing to be repaired
990  * \retval              negative error number on failure
991  */
992 static int lfsck_namespace_shrink_linkea_cond(const struct lu_env *env,
993                                               struct lfsck_component *com,
994                                               struct dt_object *parent,
995                                               struct dt_object *child,
996                                               struct linkea_data *ldata,
997                                               struct lu_name *cname,
998                                               struct lu_fid *pfid)
999 {
1000         struct lu_fid           *cfid   = &lfsck_env_info(env)->lti_fid3;
1001         struct lustre_handle     lh     = { 0 };
1002         int                      rc;
1003         ENTRY;
1004
1005         rc = lfsck_ibits_lock(env, com->lc_lfsck, parent, &lh,
1006                               MDS_INODELOCK_UPDATE, LCK_EX);
1007         if (rc != 0)
1008                 RETURN(rc);
1009
1010         dt_read_lock(env, parent, 0);
1011         if (unlikely(lfsck_is_dead_obj(parent))) {
1012                 dt_read_unlock(env, parent);
1013                 lfsck_ibits_unlock(&lh, LCK_EX);
1014                 rc = lfsck_namespace_shrink_linkea(env, com, child, ldata,
1015                                                    cname, pfid, true);
1016
1017                 RETURN(rc);
1018         }
1019
1020         rc = dt_lookup(env, parent, (struct dt_rec *)cfid,
1021                        (const struct dt_key *)cname->ln_name,
1022                        BYPASS_CAPA);
1023         dt_read_unlock(env, parent);
1024
1025         /* It is safe to release the ldlm lock, because when the logic come
1026          * here, we have got all the needed information above whether the
1027          * linkEA entry is valid or not. It is not important that others
1028          * may add new linkEA entry after the ldlm lock released. If other
1029          * has removed the specified linkEA entry by race, then it is OK,
1030          * because the subsequent lfsck_namespace_shrink_linkea() can handle
1031          * such case. */
1032         lfsck_ibits_unlock(&lh, LCK_EX);
1033         if (rc == -ENOENT) {
1034                 rc = lfsck_namespace_shrink_linkea(env, com, child, ldata,
1035                                                    cname, pfid, true);
1036
1037                 RETURN(rc);
1038         }
1039
1040         if (rc != 0)
1041                 RETURN(rc);
1042
1043         /* The LFSCK just found some internal status of cross-MDTs
1044          * create operation. That is normal. */
1045         if (lu_fid_eq(cfid, lfsck_dto2fid(child))) {
1046                 linkea_next_entry(ldata);
1047
1048                 RETURN(0);
1049         }
1050
1051         rc = lfsck_namespace_shrink_linkea(env, com, child, ldata, cname,
1052                                            pfid, true);
1053
1054         RETURN(rc);
1055 }
1056
1057 /**
1058  * Conditionally replace name entry in the parent.
1059  *
1060  * As required, the LFSCK may re-create the lost MDT-object for dangling
1061  * name entry, but such repairing may be wrong because of bad FID in the
1062  * name entry. As the LFSCK processing, the real MDT-object may be found,
1063  * then the LFSCK should check whether the former re-created MDT-object
1064  * has been modified or not, if not, then destroy it and update the name
1065  * entry in the parent to reference the real MDT-object.
1066  *
1067  * \param[in] env       pointer to the thread context
1068  * \param[in] com       pointer to the lfsck component
1069  * \param[in] parent    pointer to the parent directory
1070  * \param[in] child     pointer to the MDT-object that may be the real
1071  *                      MDT-object corresponding to the name entry in parent
1072  * \param[in] cfid      the current FID in the name entry
1073  * \param[in] cname     contains the name of the child in the parent directory
1074  *
1075  * \retval              positive number for repaired cases
1076  * \retval              0 if nothing to be repaired
1077  * \retval              negative error number on failure
1078  */
1079 static int lfsck_namespace_replace_cond(const struct lu_env *env,
1080                                         struct lfsck_component *com,
1081                                         struct dt_object *parent,
1082                                         struct dt_object *child,
1083                                         const struct lu_fid *cfid,
1084                                         const struct lu_name *cname)
1085 {
1086         struct lfsck_thread_info        *info   = lfsck_env_info(env);
1087         struct lu_fid                   *tfid   = &info->lti_fid5;
1088         struct lu_attr                  *la     = &info->lti_la;
1089         struct dt_insert_rec            *rec    = &info->lti_dt_rec;
1090         struct lfsck_instance           *lfsck  = com->lc_lfsck;
1091         struct dt_device                *dev    = lfsck->li_next;
1092         const char                      *name   = cname->ln_name;
1093         struct dt_object                *obj    = NULL;
1094         struct lustre_handle             plh    = { 0 };
1095         struct lustre_handle             clh    = { 0 };
1096         struct linkea_data               ldata  = { 0 };
1097         struct thandle                  *th     = NULL;
1098         bool                             exist  = true;
1099         int                              rc     = 0;
1100         ENTRY;
1101
1102         rc = lfsck_ibits_lock(env, lfsck, parent, &plh,
1103                               MDS_INODELOCK_UPDATE, LCK_EX);
1104         if (rc != 0)
1105                 GOTO(log, rc);
1106
1107         if (!fid_is_sane(cfid)) {
1108                 exist = false;
1109                 goto replace;
1110         }
1111
1112         obj = lfsck_object_find(env, lfsck, cfid);
1113         if (IS_ERR(obj)) {
1114                 rc = PTR_ERR(obj);
1115                 if (rc == -ENOENT) {
1116                         exist = false;
1117                         goto replace;
1118                 }
1119
1120                 GOTO(log, rc);
1121         }
1122
1123         if (!dt_object_exists(obj)) {
1124                 exist = false;
1125                 goto replace;
1126         }
1127
1128         rc = dt_lookup(env, parent, (struct dt_rec *)tfid,
1129                        (const struct dt_key *)name, BYPASS_CAPA);
1130         if (rc == -ENOENT) {
1131                 exist = false;
1132                 goto replace;
1133         }
1134
1135         if (rc != 0)
1136                 GOTO(log, rc);
1137
1138         /* Someone changed the name entry, cannot replace it. */
1139         if (!lu_fid_eq(cfid, tfid))
1140                 GOTO(log, rc = 0);
1141
1142         /* lock the object to be destroyed. */
1143         rc = lfsck_ibits_lock(env, lfsck, obj, &clh,
1144                               MDS_INODELOCK_UPDATE |
1145                               MDS_INODELOCK_XATTR, LCK_EX);
1146         if (rc != 0)
1147                 GOTO(log, rc);
1148
1149         if (unlikely(lfsck_is_dead_obj(obj))) {
1150                 exist = false;
1151                 goto replace;
1152         }
1153
1154         rc = dt_attr_get(env, obj, la, BYPASS_CAPA);
1155         if (rc != 0)
1156                 GOTO(log, rc);
1157
1158         /* The object has been modified by other(s), or it is not created by
1159          * LFSCK, the two cases are indistinguishable. So cannot replace it. */
1160         if (la->la_ctime != 0)
1161                 GOTO(log, rc);
1162
1163         if (S_ISREG(la->la_mode)) {
1164                 rc = dt_xattr_get(env, obj, &LU_BUF_NULL, XATTR_NAME_LOV,
1165                                   BYPASS_CAPA);
1166                 /* If someone has created related OST-object(s),
1167                  * then keep it. */
1168                 if ((rc > 0) || (rc < 0 && rc != -ENODATA))
1169                         GOTO(log, rc = (rc > 0 ? 0 : rc));
1170         }
1171
1172 replace:
1173         dt_read_lock(env, child, 0);
1174         rc = lfsck_links_read2(env, child, &ldata);
1175         dt_read_unlock(env, child);
1176
1177         /* Someone changed the child, no need to replace. */
1178         if (rc == -ENODATA)
1179                 GOTO(log, rc = 0);
1180
1181         if (rc != 0)
1182                 GOTO(log, rc);
1183
1184         rc = linkea_links_find(&ldata, cname, lfsck_dto2fid(parent));
1185         /* Someone moved the child, no need to replace. */
1186         if (rc != 0)
1187                 GOTO(log, rc = 0);
1188
1189         if (lfsck->li_bookmark_ram.lb_param & LPF_DRYRUN)
1190                 GOTO(log, rc = 1);
1191
1192         th = dt_trans_create(env, dev);
1193         if (IS_ERR(th))
1194                 GOTO(log, rc = PTR_ERR(th));
1195
1196         if (exist) {
1197                 rc = dt_declare_destroy(env, obj, th);
1198                 if (rc != 0)
1199                         GOTO(stop, rc);
1200         }
1201
1202         rc = dt_declare_delete(env, parent, (const struct dt_key *)name, th);
1203         if (rc != 0)
1204                 GOTO(stop, rc);
1205
1206         rec->rec_type = S_IFDIR;
1207         rec->rec_fid = lfsck_dto2fid(child);
1208         rc = dt_declare_insert(env, parent, (const struct dt_rec *)rec,
1209                                (const struct dt_key *)name, th);
1210         if (rc != 0)
1211                 GOTO(stop, rc);
1212
1213         rc = dt_trans_start(env, dev, th);
1214         if (rc != 0)
1215                 GOTO(stop, rc);
1216
1217         if (exist) {
1218                 rc = dt_destroy(env, obj, th);
1219                 if (rc != 0)
1220                         GOTO(stop, rc);
1221         }
1222
1223         /* The old name entry maybe not exist. */
1224         dt_delete(env, parent, (const struct dt_key *)name, th,
1225                   BYPASS_CAPA);
1226
1227         rc = dt_insert(env, parent, (const struct dt_rec *)rec,
1228                        (const struct dt_key *)name, th, BYPASS_CAPA, 1);
1229
1230         GOTO(stop, rc = (rc == 0 ? 1 : rc));
1231
1232 stop:
1233         dt_trans_stop(env, dev, th);
1234
1235 log:
1236         lfsck_ibits_unlock(&clh, LCK_EX);
1237         lfsck_ibits_unlock(&plh, LCK_EX);
1238         if (obj != NULL && !IS_ERR(obj))
1239                 lfsck_object_put(env, obj);
1240
1241         CDEBUG(D_LFSCK, "%s: namespace LFSCK conditionally destroy the "
1242                "object "DFID" because of conflict with the object "DFID
1243                " under the parent "DFID" with name %s: rc = %d\n",
1244                lfsck_lfsck2name(lfsck), PFID(cfid),
1245                PFID(lfsck_dto2fid(child)), PFID(lfsck_dto2fid(parent)),
1246                name, rc);
1247
1248         return rc;
1249 }
1250
1251 /**
1252  * Overwrite the linkEA for the object with the given ldata.
1253  *
1254  * The caller should take the ldlm lock before the calling.
1255  *
1256  * \param[in] env       pointer to the thread context
1257  * \param[in] com       pointer to the lfsck component
1258  * \param[in] obj       pointer to the dt_object to be handled
1259  * \param[in] ldata     pointer to the new linkEA data
1260  *
1261  * \retval              positive number for repaired cases
1262  * \retval              0 if nothing to be repaired
1263  * \retval              negative error number on failure
1264  */
1265 int lfsck_namespace_rebuild_linkea(const struct lu_env *env,
1266                                    struct lfsck_component *com,
1267                                    struct dt_object *obj,
1268                                    struct linkea_data *ldata)
1269 {
1270         struct lfsck_instance           *lfsck  = com->lc_lfsck;
1271         struct dt_device                *dev    = lfsck->li_bottom;
1272         struct thandle                  *th     = NULL;
1273         struct lu_buf                    linkea_buf;
1274         int                              rc     = 0;
1275         ENTRY;
1276
1277         LASSERT(!dt_object_remote(obj));
1278
1279         th = dt_trans_create(env, dev);
1280         if (IS_ERR(th))
1281                 GOTO(log, rc = PTR_ERR(th));
1282
1283         lfsck_buf_init(&linkea_buf, ldata->ld_buf->lb_buf,
1284                        ldata->ld_leh->leh_len);
1285         rc = dt_declare_xattr_set(env, obj, &linkea_buf,
1286                                   XATTR_NAME_LINK, 0, th);
1287         if (rc != 0)
1288                 GOTO(stop, rc);
1289
1290         rc = dt_trans_start_local(env, dev, th);
1291         if (rc != 0)
1292                 GOTO(stop, rc);
1293
1294         dt_write_lock(env, obj, 0);
1295         if (unlikely(lfsck_is_dead_obj(obj)))
1296                 GOTO(unlock, rc = 0);
1297
1298         if (lfsck->li_bookmark_ram.lb_param & LPF_DRYRUN)
1299                 GOTO(unlock, rc = 1);
1300
1301         rc = dt_xattr_set(env, obj, &linkea_buf,
1302                           XATTR_NAME_LINK, 0, th, BYPASS_CAPA);
1303
1304         GOTO(unlock, rc = (rc == 0 ? 1 : rc));
1305
1306 unlock:
1307         dt_write_unlock(env, obj);
1308
1309 stop:
1310         dt_trans_stop(env, dev, th);
1311
1312 log:
1313         CDEBUG(D_LFSCK, "%s: namespace LFSCK rebuild linkEA for the "
1314                "object "DFID": rc = %d\n",
1315                lfsck_lfsck2name(lfsck), PFID(lfsck_dto2fid(obj)), rc);
1316
1317         if (rc != 0) {
1318                 struct lfsck_namespace *ns = com->lc_file_ram;
1319
1320                 ns->ln_flags |= LF_INCONSISTENT;
1321         }
1322
1323         return rc;
1324 }
1325
1326 /**
1327  * Repair invalid name entry.
1328  *
1329  * If the name entry contains invalid information, such as bad file type
1330  * or (and) corrupted object FID, then either remove the name entry or
1331  * udpate the name entry with the given (right) information.
1332  *
1333  * \param[in] env       pointer to the thread context
1334  * \param[in] com       pointer to the lfsck component
1335  * \param[in] parent    pointer to the parent directory
1336  * \param[in] child     pointer to the object referenced by the name entry
1337  * \param[in] name      the old name of the child under the parent directory
1338  * \param[in] name2     the new name of the child under the parent directory
1339  * \param[in] type      the type claimed by the name entry
1340  * \param[in] update    update the name entry if true; otherwise, remove it
1341  * \param[in] dec       decrease the parent nlink count if true
1342  *
1343  * \retval              positive number for repaired successfully
1344  * \retval              0 if nothing to be repaired
1345  * \retval              negative error number on failure
1346  */
1347 int lfsck_namespace_repair_dirent(const struct lu_env *env,
1348                                   struct lfsck_component *com,
1349                                   struct dt_object *parent,
1350                                   struct dt_object *child,
1351                                   const char *name, const char *name2,
1352                                   __u16 type, bool update, bool dec)
1353 {
1354         struct lfsck_thread_info        *info   = lfsck_env_info(env);
1355         struct dt_insert_rec            *rec    = &info->lti_dt_rec;
1356         const struct lu_fid             *cfid   = lfsck_dto2fid(child);
1357         struct lu_fid                   *tfid   = &info->lti_fid5;
1358         struct lfsck_instance           *lfsck  = com->lc_lfsck;
1359         struct dt_device                *dev    = lfsck->li_next;
1360         struct thandle                  *th     = NULL;
1361         struct lustre_handle             lh     = { 0 };
1362         int                              rc     = 0;
1363         ENTRY;
1364
1365         if (unlikely(!dt_try_as_dir(env, parent)))
1366                 GOTO(log, rc = -ENOTDIR);
1367
1368         rc = lfsck_ibits_lock(env, lfsck, parent, &lh,
1369                               MDS_INODELOCK_UPDATE, LCK_EX);
1370         if (rc != 0)
1371                 GOTO(log, rc);
1372
1373         th = dt_trans_create(env, dev);
1374         if (IS_ERR(th))
1375                 GOTO(unlock1, rc = PTR_ERR(th));
1376
1377         rc = dt_declare_delete(env, parent, (const struct dt_key *)name, th);
1378         if (rc != 0)
1379                 GOTO(stop, rc);
1380
1381         if (update) {
1382                 rec->rec_type = lfsck_object_type(child) & S_IFMT;
1383                 rec->rec_fid = cfid;
1384                 rc = dt_declare_insert(env, parent,
1385                                        (const struct dt_rec *)rec,
1386                                        (const struct dt_key *)name2, th);
1387                 if (rc != 0)
1388                         GOTO(stop, rc);
1389         }
1390
1391         if (dec) {
1392                 rc = dt_declare_ref_del(env, parent, th);
1393                 if (rc != 0)
1394                         GOTO(stop, rc);
1395         }
1396
1397         rc = dt_trans_start(env, dev, th);
1398         if (rc != 0)
1399                 GOTO(stop, rc);
1400
1401         dt_write_lock(env, parent, 0);
1402         rc = dt_lookup(env, parent, (struct dt_rec *)tfid,
1403                        (const struct dt_key *)name, BYPASS_CAPA);
1404         /* Someone has removed the bad name entry by race. */
1405         if (rc == -ENOENT)
1406                 GOTO(unlock2, rc = 0);
1407
1408         if (rc != 0)
1409                 GOTO(unlock2, rc);
1410
1411         /* Someone has removed the bad name entry and reuse it for other
1412          * object by race. */
1413         if (!lu_fid_eq(tfid, cfid))
1414                 GOTO(unlock2, rc = 0);
1415
1416         if (lfsck->li_bookmark_ram.lb_param & LPF_DRYRUN)
1417                 GOTO(unlock2, rc = 1);
1418
1419         rc = dt_delete(env, parent, (const struct dt_key *)name, th,
1420                        BYPASS_CAPA);
1421         if (rc != 0)
1422                 GOTO(unlock2, rc);
1423
1424         if (update) {
1425                 rc = dt_insert(env, parent,
1426                                (const struct dt_rec *)rec,
1427                                (const struct dt_key *)name2, th,
1428                                BYPASS_CAPA, 1);
1429                 if (rc != 0)
1430                         GOTO(unlock2, rc);
1431         }
1432
1433         if (dec) {
1434                 rc = dt_ref_del(env, parent, th);
1435                 if (rc != 0)
1436                         GOTO(unlock2, rc);
1437         }
1438
1439         GOTO(unlock2, rc = (rc == 0 ? 1 : rc));
1440
1441 unlock2:
1442         dt_write_unlock(env, parent);
1443
1444 stop:
1445         dt_trans_stop(env, dev, th);
1446
1447         /* We are not sure whether the child will become orphan or not.
1448          * Record it in the LFSCK tracing file for further checking in
1449          * the second-stage scanning. */
1450         if (!update && !dec && rc == 0)
1451                 lfsck_namespace_trace_update(env, com, cfid,
1452                                              LNTF_CHECK_LINKEA, true);
1453
1454 unlock1:
1455         lfsck_ibits_unlock(&lh, LCK_EX);
1456
1457 log:
1458         CDEBUG(D_LFSCK, "%s: namespace LFSCK assistant found bad name "
1459                "entry for: parent "DFID", child "DFID", name %s, type "
1460                "in name entry %o, type claimed by child %o. repair it "
1461                "by %s with new name2 %s: rc = %d\n", lfsck_lfsck2name(lfsck),
1462                PFID(lfsck_dto2fid(parent)), PFID(lfsck_dto2fid(child)),
1463                name, type, update ? lfsck_object_type(child) : 0,
1464                update ? "updating" : "removing", name2, rc);
1465
1466         if (rc != 0) {
1467                 struct lfsck_namespace *ns = com->lc_file_ram;
1468
1469                 ns->ln_flags |= LF_INCONSISTENT;
1470         }
1471
1472         return rc;
1473 }
1474
1475 /**
1476  * Update the ".." name entry for the given object.
1477  *
1478  * The object's ".." is corrupted, this function will update the ".." name
1479  * entry with the given pfid, and the linkEA with the given ldata.
1480  *
1481  * The caller should take the ldlm lock before the calling.
1482  *
1483  * \param[in] env       pointer to the thread context
1484  * \param[in] com       pointer to the lfsck component
1485  * \param[in] obj       pointer to the dt_object to be handled
1486  * \param[in] pfid      the new fid for the object's ".." name entry
1487  * \param[in] cname     the name for the @obj in the parent directory
1488  *
1489  * \retval              positive number for repaired cases
1490  * \retval              0 if nothing to be repaired
1491  * \retval              negative error number on failure
1492  */
1493 static int lfsck_namespace_repair_unmatched_pairs(const struct lu_env *env,
1494                                                   struct lfsck_component *com,
1495                                                   struct dt_object *obj,
1496                                                   const struct lu_fid *pfid,
1497                                                   struct lu_name *cname)
1498 {
1499         struct lfsck_thread_info        *info   = lfsck_env_info(env);
1500         struct dt_insert_rec            *rec    = &info->lti_dt_rec;
1501         struct lfsck_instance           *lfsck  = com->lc_lfsck;
1502         struct dt_device                *dev    = lfsck->li_bottom;
1503         struct thandle                  *th     = NULL;
1504         struct linkea_data               ldata  = { 0 };
1505         struct lu_buf                    linkea_buf;
1506         int                              rc     = 0;
1507         ENTRY;
1508
1509         LASSERT(!dt_object_remote(obj));
1510         LASSERT(S_ISDIR(lfsck_object_type(obj)));
1511
1512         rc = linkea_data_new(&ldata, &info->lti_big_buf);
1513         if (rc != 0)
1514                 GOTO(log, rc);
1515
1516         rc = linkea_add_buf(&ldata, cname, pfid);
1517         if (rc != 0)
1518                 GOTO(log, rc);
1519
1520         lfsck_buf_init(&linkea_buf, ldata.ld_buf->lb_buf,
1521                        ldata.ld_leh->leh_len);
1522
1523         th = dt_trans_create(env, dev);
1524         if (IS_ERR(th))
1525                 GOTO(log, rc = PTR_ERR(th));
1526
1527         rc = dt_declare_delete(env, obj, (const struct dt_key *)dotdot, th);
1528         if (rc != 0)
1529                 GOTO(stop, rc);
1530
1531         rec->rec_type = S_IFDIR;
1532         rec->rec_fid = pfid;
1533         rc = dt_declare_insert(env, obj, (const struct dt_rec *)rec,
1534                                (const struct dt_key *)dotdot, th);
1535         if (rc != 0)
1536                 GOTO(stop, rc);
1537
1538         rc = dt_declare_xattr_set(env, obj, &linkea_buf,
1539                                   XATTR_NAME_LINK, 0, th);
1540         if (rc != 0)
1541                 GOTO(stop, rc);
1542
1543         rc = dt_trans_start_local(env, dev, th);
1544         if (rc != 0)
1545                 GOTO(stop, rc);
1546
1547         dt_write_lock(env, obj, 0);
1548         if (unlikely(lfsck_is_dead_obj(obj)))
1549                 GOTO(unlock, rc = 0);
1550
1551         if (lfsck->li_bookmark_ram.lb_param & LPF_DRYRUN)
1552                 GOTO(unlock, rc = 1);
1553
1554         /* The old ".." name entry maybe not exist. */
1555         dt_delete(env, obj, (const struct dt_key *)dotdot, th,
1556                   BYPASS_CAPA);
1557
1558         rc = dt_insert(env, obj, (const struct dt_rec *)rec,
1559                        (const struct dt_key *)dotdot, th, BYPASS_CAPA, 1);
1560         if (rc != 0)
1561                 GOTO(unlock, rc);
1562
1563         rc = dt_xattr_set(env, obj, &linkea_buf,
1564                           XATTR_NAME_LINK, 0, th, BYPASS_CAPA);
1565
1566         GOTO(unlock, rc = (rc == 0 ? 1 : rc));
1567
1568 unlock:
1569         dt_write_unlock(env, obj);
1570
1571 stop:
1572         dt_trans_stop(env, dev, th);
1573
1574 log:
1575         CDEBUG(D_LFSCK, "%s: namespace LFSCK rebuild dotdot name entry for "
1576                "the object "DFID", new parent "DFID": rc = %d\n",
1577                lfsck_lfsck2name(lfsck), PFID(lfsck_dto2fid(obj)),
1578                PFID(pfid), rc);
1579
1580         if (rc != 0) {
1581                 struct lfsck_namespace *ns = com->lc_file_ram;
1582
1583                 ns->ln_flags |= LF_INCONSISTENT;
1584         }
1585
1586         return rc;
1587 }
1588
1589 /**
1590  * Handle orphan @obj during Double Scan Directory.
1591  *
1592  * Remove the @obj's current (invalid) linkEA entries, and insert
1593  * it in the directory .lustre/lost+found/MDTxxxx/ with the name:
1594  * ${FID}-${PFID}-D-${conflict_version}
1595  *
1596  * The caller should take the ldlm lock before the calling.
1597  *
1598  * \param[in] env       pointer to the thread context
1599  * \param[in] com       pointer to the lfsck component
1600  * \param[in] obj       pointer to the orphan object to be handled
1601  * \param[in] pfid      the new fid for the object's ".." name entry
1602  * \param[in,out] lh    ldlm lock handler for the given @obj
1603  * \param[out] type     to tell the caller what the inconsistency is
1604  *
1605  * \retval              positive number for repaired cases
1606  * \retval              0 if nothing to be repaired
1607  * \retval              negative error number on failure
1608  */
1609 static int
1610 lfsck_namespace_dsd_orphan(const struct lu_env *env,
1611                            struct lfsck_component *com,
1612                            struct dt_object *obj,
1613                            const struct lu_fid *pfid,
1614                            struct lustre_handle *lh,
1615                            enum lfsck_namespace_inconsistency_type *type)
1616 {
1617         struct lfsck_thread_info *info = lfsck_env_info(env);
1618         int                       rc;
1619         ENTRY;
1620
1621         /* Remove the unrecognized linkEA. */
1622         rc = lfsck_namespace_links_remove(env, com, obj);
1623         lfsck_ibits_unlock(lh, LCK_EX);
1624         if (rc < 0 && rc != -ENODATA)
1625                 RETURN(rc);
1626
1627         *type = LNIT_MUL_REF;
1628         /* The unique linkEA is invalid, even if the ".." name entry may be
1629          * valid, we still cannot know via which name entry this directory
1630          * will be referenced. Then handle it as pure orphan. */
1631         snprintf(info->lti_tmpbuf, sizeof(info->lti_tmpbuf),
1632                  "-"DFID, PFID(pfid));
1633         rc = lfsck_namespace_insert_orphan(env, com, obj,
1634                                            info->lti_tmpbuf, "D", NULL);
1635
1636         RETURN(rc);
1637 }
1638
1639 /**
1640  * Double Scan Directory object for single linkEA entry case.
1641  *
1642  * The given @child has unique linkEA entry. If the linkEA entry is valid,
1643  * then check whether the name is in the namespace or not, if not, add the
1644  * missing name entry back to namespace. If the linkEA entry is invalid,
1645  * then remove it and insert the @child in the .lustre/lost+found/MDTxxxx/
1646  * as an orphan.
1647  *
1648  * \param[in] env       pointer to the thread context
1649  * \param[in] com       pointer to the lfsck component
1650  * \param[in] child     pointer to the directory to be double scanned
1651  * \param[in] pfid      the FID corresponding to the ".." entry
1652  * \param[in] ldata     pointer to the linkEA data for the given @child
1653  * \param[in,out] lh    ldlm lock handler for the given @child
1654  * \param[out] type     to tell the caller what the inconsistency is
1655  * \param[in] retry     if found inconsistency, but the caller does not hold
1656  *                      ldlm lock on the @child, then set @retry as true
1657  *
1658  * \retval              positive number for repaired cases
1659  * \retval              0 if nothing to be repaired
1660  * \retval              negative error number on failure
1661  */
1662 static int
1663 lfsck_namespace_dsd_single(const struct lu_env *env,
1664                            struct lfsck_component *com,
1665                            struct dt_object *child,
1666                            const struct lu_fid *pfid,
1667                            struct linkea_data *ldata,
1668                            struct lustre_handle *lh,
1669                            enum lfsck_namespace_inconsistency_type *type,
1670                            bool *retry)
1671 {
1672         struct lfsck_thread_info *info          = lfsck_env_info(env);
1673         struct lu_name           *cname         = &info->lti_name;
1674         const struct lu_fid      *cfid          = lfsck_dto2fid(child);
1675         struct lu_fid            *tfid          = &info->lti_fid3;
1676         struct lfsck_instance    *lfsck         = com->lc_lfsck;
1677         struct dt_object         *parent        = NULL;
1678         int                       rc            = 0;
1679         ENTRY;
1680
1681         lfsck_namespace_unpack_linkea_entry(ldata, cname, tfid, info->lti_key);
1682         /* The unique linkEA entry with bad parent will be handled as orphan. */
1683         if (!fid_is_sane(tfid)) {
1684                 if (!lustre_handle_is_used(lh) && retry != NULL)
1685                         *retry = true;
1686                 else
1687                         rc = lfsck_namespace_dsd_orphan(env, com, child,
1688                                                         pfid, lh, type);
1689
1690                 GOTO(out, rc);
1691         }
1692
1693         parent = lfsck_object_find_bottom(env, lfsck, tfid);
1694         if (IS_ERR(parent))
1695                 GOTO(out, rc = PTR_ERR(parent));
1696
1697         /* We trust the unique linkEA entry in spite of whether it matches the
1698          * ".." name entry or not. Because even if the linkEA entry is wrong
1699          * and the ".." name entry is right, we still cannot know via which
1700          * name entry the child will be referenced, since all known entries
1701          * have been verified during the first-stage scanning. */
1702         if (!dt_object_exists(parent)) {
1703                 if (!lustre_handle_is_used(lh) && retry != NULL) {
1704                         *retry = true;
1705
1706                         GOTO(out, rc = 0);
1707                 }
1708
1709                 lfsck_ibits_unlock(lh, LCK_EX);
1710                 /* Create the lost parent as an orphan. */
1711                 rc = lfsck_namespace_create_orphan(env, com, parent);
1712                 if (rc >= 0)
1713                         /* Add the missing name entry to the parent. */
1714                         rc = lfsck_namespace_insert_normal(env, com, parent,
1715                                                         child, cname->ln_name);
1716
1717                 GOTO(out, rc);
1718         }
1719
1720         /* The unique linkEA entry with bad parent will be handled as orphan. */
1721         if (unlikely(!dt_try_as_dir(env, parent))) {
1722                 if (!lustre_handle_is_used(lh) && retry != NULL)
1723                         *retry = true;
1724                 else
1725                         rc = lfsck_namespace_dsd_orphan(env, com, child,
1726                                                         pfid, lh, type);
1727
1728                 GOTO(out, rc);
1729         }
1730
1731         rc = dt_lookup(env, parent, (struct dt_rec *)tfid,
1732                        (const struct dt_key *)cname->ln_name, BYPASS_CAPA);
1733         if (rc == -ENOENT) {
1734                 if (!lustre_handle_is_used(lh) && retry != NULL) {
1735                         *retry = true;
1736
1737                         GOTO(out, rc = 0);
1738                 }
1739
1740                 lfsck_ibits_unlock(lh, LCK_EX);
1741                 /* Add the missing name entry back to the namespace. */
1742                 rc = lfsck_namespace_insert_normal(env, com, parent, child,
1743                                                    cname->ln_name);
1744
1745                 GOTO(out, rc);
1746         }
1747
1748         if (rc != 0)
1749                 GOTO(out, rc);
1750
1751         if (!lu_fid_eq(tfid, cfid)) {
1752                 if (!lustre_handle_is_used(lh) && retry != NULL) {
1753                         *retry = true;
1754
1755                         GOTO(out, rc = 0);
1756                 }
1757
1758                 lfsck_ibits_unlock(lh, LCK_EX);
1759                 /* The name entry references another MDT-object that
1760                  * may be created by the LFSCK for repairing dangling
1761                  * name entry. Try to replace it. */
1762                 rc = lfsck_namespace_replace_cond(env, com, parent, child,
1763                                                   tfid, cname);
1764                 if (rc == 0)
1765                         rc = lfsck_namespace_dsd_orphan(env, com, child,
1766                                                         pfid, lh, type);
1767
1768                 GOTO(out, rc);
1769         }
1770
1771         /* The ".." name entry is wrong, update it. */
1772         if (!lu_fid_eq(pfid, lfsck_dto2fid(parent))) {
1773                 if (!lustre_handle_is_used(lh) && retry != NULL) {
1774                         *retry = true;
1775
1776                         GOTO(out, rc = 0);
1777                 }
1778
1779                 *type = LNIT_UNMATCHED_PAIRS;
1780                 rc = lfsck_namespace_repair_unmatched_pairs(env, com, child,
1781                                                 lfsck_dto2fid(parent), cname);
1782         }
1783
1784         GOTO(out, rc);
1785
1786 out:
1787         if (parent != NULL && !IS_ERR(parent))
1788                 lfsck_object_put(env, parent);
1789
1790         return rc;
1791 }
1792
1793 /**
1794  * Double Scan Directory object for multiple linkEA entries case.
1795  *
1796  * The given @child has multiple linkEA entries. There is at most one linkEA
1797  * entry will be valid, all the others will be removed. Firstly, the function
1798  * will try to find out the linkEA entry for which the name entry exists under
1799  * the given parent (@pfid). If there is no linkEA entry that matches the given
1800  * ".." name entry, then tries to find out the first linkEA entry that both the
1801  * parent and the name entry exist to rebuild a new ".." name entry.
1802  *
1803  * \param[in] env       pointer to the thread context
1804  * \param[in] com       pointer to the lfsck component
1805  * \param[in] child     pointer to the directory to be double scanned
1806  * \param[in] pfid      the FID corresponding to the ".." entry
1807  * \param[in] ldata     pointer to the linkEA data for the given @child
1808  * \param[in,out] lh    ldlm lock handler for the given @child
1809  * \param[out] type     to tell the caller what the inconsistency is
1810  * \param[in] lpf       true if the ".." entry is under lost+found/MDTxxxx/
1811  *
1812  * \retval              positive number for repaired cases
1813  * \retval              0 if nothing to be repaired
1814  * \retval              negative error number on failure
1815  */
1816 static int
1817 lfsck_namespace_dsd_multiple(const struct lu_env *env,
1818                              struct lfsck_component *com,
1819                              struct dt_object *child,
1820                              const struct lu_fid *pfid,
1821                              struct linkea_data *ldata,
1822                              struct lustre_handle *lh,
1823                              enum lfsck_namespace_inconsistency_type *type,
1824                              bool lpf)
1825 {
1826         struct lfsck_thread_info *info          = lfsck_env_info(env);
1827         struct lu_name           *cname         = &info->lti_name;
1828         const struct lu_fid      *cfid          = lfsck_dto2fid(child);
1829         struct lu_fid            *tfid          = &info->lti_fid3;
1830         struct lu_fid            *pfid2         = &info->lti_fid4;
1831         struct lfsck_namespace   *ns            = com->lc_file_ram;
1832         struct lfsck_instance    *lfsck         = com->lc_lfsck;
1833         struct lfsck_bookmark    *bk            = &lfsck->li_bookmark_ram;
1834         struct dt_object         *parent        = NULL;
1835         struct linkea_data        ldata_new     = { 0 };
1836         int                       count         = 0;
1837         int                       rc            = 0;
1838         bool                      once          = true;
1839         ENTRY;
1840
1841 again:
1842         while (ldata->ld_lee != NULL) {
1843                 lfsck_namespace_unpack_linkea_entry(ldata, cname, tfid,
1844                                                     info->lti_key);
1845                 /* Drop repeated linkEA entries. */
1846                 lfsck_namespace_filter_linkea_entry(ldata, cname, tfid, true);
1847                 /* Drop invalid linkEA entry. */
1848                 if (!fid_is_sane(tfid)) {
1849                         linkea_del_buf(ldata, cname);
1850                         continue;
1851                 }
1852
1853                 /* If current dotdot is the .lustre/lost+found/MDTxxxx/,
1854                  * then it is possible that: the directry object has ever
1855                  * been lost, but its name entry was there. In the former
1856                  * LFSCK run, during the first-stage scanning, the LFSCK
1857                  * found the dangling name entry, but it did not recreate
1858                  * the lost object, and when moved to the second-stage
1859                  * scanning, some children objects of the lost directory
1860                  * object were found, then the LFSCK recreated such lost
1861                  * directory object as an orphan.
1862                  *
1863                  * When the LFSCK runs again, if the dangling name is still
1864                  * there, the LFSCK should move the orphan directory object
1865                  * back to the normal namespace. */
1866                 if (!lpf && !lu_fid_eq(pfid, tfid) && once) {
1867                         linkea_next_entry(ldata);
1868                         continue;
1869                 }
1870
1871                 parent = lfsck_object_find_bottom(env, lfsck, tfid);
1872                 if (IS_ERR(parent))
1873                         RETURN(PTR_ERR(parent));
1874
1875                 if (!dt_object_exists(parent)) {
1876                         lfsck_object_put(env, parent);
1877                         if (ldata->ld_leh->leh_reccount > 1) {
1878                                 /* If it is NOT the last linkEA entry, then
1879                                  * there is still other chance to make the
1880                                  * child to be visible via other parent, then
1881                                  * remove this linkEA entry. */
1882                                 linkea_del_buf(ldata, cname);
1883                                 continue;
1884                         }
1885
1886                         break;
1887                 }
1888
1889                 /* The linkEA entry with bad parent will be removed. */
1890                 if (unlikely(!dt_try_as_dir(env, parent))) {
1891                         lfsck_object_put(env, parent);
1892                         linkea_del_buf(ldata, cname);
1893                         continue;
1894                 }
1895
1896                 rc = dt_lookup(env, parent, (struct dt_rec *)tfid,
1897                                (const struct dt_key *)cname->ln_name,
1898                                BYPASS_CAPA);
1899                 *pfid2 = *lfsck_dto2fid(parent);
1900                 if (rc == -ENOENT) {
1901                         lfsck_object_put(env, parent);
1902                         linkea_next_entry(ldata);
1903                         continue;
1904                 }
1905
1906                 if (rc != 0) {
1907                         lfsck_object_put(env, parent);
1908
1909                         RETURN(rc);
1910                 }
1911
1912                 if (lu_fid_eq(tfid, cfid)) {
1913                         lfsck_object_put(env, parent);
1914                         if (!lu_fid_eq(pfid, pfid2)) {
1915                                 *type = LNIT_UNMATCHED_PAIRS;
1916                                 rc = lfsck_namespace_repair_unmatched_pairs(env,
1917                                                 com, child, pfid2, cname);
1918
1919                                 RETURN(rc);
1920                         }
1921
1922 rebuild:
1923                         /* It is the most common case that we find the
1924                          * name entry corresponding to the linkEA entry
1925                          * that matches the ".." name entry. */
1926                         rc = linkea_data_new(&ldata_new, &info->lti_big_buf);
1927                         if (rc != 0)
1928                                 RETURN(rc);
1929
1930                         rc = linkea_add_buf(&ldata_new, cname, pfid2);
1931                         if (rc != 0)
1932                                 RETURN(rc);
1933
1934                         rc = lfsck_namespace_rebuild_linkea(env, com, child,
1935                                                             &ldata_new);
1936                         if (rc < 0)
1937                                 RETURN(rc);
1938
1939                         linkea_del_buf(ldata, cname);
1940                         linkea_first_entry(ldata);
1941                         /* There may be some invalid dangling name entries under
1942                          * other parent directories, remove all of them. */
1943                         while (ldata->ld_lee != NULL) {
1944                                 lfsck_namespace_unpack_linkea_entry(ldata,
1945                                                 cname, tfid, info->lti_key);
1946                                 if (!fid_is_sane(tfid))
1947                                         goto next;
1948
1949                                 parent = lfsck_object_find_bottom(env, lfsck,
1950                                                                   tfid);
1951                                 if (IS_ERR(parent)) {
1952                                         rc = PTR_ERR(parent);
1953                                         if (rc != -ENOENT &&
1954                                             bk->lb_param & LPF_FAILOUT)
1955                                                 RETURN(rc);
1956
1957                                         goto next;
1958                                 }
1959
1960                                 if (!dt_object_exists(parent)) {
1961                                         lfsck_object_put(env, parent);
1962                                         goto next;
1963                                 }
1964
1965                                 rc = lfsck_namespace_repair_dirent(env, com,
1966                                         parent, child, cname->ln_name,
1967                                         cname->ln_name, S_IFDIR, false, true);
1968                                 lfsck_object_put(env, parent);
1969                                 if (rc < 0) {
1970                                         if (bk->lb_param & LPF_FAILOUT)
1971                                                 RETURN(rc);
1972
1973                                         goto next;
1974                                 }
1975
1976                                 count += rc;
1977
1978 next:
1979                                 linkea_del_buf(ldata, cname);
1980                         }
1981
1982                         ns->ln_dirent_repaired += count;
1983
1984                         RETURN(rc);
1985                 }
1986
1987                 lfsck_ibits_unlock(lh, LCK_EX);
1988                 /* The name entry references another MDT-object that may be
1989                  * created by the LFSCK for repairing dangling name entry.
1990                  * Try to replace it. */
1991                 rc = lfsck_namespace_replace_cond(env, com, parent, child,
1992                                                   tfid, cname);
1993                 lfsck_object_put(env, parent);
1994                 if (rc < 0)
1995                         RETURN(rc);
1996
1997                 if (rc > 0)
1998                         goto rebuild;
1999
2000                 linkea_del_buf(ldata, cname);
2001         }
2002
2003         if (ldata->ld_leh->leh_reccount == 1) {
2004                 rc = lfsck_namespace_dsd_single(env, com, child, pfid, ldata,
2005                                                 lh, type, NULL);
2006
2007                 RETURN(rc);
2008         }
2009
2010         /* All linkEA entries are invalid and removed, then handle the @child
2011          * as an orphan.*/
2012         if (ldata->ld_leh->leh_reccount == 0) {
2013                 rc = lfsck_namespace_dsd_orphan(env, com, child, pfid, lh,
2014                                                 type);
2015
2016                 RETURN(rc);
2017         }
2018
2019         linkea_first_entry(ldata);
2020         /* If the dangling name entry for the orphan directory object has
2021          * been remvoed, then just check whether the directory object is
2022          * still under the .lustre/lost+found/MDTxxxx/ or not. */
2023         if (lpf) {
2024                 lpf = false;
2025                 goto again;
2026         }
2027
2028         /* There is no linkEA entry that matches the ".." name entry. Find
2029          * the first linkEA entry that both parent and name entry exist to
2030          * rebuild a new ".." name entry. */
2031         if (once) {
2032                 once = false;
2033                 goto again;
2034         }
2035
2036         RETURN(rc);
2037 }
2038
2039 /**
2040  * Double scan the directory object for namespace LFSCK.
2041  *
2042  * This function will verify the <parent, child> pairs in the namespace tree:
2043  * the parent references the child via some name entry that should be in the
2044  * child's linkEA entry, the child should back references the parent via its
2045  * ".." name entry.
2046  *
2047  * The LFSCK will scan every linkEA entry in turn until find out the first
2048  * matched pairs. If found, then all other linkEA entries will be dropped.
2049  * If all the linkEA entries cannot match the ".." name entry, then there
2050  * are serveral possible cases:
2051  *
2052  * 1) If there is only one linkEA entry, then trust it as long as the PFID
2053  *    in the linkEA entry is valid.
2054  *
2055  * 2) If there are multiple linkEA entries, then try to find the linkEA
2056  *    that matches the ".." name entry. If found, then all other entries
2057  *    are invalid; otherwise, it is quite possible that the ".." name entry
2058  *    is corrupted. Under such case, the LFSCK will rebuild the ".." name
2059  *    entry according to the first valid linkEA entry (both the parent and
2060  *    the name entry should exist).
2061  *
2062  * 3) If the directory object has no (valid) linkEA entry, then the
2063  *    directory object will be handled as pure orphan and inserted
2064  *    in the .lustre/lost+found/MDTxxxx/ with the name:
2065  *    ${self_FID}-${PFID}-D-${conflict_version}
2066  *
2067  * \param[in] env       pointer to the thread context
2068  * \param[in] com       pointer to the lfsck component
2069  * \param[in] child     pointer to the directory object to be handled
2070  * \param[in] flags     to indicate the specical checking on the @child
2071  *
2072  * \retval              positive number for repaired cases
2073  * \retval              0 if nothing to be repaired
2074  * \retval              negative error number on failure
2075  */
2076 static int lfsck_namespace_double_scan_dir(const struct lu_env *env,
2077                                            struct lfsck_component *com,
2078                                            struct dt_object *child, __u8 flags)
2079 {
2080         struct lfsck_thread_info *info          = lfsck_env_info(env);
2081         const struct lu_fid      *cfid          = lfsck_dto2fid(child);
2082         struct lu_fid            *pfid          = &info->lti_fid2;
2083         struct lfsck_namespace   *ns            = com->lc_file_ram;
2084         struct lfsck_instance    *lfsck         = com->lc_lfsck;
2085         struct lustre_handle      lh            = { 0 };
2086         struct linkea_data        ldata         = { 0 };
2087         bool                      unknown       = false;
2088         bool                      lpf           = false;
2089         bool                      retry         = false;
2090         enum lfsck_namespace_inconsistency_type type = LNIT_BAD_LINKEA;
2091         int                       rc            = 0;
2092         ENTRY;
2093
2094         LASSERT(!dt_object_remote(child));
2095
2096         if (!(lfsck->li_bookmark_ram.lb_param & LPF_ALL_TGT)) {
2097                 CDEBUG(D_LFSCK, "%s: some MDT(s) maybe NOT take part in the"
2098                        "the namespace LFSCK, then the LFSCK cannot guarantee"
2099                        "all the name entries have been verified in first-stage"
2100                        "scanning. So have to skip orphan related handling for"
2101                        "the directory object "DFID" with remote name entry\n",
2102                        lfsck_lfsck2name(lfsck), PFID(cfid));
2103
2104                 RETURN(0);
2105         }
2106
2107         if (unlikely(!dt_try_as_dir(env, child)))
2108                 GOTO(out, rc = -ENOTDIR);
2109
2110         /* We only take ldlm lock on the @child when required. When the
2111          * logic comes here for the first time, it is always false. */
2112         if (0) {
2113
2114 lock:
2115                 rc = lfsck_ibits_lock(env, lfsck, child, &lh,
2116                                       MDS_INODELOCK_UPDATE |
2117                                       MDS_INODELOCK_XATTR, LCK_EX);
2118                 if (rc != 0)
2119                         GOTO(out, rc);
2120         }
2121
2122         dt_read_lock(env, child, 0);
2123         if (unlikely(lfsck_is_dead_obj(child))) {
2124                 dt_read_unlock(env, child);
2125
2126                 GOTO(out, rc = 0);
2127         }
2128
2129         rc = dt_lookup(env, child, (struct dt_rec *)pfid,
2130                        (const struct dt_key *)dotdot, BYPASS_CAPA);
2131         if (rc != 0) {
2132                 if (rc != -ENOENT && rc != -ENODATA && rc != -EINVAL) {
2133                         dt_read_unlock(env, child);
2134
2135                         GOTO(out, rc);
2136                 }
2137
2138                 if (!lustre_handle_is_used(&lh)) {
2139                         dt_read_unlock(env, child);
2140                         goto lock;
2141                 }
2142
2143                 fid_zero(pfid);
2144         } else if (lfsck->li_lpf_obj != NULL &&
2145                    lu_fid_eq(pfid, lfsck_dto2fid(lfsck->li_lpf_obj))) {
2146                 lpf = true;
2147         }
2148
2149         rc = lfsck_links_read(env, child, &ldata);
2150         dt_read_unlock(env, child);
2151         if (rc != 0) {
2152                 if (rc != -ENODATA && rc != -EINVAL)
2153                         GOTO(out, rc);
2154
2155                 if (!lustre_handle_is_used(&lh))
2156                         goto lock;
2157
2158                 if (rc == -EINVAL && !fid_is_zero(pfid)) {
2159                         /* Remove the corrupted linkEA. */
2160                         rc = lfsck_namespace_links_remove(env, com, child);
2161                         if (rc == 0)
2162                                 /* Here, because of the crashed linkEA, we
2163                                  * cannot know whether there is some parent
2164                                  * that references the child directory via
2165                                  * some name entry or not. So keep it there,
2166                                  * when the LFSCK run next time, if there is
2167                                  * some parent that references this object,
2168                                  * then the LFSCK can rebuild the linkEA;
2169                                  * otherwise, this object will be handled
2170                                  * as orphan as above. */
2171                                 unknown = true;
2172                 } else {
2173                         /* 1. If we have neither ".." nor linkEA,
2174                          *    then it is an orphan.
2175                          *
2176                          * 2. If we only have the ".." name entry,
2177                          *    but no parent references this child
2178                          *    directory, then handle it as orphan. */
2179                         lfsck_ibits_unlock(&lh, LCK_EX);
2180                         type = LNIT_MUL_REF;
2181                         snprintf(info->lti_tmpbuf, sizeof(info->lti_tmpbuf),
2182                                  "-"DFID, PFID(pfid));
2183                         rc = lfsck_namespace_insert_orphan(env, com, child,
2184                                                 info->lti_tmpbuf, "D", NULL);
2185                 }
2186
2187                 GOTO(out, rc);
2188         }
2189
2190         linkea_first_entry(&ldata);
2191         /* This is the most common case: the object has unique linkEA entry. */
2192         if (ldata.ld_leh->leh_reccount == 1) {
2193                 rc = lfsck_namespace_dsd_single(env, com, child, pfid, &ldata,
2194                                                 &lh, &type, &retry);
2195                 if (retry) {
2196                         LASSERT(!lustre_handle_is_used(&lh));
2197
2198                         retry = false;
2199                         goto lock;
2200                 }
2201
2202                 GOTO(out, rc);
2203         }
2204
2205         if (!lustre_handle_is_used(&lh))
2206                 goto lock;
2207
2208         if (unlikely(ldata.ld_leh->leh_reccount == 0)) {
2209                 rc = lfsck_namespace_dsd_orphan(env, com, child, pfid, &lh,
2210                                                 &type);
2211
2212                 GOTO(out, rc);
2213         }
2214
2215         /* When we come here, the cases usually like that:
2216          * 1) The directory object has a corrupted linkEA entry. During the
2217          *    first-stage scanning, the LFSCK cannot know such corruption,
2218          *    then it appends the right linkEA entry according to the found
2219          *    name entry after the bad one.
2220          *
2221          * 2) The directory object has a right linkEA entry. During the
2222          *    first-stage scanning, the LFSCK finds some bad name entry,
2223          *    but the LFSCK cannot aware that at that time, then it adds
2224          *    the bad linkEA entry for further processing. */
2225         rc = lfsck_namespace_dsd_multiple(env, com, child, pfid, &ldata,
2226                                           &lh, &type, lpf);
2227
2228         GOTO(out, rc);
2229
2230 out:
2231         lfsck_ibits_unlock(&lh, LCK_EX);
2232         if (rc > 0) {
2233                 switch (type) {
2234                 case LNIT_BAD_LINKEA:
2235                         ns->ln_linkea_repaired++;
2236                         break;
2237                 case LNIT_UNMATCHED_PAIRS:
2238                         ns->ln_unmatched_pairs_repaired++;
2239                         break;
2240                 case LNIT_MUL_REF:
2241                         ns->ln_mul_ref_repaired++;
2242                         break;
2243                 default:
2244                         break;
2245                 }
2246         }
2247
2248         if (unknown)
2249                 ns->ln_unknown_inconsistency++;
2250
2251         return rc;
2252 }
2253
2254 /**
2255  * Double scan the MDT-object for namespace LFSCK.
2256  *
2257  * If the MDT-object contains invalid or repeated linkEA entries, then drop
2258  * those entries from the linkEA; if the linkEA becomes empty or the object
2259  * has no linkEA, then it is an orphan and will be added into the directory
2260  * .lustre/lost+found/MDTxxxx/; if the remote parent is lost, then recreate
2261  * the remote parent; if the name entry corresponding to some linkEA entry
2262  * is lost, then add the name entry back to the namespace.
2263  *
2264  * \param[in] env       pointer to the thread context
2265  * \param[in] com       pointer to the lfsck component
2266  * \param[in] child     pointer to the dt_object to be handled
2267  * \param[in] flags     some hints to indicate how the @child should be handled
2268  *
2269  * \retval              positive number for repaired cases
2270  * \retval              0 if nothing to be repaired
2271  * \retval              negative error number on failure
2272  */
2273 static int lfsck_namespace_double_scan_one(const struct lu_env *env,
2274                                            struct lfsck_component *com,
2275                                            struct dt_object *child, __u8 flags)
2276 {
2277         struct lfsck_thread_info *info     = lfsck_env_info(env);
2278         struct lu_attr           *la       = &info->lti_la;
2279         struct lu_name           *cname    = &info->lti_name;
2280         struct lu_fid            *pfid     = &info->lti_fid;
2281         struct lu_fid            *cfid     = &info->lti_fid2;
2282         struct lfsck_instance    *lfsck    = com->lc_lfsck;
2283         struct lfsck_namespace   *ns       = com->lc_file_ram;
2284         struct dt_object         *parent   = NULL;
2285         struct linkea_data        ldata    = { 0 };
2286         bool                      repaired = false;
2287         int                       count    = 0;
2288         int                       rc;
2289         ENTRY;
2290
2291         dt_read_lock(env, child, 0);
2292         if (unlikely(lfsck_is_dead_obj(child))) {
2293                 dt_read_unlock(env, child);
2294
2295                 RETURN(0);
2296         }
2297
2298         if (S_ISDIR(lfsck_object_type(child))) {
2299                 dt_read_unlock(env, child);
2300                 rc = lfsck_namespace_double_scan_dir(env, com, child, flags);
2301
2302                 RETURN(rc);
2303         }
2304
2305         rc = lfsck_links_read(env, child, &ldata);
2306         dt_read_unlock(env, child);
2307         if (rc != 0)
2308                 GOTO(out, rc);
2309
2310         linkea_first_entry(&ldata);
2311         while (ldata.ld_lee != NULL) {
2312                 lfsck_namespace_unpack_linkea_entry(&ldata, cname, pfid,
2313                                                     info->lti_key);
2314                 rc = lfsck_namespace_filter_linkea_entry(&ldata, cname, pfid,
2315                                                          false);
2316                 /* Found repeated linkEA entries */
2317                 if (rc > 0) {
2318                         rc = lfsck_namespace_shrink_linkea(env, com, child,
2319                                                 &ldata, cname, pfid, false);
2320                         if (rc < 0)
2321                                 GOTO(out, rc);
2322
2323                         if (rc == 0)
2324                                 continue;
2325
2326                         repaired = true;
2327
2328                         /* fall through */
2329                 }
2330
2331                 /* Invalid PFID in the linkEA entry. */
2332                 if (!fid_is_sane(pfid)) {
2333                         rc = lfsck_namespace_shrink_linkea(env, com, child,
2334                                                 &ldata, cname, pfid, true);
2335                         if (rc < 0)
2336                                 GOTO(out, rc);
2337
2338                         if (rc > 0)
2339                                 repaired = true;
2340
2341                         continue;
2342                 }
2343
2344                 parent = lfsck_object_find_bottom(env, lfsck, pfid);
2345                 if (IS_ERR(parent))
2346                         GOTO(out, rc = PTR_ERR(parent));
2347
2348                 if (!dt_object_exists(parent)) {
2349                         if (ldata.ld_leh->leh_reccount > 1) {
2350                                 /* If it is NOT the last linkEA entry, then
2351                                  * there is still other chance to make the
2352                                  * child to be visible via other parent, then
2353                                  * remove this linkEA entry. */
2354                                 rc = lfsck_namespace_shrink_linkea(env, com,
2355                                         child, &ldata, cname, pfid, true);
2356                         } else {
2357                                 /* Create the lost parent as an orphan. */
2358                                 rc = lfsck_namespace_create_orphan(env, com,
2359                                                                    parent);
2360                                 if (rc < 0) {
2361                                         lfsck_object_put(env, parent);
2362
2363                                         GOTO(out, rc);
2364                                 }
2365
2366                                 if (rc > 0)
2367                                         repaired = true;
2368
2369                                 /* Add the missing name entry to the parent. */
2370                                 rc = lfsck_namespace_insert_normal(env, com,
2371                                                 parent, child, cname->ln_name);
2372                                 linkea_next_entry(&ldata);
2373                         }
2374
2375                         lfsck_object_put(env, parent);
2376                         if (rc < 0)
2377                                 GOTO(out, rc);
2378
2379                         if (rc > 0)
2380                                 repaired = true;
2381
2382                         continue;
2383                 }
2384
2385                 /* The linkEA entry with bad parent will be removed. */
2386                 if (unlikely(!dt_try_as_dir(env, parent))) {
2387                         lfsck_object_put(env, parent);
2388                         rc = lfsck_namespace_shrink_linkea(env, com, child,
2389                                                 &ldata, cname, pfid, true);
2390                         if (rc < 0)
2391                                 GOTO(out, rc);
2392
2393                         if (rc > 0)
2394                                 repaired = true;
2395
2396                         continue;
2397                 }
2398
2399                 rc = dt_lookup(env, parent, (struct dt_rec *)cfid,
2400                                (const struct dt_key *)cname->ln_name,
2401                                BYPASS_CAPA);
2402                 if (rc != 0 && rc != -ENOENT) {
2403                         lfsck_object_put(env, parent);
2404
2405                         GOTO(out, rc);
2406                 }
2407
2408                 if (rc == 0) {
2409                         if (lu_fid_eq(cfid, lfsck_dto2fid(child))) {
2410                                 /* It is the most common case that we
2411                                  * find the name entry corresponding
2412                                  * to the linkEA entry. */
2413                                 lfsck_object_put(env, parent);
2414                                 linkea_next_entry(&ldata);
2415                         } else {
2416                                 /* The name entry references another
2417                                  * MDT-object that may be created by
2418                                  * the LFSCK for repairing dangling
2419                                  * name entry. Try to replace it. */
2420                                 rc = lfsck_namespace_replace_cond(env, com,
2421                                                 parent, child, cfid, cname);
2422                                 lfsck_object_put(env, parent);
2423                                 if (rc < 0)
2424                                         GOTO(out, rc);
2425
2426                                 if (rc > 0) {
2427                                         repaired = true;
2428                                         linkea_next_entry(&ldata);
2429                                 } else {
2430                                         rc = lfsck_namespace_shrink_linkea(env,
2431                                                         com, child, &ldata,
2432                                                         cname, pfid, true);
2433                                         if (rc < 0)
2434                                                 GOTO(out, rc);
2435
2436                                         if (rc > 0)
2437                                                 repaired = true;
2438                                 }
2439                         }
2440
2441                         continue;
2442                 }
2443
2444                 rc = dt_attr_get(env, child, la, BYPASS_CAPA);
2445                 if (rc != 0)
2446                         GOTO(out, rc);
2447
2448                 /* If there is no name entry in the parent dir and the object
2449                  * link count is less than the linkea entries count, then the
2450                  * linkea entry should be removed. */
2451                 if (ldata.ld_leh->leh_reccount > la->la_nlink) {
2452                         rc = lfsck_namespace_shrink_linkea_cond(env, com,
2453                                         parent, child, &ldata, cname, pfid);
2454                         lfsck_object_put(env, parent);
2455                         if (rc < 0)
2456                                 GOTO(out, rc);
2457
2458                         if (rc > 0)
2459                                 repaired = true;
2460
2461                         continue;
2462                 }
2463
2464                 /* Add the missing name entry back to the namespace. */
2465                 rc = lfsck_namespace_insert_normal(env, com, parent, child,
2466                                                    cname->ln_name);
2467                 lfsck_object_put(env, parent);
2468                 if (rc < 0)
2469                         GOTO(out, rc);
2470
2471                 if (rc > 0)
2472                         repaired = true;
2473
2474                 linkea_next_entry(&ldata);
2475         }
2476
2477         GOTO(out, rc = 0);
2478
2479 out:
2480         if (rc < 0 && rc != -ENODATA)
2481                 return rc;
2482
2483         if (rc == 0) {
2484                 LASSERT(ldata.ld_leh != NULL);
2485
2486                 count = ldata.ld_leh->leh_reccount;
2487         }
2488
2489         if (count == 0) {
2490                 /* If the child becomes orphan, then insert it into
2491                  * the global .lustre/lost+found/MDTxxxx directory. */
2492                 rc = lfsck_namespace_insert_orphan(env, com, child, "", "O",
2493                                                    &count);
2494                 if (rc < 0)
2495                         return rc;
2496
2497                 if (rc > 0) {
2498                         ns->ln_mul_ref_repaired++;
2499                         repaired = true;
2500                 }
2501         }
2502
2503         rc = dt_attr_get(env, child, la, BYPASS_CAPA);
2504         if (rc != 0)
2505                 return rc;
2506
2507         if (la->la_nlink != count) {
2508                 /* XXX: there will be other patch(es) for MDT-object
2509                  *      hard links verification. */
2510         }
2511
2512         if (repaired) {
2513                 if (la->la_nlink > 1)
2514                         ns->ln_mul_linked_repaired++;
2515
2516                 if (rc == 0)
2517                         rc = 1;
2518         }
2519
2520         return rc;
2521 }
2522
2523 static void lfsck_namespace_dump_statistics(struct seq_file *m,
2524                                             struct lfsck_namespace *ns,
2525                                             __u64 checked_phase1,
2526                                             __u64 checked_phase2,
2527                                             __u32 time_phase1,
2528                                             __u32 time_phase2)
2529 {
2530         seq_printf(m, "checked_phase1: "LPU64"\n"
2531                       "checked_phase2: "LPU64"\n"
2532                       "updated_phase1: "LPU64"\n"
2533                       "updated_phase2: "LPU64"\n"
2534                       "failed_phase1: "LPU64"\n"
2535                       "failed_phase2: "LPU64"\n"
2536                       "directories: "LPU64"\n"
2537                       "dirent_repaired: "LPU64"\n"
2538                       "linkea_repaired: "LPU64"\n"
2539                       "nlinks_repaired: "LPU64"\n"
2540                       "lost_found: "LPU64"\n"
2541                       "multiple_linked_checked: "LPU64"\n"
2542                       "multiple_linked_repaired: "LPU64"\n"
2543                       "unknown_inconsistency: "LPU64"\n"
2544                       "unmatched_pairs_repaired: "LPU64"\n"
2545                       "dangling_repaired: "LPU64"\n"
2546                       "multiple_referenced_repaired: "LPU64"\n"
2547                       "bad_file_type_repaired: "LPU64"\n"
2548                       "success_count: %u\n"
2549                       "run_time_phase1: %u seconds\n"
2550                       "run_time_phase2: %u seconds\n",
2551                       checked_phase1,
2552                       checked_phase2,
2553                       ns->ln_items_repaired,
2554                       ns->ln_objs_repaired_phase2,
2555                       ns->ln_items_failed,
2556                       ns->ln_objs_failed_phase2,
2557                       ns->ln_dirs_checked,
2558                       ns->ln_dirent_repaired,
2559                       ns->ln_linkea_repaired,
2560                       ns->ln_objs_nlink_repaired,
2561                       ns->ln_objs_lost_found,
2562                       ns->ln_mul_linked_checked,
2563                       ns->ln_mul_linked_repaired,
2564                       ns->ln_unknown_inconsistency,
2565                       ns->ln_unmatched_pairs_repaired,
2566                       ns->ln_dangling_repaired,
2567                       ns->ln_mul_ref_repaired,
2568                       ns->ln_bad_type_repaired,
2569                       ns->ln_success_count,
2570                       time_phase1,
2571                       time_phase2);
2572 }
2573
2574 /* namespace APIs */
2575
2576 static int lfsck_namespace_reset(const struct lu_env *env,
2577                                  struct lfsck_component *com, bool init)
2578 {
2579         struct lfsck_instance   *lfsck = com->lc_lfsck;
2580         struct lfsck_namespace  *ns    = com->lc_file_ram;
2581         struct dt_object        *root;
2582         struct dt_object        *dto;
2583         int                      rc;
2584         ENTRY;
2585
2586         root = dt_locate(env, lfsck->li_bottom, &lfsck->li_local_root_fid);
2587         if (IS_ERR(root))
2588                 GOTO(log, rc = PTR_ERR(root));
2589
2590         if (unlikely(!dt_try_as_dir(env, root)))
2591                 GOTO(put, rc = -ENOTDIR);
2592
2593         down_write(&com->lc_sem);
2594         if (init) {
2595                 memset(ns, 0, sizeof(*ns));
2596         } else {
2597                 __u32 count = ns->ln_success_count;
2598                 __u64 last_time = ns->ln_time_last_complete;
2599
2600                 memset(ns, 0, sizeof(*ns));
2601                 ns->ln_success_count = count;
2602                 ns->ln_time_last_complete = last_time;
2603         }
2604         ns->ln_magic = LFSCK_NAMESPACE_MAGIC;
2605         ns->ln_status = LS_INIT;
2606
2607         rc = local_object_unlink(env, lfsck->li_bottom, root,
2608                                  lfsck_namespace_name);
2609         if (rc != 0)
2610                 GOTO(out, rc);
2611
2612         lfsck_object_put(env, com->lc_obj);
2613         com->lc_obj = NULL;
2614         dto = local_index_find_or_create(env, lfsck->li_los, root,
2615                                          lfsck_namespace_name,
2616                                          S_IFREG | S_IRUGO | S_IWUSR,
2617                                          &dt_lfsck_features);
2618         if (IS_ERR(dto))
2619                 GOTO(out, rc = PTR_ERR(dto));
2620
2621         com->lc_obj = dto;
2622         rc = dto->do_ops->do_index_try(env, dto, &dt_lfsck_features);
2623         if (rc != 0)
2624                 GOTO(out, rc);
2625
2626         rc = lfsck_namespace_store(env, com, true);
2627
2628         GOTO(out, rc);
2629
2630 out:
2631         up_write(&com->lc_sem);
2632
2633 put:
2634         lu_object_put(env, &root->do_lu);
2635 log:
2636         CDEBUG(D_LFSCK, "%s: namespace LFSCK reset: rc = %d\n",
2637                lfsck_lfsck2name(lfsck), rc);
2638         return rc;
2639 }
2640
2641 static void
2642 lfsck_namespace_fail(const struct lu_env *env, struct lfsck_component *com,
2643                      bool new_checked)
2644 {
2645         struct lfsck_namespace *ns = com->lc_file_ram;
2646
2647         down_write(&com->lc_sem);
2648         if (new_checked)
2649                 com->lc_new_checked++;
2650         lfsck_namespace_record_failure(env, com->lc_lfsck, ns);
2651         up_write(&com->lc_sem);
2652 }
2653
2654 static int lfsck_namespace_checkpoint(const struct lu_env *env,
2655                                       struct lfsck_component *com, bool init)
2656 {
2657         struct lfsck_instance   *lfsck = com->lc_lfsck;
2658         struct lfsck_namespace  *ns    = com->lc_file_ram;
2659         int                      rc;
2660
2661         if (!init) {
2662                 rc = lfsck_checkpoint_generic(env, com);
2663                 if (rc != 0)
2664                         goto log;
2665         }
2666
2667         down_write(&com->lc_sem);
2668         if (init) {
2669                 ns->ln_pos_latest_start = lfsck->li_pos_checkpoint;
2670         } else {
2671                 ns->ln_pos_last_checkpoint = lfsck->li_pos_checkpoint;
2672                 ns->ln_run_time_phase1 += cfs_duration_sec(cfs_time_current() +
2673                                 HALF_SEC - lfsck->li_time_last_checkpoint);
2674                 ns->ln_time_last_checkpoint = cfs_time_current_sec();
2675                 ns->ln_items_checked += com->lc_new_checked;
2676                 com->lc_new_checked = 0;
2677         }
2678
2679         rc = lfsck_namespace_store(env, com, false);
2680         up_write(&com->lc_sem);
2681
2682 log:
2683         CDEBUG(D_LFSCK, "%s: namespace LFSCK checkpoint at the pos ["LPU64
2684                ", "DFID", "LPX64"]: rc = %d\n", lfsck_lfsck2name(lfsck),
2685                lfsck->li_pos_current.lp_oit_cookie,
2686                PFID(&lfsck->li_pos_current.lp_dir_parent),
2687                lfsck->li_pos_current.lp_dir_cookie, rc);
2688
2689         return rc > 0 ? 0 : rc;
2690 }
2691
2692 static int lfsck_namespace_prep(const struct lu_env *env,
2693                                 struct lfsck_component *com,
2694                                 struct lfsck_start_param *lsp)
2695 {
2696         struct lfsck_instance   *lfsck  = com->lc_lfsck;
2697         struct lfsck_namespace  *ns     = com->lc_file_ram;
2698         struct lfsck_position   *pos    = &com->lc_pos_start;
2699         int                      rc;
2700
2701         if (ns->ln_status == LS_COMPLETED) {
2702                 rc = lfsck_namespace_reset(env, com, false);
2703                 if (rc == 0)
2704                         rc = lfsck_set_param(env, lfsck, lsp->lsp_start, true);
2705
2706                 if (rc != 0) {
2707                         CDEBUG(D_LFSCK, "%s: namespace LFSCK prep failed: "
2708                                "rc = %d\n", lfsck_lfsck2name(lfsck), rc);
2709
2710                         return rc;
2711                 }
2712         }
2713
2714         down_write(&com->lc_sem);
2715         ns->ln_time_latest_start = cfs_time_current_sec();
2716         spin_lock(&lfsck->li_lock);
2717
2718         if (ns->ln_flags & LF_SCANNED_ONCE) {
2719                 if (!lfsck->li_drop_dryrun ||
2720                     lfsck_pos_is_zero(&ns->ln_pos_first_inconsistent)) {
2721                         ns->ln_status = LS_SCANNING_PHASE2;
2722                         list_move_tail(&com->lc_link,
2723                                        &lfsck->li_list_double_scan);
2724                         if (!list_empty(&com->lc_link_dir))
2725                                 list_del_init(&com->lc_link_dir);
2726                         lfsck_pos_set_zero(pos);
2727                 } else {
2728                         ns->ln_status = LS_SCANNING_PHASE1;
2729                         ns->ln_run_time_phase1 = 0;
2730                         ns->ln_run_time_phase2 = 0;
2731                         ns->ln_items_checked = 0;
2732                         ns->ln_items_repaired = 0;
2733                         ns->ln_items_failed = 0;
2734                         ns->ln_dirs_checked = 0;
2735                         ns->ln_objs_checked_phase2 = 0;
2736                         ns->ln_objs_repaired_phase2 = 0;
2737                         ns->ln_objs_failed_phase2 = 0;
2738                         ns->ln_objs_nlink_repaired = 0;
2739                         ns->ln_objs_lost_found = 0;
2740                         ns->ln_dirent_repaired = 0;
2741                         ns->ln_linkea_repaired = 0;
2742                         ns->ln_mul_linked_checked = 0;
2743                         ns->ln_mul_linked_repaired = 0;
2744                         ns->ln_unknown_inconsistency = 0;
2745                         ns->ln_unmatched_pairs_repaired = 0;
2746                         ns->ln_dangling_repaired = 0;
2747                         ns->ln_mul_ref_repaired = 0;
2748                         ns->ln_bad_type_repaired = 0;
2749                         fid_zero(&ns->ln_fid_latest_scanned_phase2);
2750                         if (list_empty(&com->lc_link_dir))
2751                                 list_add_tail(&com->lc_link_dir,
2752                                               &lfsck->li_list_dir);
2753                         *pos = ns->ln_pos_first_inconsistent;
2754                 }
2755         } else {
2756                 ns->ln_status = LS_SCANNING_PHASE1;
2757                 if (list_empty(&com->lc_link_dir))
2758                         list_add_tail(&com->lc_link_dir,
2759                                       &lfsck->li_list_dir);
2760                 if (!lfsck->li_drop_dryrun ||
2761                     lfsck_pos_is_zero(&ns->ln_pos_first_inconsistent)) {
2762                         *pos = ns->ln_pos_last_checkpoint;
2763                         pos->lp_oit_cookie++;
2764                 } else {
2765                         *pos = ns->ln_pos_first_inconsistent;
2766                 }
2767         }
2768
2769         spin_unlock(&lfsck->li_lock);
2770         up_write(&com->lc_sem);
2771
2772         rc = lfsck_start_assistant(env, com, lsp);
2773
2774         CDEBUG(D_LFSCK, "%s: namespace LFSCK prep done, start pos ["LPU64", "
2775                DFID", "LPX64"]: rc = %d\n",
2776                lfsck_lfsck2name(lfsck), pos->lp_oit_cookie,
2777                PFID(&pos->lp_dir_parent), pos->lp_dir_cookie, rc);
2778
2779         return rc;
2780 }
2781
2782 static int lfsck_namespace_exec_oit(const struct lu_env *env,
2783                                     struct lfsck_component *com,
2784                                     struct dt_object *obj)
2785 {
2786         struct lfsck_thread_info *info  = lfsck_env_info(env);
2787         struct lfsck_namespace   *ns    = com->lc_file_ram;
2788         struct lfsck_instance    *lfsck = com->lc_lfsck;
2789         const struct lu_fid      *fid   = lfsck_dto2fid(obj);
2790         struct lu_attr           *la    = &info->lti_la;
2791         struct lu_fid            *pfid  = &info->lti_fid2;
2792         struct lu_name           *cname = &info->lti_name;
2793         struct lu_seq_range      *range = &info->lti_range;
2794         struct dt_device         *dev   = lfsck->li_bottom;
2795         struct seq_server_site   *ss    =
2796                                 lu_site2seq(dev->dd_lu_dev.ld_site);
2797         struct linkea_data        ldata = { 0 };
2798         __u32                     idx   = lfsck_dev_idx(dev);
2799         int                       rc;
2800         ENTRY;
2801
2802         rc = lfsck_links_read(env, obj, &ldata);
2803         if (rc == -ENOENT)
2804                 GOTO(out, rc = 0);
2805
2806         /* -EINVAL means crashed linkEA, should be verified. */
2807         if (rc == -EINVAL) {
2808                 rc = lfsck_namespace_trace_update(env, com, fid,
2809                                                   LNTF_CHECK_LINKEA, true);
2810                 if (rc == 0) {
2811                         struct lustre_handle lh = { 0 };
2812
2813                         rc = lfsck_ibits_lock(env, lfsck, obj, &lh,
2814                                               MDS_INODELOCK_UPDATE |
2815                                               MDS_INODELOCK_XATTR, LCK_EX);
2816                         if (rc == 0) {
2817                                 rc = lfsck_namespace_links_remove(env, com,
2818                                                                   obj);
2819                                 lfsck_ibits_unlock(&lh, LCK_EX);
2820                         }
2821                 }
2822
2823                 GOTO(out, rc = (rc == -ENOENT ? 0 : rc));
2824         }
2825
2826         /* zero-linkEA object may be orphan, but it also maybe because
2827          * of upgrading. Currently, we cannot record it for double scan.
2828          * Because it may cause the LFSCK tracing file to be too large. */
2829         if (rc == -ENODATA) {
2830                 if (S_ISDIR(lfsck_object_type(obj)))
2831                         GOTO(out, rc = 0);
2832
2833                 rc = dt_attr_get(env, obj, la, BYPASS_CAPA);
2834                 if (rc != 0)
2835                         GOTO(out, rc);
2836
2837                 if (la->la_nlink > 1)
2838                         rc = lfsck_namespace_trace_update(env, com, fid,
2839                                                 LNTF_CHECK_LINKEA, true);
2840
2841                 GOTO(out, rc);
2842         }
2843
2844         if (rc != 0)
2845                 GOTO(out, rc);
2846
2847         /* Record multiple-linked object. */
2848         if (ldata.ld_leh->leh_reccount > 1) {
2849                 rc = lfsck_namespace_trace_update(env, com, fid,
2850                                                   LNTF_CHECK_LINKEA, true);
2851
2852                 GOTO(out, rc);
2853         }
2854
2855         linkea_first_entry(&ldata);
2856         linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen, cname, pfid);
2857         if (!fid_is_sane(pfid)) {
2858                 rc = lfsck_namespace_trace_update(env, com, fid,
2859                                                   LNTF_CHECK_PARENT, true);
2860         } else {
2861                 fld_range_set_mdt(range);
2862                 rc = fld_local_lookup(env, ss->ss_server_fld,
2863                                       fid_seq(pfid), range);
2864                 if ((rc == -ENOENT) ||
2865                     (rc == 0 && range->lsr_index != idx)) {
2866                         rc = lfsck_namespace_trace_update(env, com, fid,
2867                                                 LNTF_CHECK_LINKEA, true);
2868                 } else {
2869                         if (S_ISDIR(lfsck_object_type(obj)))
2870                                 GOTO(out, rc = 0);
2871
2872                         rc = dt_attr_get(env, obj, la, BYPASS_CAPA);
2873                         if (rc != 0)
2874                                 GOTO(out, rc);
2875
2876                         if (la->la_nlink > 1)
2877                                 rc = lfsck_namespace_trace_update(env, com,
2878                                                 fid, LNTF_CHECK_LINKEA, true);
2879                 }
2880         }
2881
2882         GOTO(out, rc);
2883
2884 out:
2885         down_write(&com->lc_sem);
2886         com->lc_new_checked++;
2887         if (S_ISDIR(lfsck_object_type(obj)))
2888                 ns->ln_dirs_checked++;
2889         if (rc != 0)
2890                 lfsck_namespace_record_failure(env, com->lc_lfsck, ns);
2891         up_write(&com->lc_sem);
2892
2893         return rc;
2894 }
2895
2896 static int lfsck_namespace_exec_dir(const struct lu_env *env,
2897                                     struct lfsck_component *com,
2898                                     struct lu_dirent *ent, __u16 type)
2899 {
2900         struct lfsck_assistant_data     *lad    = com->lc_data;
2901         struct lfsck_namespace_req      *lnr;
2902         bool                             wakeup = false;
2903
2904         lnr = lfsck_namespace_assistant_req_init(com->lc_lfsck, ent, type);
2905         if (IS_ERR(lnr)) {
2906                 struct lfsck_namespace *ns = com->lc_file_ram;
2907
2908                 lfsck_namespace_record_failure(env, com->lc_lfsck, ns);
2909                 return PTR_ERR(lnr);
2910         }
2911
2912         spin_lock(&lad->lad_lock);
2913         if (lad->lad_assistant_status < 0) {
2914                 spin_unlock(&lad->lad_lock);
2915                 lfsck_namespace_assistant_req_fini(env, &lnr->lnr_lar);
2916                 return lad->lad_assistant_status;
2917         }
2918
2919         list_add_tail(&lnr->lnr_lar.lar_list, &lad->lad_req_list);
2920         if (lad->lad_prefetched == 0)
2921                 wakeup = true;
2922
2923         lad->lad_prefetched++;
2924         spin_unlock(&lad->lad_lock);
2925         if (wakeup)
2926                 wake_up_all(&lad->lad_thread.t_ctl_waitq);
2927
2928         down_write(&com->lc_sem);
2929         com->lc_new_checked++;
2930         up_write(&com->lc_sem);
2931
2932         return 0;
2933 }
2934
2935 static int lfsck_namespace_post(const struct lu_env *env,
2936                                 struct lfsck_component *com,
2937                                 int result, bool init)
2938 {
2939         struct lfsck_instance   *lfsck = com->lc_lfsck;
2940         struct lfsck_namespace  *ns    = com->lc_file_ram;
2941         int                      rc;
2942         ENTRY;
2943
2944         lfsck_post_generic(env, com, &result);
2945
2946         down_write(&com->lc_sem);
2947         spin_lock(&lfsck->li_lock);
2948         if (!init)
2949                 ns->ln_pos_last_checkpoint = lfsck->li_pos_checkpoint;
2950         if (result > 0) {
2951                 ns->ln_status = LS_SCANNING_PHASE2;
2952                 ns->ln_flags |= LF_SCANNED_ONCE;
2953                 ns->ln_flags &= ~LF_UPGRADE;
2954                 list_del_init(&com->lc_link_dir);
2955                 list_move_tail(&com->lc_link, &lfsck->li_list_double_scan);
2956         } else if (result == 0) {
2957                 ns->ln_status = lfsck->li_status;
2958                 if (ns->ln_status == 0)
2959                         ns->ln_status = LS_STOPPED;
2960                 if (ns->ln_status != LS_PAUSED) {
2961                         list_del_init(&com->lc_link_dir);
2962                         list_move_tail(&com->lc_link, &lfsck->li_list_idle);
2963                 }
2964         } else {
2965                 ns->ln_status = LS_FAILED;
2966                 list_del_init(&com->lc_link_dir);
2967                 list_move_tail(&com->lc_link, &lfsck->li_list_idle);
2968         }
2969         spin_unlock(&lfsck->li_lock);
2970
2971         if (!init) {
2972                 ns->ln_run_time_phase1 += cfs_duration_sec(cfs_time_current() +
2973                                 HALF_SEC - lfsck->li_time_last_checkpoint);
2974                 ns->ln_time_last_checkpoint = cfs_time_current_sec();
2975                 ns->ln_items_checked += com->lc_new_checked;
2976                 com->lc_new_checked = 0;
2977         }
2978
2979         rc = lfsck_namespace_store(env, com, false);
2980         up_write(&com->lc_sem);
2981
2982         CDEBUG(D_LFSCK, "%s: namespace LFSCK post done: rc = %d\n",
2983                lfsck_lfsck2name(lfsck), rc);
2984
2985         RETURN(rc);
2986 }
2987
2988 static int
2989 lfsck_namespace_dump(const struct lu_env *env, struct lfsck_component *com,
2990                      struct seq_file *m)
2991 {
2992         struct lfsck_instance   *lfsck = com->lc_lfsck;
2993         struct lfsck_bookmark   *bk    = &lfsck->li_bookmark_ram;
2994         struct lfsck_namespace  *ns    = com->lc_file_ram;
2995         int                      rc;
2996
2997         down_read(&com->lc_sem);
2998         seq_printf(m, "name: lfsck_namespace\n"
2999                    "magic: %#x\n"
3000                    "version: %d\n"
3001                    "status: %s\n",
3002                    ns->ln_magic,
3003                    bk->lb_version,
3004                    lfsck_status2names(ns->ln_status));
3005
3006         rc = lfsck_bits_dump(m, ns->ln_flags, lfsck_flags_names, "flags");
3007         if (rc < 0)
3008                 goto out;
3009
3010         rc = lfsck_bits_dump(m, bk->lb_param, lfsck_param_names, "param");
3011         if (rc < 0)
3012                 goto out;
3013
3014         rc = lfsck_time_dump(m, ns->ln_time_last_complete,
3015                              "time_since_last_completed");
3016         if (rc < 0)
3017                 goto out;
3018
3019         rc = lfsck_time_dump(m, ns->ln_time_latest_start,
3020                              "time_since_latest_start");
3021         if (rc < 0)
3022                 goto out;
3023
3024         rc = lfsck_time_dump(m, ns->ln_time_last_checkpoint,
3025                              "time_since_last_checkpoint");
3026         if (rc < 0)
3027                 goto out;
3028
3029         rc = lfsck_pos_dump(m, &ns->ln_pos_latest_start,
3030                             "latest_start_position");
3031         if (rc < 0)
3032                 goto out;
3033
3034         rc = lfsck_pos_dump(m, &ns->ln_pos_last_checkpoint,
3035                             "last_checkpoint_position");
3036         if (rc < 0)
3037                 goto out;
3038
3039         rc = lfsck_pos_dump(m, &ns->ln_pos_first_inconsistent,
3040                             "first_failure_position");
3041         if (rc < 0)
3042                 goto out;
3043
3044         if (ns->ln_status == LS_SCANNING_PHASE1) {
3045                 struct lfsck_position pos;
3046                 const struct dt_it_ops *iops;
3047                 cfs_duration_t duration = cfs_time_current() -
3048                                           lfsck->li_time_last_checkpoint;
3049                 __u64 checked = ns->ln_items_checked + com->lc_new_checked;
3050                 __u64 speed = checked;
3051                 __u64 new_checked = com->lc_new_checked * HZ;
3052                 __u32 rtime = ns->ln_run_time_phase1 +
3053                               cfs_duration_sec(duration + HALF_SEC);
3054
3055                 if (duration != 0)
3056                         do_div(new_checked, duration);
3057                 if (rtime != 0)
3058                         do_div(speed, rtime);
3059                 lfsck_namespace_dump_statistics(m, ns, checked,
3060                                                 ns->ln_objs_checked_phase2,
3061                                                 rtime, ns->ln_run_time_phase2);
3062
3063                 seq_printf(m, "average_speed_phase1: "LPU64" items/sec\n"
3064                               "average_speed_phase2: N/A\n"
3065                               "real_time_speed_phase1: "LPU64" items/sec\n"
3066                               "real_time_speed_phase2: N/A\n",
3067                               speed,
3068                               new_checked);
3069
3070                 LASSERT(lfsck->li_di_oit != NULL);
3071
3072                 iops = &lfsck->li_obj_oit->do_index_ops->dio_it;
3073
3074                 /* The low layer otable-based iteration position may NOT
3075                  * exactly match the namespace-based directory traversal
3076                  * cookie. Generally, it is not a serious issue. But the
3077                  * caller should NOT make assumption on that. */
3078                 pos.lp_oit_cookie = iops->store(env, lfsck->li_di_oit);
3079                 if (!lfsck->li_current_oit_processed)
3080                         pos.lp_oit_cookie--;
3081
3082                 spin_lock(&lfsck->li_lock);
3083                 if (lfsck->li_di_dir != NULL) {
3084                         pos.lp_dir_cookie = lfsck->li_cookie_dir;
3085                         if (pos.lp_dir_cookie >= MDS_DIR_END_OFF) {
3086                                 fid_zero(&pos.lp_dir_parent);
3087                                 pos.lp_dir_cookie = 0;
3088                         } else {
3089                                 pos.lp_dir_parent =
3090                                         *lfsck_dto2fid(lfsck->li_obj_dir);
3091                         }
3092                 } else {
3093                         fid_zero(&pos.lp_dir_parent);
3094                         pos.lp_dir_cookie = 0;
3095                 }
3096                 spin_unlock(&lfsck->li_lock);
3097                 lfsck_pos_dump(m, &pos, "current_position");
3098         } else if (ns->ln_status == LS_SCANNING_PHASE2) {
3099                 cfs_duration_t duration = cfs_time_current() -
3100                                           lfsck->li_time_last_checkpoint;
3101                 __u64 checked = ns->ln_objs_checked_phase2 +
3102                                 com->lc_new_checked;
3103                 __u64 speed1 = ns->ln_items_checked;
3104                 __u64 speed2 = checked;
3105                 __u64 new_checked = com->lc_new_checked * HZ;
3106                 __u32 rtime = ns->ln_run_time_phase2 +
3107                               cfs_duration_sec(duration + HALF_SEC);
3108
3109                 if (duration != 0)
3110                         do_div(new_checked, duration);
3111                 if (ns->ln_run_time_phase1 != 0)
3112                         do_div(speed1, ns->ln_run_time_phase1);
3113                 if (rtime != 0)
3114                         do_div(speed2, rtime);
3115                 lfsck_namespace_dump_statistics(m, ns, ns->ln_items_checked,
3116                                                 checked,
3117                                                 ns->ln_run_time_phase1, rtime);
3118
3119                 seq_printf(m, "average_speed_phase1: "LPU64" items/sec\n"
3120                               "average_speed_phase2: "LPU64" objs/sec\n"
3121                               "real_time_speed_phase1: N/A\n"
3122                               "real_time_speed_phase2: "LPU64" objs/sec\n"
3123                               "current_position: "DFID"\n",
3124                               speed1,
3125                               speed2,
3126                               new_checked,
3127                               PFID(&ns->ln_fid_latest_scanned_phase2));
3128         } else {
3129                 __u64 speed1 = ns->ln_items_checked;
3130                 __u64 speed2 = ns->ln_objs_checked_phase2;
3131
3132                 if (ns->ln_run_time_phase1 != 0)
3133                         do_div(speed1, ns->ln_run_time_phase1);
3134                 if (ns->ln_run_time_phase2 != 0)
3135                         do_div(speed2, ns->ln_run_time_phase2);
3136                 lfsck_namespace_dump_statistics(m, ns, ns->ln_items_checked,
3137                                                 ns->ln_objs_checked_phase2,
3138                                                 ns->ln_run_time_phase1,
3139                                                 ns->ln_run_time_phase2);
3140
3141                 seq_printf(m, "average_speed_phase1: "LPU64" items/sec\n"
3142                               "average_speed_phase2: "LPU64" objs/sec\n"
3143                               "real_time_speed_phase1: N/A\n"
3144                               "real_time_speed_phase2: N/A\n"
3145                               "current_position: N/A\n",
3146                               speed1,
3147                               speed2);
3148         }
3149 out:
3150         up_read(&com->lc_sem);
3151         return 0;
3152 }
3153
3154 static int lfsck_namespace_double_scan(const struct lu_env *env,
3155                                        struct lfsck_component *com)
3156 {
3157         struct lfsck_namespace *ns = com->lc_file_ram;
3158
3159         return lfsck_double_scan_generic(env, com, ns->ln_status);
3160 }
3161
3162 static void lfsck_namespace_data_release(const struct lu_env *env,
3163                                          struct lfsck_component *com)
3164 {
3165         struct lfsck_assistant_data     *lad    = com->lc_data;
3166         struct lfsck_tgt_descs          *ltds   = &com->lc_lfsck->li_mdt_descs;
3167         struct lfsck_tgt_desc           *ltd;
3168         struct lfsck_tgt_desc           *next;
3169
3170         LASSERT(lad != NULL);
3171         LASSERT(thread_is_init(&lad->lad_thread) ||
3172                 thread_is_stopped(&lad->lad_thread));
3173         LASSERT(list_empty(&lad->lad_req_list));
3174
3175         com->lc_data = NULL;
3176
3177         spin_lock(&ltds->ltd_lock);
3178         list_for_each_entry_safe(ltd, next, &lad->lad_mdt_phase1_list,
3179                                  ltd_namespace_phase_list) {
3180                 list_del_init(&ltd->ltd_namespace_phase_list);
3181         }
3182         list_for_each_entry_safe(ltd, next, &lad->lad_mdt_phase2_list,
3183                                  ltd_namespace_phase_list) {
3184                 list_del_init(&ltd->ltd_namespace_phase_list);
3185         }
3186         list_for_each_entry_safe(ltd, next, &lad->lad_mdt_list,
3187                                  ltd_namespace_list) {
3188                 list_del_init(&ltd->ltd_namespace_list);
3189         }
3190         spin_unlock(&ltds->ltd_lock);
3191
3192         CFS_FREE_BITMAP(lad->lad_bitmap);
3193
3194         OBD_FREE_PTR(lad);
3195 }
3196
3197 static int lfsck_namespace_in_notify(const struct lu_env *env,
3198                                      struct lfsck_component *com,
3199                                      struct lfsck_request *lr)
3200 {
3201         struct lfsck_instance           *lfsck = com->lc_lfsck;
3202         struct lfsck_namespace          *ns    = com->lc_file_ram;
3203         struct lfsck_assistant_data     *lad   = com->lc_data;
3204         struct lfsck_tgt_descs          *ltds  = &lfsck->li_mdt_descs;
3205         struct lfsck_tgt_desc           *ltd;
3206         bool                             fail  = false;
3207         ENTRY;
3208
3209         if (lr->lr_event != LE_PHASE1_DONE &&
3210             lr->lr_event != LE_PHASE2_DONE &&
3211             lr->lr_event != LE_PEER_EXIT)
3212                 RETURN(-EINVAL);
3213
3214         CDEBUG(D_LFSCK, "%s: namespace LFSCK handles notify %u from MDT %x, "
3215                "status %d\n", lfsck_lfsck2name(lfsck), lr->lr_event,
3216                lr->lr_index, lr->lr_status);
3217
3218         spin_lock(&ltds->ltd_lock);
3219         ltd = LTD_TGT(ltds, lr->lr_index);
3220         if (ltd == NULL) {
3221                 spin_unlock(&ltds->ltd_lock);
3222
3223                 RETURN(-ENXIO);
3224         }
3225
3226         list_del_init(&ltd->ltd_namespace_phase_list);
3227         switch (lr->lr_event) {
3228         case LE_PHASE1_DONE:
3229                 if (lr->lr_status <= 0) {
3230                         ltd->ltd_namespace_done = 1;
3231                         list_del_init(&ltd->ltd_namespace_list);
3232                         CDEBUG(D_LFSCK, "%s: MDT %x failed/stopped at "
3233                                "phase1 for namespace LFSCK: rc = %d.\n",
3234                                lfsck_lfsck2name(lfsck),
3235                                ltd->ltd_index, lr->lr_status);
3236                         ns->ln_flags |= LF_INCOMPLETE;
3237                         fail = true;
3238                         break;
3239                 }
3240
3241                 if (list_empty(&ltd->ltd_namespace_list))
3242                         list_add_tail(&ltd->ltd_namespace_list,
3243                                       &lad->lad_mdt_list);
3244                 list_add_tail(&ltd->ltd_namespace_phase_list,
3245                               &lad->lad_mdt_phase2_list);
3246                 break;
3247         case LE_PHASE2_DONE:
3248                 ltd->ltd_namespace_done = 1;
3249                 list_del_init(&ltd->ltd_namespace_list);
3250                 break;
3251         case LE_PEER_EXIT:
3252                 fail = true;
3253                 ltd->ltd_namespace_done = 1;
3254                 list_del_init(&ltd->ltd_namespace_list);
3255                 if (!(lfsck->li_bookmark_ram.lb_param & LPF_FAILOUT)) {
3256                         CDEBUG(D_LFSCK,
3257                                "%s: the peer MDT %x exit namespace LFSCK\n",
3258                                lfsck_lfsck2name(lfsck), ltd->ltd_index);
3259                         ns->ln_flags |= LF_INCOMPLETE;
3260                 }
3261                 break;
3262         default:
3263                 break;
3264         }
3265         spin_unlock(&ltds->ltd_lock);
3266
3267         if (fail && lfsck->li_bookmark_ram.lb_param & LPF_FAILOUT) {
3268                 struct lfsck_stop *stop = &lfsck_env_info(env)->lti_stop;
3269
3270                 memset(stop, 0, sizeof(*stop));
3271                 stop->ls_status = lr->lr_status;
3272                 stop->ls_flags = lr->lr_param & ~LPF_BROADCAST;
3273                 lfsck_stop(env, lfsck->li_bottom, stop);
3274         } else if (lfsck_phase2_next_ready(lad)) {
3275                 wake_up_all(&lad->lad_thread.t_ctl_waitq);
3276         }
3277
3278         RETURN(0);
3279 }
3280
3281 static int lfsck_namespace_query(const struct lu_env *env,
3282                                  struct lfsck_component *com)
3283 {
3284         struct lfsck_namespace *ns = com->lc_file_ram;
3285
3286         return ns->ln_status;
3287 }
3288
3289 static struct lfsck_operations lfsck_namespace_ops = {
3290         .lfsck_reset            = lfsck_namespace_reset,
3291         .lfsck_fail             = lfsck_namespace_fail,
3292         .lfsck_checkpoint       = lfsck_namespace_checkpoint,
3293         .lfsck_prep             = lfsck_namespace_prep,
3294         .lfsck_exec_oit         = lfsck_namespace_exec_oit,
3295         .lfsck_exec_dir         = lfsck_namespace_exec_dir,
3296         .lfsck_post             = lfsck_namespace_post,
3297         .lfsck_dump             = lfsck_namespace_dump,
3298         .lfsck_double_scan      = lfsck_namespace_double_scan,
3299         .lfsck_data_release     = lfsck_namespace_data_release,
3300         .lfsck_quit             = lfsck_quit_generic,
3301         .lfsck_in_notify        = lfsck_namespace_in_notify,
3302         .lfsck_query            = lfsck_namespace_query,
3303 };
3304
3305 /**
3306  * Repair dangling name entry.
3307  *
3308  * For the name entry with dangling reference, we need to repare the
3309  * inconsistency according to the LFSCK sponsor's requirement:
3310  *
3311  * 1) Keep the inconsistency there and report the inconsistency case,
3312  *    then give the chance to the application to find related issues,
3313  *    and the users can make the decision about how to handle it with
3314  *    more human knownledge. (by default)
3315  *
3316  * 2) Re-create the missed MDT-object with the FID information.
3317  *
3318  * \param[in] env       pointer to the thread context
3319  * \param[in] com       pointer to the lfsck component
3320  * \param[in] child     pointer to the object corresponding to the dangling
3321  *                      name entry
3322  * \param[in] lnr       pointer to the namespace request that contains the
3323  *                      name's name, parent object, parent's LMV, and ect.
3324  *
3325  * \retval              positive number if no need to repair
3326  * \retval              zero for repaired successfully
3327  * \retval              negative error number on failure
3328  */
3329 int lfsck_namespace_repair_dangling(const struct lu_env *env,
3330                                     struct lfsck_component *com,
3331                                     struct dt_object *child,
3332                                     struct lfsck_namespace_req *lnr)
3333 {
3334         struct lfsck_thread_info        *info   = lfsck_env_info(env);
3335         struct lu_attr                  *la     = &info->lti_la;
3336         struct dt_allocation_hint       *hint   = &info->lti_hint;
3337         struct dt_object_format         *dof    = &info->lti_dof;
3338         struct dt_insert_rec            *rec    = &info->lti_dt_rec;
3339         struct dt_object                *parent = lnr->lnr_obj;
3340         const struct lu_name            *cname;
3341         struct linkea_data               ldata  = { 0 };
3342         struct lustre_handle             lh     = { 0 };
3343         struct lu_buf                    linkea_buf;
3344         struct lfsck_instance           *lfsck  = com->lc_lfsck;
3345         struct lfsck_bookmark           *bk     = &lfsck->li_bookmark_ram;
3346         struct dt_device                *dev    = lfsck_obj2dt_dev(child);
3347         struct thandle                  *th     = NULL;
3348         int                              rc     = 0;
3349         __u16                            type   = lnr->lnr_type;
3350         bool                             create;
3351         ENTRY;
3352
3353         cname = lfsck_name_get_const(env, lnr->lnr_name, lnr->lnr_namelen);
3354         if (bk->lb_param & LPF_CREATE_MDTOBJ)
3355                 create = true;
3356         else
3357                 create = false;
3358
3359         if (!create || bk->lb_param & LPF_DRYRUN)
3360                 GOTO(log, rc = 0);
3361
3362         rc = linkea_data_new(&ldata, &info->lti_linkea_buf2);
3363         if (rc != 0)
3364                 GOTO(log, rc);
3365
3366         rc = linkea_add_buf(&ldata, cname, lfsck_dto2fid(parent));
3367         if (rc != 0)
3368                 GOTO(log, rc);
3369
3370         rc = lfsck_ibits_lock(env, lfsck, parent, &lh,
3371                               MDS_INODELOCK_UPDATE, LCK_EX);
3372         if (rc != 0)
3373                 GOTO(log, rc);
3374
3375         rc = lfsck_namespace_check_exist(env, parent, child, lnr->lnr_name);
3376         if (rc != 0)
3377                 GOTO(log, rc);
3378
3379         th = dt_trans_create(env, dev);
3380         if (IS_ERR(th))
3381                 GOTO(log, rc = PTR_ERR(th));
3382
3383         /* Set the ctime as zero, then others can know it is created for
3384          * repairing dangling name entry by LFSCK. And if the LFSCK made
3385          * wrong decision and the real MDT-object has been found later,
3386          * then the LFSCK has chance to fix the incosistency properly. */
3387         memset(la, 0, sizeof(*la));
3388         la->la_mode = (type & S_IFMT) | 0600;
3389         la->la_valid = LA_TYPE | LA_MODE | LA_UID | LA_GID |
3390                         LA_ATIME | LA_MTIME | LA_CTIME;
3391
3392         child->do_ops->do_ah_init(env, hint, parent, child,
3393                                   la->la_mode & S_IFMT);
3394
3395         memset(dof, 0, sizeof(*dof));
3396         dof->dof_type = dt_mode_to_dft(type);
3397         /* If the target is a regular file, then the LFSCK will only create
3398          * the MDT-object without stripes (dof->dof_reg.striped = 0). related
3399          * OST-objects will be created when write open. */
3400
3401         /* 1a. create child. */
3402         rc = dt_declare_create(env, child, la, hint, dof, th);
3403         if (rc != 0)
3404                 GOTO(stop, rc);
3405
3406         if (S_ISDIR(type)) {
3407                 if (unlikely(!dt_try_as_dir(env, child)))
3408                         GOTO(stop, rc = -ENOTDIR);
3409
3410                 /* 2a. insert dot into child dir */
3411                 rec->rec_type = S_IFDIR;
3412                 rec->rec_fid = lfsck_dto2fid(child);
3413                 rc = dt_declare_insert(env, child,
3414                                        (const struct dt_rec *)rec,
3415                                        (const struct dt_key *)dot, th);
3416                 if (rc != 0)
3417                         GOTO(stop, rc);
3418
3419                 /* 3a. insert dotdot into child dir */
3420                 rec->rec_fid = lfsck_dto2fid(parent);
3421                 rc = dt_declare_insert(env, child,
3422                                        (const struct dt_rec *)rec,
3423                                        (const struct dt_key *)dotdot, th);
3424                 if (rc != 0)
3425                         GOTO(stop, rc);
3426
3427                 /* 4a. increase child nlink */
3428                 rc = dt_declare_ref_add(env, child, th);
3429                 if (rc != 0)
3430                         GOTO(stop, rc);
3431         }
3432
3433         /* 5a. insert linkEA for child */
3434         lfsck_buf_init(&linkea_buf, ldata.ld_buf->lb_buf,
3435                        ldata.ld_leh->leh_len);
3436         rc = dt_declare_xattr_set(env, child, &linkea_buf,
3437                                   XATTR_NAME_LINK, 0, th);
3438         if (rc != 0)
3439                 GOTO(stop, rc);
3440
3441         rc = dt_trans_start(env, dev, th);
3442         if (rc != 0)
3443                 GOTO(stop, rc = (rc == -EEXIST ? 1 : rc));
3444
3445         dt_write_lock(env, child, 0);
3446         /* 1b. create child */
3447         rc = dt_create(env, child, la, hint, dof, th);
3448         if (rc != 0)
3449                 GOTO(unlock, rc = (rc == -EEXIST ? 1 : rc));
3450
3451         if (S_ISDIR(type)) {
3452                 if (unlikely(!dt_try_as_dir(env, child)))
3453                         GOTO(unlock, rc = -ENOTDIR);
3454
3455                 /* 2b. insert dot into child dir */
3456                 rec->rec_type = S_IFDIR;
3457                 rec->rec_fid = lfsck_dto2fid(child);
3458                 rc = dt_insert(env, child, (const struct dt_rec *)rec,
3459                                (const struct dt_key *)dot, th, BYPASS_CAPA, 1);
3460                 if (rc != 0)
3461                         GOTO(unlock, rc);
3462
3463                 /* 3b. insert dotdot into child dir */
3464                 rec->rec_fid = lfsck_dto2fid(parent);
3465                 rc = dt_insert(env, child, (const struct dt_rec *)rec,
3466                                (const struct dt_key *)dotdot, th,
3467                                BYPASS_CAPA, 1);
3468                 if (rc != 0)
3469                         GOTO(unlock, rc);
3470
3471                 /* 4b. increase child nlink */
3472                 rc = dt_ref_add(env, child, th);
3473                 if (rc != 0)
3474                         GOTO(unlock, rc);
3475         }
3476
3477         /* 5b. insert linkEA for child. */
3478         rc = dt_xattr_set(env, child, &linkea_buf,
3479                           XATTR_NAME_LINK, 0, th, BYPASS_CAPA);
3480
3481         GOTO(unlock, rc);
3482
3483 unlock:
3484         dt_write_unlock(env, child);
3485
3486 stop:
3487         dt_trans_stop(env, dev, th);
3488
3489 log:
3490         lfsck_ibits_unlock(&lh, LCK_EX);
3491         CDEBUG(D_LFSCK, "%s: namespace LFSCK assistant found dangling "
3492                "reference for: parent "DFID", child "DFID", type %u, "
3493                "name %s. %s: rc = %d\n", lfsck_lfsck2name(lfsck),
3494                PFID(lfsck_dto2fid(parent)), PFID(lfsck_dto2fid(child)),
3495                type, cname->ln_name,
3496                create ? "Create the lost OST-object as required" :
3497                         "Keep the MDT-object there by default", rc);
3498
3499         if (rc <= 0) {
3500                 struct lfsck_namespace *ns = com->lc_file_ram;
3501
3502                 ns->ln_flags |= LF_INCONSISTENT;
3503         }
3504
3505         return rc;
3506 }
3507
3508 static int lfsck_namespace_assistant_handler_p1(const struct lu_env *env,
3509                                                 struct lfsck_component *com,
3510                                                 struct lfsck_assistant_req *lar)
3511 {
3512         struct lfsck_thread_info   *info     = lfsck_env_info(env);
3513         struct lu_attr             *la       = &info->lti_la;
3514         struct lfsck_instance      *lfsck    = com->lc_lfsck;
3515         struct lfsck_bookmark      *bk       = &lfsck->li_bookmark_ram;
3516         struct lfsck_namespace     *ns       = com->lc_file_ram;
3517         struct linkea_data          ldata    = { 0 };
3518         const struct lu_name       *cname;
3519         struct thandle             *handle   = NULL;
3520         struct lfsck_namespace_req *lnr      =
3521                         container_of0(lar, struct lfsck_namespace_req, lnr_lar);
3522         struct dt_object           *dir      = lnr->lnr_obj;
3523         struct dt_object           *obj      = NULL;
3524         const struct lu_fid        *pfid     = lfsck_dto2fid(dir);
3525         struct dt_device           *dev;
3526         struct lustre_handle        lh       = { 0 };
3527         bool                        repaired = false;
3528         bool                        dtlocked = false;
3529         bool                        remove;
3530         bool                        newdata;
3531         bool                        log      = false;
3532         int                         idx;
3533         int                         count    = 0;
3534         int                         rc;
3535         enum lfsck_namespace_inconsistency_type type = LNIT_NONE;
3536         ENTRY;
3537
3538         if (lnr->lnr_attr & LUDA_UPGRADE) {
3539                 ns->ln_flags |= LF_UPGRADE;
3540                 ns->ln_dirent_repaired++;
3541                 repaired = true;
3542         } else if (lnr->lnr_attr & LUDA_REPAIR) {
3543                 ns->ln_flags |= LF_INCONSISTENT;
3544                 ns->ln_dirent_repaired++;
3545                 repaired = true;
3546         }
3547
3548         if (unlikely(fid_is_zero(&lnr->lnr_fid))) {
3549                 if (strcmp(lnr->lnr_name, dotdot) != 0)
3550                         LBUG();
3551                 else
3552                         rc = lfsck_namespace_trace_update(env, com, pfid,
3553                                                 LNTF_CHECK_PARENT, true);
3554
3555                 GOTO(out, rc);
3556         }
3557
3558         if (lnr->lnr_name[0] == '.' &&
3559             (lnr->lnr_namelen == 1 || fid_seq_is_dot(fid_seq(&lnr->lnr_fid))))
3560                 GOTO(out, rc = 0);
3561
3562         idx = lfsck_find_mdt_idx_by_fid(env, lfsck, &lnr->lnr_fid);
3563         if (idx < 0)
3564                 GOTO(out, rc = idx);
3565
3566         if (idx == lfsck_dev_idx(lfsck->li_bottom)) {
3567                 if (unlikely(strcmp(lnr->lnr_name, dotdot) == 0))
3568                         GOTO(out, rc = 0);
3569
3570                 dev = lfsck->li_next;
3571         } else {
3572                 struct lfsck_tgt_desc *ltd;
3573
3574                 /* Usually, some local filesystem consistency verification
3575                  * tools can guarantee the local namespace tree consistenct.
3576                  * So the LFSCK will only verify the remote directory. */
3577                 if (unlikely(strcmp(lnr->lnr_name, dotdot) == 0)) {
3578                         rc = lfsck_namespace_trace_update(env, com, pfid,
3579                                                 LNTF_CHECK_PARENT, true);
3580
3581                         GOTO(out, rc);
3582                 }
3583
3584                 ltd = LTD_TGT(&lfsck->li_mdt_descs, idx);
3585                 if (unlikely(ltd == NULL)) {
3586                         CDEBUG(D_LFSCK, "%s: cannot talk with MDT %x which "
3587                                "did not join the namespace LFSCK\n",
3588                                lfsck_lfsck2name(lfsck), idx);
3589                         ns->ln_flags |= LF_INCOMPLETE;
3590
3591                         GOTO(out, rc = -ENODEV);
3592                 }
3593
3594                 dev = ltd->ltd_tgt;
3595         }
3596
3597         obj = lfsck_object_find_by_dev(env, dev, &lnr->lnr_fid);
3598         if (IS_ERR(obj))
3599                 GOTO(out, rc = PTR_ERR(obj));
3600
3601         cname = lfsck_name_get_const(env, lnr->lnr_name, lnr->lnr_namelen);
3602         if (dt_object_exists(obj) == 0) {
3603
3604 dangling:
3605                 rc = lfsck_namespace_check_exist(env, dir, obj, lnr->lnr_name);
3606                 if (rc == 0) {
3607                         type = LNIT_DANGLING;
3608                         rc = lfsck_namespace_repair_dangling(env, com,
3609                                                              obj, lnr);
3610                         if (rc == 0)
3611                                 repaired = true;
3612                 }
3613
3614                 GOTO(out, rc);
3615         }
3616
3617         if (!(bk->lb_param & LPF_DRYRUN) && repaired) {
3618
3619 again:
3620                 rc = lfsck_ibits_lock(env, lfsck, obj, &lh,
3621                                       MDS_INODELOCK_UPDATE |
3622                                       MDS_INODELOCK_XATTR, LCK_EX);
3623                 if (rc != 0)
3624                         GOTO(out, rc);
3625
3626                 handle = dt_trans_create(env, dev);
3627                 if (IS_ERR(handle))
3628                         GOTO(out, rc = PTR_ERR(handle));
3629
3630                 rc = lfsck_declare_namespace_exec_dir(env, obj, handle);
3631                 if (rc != 0)
3632                         GOTO(stop, rc);
3633
3634                 rc = dt_trans_start(env, dev, handle);
3635                 if (rc != 0)
3636                         GOTO(stop, rc);
3637
3638                 dt_write_lock(env, obj, 0);
3639                 dtlocked = true;
3640         }
3641
3642         rc = lfsck_namespace_check_exist(env, dir, obj, lnr->lnr_name);
3643         if (rc != 0)
3644                 GOTO(stop, rc);
3645
3646         rc = lfsck_links_read(env, obj, &ldata);
3647         if (unlikely(rc == -ENOENT)) {
3648                 if (handle != NULL) {
3649                         dt_write_unlock(env, obj);
3650                         dtlocked = false;
3651
3652                         dt_trans_stop(env, dev, handle);
3653                         handle = NULL;
3654
3655                         lfsck_ibits_unlock(&lh, LCK_EX);
3656                 }
3657
3658                 /* It may happen when the remote object has been removed,
3659                  * but the local MDT is not aware of that. */
3660                 goto dangling;
3661         } else if (rc == 0) {
3662                 count = ldata.ld_leh->leh_reccount;
3663                 rc = linkea_links_find(&ldata, cname, pfid);
3664                 if ((rc == 0) &&
3665                     (count == 1 || !S_ISDIR(lfsck_object_type(obj)))) {
3666                         if ((lfsck_object_type(obj) & S_IFMT) !=
3667                             lnr->lnr_type) {
3668                                 ns->ln_flags |= LF_INCONSISTENT;
3669                                 type = LNIT_BAD_TYPE;
3670                         }
3671
3672                         goto record;
3673                 }
3674
3675                 ns->ln_flags |= LF_INCONSISTENT;
3676
3677                 /* If the file type stored in the name entry does not match
3678                  * the file type claimed by the object, and the object does
3679                  * not recognize the name entry, then it is quite possible
3680                  * that the name entry is corrupted. */
3681                 if ((lfsck_object_type(obj) & S_IFMT) != lnr->lnr_type) {
3682                         type = LNIT_BAD_DIRENT;
3683
3684                         GOTO(stop, rc = 0);
3685                 }
3686
3687                 /* For sub-dir object, we cannot make sure whether the sub-dir
3688                  * back references the parent via ".." name entry correctly or
3689                  * not in the LFSCK first-stage scanning. It may be that the
3690                  * (remote) sub-dir ".." name entry has no parent FID after
3691                  * file-level backup/restore and its linkEA may be wrong.
3692                  * So under such case, we should replace the linkEA according
3693                  * to current name entry. But this needs to be done during the
3694                  * LFSCK second-stage scanning. The LFSCK will record the name
3695                  * entry for further possible using. */
3696                 remove = false;
3697                 newdata = false;
3698                 goto nodata;
3699         } else if (unlikely(rc == -EINVAL)) {
3700                 if ((lfsck_object_type(obj) & S_IFMT) != lnr->lnr_type)
3701                         type = LNIT_BAD_TYPE;
3702
3703                 count = 1;
3704                 ns->ln_flags |= LF_INCONSISTENT;
3705                 /* The magic crashed, we are not sure whether there are more
3706                  * corrupt data in the linkea, so remove all linkea entries. */
3707                 remove = true;
3708                 newdata = true;
3709                 goto nodata;
3710         } else if (rc == -ENODATA) {
3711                 if ((lfsck_object_type(obj) & S_IFMT) != lnr->lnr_type)
3712                         type = LNIT_BAD_TYPE;
3713
3714                 count = 1;
3715                 ns->ln_flags |= LF_UPGRADE;
3716                 remove = false;
3717                 newdata = true;
3718
3719 nodata:
3720                 if (bk->lb_param & LPF_DRYRUN) {
3721                         ns->ln_linkea_repaired++;
3722                         repaired = true;
3723                         log = true;
3724                         goto record;
3725                 }
3726
3727                 if (!lustre_handle_is_used(&lh))
3728                         goto again;
3729
3730                 if (remove) {
3731                         LASSERT(newdata);
3732
3733                         rc = dt_xattr_del(env, obj, XATTR_NAME_LINK, handle,
3734                                           BYPASS_CAPA);
3735                         if (rc != 0)
3736                                 GOTO(stop, rc);
3737                 }
3738
3739                 if (newdata) {
3740                         rc = linkea_data_new(&ldata,
3741                                         &lfsck_env_info(env)->lti_linkea_buf);
3742                         if (rc != 0)
3743                                 GOTO(stop, rc);
3744                 }
3745
3746                 rc = linkea_add_buf(&ldata, cname, pfid);
3747                 if (rc != 0)
3748                         GOTO(stop, rc);
3749
3750                 rc = lfsck_links_write(env, obj, &ldata, handle);
3751                 if (rc != 0)
3752                         GOTO(stop, rc);
3753
3754                 count = ldata.ld_leh->leh_reccount;
3755                 if (!S_ISDIR(lfsck_object_type(obj)) ||
3756                     !dt_object_remote(obj)) {
3757                         ns->ln_linkea_repaired++;
3758                         repaired = true;
3759                         log = true;
3760                 }
3761         } else {
3762                 GOTO(stop, rc);
3763         }
3764
3765 record:
3766         LASSERT(count > 0);
3767
3768         rc = dt_attr_get(env, obj, la, BYPASS_CAPA);
3769         if (rc != 0)
3770                 GOTO(stop, rc);
3771
3772         if ((count == 1 && la->la_nlink == 1) ||
3773             S_ISDIR(lfsck_object_type(obj)))
3774                 /* Usually, it is for single linked object or dir, do nothing.*/
3775                 GOTO(stop, rc);
3776
3777         /* Following modification will be in another transaction.  */
3778         if (handle != NULL) {
3779                 dt_write_unlock(env, obj);
3780                 dtlocked = false;
3781
3782                 dt_trans_stop(env, dev, handle);
3783                 handle = NULL;
3784
3785                 lfsck_ibits_unlock(&lh, LCK_EX);
3786         }
3787
3788         ns->ln_mul_linked_checked++;
3789         rc = lfsck_namespace_trace_update(env, com, &lnr->lnr_fid,
3790                                           LNTF_CHECK_LINKEA, true);
3791
3792         GOTO(out, rc);
3793
3794 stop:
3795         if (dtlocked)
3796                 dt_write_unlock(env, obj);
3797
3798         if (handle != NULL && !IS_ERR(handle))
3799                 dt_trans_stop(env, dev, handle);
3800
3801 out:
3802         lfsck_ibits_unlock(&lh, LCK_EX);
3803
3804         if (rc >= 0) {
3805                 switch (type) {
3806                 case LNIT_BAD_TYPE:
3807                         log = false;
3808                         rc = lfsck_namespace_repair_dirent(env, com, dir,
3809                                         obj, lnr->lnr_name, lnr->lnr_name,
3810                                         lnr->lnr_type, true, false);
3811                         if (rc > 0)
3812                                 repaired = true;
3813                         break;
3814                 case LNIT_BAD_DIRENT:
3815                         log = false;
3816                         /* XXX: This is a bad dirent, we do not know whether
3817                          *      the original name entry reference a regular
3818                          *      file or a directory, then keep the parent's
3819                          *      nlink count unchanged here. */
3820                         rc = lfsck_namespace_repair_dirent(env, com, dir,
3821                                         obj, lnr->lnr_name, lnr->lnr_name,
3822                                         lnr->lnr_type, false, false);
3823                         if (rc > 0)
3824                                 repaired = true;
3825                         break;
3826                 default:
3827                         break;
3828                 }
3829         }
3830
3831         down_write(&com->lc_sem);
3832         if (rc < 0) {
3833                 CDEBUG(D_LFSCK, "%s: namespace LFSCK assistant fail to handle "
3834                        "the entry: "DFID", parent "DFID", name %.*s: rc = %d\n",
3835                        lfsck_lfsck2name(lfsck), PFID(&lnr->lnr_fid),
3836                        PFID(lfsck_dto2fid(lnr->lnr_obj)),
3837                        lnr->lnr_namelen, lnr->lnr_name, rc);
3838
3839                 lfsck_namespace_record_failure(env, lfsck, ns);
3840                 if (!(bk->lb_param & LPF_FAILOUT))
3841                         rc = 0;
3842         } else {
3843                 if (log)
3844                         CDEBUG(D_LFSCK, "%s: namespace LFSCK assistant "
3845                                "repaired the entry: "DFID", parent "DFID
3846                                ", name %.*s\n", lfsck_lfsck2name(lfsck),
3847                                PFID(&lnr->lnr_fid),
3848                                PFID(lfsck_dto2fid(lnr->lnr_obj)),
3849                                lnr->lnr_namelen, lnr->lnr_name);
3850
3851                 if (repaired) {
3852                         ns->ln_items_repaired++;
3853
3854                         switch (type) {
3855                         case LNIT_DANGLING:
3856                                 ns->ln_dangling_repaired++;
3857                                 break;
3858                         case LNIT_BAD_TYPE:
3859                                 ns->ln_bad_type_repaired++;
3860                                 break;
3861                         case LNIT_BAD_DIRENT:
3862                                 ns->ln_dirent_repaired++;
3863                                 break;
3864                         default:
3865                                 break;
3866                         }
3867
3868                         if (bk->lb_param & LPF_DRYRUN &&
3869                             lfsck_pos_is_zero(&ns->ln_pos_first_inconsistent))
3870                                 lfsck_pos_fill(env, lfsck,
3871                                                &ns->ln_pos_first_inconsistent,
3872                                                false);
3873                 }
3874
3875                 rc = 0;
3876         }
3877         up_write(&com->lc_sem);
3878
3879         if (obj != NULL && !IS_ERR(obj))
3880                 lfsck_object_put(env, obj);
3881         return rc;
3882 }
3883
3884 static int lfsck_namespace_assistant_handler_p2(const struct lu_env *env,
3885                                                 struct lfsck_component *com)
3886 {
3887         struct lfsck_instance   *lfsck  = com->lc_lfsck;
3888         struct ptlrpc_thread    *thread = &lfsck->li_thread;
3889         struct lfsck_bookmark   *bk     = &lfsck->li_bookmark_ram;
3890         struct lfsck_namespace  *ns     = com->lc_file_ram;
3891         struct dt_object        *obj    = com->lc_obj;
3892         const struct dt_it_ops  *iops   = &obj->do_index_ops->dio_it;
3893         struct dt_object        *target;
3894         struct dt_it            *di;
3895         struct dt_key           *key;
3896         struct lu_fid            fid;
3897         int                      rc;
3898         __u8                     flags  = 0;
3899         ENTRY;
3900
3901         CDEBUG(D_LFSCK, "%s: namespace LFSCK phase2 scan start\n",
3902                lfsck_lfsck2name(lfsck));
3903
3904         com->lc_new_checked = 0;
3905         com->lc_new_scanned = 0;
3906         com->lc_time_last_checkpoint = cfs_time_current();
3907         com->lc_time_next_checkpoint = com->lc_time_last_checkpoint +
3908                                 cfs_time_seconds(LFSCK_CHECKPOINT_INTERVAL);
3909
3910         di = iops->init(env, obj, 0, BYPASS_CAPA);
3911         if (IS_ERR(di))
3912                 RETURN(PTR_ERR(di));
3913
3914         fid_cpu_to_be(&fid, &ns->ln_fid_latest_scanned_phase2);
3915         rc = iops->get(env, di, (const struct dt_key *)&fid);
3916         if (rc < 0)
3917                 GOTO(fini, rc);
3918
3919         /* Skip the start one, which either has been processed or non-exist. */
3920         rc = iops->next(env, di);
3921         if (rc != 0)
3922                 GOTO(put, rc);
3923
3924         do {
3925                 if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_DELAY3) &&
3926                     cfs_fail_val > 0) {
3927                         struct l_wait_info lwi;
3928
3929                         lwi = LWI_TIMEOUT(cfs_time_seconds(cfs_fail_val),
3930                                           NULL, NULL);
3931                         l_wait_event(thread->t_ctl_waitq,
3932                                      !thread_is_running(thread),
3933                                      &lwi);
3934
3935                         if (unlikely(!thread_is_running(thread)))
3936                                 GOTO(put, rc = 0);
3937                 }
3938
3939                 key = iops->key(env, di);
3940                 fid_be_to_cpu(&fid, (const struct lu_fid *)key);
3941                 if (!fid_is_sane(&fid)) {
3942                         rc = 0;
3943                         goto checkpoint;
3944                 }
3945
3946                 target = lfsck_object_find(env, lfsck, &fid);
3947                 if (IS_ERR(target)) {
3948                         rc = PTR_ERR(target);
3949                         goto checkpoint;
3950                 }
3951
3952                 if (dt_object_exists(target)) {
3953                         rc = iops->rec(env, di, (struct dt_rec *)&flags, 0);
3954                         if (rc == 0) {
3955                                 rc = lfsck_namespace_double_scan_one(env, com,
3956                                                                 target, flags);
3957                                 if (rc == -ENOENT)
3958                                         rc = 0;
3959                         }
3960                 }
3961
3962                 lfsck_object_put(env, target);
3963
3964 checkpoint:
3965                 down_write(&com->lc_sem);
3966                 com->lc_new_checked++;
3967                 com->lc_new_scanned++;
3968                 ns->ln_fid_latest_scanned_phase2 = fid;
3969                 if (rc > 0)
3970                         ns->ln_objs_repaired_phase2++;
3971                 else if (rc < 0)
3972                         ns->ln_objs_failed_phase2++;
3973                 up_write(&com->lc_sem);
3974
3975                 if (rc < 0 && bk->lb_param & LPF_FAILOUT)
3976                         GOTO(put, rc);
3977
3978                 if (unlikely(cfs_time_beforeq(com->lc_time_next_checkpoint,
3979                                               cfs_time_current())) &&
3980                     com->lc_new_checked != 0) {
3981                         down_write(&com->lc_sem);
3982                         ns->ln_run_time_phase2 +=
3983                                 cfs_duration_sec(cfs_time_current() +
3984                                 HALF_SEC - com->lc_time_last_checkpoint);
3985                         ns->ln_time_last_checkpoint = cfs_time_current_sec();
3986                         ns->ln_objs_checked_phase2 += com->lc_new_checked;
3987                         com->lc_new_checked = 0;
3988                         rc = lfsck_namespace_store(env, com, false);
3989                         up_write(&com->lc_sem);
3990                         if (rc != 0)
3991                                 GOTO(put, rc);
3992
3993                         com->lc_time_last_checkpoint = cfs_time_current();
3994                         com->lc_time_next_checkpoint =
3995                                 com->lc_time_last_checkpoint +
3996                                 cfs_time_seconds(LFSCK_CHECKPOINT_INTERVAL);
3997                 }
3998
3999                 lfsck_control_speed_by_self(com);
4000                 if (unlikely(!thread_is_running(thread)))
4001                         GOTO(put, rc = 0);
4002
4003                 rc = iops->next(env, di);
4004         } while (rc == 0);
4005
4006         GOTO(put, rc);
4007
4008 put:
4009         iops->put(env, di);
4010
4011 fini:
4012         iops->fini(env, di);
4013
4014         CDEBUG(D_LFSCK, "%s: namespace LFSCK phase2 scan stop: rc = %d\n",
4015                lfsck_lfsck2name(lfsck), rc);
4016
4017         return rc;
4018 }
4019
4020 static void lfsck_namespace_assistant_fill_pos(const struct lu_env *env,
4021                                                struct lfsck_component *com,
4022                                                struct lfsck_position *pos)
4023 {
4024         struct lfsck_assistant_data     *lad = com->lc_data;
4025         struct lfsck_namespace_req      *lnr;
4026
4027         if (list_empty(&lad->lad_req_list))
4028                 return;
4029
4030         lnr = list_entry(lad->lad_req_list.next,
4031                          struct lfsck_namespace_req,
4032                          lnr_lar.lar_list);
4033         pos->lp_oit_cookie = lnr->lnr_oit_cookie;
4034         pos->lp_dir_cookie = lnr->lnr_dir_cookie - 1;
4035         pos->lp_dir_parent = *lfsck_dto2fid(lnr->lnr_obj);
4036 }
4037
4038 static int lfsck_namespace_double_scan_result(const struct lu_env *env,
4039                                               struct lfsck_component *com,
4040                                               int rc)
4041 {
4042         struct lfsck_instance   *lfsck  = com->lc_lfsck;
4043         struct lfsck_namespace  *ns     = com->lc_file_ram;
4044
4045         down_write(&com->lc_sem);
4046         ns->ln_run_time_phase2 += cfs_duration_sec(cfs_time_current() +
4047                                 HALF_SEC - lfsck->li_time_last_checkpoint);
4048         ns->ln_time_last_checkpoint = cfs_time_current_sec();
4049         ns->ln_objs_checked_phase2 += com->lc_new_checked;
4050         com->lc_new_checked = 0;
4051
4052         if (rc > 0) {
4053                 if (ns->ln_flags & LF_INCOMPLETE)
4054                         ns->ln_status = LS_PARTIAL;
4055                 else
4056                         ns->ln_status = LS_COMPLETED;
4057                 if (!(lfsck->li_bookmark_ram.lb_param & LPF_DRYRUN))
4058                         ns->ln_flags &= ~(LF_SCANNED_ONCE | LF_INCONSISTENT);
4059                 ns->ln_time_last_complete = ns->ln_time_last_checkpoint;
4060                 ns->ln_success_count++;
4061         } else if (rc == 0) {
4062                 ns->ln_status = lfsck->li_status;
4063                 if (ns->ln_status == 0)
4064                         ns->ln_status = LS_STOPPED;
4065         } else {
4066                 ns->ln_status = LS_FAILED;
4067         }
4068
4069         rc = lfsck_namespace_store(env, com, false);
4070         up_write(&com->lc_sem);
4071
4072         return rc;
4073 }
4074
4075 static void lfsck_namespace_assistant_sync_failures(const struct lu_env *env,
4076                                                     struct lfsck_component *com,
4077                                                     struct lfsck_request *lr)
4078 {
4079         /* XXX: TBD */
4080 }
4081
4082 struct lfsck_assistant_operations lfsck_namespace_assistant_ops = {
4083         .la_handler_p1          = lfsck_namespace_assistant_handler_p1,
4084         .la_handler_p2          = lfsck_namespace_assistant_handler_p2,
4085         .la_fill_pos            = lfsck_namespace_assistant_fill_pos,
4086         .la_double_scan_result  = lfsck_namespace_double_scan_result,
4087         .la_req_fini            = lfsck_namespace_assistant_req_fini,
4088         .la_sync_failures       = lfsck_namespace_assistant_sync_failures,
4089 };
4090
4091 /**
4092  * Verify the specified linkEA entry for the given directory object.
4093  * If the object has no such linkEA entry or it has more other linkEA
4094  * entries, then re-generate the linkEA with the given information.
4095  *
4096  * \param[in] env       pointer to the thread context
4097  * \param[in] dev       pointer to the dt_device
4098  * \param[in] obj       pointer to the dt_object to be handled
4099  * \param[in] cname     the name for the child in the parent directory
4100  * \param[in] pfid      the parent directory's FID for the linkEA
4101  *
4102  * \retval              0 for success
4103  * \retval              negative error number on failure
4104  */
4105 int lfsck_verify_linkea(const struct lu_env *env, struct dt_device *dev,
4106                         struct dt_object *obj, const struct lu_name *cname,
4107                         const struct lu_fid *pfid)
4108 {
4109         struct linkea_data       ldata  = { 0 };
4110         struct lu_buf            linkea_buf;
4111         struct thandle          *th;
4112         int                      rc;
4113         int                      fl     = LU_XATTR_CREATE;
4114         bool                     dirty  = false;
4115         ENTRY;
4116
4117         LASSERT(S_ISDIR(lfsck_object_type(obj)));
4118
4119         rc = lfsck_links_read(env, obj, &ldata);
4120         if (rc == -ENODATA) {
4121                 dirty = true;
4122         } else if (rc == 0) {
4123                 fl = LU_XATTR_REPLACE;
4124                 if (ldata.ld_leh->leh_reccount != 1) {
4125                         dirty = true;
4126                 } else {
4127                         rc = linkea_links_find(&ldata, cname, pfid);
4128                         if (rc != 0)
4129                                 dirty = true;
4130                 }
4131         }
4132
4133         if (!dirty)
4134                 RETURN(rc);
4135
4136         rc = linkea_data_new(&ldata, &lfsck_env_info(env)->lti_linkea_buf);
4137         if (rc != 0)
4138                 RETURN(rc);
4139
4140         rc = linkea_add_buf(&ldata, cname, pfid);
4141         if (rc != 0)
4142                 RETURN(rc);
4143
4144         lfsck_buf_init(&linkea_buf, ldata.ld_buf->lb_buf,
4145                        ldata.ld_leh->leh_len);
4146         th = dt_trans_create(env, dev);
4147         if (IS_ERR(th))
4148                 RETURN(PTR_ERR(th));
4149
4150         rc = dt_declare_xattr_set(env, obj, &linkea_buf,
4151                                   XATTR_NAME_LINK, fl, th);
4152         if (rc != 0)
4153                 GOTO(stop, rc);
4154
4155         rc = dt_trans_start_local(env, dev, th);
4156         if (rc != 0)
4157                 GOTO(stop, rc);
4158
4159         dt_write_lock(env, obj, 0);
4160         rc = dt_xattr_set(env, obj, &linkea_buf,
4161                           XATTR_NAME_LINK, fl, th, BYPASS_CAPA);
4162         dt_write_unlock(env, obj);
4163
4164         GOTO(stop, rc);
4165
4166 stop:
4167         dt_trans_stop(env, dev, th);
4168         return rc;
4169 }
4170
4171 /**
4172  * Get the name and parent directory's FID from the first linkEA entry.
4173  *
4174  * \param[in] env       pointer to the thread context
4175  * \param[in] obj       pointer to the object which get linkEA from
4176  * \param[out] name     pointer to the buffer to hold the name
4177  *                      in the first linkEA entry
4178  * \param[out] pfid     pointer to the buffer to hold the parent
4179  *                      directory's FID in the first linkEA entry
4180  *
4181  * \retval              0 for success
4182  * \retval              negative error number on failure
4183  */
4184 int lfsck_links_get_first(const struct lu_env *env, struct dt_object *obj,
4185                           char *name, struct lu_fid *pfid)
4186 {
4187         struct lu_name           *cname = &lfsck_env_info(env)->lti_name;
4188         struct linkea_data        ldata = { 0 };
4189         int                       rc;
4190
4191         rc = lfsck_links_read(env, obj, &ldata);
4192         if (rc != 0)
4193                 return rc;
4194
4195         linkea_first_entry(&ldata);
4196         if (ldata.ld_lee == NULL)
4197                 return -ENODATA;
4198
4199         linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen, cname, pfid);
4200         /* To guarantee the 'name' is terminated with '0'. */
4201         memcpy(name, cname->ln_name, cname->ln_namelen);
4202         name[cname->ln_namelen] = 0;
4203
4204         return 0;
4205 }
4206
4207 /**
4208  * Remove the name entry from the parent directory.
4209  *
4210  * No need to care about the object referenced by the name entry,
4211  * either the name entry is invalid or redundant, or the referenced
4212  * object has been processed has been or will be handled by others.
4213  *
4214  * \param[in] env       pointer to the thread context
4215  * \param[in] lfsck     pointer to the lfsck instance
4216  * \param[in] parent    pointer to the lost+found object
4217  * \param[in] name      the name for the name entry to be removed
4218  * \param[in] type      the type for the name entry to be removed
4219  *
4220  * \retval              0 for success
4221  * \retval              negative error number on failure
4222  */
4223 int lfsck_remove_name_entry(const struct lu_env *env,
4224                             struct lfsck_instance *lfsck,
4225                             struct dt_object *parent,
4226                             const char *name, __u32 type)
4227 {
4228         struct dt_device        *dev    = lfsck->li_next;
4229         struct thandle          *th;
4230         struct lustre_handle     lh     = { 0 };
4231         int                      rc;
4232         ENTRY;
4233
4234         rc = lfsck_ibits_lock(env, lfsck, parent, &lh,
4235                               MDS_INODELOCK_UPDATE, LCK_EX);
4236         if (rc != 0)
4237                 RETURN(rc);
4238
4239         th = dt_trans_create(env, dev);
4240         if (IS_ERR(th))
4241                 GOTO(unlock, rc = PTR_ERR(th));
4242
4243         rc = dt_declare_delete(env, parent, (const struct dt_key *)name, th);
4244         if (rc != 0)
4245                 GOTO(stop, rc);
4246
4247         if (S_ISDIR(type)) {
4248                 rc = dt_declare_ref_del(env, parent, th);
4249                 if (rc != 0)
4250                         GOTO(stop, rc);
4251         }
4252
4253         rc = dt_trans_start(env, dev, th);
4254         if (rc != 0)
4255                 GOTO(stop, rc);
4256
4257         rc = dt_delete(env, parent, (const struct dt_key *)name, th,
4258                        BYPASS_CAPA);
4259         if (rc != 0)
4260                 GOTO(stop, rc);
4261
4262         if (S_ISDIR(type)) {
4263                 dt_write_lock(env, parent, 0);
4264                 rc = dt_ref_del(env, parent, th);
4265                 dt_write_unlock(env, parent);
4266         }
4267
4268         GOTO(stop, rc);
4269
4270 stop:
4271         dt_trans_stop(env, dev, th);
4272
4273 unlock:
4274         lfsck_ibits_unlock(&lh, LCK_EX);
4275
4276         CDEBUG(D_LFSCK, "%s: remove name entry "DFID"/%s "
4277                "with type %o: rc = %d\n", lfsck_lfsck2name(lfsck),
4278                PFID(lfsck_dto2fid(parent)), name, type, rc);
4279
4280         return rc;
4281 }
4282
4283 /**
4284  * Update the object's name entry with the given FID.
4285  *
4286  * \param[in] env       pointer to the thread context
4287  * \param[in] lfsck     pointer to the lfsck instance
4288  * \param[in] parent    pointer to the parent directory that holds
4289  *                      the name entry
4290  * \param[in] name      the name for the entry to be updated
4291  * \param[in] pfid      the new PFID for the name entry
4292  * \param[in] type      the type for the name entry to be updated
4293  *
4294  * \retval              0 for success
4295  * \retval              negative error number on failure
4296  */
4297 int lfsck_update_name_entry(const struct lu_env *env,
4298                             struct lfsck_instance *lfsck,
4299                             struct dt_object *parent, const char *name,
4300                             const struct lu_fid *pfid, __u32 type)
4301 {
4302         struct dt_insert_rec    *rec    = &lfsck_env_info(env)->lti_dt_rec;
4303         struct dt_device        *dev    = lfsck->li_next;
4304         struct lustre_handle     lh     = { 0 };
4305         struct thandle          *th;
4306         int                      rc;
4307         bool                     exists = true;
4308         ENTRY;
4309
4310         rc = lfsck_ibits_lock(env, lfsck, parent, &lh,
4311                               MDS_INODELOCK_UPDATE, LCK_EX);
4312         if (rc != 0)
4313                 RETURN(rc);
4314
4315         th = dt_trans_create(env, dev);
4316         if (IS_ERR(th))
4317                 GOTO(unlock, rc = PTR_ERR(th));
4318
4319         rc = dt_declare_delete(env, parent, (const struct dt_key *)name, th);
4320         if (rc != 0)
4321                 GOTO(stop, rc);
4322
4323         rec->rec_type = type;
4324         rec->rec_fid = pfid;
4325         rc = dt_declare_insert(env, parent, (const struct dt_rec *)rec,
4326                                (const struct dt_key *)name, th);
4327         if (rc != 0)
4328                 GOTO(stop, rc);
4329
4330         rc = dt_declare_ref_add(env, parent, th);
4331         if (rc != 0)
4332                 GOTO(stop, rc);
4333
4334         rc = dt_trans_start(env, dev, th);
4335         if (rc != 0)
4336                 GOTO(stop, rc);
4337
4338         rc = dt_delete(env, parent, (const struct dt_key *)name, th,
4339                        BYPASS_CAPA);
4340         if (rc == -ENOENT) {
4341                 exists = false;
4342                 rc = 0;
4343         }
4344
4345         if (rc != 0)
4346                 GOTO(stop, rc);
4347
4348         rc = dt_insert(env, parent, (const struct dt_rec *)rec,
4349                        (const struct dt_key *)name, th, BYPASS_CAPA, 1);
4350         if (rc == 0 && S_ISDIR(type) && !exists) {
4351                 dt_write_lock(env, parent, 0);
4352                 rc = dt_ref_add(env, parent, th);
4353                 dt_write_unlock(env, parent);
4354         }
4355
4356         GOTO(stop, rc);
4357
4358 stop:
4359         dt_trans_stop(env, dev, th);
4360
4361 unlock:
4362         lfsck_ibits_unlock(&lh, LCK_EX);
4363
4364         CDEBUG(D_LFSCK, "%s: update name entry "DFID"/%s with the FID "DFID
4365                " and the type %o: rc = %d\n", lfsck_lfsck2name(lfsck),
4366                PFID(lfsck_dto2fid(parent)), name, PFID(pfid), type, rc);
4367
4368         return rc;
4369 }
4370
4371 int lfsck_namespace_setup(const struct lu_env *env,
4372                           struct lfsck_instance *lfsck)
4373 {
4374         struct lfsck_component  *com;
4375         struct lfsck_namespace  *ns;
4376         struct dt_object        *root = NULL;
4377         struct dt_object        *obj;
4378         int                      rc;
4379         ENTRY;
4380
4381         LASSERT(lfsck->li_master);
4382
4383         OBD_ALLOC_PTR(com);
4384         if (com == NULL)
4385                 RETURN(-ENOMEM);
4386
4387         INIT_LIST_HEAD(&com->lc_link);
4388         INIT_LIST_HEAD(&com->lc_link_dir);
4389         init_rwsem(&com->lc_sem);
4390         atomic_set(&com->lc_ref, 1);
4391         com->lc_lfsck = lfsck;
4392         com->lc_type = LFSCK_TYPE_NAMESPACE;
4393         com->lc_ops = &lfsck_namespace_ops;
4394         com->lc_data = lfsck_assistant_data_init(
4395                         &lfsck_namespace_assistant_ops,
4396                         "lfsck_namespace");
4397         if (com->lc_data == NULL)
4398                 GOTO(out, rc = -ENOMEM);
4399
4400         com->lc_file_size = sizeof(struct lfsck_namespace);
4401         OBD_ALLOC(com->lc_file_ram, com->lc_file_size);
4402         if (com->lc_file_ram == NULL)
4403                 GOTO(out, rc = -ENOMEM);
4404
4405         OBD_ALLOC(com->lc_file_disk, com->lc_file_size);
4406         if (com->lc_file_disk == NULL)
4407                 GOTO(out, rc = -ENOMEM);
4408
4409         root = dt_locate(env, lfsck->li_bottom, &lfsck->li_local_root_fid);
4410         if (IS_ERR(root))
4411                 GOTO(out, rc = PTR_ERR(root));
4412
4413         if (unlikely(!dt_try_as_dir(env, root)))
4414                 GOTO(out, rc = -ENOTDIR);
4415
4416         obj = local_index_find_or_create(env, lfsck->li_los, root,
4417                                          lfsck_namespace_name,
4418                                          S_IFREG | S_IRUGO | S_IWUSR,
4419                                          &dt_lfsck_features);
4420         if (IS_ERR(obj))
4421                 GOTO(out, rc = PTR_ERR(obj));
4422
4423         com->lc_obj = obj;
4424         rc = obj->do_ops->do_index_try(env, obj, &dt_lfsck_features);
4425         if (rc != 0)
4426                 GOTO(out, rc);
4427
4428         rc = lfsck_namespace_load(env, com);
4429         if (rc > 0)
4430                 rc = lfsck_namespace_reset(env, com, true);
4431         else if (rc == -ENODATA)
4432                 rc = lfsck_namespace_init(env, com);
4433         if (rc != 0)
4434                 GOTO(out, rc);
4435
4436         ns = com->lc_file_ram;
4437         switch (ns->ln_status) {
4438         case LS_INIT:
4439         case LS_COMPLETED:
4440         case LS_FAILED:
4441         case LS_STOPPED:
4442                 spin_lock(&lfsck->li_lock);
4443                 list_add_tail(&com->lc_link, &lfsck->li_list_idle);
4444                 spin_unlock(&lfsck->li_lock);
4445                 break;
4446         default:
4447                 CERROR("%s: unknown lfsck_namespace status %d\n",
4448                        lfsck_lfsck2name(lfsck), ns->ln_status);
4449                 /* fall through */
4450         case LS_SCANNING_PHASE1:
4451         case LS_SCANNING_PHASE2:
4452                 /* No need to store the status to disk right now.
4453                  * If the system crashed before the status stored,
4454                  * it will be loaded back when next time. */
4455                 ns->ln_status = LS_CRASHED;
4456                 /* fall through */
4457         case LS_PAUSED:
4458         case LS_CRASHED:
4459                 spin_lock(&lfsck->li_lock);
4460                 list_add_tail(&com->lc_link, &lfsck->li_list_scan);
4461                 list_add_tail(&com->lc_link_dir, &lfsck->li_list_dir);
4462                 spin_unlock(&lfsck->li_lock);
4463                 break;
4464         }
4465
4466         GOTO(out, rc = 0);
4467
4468 out:
4469         if (root != NULL && !IS_ERR(root))
4470                 lu_object_put(env, &root->do_lu);
4471         if (rc != 0) {
4472                 lfsck_component_cleanup(env, com);
4473                 CERROR("%s: fail to init namespace LFSCK component: rc = %d\n",
4474                        lfsck_lfsck2name(lfsck), rc);
4475         }
4476         return rc;
4477 }