diff mbox series

[1/3] mem_region: Add a local_free function

Message ID 20230513113137.97093-1-npiggin@gmail.com
State Accepted
Headers show
Series [1/3] mem_region: Add a local_free function | expand

Commit Message

Nicholas Piggin May 13, 2023, 11:31 a.m. UTC
This allows memory to be allocated with local_alloc() to be freed.

Signed-off-by: Nicholas Piggin <npiggin@gmail.com>
---
 core/mem_region.c           | 34 ++++++++++++++++++++++++++++++++++
 include/mem_region-malloc.h |  4 ++++
 2 files changed, 38 insertions(+)

Comments

Reza Arbab June 6, 2023, 7:13 p.m. UTC | #1
On Sat, May 13, 2023 at 09:31:34PM +1000, Nicholas Piggin wrote:
>This allows memory to be allocated with local_alloc() to be freed.

LGTM. Series applied to master.
diff mbox series

Patch

diff --git a/core/mem_region.c b/core/mem_region.c
index e78d0a94..0ed00f36 100644
--- a/core/mem_region.c
+++ b/core/mem_region.c
@@ -920,6 +920,40 @@  restart:
 	return p;
 }
 
+static struct mem_region *mem_to_region(void *mem)
+{
+	struct mem_region *region;
+
+	list_for_each(&regions, region, list) {
+		if (mem < region_start(region))
+			continue;
+		if (mem >= region_start(region) + region->len)
+			continue;
+		return region;
+	}
+	return NULL;
+}
+
+void __local_free(void *mem, const char *location)
+{
+	struct mem_region *region;
+
+	lock(&mem_region_lock);
+
+	region = mem_to_region(mem);
+	if (!region) {
+		prerror("MEM: local_free mem=%p no matching region.\n", mem);
+		unlock(&mem_region_lock);
+		return;
+	}
+
+	lock(&region->free_list_lock);
+	mem_free(region, mem, location);
+	unlock(&region->free_list_lock);
+
+	unlock(&mem_region_lock);
+}
+
 struct mem_region *find_mem_region(const char *name)
 {
 	struct mem_region *region;
diff --git a/include/mem_region-malloc.h b/include/mem_region-malloc.h
index 271311b2..b2e4337d 100644
--- a/include/mem_region-malloc.h
+++ b/include/mem_region-malloc.h
@@ -28,4 +28,8 @@  void *__local_alloc(unsigned int chip, size_t size, size_t align,
 #define local_alloc(chip_id, size, align)	\
 	__local_alloc((chip_id), (size), (align), __location__)
 
+void __local_free(void *mem, const char *location);
+#define local_free(mem)				\
+	__local_free((mem), __location__)
+
 #endif /* __MEM_REGION_MALLOC_H */