Skip to contentSkip to conversation

drm/amdkfd: Fix memory leak in kfd_mem_dmamap_userptr()

PATCH In review Rafael Mendonca 2 participants 2 messages Oct 18, 2022 – Oct 19, 2022

Subsystems (3)
lore
Share & tools
lore
#0 lore raw

PATCH 1/1 drm/amdkfd: Fix memory leak in kfd_mem_dmamap_userptr()

If the number of pages from the userptr BO differs from the SG BO then the allocated memory for the SG table doesn't get freed before returning -EINVAL, which may lead to a memory leak in some error paths. Fix this by checking the number of pages before allocating memory for the SG table.

Fixes 264fb4d332f5 ("drm/amdgpu: Add multi-GPU DMA mapping helpers")
---
 drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c +3 -3
index 978d3970b5cc..84f44f7e4111 100644
@@ -510,13 +510,13 @@ kfd_mem_dmamap_userptr(struct kgd_mem *mem,
 	struct ttm_tt *ttm = bo->tbo.ttm;
 	int ret;
 
+	if (WARN_ON(ttm->num_pages != src_ttm->num_pages))
+		return -EINVAL;
+
 	ttm->sg = kmalloc(sizeof(*ttm->sg), GFP_KERNEL);
 	if (unlikely(!ttm->sg))
 		return -ENOMEM;
 
-	if (WARN_ON(ttm->num_pages != src_ttm->num_pages))
-		return -EINVAL;
-
 	/* Same sequence as in amdgpu_ttm_tt_pin_userptr */
 	ret = sg_alloc_table_from_pages(ttm->sg, src_ttm->pages,
 					ttm->num_pages, 0,
Signature · 1 line
2.34.1
maintainer Reviewed-by on v1 1/1
#1 lore raw
Quoted 7 lines · Rafael Mendonca

If the number of pages from the userptr BO differs from the SG BO then the allocated memory for the SG table doesn't get freed before returning -EINVAL, which may lead to a memory leak in some error paths. Fix this by checking the number of pages before allocating memory for the SG table.

Fixes 264fb4d332f5 ("drm/amdgpu: Add multi-GPU DMA mapping helpers")

Thank you for catching this. The patch is

I submitted it to our amd-staging-drm-next branch.

Regards,
  Felix

Quoted 25 lines
---
  drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c | 6 +++---
  1 file changed, 3 insertions(+), 3 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c +3 -3
index 978d3970b5cc..84f44f7e4111 100644
@@ -510,13 +510,13 @@ kfd_mem_dmamap_userptr(struct kgd_mem *mem,
  	struct ttm_tt *ttm = bo->tbo.ttm;
  	int ret;
 
+	if (WARN_ON(ttm->num_pages != src_ttm->num_pages))
+		return -EINVAL;
+
  	ttm->sg = kmalloc(sizeof(*ttm->sg), GFP_KERNEL);
  	if (unlikely(!ttm->sg))
  		return -ENOMEM;
 
-	if (WARN_ON(ttm->num_pages != src_ttm->num_pages))
-		return -EINVAL;
-
  	/* Same sequence as in amdgpu_ttm_tt_pin_userptr */
  	ret = sg_alloc_table_from_pages(ttm->sg, src_ttm->pages,
  					ttm->num_pages, 0,