Skip to content

Commit

Permalink
linux/kernel.h: Fix DIV_ROUND_CLOSEST to support negative dividends
Browse files Browse the repository at this point in the history
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 <[email protected]>
Acked-by: Jean Delvare <[email protected]>
  • Loading branch information
groeck committed Sep 2, 2012
1 parent 4cbe5a5 commit b6d86d3
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions include/linux/kernel.h
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,18 @@
__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)( \
{ \
typeof(divisor) __divisor = divisor; \
(((x) + ((__divisor) / 2)) / (__divisor)); \
typeof(x) __x = x; \
typeof(divisor) __d = divisor; \
(((typeof(x))-1) >= 0 || (__x) >= 0) ? \
(((__x) + ((__d) / 2)) / (__d)) : \
(((__x) - ((__d) / 2)) / (__d)); \
} \
)

Expand Down

0 comments on commit b6d86d3

Please sign in to comment.