xref: /linux/fs/xfs/scrub/dir_repair.c (revision 546b928da0427b0d6c663cbb992bd7bfa9ac7971)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) 2020-2024 Oracle.  All Rights Reserved.
4  * Author: Darrick J. Wong <djwong@kernel.org>
5  */
6 #include "xfs_platform.h"
7 #include "xfs_fs.h"
8 #include "xfs_shared.h"
9 #include "xfs_format.h"
10 #include "xfs_trans_resv.h"
11 #include "xfs_mount.h"
12 #include "xfs_defer.h"
13 #include "xfs_bit.h"
14 #include "xfs_log_format.h"
15 #include "xfs_trans.h"
16 #include "xfs_sb.h"
17 #include "xfs_inode.h"
18 #include "xfs_icache.h"
19 #include "xfs_da_format.h"
20 #include "xfs_da_btree.h"
21 #include "xfs_dir2.h"
22 #include "xfs_dir2_priv.h"
23 #include "xfs_bmap.h"
24 #include "xfs_quota.h"
25 #include "xfs_bmap_btree.h"
26 #include "xfs_trans_space.h"
27 #include "xfs_bmap_util.h"
28 #include "xfs_exchmaps.h"
29 #include "xfs_exchrange.h"
30 #include "xfs_ag.h"
31 #include "xfs_parent.h"
32 #include "scrub/xfs_scrub.h"
33 #include "scrub/scrub.h"
34 #include "scrub/common.h"
35 #include "scrub/trace.h"
36 #include "scrub/repair.h"
37 #include "scrub/tempfile.h"
38 #include "scrub/tempexch.h"
39 #include "scrub/xfile.h"
40 #include "scrub/xfarray.h"
41 #include "scrub/xfblob.h"
42 #include "scrub/iscan.h"
43 #include "scrub/readdir.h"
44 #include "scrub/reap.h"
45 #include "scrub/findparent.h"
46 #include "scrub/orphanage.h"
47 #include "scrub/listxattr.h"
48 
49 /*
50  * Directory Repair
51  * ================
52  *
53  * We repair directories by reading the directory data blocks looking for
54  * directory entries that look salvageable (name passes verifiers, entry points
55  * to a valid allocated inode, etc).  Each entry worth salvaging is stashed in
56  * memory, and the stashed entries are periodically replayed into a temporary
57  * directory to constrain memory use.  Batching the construction of the
58  * temporary directory in this fashion reduces lock cycling of the directory
59  * being repaired and the temporary directory, and will later become important
60  * for parent pointer scanning.
61  *
62  * If parent pointers are enabled on this filesystem, we instead reconstruct
63  * the directory by visiting each parent pointer of each file in the filesystem
64  * and translating the relevant parent pointer records into dirents.  In this
65  * case, it is advantageous to stash all directory entries created from parent
66  * pointers for a single child file before replaying them into the temporary
67  * directory.  To save memory, the live filesystem scan reuses the findparent
68  * fields.  Directory repair chooses either parent pointer scanning or
69  * directory entry salvaging, but not both.
70  *
71  * Directory entries added to the temporary directory do not elevate the link
72  * counts of the inodes found.  When salvaging completes, the remaining stashed
73  * entries are replayed to the temporary directory.  An atomic mapping exchange
74  * is used to commit the new directory blocks to the directory being repaired.
75  * This will disrupt readdir cursors.
76  *
77  * Locking Issues
78  * --------------
79  *
80  * If /a, /a/b, and /c are all directories, the VFS does not take i_rwsem on
81  * /a/b for a "mv /a/b /c/" operation.  This means that only b's ILOCK protects
82  * b's dotdot update.  This is in contrast to every other dotdot update (link,
83  * remove, mkdir).  If the repair code drops the ILOCK, it must either
84  * revalidate the dotdot entry or use dirent hooks to capture updates from
85  * other threads.
86  */
87 
88 /* Create a dirent in the tempdir. */
89 #define XREP_DIRENT_ADD		(1)
90 
91 /* Remove a dirent from the tempdir. */
92 #define XREP_DIRENT_REMOVE	(2)
93 
94 /* Directory entry to be restored in the new directory. */
95 struct xrep_dirent {
96 	/* Cookie for retrieval of the dirent name. */
97 	xfblob_cookie		name_cookie;
98 
99 	/* Target inode number. */
100 	xfs_ino_t		ino;
101 
102 	/* Length of the dirent name. */
103 	uint8_t			namelen;
104 
105 	/* File type of the dirent. */
106 	uint8_t			ftype;
107 
108 	/* XREP_DIRENT_{ADD,REMOVE} */
109 	uint8_t			action;
110 };
111 
112 /*
113  * Stash up to 8 pages of recovered dirent data in dir_entries and dir_names
114  * before we write them to the temp dir.
115  */
116 #define XREP_DIR_MAX_STASH_BYTES	(PAGE_SIZE * 8)
117 
118 struct xrep_dir {
119 	struct xfs_scrub	*sc;
120 
121 	/* Fixed-size array of xrep_dirent structures. */
122 	struct xfarray		*dir_entries;
123 
124 	/* Blobs containing directory entry names. */
125 	struct xfblob		*dir_names;
126 
127 	/* Information for exchanging data forks at the end. */
128 	struct xrep_tempexch	tx;
129 
130 	/* Preallocated args struct for performing dir operations */
131 	struct xfs_da_args	args;
132 
133 	/*
134 	 * Information used to scan the filesystem to find the inumber of the
135 	 * dotdot entry for this directory.  For directory salvaging when
136 	 * parent pointers are not enabled, we use the findparent_* functions
137 	 * on this object and access only the parent_ino field directly.
138 	 *
139 	 * When parent pointers are enabled, however, the pptr scanner uses the
140 	 * iscan, hooks, lock, and parent_ino fields of this object directly.
141 	 * @pscan.lock coordinates access to dir_entries, dir_names,
142 	 * parent_ino, subdirs, dirents, and args.  This reduces the memory
143 	 * requirements of this structure.
144 	 */
145 	struct xrep_parent_scan_info pscan;
146 
147 	/*
148 	 * Context information for attaching this directory to the lost+found
149 	 * if this directory does not have a parent.
150 	 */
151 	struct xrep_adoption	adoption;
152 
153 	/* How many subdirectories did we find? */
154 	uint64_t		subdirs;
155 
156 	/* How many dirents did we find? */
157 	unsigned int		dirents;
158 
159 	/* Should we move this directory to the orphanage? */
160 	bool			needs_adoption;
161 
162 	/* Directory entry name, plus the trailing null. */
163 	struct xfs_name		xname;
164 	unsigned char		namebuf[MAXNAMELEN];
165 };
166 
167 /* Tear down all the incore stuff we created. */
168 static void
xrep_dir_teardown(struct xfs_scrub * sc)169 xrep_dir_teardown(
170 	struct xfs_scrub	*sc)
171 {
172 	struct xrep_dir		*rd = sc->buf;
173 
174 	xrep_findparent_scan_teardown(&rd->pscan);
175 	if (rd->dir_names)
176 		xfblob_destroy(rd->dir_names);
177 	rd->dir_names = NULL;
178 	if (rd->dir_entries)
179 		xfarray_destroy(rd->dir_entries);
180 	rd->dir_entries = NULL;
181 }
182 
183 /* Set up for a directory repair. */
184 int
xrep_setup_directory(struct xfs_scrub * sc)185 xrep_setup_directory(
186 	struct xfs_scrub	*sc)
187 {
188 	struct xrep_dir		*rd;
189 	int			error;
190 
191 	xchk_fsgates_enable(sc, XCHK_FSGATES_DIRENTS);
192 
193 	error = xrep_orphanage_try_create(sc);
194 	if (error)
195 		return error;
196 
197 	error = xrep_tempfile_create(sc, S_IFDIR);
198 	if (error)
199 		return error;
200 
201 	rd = kvzalloc_obj(struct xrep_dir, XCHK_GFP_FLAGS);
202 	if (!rd)
203 		return -ENOMEM;
204 	rd->sc = sc;
205 	rd->xname.name = rd->namebuf;
206 	sc->buf = rd;
207 
208 	return 0;
209 }
210 
211 /*
212  * Look up the dotdot entry and confirm that it's really the parent.
213  * Returns NULLFSINO if we don't know what to do.
214  */
215 static inline xfs_ino_t
xrep_dir_lookup_parent(struct xrep_dir * rd)216 xrep_dir_lookup_parent(
217 	struct xrep_dir		*rd)
218 {
219 	struct xfs_scrub	*sc = rd->sc;
220 	xfs_ino_t		ino;
221 	int			error;
222 
223 	error = xfs_dir_lookup(sc->tp, sc->ip, &xfs_name_dotdot, &ino, NULL);
224 	if (error)
225 		return NULLFSINO;
226 	if (!xfs_verify_dir_ino(sc->mp, ino))
227 		return NULLFSINO;
228 
229 	error = xrep_findparent_confirm(sc, &ino);
230 	if (error)
231 		return NULLFSINO;
232 
233 	return ino;
234 }
235 
236 /*
237  * Look up '..' in the dentry cache and confirm that it's really the parent.
238  * Returns NULLFSINO if the dcache misses or if the hit is implausible.
239  */
240 static inline xfs_ino_t
xrep_dir_dcache_parent(struct xrep_dir * rd)241 xrep_dir_dcache_parent(
242 	struct xrep_dir		*rd)
243 {
244 	struct xfs_scrub	*sc = rd->sc;
245 	xfs_ino_t		parent_ino;
246 	int			error;
247 
248 	parent_ino = xrep_findparent_from_dcache(sc);
249 	if (parent_ino == NULLFSINO)
250 		return parent_ino;
251 
252 	error = xrep_findparent_confirm(sc, &parent_ino);
253 	if (error)
254 		return NULLFSINO;
255 
256 	return parent_ino;
257 }
258 
259 /* Try to find the parent of the directory being repaired. */
260 STATIC int
xrep_dir_find_parent(struct xrep_dir * rd)261 xrep_dir_find_parent(
262 	struct xrep_dir		*rd)
263 {
264 	xfs_ino_t		ino;
265 
266 	ino = xrep_findparent_self_reference(rd->sc);
267 	if (ino != NULLFSINO) {
268 		xrep_findparent_scan_finish_early(&rd->pscan, ino);
269 		return 0;
270 	}
271 
272 	ino = xrep_dir_dcache_parent(rd);
273 	if (ino != NULLFSINO) {
274 		xrep_findparent_scan_finish_early(&rd->pscan, ino);
275 		return 0;
276 	}
277 
278 	ino = xrep_dir_lookup_parent(rd);
279 	if (ino != NULLFSINO) {
280 		xrep_findparent_scan_finish_early(&rd->pscan, ino);
281 		return 0;
282 	}
283 
284 	/*
285 	 * A full filesystem scan is the last resort.  On a busy filesystem,
286 	 * the scan can fail with -EBUSY if we cannot grab IOLOCKs.  That means
287 	 * that we don't know what who the parent is, so we should return to
288 	 * userspace.
289 	 */
290 	return xrep_findparent_scan(&rd->pscan);
291 }
292 
293 /*
294  * Decide if we want to salvage this entry.  We don't bother with oversized
295  * names or the dot entry.
296  */
297 STATIC int
xrep_dir_want_salvage(struct xrep_dir * rd,const char * name,int namelen,xfs_ino_t ino)298 xrep_dir_want_salvage(
299 	struct xrep_dir		*rd,
300 	const char		*name,
301 	int			namelen,
302 	xfs_ino_t		ino)
303 {
304 	struct xfs_mount	*mp = rd->sc->mp;
305 
306 	/* No pointers to ourselves or to garbage. */
307 	if (ino == I_INO(rd->sc->ip))
308 		return false;
309 	if (!xfs_verify_dir_ino(mp, ino))
310 		return false;
311 
312 	/* No weird looking names or dot entries. */
313 	if (namelen >= MAXNAMELEN || namelen <= 0)
314 		return false;
315 	if (namelen == 1 && name[0] == '.')
316 		return false;
317 	if (!xfs_dir2_namecheck(name, namelen))
318 		return false;
319 
320 	return true;
321 }
322 
323 /*
324  * Remember that we want to create a dirent in the tempdir.  These stashed
325  * actions will be replayed later.
326  */
327 STATIC int
xrep_dir_stash_createname(struct xrep_dir * rd,const struct xfs_name * name,xfs_ino_t ino)328 xrep_dir_stash_createname(
329 	struct xrep_dir		*rd,
330 	const struct xfs_name	*name,
331 	xfs_ino_t		ino)
332 {
333 	struct xrep_dirent	dirent = {
334 		.action		= XREP_DIRENT_ADD,
335 		.ino		= ino,
336 		.namelen	= name->len,
337 		.ftype		= name->type,
338 	};
339 	int			error;
340 
341 	trace_xrep_dir_stash_createname(rd->sc->tempip, name, ino);
342 
343 	error = xfblob_storename(rd->dir_names, &dirent.name_cookie, name);
344 	if (error)
345 		return error;
346 
347 	return xfarray_append(rd->dir_entries, &dirent);
348 }
349 
350 /*
351  * Remember that we want to remove a dirent from the tempdir.  These stashed
352  * actions will be replayed later.
353  */
354 STATIC int
xrep_dir_stash_removename(struct xrep_dir * rd,const struct xfs_name * name,xfs_ino_t ino)355 xrep_dir_stash_removename(
356 	struct xrep_dir		*rd,
357 	const struct xfs_name	*name,
358 	xfs_ino_t		ino)
359 {
360 	struct xrep_dirent	dirent = {
361 		.action		= XREP_DIRENT_REMOVE,
362 		.ino		= ino,
363 		.namelen	= name->len,
364 		.ftype		= name->type,
365 	};
366 	int			error;
367 
368 	trace_xrep_dir_stash_removename(rd->sc->tempip, name, ino);
369 
370 	error = xfblob_storename(rd->dir_names, &dirent.name_cookie, name);
371 	if (error)
372 		return error;
373 
374 	return xfarray_append(rd->dir_entries, &dirent);
375 }
376 
377 /* Allocate an in-core record to hold entries while we rebuild the dir data. */
378 STATIC int
xrep_dir_salvage_entry(struct xrep_dir * rd,unsigned char * name,unsigned int namelen,xfs_ino_t ino)379 xrep_dir_salvage_entry(
380 	struct xrep_dir		*rd,
381 	unsigned char		*name,
382 	unsigned int		namelen,
383 	xfs_ino_t		ino)
384 {
385 	struct xfs_name		xname = {
386 		.name		= name,
387 	};
388 	struct xfs_scrub	*sc = rd->sc;
389 	struct xfs_inode	*ip;
390 	unsigned int		i = 0;
391 	int			error = 0;
392 
393 	if (xchk_should_terminate(sc, &error))
394 		return error;
395 
396 	/*
397 	 * Truncate the name to the first character that would trip namecheck.
398 	 * If we no longer have a name after that, ignore this entry.
399 	 */
400 	while (i < namelen && name[i] != 0 && name[i] != '/')
401 		i++;
402 	if (i == 0)
403 		return 0;
404 	xname.len = i;
405 
406 	/* Ignore '..' entries; we already picked the new parent. */
407 	if (xname.len == 2 && name[0] == '.' && name[1] == '.') {
408 		trace_xrep_dir_salvaged_parent(sc->ip, ino);
409 		return 0;
410 	}
411 
412 	trace_xrep_dir_salvage_entry(sc->ip, &xname, ino);
413 
414 	/*
415 	 * Compute the ftype or dump the entry if we can't.  We don't lock the
416 	 * inode because inodes can't change type while we have a reference.
417 	 */
418 	error = xchk_iget(sc, ino, &ip);
419 	if (error)
420 		return 0;
421 
422 	/* Don't mix metadata and regular directory trees. */
423 	if (xfs_is_metadir_inode(ip) != xfs_is_metadir_inode(rd->sc->ip)) {
424 		xchk_irele(sc, ip);
425 		return 0;
426 	}
427 
428 	xname.type = xfs_mode_to_ftype(VFS_I(ip)->i_mode);
429 	xchk_irele(sc, ip);
430 
431 	return xrep_dir_stash_createname(rd, &xname, ino);
432 }
433 
434 /* Record a shortform directory entry for later reinsertion. */
435 STATIC int
xrep_dir_salvage_sf_entry(struct xrep_dir * rd,struct xfs_dir2_sf_hdr * sfp,struct xfs_dir2_sf_entry * sfep)436 xrep_dir_salvage_sf_entry(
437 	struct xrep_dir			*rd,
438 	struct xfs_dir2_sf_hdr		*sfp,
439 	struct xfs_dir2_sf_entry	*sfep)
440 {
441 	xfs_ino_t			ino;
442 
443 	ino = xfs_dir2_sf_get_ino(rd->sc->mp, sfp, sfep);
444 	if (!xrep_dir_want_salvage(rd, sfep->name, sfep->namelen, ino))
445 		return 0;
446 
447 	return xrep_dir_salvage_entry(rd, sfep->name, sfep->namelen, ino);
448 }
449 
450 /* Record a regular directory entry for later reinsertion. */
451 STATIC int
xrep_dir_salvage_data_entry(struct xrep_dir * rd,struct xfs_dir2_data_entry * dep)452 xrep_dir_salvage_data_entry(
453 	struct xrep_dir			*rd,
454 	struct xfs_dir2_data_entry	*dep)
455 {
456 	xfs_ino_t			ino;
457 
458 	ino = be64_to_cpu(dep->inumber);
459 	if (!xrep_dir_want_salvage(rd, dep->name, dep->namelen, ino))
460 		return 0;
461 
462 	return xrep_dir_salvage_entry(rd, dep->name, dep->namelen, ino);
463 }
464 
465 /* Try to recover block/data format directory entries. */
466 STATIC int
xrep_dir_recover_data(struct xrep_dir * rd,struct xfs_buf * bp)467 xrep_dir_recover_data(
468 	struct xrep_dir		*rd,
469 	struct xfs_buf		*bp)
470 {
471 	struct xfs_da_geometry	*geo = rd->sc->mp->m_dir_geo;
472 	unsigned int		offset;
473 	unsigned int		end;
474 	int			error = 0;
475 
476 	/*
477 	 * Loop over the data portion of the block.
478 	 * Each object is a real entry (dep) or an unused one (dup).
479 	 */
480 	offset = geo->data_entry_offset;
481 	end = min_t(unsigned int, BBTOB(bp->b_length),
482 			xfs_dir3_data_end_offset(geo, bp->b_addr));
483 
484 	while (offset < end) {
485 		struct xfs_dir2_data_unused	*dup = bp->b_addr + offset;
486 		struct xfs_dir2_data_entry	*dep = bp->b_addr + offset;
487 		unsigned int			advance;
488 
489 		if (xchk_should_terminate(rd->sc, &error))
490 			return error;
491 
492 		/* Skip unused entries. */
493 		if (be16_to_cpu(dup->freetag) == XFS_DIR2_DATA_FREE_TAG) {
494 			if (!dup->length)
495 				break;
496 			offset += be16_to_cpu(dup->length);
497 			continue;
498 		}
499 
500 		/* Don't walk off the end of the block. */
501 		advance = xfs_dir2_data_entsize(rd->sc->mp, dep->namelen);
502 		if (!advance)
503 			break;
504 		offset += advance;
505 		if (offset > end)
506 			break;
507 
508 		/* Ok, let's save this entry. */
509 		error = xrep_dir_salvage_data_entry(rd, dep);
510 		if (error)
511 			return error;
512 
513 	}
514 
515 	return 0;
516 }
517 
518 /* Try to recover shortform directory entries. */
519 STATIC int
xrep_dir_recover_sf(struct xrep_dir * rd)520 xrep_dir_recover_sf(
521 	struct xrep_dir			*rd)
522 {
523 	struct xfs_dir2_sf_hdr		*hdr;
524 	struct xfs_dir2_sf_entry	*sfep;
525 	struct xfs_dir2_sf_entry	*next;
526 	struct xfs_ifork		*ifp;
527 	xfs_ino_t			ino;
528 	unsigned char			*end;
529 	int				error = 0;
530 
531 	ifp = xfs_ifork_ptr(rd->sc->ip, XFS_DATA_FORK);
532 	hdr = ifp->if_data;
533 	end = (unsigned char *)ifp->if_data + ifp->if_bytes;
534 
535 	ino = xfs_dir2_sf_get_parent_ino(hdr);
536 	trace_xrep_dir_salvaged_parent(rd->sc->ip, ino);
537 
538 	sfep = xfs_dir2_sf_firstentry(hdr);
539 	while ((unsigned char *)sfep < end) {
540 		if (xchk_should_terminate(rd->sc, &error))
541 			return error;
542 
543 		next = xfs_dir2_sf_nextentry(rd->sc->mp, hdr, sfep);
544 		if ((unsigned char *)next > end)
545 			break;
546 
547 		/* Ok, let's save this entry. */
548 		error = xrep_dir_salvage_sf_entry(rd, hdr, sfep);
549 		if (error)
550 			return error;
551 
552 		sfep = next;
553 	}
554 
555 	return 0;
556 }
557 
558 /*
559  * Try to figure out the format of this directory from the data fork mappings
560  * and the directory size.  If we can be reasonably sure of format, we can be
561  * more aggressive in salvaging directory entries.  On return, @magic_guess
562  * will be set to DIR3_BLOCK_MAGIC if we think this is a "block format"
563  * directory; DIR3_DATA_MAGIC if we think this is a "data format" directory,
564  * and 0 if we can't tell.
565  */
566 STATIC void
xrep_dir_guess_format(struct xrep_dir * rd,__be32 * magic_guess)567 xrep_dir_guess_format(
568 	struct xrep_dir		*rd,
569 	__be32			*magic_guess)
570 {
571 	struct xfs_inode	*dp = rd->sc->ip;
572 	struct xfs_mount	*mp = rd->sc->mp;
573 	struct xfs_da_geometry	*geo = mp->m_dir_geo;
574 	xfs_fileoff_t		last;
575 	int			error;
576 
577 	ASSERT(xfs_has_crc(mp));
578 
579 	*magic_guess = 0;
580 
581 	/*
582 	 * If there's a single directory block and the directory size is
583 	 * exactly one block, this has to be a single block format directory.
584 	 */
585 	error = xfs_bmap_last_offset(dp, &last, XFS_DATA_FORK);
586 	if (!error && XFS_FSB_TO_B(mp, last) == geo->blksize &&
587 	    dp->i_disk_size == geo->blksize) {
588 		*magic_guess = cpu_to_be32(XFS_DIR3_BLOCK_MAGIC);
589 		return;
590 	}
591 
592 	/*
593 	 * If the last extent before the leaf offset matches the directory
594 	 * size and the directory size is larger than 1 block, this is a
595 	 * data format directory.
596 	 */
597 	last = geo->leafblk;
598 	error = xfs_bmap_last_before(rd->sc->tp, dp, &last, XFS_DATA_FORK);
599 	if (!error &&
600 	    XFS_FSB_TO_B(mp, last) > geo->blksize &&
601 	    XFS_FSB_TO_B(mp, last) == dp->i_disk_size) {
602 		*magic_guess = cpu_to_be32(XFS_DIR3_DATA_MAGIC);
603 		return;
604 	}
605 }
606 
607 /* Recover directory entries from a specific directory block. */
608 STATIC int
xrep_dir_recover_dirblock(struct xrep_dir * rd,__be32 magic_guess,xfs_dablk_t dabno)609 xrep_dir_recover_dirblock(
610 	struct xrep_dir		*rd,
611 	__be32			magic_guess,
612 	xfs_dablk_t		dabno)
613 {
614 	struct xfs_dir2_data_hdr *hdr;
615 	struct xfs_buf		*bp;
616 	__be32			oldmagic;
617 	int			error;
618 
619 	/*
620 	 * Try to read buffer.  We invalidate them in the next step so we don't
621 	 * bother to set a buffer type or ops.
622 	 */
623 	error = xfs_da_read_buf(rd->sc->tp, rd->sc->ip, dabno,
624 			XFS_DABUF_MAP_HOLE_OK, &bp, XFS_DATA_FORK, NULL);
625 	if (error || !bp)
626 		return error;
627 
628 	hdr = bp->b_addr;
629 	oldmagic = hdr->magic;
630 
631 	trace_xrep_dir_recover_dirblock(rd->sc->ip, dabno,
632 			be32_to_cpu(hdr->magic), be32_to_cpu(magic_guess));
633 
634 	/*
635 	 * If we're sure of the block's format, proceed with the salvage
636 	 * operation using the specified magic number.
637 	 */
638 	if (magic_guess) {
639 		hdr->magic = magic_guess;
640 		goto recover;
641 	}
642 
643 	/*
644 	 * If we couldn't guess what type of directory this is, then we will
645 	 * only salvage entries from directory blocks that match the magic
646 	 * number and pass verifiers.
647 	 */
648 	switch (hdr->magic) {
649 	case cpu_to_be32(XFS_DIR2_BLOCK_MAGIC):
650 	case cpu_to_be32(XFS_DIR3_BLOCK_MAGIC):
651 		if (!xrep_buf_verify_struct(bp, &xfs_dir3_block_buf_ops))
652 			goto out;
653 		if (xfs_dir3_block_header_check(bp, I_INO(rd->sc->ip)) != NULL)
654 			goto out;
655 		break;
656 	case cpu_to_be32(XFS_DIR2_DATA_MAGIC):
657 	case cpu_to_be32(XFS_DIR3_DATA_MAGIC):
658 		if (!xrep_buf_verify_struct(bp, &xfs_dir3_data_buf_ops))
659 			goto out;
660 		if (xfs_dir3_data_header_check(bp, I_INO(rd->sc->ip)) != NULL)
661 			goto out;
662 		break;
663 	default:
664 		goto out;
665 	}
666 
667 recover:
668 	error = xrep_dir_recover_data(rd, bp);
669 
670 out:
671 	hdr->magic = oldmagic;
672 	xfs_trans_brelse(rd->sc->tp, bp);
673 	return error;
674 }
675 
676 static inline void
xrep_dir_init_args(struct xrep_dir * rd,struct xfs_inode * dp,const struct xfs_name * name)677 xrep_dir_init_args(
678 	struct xrep_dir		*rd,
679 	struct xfs_inode	*dp,
680 	const struct xfs_name	*name)
681 {
682 	memset(&rd->args, 0, sizeof(struct xfs_da_args));
683 	rd->args.geo = rd->sc->mp->m_dir_geo;
684 	rd->args.whichfork = XFS_DATA_FORK;
685 	rd->args.owner = I_INO(rd->sc->ip);
686 	rd->args.trans = rd->sc->tp;
687 	rd->args.dp = dp;
688 	if (!name)
689 		return;
690 	rd->args.name = name->name;
691 	rd->args.namelen = name->len;
692 	rd->args.filetype = name->type;
693 	rd->args.hashval = xfs_dir2_hashname(rd->sc->mp, name);
694 }
695 
696 /* Replay a stashed createname into the temporary directory. */
697 STATIC int
xrep_dir_replay_createname(struct xrep_dir * rd,const struct xfs_name * name,xfs_ino_t inum,xfs_extlen_t total)698 xrep_dir_replay_createname(
699 	struct xrep_dir		*rd,
700 	const struct xfs_name	*name,
701 	xfs_ino_t		inum,
702 	xfs_extlen_t		total)
703 {
704 	struct xfs_scrub	*sc = rd->sc;
705 	struct xfs_inode	*dp = rd->sc->tempip;
706 	int			error;
707 
708 	ASSERT(S_ISDIR(VFS_I(dp)->i_mode));
709 
710 	error = xfs_dir_ino_validate(sc->mp, inum);
711 	if (error)
712 		return error;
713 
714 	trace_xrep_dir_replay_createname(dp, name, inum);
715 
716 	xrep_dir_init_args(rd, dp, name);
717 	rd->args.inumber = inum;
718 	rd->args.total = total;
719 	rd->args.op_flags = XFS_DA_OP_ADDNAME | XFS_DA_OP_OKNOENT;
720 	return xfs_dir_createname_args(&rd->args);
721 }
722 
723 /* Replay a stashed removename onto the temporary directory. */
724 STATIC int
xrep_dir_replay_removename(struct xrep_dir * rd,const struct xfs_name * name,xfs_extlen_t total)725 xrep_dir_replay_removename(
726 	struct xrep_dir		*rd,
727 	const struct xfs_name	*name,
728 	xfs_extlen_t		total)
729 {
730 	struct xfs_inode	*dp = rd->sc->tempip;
731 
732 	ASSERT(S_ISDIR(VFS_I(dp)->i_mode));
733 
734 	xrep_dir_init_args(rd, dp, name);
735 	rd->args.op_flags = 0;
736 	rd->args.total = total;
737 
738 	trace_xrep_dir_replay_removename(dp, name, 0);
739 	return xfs_dir_removename_args(&rd->args);
740 }
741 
742 /*
743  * Add this stashed incore directory entry to the temporary directory.
744  * The caller must hold the tempdir's IOLOCK, must not hold any ILOCKs, and
745  * must not be in transaction context.
746  */
747 STATIC int
xrep_dir_replay_update(struct xrep_dir * rd,const struct xfs_name * xname,const struct xrep_dirent * dirent)748 xrep_dir_replay_update(
749 	struct xrep_dir			*rd,
750 	const struct xfs_name		*xname,
751 	const struct xrep_dirent	*dirent)
752 {
753 	struct xfs_mount		*mp = rd->sc->mp;
754 #ifdef DEBUG
755 	xfs_ino_t			ino;
756 #endif
757 	uint				resblks;
758 	int				error;
759 
760 	resblks = xfs_link_space_res(mp, xname->len);
761 	error = xchk_trans_alloc(rd->sc, resblks);
762 	if (error)
763 		return error;
764 
765 	/* Lock the temporary directory and join it to the transaction */
766 	xrep_tempfile_ilock(rd->sc);
767 	xfs_trans_ijoin(rd->sc->tp, rd->sc->tempip, 0);
768 
769 	switch (dirent->action) {
770 	case XREP_DIRENT_ADD:
771 		/*
772 		 * Create a replacement dirent in the temporary directory.
773 		 * Note that _createname doesn't check for existing entries.
774 		 * There shouldn't be any in the temporary dir, but we'll
775 		 * verify this in debug mode.
776 		 */
777 #ifdef DEBUG
778 		error = xchk_dir_lookup(rd->sc, rd->sc->tempip, xname, &ino);
779 		if (error != -ENOENT) {
780 			ASSERT(error != -ENOENT);
781 			goto out_cancel;
782 		}
783 #endif
784 
785 		error = xrep_dir_replay_createname(rd, xname, dirent->ino,
786 				resblks);
787 		if (error)
788 			goto out_cancel;
789 
790 		if (xname->type == XFS_DIR3_FT_DIR)
791 			rd->subdirs++;
792 		rd->dirents++;
793 		break;
794 	case XREP_DIRENT_REMOVE:
795 		/*
796 		 * Remove a dirent from the temporary directory.  Note that
797 		 * _removename doesn't check the inode target of the exist
798 		 * entry.  There should be a perfect match in the temporary
799 		 * dir, but we'll verify this in debug mode.
800 		 */
801 #ifdef DEBUG
802 		error = xchk_dir_lookup(rd->sc, rd->sc->tempip, xname, &ino);
803 		if (error) {
804 			ASSERT(error != 0);
805 			goto out_cancel;
806 		}
807 		if (ino != dirent->ino) {
808 			ASSERT(ino == dirent->ino);
809 			error = -EIO;
810 			goto out_cancel;
811 		}
812 #endif
813 
814 		error = xrep_dir_replay_removename(rd, xname, resblks);
815 		if (error)
816 			goto out_cancel;
817 
818 		if (xname->type == XFS_DIR3_FT_DIR)
819 			rd->subdirs--;
820 		rd->dirents--;
821 		break;
822 	default:
823 		ASSERT(0);
824 		error = -EIO;
825 		goto out_cancel;
826 	}
827 
828 	/* Commit and unlock. */
829 	error = xrep_trans_commit(rd->sc);
830 	if (error)
831 		return error;
832 
833 	xrep_tempfile_iunlock(rd->sc);
834 	return 0;
835 out_cancel:
836 	xchk_trans_cancel(rd->sc);
837 	xrep_tempfile_iunlock(rd->sc);
838 	return error;
839 }
840 
841 /*
842  * Flush stashed incore dirent updates that have been recorded by the scanner.
843  * This is done to reduce the memory requirements of the directory rebuild,
844  * since directories can contain up to 32GB of directory data.
845  *
846  * Caller must not hold transactions or ILOCKs.  Caller must hold the tempdir
847  * IOLOCK.
848  */
849 STATIC int
xrep_dir_replay_updates(struct xrep_dir * rd)850 xrep_dir_replay_updates(
851 	struct xrep_dir		*rd)
852 {
853 	xfarray_idx_t		array_cur;
854 	int			error;
855 
856 	/* Add all the salvaged dirents to the temporary directory. */
857 	mutex_lock(&rd->pscan.lock);
858 	foreach_xfarray_idx(rd->dir_entries, array_cur) {
859 		struct xrep_dirent	dirent;
860 
861 		error = xfarray_load(rd->dir_entries, array_cur, &dirent);
862 		if (error)
863 			goto out_unlock;
864 
865 		error = xfblob_loadname(rd->dir_names, dirent.name_cookie,
866 				&rd->xname, dirent.namelen);
867 		if (error)
868 			goto out_unlock;
869 		rd->xname.type = dirent.ftype;
870 		mutex_unlock(&rd->pscan.lock);
871 
872 		error = xrep_dir_replay_update(rd, &rd->xname, &dirent);
873 		if (error)
874 			return error;
875 		mutex_lock(&rd->pscan.lock);
876 	}
877 
878 	/* Empty out both arrays now that we've added the entries. */
879 	xfarray_truncate(rd->dir_entries);
880 	xfblob_truncate(rd->dir_names);
881 	mutex_unlock(&rd->pscan.lock);
882 	return 0;
883 out_unlock:
884 	mutex_unlock(&rd->pscan.lock);
885 	return error;
886 }
887 
888 /*
889  * Periodically flush stashed directory entries to the temporary dir.  This
890  * is done to reduce the memory requirements of the directory rebuild, since
891  * directories can contain up to 32GB of directory data.
892  */
893 STATIC int
xrep_dir_flush_stashed(struct xrep_dir * rd)894 xrep_dir_flush_stashed(
895 	struct xrep_dir		*rd)
896 {
897 	int			error;
898 
899 	/*
900 	 * Entering this function, the scrub context has a reference to the
901 	 * inode being repaired, the temporary file, and a scrub transaction
902 	 * that we use during dirent salvaging to avoid livelocking if there
903 	 * are cycles in the directory structures.  We hold ILOCK_EXCL on both
904 	 * the inode being repaired and the temporary file, though they are
905 	 * not ijoined to the scrub transaction.
906 	 *
907 	 * To constrain kernel memory use, we occasionally write salvaged
908 	 * dirents from the xfarray and xfblob structures into the temporary
909 	 * directory in preparation for exchanging the directory structures at
910 	 * the end.  Updating the temporary file requires a transaction, so we
911 	 * commit the scrub transaction and drop the two ILOCKs so that
912 	 * we can allocate whatever transaction we want.
913 	 *
914 	 * We still hold IOLOCK_EXCL on the inode being repaired, which
915 	 * prevents anyone from accessing the damaged directory data while we
916 	 * repair it.
917 	 */
918 	error = xrep_trans_commit(rd->sc);
919 	if (error)
920 		return error;
921 	xchk_iunlock(rd->sc, XFS_ILOCK_EXCL);
922 
923 	/*
924 	 * Take the IOLOCK of the temporary file while we modify dirents.  This
925 	 * isn't strictly required because the temporary file is never revealed
926 	 * to userspace, but we follow the same locking rules.  We still hold
927 	 * sc->ip's IOLOCK.
928 	 */
929 	error = xrep_tempfile_iolock_polled(rd->sc);
930 	if (error)
931 		return error;
932 
933 	/* Write to the tempdir all the updates that we've stashed. */
934 	error = xrep_dir_replay_updates(rd);
935 	xrep_tempfile_iounlock(rd->sc);
936 	if (error)
937 		return error;
938 
939 	/*
940 	 * Recreate the salvage transaction and relock the dir we're salvaging.
941 	 */
942 	error = xchk_trans_alloc(rd->sc, 0);
943 	if (error)
944 		return error;
945 	xchk_ilock(rd->sc, XFS_ILOCK_EXCL);
946 	return 0;
947 }
948 
949 /* Decide if we've stashed too much dirent data in memory. */
950 static inline bool
xrep_dir_want_flush_stashed(struct xrep_dir * rd)951 xrep_dir_want_flush_stashed(
952 	struct xrep_dir		*rd)
953 {
954 	unsigned long long	bytes;
955 
956 	bytes = xfarray_bytes(rd->dir_entries) + xfblob_bytes(rd->dir_names);
957 	return bytes > XREP_DIR_MAX_STASH_BYTES;
958 }
959 
960 /* Extract as many directory entries as we can. */
961 STATIC int
xrep_dir_recover(struct xrep_dir * rd)962 xrep_dir_recover(
963 	struct xrep_dir		*rd)
964 {
965 	struct xfs_bmbt_irec	got;
966 	struct xfs_scrub	*sc = rd->sc;
967 	struct xfs_da_geometry	*geo = sc->mp->m_dir_geo;
968 	xfs_fileoff_t		offset;
969 	xfs_dablk_t		dabno;
970 	__be32			magic_guess;
971 	int			nmap;
972 	int			error;
973 
974 	xrep_dir_guess_format(rd, &magic_guess);
975 
976 	/* Iterate each directory data block in the data fork. */
977 	for (offset = 0;
978 	     offset < geo->leafblk;
979 	     offset = got.br_startoff + got.br_blockcount) {
980 		nmap = 1;
981 		error = xfs_bmapi_read(sc->ip, offset, geo->leafblk - offset,
982 				&got, &nmap, 0);
983 		if (error)
984 			return error;
985 		if (nmap != 1)
986 			return -EFSCORRUPTED;
987 		if (!xfs_bmap_is_written_extent(&got))
988 			continue;
989 
990 		for (dabno = round_up(got.br_startoff, geo->fsbcount);
991 		     dabno < got.br_startoff + got.br_blockcount;
992 		     dabno += geo->fsbcount) {
993 			if (xchk_should_terminate(rd->sc, &error))
994 				return error;
995 
996 			error = xrep_dir_recover_dirblock(rd,
997 					magic_guess, dabno);
998 			if (error)
999 				return error;
1000 
1001 			/* Flush dirents to constrain memory usage. */
1002 			if (xrep_dir_want_flush_stashed(rd)) {
1003 				error = xrep_dir_flush_stashed(rd);
1004 				if (error)
1005 					return error;
1006 			}
1007 		}
1008 	}
1009 
1010 	return 0;
1011 }
1012 
1013 /*
1014  * Find all the directory entries for this inode by scraping them out of the
1015  * directory leaf blocks by hand, and flushing them into the temp dir.
1016  */
1017 STATIC int
xrep_dir_find_entries(struct xrep_dir * rd)1018 xrep_dir_find_entries(
1019 	struct xrep_dir		*rd)
1020 {
1021 	struct xfs_inode	*dp = rd->sc->ip;
1022 	int			error;
1023 
1024 	/*
1025 	 * Salvage directory entries from the old directory, and write them to
1026 	 * the temporary directory.
1027 	 */
1028 	if (dp->i_df.if_format == XFS_DINODE_FMT_LOCAL) {
1029 		error = xrep_dir_recover_sf(rd);
1030 	} else {
1031 		error = xfs_iread_extents(rd->sc->tp, dp, XFS_DATA_FORK);
1032 		if (error)
1033 			return error;
1034 
1035 		error = xrep_dir_recover(rd);
1036 	}
1037 	if (error)
1038 		return error;
1039 
1040 	return xrep_dir_flush_stashed(rd);
1041 }
1042 
1043 /* Scan all files in the filesystem for dirents. */
1044 STATIC int
xrep_dir_salvage_entries(struct xrep_dir * rd)1045 xrep_dir_salvage_entries(
1046 	struct xrep_dir		*rd)
1047 {
1048 	struct xfs_scrub	*sc = rd->sc;
1049 	int			error;
1050 
1051 	/*
1052 	 * Drop the ILOCK on this directory so that we can scan for this
1053 	 * directory's parent.  Figure out who is going to be the parent of
1054 	 * this directory, then retake the ILOCK so that we can salvage
1055 	 * directory entries.
1056 	 */
1057 	xchk_iunlock(sc, XFS_ILOCK_EXCL);
1058 	error = xrep_dir_find_parent(rd);
1059 	xchk_ilock(sc, XFS_ILOCK_EXCL);
1060 	if (error)
1061 		return error;
1062 
1063 	/*
1064 	 * Collect directory entries by parsing raw leaf blocks to salvage
1065 	 * whatever we can.  When we're done, free the staging memory before
1066 	 * exchanging the directories to reduce memory usage.
1067 	 */
1068 	error = xrep_dir_find_entries(rd);
1069 	if (error)
1070 		return error;
1071 
1072 	/*
1073 	 * Cancel the repair transaction and drop the ILOCK so that we can
1074 	 * (later) use the atomic mapping exchange functions to compute the
1075 	 * correct block reservations and re-lock the inodes.
1076 	 *
1077 	 * We still hold IOLOCK_EXCL (aka i_rwsem) which will prevent directory
1078 	 * modifications, but there's nothing to prevent userspace from reading
1079 	 * the directory until we're ready for the exchange operation.  Reads
1080 	 * will return -EIO without shutting down the fs, so we're ok with
1081 	 * that.
1082 	 *
1083 	 * The VFS can change dotdot on us, but the findparent scan will keep
1084 	 * our incore parent inode up to date.  See the note on locking issues
1085 	 * for more details.
1086 	 */
1087 	error = xrep_trans_commit(sc);
1088 	if (error)
1089 		return error;
1090 
1091 	xchk_iunlock(sc, XFS_ILOCK_EXCL);
1092 	return 0;
1093 }
1094 
1095 
1096 /*
1097  * Examine a parent pointer of a file.  If it leads us back to the directory
1098  * that we're rebuilding, create an incore dirent from the parent pointer and
1099  * stash it.
1100  */
1101 STATIC int
xrep_dir_scan_pptr(struct xfs_scrub * sc,struct xfs_inode * ip,unsigned int attr_flags,const unsigned char * name,unsigned int namelen,const void * value,unsigned int valuelen,void * priv)1102 xrep_dir_scan_pptr(
1103 	struct xfs_scrub		*sc,
1104 	struct xfs_inode		*ip,
1105 	unsigned int			attr_flags,
1106 	const unsigned char		*name,
1107 	unsigned int			namelen,
1108 	const void			*value,
1109 	unsigned int			valuelen,
1110 	void				*priv)
1111 {
1112 	struct xfs_name			xname = {
1113 		.name			= name,
1114 		.len			= namelen,
1115 		.type			= xfs_mode_to_ftype(VFS_I(ip)->i_mode),
1116 	};
1117 	xfs_ino_t			parent_ino;
1118 	uint32_t			parent_gen;
1119 	struct xrep_dir			*rd = priv;
1120 	int				error;
1121 
1122 	if (!(attr_flags & XFS_ATTR_PARENT))
1123 		return 0;
1124 
1125 	/*
1126 	 * Ignore parent pointers that point back to a different dir, list the
1127 	 * wrong generation number, or are invalid.
1128 	 */
1129 	error = xfs_parent_from_attr(sc->mp, attr_flags, name, namelen, value,
1130 			valuelen, &parent_ino, &parent_gen);
1131 	if (error)
1132 		return error;
1133 
1134 	if (parent_ino != I_INO(sc->ip) ||
1135 	    parent_gen != VFS_I(sc->ip)->i_generation)
1136 		return 0;
1137 
1138 	mutex_lock(&rd->pscan.lock);
1139 	error = xrep_dir_stash_createname(rd, &xname, I_INO(ip));
1140 	mutex_unlock(&rd->pscan.lock);
1141 	return error;
1142 }
1143 
1144 /*
1145  * If this child dirent points to the directory being repaired, remember that
1146  * fact so that we can reset the dotdot entry if necessary.
1147  */
1148 STATIC int
xrep_dir_scan_dirent(struct xfs_scrub * sc,struct xfs_inode * dp,xfs_dir2_dataptr_t dapos,const struct xfs_name * name,xfs_ino_t ino,void * priv)1149 xrep_dir_scan_dirent(
1150 	struct xfs_scrub	*sc,
1151 	struct xfs_inode	*dp,
1152 	xfs_dir2_dataptr_t	dapos,
1153 	const struct xfs_name	*name,
1154 	xfs_ino_t		ino,
1155 	void			*priv)
1156 {
1157 	struct xrep_dir		*rd = priv;
1158 
1159 	/* Dirent doesn't point to this directory. */
1160 	if (ino != I_INO(rd->sc->ip))
1161 		return 0;
1162 
1163 	/* Ignore garbage inum. */
1164 	if (!xfs_verify_dir_ino(rd->sc->mp, ino))
1165 		return 0;
1166 
1167 	/* No weird looking names. */
1168 	if (name->len >= MAXNAMELEN || name->len <= 0)
1169 		return 0;
1170 
1171 	/* Don't pick up dot or dotdot entries; we only want child dirents. */
1172 	if (xfs_dir2_samename(name, &xfs_name_dotdot) ||
1173 	    xfs_dir2_samename(name, &xfs_name_dot))
1174 		return 0;
1175 
1176 	trace_xrep_dir_stash_createname(sc->tempip, &xfs_name_dotdot,
1177 			I_INO(dp));
1178 
1179 	xrep_findparent_scan_found(&rd->pscan, I_INO(dp));
1180 	return 0;
1181 }
1182 
1183 /*
1184  * Decide if we want to look for child dirents or parent pointers in this file.
1185  * Skip the dir being repaired and any files being used to stage repairs.
1186  */
1187 static inline bool
xrep_dir_want_scan(struct xrep_dir * rd,const struct xfs_inode * ip)1188 xrep_dir_want_scan(
1189 	struct xrep_dir		*rd,
1190 	const struct xfs_inode	*ip)
1191 {
1192 	return ip != rd->sc->ip && !xrep_is_tempfile(ip);
1193 }
1194 
1195 /*
1196  * Take ILOCK on a file that we want to scan.
1197  *
1198  * Select ILOCK_EXCL if the file is a directory with an unloaded data bmbt or
1199  * has an unloaded attr bmbt.  Otherwise, take ILOCK_SHARED.
1200  */
1201 static inline unsigned int
xrep_dir_scan_ilock(struct xrep_dir * rd,struct xfs_inode * ip)1202 xrep_dir_scan_ilock(
1203 	struct xrep_dir		*rd,
1204 	struct xfs_inode	*ip)
1205 {
1206 	uint			lock_mode = XFS_ILOCK_SHARED;
1207 
1208 	/* Need to take the shared ILOCK to advance the iscan cursor. */
1209 	if (!xrep_dir_want_scan(rd, ip))
1210 		goto lock;
1211 
1212 	if (S_ISDIR(VFS_I(ip)->i_mode) && xfs_need_iread_extents(&ip->i_df)) {
1213 		lock_mode = XFS_ILOCK_EXCL;
1214 		goto lock;
1215 	}
1216 
1217 	if (xfs_inode_has_attr_fork(ip) && xfs_need_iread_extents(&ip->i_af))
1218 		lock_mode = XFS_ILOCK_EXCL;
1219 
1220 lock:
1221 	xfs_ilock(ip, lock_mode);
1222 	return lock_mode;
1223 }
1224 
1225 /*
1226  * Scan this file for relevant child dirents or parent pointers that point to
1227  * the directory we're rebuilding.
1228  */
1229 STATIC int
xrep_dir_scan_file(struct xrep_dir * rd,struct xfs_inode * ip)1230 xrep_dir_scan_file(
1231 	struct xrep_dir		*rd,
1232 	struct xfs_inode	*ip)
1233 {
1234 	unsigned int		lock_mode;
1235 	int			error = 0;
1236 
1237 	lock_mode = xrep_dir_scan_ilock(rd, ip);
1238 
1239 	if (!xrep_dir_want_scan(rd, ip))
1240 		goto scan_done;
1241 
1242 	/*
1243 	 * If the extended attributes look as though they has been zapped by
1244 	 * the inode record repair code, we cannot scan for parent pointers.
1245 	 */
1246 	if (xchk_pptr_looks_zapped(ip)) {
1247 		error = -EBUSY;
1248 		goto scan_done;
1249 	}
1250 
1251 	error = xchk_xattr_walk(rd->sc, ip, xrep_dir_scan_pptr, NULL, rd);
1252 	if (error)
1253 		goto scan_done;
1254 
1255 	if (S_ISDIR(VFS_I(ip)->i_mode)) {
1256 		/*
1257 		 * If the directory looks as though it has been zapped by the
1258 		 * inode record repair code, we cannot scan for child dirents.
1259 		 */
1260 		if (xchk_dir_looks_zapped(ip)) {
1261 			error = -EBUSY;
1262 			goto scan_done;
1263 		}
1264 
1265 		error = xchk_dir_walk(rd->sc, ip, xrep_dir_scan_dirent, rd);
1266 		if (error)
1267 			goto scan_done;
1268 	}
1269 
1270 scan_done:
1271 	xchk_iscan_mark_visited(&rd->pscan.iscan, ip);
1272 	xfs_iunlock(ip, lock_mode);
1273 	return error;
1274 }
1275 
1276 /*
1277  * Scan all files in the filesystem for parent pointers that we can turn into
1278  * replacement dirents, and a dirent that we can use to set the dotdot pointer.
1279  */
1280 STATIC int
xrep_dir_scan_dirtree(struct xrep_dir * rd)1281 xrep_dir_scan_dirtree(
1282 	struct xrep_dir		*rd)
1283 {
1284 	struct xfs_scrub	*sc = rd->sc;
1285 	struct xfs_inode	*ip;
1286 	int			error;
1287 
1288 	/* Roots of directory trees are their own parents. */
1289 	if (xchk_inode_is_dirtree_root(sc->ip))
1290 		xrep_findparent_scan_found(&rd->pscan, I_INO(sc->ip));
1291 
1292 	/*
1293 	 * Filesystem scans are time consuming.  Drop the directory ILOCK and
1294 	 * all other resources for the duration of the scan and hope for the
1295 	 * best.  The live update hooks will keep our scan information up to
1296 	 * date even though we've dropped the locks.
1297 	 */
1298 	xchk_trans_cancel(sc);
1299 	if (sc->ilock_flags & (XFS_ILOCK_SHARED | XFS_ILOCK_EXCL))
1300 		xchk_iunlock(sc, sc->ilock_flags & (XFS_ILOCK_SHARED |
1301 						    XFS_ILOCK_EXCL));
1302 	xchk_trans_alloc_empty(sc);
1303 
1304 	while ((error = xchk_iscan_iter(&rd->pscan.iscan, &ip)) == 1) {
1305 		bool		flush;
1306 
1307 		error = xrep_dir_scan_file(rd, ip);
1308 		xchk_irele(sc, ip);
1309 		if (error)
1310 			break;
1311 
1312 		/* Flush stashed dirent updates to constrain memory usage. */
1313 		mutex_lock(&rd->pscan.lock);
1314 		flush = xrep_dir_want_flush_stashed(rd);
1315 		mutex_unlock(&rd->pscan.lock);
1316 		if (flush) {
1317 			xchk_trans_cancel(sc);
1318 
1319 			error = xrep_tempfile_iolock_polled(sc);
1320 			if (error)
1321 				break;
1322 
1323 			error = xrep_dir_replay_updates(rd);
1324 			xrep_tempfile_iounlock(sc);
1325 			if (error)
1326 				break;
1327 
1328 			xchk_trans_alloc_empty(sc);
1329 		}
1330 
1331 		if (xchk_should_terminate(sc, &error))
1332 			break;
1333 	}
1334 	xchk_iscan_iter_finish(&rd->pscan.iscan);
1335 	if (error) {
1336 		/*
1337 		 * If we couldn't grab an inode that was busy with a state
1338 		 * change, change the error code so that we exit to userspace
1339 		 * as quickly as possible.
1340 		 */
1341 		if (error == -EBUSY)
1342 			return -ECANCELED;
1343 		return error;
1344 	}
1345 
1346 	/*
1347 	 * Cancel the empty transaction so that we can (later) use the atomic
1348 	 * file mapping exchange functions to lock files and commit the new
1349 	 * directory.
1350 	 */
1351 	xchk_trans_cancel(rd->sc);
1352 	return 0;
1353 }
1354 
1355 /*
1356  * Capture dirent updates being made by other threads which are relevant to the
1357  * directory being repaired.
1358  */
1359 STATIC int
xrep_dir_live_update(struct notifier_block * nb,unsigned long action,void * data)1360 xrep_dir_live_update(
1361 	struct notifier_block		*nb,
1362 	unsigned long			action,
1363 	void				*data)
1364 {
1365 	struct xfs_dir_update_params	*p = data;
1366 	struct xrep_dir			*rd;
1367 	struct xfs_scrub		*sc;
1368 	int				error = 0;
1369 
1370 	rd = container_of(nb, struct xrep_dir, pscan.dhook.dirent_hook.nb);
1371 	sc = rd->sc;
1372 
1373 	/*
1374 	 * This thread updated a child dirent in the directory that we're
1375 	 * rebuilding.  Stash the update for replay against the temporary
1376 	 * directory.
1377 	 */
1378 	if (I_INO(p->dp) == I_INO(sc->ip) &&
1379 	    xchk_iscan_want_live_update(&rd->pscan.iscan, I_INO(p->ip))) {
1380 		mutex_lock(&rd->pscan.lock);
1381 		if (p->delta > 0)
1382 			error = xrep_dir_stash_createname(rd, p->name,
1383 					I_INO(p->ip));
1384 		else {
1385 			/*
1386 			 * xfs_dentry_to_name in unlink or rename-exchange can
1387 			 * pass us names with ftype FT_UNKNOWN, but we really
1388 			 * must know the ftype of the child that is being
1389 			 * removed so that we can do nlink updates correctly
1390 			 * without holding inode references.
1391 			 */
1392 			struct xfs_name	name = {
1393 				.name	= p->name->name,
1394 				.len	= p->name->len,
1395 				.type	= xfs_mode_to_ftype(
1396 						VFS_IC(p->ip)->i_mode),
1397 			};
1398 
1399 			error = xrep_dir_stash_removename(rd, &name,
1400 					I_INO(p->ip));
1401 		}
1402 		mutex_unlock(&rd->pscan.lock);
1403 		if (error)
1404 			goto out_abort;
1405 	}
1406 
1407 	/*
1408 	 * This thread updated another directory's child dirent that points to
1409 	 * the directory that we're rebuilding, so remember the new dotdot
1410 	 * target.
1411 	 */
1412 	if (I_INO(p->ip) == I_INO(sc->ip) &&
1413 	    xchk_iscan_want_live_update(&rd->pscan.iscan, I_INO(p->dp))) {
1414 		if (p->delta > 0) {
1415 			trace_xrep_dir_stash_createname(sc->tempip,
1416 					&xfs_name_dotdot,
1417 					I_INO(p->dp));
1418 
1419 			xrep_findparent_scan_found(&rd->pscan, I_INO(p->dp));
1420 		} else {
1421 			trace_xrep_dir_stash_removename(sc->tempip,
1422 					&xfs_name_dotdot,
1423 					rd->pscan.parent_ino);
1424 
1425 			xrep_findparent_scan_found(&rd->pscan, NULLFSINO);
1426 		}
1427 	}
1428 
1429 	return NOTIFY_DONE;
1430 out_abort:
1431 	xchk_iscan_abort(&rd->pscan.iscan);
1432 	return NOTIFY_DONE;
1433 }
1434 
1435 /*
1436  * Free all the directory blocks and reset the data fork.  The caller must
1437  * join the inode to the transaction.  This function returns with the inode
1438  * joined to a clean scrub transaction.
1439  */
1440 STATIC int
xrep_dir_reset_fork(struct xrep_dir * rd,xfs_ino_t parent_ino)1441 xrep_dir_reset_fork(
1442 	struct xrep_dir		*rd,
1443 	xfs_ino_t		parent_ino)
1444 {
1445 	struct xfs_scrub	*sc = rd->sc;
1446 	struct xfs_ifork	*ifp = xfs_ifork_ptr(sc->tempip, XFS_DATA_FORK);
1447 	int			error;
1448 
1449 	/* Unmap all the directory buffers. */
1450 	if (xfs_ifork_has_extents(ifp)) {
1451 		error = xrep_reap_ifork(sc, sc->tempip, XFS_DATA_FORK);
1452 		if (error)
1453 			return error;
1454 	}
1455 
1456 	trace_xrep_dir_reset_fork(sc->tempip, parent_ino);
1457 
1458 	/* Reset the data fork to an empty data fork. */
1459 	xfs_idestroy_fork(ifp);
1460 	ifp->if_bytes = 0;
1461 	sc->tempip->i_disk_size = 0;
1462 
1463 	/* Reinitialize the short form directory. */
1464 	xrep_dir_init_args(rd, sc->tempip, NULL);
1465 	return xfs_dir2_sf_create(&rd->args, parent_ino);
1466 }
1467 
1468 /*
1469  * Prepare both inodes' directory forks for exchanging mappings.  Promote the
1470  * tempfile from short format to leaf format, and if the file being repaired
1471  * has a short format data fork, turn it into an empty extent list.
1472  */
1473 STATIC int
xrep_dir_swap_prep(struct xfs_scrub * sc,bool temp_local,bool ip_local)1474 xrep_dir_swap_prep(
1475 	struct xfs_scrub	*sc,
1476 	bool			temp_local,
1477 	bool			ip_local)
1478 {
1479 	int			error;
1480 
1481 	/*
1482 	 * If the tempfile's directory is in shortform format, convert that to
1483 	 * a single leaf extent so that we can use the atomic mapping exchange.
1484 	 */
1485 	if (temp_local) {
1486 		struct xfs_da_args	args = {
1487 			.dp		= sc->tempip,
1488 			.geo		= sc->mp->m_dir_geo,
1489 			.whichfork	= XFS_DATA_FORK,
1490 			.trans		= sc->tp,
1491 			.total		= xfs_dabuf_nfsb(sc->mp, XFS_DATA_FORK),
1492 			.owner		= I_INO(sc->ip),
1493 		};
1494 
1495 		error = xfs_dir2_sf_to_block(&args);
1496 		if (error)
1497 			return error;
1498 
1499 		/*
1500 		 * Roll the deferred log items to get us back to a clean
1501 		 * transaction.
1502 		 */
1503 		error = xfs_defer_finish(&sc->tp);
1504 		if (error)
1505 			return error;
1506 	}
1507 
1508 	/*
1509 	 * If the file being repaired had a shortform data fork, convert that
1510 	 * to an empty extent list in preparation for the atomic mapping
1511 	 * exchange.
1512 	 */
1513 	if (ip_local) {
1514 		struct xfs_ifork	*ifp;
1515 
1516 		ifp = xfs_ifork_ptr(sc->ip, XFS_DATA_FORK);
1517 		xfs_idestroy_fork(ifp);
1518 		ifp->if_format = XFS_DINODE_FMT_EXTENTS;
1519 		ifp->if_nextents = 0;
1520 		ifp->if_bytes = 0;
1521 		ifp->if_data = NULL;
1522 		ifp->if_height = 0;
1523 
1524 		xfs_trans_log_inode(sc->tp, sc->ip,
1525 				XFS_ILOG_CORE | XFS_ILOG_DDATA);
1526 	}
1527 
1528 	return 0;
1529 }
1530 
1531 /*
1532  * Replace the inode number of a directory entry.
1533  */
1534 static int
xrep_dir_replace(struct xrep_dir * rd,struct xfs_inode * dp,const struct xfs_name * name,xfs_ino_t inum,xfs_extlen_t total)1535 xrep_dir_replace(
1536 	struct xrep_dir		*rd,
1537 	struct xfs_inode	*dp,
1538 	const struct xfs_name	*name,
1539 	xfs_ino_t		inum,
1540 	xfs_extlen_t		total)
1541 {
1542 	struct xfs_scrub	*sc = rd->sc;
1543 	int			error;
1544 
1545 	ASSERT(S_ISDIR(VFS_I(dp)->i_mode));
1546 
1547 	error = xfs_dir_ino_validate(sc->mp, inum);
1548 	if (error)
1549 		return error;
1550 
1551 	xrep_dir_init_args(rd, dp, name);
1552 	rd->args.inumber = inum;
1553 	rd->args.total = total;
1554 	return xfs_dir_replace_args(&rd->args);
1555 }
1556 
1557 /*
1558  * Reset the link count of this directory and adjust the unlinked list pointers
1559  * as needed.
1560  */
1561 STATIC int
xrep_dir_set_nlink(struct xrep_dir * rd)1562 xrep_dir_set_nlink(
1563 	struct xrep_dir		*rd)
1564 {
1565 	struct xfs_scrub	*sc = rd->sc;
1566 	struct xfs_inode	*dp = sc->ip;
1567 	struct xfs_perag	*pag;
1568 	unsigned int		new_nlink = min_t(unsigned long long,
1569 						  rd->subdirs + 2,
1570 						  XFS_NLINK_PINNED);
1571 	int			error;
1572 
1573 	/*
1574 	 * The directory is not on the incore unlinked list, which means that
1575 	 * it needs to be reachable via the directory tree.  Update the nlink
1576 	 * with our observed link count.  If the directory has no parent, it
1577 	 * will be moved to the orphanage.
1578 	 */
1579 	if (!xfs_inode_on_unlinked_list(dp))
1580 		goto reset_nlink;
1581 
1582 	/*
1583 	 * The directory is on the unlinked list and we did not find any
1584 	 * dirents.  Set the link count to zero and let the directory
1585 	 * inactivate when the last reference drops.
1586 	 */
1587 	if (rd->dirents == 0) {
1588 		rd->needs_adoption = false;
1589 		new_nlink = 0;
1590 		goto reset_nlink;
1591 	}
1592 
1593 	/*
1594 	 * The directory is on the unlinked list and we found dirents.  This
1595 	 * directory needs to be reachable via the directory tree.  Remove the
1596 	 * dir from the unlinked list and update nlink with the observed link
1597 	 * count.  If the directory has no parent, it will be moved to the
1598 	 * orphanage.
1599 	 */
1600 	pag = xfs_perag_get(sc->mp, XFS_INODE_TO_AGNO(dp));
1601 	if (!pag) {
1602 		ASSERT(0);
1603 		return -EFSCORRUPTED;
1604 	}
1605 
1606 	error = xfs_iunlink_remove(sc->tp, pag, dp);
1607 	xfs_perag_put(pag);
1608 	if (error)
1609 		return error;
1610 
1611 reset_nlink:
1612 	if (VFS_I(dp)->i_nlink != new_nlink)
1613 		set_nlink(VFS_I(dp), new_nlink);
1614 	return 0;
1615 }
1616 
1617 /*
1618  * Finish replaying stashed dirent updates, allocate a transaction for
1619  * exchanging data fork mappings, and take the ILOCKs of both directories
1620  * before we commit the new directory structure.
1621  */
1622 STATIC int
xrep_dir_finalize_tempdir(struct xrep_dir * rd)1623 xrep_dir_finalize_tempdir(
1624 	struct xrep_dir		*rd)
1625 {
1626 	struct xfs_scrub	*sc = rd->sc;
1627 	int			error;
1628 
1629 	if (!xfs_has_parent(sc->mp))
1630 		return xrep_tempexch_trans_alloc(sc, XFS_DATA_FORK, &rd->tx);
1631 
1632 	/*
1633 	 * Repair relies on the ILOCK to quiesce all possible dirent updates.
1634 	 * Replay all queued dirent updates into the tempdir before exchanging
1635 	 * the contents, even if that means dropping the ILOCKs and the
1636 	 * transaction.
1637 	 */
1638 	do {
1639 		error = xrep_dir_replay_updates(rd);
1640 		if (error)
1641 			return error;
1642 
1643 		error = xrep_tempexch_trans_alloc(sc, XFS_DATA_FORK, &rd->tx);
1644 		if (error)
1645 			return error;
1646 
1647 		if (xfarray_length(rd->dir_entries) == 0)
1648 			break;
1649 
1650 		xchk_trans_cancel(sc);
1651 		xrep_tempfile_iunlock_both(sc);
1652 	} while (!xchk_should_terminate(sc, &error));
1653 	return error;
1654 }
1655 
1656 /* Exchange the temporary directory's data fork with the one being repaired. */
1657 STATIC int
xrep_dir_swap(struct xrep_dir * rd)1658 xrep_dir_swap(
1659 	struct xrep_dir		*rd)
1660 {
1661 	struct xfs_scrub	*sc = rd->sc;
1662 	xfs_ino_t		ino;
1663 	bool			ip_local, temp_local;
1664 	int			error = 0;
1665 
1666 	/*
1667 	 * If we never found the parent for this directory, temporarily assign
1668 	 * the root dir as the parent; we'll move this to the orphanage after
1669 	 * exchanging the dir contents.  We hold the ILOCK of the dir being
1670 	 * repaired, so we're not worried about racy updates of dotdot.
1671 	 */
1672 	ASSERT(sc->ilock_flags & XFS_ILOCK_EXCL);
1673 	if (rd->pscan.parent_ino == NULLFSINO) {
1674 		rd->needs_adoption = true;
1675 		rd->pscan.parent_ino = rd->sc->mp->m_sb.sb_rootino;
1676 	}
1677 
1678 	/*
1679 	 * Reset the temporary directory's '..' entry to point to the parent
1680 	 * that we found.  The dirent replace code asserts if the dirent
1681 	 * already points at the new inumber, so we look it up here.
1682 	 *
1683 	 * It's also possible that this replacement could also expand a sf
1684 	 * tempdir into block format.
1685 	 */
1686 	error = xchk_dir_lookup(sc, rd->sc->tempip, &xfs_name_dotdot, &ino);
1687 	if (error)
1688 		return error;
1689 
1690 	if (rd->pscan.parent_ino != ino) {
1691 		error = xrep_dir_replace(rd, rd->sc->tempip, &xfs_name_dotdot,
1692 				rd->pscan.parent_ino, rd->tx.req.resblks);
1693 		if (error)
1694 			return error;
1695 	}
1696 
1697 	/*
1698 	 * Changing the dot and dotdot entries could have changed the shape of
1699 	 * the directory, so we recompute these.
1700 	 */
1701 	ip_local = sc->ip->i_df.if_format == XFS_DINODE_FMT_LOCAL;
1702 	temp_local = sc->tempip->i_df.if_format == XFS_DINODE_FMT_LOCAL;
1703 
1704 	/*
1705 	 * If the both files have a local format data fork and the rebuilt
1706 	 * directory data would fit in the repaired file's data fork, copy
1707 	 * the contents from the tempfile and update the directory link count.
1708 	 * We're done now.
1709 	 */
1710 	if (ip_local && temp_local &&
1711 	    sc->tempip->i_disk_size <= xfs_inode_data_fork_size(sc->ip)) {
1712 		xrep_tempfile_copyout_local(sc, XFS_DATA_FORK);
1713 		return xrep_dir_set_nlink(rd);
1714 	}
1715 
1716 	/*
1717 	 * Clean the transaction before we start working on exchanging
1718 	 * directory contents.
1719 	 */
1720 	error = xrep_tempfile_roll_trans(rd->sc);
1721 	if (error)
1722 		return error;
1723 
1724 	/* Otherwise, make sure both data forks are in block-mapping mode. */
1725 	error = xrep_dir_swap_prep(sc, temp_local, ip_local);
1726 	if (error)
1727 		return error;
1728 
1729 	/*
1730 	 * Set nlink of the directory in the same transaction sequence that
1731 	 * (atomically) commits the new directory data.
1732 	 */
1733 	error = xrep_dir_set_nlink(rd);
1734 	if (error)
1735 		return error;
1736 
1737 	return xrep_tempexch_contents(sc, &rd->tx);
1738 }
1739 
1740 /*
1741  * Exchange the new directory contents (which we created in the tempfile) with
1742  * the directory being repaired.
1743  */
1744 STATIC int
xrep_dir_rebuild_tree(struct xrep_dir * rd)1745 xrep_dir_rebuild_tree(
1746 	struct xrep_dir		*rd)
1747 {
1748 	struct xfs_scrub	*sc = rd->sc;
1749 	int			error;
1750 
1751 	trace_xrep_dir_rebuild_tree(sc->ip, rd->pscan.parent_ino);
1752 
1753 	/*
1754 	 * Take the IOLOCK on the temporary file so that we can run dir
1755 	 * operations with the same locks held as we would for a normal file.
1756 	 * We still hold sc->ip's IOLOCK.
1757 	 */
1758 	error = xrep_tempfile_iolock_polled(rd->sc);
1759 	if (error)
1760 		return error;
1761 
1762 	/*
1763 	 * Allocate transaction, lock inodes, and make sure that we've replayed
1764 	 * all the stashed dirent updates to the tempdir.  After this point,
1765 	 * we're ready to exchange data fork mappings.
1766 	 */
1767 	error = xrep_dir_finalize_tempdir(rd);
1768 	if (error)
1769 		return error;
1770 
1771 	if (xchk_iscan_aborted(&rd->pscan.iscan))
1772 		return -ECANCELED;
1773 
1774 	/*
1775 	 * Exchange the tempdir's data fork with the file being repaired.  This
1776 	 * recreates the transaction and re-takes the ILOCK in the scrub
1777 	 * context.
1778 	 */
1779 	error = xrep_dir_swap(rd);
1780 	if (error)
1781 		return error;
1782 
1783 	/*
1784 	 * Release the old directory blocks and reset the data fork of the temp
1785 	 * directory to an empty shortform directory because inactivation does
1786 	 * nothing for directories.
1787 	 */
1788 	error = xrep_dir_reset_fork(rd, I_INO(sc->mp->m_rootip));
1789 	if (error)
1790 		return error;
1791 
1792 	/*
1793 	 * Roll to get a transaction without any inodes joined to it.  Then we
1794 	 * can drop the tempfile's ILOCK and IOLOCK before doing more work on
1795 	 * the scrub target directory.
1796 	 */
1797 	error = xfs_trans_roll(&sc->tp);
1798 	if (error)
1799 		return error;
1800 
1801 	xrep_tempfile_iunlock(sc);
1802 	xrep_tempfile_iounlock(sc);
1803 	return 0;
1804 }
1805 
1806 /* Set up the filesystem scan so we can regenerate directory entries. */
1807 STATIC int
xrep_dir_setup_scan(struct xrep_dir * rd)1808 xrep_dir_setup_scan(
1809 	struct xrep_dir		*rd)
1810 {
1811 	struct xfs_scrub	*sc = rd->sc;
1812 	int			error;
1813 
1814 	/* Set up some staging memory for salvaging dirents. */
1815 	error = xfarray_create("directory entries", 0,
1816 			sizeof(struct xrep_dirent), &rd->dir_entries);
1817 	if (error)
1818 		return error;
1819 
1820 	error = xfblob_create("directory entry names", &rd->dir_names);
1821 	if (error)
1822 		goto out_xfarray;
1823 
1824 	if (xfs_has_parent(sc->mp))
1825 		error = __xrep_findparent_scan_start(sc, &rd->pscan,
1826 				xrep_dir_live_update);
1827 	else
1828 		error = xrep_findparent_scan_start(sc, &rd->pscan);
1829 	if (error)
1830 		goto out_xfblob;
1831 
1832 	return 0;
1833 
1834 out_xfblob:
1835 	xfblob_destroy(rd->dir_names);
1836 	rd->dir_names = NULL;
1837 out_xfarray:
1838 	xfarray_destroy(rd->dir_entries);
1839 	rd->dir_entries = NULL;
1840 	return error;
1841 }
1842 
1843 /*
1844  * Move the current file to the orphanage.
1845  *
1846  * Caller must hold IOLOCK_EXCL on @sc->ip, and no other inode locks.  Upon
1847  * successful return, the scrub transaction will have enough extra reservation
1848  * to make the move; it will hold IOLOCK_EXCL and ILOCK_EXCL of @sc->ip and the
1849  * orphanage; and both inodes will be ijoined.
1850  */
1851 STATIC int
xrep_dir_move_to_orphanage(struct xrep_dir * rd)1852 xrep_dir_move_to_orphanage(
1853 	struct xrep_dir		*rd)
1854 {
1855 	struct xfs_scrub	*sc = rd->sc;
1856 	xfs_ino_t		orig_parent, new_parent;
1857 	int			error;
1858 
1859 	/*
1860 	 * We are about to drop the ILOCK on sc->ip to lock the orphanage and
1861 	 * prepare for the adoption.  Therefore, look up the old dotdot entry
1862 	 * for sc->ip so that we can compare it after we re-lock sc->ip.
1863 	 */
1864 	error = xchk_dir_lookup(sc, sc->ip, &xfs_name_dotdot, &orig_parent);
1865 	if (error)
1866 		return error;
1867 
1868 	/*
1869 	 * Drop the ILOCK on the scrub target and commit the transaction.
1870 	 * Adoption computes its own resource requirements and gathers the
1871 	 * necessary components.
1872 	 */
1873 	error = xrep_trans_commit(sc);
1874 	if (error)
1875 		return error;
1876 	xchk_iunlock(sc, XFS_ILOCK_EXCL);
1877 
1878 	/* If we can take the orphanage's iolock then we're ready to move. */
1879 	if (!xrep_orphanage_ilock_nowait(sc, XFS_IOLOCK_EXCL)) {
1880 		xchk_iunlock(sc, sc->ilock_flags);
1881 		error = xrep_orphanage_iolock_two(sc);
1882 		if (error)
1883 			return error;
1884 	}
1885 
1886 	/* Grab transaction and ILOCK the two files. */
1887 	error = xrep_adoption_trans_alloc(sc, &rd->adoption);
1888 	if (error)
1889 		return error;
1890 
1891 	error = xrep_adoption_compute_name(&rd->adoption, &rd->xname);
1892 	if (error)
1893 		return error;
1894 
1895 	/*
1896 	 * Now that we've reacquired the ILOCK on sc->ip, look up the dotdot
1897 	 * entry again.  If the parent changed or the child was unlinked while
1898 	 * the child directory was unlocked, we don't need to move the child to
1899 	 * the orphanage after all.
1900 	 */
1901 	error = xchk_dir_lookup(sc, sc->ip, &xfs_name_dotdot, &new_parent);
1902 	if (error)
1903 		return error;
1904 
1905 	/*
1906 	 * Attach to the orphanage if we still have a linked directory and it
1907 	 * hasn't been moved.
1908 	 */
1909 	if (orig_parent == new_parent && VFS_I(sc->ip)->i_nlink > 0) {
1910 		error = xrep_adoption_move(&rd->adoption);
1911 		if (error)
1912 			return error;
1913 	}
1914 
1915 	/*
1916 	 * Launder the scrub transaction so we can drop the orphanage ILOCK
1917 	 * and IOLOCK.  Return holding the scrub target's ILOCK and IOLOCK.
1918 	 */
1919 	error = xrep_adoption_trans_roll(&rd->adoption);
1920 	if (error)
1921 		return error;
1922 
1923 	xrep_orphanage_iunlock(sc, XFS_ILOCK_EXCL);
1924 	xrep_orphanage_iunlock(sc, XFS_IOLOCK_EXCL);
1925 	return 0;
1926 }
1927 
1928 /*
1929  * Repair the directory metadata.
1930  *
1931  * XXX: Directory entry buffers can be multiple fsblocks in size.  The buffer
1932  * cache in XFS can't handle aliased multiblock buffers, so this might
1933  * misbehave if the directory blocks are crosslinked with other filesystem
1934  * metadata.
1935  *
1936  * XXX: Is it necessary to check the dcache for this directory to make sure
1937  * that we always recreate every cached entry?
1938  */
1939 int
xrep_directory(struct xfs_scrub * sc)1940 xrep_directory(
1941 	struct xfs_scrub	*sc)
1942 {
1943 	struct xrep_dir		*rd = sc->buf;
1944 	int			error;
1945 
1946 	/* The rmapbt is required to reap the old data fork. */
1947 	if (!xfs_has_rmapbt(sc->mp))
1948 		return -EOPNOTSUPP;
1949 	/* We require atomic file exchange range to rebuild anything. */
1950 	if (!xfs_has_exchange_range(sc->mp))
1951 		return -EOPNOTSUPP;
1952 
1953 	error = xrep_dir_setup_scan(rd);
1954 	if (error)
1955 		return error;
1956 
1957 	if (xfs_has_parent(sc->mp))
1958 		error = xrep_dir_scan_dirtree(rd);
1959 	else
1960 		error = xrep_dir_salvage_entries(rd);
1961 	if (error)
1962 		goto out_teardown;
1963 
1964 	/* Last chance to abort before we start committing fixes. */
1965 	if (xchk_should_terminate(sc, &error))
1966 		goto out_teardown;
1967 
1968 	error = xrep_dir_rebuild_tree(rd);
1969 	if (error)
1970 		goto out_teardown;
1971 
1972 	if (rd->needs_adoption) {
1973 		if (!xrep_orphanage_can_adopt(rd->sc))
1974 			error = -EFSCORRUPTED;
1975 		else
1976 			error = xrep_dir_move_to_orphanage(rd);
1977 		if (error)
1978 			goto out_teardown;
1979 	}
1980 
1981 out_teardown:
1982 	xrep_dir_teardown(sc);
1983 	return error;
1984 }
1985