[PATCH 6.1.y-cip 51/85] mm/util: Introduce kmemdup_array()

Tommaso Merciai
2025-03-13T01:33:16Z

From: Kartik <kkartik@nvidia.com>

commit 7092e9b3bed1252c7d3f5812b9fb9d82375b73a6 upstream.

Introduce kmemdup_array() API to duplicate `n` number of elements
from a given array. This internally uses kmemdup to allocate and duplicate
the `src` array.

Signed-off-by: Kartik <kkartik@nvidia.com>
Acked-by: Kees Cook <keescook@chromium.org>
Signed-off-by: Thierry Reding <treding@nvidia.com>
---
include/linux/string.h | 1 +
mm/util.c | 17 +++++++++++++++++
2 files changed, 18 insertions(+)

diff --git a/include/linux/string.h b/include/linux/string.h
index 422606e98cc4..066203187c8d 100644
--- a/include/linux/string.h
+++ b/include/linux/string.h
@@ -218,6 +218,7 @@ extern const char *kstrdup_const(const char *s, gfp_t gfp);
extern char *kstrndup(const char *s, size_t len, gfp_t gfp);
extern void *kmemdup(const void *src, size_t len, gfp_t gfp);
extern char *kmemdup_nul(const char *s, size_t len, gfp_t gfp);
+extern void *kmemdup_array(const void *src, size_t element_size, size_t count, gfp_t gfp);

extern char **argv_split(gfp_t gfp, const char *str, int *argcp);
extern void argv_free(char **argv);
diff --git a/mm/util.c b/mm/util.c
index d3a2877c176f..770803ece795 100644
--- a/mm/util.c
+++ b/mm/util.c
@@ -133,6 +133,23 @@ void *kmemdup(const void *src, size_t len, gfp_t gfp)
}
EXPORT_SYMBOL(kmemdup);

+/**
+ * kmemdup_array - duplicate a given array.
+ *
+ * @src: array to duplicate.
+ * @element_size: size of each element of array.
+ * @count: number of elements to duplicate from array.
+ * @gfp: GFP mask to use.
+ *
+ * Return: duplicated array of @src or %NULL in case of error,
+ * result is physically contiguous. Use kfree() to free.
+ */
+void *kmemdup_array(const void *src, size_t element_size, size_t count, gfp_t gfp)
+{
+ return kmemdup(src, size_mul(element_size, count), gfp);
+}
+EXPORT_SYMBOL(kmemdup_array);
+
/**
* kmemdup_nul - Create a NUL-terminated string from unterminated data
* @s: The data to stringify
--
2.43.0