Re: [PATCH] kernel: rounddown helper function

From: Andrew Morton
Date: Wed Aug 04 2010 - 17:36:07 EST


On Tue, 3 Aug 2010 11:23:54 -0700
Randy Dunlap <randy.dunlap@xxxxxxxxxx> wrote:

> On Tue, 03 Aug 2010 14:16:07 -0400 Eric Paris wrote:
>
> > The roundup() helper function will round a given value up to a multiple of
> > another given value. aka roundup(11, 7) would give 14 = 7 * 2. This new
> > function does the opposite. It will round a given number down to the
> > nearest multiple of the second number: rounddown(11, 7) would give 7.
> >
> > I need this in some future SELinux code and can carry the macro myself, but
> > figured I would put it in the core kernel so others might find and use it
> > if need be.
> >
> > Signed-off-by: Eric Paris <eparis@xxxxxxxxxx>
> > ---
> >
> > include/linux/kernel.h | 1 +
> > 1 files changed, 1 insertions(+), 0 deletions(-)
> >
> > diff --git a/include/linux/kernel.h b/include/linux/kernel.h
> > index 7d5b10f..d6092fd 100644
> > --- a/include/linux/kernel.h
> > +++ b/include/linux/kernel.h
> > @@ -59,6 +59,7 @@ extern const char linux_proc_banner[];
> > #define FIELD_SIZEOF(t, f) (sizeof(((t*)0)->f))
> > #define DIV_ROUND_UP(n,d) (((n) + (d) - 1) / (d))
> > #define roundup(x, y) ((((x) + ((y) - 1)) / (y)) * (y))
> > +#define rounddown(x, y) ((x) - ((x) % (y)))
> > #define DIV_ROUND_CLOSEST(x, divisor)( \
> > { \
> > typeof(divisor) __divisor = divisor; \
> >
> > --
>
> I'm more used to seeing it like
>
> #define DIV_ROUND_DOWN(n, d) (((n) / (d)) * (d))
>
> but since multiply/divide/modulus are usually slower, your (SELinux) way is better,
> I suppose.
>
> and the usual caveats apply: don't use these macros with expressions (nor with y
> or d == 0).

Yes, it really shouldn't reference its argument twice. And that's easy
to fix.

A fancy version would detect constant-power-of-two and do an `& (d - 1)'
instead of the modulus. But probably the compiler does optimisatons in
that case - for unsigned types, at least.
--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/