[PATCH RFC] slab: introduce knalloc/kxnalloc

From: Xi Wang
Date: Thu Feb 09 2012 - 07:41:48 EST


This patch introduces knalloc/kxnalloc wrappers that perform integer
overflow checks without zeroing the memory.

knalloc(n, size, flags) is the non-zeroing version of kcalloc(),
which allocates n * size bytes.

kxnalloc(xsize, n, size, flags) allocates xsize + n * size bytes.
It is useful to allocate a structure ending with a zero-length array,
which is a commonly used pattern. For example, in posix_acl_alloc()
to allocate a posix_acl object one could call

kxnalloc(sizeof(struct posix_acl),
count, sizeof(struct posix_acl_entry), flags);

to avoid overflowing the allocation size.

Suggested-by: Andrew Morton <akpm@xxxxxxxxxxxxxxxxxxxx>
Signed-off-by: Xi Wang <xi.wang@xxxxxxxxx>
---
I coined the name knalloc() for Andrew's wtf_do_i_call_this() in the
previous email. A better name is welcome.

I additionally added kxnalloc() since it's a common idiom.
---
include/linux/slab.h | 31 +++++++++++++++++++++++++++----
1 files changed, 27 insertions(+), 4 deletions(-)

diff --git a/include/linux/slab.h b/include/linux/slab.h
index 573c809..e3a1e81 100644
--- a/include/linux/slab.h
+++ b/include/linux/slab.h
@@ -190,7 +190,8 @@ size_t ksize(const void *);
#endif

/**
- * kcalloc - allocate memory for an array. The memory is set to zero.
+ * kxnalloc - allocate memory for an array with an extra header.
+ * @xsize: extra header size.
* @n: number of elements.
* @size: element size.
* @flags: the type of memory to allocate.
@@ -240,11 +241,33 @@ size_t ksize(const void *);
* for general use, and so are not documented here. For a full list of
* potential flags, always refer to linux/gfp.h.
*/
-static inline void *kcalloc(size_t n, size_t size, gfp_t flags)
+static inline void *kxnalloc(size_t xsize, size_t n, size_t size, gfp_t flags)
{
- if (size != 0 && n > ULONG_MAX / size)
+ if (size != 0 && n > (ULONG_MAX - xsize) / size)
return NULL;
- return __kmalloc(n * size, flags | __GFP_ZERO);
+ return __kmalloc(xsize + n * size, flags);
+}
+
+/**
+ * knalloc - allocate memory for an array.
+ * @n: number of elements.
+ * @size: element size.
+ * @flags: the type of memory to allocate (see kmalloc).
+ */
+static inline void *knalloc(size_t n, size_t size, gfp_t flags)
+{
+ return kxnalloc(0, n, size, flags);
+}
+
+/**
+ * kcalloc - allocate memory for an array. The memory is set to zero.
+ * @n: number of elements.
+ * @size: element size.
+ * @flags: the type of memory to allocate (see kmalloc).
+ */
+static inline void *kcalloc(size_t n, size_t size, gfp_t flags)
+{
+ return knalloc(n, size, flags | __GFP_ZERO);
}

#if !defined(CONFIG_NUMA) && !defined(CONFIG_SLOB)
--
1.7.5.4

--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/