aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGuenter Roeck <linux@roeck-us.net>2012-08-24 20:25:01 -0400
committerGuenter Roeck <linux@roeck-us.net>2012-09-01 21:58:09 -0400
commitb6d86d3d6d6e4c9b588d81615c81b5a8292b62ed (patch)
tree814c4ba720911beba197b610d4bd4559a26c3e96
parent4cbe5a555fa58a79b6ecbb6c531b8bab0650778d (diff)
linux/kernel.h: Fix DIV_ROUND_CLOSEST to support negative dividends
DIV_ROUND_CLOSEST returns a bad result for negative dividends: DIV_ROUND_CLOSEST(-2, 2) = 0 Most of the time this does not matter. However, in the hardware monitoring subsystem, DIV_ROUND_CLOSEST is sometimes used on integers which can be negative (such as temperatures). Signed-off-by: Guenter Roeck <linux@roeck-us.net> Acked-by: Jean Delvare <khali@linux-fr.org>
-rw-r--r--include/linux/kernel.h12
1 files changed, 10 insertions, 2 deletions
diff --git a/include/linux/kernel.h b/include/linux/kernel.h
index 604382143bc..594b419b7d2 100644
--- a/include/linux/kernel.h
+++ b/include/linux/kernel.h
@@ -82,10 +82,18 @@
82 __x - (__x % (y)); \ 82 __x - (__x % (y)); \
83} \ 83} \
84) 84)
85
86/*
87 * Divide positive or negative dividend by positive divisor and round
88 * to closest integer. Result is undefined for negative divisors.
89 */
85#define DIV_ROUND_CLOSEST(x, divisor)( \ 90#define DIV_ROUND_CLOSEST(x, divisor)( \
86{ \ 91{ \
87 typeof(divisor) __divisor = divisor; \ 92 typeof(x) __x = x; \
88 (((x) + ((__divisor) / 2)) / (__divisor)); \ 93 typeof(divisor) __d = divisor; \
94 (((typeof(x))-1) >= 0 || (__x) >= 0) ? \
95 (((__x) + ((__d) / 2)) / (__d)) : \
96 (((__x) - ((__d) / 2)) / (__d)); \
89} \ 97} \
90) 98)
91 99