RE: [PATCH] cxl: Fix memory leak bug in alloc_mock_res()

Dan Williams posted 1 patch 2 years, 6 months ago
RE: [PATCH] cxl: Fix memory leak bug in alloc_mock_res()
Posted by Dan Williams 2 years, 6 months ago
Chenyuan Mi wrote:
> When gen_pool_alloc_algo() fails, the error handling path
> forgets to free 'res'. It would cause a memory leak bug.
> 
> Fix it by add kfree() in error handling path.

Going forward I want to set the policy that any error path resource leaks be
fixed by converting to using __free() and associated helpers.

So in this case it would be:

-- >8 --
diff --git a/tools/testing/cxl/test/cxl.c b/tools/testing/cxl/test/cxl.c
index 0e78d8e19895..ea04995fe42c 100644
--- a/tools/testing/cxl/test/cxl.c
+++ b/tools/testing/cxl/test/cxl.c
@@ -396,7 +396,8 @@ static void depopulate_all_mock_resources(void)
 
 static struct cxl_mock_res *alloc_mock_res(resource_size_t size, int align)
 {
-	struct cxl_mock_res *res = kzalloc(sizeof(*res), GFP_KERNEL);
+	struct cxl_mock_res *res __free(kfree) =
+		kzalloc(sizeof(*res), GFP_KERNEL);
 	struct genpool_data_align data = {
 		.align = align,
 	};
@@ -416,7 +417,7 @@ static struct cxl_mock_res *alloc_mock_res(resource_size_t size, int align)
 	list_add(&res->list, &mock_res);
 	mutex_unlock(&mock_res_lock);
 
-	return res;
+	return_ptr(res);
 }
 
 static int populate_cedt(void)
RE: [PATCH] cxl: Fix memory leak bug in alloc_mock_res()
Posted by Dan Williams 2 years, 6 months ago
Dan Williams wrote:
> Chenyuan Mi wrote:
> > When gen_pool_alloc_algo() fails, the error handling path
> > forgets to free 'res'. It would cause a memory leak bug.
> > 
> > Fix it by add kfree() in error handling path.
> 
> Going forward I want to set the policy that any error path resource leaks be
> fixed by converting to using __free() and associated helpers.
> 
> So in this case it would be:

...and to be clear I do think the fix should be applied in a backportable
fashion and then followed up with a conversion for the next merge window.

> 
> -- >8 --
> diff --git a/tools/testing/cxl/test/cxl.c b/tools/testing/cxl/test/cxl.c
> index 0e78d8e19895..ea04995fe42c 100644
> --- a/tools/testing/cxl/test/cxl.c
> +++ b/tools/testing/cxl/test/cxl.c
> @@ -396,7 +396,8 @@ static void depopulate_all_mock_resources(void)
>  
>  static struct cxl_mock_res *alloc_mock_res(resource_size_t size, int align)
>  {
> -	struct cxl_mock_res *res = kzalloc(sizeof(*res), GFP_KERNEL);
> +	struct cxl_mock_res *res __free(kfree) =
> +		kzalloc(sizeof(*res), GFP_KERNEL);
>  	struct genpool_data_align data = {
>  		.align = align,
>  	};
> @@ -416,7 +417,7 @@ static struct cxl_mock_res *alloc_mock_res(resource_size_t size, int align)
>  	list_add(&res->list, &mock_res);
>  	mutex_unlock(&mock_res_lock);
>  
> -	return res;
> +	return_ptr(res);
>  }
>  
>  static int populate_cedt(void)