Skip to contentSkip to conversation

btrfs: fix memory leaks in create_space_info error paths

PATCH In review Jiasheng Jiang 2 participants 2 messages Jan 11 Btrfs file system

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 btrfs: fix memory leaks in create_space_info error paths

In create_space_info(), the 'space_info' object is allocated at the beginning of the function. However, there are two error paths where the function returns an error code without freeing the allocated memory:

1. When create_space_info_sub_group() fails in zoned mode.
2. When btrfs_sysfs_add_space_info_type() fails.

In both cases, 'space_info' has not yet been added to the fs_info->space_info list, resulting in a memory leak. Fix this by adding an error handling label to kfree(space_info) before returning.

Fixes 2be12ef79fe9 ("btrfs: Separate space_info create/update")
---
 fs/btrfs/space-info.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
fs/btrfs/space-info.c +6 -2
index 6babbe333741..3f08e450f796 100644
@@ -306,18 +306,22 @@ static int create_space_info(struct btrfs_fs_info *info, u64 flags)
 							  0);
 
 		if (ret)
-			return ret;
+			goto out_free;
 	}
 
 	ret = btrfs_sysfs_add_space_info_type(space_info);
 	if (ret)
-		return ret;
+		goto out_free;
 
 	list_add(&space_info->list, &info->space_info);
 	if (flags & BTRFS_BLOCK_GROUP_DATA)
 		info->data_sinfo = space_info;
 
 	return ret;
+
+out_free:
+	kfree(space_info);
+	return ret;
 }
 
 int btrfs_init_space_info(struct btrfs_fs_info *fs_info)
Signature · 1 line
2.25.1
Reviewed-by on v1 1/1
#1 lore raw
Quoted 7 lines · Jiasheng Jiang

In create_space_info(), the 'space_info' object is allocated at the beginning of the function. However, there are two error paths where the function returns an error code without freeing the allocated memory:

1. When create_space_info_sub_group() fails in zoned mode.
2. When btrfs_sysfs_add_space_info_type() fails.

Quoted 6 lines

In both cases, 'space_info' has not yet been added to the fs_info->space_info list, resulting in a memory leak. Fix this by adding an error handling label to kfree(space_info) before returning.

Fixes 2be12ef79fe9 ("btrfs: Separate space_info create/update")

Thanks,
Qu

Quoted 33 lines
---
  fs/btrfs/space-info.c | 8 ++++++--
  1 file changed, 6 insertions(+), 2 deletions(-)
fs/btrfs/space-info.c +6 -2
index 6babbe333741..3f08e450f796 100644
@@ -306,18 +306,22 @@ static int create_space_info(struct btrfs_fs_info *info, u64 flags)
  							  0);
 
  		if (ret)
-			return ret;
+			goto out_free;
  	}
 
  	ret = btrfs_sysfs_add_space_info_type(space_info);
  	if (ret)
-		return ret;
+		goto out_free;
 
  	list_add(&space_info->list, &info->space_info);
  	if (flags & BTRFS_BLOCK_GROUP_DATA)
  		info->data_sinfo = space_info;
 
  	return ret;
+
+out_free:
+	kfree(space_info);
+	return ret;
  }
 
  int btrfs_init_space_info(struct btrfs_fs_info *fs_info)