Skip to contentSkip to conversation

scsi: sg: fix memory leak in sg_build_indirect

PATCH In review Li Bin 2 participants 2 messages Apr 13, 2020

Subsystems (2)
lore
Share & tools
lore

Li Bin

author
#0 lore raw

PATCH 1/1 scsi: sg: fix memory leak in sg_build_indirect

Fix a memory leak when there have failed, that we should free the pages under the condition rem_sz > 0.

---
 drivers/scsi/sg.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/scsi/sg.c +5 -1
index 4e6af592..8441ac5 100644
@@ -1959,8 +1959,12 @@ static long sg_compat_ioctl(struct file *filp, unsigned int cmd_in, unsigned lon
 			 k, rem_sz));
 
 	schp->bufflen = blk_size;
-	if (rem_sz > 0)	/* must have failed */
+	if (rem_sz > 0)	{ /* must have failed */
+		for (i = 0; i < k; i++)
+			__free_pages(schp->pages[i], order);
+
 		return -ENOMEM;
+	}
 	return 0;
 out:
 	for (i = 0; i < k; i++)
Signature · 1 line
1.7.12.4
maintainer
#1 lore raw
Quoted 2 lines · Li Bin

Fix a memory leak when there have failed, that we should free the pages under the condition rem_sz > 0.

May I paraphrase the above:
"Fix a memory leak that occurs when alloc_pages() succeeds several
times before failing. This condition is noticed when rem_sz > 0."

drivers/scsi/sg.c static long sg_compat_ioctl(struct file *filp, unsigned int cmd_in, unsigned lon

Quoted 11 lines
---
  drivers/scsi/sg.c | 6 +++++-
  1 file changed, 5 insertions(+), 1 deletion(-)
drivers/scsi/sg.c +0 -0
index 4e6af592..8441ac5 100644
@@ -1959,8 +1959,12 @@ static long sg_compat_ioctl(struct file *filp, unsigned int cmd_in, unsigned lon

It is the sg_build_indirect() function not sg_compat_ioctl() as suggested above by git. Can be get a replacement for git :-)

drivers/scsi/sg.c static long sg_compat_ioctl(struct file *filp, unsigned int cmd_in, unsigned lon · line 1966

Quoted 9 lines
drivers/scsi/sg.c +4 -1
  			 k, rem_sz));
 
  	schp->bufflen = blk_size;
-	if (rem_sz > 0)	/* must have failed */
+	if (rem_sz > 0)	{ /* must have failed */
+		for (i = 0; i < k; i++)
+			__free_pages(schp->pages[i], order);
+
  		return -ENOMEM;

It is easier, and less code, to replace 'return -ENOMEM'; with 'goto out'. Or even simpler:

    if (likely(rem_sz == 0))
	return 0;
out:
     ........

Doug Gilbert

BTW I spotted this one during the sg driver rewrite and fixed it. Note that this bug and several others like it won't be fixed by me while the sg driver rewrite is pending.

Quoted 5 lines
drivers/scsi/sg.c +1 -0
+	}
  	return 0;
  out:
  	for (i = 0; i < k; i++)