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