Skip to contentSkip to conversation

Freespace tree repair support

PATCH In review Nikolay Borisov 2 participants 13 messages Jun 15, 2018 – Sep 22, 2018 Btrfs file system

lore
Share & tools
lore
#0 lore raw

cover Freespace tree repair support

Hello,

This patchset adds support to btrfs check to repair corrupted freespace tree. Once this has been merged then we can start thinking of making the freespace tree the default freespace cache and deprecate the existing v1 cache in new filesystems.

This series depend on the already sent delayed refs. In order to facilitate testing the 2 series have been integrated and posted at :

https://github.com/lorddoskias/btrfs-progs.git dev/delayed-refs-fst

The main thing with this code is that the repair will always regenerate the FST with extents since it I haven't ported the code which deals with detecting that bitmaps are more space efficient. This is not a big deal since the kernel will do it.

The first patch is here for completeness' sake and was only used in a previous incarnation of this code but since I've re-worked the way the code is supposed to work it can be dropped. I don't have strong opinions either way. It just teaches btrfs_read_fs_root to return the freespace root

Patch 2 adds some low-level bit manipulation primitives which are necessary to support bitmap based FST. My initial idea was to completely ommit the bitmap support but in testing it turned out to be less pain to just include it from the get-go. Otherwise the filesystem created in the test case in patch 6 couldn't be worked on.

Patch 3 is mostly copy/paste from the kernel code bringin in necessary functions to repair the freespace tree. I've only omitted locking code since in userspace we are always single-threaded, also there is no support currently when regenerating FST to convert it to bitmap.

Patch 4 updates the compat_ro bitmask to allow reading an FST filesystem in repair mode.

Patch 5 adds the core code which utilizes everything added up until this point. It's not that big and should be fairly easy to review.

Patch 6 is a test-case which creates a filesystem with FST enabled, populates it with some files and then corrupts a bitmap and an extent records and tries to repair them. It's passing for me.

Nikolay Borisov (6):
btrfs-progs: Add support for freespace tree in btrfs_read_fs_root
btrfs-progs: Add extent buffer bitmap manipulation infrastructure
btrfs-progs: Pull free space tree related code from kernel
btrfs-progs: Add freespace tree as compat_ro supported feature
btrfs-progs: check: Add support for freespace tree fixing
btrfs-progs: tests: Test for FST corruption detection/repair

 check/main.c                                      |  61 +-
 ctree.c                                           |  77 ++
 ctree.h                                           |   8 +-
 disk-io.c                                         |   3 +
 extent-tree.c                                     |   9 +
 extent_io.c                                       |  39 +
 extent_io.h                                       |  15 +
 free-space-tree.c                                 | 893 +++++++++++++++++++++-
 free-space-tree.h                                 |  10 +-
 tests/fsck-tests/035-freespacetree-repair/test.sh |  79 ++
 10 files changed, 1163 insertions(+), 31 deletions(-)
 create mode 100755 tests/fsck-tests/035-freespacetree-repair/test.sh
Signature · 1 line
2.7.4
#1 lore raw

PATCH 1/6 btrfs-progs: Add support for freespace tree in btrfs_read_fs_root

For completeness sake add code to btrfs_read_fs_root so that it can handle the freespace tree.

---
 disk-io.c | 3 +++
 1 file changed, 3 insertions(+)
