Re: [PATCH] linux/kernel.h: fix overflow for DIV_ROUND_UP_ULL
From: Andrew Morton
Date: Tue Jun 25 2019 - 18:32:36 EST
On Tue, 25 Jun 2019 15:29:38 -0700 Andrew Morton <akpm@xxxxxxxxxxxxxxxxxxxx> wrote:
> On Tue, 25 Jun 2019 15:35:18 +0530 Vinod Koul <vkoul@xxxxxxxxxx> wrote:
>
> > DIV_ROUND_UP_ULL adds the two arguments and then invokes
> > DIV_ROUND_DOWN_ULL. But on a 32bit system the addition of two 32 bit
> > values can overflow. DIV_ROUND_DOWN_ULL does it correctly and stashes
> > the addition into a unsigned long long so cast the result to unsigned
> > long long here to avoid the overflow condition.
> >
> > ...
> >
> > --- a/include/linux/kernel.h
> > +++ b/include/linux/kernel.h
> > @@ -93,7 +93,8 @@
> > #define DIV_ROUND_DOWN_ULL(ll, d) \
> > ({ unsigned long long _tmp = (ll); do_div(_tmp, d); _tmp; })
> >
> > -#define DIV_ROUND_UP_ULL(ll, d) DIV_ROUND_DOWN_ULL((ll) + (d) - 1, (d))
> > +#define DIV_ROUND_UP_ULL(ll, d) \
> > + ({ DIV_ROUND_DOWN_ULL((unsigned long long)(ll) + (d) - 1, (d)) })
> >
>
> This clearly wasn't tested :(
>
> fs/fs-writeback.c: In function wb_split_bdi_pages:
> ./include/linux/kernel.h:97:65: error: expected ; before } token
> ({ DIV_ROUND_DOWN_ULL((unsigned long long)(ll) + (d) - 1, (d)) })
> ^
> fs/fs-writeback.c:811:10: note: in expansion of macro DIV_ROUND_UP_ULL
> return DIV_ROUND_UP_ULL((u64)nr_pages * this_bw, tot_bw);
>
>
> From: Andrew Morton <akpm@xxxxxxxxxxxxxxxxxxxx>
> Subject: linux-kernelh-fix-overflow-for-div_round_up_ull-fix
>
> DIV_ROUND_UP_ULL must be an rval
>
> Cc: Bjorn Andersson <bjorn.andersson@xxxxxxxxxx>
> Cc: Randy Dunlap <rdunlap@xxxxxxxxxxxxx>
> Cc: Vinod Koul <vkoul@xxxxxxxxxx>
> Signed-off-by: Andrew Morton <akpm@xxxxxxxxxxxxxxxxxxxx>
> ---
>
> include/linux/kernel.h | 6 ++++--
> 1 file changed, 4 insertions(+), 2 deletions(-)
>
> --- a/include/linux/kernel.h~linux-kernelh-fix-overflow-for-div_round_up_ull-fix
> +++ a/include/linux/kernel.h
> @@ -93,8 +93,10 @@
> #define DIV_ROUND_DOWN_ULL(ll, d) \
> ({ unsigned long long _tmp = (ll); do_div(_tmp, d); _tmp; })
>
> -#define DIV_ROUND_UP_ULL(ll, d) \
> - ({ DIV_ROUND_DOWN_ULL((unsigned long long)(ll) + (d) - 1, (d)) })
> +#define DIV_ROUND_UP_ULL(ll, d) ({ \
> + unsigned long long _tmp; \
> + _tmp = DIV_ROUND_DOWN_ULL((unsigned long long)(ll) + (d) - 1, (d)); \
> + _tmp; })
Simpler:
--- a/include/linux/kernel.h~linux-kernelh-fix-overflow-for-div_round_up_ull-fix
+++ a/include/linux/kernel.h
@@ -94,7 +94,7 @@
({ unsigned long long _tmp = (ll); do_div(_tmp, d); _tmp; })
#define DIV_ROUND_UP_ULL(ll, d) \
- ({ DIV_ROUND_DOWN_ULL((unsigned long long)(ll) + (d) - 1, (d)) })
+ DIV_ROUND_DOWN_ULL((unsigned long long)(ll) + (d) - 1, (d))
#if BITS_PER_LONG == 32
# define DIV_ROUND_UP_SECTOR_T(ll,d) DIV_ROUND_UP_ULL(ll, d)
_