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