Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > linux.kernel > #1187880

[RFC 3/3] slab.h: use check_mul_overflow in kmalloc_array

From Rasmus Villemoes <linux@rasmusvillemoes.dk>
Newsgroups linux.kernel
Subject [RFC 3/3] slab.h: use check_mul_overflow in kmalloc_array
Date 2015-07-20 01:20 +0200
Message-ID <pO62e-iN-21@gated-at.bofh.it> (permalink)
References <pO62e-iN-13@gated-at.bofh.it>
Organization linux.* mail to news gateway

Show all headers | View raw


For recent enough gcc, check_mul_overflow maps to
__builtin_mul_overflow, which on e.g. x86 allows gcc to do the
multiplication and then check the overflow flag, instead of doing a
separate comparison (which may even involve an expensive division, in
the cases where size is not a compile-time constant).

Unfortunately, it's not necessarily always a performance improvement:
For example, when size is a compile-time constant power-of-2, gcc will
now do the multiplication using the mul instruction instead of doing a
comparison against an immediate and then a left shift for the
multiplication. However, I think the compiler should be trusted to
optimize the code - nothing prevents it from doing the overflow check
the old way.

Signed-off-by: Rasmus Villemoes <linux@rasmusvillemoes.dk>
---
 include/linux/slab.h | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)

diff --git a/include/linux/slab.h b/include/linux/slab.h
index a99f0e5243e1..82e49dee938d 100644
--- a/include/linux/slab.h
+++ b/include/linux/slab.h
@@ -14,6 +14,7 @@
 #include <linux/gfp.h>
 #include <linux/types.h>
 #include <linux/workqueue.h>
+#include <linux/overflow.h>
 
 
 /*
@@ -524,9 +525,11 @@ int memcg_update_all_caches(int num_memcgs);
  */
 static inline void *kmalloc_array(size_t n, size_t size, gfp_t flags)
 {
-	if (size != 0 && n > SIZE_MAX / size)
+	size_t prod;
+
+	if (check_mul_overflow(n, size, &prod))
 		return NULL;
-	return __kmalloc(n * size, flags);
+	return __kmalloc(prod, flags);
 }
 
 /**
-- 
2.1.3

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

Back to linux.kernel | Previous | Next | Find similar | Unroll thread


Thread

[RFC 3/3] slab.h: use check_mul_overflow in kmalloc_array Rasmus Villemoes <linux@rasmusvillemoes.dk> - 2015-07-20 01:20 +0200

csiph-web