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