Re: ALIGN (Re: [PATCH] Fix get_order())

From: Linus Torvalds
Date: Fri Mar 09 2007 - 18:16:24 EST




On Sat, 10 Mar 2007, Oleg Verych wrote:
>
> OTOH, if i would write it this way
>
> #define BALIGN(x,bits) ((((x) >> (bits)) + 1) << (bits))

But that's *wrong*. It aligns something that is *already* aligned to
something else.

So you'd have to do it as something like

#define ALIGN_TO_POW2(x,pow) \
((((x)+(1<<(pow))-1)>>(pow))<<(pow))

and the thing is, that's actually both (a) less readable than what ALIGN()
already does (b) unless the compiler notices that what you really want is
a "bitwise and", it's really inefficient too because shifts are generally
much more expensive than simple bitops.

So you're simply better off doing it as

#define ALIGN_TO_POW2(x,pow) ALIGN(x, (1ull << pow))

but then you'd still have to depend on the "typeof()" magic in ALIGN() to
turn the final end result back to the type of "x".

(the "1ull" is necessary exactly because you don't know what type "x" is
beforehand, so you need to make sure that the mask is at *least* as big a
type as x, and not overflow to undefined C semantics).

Linus
-
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/