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