From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1754325AbbGSXRx (ORCPT ); Sun, 19 Jul 2015 19:17:53 -0400 Received: from mail-lb0-f180.google.com ([209.85.217.180]:33042 "EHLO mail-lb0-f180.google.com" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S1754072AbbGSXRv (ORCPT ); Sun, 19 Jul 2015 19:17:51 -0400 From: Rasmus Villemoes To: mingo@kernel.org, akpm@linux-foundation.org, Sasha Levin Cc: Rasmus Villemoes , linux-mm@kvack.org, linux-kernel@vger.kernel.org Subject: [RFC 3/3] slab.h: use check_mul_overflow in kmalloc_array Date: Mon, 20 Jul 2015 01:17:32 +0200 Message-Id: <1437347852-24921-3-git-send-email-linux@rasmusvillemoes.dk> X-Mailer: git-send-email 2.1.3 In-Reply-To: <1437347852-24921-1-git-send-email-linux@rasmusvillemoes.dk> References: <1437347852-24921-1-git-send-email-linux@rasmusvillemoes.dk> Sender: linux-kernel-owner@vger.kernel.org List-ID: X-Mailing-List: linux-kernel@vger.kernel.org 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 --- 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 #include #include +#include /* @@ -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