Commit b6d86d3d authored by Guenter Roeck's avatar Guenter Roeck

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: default avatarGuenter Roeck <linux@roeck-us.net>
Acked-by: default avatarJean Delvare <khali@linux-fr.org>
parent 4cbe5a55
...@@ -82,10 +82,18 @@ ...@@ -82,10 +82,18 @@
__x - (__x % (y)); \ __x - (__x % (y)); \
} \ } \
) )
/*
* Divide positive or negative dividend by positive divisor and round
* to closest integer. Result is undefined for negative divisors.
*/
#define DIV_ROUND_CLOSEST(x, divisor)( \ #define DIV_ROUND_CLOSEST(x, divisor)( \
{ \ { \
typeof(divisor) __divisor = divisor; \ typeof(x) __x = x; \
(((x) + ((__divisor) / 2)) / (__divisor)); \ typeof(divisor) __d = divisor; \
(((typeof(x))-1) >= 0 || (__x) >= 0) ? \
(((__x) + ((__d) / 2)) / (__d)) : \
(((__x) - ((__d) / 2)) / (__d)); \
} \ } \
) )
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment