Skip to contentSkip to conversation

lib/idr: fix memory leak in ida_alloc_range() error path

PATCH New Josh Law 1 participant 1 message Mar 12

Subsystems (4)
lore
Share & tools
lore

Josh Law

author
#0 lore raw

PATCH 1/1 lib/idr: fix memory leak in ida_alloc_range() error path

In ida_alloc_range(), if the XArray operation encounters an error (e.g., -ENOSPC) during allocation, the function exits early via return xas_error(&xas). However, if an intermediate alloc bitmap was allocated via kzalloc() earlier in the function but the XArray insertion failed, the error path returns without freeing alloc.

Reorder the error handling to ensure alloc is properly freed when an XArray error occurs.

---
 lib/idr.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
lib/idr.c +4 -2
index 07098eb4ddc3..2ad96befa17a 100644
@@ -460,10 +460,12 @@ int ida_alloc_range(struct ida *ida, unsigned int min, unsigned int max,
 		bit = min % IDA_BITMAP_BITS;
 		goto retry;
 	}
-	if (bitmap != alloc)
+	if (xas_error(&xas)) {
 		kfree(alloc);
-	if (xas_error(&xas))
 		return xas_error(&xas);
+	}
+	if (bitmap != alloc)
+		kfree(alloc);
 	return xas.xa_index * IDA_BITMAP_BITS + bit;
 alloc:
 	xas_unlock_irqrestore(&xas, flags);
Signature · 1 line
2.34.1