[Concept,15/35] malloc: Add malloc_get_info() to retrieve memory statistics

Message ID 20251210000737.180797-16-sjg@u-boot.org
State New
Headers
Series malloc: Add heap debugging commands and mcheck caller tracking |

Commit Message

Simon Glass Dec. 10, 2025, 12:07 a.m. UTC
  From: Simon Glass <simon.glass@canonical.com>

Add struct malloc_info and malloc_get_info() function to
programmatically access the memory-allocation stats that malloc_stats()
prints.

The struct contains the size of the malloc() poll and the number of
bytes in use.

Add a static inline stub to return an error when DEBUG is not defined.

Co-developed-by: Claude <noreply@anthropic.com>
Signed-off-by: Simon Glass <simon.glass@canonical.com>
---

 common/dlmalloc.c | 10 ++++++++++
 include/malloc.h  | 29 +++++++++++++++++++++++++++++
 2 files changed, 39 insertions(+)
  

Patch

diff --git a/common/dlmalloc.c b/common/dlmalloc.c
index efeff18653f..004dafe4b3b 100644
--- a/common/dlmalloc.c
+++ b/common/dlmalloc.c
@@ -3689,6 +3689,16 @@  static struct mallinfo internal_mallinfo(mstate m) {
   }
   return nm;
 }
+
+int malloc_get_info(struct malloc_info *info)
+{
+  struct mallinfo mi = internal_mallinfo(gm);
+
+  info->total_bytes = mem_malloc_end - mem_malloc_start;
+  info->in_use_bytes = mi.uordblks;
+
+  return 0;
+}
 #endif /* !NO_MALLINFO */
 
 #if !NO_MALLOC_STATS
diff --git a/include/malloc.h b/include/malloc.h
index 73b2da0c383..fd8a8ddcfaf 100644
--- a/include/malloc.h
+++ b/include/malloc.h
@@ -665,8 +665,22 @@  void mspace_inspect_all(mspace msp,
 /* --------------------- U-Boot additions --------------------- */
 
 #ifdef __UBOOT__
+#include <linux/errno.h>
 #include <linux/types.h>
 
+/**
+ * struct malloc_info - Memory allocation statistics
+ *
+ * This is filled in by malloc_get_info().
+ *
+ * @total_bytes: Total bytes available in the heap
+ * @in_use_bytes: Current bytes allocated (in use by application)
+ */
+struct malloc_info {
+	ulong total_bytes;
+	ulong in_use_bytes;
+};
+
 /* Memory pool boundaries */
 extern ulong mem_malloc_start;
 extern ulong mem_malloc_end;
@@ -735,6 +749,21 @@  void *memalign_simple(size_t alignment, size_t bytes);
  */
 int initf_malloc(void);
 
+/**
+ * malloc_get_info() - Get memory allocation statistics
+ *
+ * @info: Place to put the statistics
+ * Return: 0 on success, -ENOSYS if not available (DEBUG not defined)
+ */
+#ifdef DEBUG
+int malloc_get_info(struct malloc_info *info);
+#else
+static inline int malloc_get_info(struct malloc_info *info)
+{
+	return -ENOSYS;
+}
+#endif
+
 #endif /* __UBOOT__ */
 
 #ifdef __cplusplus