disk-io.c +3 -0
index 8da6e3ce5fc8..9ad826b83b3e 100644
@@ -664,6 +664,9 @@ struct btrfs_root *btrfs_read_fs_root(struct btrfs_fs_info *fs_info,
 	if (location->objectid == BTRFS_QUOTA_TREE_OBJECTID)
 		return fs_info->quota_enabled ? fs_info->quota_root :
 				ERR_PTR(-ENOENT);
+	if (location->objectid == BTRFS_FREE_SPACE_TREE_OBJECTID)
+        return fs_info->free_space_root ? fs_info->free_space_root :
+                                                  ERR_PTR(-ENOENT);
 
 	BUG_ON(location->objectid == BTRFS_TREE_RELOC_OBJECTID ||
 	       location->offset != (u64)-1);
Signature · 1 line
2.7.4
Reviewed-by on v1 1/6
#2 lore raw

Re: [PATCH 1/6] btrfs-progs: Add support for freespace tree in btrfs_read_fs_root

Quoted 2 lines · Nikolay Borisov

For completeness sake add code to btrfs_read_fs_root so that it can handle the freespace tree.

Quoted 22 lines
---
 disk-io.c | 3 +++
 1 file changed, 3 insertions(+)
disk-io.c +3 -0
index 8da6e3ce5fc8..9ad826b83b3e 100644
@@ -664,6 +664,9 @@ struct btrfs_root *btrfs_read_fs_root(struct btrfs_fs_info *fs_info,
 	if (location->objectid == BTRFS_QUOTA_TREE_OBJECTID)
 		return fs_info->quota_enabled ? fs_info->quota_root :
 				ERR_PTR(-ENOENT);
+	if (location->objectid == BTRFS_FREE_SPACE_TREE_OBJECTID)
+        return fs_info->free_space_root ? fs_info->free_space_root :
+                                                  ERR_PTR(-ENOENT);
 
 	BUG_ON(location->objectid == BTRFS_TREE_RELOC_OBJECTID ||
 	       location->offset != (u64)-1);
Signature · 1 line
2.7.4
#3 lore raw

PATCH 2/6 btrfs-progs: Add extent buffer bitmap manipulation infrastructure

In reply to Nikolay Borisov

Those functions are in preparation for adding the freespace tree repair code since it needs to be able to deal with bitmap based fsts. This patch adds extent_buffer_bitmap_set and extent_buffer_bitmap_clear functions. Since in userspace we don't have to deal with page mappings their implementation is vastly simplified by simply setting each bit in the passed range.

---
 extent_io.c | 39 +++++++++++++++++++++++++++++++++++++++
 extent_io.h | 15 +++++++++++++++
 2 files changed, 54 insertions(+)
extent_io.c +39 -0
index 198492699438..568a12f7084b 100644
@@ -204,6 +204,45 @@ static int clear_state_bit(struct extent_io_tree *tree,
 	return ret;
 }
 
+/**
+ * extent_buffer_bitmap_set - set an area of a bitmap
+ * @eb: the extent buffer
+ * @start: offset of the bitmap item in the extent buffer
+ * @pos: bit number of the first bit
+ * @len: number of bits to set
+ */
+void extent_buffer_bitmap_set(struct extent_buffer *eb, unsigned long start,
+                              unsigned long pos, unsigned long len)
+{
+        u8 *kaddr = (u8 *)eb->data + start;
+
+        while (len) {
+		le_set_bit(pos, kaddr);
+		pos++;
+		len--;
+        }
+}
+
+
+/**
+ * extent_buffer_bitmap_clear - clear an area of a bitmap
+ * @eb: the extent buffer
+ * @start: offset of the bitmap item in the extent buffer
+ * @pos: bit number of the first bit
+ * @len: number of bits to clear
+ */
+void extent_buffer_bitmap_clear(struct extent_buffer *eb, unsigned long start,
+                                unsigned long pos, unsigned long len)
+{
+        u8 *kaddr = (u8 *)eb->data + start;
+
+        while (len) {
+		le_clear_bit(pos, kaddr);
+		pos++;
+		len--;
+        }
+}
+
 /*
  * clear some bits on a range in the tree.
  */
extent_io.h +15 -0
index d407d93d617e..f9097911f5ef 100644
@@ -68,6 +68,17 @@ static inline int le_test_bit(int nr, const u8 *addr)
 	return 1U & (addr[BIT_BYTE(nr)] >> (nr & (BITS_PER_BYTE-1)));
 }
 
+
+static inline void le_set_bit(int nr, u8 *addr)
+{
+	addr[BIT_BYTE(nr)] |= (1U << (nr & (BITS_PER_BYTE-1)));
+}
+
+static inline void le_clear_bit(int nr, u8 *addr)
+{
+	addr[BIT_BYTE(nr)] &= ~(1U << (nr & (BITS_PER_BYTE-1)));
+}
+
 struct btrfs_fs_info;
 
 struct extent_io_tree {
@@ -175,4 +186,8 @@ int read_data_from_disk(struct btrfs_fs_info *info, void *buf, u64 offset,
 			u64 bytes, int mirror);
 int write_data_to_disk(struct btrfs_fs_info *info, void *buf, u64 offset,
 		       u64 bytes, int mirror);
+void extent_buffer_bitmap_clear(struct extent_buffer *eb, unsigned long start,
+                                unsigned long pos, unsigned long len);
+void extent_buffer_bitmap_set(struct extent_buffer *eb, unsigned long start,
+                              unsigned long pos, unsigned long len);
 #endif
Signature · 1 line
2.7.4
#4 lore raw

Re: [PATCH 2/6] btrfs-progs: Add extent buffer bitmap manipulation infrastructure

Quoted 50 lines · Nikolay Borisov

Those functions are in preparation for adding the freespace tree repair code since it needs to be able to deal with bitmap based fsts. This patch adds extent_buffer_bitmap_set and extent_buffer_bitmap_clear functions. Since in userspace we don't have to deal with page mappings their implementation is vastly simplified by simply setting each bit in the passed range.

---
 extent_io.c | 39 +++++++++++++++++++++++++++++++++++++++
 extent_io.h | 15 +++++++++++++++
 2 files changed, 54 insertions(+)
extent_io.c +29 -0
index 198492699438..568a12f7084b 100644
@@ -204,6 +204,45 @@ static int clear_state_bit(struct extent_io_tree *tree,
 	return ret;
 }
 
+/**
+ * extent_buffer_bitmap_set - set an area of a bitmap
+ * @eb: the extent buffer
+ * @start: offset of the bitmap item in the extent buffer
+ * @pos: bit number of the first bit
+ * @len: number of bits to set
+ */
+void extent_buffer_bitmap_set(struct extent_buffer *eb, unsigned long start,
+                              unsigned long pos, unsigned long len)
+{
+        u8 *kaddr = (u8 *)eb->data + start;
+
+        while (len) {
+		le_set_bit(pos, kaddr);
+		pos++;
+		len--;
+        }
+}
+
+
+/**
+ * extent_buffer_bitmap_clear - clear an area of a bitmap
+ * @eb: the extent buffer
+ * @start: offset of the bitmap item in the extent buffer
+ * @pos: bit number of the first bit
+ * @len: number of bits to clear
+ */
+void extent_buffer_bitmap_clear(struct extent_buffer *eb, unsigned long start,
+                                unsigned long pos, unsigned long len)

extent_io.c static int clear_state_bit(struct extent_io_tree *tree, · line 245

Quoted 10 lines
extent_io.c +10 -0
+{
+        u8 *kaddr = (u8 *)eb->data + start;
+
+        while (len) {
+		le_clear_bit(pos, kaddr);
+		pos++;
+		len--;
+        }
+}
+

Hm, bit-by-bit is pretty slow. We don't have to worry about the kmap nonsense, but we can still do this byte-by-byte:

/**
* extent_buffer_bitmap_set - set an area of a bitmap
* @eb: the extent buffer
* @start: offset of the bitmap item in the extent buffer
* @pos: bit number of the first bit
* @len: number of bits to set
*/
void extent_buffer_bitmap_set(struct extent_buffer *eb, unsigned long start,
unsigned long pos, unsigned long len)

{
        u8 *p = (u8 *)eb->data + start + BIT_BYTE(pos);
	const unsigned int size = pos + len;
	int bits_to_set = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
	u8 mask_to_set = BITMAP_FIRST_BYTE_MASK(pos);

	while (len >= bits_to_set) {
		*p |= mask_to_set;
		len -= bits_to_set;
		bits_to_set = BITS_PER_BYTE;
		mask_to_set = ~0;
		p++;
	}
	if (len) {
		mask_to_set &= BITMAP_LAST_BYTE_MASK(size);
		*p |= mask_to_set;
	}
}

/**
* extent_buffer_bitmap_clear - clear an area of a bitmap
* @eb: the extent buffer
* @start: offset of the bitmap item in the extent buffer
* @pos: bit number of the first bit
* @len: number of bits to clear
*/
void extent_buffer_bitmap_clear(struct extent_buffer *eb, unsigned long start,
unsigned long pos, unsigned long len)

{
        u8 *p = (u8 *)eb->data + start + BIT_BYTE(pos);
	const unsigned int size = pos + len;
	int bits_to_clear = BITS_PER_BYTE - (pos % BITS_PER_BYTE);
	u8 mask_to_clear = BITMAP_FIRST_BYTE_MASK(pos);

	while (len >= bits_to_clear) {
		*p &= ~mask_to_clear;
		len -= bits_to_clear;
		bits_to_clear = BITS_PER_BYTE;
		mask_to_clear = ~0;
		p++;
	}
	if (len) {
		mask_to_clear &= BITMAP_LAST_BYTE_MASK(size);
		*p &= ~mask_to_clear;
	}
}

I'm 95% sure that's right ;) Compare to __bitmap_set() and __bitmap_clear() in the kernel.

#5 lore raw

PATCH 3/6 btrfs-progs: Pull free space tree related code from kernel

In reply to Nikolay Borisov

To help implement free space tree checker in user space some kernel function are necessary, namely iterating/deleting/adding freespace items, some internal search functions. Functions to populate a block group based on the extent tree. The code is largely copy/paste from the kernel with locking eliminated (i.e free_space_lock). It supports reading/writing of both bitmap and extent based FST trees.

---
 ctree.c           |  77 +++++
 ctree.h           |   4 +
 free-space-tree.c | 893 +++++++++++++++++++++++++++++++++++++++++++++++++++++-
 free-space-tree.h |  10 +-
 4 files changed, 977 insertions(+), 7 deletions(-)
ctree.c +77 -0
index d8a6883aa85f..aa1568620205 100644
@@ -1226,6 +1226,83 @@ int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root
 }
 
 /*
+ * helper to use instead of search slot if no exact match is needed but
+ * instead the next or previous item should be returned.
+ * When find_higher is true, the next higher item is returned, the next lower
+ * otherwise.
+ * When return_any and find_higher are both true, and no higher item is found,
+ * return the next lower instead.
+ * When return_any is true and find_higher is false, and no lower item is found,
+ * return the next higher instead.
+ * It returns 0 if any item is found, 1 if none is found (tree empty), and
+ * < 0 on error
+ */
+int btrfs_search_slot_for_read(struct btrfs_root *root,
+                               const struct btrfs_key *key,
+                               struct btrfs_path *p, int find_higher,
+                               int return_any)
+{
+        int ret;
+        struct extent_buffer *leaf;
+
+again:
+        ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
+        if (ret <= 0)
+                return ret;
+        /*
+         * a return value of 1 means the path is at the position where the
+         * item should be inserted. Normally this is the next bigger item,
+         * but in case the previous item is the last in a leaf, path points
+         * to the first free slot in the previous leaf, i.e. at an invalid
+         * item.
+         */
+        leaf = p->nodes[0];
+
+        if (find_higher) {
+                if (p->slots[0] >= btrfs_header_nritems(leaf)) {
+                        ret = btrfs_next_leaf(root, p);
+                        if (ret <= 0)
+                                return ret;
+                        if (!return_any)
+                                return 1;
+                        /*
+                         * no higher item found, return the next
+                         * lower instead
+                         */
+                        return_any = 0;
+                        find_higher = 0;
+                        btrfs_release_path(p);
+                        goto again;
+                }
+        } else {
+                if (p->slots[0] == 0) {
+                        ret = btrfs_prev_leaf(root, p);
+                        if (ret < 0)
+                                return ret;
+                        if (!ret) {
+                                leaf = p->nodes[0];
+                                if (p->slots[0] == btrfs_header_nritems(leaf))
+                                        p->slots[0]--;
+                                return 0;
+                        }
+                        if (!return_any)
+                                return 1;
+                        /*
+                         * no lower item found, return the next
+                         * higher instead
+                         */
+                        return_any = 0;
+                        find_higher = 1;
+                        btrfs_release_path(p);
+                        goto again;
+                } else {
+                        --p->slots[0];
+                }
+        }
+        return 0;
+}
+
+/*
  * adjust the pointers going up the tree, starting at level
  * making sure the right key of each node is points to 'key'.
  * This is used after shifting pointers to the left, so it stops
ctree.h +4 -0
index 3e9ca2ca8432..ade883fecbd6 100644
@@ -2619,6 +2619,10 @@ int btrfs_split_item(struct btrfs_trans_handle *trans,
 int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root
 		      *root, struct btrfs_key *key, struct btrfs_path *p, int
 		      ins_len, int cow);
+int btrfs_search_slot_for_read(struct btrfs_root *root,
+                               const struct btrfs_key *key,
+                               struct btrfs_path *p, int find_higher,
+                               int return_any);
 int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *found_path,
 		u64 iobjectid, u64 ioff, u8 key_type,
 		struct btrfs_key *found_key);
free-space-tree.c +887 -6

926 lines not on this page · raw message

free-space-tree.h +9 -1
index 4845f13e6808..0509e9ae21ae 100644
@@ -22,5 +22,13 @@
 int btrfs_clear_free_space_tree(struct btrfs_fs_info *fs_info);
 int load_free_space_tree(struct btrfs_fs_info *fs_info,
 			 struct btrfs_block_group_cache *block_group);
-
+int populate_free_space_tree(struct btrfs_trans_handle *trans,
+			     struct btrfs_block_group_cache *block_group);
+int remove_block_group_free_space(struct btrfs_trans_handle *trans,
+				  struct btrfs_block_group_cache *block_group);
+int add_to_free_space_tree(struct btrfs_trans_handle *trans, u64 start,
+			   u64 size);
+int remove_from_free_space_tree(struct btrfs_trans_handle *trans, u64 start,
+				u64 size);
+int btrfs_create_free_space_tree(struct btrfs_fs_info *info);
 #endif
Signature · 1 line
2.7.4
#6 lore raw

Re: [PATCH 3/6] btrfs-progs: Pull free space tree related code from kernel

Quoted 8 lines · Nikolay Borisov

To help implement free space tree checker in user space some kernel function are necessary, namely iterating/deleting/adding freespace items, some internal search functions. Functions to populate a block group based on the extent tree. The code is largely copy/paste from the kernel with locking eliminated (i.e free_space_lock). It supports reading/writing of both bitmap and extent based FST trees.

Why doesn't this include the bitmap <-> extent conversions? If we end up rebuilding the free space tree, we're never going to use the bitmap format, which sucks if the free space is fragmented.

#7 lore raw

Re: [PATCH 3/6] btrfs-progs: Pull free space tree related code from kernel

Quoted 8 lines · Omar Sandoval
Quoted 7 lines · Nikolay Borisov

To help implement free space tree checker in user space some kernel function are necessary, namely iterating/deleting/adding freespace items, some internal search functions. Functions to populate a block group based on the extent tree. The code is largely copy/paste from the kernel with locking eliminated (i.e free_space_lock). It supports reading/writing of both bitmap and extent based FST trees.

Quoted 6 lines
Quoted 1 line

Why doesn't this include the bitmap <-> extent conversions? If we end up rebuilding the free space tree, we're never going to use the bitmap format, which sucks if the free space is fragmented.

The idea was to have *something* working initially and then add as deemed appropriate.

#8 lore raw

PATCH 4/6 btrfs-progs: Add freespace tree as compat_ro supported feature

In reply to Nikolay Borisov

The RO_FREE_SPACE_TREE(_VALID) flags are required in order to be able to open an FST filesystem in repair mode. Add them to BTRFS_FEATURE_COMPAT_RO_SUPP.

---
 ctree.h | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
ctree.h +3 -1
index ade883fecbd6..ef05e8122982 100644
@@ -497,7 +497,9 @@ struct btrfs_super_block {
  * added here until read-write support for the free space tree is implemented in
  * btrfs-progs.
  */
-#define BTRFS_FEATURE_COMPAT_RO_SUPP		0ULL
+#define BTRFS_FEATURE_COMPAT_RO_SUPP			\
+	(BTRFS_FEATURE_COMPAT_RO_FREE_SPACE_TREE |	\
+	 BTRFS_FEATURE_COMPAT_RO_FREE_SPACE_TREE_VALID)
 
 #define BTRFS_FEATURE_INCOMPAT_SUPP			\
 	(BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF |		\
Signature · 1 line
2.7.4
#9 lore raw

Re: [PATCH 4/6] btrfs-progs: Add freespace tree as compat_ro supported feature

Quoted 14 lines · Nikolay Borisov

The RO_FREE_SPACE_TREE(_VALID) flags are required in order to be able to open an FST filesystem in repair mode. Add them to BTRFS_FEATURE_COMPAT_RO_SUPP.

---
 ctree.h | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
ctree.h +0 -0
index ade883fecbd6..ef05e8122982 100644

ctree.h struct btrfs_super_block { · line 502

Quoted 7 lines
ctree.h +3 -1
@@ -497,7 +497,9 @@ struct btrfs_super_block {
  * added here until read-write support for the free space tree is implemented in
  * btrfs-progs.
  */
-#define BTRFS_FEATURE_COMPAT_RO_SUPP		0ULL
+#define BTRFS_FEATURE_COMPAT_RO_SUPP			\
+	(BTRFS_FEATURE_COMPAT_RO_FREE_SPACE_TREE |	\
+	 BTRFS_FEATURE_COMPAT_RO_FREE_SPACE_TREE_VALID)

Have you tested whether btrfs-progs commands that modify the filesystem (e.g., btrfstune or btrfs fi label) work with this series? Because that is a requirement for claiming that we support this bit (at which point we can delete the comment above). Also, this needs to happen _after_ we hook up the free space tree with the extent tree.

See here for some historical context:
https://www.mail-archive.com/[email protected]/msg57738.html

#10 lore raw

PATCH 5/6 btrfs-progs: check: Add support for freespace tree fixing

In reply to Nikolay Borisov

Now that all the prerequisite code for proper support of free space tree repair is in, it's time to wire it in. This is achieved by first hooking the freespace tree to the __free_extent/alloc_reserved_tree_block functions. And then introducing a wrapper function to contains the existing check_space_cache and the newly introduced repair code. Finally, it's important to note that FST repair code first clears the existing FST in case of any problem found and rebuilds it from scratch.

---
 check/main.c  | 61 +++++++++++++++++++++++++++++++++++++----------------------
 extent-tree.c |  9 +++++++++
 2 files changed, 47 insertions(+), 23 deletions(-)
check/main.c +38 -23
index 3a5efaf615a9..44d734ff4254 100644
@@ -5321,19 +5321,6 @@ static int check_space_cache(struct btrfs_root *root)
 	int ret;
 	int error = 0;
 
-	if (btrfs_super_cache_generation(root->fs_info->super_copy) != -1ULL &&
-	    btrfs_super_generation(root->fs_info->super_copy) !=
-	    btrfs_super_cache_generation(root->fs_info->super_copy)) {
-		printf("cache and super generation don't match, space cache "
-		       "will be invalidated\n");
-		return 0;
-	}
-
-	if (ctx.progress_enabled) {
-		ctx.tp = TASK_FREE_SPACE;
-		task_start(ctx.info);
-	}
-
 	while (1) {
 		cache = btrfs_lookup_first_block_group(root->fs_info, start);
 		if (!cache)
@@ -5383,11 +5370,11 @@ static int check_space_cache(struct btrfs_root *root)
 		}
 	}
 
-	task_stop(ctx.info);
 
 	return error ? -EINVAL : 0;
 }
 
+
 /*
  * Check data checksum for [@bytenr, @bytenr + @num_bytes).
  *
@@ -9338,7 +9325,6 @@ static int do_clear_free_space_cache(struct btrfs_fs_info *fs_info,
 			ret = 1;
 			goto close_out;
 		}
-		printf("Clearing free space cache\n");
 		ret = clear_free_space_cache(fs_info);
 		if (ret) {
 			error("failed to clear free space cache");
@@ -9365,6 +9351,41 @@ static int do_clear_free_space_cache(struct btrfs_fs_info *fs_info,
 	return ret;
 }
 
+static int validate_free_space_cache(struct btrfs_root *root)
+{
+
+	int ret;
+
+	if (btrfs_super_cache_generation(root->fs_info->super_copy) != -1ULL &&
+	    btrfs_super_generation(root->fs_info->super_copy) !=
+	    btrfs_super_cache_generation(root->fs_info->super_copy)) {
+		printf("cache and super generation don't match, space cache "
+		       "will be invalidated\n");
+		return 0;
+	}
+
+	if (ctx.progress_enabled) {
+		ctx.tp = TASK_FREE_SPACE;
+		task_start(ctx.info);
+	}
+
+	ret = check_space_cache(root);
+	if (ret && btrfs_fs_compat_ro(global_info, FREE_SPACE_TREE)
+	    && repair) {
+		ret = do_clear_free_space_cache(global_info, 2);
+		if (ret)
+			goto out;
+
+		ret = btrfs_create_free_space_tree(global_info);
+		if (ret)
+			error("couldn't repair freespace tree");
+	}
+
+out:
+	task_stop(ctx.info);
+	return ret ? -EINVAL : 0;
+}
+
 const char * const cmd_check_usage[] = {
 	"btrfs check [options] <device>",
 	"Check structural integrity of a filesystem (unmounted).",
@@ -9768,15 +9789,9 @@ int cmd_check(int argc, char **argv)
 		else
 			fprintf(stderr, "checking free space cache\n");
 	}
-	ret = check_space_cache(root);
+
+	ret = validate_free_space_cache(root);
 	err |= !!ret;
-	if (ret) {
-		if (btrfs_fs_compat_ro(info, FREE_SPACE_TREE))
-			error("errors found in free space tree");
-		else
-			error("errors found in free space cache");
-		goto out;
-	}
 
 	/*
 	 * We used to have to have these hole extents in between our real
extent-tree.c +9 -0
index b9d51b388c9a..40117f81352e 100644
@@ -29,6 +29,7 @@
 #include "crc32c.h"
 #include "volumes.h"
 #include "free-space-cache.h"
+#include "free-space-tree.h"
 #include "utils.h"
 
 #define PENDING_EXTENT_INSERT 0
@@ -2292,6 +2293,11 @@ static int __free_extent(struct btrfs_trans_handle *trans,
 			BUG_ON(ret);
 		}
 
+		ret = add_to_free_space_tree(trans, bytenr, num_bytes);
+		if (ret) {
+			goto fail;
+		}
+
 		update_block_group(trans->fs_info, bytenr, num_bytes, 0,
 				   mark_free);
 	}
@@ -2630,6 +2636,9 @@ static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
 	btrfs_mark_buffer_dirty(leaf);
 	btrfs_free_path(path);
 
+	ret = remove_from_free_space_tree(trans, ins->objectid, fs_info->nodesize);
+	if (ret)
+		return ret;
 	ret = update_block_group(fs_info, ins->objectid, fs_info->nodesize,
 				 1, 0);
 	return ret;
Signature · 1 line
2.7.4
#11 lore raw

Re: [PATCH 5/6] btrfs-progs: check: Add support for freespace tree fixing

Quoted 39 lines · Nikolay Borisov

Now that all the prerequisite code for proper support of free space tree repair is in, it's time to wire it in. This is achieved by first hooking the freespace tree to the __free_extent/alloc_reserved_tree_block functions. And then introducing a wrapper function to contains the existing check_space_cache and the newly introduced repair code. Finally, it's important to note that FST repair code first clears the existing FST in case of any problem found and rebuilds it from scratch.

---
 check/main.c  | 61 +++++++++++++++++++++++++++++++++++++----------------------
 extent-tree.c |  9 +++++++++
 2 files changed, 47 insertions(+), 23 deletions(-)
check/main.c +0 -13
index 3a5efaf615a9..44d734ff4254 100644
@@ -5321,19 +5321,6 @@ static int check_space_cache(struct btrfs_root *root)
 	int ret;
 	int error = 0;
 
-	if (btrfs_super_cache_generation(root->fs_info->super_copy) != -1ULL &&
-	    btrfs_super_generation(root->fs_info->super_copy) !=
-	    btrfs_super_cache_generation(root->fs_info->super_copy)) {
-		printf("cache and super generation don't match, space cache "
-		       "will be invalidated\n");
-		return 0;
-	}
-
-	if (ctx.progress_enabled) {
-		ctx.tp = TASK_FREE_SPACE;
-		task_start(ctx.info);
-	}
-
 	while (1) {
 		cache = btrfs_lookup_first_block_group(root->fs_info, start);
 		if (!cache)

check/main.c static int check_space_cache(struct btrfs_root *root) · line 5377

Quoted 9 lines
check/main.c +1 -1
@@ -5383,11 +5370,11 @@ static int check_space_cache(struct btrfs_root *root)
 		}
 	}
 
-	task_stop(ctx.info);
 
 	return error ? -EINVAL : 0;
 }
 
+

Stray newline.

Quoted 61 lines
check/main.c +37 -2
 /*
  * Check data checksum for [@bytenr, @bytenr + @num_bytes).
  *
@@ -9338,7 +9325,6 @@ static int do_clear_free_space_cache(struct btrfs_fs_info *fs_info,
 			ret = 1;
 			goto close_out;
 		}
-		printf("Clearing free space cache\n");
 		ret = clear_free_space_cache(fs_info);
 		if (ret) {
 			error("failed to clear free space cache");
@@ -9365,6 +9351,41 @@ static int do_clear_free_space_cache(struct btrfs_fs_info *fs_info,
 	return ret;
 }
 
+static int validate_free_space_cache(struct btrfs_root *root)
+{
+
+	int ret;
+
+	if (btrfs_super_cache_generation(root->fs_info->super_copy) != -1ULL &&
+	    btrfs_super_generation(root->fs_info->super_copy) !=
+	    btrfs_super_cache_generation(root->fs_info->super_copy)) {
+		printf("cache and super generation don't match, space cache "
+		       "will be invalidated\n");
+		return 0;
+	}
+
+	if (ctx.progress_enabled) {
+		ctx.tp = TASK_FREE_SPACE;
+		task_start(ctx.info);
+	}
+
+	ret = check_space_cache(root);
+	if (ret && btrfs_fs_compat_ro(global_info, FREE_SPACE_TREE)
+	    && repair) {
+		ret = do_clear_free_space_cache(global_info, 2);
+		if (ret)
+			goto out;
+
+		ret = btrfs_create_free_space_tree(global_info);
+		if (ret)
+			error("couldn't repair freespace tree");
+	}
+
+out:
+	task_stop(ctx.info);
+	return ret ? -EINVAL : 0;
+}
+
 const char * const cmd_check_usage[] = {
 	"btrfs check [options] <device>",
 	"Check structural integrity of a filesystem (unmounted).",
@@ -9768,15 +9789,9 @@ int cmd_check(int argc, char **argv)
 		else
 			fprintf(stderr, "checking free space cache\n");
 	}
-	ret = check_space_cache(root);
+
+	ret = validate_free_space_cache(root);
 	err |= !!ret;

check/main.c int cmd_check(int argc, char **argv) · line 9797

Quoted 10 lines
check/main.c +0 -7
-	if (ret) {
-		if (btrfs_fs_compat_ro(info, FREE_SPACE_TREE))
-			error("errors found in free space tree");
-		else
-			error("errors found in free space cache");
-		goto out;
-	}
 
 	/*
 	 * We used to have to have these hole extents in between our real

This approach seems reasonable.

Quoted 25 lines
extent-tree.c +6 -0
index b9d51b388c9a..40117f81352e 100644
@@ -29,6 +29,7 @@
 #include "crc32c.h"
 #include "volumes.h"
 #include "free-space-cache.h"
+#include "free-space-tree.h"
 #include "utils.h"
 
 #define PENDING_EXTENT_INSERT 0
@@ -2292,6 +2293,11 @@ static int __free_extent(struct btrfs_trans_handle *trans,
 			BUG_ON(ret);
 		}
 
+		ret = add_to_free_space_tree(trans, bytenr, num_bytes);
+		if (ret) {
+			goto fail;
+		}
+
 		update_block_group(trans->fs_info, bytenr, num_bytes, 0,
 				   mark_free);
 	}

extent-tree.c static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans, · line 2644

Quoted 9 lines
extent-tree.c +3 -0
@@ -2630,6 +2636,9 @@ static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
 	btrfs_mark_buffer_dirty(leaf);
 	btrfs_free_path(path);
 
+	ret = remove_from_free_space_tree(trans, ins->objectid, fs_info->nodesize);
+	if (ret)
+		return ret;
 	ret = update_block_group(fs_info, ins->objectid, fs_info->nodesize,
 				 1, 0);
 	return ret;

Related to my comment on patch 4, the extent-tree.c changes should be a separate patch that comes before we add the compat bit, assuming it works with commands that open_ctree(..., OPEN_CTREE_WRITES) and modify the fs.

#12 lore raw

PATCH 6/6 btrfs-progs: tests: Test for FST corruption detection/repair

In reply to Nikolay Borisov

Simple test case which preps a filesystem, then corrupts the FST and finally repairs it. Tests both extent based and bitmap based FSTs.

---
 tests/fsck-tests/035-freespacetree-repair/test.sh | 79 +++++++++++++++++++++++
 1 file changed, 79 insertions(+)
 create mode 100755 tests/fsck-tests/035-freespacetree-repair/test.sh
tests/fsck-tests/035-freespacetree-repair/test.sh new file +79 -0
new file mode 100755
index 000000000000..e19d997b3d6a
@@ -0,0 +1,79 @@
+#!/bin/bash
+# Corrupt a filesystem that is using freespace tree and then ensure that 
+# btrfs check is able to repair it. This tests correct detection/repair of 
+# both a FREE_SPACE_EXTENT based FST and a FREE_SPACE_BITMAP based FST. 
+
+source "$TEST_TOP/common"
+
+repair_and_verify()
+{
+	# since repairing entails allocating a block, which in turn implies 
+	# FST modification another btrfs check is required to ensure that 
+	# FST modification logic is correct. 
+	run_check $SUDO_HELPER "$TOP/btrfs" check --repair "$TEST_DEV"
+	run_check $SUDO_HELPER "$TOP/btrfs" check "$TEST_DEV"
+}
+
+# wrapper for btrfs-corrupt-item
+# $1: Type of item we want to corrupt - extent or bitmap
+corrupt_fst_item()
+{
+	local type
+	local objectid
+	local offset
+	type="$1"
+
+	if [[ $type == "bitmap" ]]; then 
+		type=200
+		objectid=$("$TOP/btrfs" inspect-internal dump-tree -t 10 "$TEST_DEV" | \
+			grep -o "[[:digit:]]* FREE_SPACE_BITMAP [[:digit:]]*" | \
+			cut -d' ' -f1 | tail -2 | head -1)
+		offset=$("$TOP/btrfs" inspect-internal dump-tree -t 10 "$TEST_DEV" | \
+			grep -o "[[:digit:]]* FREE_SPACE_BITMAP [[:digit:]]*" | \
+			cut -d' ' -f3 |tail -2 | head -1)
+		echo "Corrupting $objectid,FREE_SPACE_BITMAP,$offset"
+	elif [[ $type == "extent" ]]; then
+		type=199
+		objectid=$("$TOP/btrfs" inspect-internal dump-tree -t 10 "$TEST_DEV" | \
+			grep -o "[[:digit:]]* FREE_SPACE_EXTENT [[:digit:]]*" | \
+			cut -d' ' -f1 | tail -2 | head -1)
+		offset=$("$TOP/btrfs" inspect-internal dump-tree -t 10 "$TEST_DEV" | \
+			grep -o "[[:digit:]]* FREE_SPACE_EXTENT [[:digit:]]*" | \
+			cut -d' ' -f3 | tail -2 | head -1)
+		echo "Corrupting $objectid,FREE_SPACE_EXTENT,$offset"
+	else
+		_fail "Unknown item type for corruption"
+	fi
+	
+
+	run_check "$TOP/btrfs-corrupt-block" -r 10 -K "$objectid,$type,$offset" \
+		-f offset "$TEST_DEV"
+}
+
+check_prereq btrfs
+check_prereq mkfs.btrfs
+check_global_prereq grep
+check_global_prereq tail 
+check_global_prereq head
+check_global_prereq cut
+
+setup_root_helper
+prepare_test_dev 256M
+
+run_check "$TOP/mkfs.btrfs" -n 4k -f "$TEST_DEV"
+run_check_mount_test_dev -oclear_cache,space_cache=v2
+
+#create files which will populate the FST
+for i in {1..3000}; do
+	fallocate -l 4k "$TEST_MNT/file.$i" 
+done
+
+run_check_umount_test_dev
+
+#now corrupt one of the bitmap items 
+corrupt_fst_item "bitmap"
+check_image "$TEST_DEV"
+
+#now corrupt an extent 
+corrupt_fst_item "extent"
+check_image "$TEST_DEV"
Signature · 1 line
2.7.4