[U-Boot] [RFC PATCH 07/12] devres: add devm_kmalloc() and friends (managed memory allocation)

Masahiro Yamada yamada.masahiro at socionext.com
Wed Jul 8 06:29:37 CEST 2015


devm_kmalloc() is identical to kmalloc() except that the memory
allocated with it is managed and will be automatically released
when the device is removed/unbound.

Likewise for the other variants.

Signed-off-by: Masahiro Yamada <yamada.masahiro at socionext.com>
---

 drivers/core/devres.c | 21 +++++++++++++++++++++
 include/dm/device.h   | 23 +++++++++++++++++++++++
 2 files changed, 44 insertions(+)

diff --git a/drivers/core/devres.c b/drivers/core/devres.c
index 2e967bf..f24bcac 100644
--- a/drivers/core/devres.c
+++ b/drivers/core/devres.c
@@ -135,3 +135,24 @@ void devres_release_all(struct udevice *dev)
 {
 	release_nodes(dev, &dev->devres_head, false);
 }
+
+/*
+ * Managed kmalloc/kfree
+ */
+static void devm_kmalloc_release(struct udevice *dev, void *res)
+{
+	/* noop */
+}
+
+void *devm_kmalloc(struct udevice *dev, size_t size, gfp_t gfp)
+{
+	void *data;
+
+	data = devres_alloc(devm_kmalloc_release, size, gfp);
+	if (unlikely(!data))
+		return NULL;
+
+	devres_add(dev, data);
+
+	return data;
+}
diff --git a/include/dm/device.h b/include/dm/device.h
index 7b39659..fac0868 100644
--- a/include/dm/device.h
+++ b/include/dm/device.h
@@ -14,6 +14,8 @@
 #include <dm/uclass-id.h>
 #include <fdtdec.h>
 #include <linker_lists.h>
+#include <linux/compat.h>
+#include <linux/kernel.h>
 #include <linux/list.h>
 
 struct driver_info;
@@ -466,4 +468,25 @@ void devres_add(struct udevice *dev, void *res);
 void devres_release_probe(struct udevice *dev);
 void devres_release_all(struct udevice *dev);
 
+/* managed devm_k.alloc/kfree for device drivers */
+void *devm_kmalloc(struct udevice *dev, size_t size, gfp_t gfp);
+static inline void *devm_kzalloc(struct udevice *dev, size_t size, gfp_t gfp)
+{
+	return devm_kmalloc(dev, size, gfp | __GFP_ZERO);
+}
+static inline void *devm_kmalloc_array(struct udevice *dev,
+				       size_t n, size_t size, gfp_t flags)
+{
+	if (size != 0 && n > SIZE_MAX / size)
+		return NULL;
+	return devm_kmalloc(dev, n * size, flags);
+}
+static inline void *devm_kcalloc(struct udevice *dev,
+				 size_t n, size_t size, gfp_t flags)
+{
+	return devm_kmalloc_array(dev, n, size, flags | __GFP_ZERO);
+}
+void devm_kfree(struct udevice *dev, void *p);
+
+
 #endif
-- 
1.9.1



More information about the U-Boot mailing list