Whamcloud - gitweb
54b34981935550cb8815d3d6f2c83fef95e4b97c
[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         lu_object_get(&lfsck->li_obj_dir->do_lu);
68         lnr->lnr_obj = lfsck->li_obj_dir;
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         lu_object_put(env, &lnr->lnr_obj->do_lu);
88         OBD_FREE(lnr, lnr->lnr_size);
89 }
90
91 static void lfsck_namespace_le_to_cpu(struct lfsck_namespace *dst,
92                                       struct lfsck_namespace *src)
93 {
94         dst->ln_magic = le32_to_cpu(src->ln_magic);
95         dst->ln_status = le32_to_cpu(src->ln_status);
96         dst->ln_flags = le32_to_cpu(src->ln_flags);
97         dst->ln_success_count = le32_to_cpu(src->ln_success_count);
98         dst->ln_run_time_phase1 = le32_to_cpu(src->ln_run_time_phase1);
99         dst->ln_run_time_phase2 = le32_to_cpu(src->ln_run_time_phase2);
100         dst->ln_time_last_complete = le64_to_cpu(src->ln_time_last_complete);
101         dst->ln_time_latest_start = le64_to_cpu(src->ln_time_latest_start);
102         dst->ln_time_last_checkpoint =
103                                 le64_to_cpu(src->ln_time_last_checkpoint);
104         lfsck_position_le_to_cpu(&dst->ln_pos_latest_start,
105                                  &src->ln_pos_latest_start);
106         lfsck_position_le_to_cpu(&dst->ln_pos_last_checkpoint,
107                                  &src->ln_pos_last_checkpoint);
108         lfsck_position_le_to_cpu(&dst->ln_pos_first_inconsistent,
109                                  &src->ln_pos_first_inconsistent);
110         dst->ln_items_checked = le64_to_cpu(src->ln_items_checked);
111         dst->ln_items_repaired = le64_to_cpu(src->ln_items_repaired);
112         dst->ln_items_failed = le64_to_cpu(src->ln_items_failed);
113         dst->ln_dirs_checked = le64_to_cpu(src->ln_dirs_checked);
114         dst->ln_objs_checked_phase2 = le64_to_cpu(src->ln_objs_checked_phase2);
115         dst->ln_objs_repaired_phase2 =
116                                 le64_to_cpu(src->ln_objs_repaired_phase2);
117         dst->ln_objs_failed_phase2 = le64_to_cpu(src->ln_objs_failed_phase2);
118         dst->ln_objs_nlink_repaired = le64_to_cpu(src->ln_objs_nlink_repaired);
119         dst->ln_objs_lost_found = le64_to_cpu(src->ln_objs_lost_found);
120         fid_le_to_cpu(&dst->ln_fid_latest_scanned_phase2,
121                       &src->ln_fid_latest_scanned_phase2);
122         dst->ln_dirent_repaired = le64_to_cpu(src->ln_dirent_repaired);
123         dst->ln_linkea_repaired = le64_to_cpu(src->ln_linkea_repaired);
124         dst->ln_mul_linked_checked = le64_to_cpu(src->ln_mul_linked_checked);
125         dst->ln_mul_linked_repaired = le64_to_cpu(src->ln_mul_linked_repaired);
126         dst->ln_unknown_inconsistency =
127                                 le64_to_cpu(src->ln_unknown_inconsistency);
128         dst->ln_unmatched_pairs_repaired =
129                                 le64_to_cpu(src->ln_unmatched_pairs_repaired);
130         dst->ln_dangling_repaired = le64_to_cpu(src->ln_dangling_repaired);
131 }
132
133 static void lfsck_namespace_cpu_to_le(struct lfsck_namespace *dst,
134                                       struct lfsck_namespace *src)
135 {
136         dst->ln_magic = cpu_to_le32(src->ln_magic);
137         dst->ln_status = cpu_to_le32(src->ln_status);
138         dst->ln_flags = cpu_to_le32(src->ln_flags);
139         dst->ln_success_count = cpu_to_le32(src->ln_success_count);
140         dst->ln_run_time_phase1 = cpu_to_le32(src->ln_run_time_phase1);
141         dst->ln_run_time_phase2 = cpu_to_le32(src->ln_run_time_phase2);
142         dst->ln_time_last_complete = cpu_to_le64(src->ln_time_last_complete);
143         dst->ln_time_latest_start = cpu_to_le64(src->ln_time_latest_start);
144         dst->ln_time_last_checkpoint =
145                                 cpu_to_le64(src->ln_time_last_checkpoint);
146         lfsck_position_cpu_to_le(&dst->ln_pos_latest_start,
147                                  &src->ln_pos_latest_start);
148         lfsck_position_cpu_to_le(&dst->ln_pos_last_checkpoint,
149                                  &src->ln_pos_last_checkpoint);
150         lfsck_position_cpu_to_le(&dst->ln_pos_first_inconsistent,
151                                  &src->ln_pos_first_inconsistent);
152         dst->ln_items_checked = cpu_to_le64(src->ln_items_checked);
153         dst->ln_items_repaired = cpu_to_le64(src->ln_items_repaired);
154         dst->ln_items_failed = cpu_to_le64(src->ln_items_failed);
155         dst->ln_dirs_checked = cpu_to_le64(src->ln_dirs_checked);
156         dst->ln_objs_checked_phase2 = cpu_to_le64(src->ln_objs_checked_phase2);
157         dst->ln_objs_repaired_phase2 =
158                                 cpu_to_le64(src->ln_objs_repaired_phase2);
159         dst->ln_objs_failed_phase2 = cpu_to_le64(src->ln_objs_failed_phase2);
160         dst->ln_objs_nlink_repaired = cpu_to_le64(src->ln_objs_nlink_repaired);
161         dst->ln_objs_lost_found = cpu_to_le64(src->ln_objs_lost_found);
162         fid_cpu_to_le(&dst->ln_fid_latest_scanned_phase2,
163                       &src->ln_fid_latest_scanned_phase2);
164         dst->ln_dirent_repaired = cpu_to_le64(src->ln_dirent_repaired);
165         dst->ln_linkea_repaired = cpu_to_le64(src->ln_linkea_repaired);
166         dst->ln_mul_linked_checked = cpu_to_le64(src->ln_mul_linked_checked);
167         dst->ln_mul_linked_repaired = cpu_to_le64(src->ln_mul_linked_repaired);
168         dst->ln_unknown_inconsistency =
169                                 cpu_to_le64(src->ln_unknown_inconsistency);
170         dst->ln_unmatched_pairs_repaired =
171                                 cpu_to_le64(src->ln_unmatched_pairs_repaired);
172         dst->ln_dangling_repaired = cpu_to_le64(src->ln_dangling_repaired);
173 }
174
175 static void lfsck_namespace_record_failure(const struct lu_env *env,
176                                            struct lfsck_instance *lfsck,
177                                            struct lfsck_namespace *ns)
178 {
179         struct lfsck_position pos;
180
181         ns->ln_items_failed++;
182         lfsck_pos_fill(env, lfsck, &pos, false);
183         if (lfsck_pos_is_zero(&ns->ln_pos_first_inconsistent) ||
184             lfsck_pos_is_eq(&pos, &ns->ln_pos_first_inconsistent) < 0) {
185                 ns->ln_pos_first_inconsistent = pos;
186
187                 CDEBUG(D_LFSCK, "%s: namespace LFSCK hit first non-repaired "
188                        "inconsistency at the pos ["LPU64", "DFID", "LPX64"]\n",
189                        lfsck_lfsck2name(lfsck),
190                        ns->ln_pos_first_inconsistent.lp_oit_cookie,
191                        PFID(&ns->ln_pos_first_inconsistent.lp_dir_parent),
192                        ns->ln_pos_first_inconsistent.lp_dir_cookie);
193         }
194 }
195
196 /**
197  * \retval +ve: the lfsck_namespace is broken, the caller should reset it.
198  * \retval 0: succeed.
199  * \retval -ve: failed cases.
200  */
201 static int lfsck_namespace_load(const struct lu_env *env,
202                                 struct lfsck_component *com)
203 {
204         int len = com->lc_file_size;
205         int rc;
206
207         rc = dt_xattr_get(env, com->lc_obj,
208                           lfsck_buf_get(env, com->lc_file_disk, len),
209                           XATTR_NAME_LFSCK_NAMESPACE, BYPASS_CAPA);
210         if (rc == len) {
211                 struct lfsck_namespace *ns = com->lc_file_ram;
212
213                 lfsck_namespace_le_to_cpu(ns,
214                                 (struct lfsck_namespace *)com->lc_file_disk);
215                 if (ns->ln_magic != LFSCK_NAMESPACE_MAGIC) {
216                         CDEBUG(D_LFSCK, "%s: invalid lfsck_namespace magic "
217                                "%#x != %#x\n", lfsck_lfsck2name(com->lc_lfsck),
218                                ns->ln_magic, LFSCK_NAMESPACE_MAGIC);
219                         rc = 1;
220                 } else {
221                         rc = 0;
222                 }
223         } else if (rc != -ENODATA) {
224                 CDEBUG(D_LFSCK, "%s: fail to load lfsck_namespace, "
225                        "expected = %d: rc = %d\n",
226                        lfsck_lfsck2name(com->lc_lfsck), len, rc);
227                 if (rc >= 0)
228                         rc = 1;
229         }
230         return rc;
231 }
232
233 static int lfsck_namespace_store(const struct lu_env *env,
234                                  struct lfsck_component *com, bool init)
235 {
236         struct dt_object        *obj    = com->lc_obj;
237         struct lfsck_instance   *lfsck  = com->lc_lfsck;
238         struct thandle          *handle;
239         int                      len    = com->lc_file_size;
240         int                      rc;
241         ENTRY;
242
243         lfsck_namespace_cpu_to_le((struct lfsck_namespace *)com->lc_file_disk,
244                                   (struct lfsck_namespace *)com->lc_file_ram);
245         handle = dt_trans_create(env, lfsck->li_bottom);
246         if (IS_ERR(handle))
247                 GOTO(log, rc = PTR_ERR(handle));
248
249         rc = dt_declare_xattr_set(env, obj,
250                                   lfsck_buf_get(env, com->lc_file_disk, len),
251                                   XATTR_NAME_LFSCK_NAMESPACE, 0, handle);
252         if (rc != 0)
253                 GOTO(out, rc);
254
255         rc = dt_trans_start_local(env, lfsck->li_bottom, handle);
256         if (rc != 0)
257                 GOTO(out, rc);
258
259         rc = dt_xattr_set(env, obj,
260                           lfsck_buf_get(env, com->lc_file_disk, len),
261                           XATTR_NAME_LFSCK_NAMESPACE,
262                           init ? LU_XATTR_CREATE : LU_XATTR_REPLACE,
263                           handle, BYPASS_CAPA);
264
265         GOTO(out, rc);
266
267 out:
268         dt_trans_stop(env, lfsck->li_bottom, handle);
269
270 log:
271         if (rc != 0)
272                 CDEBUG(D_LFSCK, "%s: fail to store lfsck_namespace: rc = %d\n",
273                        lfsck_lfsck2name(lfsck), rc);
274         return rc;
275 }
276
277 static int lfsck_namespace_init(const struct lu_env *env,
278                                 struct lfsck_component *com)
279 {
280         struct lfsck_namespace *ns = com->lc_file_ram;
281         int rc;
282
283         memset(ns, 0, sizeof(*ns));
284         ns->ln_magic = LFSCK_NAMESPACE_MAGIC;
285         ns->ln_status = LS_INIT;
286         down_write(&com->lc_sem);
287         rc = lfsck_namespace_store(env, com, true);
288         up_write(&com->lc_sem);
289         return rc;
290 }
291
292 /**
293  * Update the namespace LFSCK tracing file for the given @fid
294  *
295  * \param[in] env       pointer to the thread context
296  * \param[in] com       pointer to the lfsck component
297  * \param[in] fid       the fid which flags to be updated in the lfsck
298  *                      tracing file
299  * \param[in] add       true if add new flags, otherwise remove flags
300  *
301  * \retval              0 for succeed or nothing to be done
302  * \retval              negative error number on failure
303  */
304 int lfsck_namespace_trace_update(const struct lu_env *env,
305                                  struct lfsck_component *com,
306                                  const struct lu_fid *fid,
307                                  const __u8 flags, bool add)
308 {
309         struct lfsck_instance   *lfsck  = com->lc_lfsck;
310         struct dt_object        *obj    = com->lc_obj;
311         struct lu_fid           *key    = &lfsck_env_info(env)->lti_fid3;
312         struct dt_device        *dev    = lfsck->li_bottom;
313         struct thandle          *th     = NULL;
314         int                      rc     = 0;
315         __u8                     old    = 0;
316         __u8                     new    = 0;
317         ENTRY;
318
319         LASSERT(flags != 0);
320
321         down_write(&com->lc_sem);
322         fid_cpu_to_be(key, fid);
323         rc = dt_lookup(env, obj, (struct dt_rec *)&old,
324                        (const struct dt_key *)key, BYPASS_CAPA);
325         if (rc == -ENOENT) {
326                 if (!add)
327                         GOTO(unlock, rc = 0);
328
329                 old = 0;
330                 new = flags;
331         } else if (rc == 0) {
332                 if (add) {
333                         if ((old & flags) == flags)
334                                 GOTO(unlock, rc = 0);
335
336                         new = old | flags;
337                 } else {
338                         if ((old & flags) == 0)
339                                 GOTO(unlock, rc = 0);
340
341                         new = old & ~flags;
342                 }
343         } else {
344                 GOTO(log, rc);
345         }
346
347         th = dt_trans_create(env, dev);
348         if (IS_ERR(th))
349                 GOTO(log, rc = PTR_ERR(th));
350
351         if (old != 0) {
352                 rc = dt_declare_delete(env, obj,
353                                        (const struct dt_key *)key, th);
354                 if (rc != 0)
355                         GOTO(log, rc);
356         }
357
358         if (new != 0) {
359                 rc = dt_declare_insert(env, obj,
360                                        (const struct dt_rec *)&new,
361                                        (const struct dt_key *)key, th);
362                 if (rc != 0)
363                         GOTO(log, rc);
364         }
365
366         rc = dt_trans_start_local(env, dev, th);
367         if (rc != 0)
368                 GOTO(log, rc);
369
370         if (old != 0) {
371                 rc = dt_delete(env, obj, (const struct dt_key *)key,
372                                th, BYPASS_CAPA);
373                 if (rc != 0)
374                         GOTO(log, rc);
375         }
376
377         if (new != 0) {
378                 rc = dt_insert(env, obj, (const struct dt_rec *)&new,
379                                (const struct dt_key *)key, th, BYPASS_CAPA, 1);
380                 if (rc != 0)
381                         GOTO(log, rc);
382         }
383
384         GOTO(log, rc);
385
386 log:
387         if (th != NULL && !IS_ERR(th))
388                 dt_trans_stop(env, dev, th);
389
390         CDEBUG(D_LFSCK, "%s: namespace LFSCK %s flags for "DFID" in the "
391                "tracing file, flags %x, old %x, new %x: rc = %d\n",
392                lfsck_lfsck2name(lfsck), add ? "add" : "del", PFID(fid),
393                (__u32)flags, (__u32)old, (__u32)new, rc);
394
395 unlock:
396         up_write(&com->lc_sem);
397
398         return rc;
399 }
400
401 static int lfsck_namespace_check_exist(const struct lu_env *env,
402                                        struct dt_object *dir,
403                                        struct dt_object *obj, const char *name)
404 {
405         struct lu_fid    *fid = &lfsck_env_info(env)->lti_fid;
406         int               rc;
407         ENTRY;
408
409         if (unlikely(lfsck_is_dead_obj(obj)))
410                 RETURN(LFSCK_NAMEENTRY_DEAD);
411
412         rc = dt_lookup(env, dir, (struct dt_rec *)fid,
413                        (const struct dt_key *)name, BYPASS_CAPA);
414         if (rc == -ENOENT)
415                 RETURN(LFSCK_NAMEENTRY_REMOVED);
416
417         if (rc < 0)
418                 RETURN(rc);
419
420         if (!lu_fid_eq(fid, lfsck_dto2fid(obj)))
421                 RETURN(LFSCK_NAMEENTRY_RECREATED);
422
423         RETURN(0);
424 }
425
426 static int lfsck_declare_namespace_exec_dir(const struct lu_env *env,
427                                             struct dt_object *obj,
428                                             struct thandle *handle)
429 {
430         int rc;
431
432         /* For destroying all invalid linkEA entries. */
433         rc = dt_declare_xattr_del(env, obj, XATTR_NAME_LINK, handle);
434         if (rc != 0)
435                 return rc;
436
437         /* For insert new linkEA entry. */
438         rc = dt_declare_xattr_set(env, obj,
439                         lfsck_buf_get_const(env, NULL, DEFAULT_LINKEA_SIZE),
440                         XATTR_NAME_LINK, 0, handle);
441         return rc;
442 }
443
444 int __lfsck_links_read(const struct lu_env *env, struct dt_object *obj,
445                        struct linkea_data *ldata)
446 {
447         int rc;
448
449         if (ldata->ld_buf->lb_buf == NULL)
450                 return -ENOMEM;
451
452         if (!dt_object_exists(obj))
453                 return -ENOENT;
454
455         rc = dt_xattr_get(env, obj, ldata->ld_buf, XATTR_NAME_LINK, BYPASS_CAPA);
456         if (rc == -ERANGE) {
457                 /* Buf was too small, figure out what we need. */
458                 rc = dt_xattr_get(env, obj, &LU_BUF_NULL, XATTR_NAME_LINK,
459                                   BYPASS_CAPA);
460                 if (rc <= 0)
461                         return rc;
462
463                 lu_buf_realloc(ldata->ld_buf, rc);
464                 if (ldata->ld_buf->lb_buf == NULL)
465                         return -ENOMEM;
466
467                 rc = dt_xattr_get(env, obj, ldata->ld_buf, XATTR_NAME_LINK,
468                                   BYPASS_CAPA);
469         }
470
471         if (rc > 0)
472                 rc = linkea_init(ldata);
473
474         return rc;
475 }
476
477 /**
478  * Remove linkEA for the given object.
479  *
480  * The caller should take the ldlm lock before the calling.
481  *
482  * \param[in] env       pointer to the thread context
483  * \param[in] com       pointer to the lfsck component
484  * \param[in] obj       pointer to the dt_object to be handled
485  *
486  * \retval              0 for repaired cases
487  * \retval              negative error number on failure
488  */
489 static int lfsck_namespace_links_remove(const struct lu_env *env,
490                                         struct lfsck_component *com,
491                                         struct dt_object *obj)
492 {
493         struct lfsck_instance           *lfsck  = com->lc_lfsck;
494         struct dt_device                *dev    = lfsck->li_bottom;
495         struct thandle                  *th     = NULL;
496         int                              rc     = 0;
497         ENTRY;
498
499         LASSERT(dt_object_remote(obj) == 0);
500
501         th = dt_trans_create(env, dev);
502         if (IS_ERR(th))
503                 GOTO(log, rc = PTR_ERR(th));
504
505         rc = dt_declare_xattr_del(env, obj, XATTR_NAME_LINK, th);
506         if (rc != 0)
507                 GOTO(stop, rc);
508
509         rc = dt_trans_start_local(env, dev, th);
510         if (rc != 0)
511                 GOTO(stop, rc);
512
513         dt_write_lock(env, obj, 0);
514         if (unlikely(lfsck_is_dead_obj(obj)))
515                 GOTO(unlock, rc = -ENOENT);
516
517         if (lfsck->li_bookmark_ram.lb_param & LPF_DRYRUN)
518                 GOTO(unlock, rc = 0);
519
520         rc = dt_xattr_del(env, obj, XATTR_NAME_LINK, th, BYPASS_CAPA);
521
522         GOTO(unlock, rc);
523
524 unlock:
525         dt_write_unlock(env, obj);
526
527 stop:
528         dt_trans_stop(env, dev, th);
529
530 log:
531         CDEBUG(D_LFSCK, "%s: namespace LFSCK remove invalid linkEA "
532                "for the object "DFID": rc = %d\n",
533                lfsck_lfsck2name(lfsck), PFID(lfsck_dto2fid(obj)), rc);
534
535         if (rc == 0) {
536                 struct lfsck_namespace *ns = com->lc_file_ram;
537
538                 ns->ln_flags |= LF_INCONSISTENT;
539         }
540
541         return rc;
542 }
543
544 static int lfsck_links_write(const struct lu_env *env, struct dt_object *obj,
545                              struct linkea_data *ldata, struct thandle *handle)
546 {
547         const struct lu_buf *buf = lfsck_buf_get_const(env,
548                                                        ldata->ld_buf->lb_buf,
549                                                        ldata->ld_leh->leh_len);
550
551         return dt_xattr_set(env, obj, buf, XATTR_NAME_LINK, 0, handle,
552                             BYPASS_CAPA);
553 }
554
555 static void lfsck_namespace_unpack_linkea_entry(struct linkea_data *ldata,
556                                                 struct lu_name *cname,
557                                                 struct lu_fid *pfid,
558                                                 char *buf)
559 {
560         linkea_entry_unpack(ldata->ld_lee, &ldata->ld_reclen, cname, pfid);
561         /* To guarantee the 'name' is terminated with '0'. */
562         memcpy(buf, cname->ln_name, cname->ln_namelen);
563         buf[cname->ln_namelen] = 0;
564         cname->ln_name = buf;
565 }
566
567 static int lfsck_namespace_filter_linkea_entry(struct linkea_data *ldata,
568                                                struct lu_name *cname,
569                                                struct lu_fid *pfid,
570                                                bool remove)
571 {
572         struct link_ea_entry    *oldlee;
573         int                      oldlen;
574         int                      repeated = 0;
575
576         oldlee = ldata->ld_lee;
577         oldlen = ldata->ld_reclen;
578         linkea_next_entry(ldata);
579         while (ldata->ld_lee != NULL) {
580                 ldata->ld_reclen = (ldata->ld_lee->lee_reclen[0] << 8) |
581                                    ldata->ld_lee->lee_reclen[1];
582                 if (unlikely(ldata->ld_reclen == oldlen &&
583                              memcmp(ldata->ld_lee, oldlee, oldlen) == 0)) {
584                         repeated++;
585                         if (!remove)
586                                 break;
587
588                         linkea_del_buf(ldata, cname);
589                 } else {
590                         linkea_next_entry(ldata);
591                 }
592         }
593         ldata->ld_lee = oldlee;
594         ldata->ld_reclen = oldlen;
595
596         return repeated;
597 }
598
599 static int lfsck_namespace_insert_orphan(const struct lu_env *env,
600                                          struct lfsck_component *com,
601                                          struct dt_object *orphan,
602                                          const char *infix, const char *type,
603                                          int *count)
604 {
605         /* XXX: TBD */
606         return 0;
607 }
608
609 static int lfsck_namespace_insert_normal(const struct lu_env *env,
610                                          struct lfsck_component *com,
611                                          struct dt_object *parent,
612                                          struct dt_object *child,
613                                          const char *name)
614 {
615         /* XXX: TBD */
616         return 0;
617 }
618
619 static int lfsck_namespace_create_orphan(const struct lu_env *env,
620                                          struct lfsck_component *com,
621                                          struct dt_object *orphan)
622 {
623         /* XXX: TBD */
624         return 0;
625 }
626
627 /**
628  * Remove the specified entry from the linkEA.
629  *
630  * Locate the linkEA entry with the given @cname and @pfid, then
631  * remove this entry or the other entries those are repeated with
632  * this entry.
633  *
634  * \param[in] env       pointer to the thread context
635  * \param[in] com       pointer to the lfsck component
636  * \param[in] obj       pointer to the dt_object to be handled
637  * \param[in,out]ldata  pointer to the buffer that holds the linkEA
638  * \param[in] cname     the name for the child in the parent directory
639  * \param[in] pfid      the parent directory's FID for the linkEA
640  * \param[in] next      if true, then remove the first found linkEA
641  *                      entry, and move the ldata->ld_lee to next entry
642  *
643  * \retval              positive number for repaired cases
644  * \retval              0 if nothing to be repaired
645  * \retval              negative error number on failure
646  */
647 static int lfsck_namespace_shrink_linkea(const struct lu_env *env,
648                                          struct lfsck_component *com,
649                                          struct dt_object *obj,
650                                          struct linkea_data *ldata,
651                                          struct lu_name *cname,
652                                          struct lu_fid *pfid,
653                                          bool next)
654 {
655         struct lfsck_instance           *lfsck     = com->lc_lfsck;
656         struct dt_device                *dev       = lfsck->li_bottom;
657         struct lfsck_bookmark           *bk        = &lfsck->li_bookmark_ram;
658         struct thandle                  *th        = NULL;
659         struct lustre_handle             lh        = { 0 };
660         struct linkea_data               ldata_new = { 0 };
661         struct lu_buf                    linkea_buf;
662         int                              rc        = 0;
663         ENTRY;
664
665         rc = lfsck_ibits_lock(env, lfsck, obj, &lh,
666                               MDS_INODELOCK_UPDATE |
667                               MDS_INODELOCK_XATTR, LCK_EX);
668         if (rc != 0)
669                 GOTO(log, rc);
670
671         if (next)
672                 linkea_del_buf(ldata, cname);
673         else
674                 lfsck_namespace_filter_linkea_entry(ldata, cname, pfid,
675                                                     true);
676         lfsck_buf_init(&linkea_buf, ldata->ld_buf->lb_buf,
677                        ldata->ld_leh->leh_len);
678
679 again:
680         th = dt_trans_create(env, dev);
681         if (IS_ERR(th))
682                 GOTO(unlock1, rc = PTR_ERR(th));
683
684         rc = dt_declare_xattr_set(env, obj, &linkea_buf,
685                                   XATTR_NAME_LINK, 0, th);
686         if (rc != 0)
687                 GOTO(stop, rc);
688
689         rc = dt_trans_start_local(env, dev, th);
690         if (rc != 0)
691                 GOTO(stop, rc);
692
693         dt_write_lock(env, obj, 0);
694         if (unlikely(lfsck_is_dead_obj(obj)))
695                 GOTO(unlock2, rc = -ENOENT);
696
697         rc = lfsck_links_read2(env, obj, &ldata_new);
698         if (rc != 0)
699                 GOTO(unlock2, rc);
700
701         /* The specified linkEA entry has been removed by race. */
702         rc = linkea_links_find(&ldata_new, cname, pfid);
703         if (rc != 0)
704                 GOTO(unlock2, rc = 0);
705
706         if (bk->lb_param & LPF_DRYRUN)
707                 GOTO(unlock2, rc = 1);
708
709         if (next)
710                 linkea_del_buf(&ldata_new, cname);
711         else
712                 lfsck_namespace_filter_linkea_entry(&ldata_new, cname, pfid,
713                                                     true);
714
715         if (linkea_buf.lb_len < ldata_new.ld_leh->leh_len) {
716                 dt_write_unlock(env, obj);
717                 dt_trans_stop(env, dev, th);
718                 lfsck_buf_init(&linkea_buf, ldata_new.ld_buf->lb_buf,
719                                ldata_new.ld_leh->leh_len);
720                 goto again;
721         }
722
723         lfsck_buf_init(&linkea_buf, ldata_new.ld_buf->lb_buf,
724                        ldata_new.ld_leh->leh_len);
725         rc = dt_xattr_set(env, obj, &linkea_buf,
726                           XATTR_NAME_LINK, 0, th, BYPASS_CAPA);
727
728         GOTO(unlock2, rc = (rc == 0 ? 1 : rc));
729
730 unlock2:
731         dt_write_unlock(env, obj);
732
733 stop:
734         dt_trans_stop(env, dev, th);
735
736 unlock1:
737         lfsck_ibits_unlock(&lh, LCK_EX);
738
739 log:
740         CDEBUG(D_LFSCK, "%s: namespace LFSCK remove %s linkEA entry "
741                "for the object: "DFID", parent "DFID", name %.*s\n",
742                lfsck_lfsck2name(lfsck), next ? "invalid" : "redundant",
743                PFID(lfsck_dto2fid(obj)), PFID(pfid), cname->ln_namelen,
744                cname->ln_name);
745
746         if (rc != 0) {
747                 struct lfsck_namespace *ns = com->lc_file_ram;
748
749                 ns->ln_flags |= LF_INCONSISTENT;
750         }
751
752         return rc;
753 }
754
755 /**
756  * Conditionally remove the specified entry from the linkEA.
757  *
758  * Take the parent lock firstly, then check whether the specified
759  * name entry exists or not: if yes, do nothing; otherwise, call
760  * lfsck_namespace_shrink_linkea() to remove the linkea entry.
761  *
762  * \param[in] env       pointer to the thread context
763  * \param[in] com       pointer to the lfsck component
764  * \param[in] parent    pointer to the parent directory
765  * \param[in] child     pointer to the child object that holds the linkEA
766  * \param[in,out]ldata  pointer to the buffer that holds the linkEA
767  * \param[in] cname     the name for the child in the parent directory
768  * \param[in] pfid      the parent directory's FID for the linkEA
769  *
770  * \retval              positive number for repaired cases
771  * \retval              0 if nothing to be repaired
772  * \retval              negative error number on failure
773  */
774 static int lfsck_namespace_shrink_linkea_cond(const struct lu_env *env,
775                                               struct lfsck_component *com,
776                                               struct dt_object *parent,
777                                               struct dt_object *child,
778                                               struct linkea_data *ldata,
779                                               struct lu_name *cname,
780                                               struct lu_fid *pfid)
781 {
782         struct lu_fid           *cfid   = &lfsck_env_info(env)->lti_fid3;
783         struct lustre_handle     lh     = { 0 };
784         int                      rc;
785         ENTRY;
786
787         rc = lfsck_ibits_lock(env, com->lc_lfsck, parent, &lh,
788                               MDS_INODELOCK_UPDATE, LCK_EX);
789         if (rc != 0)
790                 RETURN(rc);
791
792         dt_read_lock(env, parent, 0);
793         if (unlikely(lfsck_is_dead_obj(parent))) {
794                 dt_read_unlock(env, parent);
795                 lfsck_ibits_unlock(&lh, LCK_EX);
796                 rc = lfsck_namespace_shrink_linkea(env, com, child, ldata,
797                                                    cname, pfid, true);
798
799                 RETURN(rc);
800         }
801
802         rc = dt_lookup(env, parent, (struct dt_rec *)cfid,
803                        (const struct dt_key *)cname->ln_name,
804                        BYPASS_CAPA);
805         dt_read_unlock(env, parent);
806
807         /* It is safe to release the ldlm lock, because when the logic come
808          * here, we have got all the needed information above whether the
809          * linkEA entry is valid or not. It is not important that others
810          * may add new linkEA entry after the ldlm lock released. If other
811          * has removed the specified linkEA entry by race, then it is OK,
812          * because the subsequent lfsck_namespace_shrink_linkea() can handle
813          * such case. */
814         lfsck_ibits_unlock(&lh, LCK_EX);
815         if (rc == -ENOENT) {
816                 rc = lfsck_namespace_shrink_linkea(env, com, child, ldata,
817                                                    cname, pfid, true);
818
819                 RETURN(rc);
820         }
821
822         if (rc != 0)
823                 RETURN(rc);
824
825         /* The LFSCK just found some internal status of cross-MDTs
826          * create operation. That is normal. */
827         if (lu_fid_eq(cfid, lfsck_dto2fid(child))) {
828                 linkea_next_entry(ldata);
829
830                 RETURN(0);
831         }
832
833         rc = lfsck_namespace_shrink_linkea(env, com, child, ldata, cname,
834                                            pfid, true);
835
836         RETURN(rc);
837 }
838
839 /**
840  * Conditionally replace name entry in the parent.
841  *
842  * As required, the LFSCK may re-create the lost MDT-object for dangling
843  * name entry, but such repairing may be wrong because of bad FID in the
844  * name entry. As the LFSCK processing, the real MDT-object may be found,
845  * then the LFSCK should check whether the former re-created MDT-object
846  * has been modified or not, if not, then destroy it and update the name
847  * entry in the parent to reference the real MDT-object.
848  *
849  * \param[in] env       pointer to the thread context
850  * \param[in] com       pointer to the lfsck component
851  * \param[in] parent    pointer to the parent directory
852  * \param[in] child     pointer to the MDT-object that may be the real
853  *                      MDT-object corresponding to the name entry in parent
854  * \param[in] cfid      the current FID in the name entry
855  * \param[in] cname     contains the name of the child in the parent directory
856  *
857  * \retval              positive number for repaired cases
858  * \retval              0 if nothing to be repaired
859  * \retval              negative error number on failure
860  */
861 static int lfsck_namespace_replace_cond(const struct lu_env *env,
862                                         struct lfsck_component *com,
863                                         struct dt_object *parent,
864                                         struct dt_object *child,
865                                         const struct lu_fid *cfid,
866                                         const struct lu_name *cname)
867 {
868         struct lfsck_thread_info        *info   = lfsck_env_info(env);
869         struct lu_fid                   *tfid   = &info->lti_fid4;
870         struct lu_attr                  *la     = &info->lti_la;
871         struct dt_insert_rec            *rec    = &info->lti_dt_rec;
872         struct lfsck_instance           *lfsck  = com->lc_lfsck;
873         struct dt_device                *dev    = lfsck->li_next;
874         const char                      *name   = cname->ln_name;
875         struct dt_object                *obj    = NULL;
876         struct lustre_handle             plh    = { 0 };
877         struct lustre_handle             clh    = { 0 };
878         struct linkea_data               ldata  = { 0 };
879         struct thandle                  *th     = NULL;
880         bool                             exist  = true;
881         int                              rc     = 0;
882         ENTRY;
883
884         rc = lfsck_ibits_lock(env, lfsck, parent, &plh,
885                               MDS_INODELOCK_UPDATE, LCK_EX);
886         if (rc != 0)
887                 GOTO(log, rc);
888
889         if (!fid_is_sane(cfid)) {
890                 exist = false;
891                 goto replace;
892         }
893
894         obj = lfsck_object_find(env, lfsck, cfid);
895         if (IS_ERR(obj)) {
896                 rc = PTR_ERR(obj);
897                 if (rc == -ENOENT) {
898                         exist = false;
899                         goto replace;
900                 }
901
902                 GOTO(log, rc);
903         }
904
905         if (!dt_object_exists(obj)) {
906                 exist = false;
907                 goto replace;
908         }
909
910         rc = dt_lookup(env, parent, (struct dt_rec *)tfid,
911                        (const struct dt_key *)name, BYPASS_CAPA);
912         if (rc == -ENOENT) {
913                 exist = false;
914                 goto replace;
915         }
916
917         if (rc != 0)
918                 GOTO(log, rc);
919
920         /* Someone changed the name entry, cannot replace it. */
921         if (!lu_fid_eq(cfid, tfid))
922                 GOTO(log, rc = 0);
923
924         /* lock the object to be destroyed. */
925         rc = lfsck_ibits_lock(env, lfsck, obj, &clh,
926                               MDS_INODELOCK_UPDATE |
927                               MDS_INODELOCK_XATTR, LCK_EX);
928         if (rc != 0)
929                 GOTO(log, rc);
930
931         if (unlikely(lfsck_is_dead_obj(obj))) {
932                 exist = false;
933                 goto replace;
934         }
935
936         rc = dt_attr_get(env, obj, la, BYPASS_CAPA);
937         if (rc != 0)
938                 GOTO(log, rc);
939
940         /* The object has been modified by other(s), or it is not created by
941          * LFSCK, the two cases are indistinguishable. So cannot replace it. */
942         if (la->la_ctime != 0)
943                 GOTO(log, rc);
944
945         if (S_ISREG(la->la_mode)) {
946                 rc = dt_xattr_get(env, obj, &LU_BUF_NULL, XATTR_NAME_LOV,
947                                   BYPASS_CAPA);
948                 /* If someone has created related OST-object(s),
949                  * then keep it. */
950                 if ((rc > 0) || (rc < 0 && rc != -ENODATA))
951                         GOTO(log, rc = (rc > 0 ? 0 : rc));
952         }
953
954 replace:
955         dt_read_lock(env, child, 0);
956         rc = lfsck_links_read2(env, child, &ldata);
957         dt_read_unlock(env, child);
958
959         /* Someone changed the child, no need to replace. */
960         if (rc == -ENODATA)
961                 GOTO(log, rc = 0);
962
963         if (rc != 0)
964                 GOTO(log, rc);
965
966         rc = linkea_links_find(&ldata, cname, lfsck_dto2fid(parent));
967         /* Someone moved the child, no need to replace. */
968         if (rc != 0)
969                 GOTO(log, rc = 0);
970
971         if (lfsck->li_bookmark_ram.lb_param & LPF_DRYRUN)
972                 GOTO(log, rc = 1);
973
974         th = dt_trans_create(env, dev);
975         if (IS_ERR(th))
976                 GOTO(log, rc = PTR_ERR(th));
977
978         if (exist) {
979                 rc = dt_declare_destroy(env, obj, th);
980                 if (rc != 0)
981                         GOTO(stop, rc);
982         }
983
984         rc = dt_declare_delete(env, parent, (const struct dt_key *)name, th);
985         if (rc != 0)
986                 GOTO(stop, rc);
987
988         rec->rec_type = S_IFDIR;
989         rec->rec_fid = lfsck_dto2fid(child);
990         rc = dt_declare_insert(env, parent, (const struct dt_rec *)rec,
991                                (const struct dt_key *)name, th);
992         if (rc != 0)
993                 GOTO(stop, rc);
994
995         rc = dt_trans_start(env, dev, th);
996         if (rc != 0)
997                 GOTO(stop, rc);
998
999         if (exist) {
1000                 rc = dt_destroy(env, obj, th);
1001                 if (rc != 0)
1002                         GOTO(stop, rc);
1003         }
1004
1005         /* The old name entry maybe not exist. */
1006         dt_delete(env, parent, (const struct dt_key *)name, th,
1007                   BYPASS_CAPA);
1008
1009         rc = dt_insert(env, parent, (const struct dt_rec *)rec,
1010                        (const struct dt_key *)name, th, BYPASS_CAPA, 1);
1011
1012         GOTO(stop, rc = (rc == 0 ? 1 : rc));
1013
1014 stop:
1015         dt_trans_stop(env, dev, th);
1016
1017 log:
1018         lfsck_ibits_unlock(&clh, LCK_EX);
1019         lfsck_ibits_unlock(&plh, LCK_EX);
1020         if (obj != NULL && !IS_ERR(obj))
1021                 lfsck_object_put(env, obj);
1022
1023         CDEBUG(D_LFSCK, "%s: namespace LFSCK conditionally destroy the "
1024                "object "DFID" because of conflict with the object "DFID
1025                " under the parent "DFID" with name %s: rc = %d\n",
1026                lfsck_lfsck2name(lfsck), PFID(cfid),
1027                PFID(lfsck_dto2fid(child)), PFID(lfsck_dto2fid(parent)),
1028                name, rc);
1029
1030         return rc;
1031 }
1032
1033 /**
1034  * Overwrite the linkEA for the object with the given ldata.
1035  *
1036  * The caller should take the ldlm lock before the calling.
1037  *
1038  * \param[in] env       pointer to the thread context
1039  * \param[in] com       pointer to the lfsck component
1040  * \param[in] obj       pointer to the dt_object to be handled
1041  * \param[in] ldata     pointer to the new linkEA data
1042  *
1043  * \retval              positive number for repaired cases
1044  * \retval              0 if nothing to be repaired
1045  * \retval              negative error number on failure
1046  */
1047 int lfsck_namespace_rebuild_linkea(const struct lu_env *env,
1048                                    struct lfsck_component *com,
1049                                    struct dt_object *obj,
1050                                    struct linkea_data *ldata)
1051 {
1052         struct lfsck_instance           *lfsck  = com->lc_lfsck;
1053         struct dt_device                *dev    = lfsck->li_bottom;
1054         struct thandle                  *th     = NULL;
1055         struct lu_buf                    linkea_buf;
1056         int                              rc     = 0;
1057         ENTRY;
1058
1059         LASSERT(!dt_object_remote(obj));
1060
1061         th = dt_trans_create(env, dev);
1062         if (IS_ERR(th))
1063                 GOTO(log, rc = PTR_ERR(th));
1064
1065         lfsck_buf_init(&linkea_buf, ldata->ld_buf->lb_buf,
1066                        ldata->ld_leh->leh_len);
1067         rc = dt_declare_xattr_set(env, obj, &linkea_buf,
1068                                   XATTR_NAME_LINK, 0, th);
1069         if (rc != 0)
1070                 GOTO(stop, rc);
1071
1072         rc = dt_trans_start_local(env, dev, th);
1073         if (rc != 0)
1074                 GOTO(stop, rc);
1075
1076         dt_write_lock(env, obj, 0);
1077         if (unlikely(lfsck_is_dead_obj(obj)))
1078                 GOTO(unlock, rc = 0);
1079
1080         if (lfsck->li_bookmark_ram.lb_param & LPF_DRYRUN)
1081                 GOTO(unlock, rc = 1);
1082
1083         rc = dt_xattr_set(env, obj, &linkea_buf,
1084                           XATTR_NAME_LINK, 0, th, BYPASS_CAPA);
1085
1086         GOTO(unlock, rc = (rc == 0 ? 1 : rc));
1087
1088 unlock:
1089         dt_write_unlock(env, obj);
1090
1091 stop:
1092         dt_trans_stop(env, dev, th);
1093
1094 log:
1095         CDEBUG(D_LFSCK, "%s: namespace LFSCK rebuild linkEA for the "
1096                "object "DFID": rc = %d\n",
1097                lfsck_lfsck2name(lfsck), PFID(lfsck_dto2fid(obj)), rc);
1098
1099         if (rc != 0) {
1100                 struct lfsck_namespace *ns = com->lc_file_ram;
1101
1102                 ns->ln_flags |= LF_INCONSISTENT;
1103         }
1104
1105         return rc;
1106 }
1107
1108 /**
1109  * Update the ".." name entry for the given object.
1110  *
1111  * The object's ".." is corrupted, this function will update the ".." name
1112  * entry with the given pfid, and the linkEA with the given ldata.
1113  *
1114  * The caller should take the ldlm lock before the calling.
1115  *
1116  * \param[in] env       pointer to the thread context
1117  * \param[in] com       pointer to the lfsck component
1118  * \param[in] obj       pointer to the dt_object to be handled
1119  * \param[in] pfid      the new fid for the object's ".." name entry
1120  * \param[in] cname     the name for the @obj in the parent directory
1121  *
1122  * \retval              positive number for repaired cases
1123  * \retval              0 if nothing to be repaired
1124  * \retval              negative error number on failure
1125  */
1126 static int lfsck_namespace_repair_unmatched_pairs(const struct lu_env *env,
1127                                                   struct lfsck_component *com,
1128                                                   struct dt_object *obj,
1129                                                   const struct lu_fid *pfid,
1130                                                   struct lu_name *cname)
1131 {
1132         struct lfsck_thread_info        *info   = lfsck_env_info(env);
1133         struct dt_insert_rec            *rec    = &info->lti_dt_rec;
1134         struct lfsck_instance           *lfsck  = com->lc_lfsck;
1135         struct dt_device                *dev    = lfsck->li_bottom;
1136         struct thandle                  *th     = NULL;
1137         struct linkea_data               ldata  = { 0 };
1138         struct lu_buf                    linkea_buf;
1139         int                              rc     = 0;
1140         ENTRY;
1141
1142         LASSERT(!dt_object_remote(obj));
1143         LASSERT(S_ISDIR(lfsck_object_type(obj)));
1144
1145         rc = linkea_data_new(&ldata, &info->lti_big_buf);
1146         if (rc != 0)
1147                 GOTO(log, rc);
1148
1149         rc = linkea_add_buf(&ldata, cname, pfid);
1150         if (rc != 0)
1151                 GOTO(log, rc);
1152
1153         lfsck_buf_init(&linkea_buf, ldata.ld_buf->lb_buf,
1154                        ldata.ld_leh->leh_len);
1155
1156         th = dt_trans_create(env, dev);
1157         if (IS_ERR(th))
1158                 GOTO(log, rc = PTR_ERR(th));
1159
1160         rc = dt_declare_delete(env, obj, (const struct dt_key *)dotdot, th);
1161         if (rc != 0)
1162                 GOTO(stop, rc);
1163
1164         rec->rec_type = S_IFDIR;
1165         rec->rec_fid = pfid;
1166         rc = dt_declare_insert(env, obj, (const struct dt_rec *)rec,
1167                                (const struct dt_key *)dotdot, th);
1168         if (rc != 0)
1169                 GOTO(stop, rc);
1170
1171         rc = dt_declare_xattr_set(env, obj, &linkea_buf,
1172                                   XATTR_NAME_LINK, 0, th);
1173         if (rc != 0)
1174                 GOTO(stop, rc);
1175
1176         rc = dt_trans_start_local(env, dev, th);
1177         if (rc != 0)
1178                 GOTO(stop, rc);
1179
1180         dt_write_lock(env, obj, 0);
1181         if (unlikely(lfsck_is_dead_obj(obj)))
1182                 GOTO(unlock, rc = 0);
1183
1184         if (lfsck->li_bookmark_ram.lb_param & LPF_DRYRUN)
1185                 GOTO(unlock, rc = 1);
1186
1187         /* The old ".." name entry maybe not exist. */
1188         dt_delete(env, obj, (const struct dt_key *)dotdot, th,
1189                   BYPASS_CAPA);
1190
1191         rc = dt_insert(env, obj, (const struct dt_rec *)rec,
1192                        (const struct dt_key *)dotdot, th, BYPASS_CAPA, 1);
1193         if (rc != 0)
1194                 GOTO(unlock, rc);
1195
1196         rc = dt_xattr_set(env, obj, &linkea_buf,
1197                           XATTR_NAME_LINK, 0, th, BYPASS_CAPA);
1198
1199         GOTO(unlock, rc = (rc == 0 ? 1 : rc));
1200
1201 unlock:
1202         dt_write_unlock(env, obj);
1203
1204 stop:
1205         dt_trans_stop(env, dev, th);
1206
1207 log:
1208         CDEBUG(D_LFSCK, "%s: namespace LFSCK rebuild dotdot name entry for "
1209                "the object "DFID", new parent "DFID": rc = %d\n",
1210                lfsck_lfsck2name(lfsck), PFID(lfsck_dto2fid(obj)),
1211                PFID(pfid), rc);
1212
1213         if (rc != 0) {
1214                 struct lfsck_namespace *ns = com->lc_file_ram;
1215
1216                 ns->ln_flags |= LF_INCONSISTENT;
1217         }
1218
1219         return rc;
1220 }
1221
1222 /**
1223  * Handle orphan @obj during Double Scan Directory.
1224  *
1225  * Remove the @obj's current (invalid) linkEA entries, and insert
1226  * it in the directory .lustre/lost+found/MDTxxxx/ with the name:
1227  * ${FID}-${PFID}-D-${conflict_version}
1228  *
1229  * The caller should take the ldlm lock before the calling.
1230  *
1231  * \param[in] env       pointer to the thread context
1232  * \param[in] com       pointer to the lfsck component
1233  * \param[in] obj       pointer to the orphan object to be handled
1234  * \param[in] pfid      the new fid for the object's ".." name entry
1235  * \param[in,out] lh    ldlm lock handler for the given @obj
1236  *
1237  * \retval              positive number for repaired cases
1238  * \retval              0 if nothing to be repaired
1239  * \retval              negative error number on failure
1240  */
1241 static int lfsck_namespace_dsd_orphan(const struct lu_env *env,
1242                                       struct lfsck_component *com,
1243                                       struct dt_object *obj,
1244                                       const struct lu_fid *pfid,
1245                                       struct lustre_handle *lh)
1246 {
1247         struct lfsck_thread_info *info = lfsck_env_info(env);
1248         int                       rc;
1249         ENTRY;
1250
1251         /* Remove the unrecognized linkEA. */
1252         rc = lfsck_namespace_links_remove(env, com, obj);
1253         lfsck_ibits_unlock(lh, LCK_EX);
1254         if (rc < 0 && rc != -ENODATA)
1255                 RETURN(rc);
1256
1257         /* The unique linkEA is invalid, even if the ".." name entry may be
1258          * valid, we still cannot know via which name entry this directory
1259          * will be referenced. Then handle it as pure orphan. */
1260         snprintf(info->lti_tmpbuf, sizeof(info->lti_tmpbuf),
1261                  "-"DFID, PFID(pfid));
1262         rc = lfsck_namespace_insert_orphan(env, com, obj,
1263                                            info->lti_tmpbuf, "D", NULL);
1264
1265         RETURN(rc);
1266 }
1267
1268 /**
1269  * Double Scan Directory object for single linkEA entry case.
1270  *
1271  * The given @child has unique linkEA entry. If the linkEA entry is valid,
1272  * then check whether the name is in the namespace or not, if not, add the
1273  * missing name entry back to namespace. If the linkEA entry is invalid,
1274  * then remove it and insert the @child in the .lustre/lost+found/MDTxxxx/
1275  * as an orphan.
1276  *
1277  * \param[in] env       pointer to the thread context
1278  * \param[in] com       pointer to the lfsck component
1279  * \param[in] child     pointer to the directory to be double scanned
1280  * \param[in] pfid      the FID corresponding to the ".." entry
1281  * \param[in] ldata     pointer to the linkEA data for the given @child
1282  * \param[in,out] lh    ldlm lock handler for the given @child
1283  * \param[out] type     to tell the caller what the inconsistency is
1284  * \param[in] retry     if found inconsistency, but the caller does not hold
1285  *                      ldlm lock on the @child, then set @retry as true
1286  *
1287  * \retval              positive number for repaired cases
1288  * \retval              0 if nothing to be repaired
1289  * \retval              negative error number on failure
1290  */
1291 static int
1292 lfsck_namespace_dsd_single(const struct lu_env *env,
1293                            struct lfsck_component *com,
1294                            struct dt_object *child,
1295                            const struct lu_fid *pfid,
1296                            struct linkea_data *ldata,
1297                            struct lustre_handle *lh,
1298                            enum lfsck_namespace_inconsistency_type *type,
1299                            bool *retry)
1300 {
1301         struct lfsck_thread_info *info          = lfsck_env_info(env);
1302         struct lu_name           *cname         = &info->lti_name;
1303         const struct lu_fid      *cfid          = lfsck_dto2fid(child);
1304         struct lu_fid            *tfid          = &info->lti_fid3;
1305         struct lfsck_instance    *lfsck         = com->lc_lfsck;
1306         struct dt_object         *parent        = NULL;
1307         int                       rc            = 0;
1308         ENTRY;
1309
1310         lfsck_namespace_unpack_linkea_entry(ldata, cname, tfid, info->lti_key);
1311         /* The unique linkEA entry with bad parent will be handled as orphan. */
1312         if (!fid_is_sane(tfid)) {
1313                 if (!lustre_handle_is_used(lh) && retry != NULL)
1314                         *retry = true;
1315                 else
1316                         rc = lfsck_namespace_dsd_orphan(env, com, child,
1317                                                         pfid, lh);
1318
1319                 GOTO(out, rc);
1320         }
1321
1322         parent = lfsck_object_find_bottom(env, lfsck, tfid);
1323         if (IS_ERR(parent))
1324                 GOTO(out, rc = PTR_ERR(parent));
1325
1326         /* We trust the unique linkEA entry in spite of whether it matches the
1327          * ".." name entry or not. Because even if the linkEA entry is wrong
1328          * and the ".." name entry is right, we still cannot know via which
1329          * name entry the child will be referenced, since all known entries
1330          * have been verified during the first-stage scanning. */
1331         if (!dt_object_exists(parent)) {
1332                 if (!lustre_handle_is_used(lh) && retry != NULL) {
1333                         *retry = true;
1334
1335                         GOTO(out, rc = 0);
1336                 }
1337
1338                 lfsck_ibits_unlock(lh, LCK_EX);
1339                 /* Create the lost parent as an orphan. */
1340                 rc = lfsck_namespace_create_orphan(env, com, parent);
1341                 if (rc >= 0)
1342                         /* Add the missing name entry to the parent. */
1343                         rc = lfsck_namespace_insert_normal(env, com, parent,
1344                                                         child, cname->ln_name);
1345
1346                 GOTO(out, rc);
1347         }
1348
1349         /* The unique linkEA entry with bad parent will be handled as orphan. */
1350         if (unlikely(!dt_try_as_dir(env, parent))) {
1351                 if (!lustre_handle_is_used(lh) && retry != NULL)
1352                         *retry = true;
1353                 else
1354                         rc = lfsck_namespace_dsd_orphan(env, com, child,
1355                                                         pfid, lh);
1356
1357                 GOTO(out, rc);
1358         }
1359
1360         rc = dt_lookup(env, parent, (struct dt_rec *)tfid,
1361                        (const struct dt_key *)cname->ln_name, BYPASS_CAPA);
1362         if (rc == -ENOENT) {
1363                 if (!lustre_handle_is_used(lh) && retry != NULL) {
1364                         *retry = true;
1365
1366                         GOTO(out, rc = 0);
1367                 }
1368
1369                 lfsck_ibits_unlock(lh, LCK_EX);
1370                 /* Add the missing name entry back to the namespace. */
1371                 rc = lfsck_namespace_insert_normal(env, com, parent, child,
1372                                                    cname->ln_name);
1373
1374                 GOTO(out, rc);
1375         }
1376
1377         if (rc != 0)
1378                 GOTO(out, rc);
1379
1380         if (!lu_fid_eq(tfid, cfid)) {
1381                 if (!lustre_handle_is_used(lh) && retry != NULL) {
1382                         *retry = true;
1383
1384                         GOTO(out, rc = 0);
1385                 }
1386
1387                 lfsck_ibits_unlock(lh, LCK_EX);
1388                 /* The name entry references another MDT-object that
1389                  * may be created by the LFSCK for repairing dangling
1390                  * name entry. Try to replace it. */
1391                 rc = lfsck_namespace_replace_cond(env, com, parent, child,
1392                                                   tfid, cname);
1393                 if (rc == 0)
1394                         rc = lfsck_namespace_dsd_orphan(env, com, child,
1395                                                         pfid, lh);
1396
1397                 GOTO(out, rc);
1398         }
1399
1400         /* The ".." name entry is wrong, update it. */
1401         if (!lu_fid_eq(pfid, lfsck_dto2fid(parent))) {
1402                 if (!lustre_handle_is_used(lh) && retry != NULL) {
1403                         *retry = true;
1404
1405                         GOTO(out, rc = 0);
1406                 }
1407
1408                 *type = LNIT_UNMATCHED_PAIRS;
1409                 rc = lfsck_namespace_repair_unmatched_pairs(env, com, child,
1410                                                 lfsck_dto2fid(parent), cname);
1411         }
1412
1413         GOTO(out, rc);
1414
1415 out:
1416         if (parent != NULL && !IS_ERR(parent))
1417                 lfsck_object_put(env, parent);
1418
1419         return rc;
1420 }
1421
1422 /**
1423  * Double Scan Directory object for multiple linkEA entries case.
1424  *
1425  * The given @child has multiple linkEA entries. There is at most one linkEA
1426  * entry will be valid, all the others will be removed. Firstly, the function
1427  * will try to find out the linkEA entry for which the name entry exists under
1428  * the given parent (@pfid). If there is no linkEA entry that matches the given
1429  * ".." name entry, then tries to find out the first linkEA entry that both the
1430  * parent and the name entry exist to rebuild a new ".." name entry.
1431  *
1432  * \param[in] env       pointer to the thread context
1433  * \param[in] com       pointer to the lfsck component
1434  * \param[in] child     pointer to the directory to be double scanned
1435  * \param[in] pfid      the FID corresponding to the ".." entry
1436  * \param[in] ldata     pointer to the linkEA data for the given @child
1437  * \param[in,out] lh    ldlm lock handler for the given @child
1438  * \param[out] type     to tell the caller what the inconsistency is
1439  * \param[in] lpf       true if the ".." entry is under lost+found/MDTxxxx/
1440  *
1441  * \retval              positive number for repaired cases
1442  * \retval              0 if nothing to be repaired
1443  * \retval              negative error number on failure
1444  */
1445 static int
1446 lfsck_namespace_dsd_multiple(const struct lu_env *env,
1447                              struct lfsck_component *com,
1448                              struct dt_object *child,
1449                              const struct lu_fid *pfid,
1450                              struct linkea_data *ldata,
1451                              struct lustre_handle *lh,
1452                              enum lfsck_namespace_inconsistency_type *type,
1453                              bool lpf)
1454 {
1455         struct lfsck_thread_info *info          = lfsck_env_info(env);
1456         struct lu_name           *cname         = &info->lti_name;
1457         const struct lu_fid      *cfid          = lfsck_dto2fid(child);
1458         struct lu_fid            *tfid          = &info->lti_fid3;
1459         struct lu_fid            *pfid2         = &info->lti_fid4;
1460         struct lfsck_instance    *lfsck         = com->lc_lfsck;
1461         struct dt_object         *parent        = NULL;
1462         struct linkea_data        ldata_new     = { 0 };
1463         int                       rc            = 0;
1464         bool                      once          = true;
1465         ENTRY;
1466
1467 again:
1468         while (ldata->ld_lee != NULL) {
1469                 lfsck_namespace_unpack_linkea_entry(ldata, cname, tfid,
1470                                                     info->lti_key);
1471                 /* Drop repeated linkEA entries. */
1472                 lfsck_namespace_filter_linkea_entry(ldata, cname, tfid, true);
1473                 /* Drop invalid linkEA entry. */
1474                 if (!fid_is_sane(tfid)) {
1475                         linkea_del_buf(ldata, cname);
1476                         continue;
1477                 }
1478
1479                 /* If current dotdot is the .lustre/lost+found/MDTxxxx/,
1480                  * then it is possible that: the directry object has ever
1481                  * been lost, but its name entry was there. In the former
1482                  * LFSCK run, during the first-stage scanning, the LFSCK
1483                  * found the dangling name entry, but it did not recreate
1484                  * the lost object, and when moved to the second-stage
1485                  * scanning, some children objects of the lost directory
1486                  * object were found, then the LFSCK recreated such lost
1487                  * directory object as an orphan.
1488                  *
1489                  * When the LFSCK runs again, if the dangling name is still
1490                  * there, the LFSCK should move the orphan directory object
1491                  * back to the normal namespace. */
1492                 if (!lpf && !lu_fid_eq(pfid, tfid) && once) {
1493                         linkea_next_entry(ldata);
1494                         continue;
1495                 }
1496
1497                 parent = lfsck_object_find_bottom(env, lfsck, tfid);
1498                 if (IS_ERR(parent))
1499                         RETURN(PTR_ERR(parent));
1500
1501                 if (!dt_object_exists(parent)) {
1502                         lfsck_object_put(env, parent);
1503                         if (ldata->ld_leh->leh_reccount > 1) {
1504                                 /* If it is NOT the last linkEA entry, then
1505                                  * there is still other chance to make the
1506                                  * child to be visible via other parent, then
1507                                  * remove this linkEA entry. */
1508                                 linkea_del_buf(ldata, cname);
1509                                 continue;
1510                         }
1511
1512                         break;
1513                 }
1514
1515                 /* The linkEA entry with bad parent will be removed. */
1516                 if (unlikely(!dt_try_as_dir(env, parent))) {
1517                         lfsck_object_put(env, parent);
1518                         linkea_del_buf(ldata, cname);
1519                         continue;
1520                 }
1521
1522                 rc = dt_lookup(env, parent, (struct dt_rec *)tfid,
1523                                (const struct dt_key *)cname->ln_name,
1524                                BYPASS_CAPA);
1525                 *pfid2 = *lfsck_dto2fid(parent);
1526                 if (rc == -ENOENT) {
1527                         lfsck_object_put(env, parent);
1528                         linkea_next_entry(ldata);
1529                         continue;
1530                 }
1531
1532                 if (rc != 0) {
1533                         lfsck_object_put(env, parent);
1534
1535                         RETURN(rc);
1536                 }
1537
1538                 if (lu_fid_eq(tfid, cfid)) {
1539                         lfsck_object_put(env, parent);
1540                         if (!lu_fid_eq(pfid, pfid2)) {
1541                                 *type = LNIT_UNMATCHED_PAIRS;
1542                                 rc = lfsck_namespace_repair_unmatched_pairs(env,
1543                                                 com, child, pfid2, cname);
1544
1545                                 RETURN(rc);
1546                         }
1547
1548 rebuild:
1549                         /* It is the most common case that we find the
1550                          * name entry corresponding to the linkEA entry
1551                          * that matches the ".." name entry. */
1552                         rc = linkea_data_new(&ldata_new, &info->lti_big_buf);
1553                         if (rc != 0)
1554                                 RETURN(rc);
1555
1556                         rc = linkea_add_buf(&ldata_new, cname, pfid2);
1557                         if (rc != 0)
1558                                 RETURN(rc);
1559
1560                         rc = lfsck_namespace_rebuild_linkea(env, com, child,
1561                                                             &ldata_new);
1562
1563                         /* XXX: there will be other patch. */
1564
1565                         RETURN(rc);
1566                 }
1567
1568                 lfsck_ibits_unlock(lh, LCK_EX);
1569                 /* The name entry references another MDT-object that may be
1570                  * created by the LFSCK for repairing dangling name entry.
1571                  * Try to replace it. */
1572                 rc = lfsck_namespace_replace_cond(env, com, parent, child,
1573                                                   tfid, cname);
1574                 lfsck_object_put(env, parent);
1575                 if (rc < 0)
1576                         RETURN(rc);
1577
1578                 if (rc > 0)
1579                         goto rebuild;
1580
1581                 linkea_del_buf(ldata, cname);
1582         }
1583
1584         if (ldata->ld_leh->leh_reccount == 1) {
1585                 rc = lfsck_namespace_dsd_single(env, com, child, pfid, ldata,
1586                                                 lh, type, NULL);
1587
1588                 RETURN(rc);
1589         }
1590
1591         /* All linkEA entries are invalid and removed, then handle the @child
1592          * as an orphan.*/
1593         if (ldata->ld_leh->leh_reccount == 0) {
1594                 rc = lfsck_namespace_dsd_orphan(env, com, child, pfid, lh);
1595
1596                 RETURN(rc);
1597         }
1598
1599         linkea_first_entry(ldata);
1600         /* If the dangling name entry for the orphan directory object has
1601          * been remvoed, then just check whether the directory object is
1602          * still under the .lustre/lost+found/MDTxxxx/ or not. */
1603         if (lpf) {
1604                 lpf = false;
1605                 goto again;
1606         }
1607
1608         /* There is no linkEA entry that matches the ".." name entry. Find
1609          * the first linkEA entry that both parent and name entry exist to
1610          * rebuild a new ".." name entry. */
1611         if (once) {
1612                 once = false;
1613                 goto again;
1614         }
1615
1616         RETURN(rc);
1617 }
1618
1619 /**
1620  * Double scan the directory object for namespace LFSCK.
1621  *
1622  * This function will verify the <parent, child> pairs in the namespace tree:
1623  * the parent references the child via some name entry that should be in the
1624  * child's linkEA entry, the child should back references the parent via its
1625  * ".." name entry.
1626  *
1627  * The LFSCK will scan every linkEA entry in turn until find out the first
1628  * matched pairs. If found, then all other linkEA entries will be dropped.
1629  * If all the linkEA entries cannot match the ".." name entry, then there
1630  * are serveral possible cases:
1631  *
1632  * 1) If there is only one linkEA entry, then trust it as long as the PFID
1633  *    in the linkEA entry is valid.
1634  *
1635  * 2) If there are multiple linkEA entries, then try to find the linkEA
1636  *    that matches the ".." name entry. If found, then all other entries
1637  *    are invalid; otherwise, it is quite possible that the ".." name entry
1638  *    is corrupted. Under such case, the LFSCK will rebuild the ".." name
1639  *    entry according to the first valid linkEA entry (both the parent and
1640  *    the name entry should exist).
1641  *
1642  * 3) If the directory object has no (valid) linkEA entry, then the
1643  *    directory object will be handled as pure orphan and inserted
1644  *    in the .lustre/lost+found/MDTxxxx/ with the name:
1645  *    ${self_FID}-${PFID}-D-${conflict_version}
1646  *
1647  * \param[in] env       pointer to the thread context
1648  * \param[in] com       pointer to the lfsck component
1649  * \param[in] child     pointer to the directory object to be handled
1650  * \param[in] flags     to indicate the specical checking on the @child
1651  *
1652  * \retval              positive number for repaired cases
1653  * \retval              0 if nothing to be repaired
1654  * \retval              negative error number on failure
1655  */
1656 static int lfsck_namespace_double_scan_dir(const struct lu_env *env,
1657                                            struct lfsck_component *com,
1658                                            struct dt_object *child, __u8 flags)
1659 {
1660         struct lfsck_thread_info *info          = lfsck_env_info(env);
1661         const struct lu_fid      *cfid          = lfsck_dto2fid(child);
1662         struct lu_fid            *pfid          = &info->lti_fid2;
1663         struct lfsck_namespace   *ns            = com->lc_file_ram;
1664         struct lfsck_instance    *lfsck         = com->lc_lfsck;
1665         struct lustre_handle      lh            = { 0 };
1666         struct linkea_data        ldata         = { 0 };
1667         bool                      unknown       = false;
1668         bool                      lpf           = false;
1669         bool                      retry         = false;
1670         enum lfsck_namespace_inconsistency_type type = LNIT_BAD_LINKEA;
1671         int                       rc            = 0;
1672         ENTRY;
1673
1674         LASSERT(!dt_object_remote(child));
1675
1676         if (!(lfsck->li_bookmark_ram.lb_param & LPF_ALL_TGT)) {
1677                 CDEBUG(D_LFSCK, "%s: some MDT(s) maybe NOT take part in the"
1678                        "the namespace LFSCK, then the LFSCK cannot guarantee"
1679                        "all the name entries have been verified in first-stage"
1680                        "scanning. So have to skip orphan related handling for"
1681                        "the directory object "DFID" with remote name entry\n",
1682                        lfsck_lfsck2name(lfsck), PFID(cfid));
1683
1684                 RETURN(0);
1685         }
1686
1687         if (unlikely(!dt_try_as_dir(env, child)))
1688                 GOTO(out, rc = -ENOTDIR);
1689
1690         /* We only take ldlm lock on the @child when required. When the
1691          * logic comes here for the first time, it is always false. */
1692         if (0) {
1693
1694 lock:
1695                 rc = lfsck_ibits_lock(env, lfsck, child, &lh,
1696                                       MDS_INODELOCK_UPDATE |
1697                                       MDS_INODELOCK_XATTR, LCK_EX);
1698                 if (rc != 0)
1699                         GOTO(out, rc);
1700         }
1701
1702         dt_read_lock(env, child, 0);
1703         if (unlikely(lfsck_is_dead_obj(child))) {
1704                 dt_read_unlock(env, child);
1705
1706                 GOTO(out, rc = 0);
1707         }
1708
1709         rc = dt_lookup(env, child, (struct dt_rec *)pfid,
1710                        (const struct dt_key *)dotdot, BYPASS_CAPA);
1711         if (rc != 0) {
1712                 if (rc != -ENOENT && rc != -ENODATA && rc != -EINVAL) {
1713                         dt_read_unlock(env, child);
1714
1715                         GOTO(out, rc);
1716                 }
1717
1718                 if (!lustre_handle_is_used(&lh)) {
1719                         dt_read_unlock(env, child);
1720                         goto lock;
1721                 }
1722
1723                 fid_zero(pfid);
1724         } else if (lfsck->li_lpf_obj != NULL &&
1725                    lu_fid_eq(pfid, lfsck_dto2fid(lfsck->li_lpf_obj))) {
1726                 lpf = true;
1727         }
1728
1729         rc = lfsck_links_read(env, child, &ldata);
1730         dt_read_unlock(env, child);
1731         if (rc != 0) {
1732                 if (rc != -ENODATA && rc != -EINVAL)
1733                         GOTO(out, rc);
1734
1735                 if (!lustre_handle_is_used(&lh))
1736                         goto lock;
1737
1738                 if (rc == -EINVAL && !fid_is_zero(pfid)) {
1739                         /* Remove the corrupted linkEA. */
1740                         rc = lfsck_namespace_links_remove(env, com, child);
1741                         if (rc == 0)
1742                                 /* Here, because of the crashed linkEA, we
1743                                  * cannot know whether there is some parent
1744                                  * that references the child directory via
1745                                  * some name entry or not. So keep it there,
1746                                  * when the LFSCK run next time, if there is
1747                                  * some parent that references this object,
1748                                  * then the LFSCK can rebuild the linkEA;
1749                                  * otherwise, this object will be handled
1750                                  * as orphan as above. */
1751                                 unknown = true;
1752                 } else {
1753                         /* 1. If we have neither ".." nor linkEA,
1754                          *    then it is an orphan.
1755                          *
1756                          * 2. If we only have the ".." name entry,
1757                          *    but no parent references this child
1758                          *    directory, then handle it as orphan. */
1759                         lfsck_ibits_unlock(&lh, LCK_EX);
1760                         snprintf(info->lti_tmpbuf, sizeof(info->lti_tmpbuf),
1761                                  "-"DFID, PFID(pfid));
1762                         rc = lfsck_namespace_insert_orphan(env, com, child,
1763                                                 info->lti_tmpbuf, "D", NULL);
1764                 }
1765
1766                 GOTO(out, rc);
1767         }
1768
1769         linkea_first_entry(&ldata);
1770         /* This is the most common case: the object has unique linkEA entry. */
1771         if (ldata.ld_leh->leh_reccount == 1) {
1772                 rc = lfsck_namespace_dsd_single(env, com, child, pfid, &ldata,
1773                                                 &lh, &type, &retry);
1774                 if (retry) {
1775                         LASSERT(!lustre_handle_is_used(&lh));
1776
1777                         retry = false;
1778                         goto lock;
1779                 }
1780
1781                 GOTO(out, rc);
1782         }
1783
1784         if (!lustre_handle_is_used(&lh))
1785                 goto lock;
1786
1787         if (unlikely(ldata.ld_leh->leh_reccount == 0)) {
1788                 rc = lfsck_namespace_dsd_orphan(env, com, child, pfid, &lh);
1789
1790                 GOTO(out, rc);
1791         }
1792
1793         /* When we come here, the cases usually like that:
1794          * 1) The directory object has a corrupted linkEA entry. During the
1795          *    first-stage scanning, the LFSCK cannot know such corruption,
1796          *    then it appends the right linkEA entry according to the found
1797          *    name entry after the bad one.
1798          *
1799          * 2) The directory object has a right linkEA entry. During the
1800          *    first-stage scanning, the LFSCK finds some bad name entry,
1801          *    but the LFSCK cannot aware that at that time, then it adds
1802          *    the bad linkEA entry for further processing. */
1803         rc = lfsck_namespace_dsd_multiple(env, com, child, pfid, &ldata,
1804                                           &lh, &type, lpf);
1805
1806         GOTO(out, rc);
1807
1808 out:
1809         lfsck_ibits_unlock(&lh, LCK_EX);
1810         if (rc > 0) {
1811                 switch (type) {
1812                 case LNIT_BAD_LINKEA:
1813                         ns->ln_linkea_repaired++;
1814                         break;
1815                 case LNIT_UNMATCHED_PAIRS:
1816                         ns->ln_unmatched_pairs_repaired++;
1817                         break;
1818                 default:
1819                         break;
1820                 }
1821         }
1822
1823         if (unknown)
1824                 ns->ln_unknown_inconsistency++;
1825
1826         return rc;
1827 }
1828
1829 /**
1830  * Double scan the MDT-object for namespace LFSCK.
1831  *
1832  * If the MDT-object contains invalid or repeated linkEA entries, then drop
1833  * those entries from the linkEA; if the linkEA becomes empty or the object
1834  * has no linkEA, then it is an orphan and will be added into the directory
1835  * .lustre/lost+found/MDTxxxx/; if the remote parent is lost, then recreate
1836  * the remote parent; if the name entry corresponding to some linkEA entry
1837  * is lost, then add the name entry back to the namespace.
1838  *
1839  * \param[in] env       pointer to the thread context
1840  * \param[in] com       pointer to the lfsck component
1841  * \param[in] child     pointer to the dt_object to be handled
1842  * \param[in] flags     some hints to indicate how the @child should be handled
1843  *
1844  * \retval              positive number for repaired cases
1845  * \retval              0 if nothing to be repaired
1846  * \retval              negative error number on failure
1847  */
1848 static int lfsck_namespace_double_scan_one(const struct lu_env *env,
1849                                            struct lfsck_component *com,
1850                                            struct dt_object *child, __u8 flags)
1851 {
1852         struct lfsck_thread_info *info     = lfsck_env_info(env);
1853         struct lu_attr           *la       = &info->lti_la;
1854         struct lu_name           *cname    = &info->lti_name;
1855         struct lu_fid            *pfid     = &info->lti_fid;
1856         struct lu_fid            *cfid     = &info->lti_fid2;
1857         struct lfsck_instance    *lfsck    = com->lc_lfsck;
1858         struct lfsck_namespace   *ns       = com->lc_file_ram;
1859         struct dt_object         *parent   = NULL;
1860         struct linkea_data        ldata    = { 0 };
1861         bool                      repaired = false;
1862         int                       count    = 0;
1863         int                       rc;
1864         ENTRY;
1865
1866         dt_read_lock(env, child, 0);
1867         if (unlikely(lfsck_is_dead_obj(child))) {
1868                 dt_read_unlock(env, child);
1869
1870                 RETURN(0);
1871         }
1872
1873         if (S_ISDIR(lfsck_object_type(child))) {
1874                 dt_read_unlock(env, child);
1875                 rc = lfsck_namespace_double_scan_dir(env, com, child, flags);
1876
1877                 RETURN(rc);
1878         }
1879
1880         rc = lfsck_links_read(env, child, &ldata);
1881         dt_read_unlock(env, child);
1882         if (rc != 0)
1883                 GOTO(out, rc);
1884
1885         linkea_first_entry(&ldata);
1886         while (ldata.ld_lee != NULL) {
1887                 lfsck_namespace_unpack_linkea_entry(&ldata, cname, pfid,
1888                                                     info->lti_key);
1889                 rc = lfsck_namespace_filter_linkea_entry(&ldata, cname, pfid,
1890                                                          false);
1891                 /* Found repeated linkEA entries */
1892                 if (rc > 0) {
1893                         rc = lfsck_namespace_shrink_linkea(env, com, child,
1894                                                 &ldata, cname, pfid, false);
1895                         if (rc < 0)
1896                                 GOTO(out, rc);
1897
1898                         if (rc == 0)
1899                                 continue;
1900
1901                         repaired = true;
1902
1903                         /* fall through */
1904                 }
1905
1906                 /* Invalid PFID in the linkEA entry. */
1907                 if (!fid_is_sane(pfid)) {
1908                         rc = lfsck_namespace_shrink_linkea(env, com, child,
1909                                                 &ldata, cname, pfid, true);
1910                         if (rc < 0)
1911                                 GOTO(out, rc);
1912
1913                         if (rc > 0)
1914                                 repaired = true;
1915
1916                         continue;
1917                 }
1918
1919                 parent = lfsck_object_find_bottom(env, lfsck, pfid);
1920                 if (IS_ERR(parent))
1921                         GOTO(out, rc = PTR_ERR(parent));
1922
1923                 if (!dt_object_exists(parent)) {
1924                         if (ldata.ld_leh->leh_reccount > 1) {
1925                                 /* If it is NOT the last linkEA entry, then
1926                                  * there is still other chance to make the
1927                                  * child to be visible via other parent, then
1928                                  * remove this linkEA entry. */
1929                                 rc = lfsck_namespace_shrink_linkea(env, com,
1930                                         child, &ldata, cname, pfid, true);
1931                         } else {
1932                                 /* Create the lost parent as an orphan. */
1933                                 rc = lfsck_namespace_create_orphan(env, com,
1934                                                                    parent);
1935                                 if (rc < 0) {
1936                                         lfsck_object_put(env, parent);
1937
1938                                         GOTO(out, rc);
1939                                 }
1940
1941                                 if (rc > 0)
1942                                         repaired = true;
1943
1944                                 /* Add the missing name entry to the parent. */
1945                                 rc = lfsck_namespace_insert_normal(env, com,
1946                                                 parent, child, cname->ln_name);
1947                                 linkea_next_entry(&ldata);
1948                         }
1949
1950                         lfsck_object_put(env, parent);
1951                         if (rc < 0)
1952                                 GOTO(out, rc);
1953
1954                         if (rc > 0)
1955                                 repaired = true;
1956
1957                         continue;
1958                 }
1959
1960                 /* The linkEA entry with bad parent will be removed. */
1961                 if (unlikely(!dt_try_as_dir(env, parent))) {
1962                         lfsck_object_put(env, parent);
1963                         rc = lfsck_namespace_shrink_linkea(env, com, child,
1964                                                 &ldata, cname, pfid, true);
1965                         if (rc < 0)
1966                                 GOTO(out, rc);
1967
1968                         if (rc > 0)
1969                                 repaired = true;
1970
1971                         continue;
1972                 }
1973
1974                 rc = dt_lookup(env, parent, (struct dt_rec *)cfid,
1975                                (const struct dt_key *)cname->ln_name,
1976                                BYPASS_CAPA);
1977                 if (rc != 0 && rc != -ENOENT) {
1978                         lfsck_object_put(env, parent);
1979
1980                         GOTO(out, rc);
1981                 }
1982
1983                 if (rc == 0) {
1984                         if (lu_fid_eq(cfid, lfsck_dto2fid(child))) {
1985                                 /* It is the most common case that we
1986                                  * find the name entry corresponding
1987                                  * to the linkEA entry. */
1988                                 lfsck_object_put(env, parent);
1989                                 linkea_next_entry(&ldata);
1990                         } else {
1991                                 /* The name entry references another
1992                                  * MDT-object that may be created by
1993                                  * the LFSCK for repairing dangling
1994                                  * name entry. Try to replace it. */
1995                                 rc = lfsck_namespace_replace_cond(env, com,
1996                                                 parent, child, cfid, cname);
1997                                 lfsck_object_put(env, parent);
1998                                 if (rc < 0)
1999                                         GOTO(out, rc);
2000
2001                                 if (rc > 0) {
2002                                         repaired = true;
2003                                         linkea_next_entry(&ldata);
2004                                 } else {
2005                                         rc = lfsck_namespace_shrink_linkea(env,
2006                                                         com, child, &ldata,
2007                                                         cname, pfid, true);
2008                                         if (rc < 0)
2009                                                 GOTO(out, rc);
2010
2011                                         if (rc > 0)
2012                                                 repaired = true;
2013                                 }
2014                         }
2015
2016                         continue;
2017                 }
2018
2019                 rc = dt_attr_get(env, child, la, BYPASS_CAPA);
2020                 if (rc != 0)
2021                         GOTO(out, rc);
2022
2023                 /* If there is no name entry in the parent dir and the object
2024                  * link count is less than the linkea entries count, then the
2025                  * linkea entry should be removed. */
2026                 if (ldata.ld_leh->leh_reccount > la->la_nlink) {
2027                         rc = lfsck_namespace_shrink_linkea_cond(env, com,
2028                                         parent, child, &ldata, cname, pfid);
2029                         lfsck_object_put(env, parent);
2030                         if (rc < 0)
2031                                 GOTO(out, rc);
2032
2033                         if (rc > 0)
2034                                 repaired = true;
2035
2036                         continue;
2037                 }
2038
2039                 /* Add the missing name entry back to the namespace. */
2040                 rc = lfsck_namespace_insert_normal(env, com, parent, child,
2041                                                    cname->ln_name);
2042                 lfsck_object_put(env, parent);
2043                 if (rc < 0)
2044                         GOTO(out, rc);
2045
2046                 if (rc > 0)
2047                         repaired = true;
2048
2049                 linkea_next_entry(&ldata);
2050         }
2051
2052         GOTO(out, rc = 0);
2053
2054 out:
2055         if (rc < 0 && rc != -ENODATA)
2056                 return rc;
2057
2058         if (rc == 0) {
2059                 LASSERT(ldata.ld_leh != NULL);
2060
2061                 count = ldata.ld_leh->leh_reccount;
2062         }
2063
2064         if (count == 0) {
2065                 /* If the child becomes orphan, then insert it into
2066                  * the global .lustre/lost+found/MDTxxxx directory. */
2067                 rc = lfsck_namespace_insert_orphan(env, com, child, "", "O",
2068                                                    &count);
2069                 if (rc < 0)
2070                         return rc;
2071
2072                 if (rc > 0)
2073                         repaired = true;
2074         }
2075
2076         rc = dt_attr_get(env, child, la, BYPASS_CAPA);
2077         if (rc != 0)
2078                 return rc;
2079
2080         if (la->la_nlink != count) {
2081                 /* XXX: there will be other patch(es) for MDT-object
2082                  *      hard links verification. */
2083         }
2084
2085         if (repaired) {
2086                 if (la->la_nlink > 1)
2087                         ns->ln_mul_linked_repaired++;
2088
2089                 if (rc == 0)
2090                         rc = 1;
2091         }
2092
2093         return rc;
2094 }
2095
2096 static void lfsck_namespace_dump_statistics(struct seq_file *m,
2097                                             struct lfsck_namespace *ns,
2098                                             __u64 checked_phase1,
2099                                             __u64 checked_phase2,
2100                                             __u32 time_phase1,
2101                                             __u32 time_phase2)
2102 {
2103         seq_printf(m, "checked_phase1: "LPU64"\n"
2104                       "checked_phase2: "LPU64"\n"
2105                       "updated_phase1: "LPU64"\n"
2106                       "updated_phase2: "LPU64"\n"
2107                       "failed_phase1: "LPU64"\n"
2108                       "failed_phase2: "LPU64"\n"
2109                       "directories: "LPU64"\n"
2110                       "dirent_repaired: "LPU64"\n"
2111                       "linkea_repaired: "LPU64"\n"
2112                       "nlinks_repaired: "LPU64"\n"
2113                       "lost_found: "LPU64"\n"
2114                       "multiple_linked_checked: "LPU64"\n"
2115                       "multiple_linked_repaired: "LPU64"\n"
2116                       "unknown_inconsistency: "LPU64"\n"
2117                       "unmatched_pairs_repaired: "LPU64"\n"
2118                       "dangling_repaired: "LPU64"\n"
2119                       "success_count: %u\n"
2120                       "run_time_phase1: %u seconds\n"
2121                       "run_time_phase2: %u seconds\n",
2122                       checked_phase1,
2123                       checked_phase2,
2124                       ns->ln_items_repaired,
2125                       ns->ln_objs_repaired_phase2,
2126                       ns->ln_items_failed,
2127                       ns->ln_objs_failed_phase2,
2128                       ns->ln_dirs_checked,
2129                       ns->ln_dirent_repaired,
2130                       ns->ln_linkea_repaired,
2131                       ns->ln_objs_nlink_repaired,
2132                       ns->ln_objs_lost_found,
2133                       ns->ln_mul_linked_checked,
2134                       ns->ln_mul_linked_repaired,
2135                       ns->ln_unknown_inconsistency,
2136                       ns->ln_unmatched_pairs_repaired,
2137                       ns->ln_dangling_repaired,
2138                       ns->ln_success_count,
2139                       time_phase1,
2140                       time_phase2);
2141 }
2142
2143 /* namespace APIs */
2144
2145 static int lfsck_namespace_reset(const struct lu_env *env,
2146                                  struct lfsck_component *com, bool init)
2147 {
2148         struct lfsck_instance   *lfsck = com->lc_lfsck;
2149         struct lfsck_namespace  *ns    = com->lc_file_ram;
2150         struct dt_object        *root;
2151         struct dt_object        *dto;
2152         int                      rc;
2153         ENTRY;
2154
2155         root = dt_locate(env, lfsck->li_bottom, &lfsck->li_local_root_fid);
2156         if (IS_ERR(root))
2157                 GOTO(log, rc = PTR_ERR(root));
2158
2159         if (unlikely(!dt_try_as_dir(env, root)))
2160                 GOTO(put, rc = -ENOTDIR);
2161
2162         down_write(&com->lc_sem);
2163         if (init) {
2164                 memset(ns, 0, sizeof(*ns));
2165         } else {
2166                 __u32 count = ns->ln_success_count;
2167                 __u64 last_time = ns->ln_time_last_complete;
2168
2169                 memset(ns, 0, sizeof(*ns));
2170                 ns->ln_success_count = count;
2171                 ns->ln_time_last_complete = last_time;
2172         }
2173         ns->ln_magic = LFSCK_NAMESPACE_MAGIC;
2174         ns->ln_status = LS_INIT;
2175
2176         rc = local_object_unlink(env, lfsck->li_bottom, root,
2177                                  lfsck_namespace_name);
2178         if (rc != 0)
2179                 GOTO(out, rc);
2180
2181         lfsck_object_put(env, com->lc_obj);
2182         com->lc_obj = NULL;
2183         dto = local_index_find_or_create(env, lfsck->li_los, root,
2184                                          lfsck_namespace_name,
2185                                          S_IFREG | S_IRUGO | S_IWUSR,
2186                                          &dt_lfsck_features);
2187         if (IS_ERR(dto))
2188                 GOTO(out, rc = PTR_ERR(dto));
2189
2190         com->lc_obj = dto;
2191         rc = dto->do_ops->do_index_try(env, dto, &dt_lfsck_features);
2192         if (rc != 0)
2193                 GOTO(out, rc);
2194
2195         rc = lfsck_namespace_store(env, com, true);
2196
2197         GOTO(out, rc);
2198
2199 out:
2200         up_write(&com->lc_sem);
2201
2202 put:
2203         lu_object_put(env, &root->do_lu);
2204 log:
2205         CDEBUG(D_LFSCK, "%s: namespace LFSCK reset: rc = %d\n",
2206                lfsck_lfsck2name(lfsck), rc);
2207         return rc;
2208 }
2209
2210 static void
2211 lfsck_namespace_fail(const struct lu_env *env, struct lfsck_component *com,
2212                      bool new_checked)
2213 {
2214         struct lfsck_namespace *ns = com->lc_file_ram;
2215
2216         down_write(&com->lc_sem);
2217         if (new_checked)
2218                 com->lc_new_checked++;
2219         lfsck_namespace_record_failure(env, com->lc_lfsck, ns);
2220         up_write(&com->lc_sem);
2221 }
2222
2223 static int lfsck_namespace_checkpoint(const struct lu_env *env,
2224                                       struct lfsck_component *com, bool init)
2225 {
2226         struct lfsck_instance   *lfsck = com->lc_lfsck;
2227         struct lfsck_namespace  *ns    = com->lc_file_ram;
2228         int                      rc;
2229
2230         if (!init) {
2231                 rc = lfsck_checkpoint_generic(env, com);
2232                 if (rc != 0)
2233                         goto log;
2234         }
2235
2236         down_write(&com->lc_sem);
2237         if (init) {
2238                 ns->ln_pos_latest_start = lfsck->li_pos_checkpoint;
2239         } else {
2240                 ns->ln_pos_last_checkpoint = lfsck->li_pos_checkpoint;
2241                 ns->ln_run_time_phase1 += cfs_duration_sec(cfs_time_current() +
2242                                 HALF_SEC - lfsck->li_time_last_checkpoint);
2243                 ns->ln_time_last_checkpoint = cfs_time_current_sec();
2244                 ns->ln_items_checked += com->lc_new_checked;
2245                 com->lc_new_checked = 0;
2246         }
2247
2248         rc = lfsck_namespace_store(env, com, false);
2249         up_write(&com->lc_sem);
2250
2251 log:
2252         CDEBUG(D_LFSCK, "%s: namespace LFSCK checkpoint at the pos ["LPU64
2253                ", "DFID", "LPX64"]: rc = %d\n", lfsck_lfsck2name(lfsck),
2254                lfsck->li_pos_current.lp_oit_cookie,
2255                PFID(&lfsck->li_pos_current.lp_dir_parent),
2256                lfsck->li_pos_current.lp_dir_cookie, rc);
2257
2258         return rc > 0 ? 0 : rc;
2259 }
2260
2261 static int lfsck_namespace_prep(const struct lu_env *env,
2262                                 struct lfsck_component *com,
2263                                 struct lfsck_start_param *lsp)
2264 {
2265         struct lfsck_instance   *lfsck  = com->lc_lfsck;
2266         struct lfsck_namespace  *ns     = com->lc_file_ram;
2267         struct lfsck_position   *pos    = &com->lc_pos_start;
2268         int                      rc;
2269
2270         if (ns->ln_status == LS_COMPLETED) {
2271                 rc = lfsck_namespace_reset(env, com, false);
2272                 if (rc == 0)
2273                         rc = lfsck_set_param(env, lfsck, lsp->lsp_start, true);
2274
2275                 if (rc != 0) {
2276                         CDEBUG(D_LFSCK, "%s: namespace LFSCK prep failed: "
2277                                "rc = %d\n", lfsck_lfsck2name(lfsck), rc);
2278
2279                         return rc;
2280                 }
2281         }
2282
2283         down_write(&com->lc_sem);
2284         ns->ln_time_latest_start = cfs_time_current_sec();
2285         spin_lock(&lfsck->li_lock);
2286
2287         if (ns->ln_flags & LF_SCANNED_ONCE) {
2288                 if (!lfsck->li_drop_dryrun ||
2289                     lfsck_pos_is_zero(&ns->ln_pos_first_inconsistent)) {
2290                         ns->ln_status = LS_SCANNING_PHASE2;
2291                         list_move_tail(&com->lc_link,
2292                                        &lfsck->li_list_double_scan);
2293                         if (!list_empty(&com->lc_link_dir))
2294                                 list_del_init(&com->lc_link_dir);
2295                         lfsck_pos_set_zero(pos);
2296                 } else {
2297                         ns->ln_status = LS_SCANNING_PHASE1;
2298                         ns->ln_run_time_phase1 = 0;
2299                         ns->ln_run_time_phase2 = 0;
2300                         ns->ln_items_checked = 0;
2301                         ns->ln_items_repaired = 0;
2302                         ns->ln_items_failed = 0;
2303                         ns->ln_dirs_checked = 0;
2304                         ns->ln_objs_checked_phase2 = 0;
2305                         ns->ln_objs_repaired_phase2 = 0;
2306                         ns->ln_objs_failed_phase2 = 0;
2307                         ns->ln_objs_nlink_repaired = 0;
2308                         ns->ln_objs_lost_found = 0;
2309                         ns->ln_dirent_repaired = 0;
2310                         ns->ln_linkea_repaired = 0;
2311                         ns->ln_mul_linked_checked = 0;
2312                         ns->ln_mul_linked_repaired = 0;
2313                         ns->ln_unknown_inconsistency = 0;
2314                         ns->ln_unmatched_pairs_repaired = 0;
2315                         ns->ln_dangling_repaired = 0;
2316                         fid_zero(&ns->ln_fid_latest_scanned_phase2);
2317                         if (list_empty(&com->lc_link_dir))
2318                                 list_add_tail(&com->lc_link_dir,
2319                                               &lfsck->li_list_dir);
2320                         *pos = ns->ln_pos_first_inconsistent;
2321                 }
2322         } else {
2323                 ns->ln_status = LS_SCANNING_PHASE1;
2324                 if (list_empty(&com->lc_link_dir))
2325                         list_add_tail(&com->lc_link_dir,
2326                                       &lfsck->li_list_dir);
2327                 if (!lfsck->li_drop_dryrun ||
2328                     lfsck_pos_is_zero(&ns->ln_pos_first_inconsistent)) {
2329                         *pos = ns->ln_pos_last_checkpoint;
2330                         pos->lp_oit_cookie++;
2331                 } else {
2332                         *pos = ns->ln_pos_first_inconsistent;
2333                 }
2334         }
2335
2336         spin_unlock(&lfsck->li_lock);
2337         up_write(&com->lc_sem);
2338
2339         rc = lfsck_start_assistant(env, com, lsp);
2340
2341         CDEBUG(D_LFSCK, "%s: namespace LFSCK prep done, start pos ["LPU64", "
2342                DFID", "LPX64"]: rc = %d\n",
2343                lfsck_lfsck2name(lfsck), pos->lp_oit_cookie,
2344                PFID(&pos->lp_dir_parent), pos->lp_dir_cookie, rc);
2345
2346         return rc;
2347 }
2348
2349 static int lfsck_namespace_exec_oit(const struct lu_env *env,
2350                                     struct lfsck_component *com,
2351                                     struct dt_object *obj)
2352 {
2353         struct lfsck_thread_info *info  = lfsck_env_info(env);
2354         struct lfsck_namespace   *ns    = com->lc_file_ram;
2355         struct lfsck_instance    *lfsck = com->lc_lfsck;
2356         const struct lu_fid      *fid   = lfsck_dto2fid(obj);
2357         struct lu_attr           *la    = &info->lti_la;
2358         struct lu_fid            *pfid  = &info->lti_fid2;
2359         struct lu_name           *cname = &info->lti_name;
2360         struct lu_seq_range      *range = &info->lti_range;
2361         struct dt_device         *dev   = lfsck->li_bottom;
2362         struct seq_server_site   *ss    =
2363                                 lu_site2seq(dev->dd_lu_dev.ld_site);
2364         struct linkea_data        ldata = { 0 };
2365         __u32                     idx   = lfsck_dev_idx(dev);
2366         int                       rc;
2367         ENTRY;
2368
2369         rc = lfsck_links_read(env, obj, &ldata);
2370         if (rc == -ENOENT)
2371                 GOTO(out, rc = 0);
2372
2373         /* -EINVAL means crashed linkEA, should be verified. */
2374         if (rc == -EINVAL) {
2375                 rc = lfsck_namespace_trace_update(env, com, fid,
2376                                                   LNTF_CHECK_LINKEA, true);
2377                 if (rc == 0) {
2378                         struct lustre_handle lh = { 0 };
2379
2380                         rc = lfsck_ibits_lock(env, lfsck, obj, &lh,
2381                                               MDS_INODELOCK_UPDATE |
2382                                               MDS_INODELOCK_XATTR, LCK_EX);
2383                         if (rc == 0) {
2384                                 rc = lfsck_namespace_links_remove(env, com,
2385                                                                   obj);
2386                                 lfsck_ibits_unlock(&lh, LCK_EX);
2387                         }
2388                 }
2389
2390                 GOTO(out, rc = (rc == -ENOENT ? 0 : rc));
2391         }
2392
2393         /* zero-linkEA object may be orphan, but it also maybe because
2394          * of upgrading. Currently, we cannot record it for double scan.
2395          * Because it may cause the LFSCK tracing file to be too large. */
2396         if (rc == -ENODATA) {
2397                 if (S_ISDIR(lfsck_object_type(obj)))
2398                         GOTO(out, rc = 0);
2399
2400                 rc = dt_attr_get(env, obj, la, BYPASS_CAPA);
2401                 if (rc != 0)
2402                         GOTO(out, rc);
2403
2404                 if (la->la_nlink > 1)
2405                         rc = lfsck_namespace_trace_update(env, com, fid,
2406                                                 LNTF_CHECK_LINKEA, true);
2407
2408                 GOTO(out, rc);
2409         }
2410
2411         if (rc != 0)
2412                 GOTO(out, rc);
2413
2414         /* Record multiple-linked object. */
2415         if (ldata.ld_leh->leh_reccount > 1) {
2416                 rc = lfsck_namespace_trace_update(env, com, fid,
2417                                                   LNTF_CHECK_LINKEA, true);
2418
2419                 GOTO(out, rc);
2420         }
2421
2422         linkea_first_entry(&ldata);
2423         linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen, cname, pfid);
2424         if (!fid_is_sane(pfid)) {
2425                 rc = lfsck_namespace_trace_update(env, com, fid,
2426                                                   LNTF_CHECK_PARENT, true);
2427         } else {
2428                 fld_range_set_mdt(range);
2429                 rc = fld_local_lookup(env, ss->ss_server_fld,
2430                                       fid_seq(pfid), range);
2431                 if ((rc == -ENOENT) ||
2432                     (rc == 0 && range->lsr_index != idx)) {
2433                         rc = lfsck_namespace_trace_update(env, com, fid,
2434                                                 LNTF_CHECK_LINKEA, true);
2435                 } else {
2436                         if (S_ISDIR(lfsck_object_type(obj)))
2437                                 GOTO(out, rc = 0);
2438
2439                         rc = dt_attr_get(env, obj, la, BYPASS_CAPA);
2440                         if (rc != 0)
2441                                 GOTO(out, rc);
2442
2443                         if (la->la_nlink > 1)
2444                                 rc = lfsck_namespace_trace_update(env, com,
2445                                                 fid, LNTF_CHECK_LINKEA, true);
2446                 }
2447         }
2448
2449         GOTO(out, rc);
2450
2451 out:
2452         down_write(&com->lc_sem);
2453         com->lc_new_checked++;
2454         if (S_ISDIR(lfsck_object_type(obj)))
2455                 ns->ln_dirs_checked++;
2456         if (rc != 0)
2457                 lfsck_namespace_record_failure(env, com->lc_lfsck, ns);
2458         up_write(&com->lc_sem);
2459
2460         return rc;
2461 }
2462
2463 static int lfsck_namespace_exec_dir(const struct lu_env *env,
2464                                     struct lfsck_component *com,
2465                                     struct lu_dirent *ent, __u16 type)
2466 {
2467         struct lfsck_assistant_data     *lad    = com->lc_data;
2468         struct lfsck_namespace_req      *lnr;
2469         bool                             wakeup = false;
2470
2471         lnr = lfsck_namespace_assistant_req_init(com->lc_lfsck, ent, type);
2472         if (IS_ERR(lnr)) {
2473                 struct lfsck_namespace *ns = com->lc_file_ram;
2474
2475                 lfsck_namespace_record_failure(env, com->lc_lfsck, ns);
2476                 return PTR_ERR(lnr);
2477         }
2478
2479         spin_lock(&lad->lad_lock);
2480         if (lad->lad_assistant_status < 0) {
2481                 spin_unlock(&lad->lad_lock);
2482                 lfsck_namespace_assistant_req_fini(env, &lnr->lnr_lar);
2483                 return lad->lad_assistant_status;
2484         }
2485
2486         list_add_tail(&lnr->lnr_lar.lar_list, &lad->lad_req_list);
2487         if (lad->lad_prefetched == 0)
2488                 wakeup = true;
2489
2490         lad->lad_prefetched++;
2491         spin_unlock(&lad->lad_lock);
2492         if (wakeup)
2493                 wake_up_all(&lad->lad_thread.t_ctl_waitq);
2494
2495         down_write(&com->lc_sem);
2496         com->lc_new_checked++;
2497         up_write(&com->lc_sem);
2498
2499         return 0;
2500 }
2501
2502 static int lfsck_namespace_post(const struct lu_env *env,
2503                                 struct lfsck_component *com,
2504                                 int result, bool init)
2505 {
2506         struct lfsck_instance   *lfsck = com->lc_lfsck;
2507         struct lfsck_namespace  *ns    = com->lc_file_ram;
2508         int                      rc;
2509         ENTRY;
2510
2511         lfsck_post_generic(env, com, &result);
2512
2513         down_write(&com->lc_sem);
2514         spin_lock(&lfsck->li_lock);
2515         if (!init)
2516                 ns->ln_pos_last_checkpoint = lfsck->li_pos_checkpoint;
2517         if (result > 0) {
2518                 ns->ln_status = LS_SCANNING_PHASE2;
2519                 ns->ln_flags |= LF_SCANNED_ONCE;
2520                 ns->ln_flags &= ~LF_UPGRADE;
2521                 list_del_init(&com->lc_link_dir);
2522                 list_move_tail(&com->lc_link, &lfsck->li_list_double_scan);
2523         } else if (result == 0) {
2524                 ns->ln_status = lfsck->li_status;
2525                 if (ns->ln_status == 0)
2526                         ns->ln_status = LS_STOPPED;
2527                 if (ns->ln_status != LS_PAUSED) {
2528                         list_del_init(&com->lc_link_dir);
2529                         list_move_tail(&com->lc_link, &lfsck->li_list_idle);
2530                 }
2531         } else {
2532                 ns->ln_status = LS_FAILED;
2533                 list_del_init(&com->lc_link_dir);
2534                 list_move_tail(&com->lc_link, &lfsck->li_list_idle);
2535         }
2536         spin_unlock(&lfsck->li_lock);
2537
2538         if (!init) {
2539                 ns->ln_run_time_phase1 += cfs_duration_sec(cfs_time_current() +
2540                                 HALF_SEC - lfsck->li_time_last_checkpoint);
2541                 ns->ln_time_last_checkpoint = cfs_time_current_sec();
2542                 ns->ln_items_checked += com->lc_new_checked;
2543                 com->lc_new_checked = 0;
2544         }
2545
2546         rc = lfsck_namespace_store(env, com, false);
2547         up_write(&com->lc_sem);
2548
2549         CDEBUG(D_LFSCK, "%s: namespace LFSCK post done: rc = %d\n",
2550                lfsck_lfsck2name(lfsck), rc);
2551
2552         RETURN(rc);
2553 }
2554
2555 static int
2556 lfsck_namespace_dump(const struct lu_env *env, struct lfsck_component *com,
2557                      struct seq_file *m)
2558 {
2559         struct lfsck_instance   *lfsck = com->lc_lfsck;
2560         struct lfsck_bookmark   *bk    = &lfsck->li_bookmark_ram;
2561         struct lfsck_namespace  *ns    = com->lc_file_ram;
2562         int                      rc;
2563
2564         down_read(&com->lc_sem);
2565         seq_printf(m, "name: lfsck_namespace\n"
2566                    "magic: %#x\n"
2567                    "version: %d\n"
2568                    "status: %s\n",
2569                    ns->ln_magic,
2570                    bk->lb_version,
2571                    lfsck_status2names(ns->ln_status));
2572
2573         rc = lfsck_bits_dump(m, ns->ln_flags, lfsck_flags_names, "flags");
2574         if (rc < 0)
2575                 goto out;
2576
2577         rc = lfsck_bits_dump(m, bk->lb_param, lfsck_param_names, "param");
2578         if (rc < 0)
2579                 goto out;
2580
2581         rc = lfsck_time_dump(m, ns->ln_time_last_complete,
2582                              "time_since_last_completed");
2583         if (rc < 0)
2584                 goto out;
2585
2586         rc = lfsck_time_dump(m, ns->ln_time_latest_start,
2587                              "time_since_latest_start");
2588         if (rc < 0)
2589                 goto out;
2590
2591         rc = lfsck_time_dump(m, ns->ln_time_last_checkpoint,
2592                              "time_since_last_checkpoint");
2593         if (rc < 0)
2594                 goto out;
2595
2596         rc = lfsck_pos_dump(m, &ns->ln_pos_latest_start,
2597                             "latest_start_position");
2598         if (rc < 0)
2599                 goto out;
2600
2601         rc = lfsck_pos_dump(m, &ns->ln_pos_last_checkpoint,
2602                             "last_checkpoint_position");
2603         if (rc < 0)
2604                 goto out;
2605
2606         rc = lfsck_pos_dump(m, &ns->ln_pos_first_inconsistent,
2607                             "first_failure_position");
2608         if (rc < 0)
2609                 goto out;
2610
2611         if (ns->ln_status == LS_SCANNING_PHASE1) {
2612                 struct lfsck_position pos;
2613                 const struct dt_it_ops *iops;
2614                 cfs_duration_t duration = cfs_time_current() -
2615                                           lfsck->li_time_last_checkpoint;
2616                 __u64 checked = ns->ln_items_checked + com->lc_new_checked;
2617                 __u64 speed = checked;
2618                 __u64 new_checked = com->lc_new_checked * HZ;
2619                 __u32 rtime = ns->ln_run_time_phase1 +
2620                               cfs_duration_sec(duration + HALF_SEC);
2621
2622                 if (duration != 0)
2623                         do_div(new_checked, duration);
2624                 if (rtime != 0)
2625                         do_div(speed, rtime);
2626                 lfsck_namespace_dump_statistics(m, ns, checked,
2627                                                 ns->ln_objs_checked_phase2,
2628                                                 rtime, ns->ln_run_time_phase2);
2629
2630                 seq_printf(m, "average_speed_phase1: "LPU64" items/sec\n"
2631                               "average_speed_phase2: N/A\n"
2632                               "real_time_speed_phase1: "LPU64" items/sec\n"
2633                               "real_time_speed_phase2: N/A\n",
2634                               speed,
2635                               new_checked);
2636
2637                 LASSERT(lfsck->li_di_oit != NULL);
2638
2639                 iops = &lfsck->li_obj_oit->do_index_ops->dio_it;
2640
2641                 /* The low layer otable-based iteration position may NOT
2642                  * exactly match the namespace-based directory traversal
2643                  * cookie. Generally, it is not a serious issue. But the
2644                  * caller should NOT make assumption on that. */
2645                 pos.lp_oit_cookie = iops->store(env, lfsck->li_di_oit);
2646                 if (!lfsck->li_current_oit_processed)
2647                         pos.lp_oit_cookie--;
2648
2649                 spin_lock(&lfsck->li_lock);
2650                 if (lfsck->li_di_dir != NULL) {
2651                         pos.lp_dir_cookie = lfsck->li_cookie_dir;
2652                         if (pos.lp_dir_cookie >= MDS_DIR_END_OFF) {
2653                                 fid_zero(&pos.lp_dir_parent);
2654                                 pos.lp_dir_cookie = 0;
2655                         } else {
2656                                 pos.lp_dir_parent =
2657                                         *lfsck_dto2fid(lfsck->li_obj_dir);
2658                         }
2659                 } else {
2660                         fid_zero(&pos.lp_dir_parent);
2661                         pos.lp_dir_cookie = 0;
2662                 }
2663                 spin_unlock(&lfsck->li_lock);
2664                 lfsck_pos_dump(m, &pos, "current_position");
2665         } else if (ns->ln_status == LS_SCANNING_PHASE2) {
2666                 cfs_duration_t duration = cfs_time_current() -
2667                                           lfsck->li_time_last_checkpoint;
2668                 __u64 checked = ns->ln_objs_checked_phase2 +
2669                                 com->lc_new_checked;
2670                 __u64 speed1 = ns->ln_items_checked;
2671                 __u64 speed2 = checked;
2672                 __u64 new_checked = com->lc_new_checked * HZ;
2673                 __u32 rtime = ns->ln_run_time_phase2 +
2674                               cfs_duration_sec(duration + HALF_SEC);
2675
2676                 if (duration != 0)
2677                         do_div(new_checked, duration);
2678                 if (ns->ln_run_time_phase1 != 0)
2679                         do_div(speed1, ns->ln_run_time_phase1);
2680                 if (rtime != 0)
2681                         do_div(speed2, rtime);
2682                 lfsck_namespace_dump_statistics(m, ns, ns->ln_items_checked,
2683                                                 checked,
2684                                                 ns->ln_run_time_phase1, rtime);
2685
2686                 seq_printf(m, "average_speed_phase1: "LPU64" items/sec\n"
2687                               "average_speed_phase2: "LPU64" objs/sec\n"
2688                               "real_time_speed_phase1: N/A\n"
2689                               "real_time_speed_phase2: "LPU64" objs/sec\n"
2690                               "current_position: "DFID"\n",
2691                               speed1,
2692                               speed2,
2693                               new_checked,
2694                               PFID(&ns->ln_fid_latest_scanned_phase2));
2695         } else {
2696                 __u64 speed1 = ns->ln_items_checked;
2697                 __u64 speed2 = ns->ln_objs_checked_phase2;
2698
2699                 if (ns->ln_run_time_phase1 != 0)
2700                         do_div(speed1, ns->ln_run_time_phase1);
2701                 if (ns->ln_run_time_phase2 != 0)
2702                         do_div(speed2, ns->ln_run_time_phase2);
2703                 lfsck_namespace_dump_statistics(m, ns, ns->ln_items_checked,
2704                                                 ns->ln_objs_checked_phase2,
2705                                                 ns->ln_run_time_phase1,
2706                                                 ns->ln_run_time_phase2);
2707
2708                 seq_printf(m, "average_speed_phase1: "LPU64" items/sec\n"
2709                               "average_speed_phase2: "LPU64" objs/sec\n"
2710                               "real_time_speed_phase1: N/A\n"
2711                               "real_time_speed_phase2: N/A\n"
2712                               "current_position: N/A\n",
2713                               speed1,
2714                               speed2);
2715         }
2716 out:
2717         up_read(&com->lc_sem);
2718         return 0;
2719 }
2720
2721 static int lfsck_namespace_double_scan(const struct lu_env *env,
2722                                        struct lfsck_component *com)
2723 {
2724         struct lfsck_namespace *ns = com->lc_file_ram;
2725
2726         return lfsck_double_scan_generic(env, com, ns->ln_status);
2727 }
2728
2729 static void lfsck_namespace_data_release(const struct lu_env *env,
2730                                          struct lfsck_component *com)
2731 {
2732         struct lfsck_assistant_data     *lad    = com->lc_data;
2733         struct lfsck_tgt_descs          *ltds   = &com->lc_lfsck->li_mdt_descs;
2734         struct lfsck_tgt_desc           *ltd;
2735         struct lfsck_tgt_desc           *next;
2736
2737         LASSERT(lad != NULL);
2738         LASSERT(thread_is_init(&lad->lad_thread) ||
2739                 thread_is_stopped(&lad->lad_thread));
2740         LASSERT(list_empty(&lad->lad_req_list));
2741
2742         com->lc_data = NULL;
2743
2744         spin_lock(&ltds->ltd_lock);
2745         list_for_each_entry_safe(ltd, next, &lad->lad_mdt_phase1_list,
2746                                  ltd_namespace_phase_list) {
2747                 list_del_init(&ltd->ltd_namespace_phase_list);
2748         }
2749         list_for_each_entry_safe(ltd, next, &lad->lad_mdt_phase2_list,
2750                                  ltd_namespace_phase_list) {
2751                 list_del_init(&ltd->ltd_namespace_phase_list);
2752         }
2753         list_for_each_entry_safe(ltd, next, &lad->lad_mdt_list,
2754                                  ltd_namespace_list) {
2755                 list_del_init(&ltd->ltd_namespace_list);
2756         }
2757         spin_unlock(&ltds->ltd_lock);
2758
2759         CFS_FREE_BITMAP(lad->lad_bitmap);
2760
2761         OBD_FREE_PTR(lad);
2762 }
2763
2764 static int lfsck_namespace_in_notify(const struct lu_env *env,
2765                                      struct lfsck_component *com,
2766                                      struct lfsck_request *lr)
2767 {
2768         struct lfsck_instance           *lfsck = com->lc_lfsck;
2769         struct lfsck_namespace          *ns    = com->lc_file_ram;
2770         struct lfsck_assistant_data     *lad   = com->lc_data;
2771         struct lfsck_tgt_descs          *ltds  = &lfsck->li_mdt_descs;
2772         struct lfsck_tgt_desc           *ltd;
2773         bool                             fail  = false;
2774         ENTRY;
2775
2776         if (lr->lr_event != LE_PHASE1_DONE &&
2777             lr->lr_event != LE_PHASE2_DONE &&
2778             lr->lr_event != LE_PEER_EXIT)
2779                 RETURN(-EINVAL);
2780
2781         CDEBUG(D_LFSCK, "%s: namespace LFSCK handles notify %u from MDT %x, "
2782                "status %d\n", lfsck_lfsck2name(lfsck), lr->lr_event,
2783                lr->lr_index, lr->lr_status);
2784
2785         spin_lock(&ltds->ltd_lock);
2786         ltd = LTD_TGT(ltds, lr->lr_index);
2787         if (ltd == NULL) {
2788                 spin_unlock(&ltds->ltd_lock);
2789
2790                 RETURN(-ENXIO);
2791         }
2792
2793         list_del_init(&ltd->ltd_namespace_phase_list);
2794         switch (lr->lr_event) {
2795         case LE_PHASE1_DONE:
2796                 if (lr->lr_status <= 0) {
2797                         ltd->ltd_namespace_done = 1;
2798                         list_del_init(&ltd->ltd_namespace_list);
2799                         CDEBUG(D_LFSCK, "%s: MDT %x failed/stopped at "
2800                                "phase1 for namespace LFSCK: rc = %d.\n",
2801                                lfsck_lfsck2name(lfsck),
2802                                ltd->ltd_index, lr->lr_status);
2803                         ns->ln_flags |= LF_INCOMPLETE;
2804                         fail = true;
2805                         break;
2806                 }
2807
2808                 if (list_empty(&ltd->ltd_namespace_list))
2809                         list_add_tail(&ltd->ltd_namespace_list,
2810                                       &lad->lad_mdt_list);
2811                 list_add_tail(&ltd->ltd_namespace_phase_list,
2812                               &lad->lad_mdt_phase2_list);
2813                 break;
2814         case LE_PHASE2_DONE:
2815                 ltd->ltd_namespace_done = 1;
2816                 list_del_init(&ltd->ltd_namespace_list);
2817                 break;
2818         case LE_PEER_EXIT:
2819                 fail = true;
2820                 ltd->ltd_namespace_done = 1;
2821                 list_del_init(&ltd->ltd_namespace_list);
2822                 if (!(lfsck->li_bookmark_ram.lb_param & LPF_FAILOUT)) {
2823                         CDEBUG(D_LFSCK,
2824                                "%s: the peer MDT %x exit namespace LFSCK\n",
2825                                lfsck_lfsck2name(lfsck), ltd->ltd_index);
2826                         ns->ln_flags |= LF_INCOMPLETE;
2827                 }
2828                 break;
2829         default:
2830                 break;
2831         }
2832         spin_unlock(&ltds->ltd_lock);
2833
2834         if (fail && lfsck->li_bookmark_ram.lb_param & LPF_FAILOUT) {
2835                 struct lfsck_stop *stop = &lfsck_env_info(env)->lti_stop;
2836
2837                 memset(stop, 0, sizeof(*stop));
2838                 stop->ls_status = lr->lr_status;
2839                 stop->ls_flags = lr->lr_param & ~LPF_BROADCAST;
2840                 lfsck_stop(env, lfsck->li_bottom, stop);
2841         } else if (lfsck_phase2_next_ready(lad)) {
2842                 wake_up_all(&lad->lad_thread.t_ctl_waitq);
2843         }
2844
2845         RETURN(0);
2846 }
2847
2848 static int lfsck_namespace_query(const struct lu_env *env,
2849                                  struct lfsck_component *com)
2850 {
2851         struct lfsck_namespace *ns = com->lc_file_ram;
2852
2853         return ns->ln_status;
2854 }
2855
2856 static struct lfsck_operations lfsck_namespace_ops = {
2857         .lfsck_reset            = lfsck_namespace_reset,
2858         .lfsck_fail             = lfsck_namespace_fail,
2859         .lfsck_checkpoint       = lfsck_namespace_checkpoint,
2860         .lfsck_prep             = lfsck_namespace_prep,
2861         .lfsck_exec_oit         = lfsck_namespace_exec_oit,
2862         .lfsck_exec_dir         = lfsck_namespace_exec_dir,
2863         .lfsck_post             = lfsck_namespace_post,
2864         .lfsck_dump             = lfsck_namespace_dump,
2865         .lfsck_double_scan      = lfsck_namespace_double_scan,
2866         .lfsck_data_release     = lfsck_namespace_data_release,
2867         .lfsck_quit             = lfsck_quit_generic,
2868         .lfsck_in_notify        = lfsck_namespace_in_notify,
2869         .lfsck_query            = lfsck_namespace_query,
2870 };
2871
2872 /**
2873  * Repair dangling name entry.
2874  *
2875  * For the name entry with dangling reference, we need to repare the
2876  * inconsistency according to the LFSCK sponsor's requirement:
2877  *
2878  * 1) Keep the inconsistency there and report the inconsistency case,
2879  *    then give the chance to the application to find related issues,
2880  *    and the users can make the decision about how to handle it with
2881  *    more human knownledge. (by default)
2882  *
2883  * 2) Re-create the missed MDT-object with the FID information.
2884  *
2885  * \param[in] env       pointer to the thread context
2886  * \param[in] com       pointer to the lfsck component
2887  * \param[in] child     pointer to the object corresponding to the dangling
2888  *                      name entry
2889  * \param[in] lnr       pointer to the namespace request that contains the
2890  *                      name's name, parent object, parent's LMV, and ect.
2891  *
2892  * \retval              positive number if no need to repair
2893  * \retval              zero for repaired successfully
2894  * \retval              negative error number on failure
2895  */
2896 int lfsck_namespace_repair_dangling(const struct lu_env *env,
2897                                     struct lfsck_component *com,
2898                                     struct dt_object *child,
2899                                     struct lfsck_namespace_req *lnr)
2900 {
2901         struct lfsck_thread_info        *info   = lfsck_env_info(env);
2902         struct lu_attr                  *la     = &info->lti_la;
2903         struct dt_allocation_hint       *hint   = &info->lti_hint;
2904         struct dt_object_format         *dof    = &info->lti_dof;
2905         struct dt_insert_rec            *rec    = &info->lti_dt_rec;
2906         struct dt_object                *parent = lnr->lnr_obj;
2907         const struct lu_name            *cname;
2908         struct linkea_data               ldata  = { 0 };
2909         struct lustre_handle             lh     = { 0 };
2910         struct lu_buf                    linkea_buf;
2911         struct lfsck_instance           *lfsck  = com->lc_lfsck;
2912         struct lfsck_bookmark           *bk     = &lfsck->li_bookmark_ram;
2913         struct dt_device                *dev    = lfsck_obj2dt_dev(child);
2914         struct thandle                  *th     = NULL;
2915         int                              rc     = 0;
2916         __u16                            type   = lnr->lnr_type;
2917         bool                             create;
2918         ENTRY;
2919
2920         cname = lfsck_name_get_const(env, lnr->lnr_name, lnr->lnr_namelen);
2921         if (bk->lb_param & LPF_CREATE_MDTOBJ)
2922                 create = true;
2923         else
2924                 create = false;
2925
2926         if (!create || bk->lb_param & LPF_DRYRUN)
2927                 GOTO(log, rc = 0);
2928
2929         rc = linkea_data_new(&ldata, &info->lti_linkea_buf2);
2930         if (rc != 0)
2931                 GOTO(log, rc);
2932
2933         rc = linkea_add_buf(&ldata, cname, lfsck_dto2fid(parent));
2934         if (rc != 0)
2935                 GOTO(log, rc);
2936
2937         rc = lfsck_ibits_lock(env, lfsck, parent, &lh,
2938                               MDS_INODELOCK_UPDATE, LCK_EX);
2939         if (rc != 0)
2940                 GOTO(log, rc);
2941
2942         rc = lfsck_namespace_check_exist(env, parent, child, lnr->lnr_name);
2943         if (rc != 0)
2944                 GOTO(log, rc);
2945
2946         th = dt_trans_create(env, dev);
2947         if (IS_ERR(th))
2948                 GOTO(log, rc = PTR_ERR(th));
2949
2950         /* Set the ctime as zero, then others can know it is created for
2951          * repairing dangling name entry by LFSCK. And if the LFSCK made
2952          * wrong decision and the real MDT-object has been found later,
2953          * then the LFSCK has chance to fix the incosistency properly. */
2954         memset(la, 0, sizeof(*la));
2955         la->la_mode = (type & S_IFMT) | 0600;
2956         la->la_valid = LA_TYPE | LA_MODE | LA_UID | LA_GID |
2957                         LA_ATIME | LA_MTIME | LA_CTIME;
2958
2959         child->do_ops->do_ah_init(env, hint, parent, child,
2960                                   la->la_mode & S_IFMT);
2961
2962         memset(dof, 0, sizeof(*dof));
2963         dof->dof_type = dt_mode_to_dft(type);
2964         /* If the target is a regular file, then the LFSCK will only create
2965          * the MDT-object without stripes (dof->dof_reg.striped = 0). related
2966          * OST-objects will be created when write open. */
2967
2968         /* 1a. create child. */
2969         rc = dt_declare_create(env, child, la, hint, dof, th);
2970         if (rc != 0)
2971                 GOTO(stop, rc);
2972
2973         if (S_ISDIR(type)) {
2974                 if (unlikely(!dt_try_as_dir(env, child)))
2975                         GOTO(stop, rc = -ENOTDIR);
2976
2977                 /* 2a. insert dot into child dir */
2978                 rec->rec_type = S_IFDIR;
2979                 rec->rec_fid = lfsck_dto2fid(child);
2980                 rc = dt_declare_insert(env, child,
2981                                        (const struct dt_rec *)rec,
2982                                        (const struct dt_key *)dot, th);
2983                 if (rc != 0)
2984                         GOTO(stop, rc);
2985
2986                 /* 3a. insert dotdot into child dir */
2987                 rec->rec_fid = lfsck_dto2fid(parent);
2988                 rc = dt_declare_insert(env, child,
2989                                        (const struct dt_rec *)rec,
2990                                        (const struct dt_key *)dotdot, th);
2991                 if (rc != 0)
2992                         GOTO(stop, rc);
2993
2994                 /* 4a. increase child nlink */
2995                 rc = dt_declare_ref_add(env, child, th);
2996                 if (rc != 0)
2997                         GOTO(stop, rc);
2998         }
2999
3000         /* 5a. insert linkEA for child */
3001         lfsck_buf_init(&linkea_buf, ldata.ld_buf->lb_buf,
3002                        ldata.ld_leh->leh_len);
3003         rc = dt_declare_xattr_set(env, child, &linkea_buf,
3004                                   XATTR_NAME_LINK, 0, th);
3005         if (rc != 0)
3006                 GOTO(stop, rc);
3007
3008         rc = dt_trans_start(env, dev, th);
3009         if (rc != 0)
3010                 GOTO(stop, rc = (rc == -EEXIST ? 1 : rc));
3011
3012         dt_write_lock(env, child, 0);
3013         /* 1b. create child */
3014         rc = dt_create(env, child, la, hint, dof, th);
3015         if (rc != 0)
3016                 GOTO(unlock, rc = (rc == -EEXIST ? 1 : rc));
3017
3018         if (S_ISDIR(type)) {
3019                 if (unlikely(!dt_try_as_dir(env, child)))
3020                         GOTO(unlock, rc = -ENOTDIR);
3021
3022                 /* 2b. insert dot into child dir */
3023                 rec->rec_type = S_IFDIR;
3024                 rec->rec_fid = lfsck_dto2fid(child);
3025                 rc = dt_insert(env, child, (const struct dt_rec *)rec,
3026                                (const struct dt_key *)dot, th, BYPASS_CAPA, 1);
3027                 if (rc != 0)
3028                         GOTO(unlock, rc);
3029
3030                 /* 3b. insert dotdot into child dir */
3031                 rec->rec_fid = lfsck_dto2fid(parent);
3032                 rc = dt_insert(env, child, (const struct dt_rec *)rec,
3033                                (const struct dt_key *)dotdot, th,
3034                                BYPASS_CAPA, 1);
3035                 if (rc != 0)
3036                         GOTO(unlock, rc);
3037
3038                 /* 4b. increase child nlink */
3039                 rc = dt_ref_add(env, child, th);
3040                 if (rc != 0)
3041                         GOTO(unlock, rc);
3042         }
3043
3044         /* 5b. insert linkEA for child. */
3045         rc = dt_xattr_set(env, child, &linkea_buf,
3046                           XATTR_NAME_LINK, 0, th, BYPASS_CAPA);
3047
3048         GOTO(unlock, rc);
3049
3050 unlock:
3051         dt_write_unlock(env, child);
3052
3053 stop:
3054         dt_trans_stop(env, dev, th);
3055
3056 log:
3057         lfsck_ibits_unlock(&lh, LCK_EX);
3058         CDEBUG(D_LFSCK, "%s: namespace LFSCK assistant found dangling "
3059                "reference for: parent "DFID", child "DFID", type %u, "
3060                "name %s. %s: rc = %d\n", lfsck_lfsck2name(lfsck),
3061                PFID(lfsck_dto2fid(parent)), PFID(lfsck_dto2fid(child)),
3062                type, cname->ln_name,
3063                create ? "Create the lost OST-object as required" :
3064                         "Keep the MDT-object there by default", rc);
3065
3066         if (rc <= 0) {
3067                 struct lfsck_namespace *ns = com->lc_file_ram;
3068
3069                 ns->ln_flags |= LF_INCONSISTENT;
3070         }
3071
3072         return rc;
3073 }
3074
3075 static int lfsck_namespace_assistant_handler_p1(const struct lu_env *env,
3076                                                 struct lfsck_component *com,
3077                                                 struct lfsck_assistant_req *lar)
3078 {
3079         struct lfsck_thread_info   *info     = lfsck_env_info(env);
3080         struct lu_attr             *la       = &info->lti_la;
3081         struct lfsck_instance      *lfsck    = com->lc_lfsck;
3082         struct lfsck_bookmark      *bk       = &lfsck->li_bookmark_ram;
3083         struct lfsck_namespace     *ns       = com->lc_file_ram;
3084         struct linkea_data          ldata    = { 0 };
3085         const struct lu_name       *cname;
3086         struct thandle             *handle   = NULL;
3087         struct lfsck_namespace_req *lnr      =
3088                         container_of0(lar, struct lfsck_namespace_req, lnr_lar);
3089         struct dt_object           *dir      = lnr->lnr_obj;
3090         struct dt_object           *obj      = NULL;
3091         const struct lu_fid        *pfid     = lfsck_dto2fid(dir);
3092         struct dt_device           *dev;
3093         struct lustre_handle        lh       = { 0 };
3094         bool                        repaired = false;
3095         bool                        dtlocked = false;
3096         bool                        remove;
3097         bool                        newdata;
3098         bool                        log      = false;
3099         int                         idx;
3100         int                         count    = 0;
3101         int                         rc;
3102         enum lfsck_namespace_inconsistency_type type = LNIT_NONE;
3103         ENTRY;
3104
3105         if (lnr->lnr_attr & LUDA_UPGRADE) {
3106                 ns->ln_flags |= LF_UPGRADE;
3107                 ns->ln_dirent_repaired++;
3108                 repaired = true;
3109         } else if (lnr->lnr_attr & LUDA_REPAIR) {
3110                 ns->ln_flags |= LF_INCONSISTENT;
3111                 ns->ln_dirent_repaired++;
3112                 repaired = true;
3113         }
3114
3115         if (unlikely(fid_is_zero(&lnr->lnr_fid))) {
3116                 if (strcmp(lnr->lnr_name, dotdot) != 0)
3117                         LBUG();
3118                 else
3119                         rc = lfsck_namespace_trace_update(env, com, pfid,
3120                                                 LNTF_CHECK_PARENT, true);
3121
3122                 GOTO(out, rc);
3123         }
3124
3125         if (lnr->lnr_name[0] == '.' &&
3126             (lnr->lnr_namelen == 1 || fid_seq_is_dot(fid_seq(&lnr->lnr_fid))))
3127                 GOTO(out, rc = 0);
3128
3129         idx = lfsck_find_mdt_idx_by_fid(env, lfsck, &lnr->lnr_fid);
3130         if (idx < 0)
3131                 GOTO(out, rc = idx);
3132
3133         if (idx == lfsck_dev_idx(lfsck->li_bottom)) {
3134                 if (unlikely(strcmp(lnr->lnr_name, dotdot) == 0))
3135                         GOTO(out, rc = 0);
3136
3137                 dev = lfsck->li_next;
3138         } else {
3139                 struct lfsck_tgt_desc *ltd;
3140
3141                 /* Usually, some local filesystem consistency verification
3142                  * tools can guarantee the local namespace tree consistenct.
3143                  * So the LFSCK will only verify the remote directory. */
3144                 if (unlikely(strcmp(lnr->lnr_name, dotdot) == 0)) {
3145                         rc = lfsck_namespace_trace_update(env, com, pfid,
3146                                                 LNTF_CHECK_PARENT, true);
3147
3148                         GOTO(out, rc);
3149                 }
3150
3151                 ltd = LTD_TGT(&lfsck->li_mdt_descs, idx);
3152                 if (unlikely(ltd == NULL)) {
3153                         CDEBUG(D_LFSCK, "%s: cannot talk with MDT %x which "
3154                                "did not join the namespace LFSCK\n",
3155                                lfsck_lfsck2name(lfsck), idx);
3156                         ns->ln_flags |= LF_INCOMPLETE;
3157
3158                         GOTO(out, rc = -ENODEV);
3159                 }
3160
3161                 dev = ltd->ltd_tgt;
3162         }
3163
3164         obj = lfsck_object_find_by_dev(env, dev, &lnr->lnr_fid);
3165         if (IS_ERR(obj))
3166                 GOTO(out, rc = PTR_ERR(obj));
3167
3168         cname = lfsck_name_get_const(env, lnr->lnr_name, lnr->lnr_namelen);
3169         if (dt_object_exists(obj) == 0) {
3170
3171 dangling:
3172                 rc = lfsck_namespace_check_exist(env, dir, obj, lnr->lnr_name);
3173                 if (rc == 0) {
3174                         type = LNIT_DANGLING;
3175                         rc = lfsck_namespace_repair_dangling(env, com,
3176                                                              obj, lnr);
3177                         if (rc == 0)
3178                                 repaired = true;
3179                 }
3180
3181                 GOTO(out, rc);
3182         }
3183
3184         if (!(bk->lb_param & LPF_DRYRUN) && repaired) {
3185
3186 again:
3187                 rc = lfsck_ibits_lock(env, lfsck, obj, &lh,
3188                                       MDS_INODELOCK_UPDATE |
3189                                       MDS_INODELOCK_XATTR, LCK_EX);
3190                 if (rc != 0)
3191                         GOTO(out, rc);
3192
3193                 handle = dt_trans_create(env, dev);
3194                 if (IS_ERR(handle))
3195                         GOTO(out, rc = PTR_ERR(handle));
3196
3197                 rc = lfsck_declare_namespace_exec_dir(env, obj, handle);
3198                 if (rc != 0)
3199                         GOTO(stop, rc);
3200
3201                 rc = dt_trans_start(env, dev, handle);
3202                 if (rc != 0)
3203                         GOTO(stop, rc);
3204
3205                 dt_write_lock(env, obj, 0);
3206                 dtlocked = true;
3207         }
3208
3209         rc = lfsck_namespace_check_exist(env, dir, obj, lnr->lnr_name);
3210         if (rc != 0)
3211                 GOTO(stop, rc);
3212
3213         rc = lfsck_links_read(env, obj, &ldata);
3214         if (unlikely(rc == -ENOENT)) {
3215                 if (handle != NULL) {
3216                         dt_write_unlock(env, obj);
3217                         dtlocked = false;
3218
3219                         dt_trans_stop(env, dev, handle);
3220                         handle = NULL;
3221
3222                         lfsck_ibits_unlock(&lh, LCK_EX);
3223                 }
3224
3225                 /* It may happen when the remote object has been removed,
3226                  * but the local MDT does not aware of that. */
3227                 goto dangling;
3228         } else if (rc == 0) {
3229                 count = ldata.ld_leh->leh_reccount;
3230                 rc = linkea_links_find(&ldata, cname, pfid);
3231                 if ((rc == 0) &&
3232                     (count == 1 || !S_ISDIR(lfsck_object_type(obj))))
3233                         goto record;
3234
3235                 ns->ln_flags |= LF_INCONSISTENT;
3236                 /* For sub-dir object, we cannot make sure whether the sub-dir
3237                  * back references the parent via ".." name entry correctly or
3238                  * not in the LFSCK first-stage scanning. It may be that the
3239                  * (remote) sub-dir ".." name entry has no parent FID after
3240                  * file-level backup/restore and its linkEA may be wrong.
3241                  * So under such case, we should replace the linkEA according
3242                  * to current name entry. But this needs to be done during the
3243                  * LFSCK second-stage scanning. The LFSCK will record the name
3244                  * entry for further possible using. */
3245                 remove = false;
3246                 newdata = false;
3247                 goto nodata;
3248         } else if (unlikely(rc == -EINVAL)) {
3249                 count = 1;
3250                 ns->ln_flags |= LF_INCONSISTENT;
3251                 /* The magic crashed, we are not sure whether there are more
3252                  * corrupt data in the linkea, so remove all linkea entries. */
3253                 remove = true;
3254                 newdata = true;
3255                 goto nodata;
3256         } else if (rc == -ENODATA) {
3257                 count = 1;
3258                 ns->ln_flags |= LF_UPGRADE;
3259                 remove = false;
3260                 newdata = true;
3261
3262 nodata:
3263                 if (bk->lb_param & LPF_DRYRUN) {
3264                         ns->ln_linkea_repaired++;
3265                         repaired = true;
3266                         log = true;
3267                         goto record;
3268                 }
3269
3270                 if (!lustre_handle_is_used(&lh))
3271                         goto again;
3272
3273                 if (remove) {
3274                         LASSERT(newdata);
3275
3276                         rc = dt_xattr_del(env, obj, XATTR_NAME_LINK, handle,
3277                                           BYPASS_CAPA);
3278                         if (rc != 0)
3279                                 GOTO(stop, rc);
3280                 }
3281
3282                 if (newdata) {
3283                         rc = linkea_data_new(&ldata,
3284                                         &lfsck_env_info(env)->lti_linkea_buf);
3285                         if (rc != 0)
3286                                 GOTO(stop, rc);
3287                 }
3288
3289                 rc = linkea_add_buf(&ldata, cname, pfid);
3290                 if (rc != 0)
3291                         GOTO(stop, rc);
3292
3293                 rc = lfsck_links_write(env, obj, &ldata, handle);
3294                 if (rc != 0)
3295                         GOTO(stop, rc);
3296
3297                 count = ldata.ld_leh->leh_reccount;
3298                 if (!S_ISDIR(lfsck_object_type(obj)) ||
3299                     !dt_object_remote(obj)) {
3300                         ns->ln_linkea_repaired++;
3301                         repaired = true;
3302                         log = true;
3303                 }
3304         } else {
3305                 GOTO(stop, rc);
3306         }
3307
3308 record:
3309         LASSERT(count > 0);
3310
3311         rc = dt_attr_get(env, obj, la, BYPASS_CAPA);
3312         if (rc != 0)
3313                 GOTO(stop, rc);
3314
3315         if ((count == 1 && la->la_nlink == 1) ||
3316             S_ISDIR(lfsck_object_type(obj)))
3317                 /* Usually, it is for single linked object or dir, do nothing.*/
3318                 GOTO(stop, rc);
3319
3320         /* Following modification will be in another transaction.  */
3321         if (handle != NULL) {
3322                 dt_write_unlock(env, obj);
3323                 dtlocked = false;
3324
3325                 dt_trans_stop(env, dev, handle);
3326                 handle = NULL;
3327
3328                 lfsck_ibits_unlock(&lh, LCK_EX);
3329         }
3330
3331         ns->ln_mul_linked_checked++;
3332         rc = lfsck_namespace_trace_update(env, com, &lnr->lnr_fid,
3333                                           LNTF_CHECK_LINKEA, true);
3334
3335         GOTO(out, rc);
3336
3337 stop:
3338         if (dtlocked)
3339                 dt_write_unlock(env, obj);
3340
3341         if (handle != NULL && !IS_ERR(handle))
3342                 dt_trans_stop(env, dev, handle);
3343
3344 out:
3345         lfsck_ibits_unlock(&lh, LCK_EX);
3346         down_write(&com->lc_sem);
3347         if (rc < 0) {
3348                 CDEBUG(D_LFSCK, "%s: namespace LFSCK assistant fail to handle "
3349                        "the entry: "DFID", parent "DFID", name %.*s: rc = %d\n",
3350                        lfsck_lfsck2name(lfsck), PFID(&lnr->lnr_fid),
3351                        PFID(lfsck_dto2fid(lnr->lnr_obj)),
3352                        lnr->lnr_namelen, lnr->lnr_name, rc);
3353
3354                 lfsck_namespace_record_failure(env, lfsck, ns);
3355                 if (!(bk->lb_param & LPF_FAILOUT))
3356                         rc = 0;
3357         } else {
3358                 if (log)
3359                         CDEBUG(D_LFSCK, "%s: namespace LFSCK assistant "
3360                                "repaired the entry: "DFID", parent "DFID
3361                                ", name %.*s\n", lfsck_lfsck2name(lfsck),
3362                                PFID(&lnr->lnr_fid),
3363                                PFID(lfsck_dto2fid(lnr->lnr_obj)),
3364                                lnr->lnr_namelen, lnr->lnr_name);
3365
3366                 if (repaired) {
3367                         ns->ln_items_repaired++;
3368
3369                         switch (type) {
3370                         case LNIT_DANGLING:
3371                                 ns->ln_dangling_repaired++;
3372                                 break;
3373                         default:
3374                                 break;
3375                         }
3376
3377                         if (bk->lb_param & LPF_DRYRUN &&
3378                             lfsck_pos_is_zero(&ns->ln_pos_first_inconsistent))
3379                                 lfsck_pos_fill(env, lfsck,
3380                                                &ns->ln_pos_first_inconsistent,
3381                                                false);
3382                 }
3383                 rc = 0;
3384         }
3385         up_write(&com->lc_sem);
3386
3387         if (obj != NULL && !IS_ERR(obj))
3388                 lfsck_object_put(env, obj);
3389         return rc;
3390 }
3391
3392 static int lfsck_namespace_assistant_handler_p2(const struct lu_env *env,
3393                                                 struct lfsck_component *com)
3394 {
3395         struct lfsck_instance   *lfsck  = com->lc_lfsck;
3396         struct ptlrpc_thread    *thread = &lfsck->li_thread;
3397         struct lfsck_bookmark   *bk     = &lfsck->li_bookmark_ram;
3398         struct lfsck_namespace  *ns     = com->lc_file_ram;
3399         struct dt_object        *obj    = com->lc_obj;
3400         const struct dt_it_ops  *iops   = &obj->do_index_ops->dio_it;
3401         struct dt_object        *target;
3402         struct dt_it            *di;
3403         struct dt_key           *key;
3404         struct lu_fid            fid;
3405         int                      rc;
3406         __u8                     flags  = 0;
3407         ENTRY;
3408
3409         CDEBUG(D_LFSCK, "%s: namespace LFSCK phase2 scan start\n",
3410                lfsck_lfsck2name(lfsck));
3411
3412         com->lc_new_checked = 0;
3413         com->lc_new_scanned = 0;
3414         com->lc_time_last_checkpoint = cfs_time_current();
3415         com->lc_time_next_checkpoint = com->lc_time_last_checkpoint +
3416                                 cfs_time_seconds(LFSCK_CHECKPOINT_INTERVAL);
3417
3418         di = iops->init(env, obj, 0, BYPASS_CAPA);
3419         if (IS_ERR(di))
3420                 RETURN(PTR_ERR(di));
3421
3422         fid_cpu_to_be(&fid, &ns->ln_fid_latest_scanned_phase2);
3423         rc = iops->get(env, di, (const struct dt_key *)&fid);
3424         if (rc < 0)
3425                 GOTO(fini, rc);
3426
3427         /* Skip the start one, which either has been processed or non-exist. */
3428         rc = iops->next(env, di);
3429         if (rc != 0)
3430                 GOTO(put, rc);
3431
3432         do {
3433                 if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_DELAY3) &&
3434                     cfs_fail_val > 0) {
3435                         struct l_wait_info lwi;
3436
3437                         lwi = LWI_TIMEOUT(cfs_time_seconds(cfs_fail_val),
3438                                           NULL, NULL);
3439                         l_wait_event(thread->t_ctl_waitq,
3440                                      !thread_is_running(thread),
3441                                      &lwi);
3442
3443                         if (unlikely(!thread_is_running(thread)))
3444                                 GOTO(put, rc = 0);
3445                 }
3446
3447                 key = iops->key(env, di);
3448                 fid_be_to_cpu(&fid, (const struct lu_fid *)key);
3449                 if (!fid_is_sane(&fid)) {
3450                         rc = 0;
3451                         goto checkpoint;
3452                 }
3453
3454                 target = lfsck_object_find(env, lfsck, &fid);
3455                 if (IS_ERR(target)) {
3456                         rc = PTR_ERR(target);
3457                         goto checkpoint;
3458                 }
3459
3460                 if (dt_object_exists(target)) {
3461                         rc = iops->rec(env, di, (struct dt_rec *)&flags, 0);
3462                         if (rc == 0) {
3463                                 rc = lfsck_namespace_double_scan_one(env, com,
3464                                                                 target, flags);
3465                                 if (rc == -ENOENT)
3466                                         rc = 0;
3467                         }
3468                 }
3469
3470                 lfsck_object_put(env, target);
3471
3472 checkpoint:
3473                 down_write(&com->lc_sem);
3474                 com->lc_new_checked++;
3475                 com->lc_new_scanned++;
3476                 ns->ln_fid_latest_scanned_phase2 = fid;
3477                 if (rc > 0)
3478                         ns->ln_objs_repaired_phase2++;
3479                 else if (rc < 0)
3480                         ns->ln_objs_failed_phase2++;
3481                 up_write(&com->lc_sem);
3482
3483                 if (rc < 0 && bk->lb_param & LPF_FAILOUT)
3484                         GOTO(put, rc);
3485
3486                 if (unlikely(cfs_time_beforeq(com->lc_time_next_checkpoint,
3487                                               cfs_time_current())) &&
3488                     com->lc_new_checked != 0) {
3489                         down_write(&com->lc_sem);
3490                         ns->ln_run_time_phase2 +=
3491                                 cfs_duration_sec(cfs_time_current() +
3492                                 HALF_SEC - com->lc_time_last_checkpoint);
3493                         ns->ln_time_last_checkpoint = cfs_time_current_sec();
3494                         ns->ln_objs_checked_phase2 += com->lc_new_checked;
3495                         com->lc_new_checked = 0;
3496                         rc = lfsck_namespace_store(env, com, false);
3497                         up_write(&com->lc_sem);
3498                         if (rc != 0)
3499                                 GOTO(put, rc);
3500
3501                         com->lc_time_last_checkpoint = cfs_time_current();
3502                         com->lc_time_next_checkpoint =
3503                                 com->lc_time_last_checkpoint +
3504                                 cfs_time_seconds(LFSCK_CHECKPOINT_INTERVAL);
3505                 }
3506
3507                 lfsck_control_speed_by_self(com);
3508                 if (unlikely(!thread_is_running(thread)))
3509                         GOTO(put, rc = 0);
3510
3511                 rc = iops->next(env, di);
3512         } while (rc == 0);
3513
3514         GOTO(put, rc);
3515
3516 put:
3517         iops->put(env, di);
3518
3519 fini:
3520         iops->fini(env, di);
3521
3522         CDEBUG(D_LFSCK, "%s: namespace LFSCK phase2 scan stop: rc = %d\n",
3523                lfsck_lfsck2name(lfsck), rc);
3524
3525         return rc;
3526 }
3527
3528 static void lfsck_namespace_assistant_fill_pos(const struct lu_env *env,
3529                                                struct lfsck_component *com,
3530                                                struct lfsck_position *pos)
3531 {
3532         struct lfsck_assistant_data     *lad = com->lc_data;
3533         struct lfsck_namespace_req      *lnr;
3534
3535         if (list_empty(&lad->lad_req_list))
3536                 return;
3537
3538         lnr = list_entry(lad->lad_req_list.next,
3539                          struct lfsck_namespace_req,
3540                          lnr_lar.lar_list);
3541         pos->lp_oit_cookie = lnr->lnr_oit_cookie;
3542         pos->lp_dir_cookie = lnr->lnr_dir_cookie - 1;
3543         pos->lp_dir_parent = *lfsck_dto2fid(lnr->lnr_obj);
3544 }
3545
3546 static int lfsck_namespace_double_scan_result(const struct lu_env *env,
3547                                               struct lfsck_component *com,
3548                                               int rc)
3549 {
3550         struct lfsck_instance   *lfsck  = com->lc_lfsck;
3551         struct lfsck_namespace  *ns     = com->lc_file_ram;
3552
3553         down_write(&com->lc_sem);
3554         ns->ln_run_time_phase2 += cfs_duration_sec(cfs_time_current() +
3555                                 HALF_SEC - lfsck->li_time_last_checkpoint);
3556         ns->ln_time_last_checkpoint = cfs_time_current_sec();
3557         ns->ln_objs_checked_phase2 += com->lc_new_checked;
3558         com->lc_new_checked = 0;
3559
3560         if (rc > 0) {
3561                 if (ns->ln_flags & LF_INCOMPLETE)
3562                         ns->ln_status = LS_PARTIAL;
3563                 else
3564                         ns->ln_status = LS_COMPLETED;
3565                 if (!(lfsck->li_bookmark_ram.lb_param & LPF_DRYRUN))
3566                         ns->ln_flags &= ~(LF_SCANNED_ONCE | LF_INCONSISTENT);
3567                 ns->ln_time_last_complete = ns->ln_time_last_checkpoint;
3568                 ns->ln_success_count++;
3569         } else if (rc == 0) {
3570                 ns->ln_status = lfsck->li_status;
3571                 if (ns->ln_status == 0)
3572                         ns->ln_status = LS_STOPPED;
3573         } else {
3574                 ns->ln_status = LS_FAILED;
3575         }
3576
3577         rc = lfsck_namespace_store(env, com, false);
3578         up_write(&com->lc_sem);
3579
3580         return rc;
3581 }
3582
3583 static void lfsck_namespace_assistant_sync_failures(const struct lu_env *env,
3584                                                     struct lfsck_component *com,
3585                                                     struct lfsck_request *lr)
3586 {
3587         /* XXX: TBD */
3588 }
3589
3590 struct lfsck_assistant_operations lfsck_namespace_assistant_ops = {
3591         .la_handler_p1          = lfsck_namespace_assistant_handler_p1,
3592         .la_handler_p2          = lfsck_namespace_assistant_handler_p2,
3593         .la_fill_pos            = lfsck_namespace_assistant_fill_pos,
3594         .la_double_scan_result  = lfsck_namespace_double_scan_result,
3595         .la_req_fini            = lfsck_namespace_assistant_req_fini,
3596         .la_sync_failures       = lfsck_namespace_assistant_sync_failures,
3597 };
3598
3599 /**
3600  * Verify the specified linkEA entry for the given directory object.
3601  * If the object has no such linkEA entry or it has more other linkEA
3602  * entries, then re-generate the linkEA with the given information.
3603  *
3604  * \param[in] env       pointer to the thread context
3605  * \param[in] dev       pointer to the dt_device
3606  * \param[in] obj       pointer to the dt_object to be handled
3607  * \param[in] cname     the name for the child in the parent directory
3608  * \param[in] pfid      the parent directory's FID for the linkEA
3609  *
3610  * \retval              0 for success
3611  * \retval              negative error number on failure
3612  */
3613 int lfsck_verify_linkea(const struct lu_env *env, struct dt_device *dev,
3614                         struct dt_object *obj, const struct lu_name *cname,
3615                         const struct lu_fid *pfid)
3616 {
3617         struct linkea_data       ldata  = { 0 };
3618         struct lu_buf            linkea_buf;
3619         struct thandle          *th;
3620         int                      rc;
3621         int                      fl     = LU_XATTR_CREATE;
3622         bool                     dirty  = false;
3623         ENTRY;
3624
3625         LASSERT(S_ISDIR(lfsck_object_type(obj)));
3626
3627         rc = lfsck_links_read(env, obj, &ldata);
3628         if (rc == -ENODATA) {
3629                 dirty = true;
3630         } else if (rc == 0) {
3631                 fl = LU_XATTR_REPLACE;
3632                 if (ldata.ld_leh->leh_reccount != 1) {
3633                         dirty = true;
3634                 } else {
3635                         rc = linkea_links_find(&ldata, cname, pfid);
3636                         if (rc != 0)
3637                                 dirty = true;
3638                 }
3639         }
3640
3641         if (!dirty)
3642                 RETURN(rc);
3643
3644         rc = linkea_data_new(&ldata, &lfsck_env_info(env)->lti_linkea_buf);
3645         if (rc != 0)
3646                 RETURN(rc);
3647
3648         rc = linkea_add_buf(&ldata, cname, pfid);
3649         if (rc != 0)
3650                 RETURN(rc);
3651
3652         lfsck_buf_init(&linkea_buf, ldata.ld_buf->lb_buf,
3653                        ldata.ld_leh->leh_len);
3654         th = dt_trans_create(env, dev);
3655         if (IS_ERR(th))
3656                 RETURN(PTR_ERR(th));
3657
3658         rc = dt_declare_xattr_set(env, obj, &linkea_buf,
3659                                   XATTR_NAME_LINK, fl, th);
3660         if (rc != 0)
3661                 GOTO(stop, rc);
3662
3663         rc = dt_trans_start_local(env, dev, th);
3664         if (rc != 0)
3665                 GOTO(stop, rc);
3666
3667         dt_write_lock(env, obj, 0);
3668         rc = dt_xattr_set(env, obj, &linkea_buf,
3669                           XATTR_NAME_LINK, fl, th, BYPASS_CAPA);
3670         dt_write_unlock(env, obj);
3671
3672         GOTO(stop, rc);
3673
3674 stop:
3675         dt_trans_stop(env, dev, th);
3676         return rc;
3677 }
3678
3679 /**
3680  * Get the name and parent directory's FID from the first linkEA entry.
3681  *
3682  * \param[in] env       pointer to the thread context
3683  * \param[in] obj       pointer to the object which get linkEA from
3684  * \param[out] name     pointer to the buffer to hold the name
3685  *                      in the first linkEA entry
3686  * \param[out] pfid     pointer to the buffer to hold the parent
3687  *                      directory's FID in the first linkEA entry
3688  *
3689  * \retval              0 for success
3690  * \retval              negative error number on failure
3691  */
3692 int lfsck_links_get_first(const struct lu_env *env, struct dt_object *obj,
3693                           char *name, struct lu_fid *pfid)
3694 {
3695         struct lu_name           *cname = &lfsck_env_info(env)->lti_name;
3696         struct linkea_data        ldata = { 0 };
3697         int                       rc;
3698
3699         rc = lfsck_links_read(env, obj, &ldata);
3700         if (rc != 0)
3701                 return rc;
3702
3703         linkea_first_entry(&ldata);
3704         if (ldata.ld_lee == NULL)
3705                 return -ENODATA;
3706
3707         linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen, cname, pfid);
3708         /* To guarantee the 'name' is terminated with '0'. */
3709         memcpy(name, cname->ln_name, cname->ln_namelen);
3710         name[cname->ln_namelen] = 0;
3711
3712         return 0;
3713 }
3714
3715 /**
3716  * Remove the name entry from the parent directory.
3717  *
3718  * No need to care about the object referenced by the name entry,
3719  * either the name entry is invalid or redundant, or the referenced
3720  * object has been processed has been or will be handled by others.
3721  *
3722  * \param[in] env       pointer to the thread context
3723  * \param[in] lfsck     pointer to the lfsck instance
3724  * \param[in] parent    pointer to the lost+found object
3725  * \param[in] name      the name for the name entry to be removed
3726  * \param[in] type      the type for the name entry to be removed
3727  *
3728  * \retval              0 for success
3729  * \retval              negative error number on failure
3730  */
3731 int lfsck_remove_name_entry(const struct lu_env *env,
3732                             struct lfsck_instance *lfsck,
3733                             struct dt_object *parent,
3734                             const char *name, __u32 type)
3735 {
3736         struct dt_device        *dev    = lfsck->li_next;
3737         struct thandle          *th;
3738         struct lustre_handle     lh     = { 0 };
3739         int                      rc;
3740         ENTRY;
3741
3742         rc = lfsck_ibits_lock(env, lfsck, parent, &lh,
3743                               MDS_INODELOCK_UPDATE, LCK_EX);
3744         if (rc != 0)
3745                 RETURN(rc);
3746
3747         th = dt_trans_create(env, dev);
3748         if (IS_ERR(th))
3749                 GOTO(unlock, rc = PTR_ERR(th));
3750
3751         rc = dt_declare_delete(env, parent, (const struct dt_key *)name, th);
3752         if (rc != 0)
3753                 GOTO(stop, rc);
3754
3755         if (S_ISDIR(type)) {
3756                 rc = dt_declare_ref_del(env, parent, th);
3757                 if (rc != 0)
3758                         GOTO(stop, rc);
3759         }
3760
3761         rc = dt_trans_start(env, dev, th);
3762         if (rc != 0)
3763                 GOTO(stop, rc);
3764
3765         rc = dt_delete(env, parent, (const struct dt_key *)name, th,
3766                        BYPASS_CAPA);
3767         if (rc != 0)
3768                 GOTO(stop, rc);
3769
3770         if (S_ISDIR(type)) {
3771                 dt_write_lock(env, parent, 0);
3772                 rc = dt_ref_del(env, parent, th);
3773                 dt_write_unlock(env, parent);
3774         }
3775
3776         GOTO(stop, rc);
3777
3778 stop:
3779         dt_trans_stop(env, dev, th);
3780
3781 unlock:
3782         lfsck_ibits_unlock(&lh, LCK_EX);
3783
3784         CDEBUG(D_LFSCK, "%s: remove name entry "DFID"/%s "
3785                "with type %o: rc = %d\n", lfsck_lfsck2name(lfsck),
3786                PFID(lfsck_dto2fid(parent)), name, type, rc);
3787
3788         return rc;
3789 }
3790
3791 /**
3792  * Update the object's name entry with the given FID.
3793  *
3794  * \param[in] env       pointer to the thread context
3795  * \param[in] lfsck     pointer to the lfsck instance
3796  * \param[in] parent    pointer to the parent directory that holds
3797  *                      the name entry
3798  * \param[in] name      the name for the entry to be updated
3799  * \param[in] pfid      the new PFID for the name entry
3800  * \param[in] type      the type for the name entry to be updated
3801  *
3802  * \retval              0 for success
3803  * \retval              negative error number on failure
3804  */
3805 int lfsck_update_name_entry(const struct lu_env *env,
3806                             struct lfsck_instance *lfsck,
3807                             struct dt_object *parent, const char *name,
3808                             const struct lu_fid *pfid, __u32 type)
3809 {
3810         struct dt_insert_rec    *rec    = &lfsck_env_info(env)->lti_dt_rec;
3811         struct dt_device        *dev    = lfsck->li_next;
3812         struct lustre_handle     lh     = { 0 };
3813         struct thandle          *th;
3814         int                      rc;
3815         bool                     exists = true;
3816         ENTRY;
3817
3818         rc = lfsck_ibits_lock(env, lfsck, parent, &lh,
3819                               MDS_INODELOCK_UPDATE, LCK_EX);
3820         if (rc != 0)
3821                 RETURN(rc);
3822
3823         th = dt_trans_create(env, dev);
3824         if (IS_ERR(th))
3825                 GOTO(unlock, rc = PTR_ERR(th));
3826
3827         rc = dt_declare_delete(env, parent, (const struct dt_key *)name, th);
3828         if (rc != 0)
3829                 GOTO(stop, rc);
3830
3831         rec->rec_type = type;
3832         rec->rec_fid = pfid;
3833         rc = dt_declare_insert(env, parent, (const struct dt_rec *)rec,
3834                                (const struct dt_key *)name, th);
3835         if (rc != 0)
3836                 GOTO(stop, rc);
3837
3838         rc = dt_declare_ref_add(env, parent, th);
3839         if (rc != 0)
3840                 GOTO(stop, rc);
3841
3842         rc = dt_trans_start(env, dev, th);
3843         if (rc != 0)
3844                 GOTO(stop, rc);
3845
3846         rc = dt_delete(env, parent, (const struct dt_key *)name, th,
3847                        BYPASS_CAPA);
3848         if (rc == -ENOENT) {
3849                 exists = false;
3850                 rc = 0;
3851         }
3852
3853         if (rc != 0)
3854                 GOTO(stop, rc);
3855
3856         rc = dt_insert(env, parent, (const struct dt_rec *)rec,
3857                        (const struct dt_key *)name, th, BYPASS_CAPA, 1);
3858         if (rc == 0 && S_ISDIR(type) && !exists) {
3859                 dt_write_lock(env, parent, 0);
3860                 rc = dt_ref_add(env, parent, th);
3861                 dt_write_unlock(env, parent);
3862         }
3863
3864         GOTO(stop, rc);
3865
3866 stop:
3867         dt_trans_stop(env, dev, th);
3868
3869 unlock:
3870         lfsck_ibits_unlock(&lh, LCK_EX);
3871
3872         CDEBUG(D_LFSCK, "%s: update name entry "DFID"/%s with the FID "DFID
3873                " and the type %o: rc = %d\n", lfsck_lfsck2name(lfsck),
3874                PFID(lfsck_dto2fid(parent)), name, PFID(pfid), type, rc);
3875
3876         return rc;
3877 }
3878
3879 int lfsck_namespace_setup(const struct lu_env *env,
3880                           struct lfsck_instance *lfsck)
3881 {
3882         struct lfsck_component  *com;
3883         struct lfsck_namespace  *ns;
3884         struct dt_object        *root = NULL;
3885         struct dt_object        *obj;
3886         int                      rc;
3887         ENTRY;
3888
3889         LASSERT(lfsck->li_master);
3890
3891         OBD_ALLOC_PTR(com);
3892         if (com == NULL)
3893                 RETURN(-ENOMEM);
3894
3895         INIT_LIST_HEAD(&com->lc_link);
3896         INIT_LIST_HEAD(&com->lc_link_dir);
3897         init_rwsem(&com->lc_sem);
3898         atomic_set(&com->lc_ref, 1);
3899         com->lc_lfsck = lfsck;
3900         com->lc_type = LFSCK_TYPE_NAMESPACE;
3901         com->lc_ops = &lfsck_namespace_ops;
3902         com->lc_data = lfsck_assistant_data_init(
3903                         &lfsck_namespace_assistant_ops,
3904                         "lfsck_namespace");
3905         if (com->lc_data == NULL)
3906                 GOTO(out, rc = -ENOMEM);
3907
3908         com->lc_file_size = sizeof(struct lfsck_namespace);
3909         OBD_ALLOC(com->lc_file_ram, com->lc_file_size);
3910         if (com->lc_file_ram == NULL)
3911                 GOTO(out, rc = -ENOMEM);
3912
3913         OBD_ALLOC(com->lc_file_disk, com->lc_file_size);
3914         if (com->lc_file_disk == NULL)
3915                 GOTO(out, rc = -ENOMEM);
3916
3917         root = dt_locate(env, lfsck->li_bottom, &lfsck->li_local_root_fid);
3918         if (IS_ERR(root))
3919                 GOTO(out, rc = PTR_ERR(root));
3920
3921         if (unlikely(!dt_try_as_dir(env, root)))
3922                 GOTO(out, rc = -ENOTDIR);
3923
3924         obj = local_index_find_or_create(env, lfsck->li_los, root,
3925                                          lfsck_namespace_name,
3926                                          S_IFREG | S_IRUGO | S_IWUSR,
3927                                          &dt_lfsck_features);
3928         if (IS_ERR(obj))
3929                 GOTO(out, rc = PTR_ERR(obj));
3930
3931         com->lc_obj = obj;
3932         rc = obj->do_ops->do_index_try(env, obj, &dt_lfsck_features);
3933         if (rc != 0)
3934                 GOTO(out, rc);
3935
3936         rc = lfsck_namespace_load(env, com);
3937         if (rc > 0)
3938                 rc = lfsck_namespace_reset(env, com, true);
3939         else if (rc == -ENODATA)
3940                 rc = lfsck_namespace_init(env, com);
3941         if (rc != 0)
3942                 GOTO(out, rc);
3943
3944         ns = com->lc_file_ram;
3945         switch (ns->ln_status) {
3946         case LS_INIT:
3947         case LS_COMPLETED:
3948         case LS_FAILED:
3949         case LS_STOPPED:
3950                 spin_lock(&lfsck->li_lock);
3951                 list_add_tail(&com->lc_link, &lfsck->li_list_idle);
3952                 spin_unlock(&lfsck->li_lock);
3953                 break;
3954         default:
3955                 CERROR("%s: unknown lfsck_namespace status %d\n",
3956                        lfsck_lfsck2name(lfsck), ns->ln_status);
3957                 /* fall through */
3958         case LS_SCANNING_PHASE1:
3959         case LS_SCANNING_PHASE2:
3960                 /* No need to store the status to disk right now.
3961                  * If the system crashed before the status stored,
3962                  * it will be loaded back when next time. */
3963                 ns->ln_status = LS_CRASHED;
3964                 /* fall through */
3965         case LS_PAUSED:
3966         case LS_CRASHED:
3967                 spin_lock(&lfsck->li_lock);
3968                 list_add_tail(&com->lc_link, &lfsck->li_list_scan);
3969                 list_add_tail(&com->lc_link_dir, &lfsck->li_list_dir);
3970                 spin_unlock(&lfsck->li_lock);
3971                 break;
3972         }
3973
3974         GOTO(out, rc = 0);
3975
3976 out:
3977         if (root != NULL && !IS_ERR(root))
3978                 lu_object_put(env, &root->do_lu);
3979         if (rc != 0) {
3980                 lfsck_component_cleanup(env, com);
3981                 CERROR("%s: fail to init namespace LFSCK component: rc = %d\n",
3982                        lfsck_lfsck2name(lfsck), rc);
3983         }
3984         return rc;
3985 }