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