[PATCH v4 2/4] scsi: target: rd: Release protection space on allocation failure

From: Sanan Hasanov

Date: Thu Oct 08 2026 - 20:36:44 EST


From: Sanan Hasanov <sanan.hasanov@xxxxxxx>

When rd_allocate_sgl_table() fails, rd_build_prot_space() returns the
error but leaves the partially populated sg_prot_array in place.
pi_prot_type_store() then restores the previous protection type without
calling ->free_prot(), so the pages and scatterlists allocated so far
stay attached to the device. If the user writes pi_prot_type again,
rd_build_prot_space() overwrites sg_prot_array and the earlier
allocation is leaked.

Build the protection space in local variables, free them if the
allocation fails, and only store them in rd_dev on success. The error
path then only touches memory that this call allocated.

Fixes: d7e8eb5d9216 ("target/rd: Add support for protection SGL setup + release")
Signed-off-by: Sanan Hasanov <sanan.hasanov@xxxxxxx>
---
drivers/target/target_core_rd.c | 10 ++++++----
1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/drivers/target/target_core_rd.c b/drivers/target/target_core_rd.c
index 97c63b122..b52d703d2 100644
--- a/drivers/target/target_core_rd.c
+++ b/drivers/target/target_core_rd.c
@@ -259,12 +259,14 @@ static int rd_build_prot_space(struct rd_dev *rd_dev, int prot_length, int block
if (!sg_table)
return -ENOMEM;

- rd_dev->sg_prot_array = sg_table;
- rd_dev->sg_prot_count = sg_tables;
-
rc = rd_allocate_sgl_table(rd_dev, sg_table, total_sg_needed, 0xff);
- if (rc)
+ if (rc) {
+ rd_release_sgl_table(rd_dev, sg_table, sg_tables);
return rc;
+ }
+
+ rd_dev->sg_prot_array = sg_table;
+ rd_dev->sg_prot_count = sg_tables;

pr_debug("CORE_RD[%u] - Built Ramdisk Device ID: %u prot space of"
" %u pages in %u tables\n", rd_dev->rd_host->rd_host_id,
--
2.48.1