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