[PATCH 1/2] btrfs: return early if allocations fail on add_block_entry()

Miquel Sabaté Solà posted 2 patches 1 month, 1 week ago
[PATCH 1/2] btrfs: return early if allocations fail on add_block_entry()
Posted by Miquel Sabaté Solà 1 month, 1 week ago
In add_block_entry(), if the allocation of 're' fails, return right away
instead of trying to allocate 'be' next. This also removes a useless
kfree() call.

Signed-off-by: Miquel Sabaté Solà <mssola@mssola.com>
---
 fs/btrfs/ref-verify.c | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/fs/btrfs/ref-verify.c b/fs/btrfs/ref-verify.c
index f78369ff2a66..7b4d52db7897 100644
--- a/fs/btrfs/ref-verify.c
+++ b/fs/btrfs/ref-verify.c
@@ -246,14 +246,16 @@ static struct block_entry *add_block_entry(struct btrfs_fs_info *fs_info,
 					   u64 bytenr, u64 len,
 					   u64 root_objectid)
 {
-	struct block_entry *be = NULL, *exist;
-	struct root_entry *re = NULL;
+	struct block_entry *be, *exist;
+	struct root_entry *re;
 
 	re = kzalloc_obj(struct root_entry, GFP_NOFS);
+	if (!re)
+		return ERR_PTR(-ENOMEM);
+
 	be = kzalloc_obj(struct block_entry, GFP_NOFS);
-	if (!be || !re) {
+	if (!be) {
 		kfree(re);
-		kfree(be);
 		return ERR_PTR(-ENOMEM);
 	}
 	be->bytenr = bytenr;
-- 
2.53.0

Re: [PATCH 1/2] btrfs: return early if allocations fail on add_block_entry()
Posted by Qu Wenruo 1 month, 1 week ago

在 2026/2/28 01:47, Miquel Sabaté Solà 写道:
> In add_block_entry(), if the allocation of 're' fails, return right away
> instead of trying to allocate 'be' next. This also removes a useless
> kfree() call.
> 
> Signed-off-by: Miquel Sabaté Solà <mssola@mssola.com>

Please don't.

It's a common pattern for multiple allocations, and it's very expandable.
If you need to allocate new things, just a new allocation and add the 
pointer check into the if () condition.

It's way more expandable than checking each return pointer.

Thanks,
Qu

> ---
>   fs/btrfs/ref-verify.c | 10 ++++++----
>   1 file changed, 6 insertions(+), 4 deletions(-)
> 
> diff --git a/fs/btrfs/ref-verify.c b/fs/btrfs/ref-verify.c
> index f78369ff2a66..7b4d52db7897 100644
> --- a/fs/btrfs/ref-verify.c
> +++ b/fs/btrfs/ref-verify.c
> @@ -246,14 +246,16 @@ static struct block_entry *add_block_entry(struct btrfs_fs_info *fs_info,
>   					   u64 bytenr, u64 len,
>   					   u64 root_objectid)
>   {
> -	struct block_entry *be = NULL, *exist;
> -	struct root_entry *re = NULL;
> +	struct block_entry *be, *exist;
> +	struct root_entry *re;
>   
>   	re = kzalloc_obj(struct root_entry, GFP_NOFS);
> +	if (!re)
> +		return ERR_PTR(-ENOMEM);
> +
>   	be = kzalloc_obj(struct block_entry, GFP_NOFS);
> -	if (!be || !re) {
> +	if (!be) {
>   		kfree(re);
> -		kfree(be);
>   		return ERR_PTR(-ENOMEM);
>   	}
>   	be->bytenr = bytenr;