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