Re: [PATCH] Add BUILD_BUG_ON_NOT_POWER_OF_2()

From: Robert P. J. Day
Date: Thu Jan 07 2010 - 03:36:57 EST


On Wed, 6 Jan 2010, Roland Dreier wrote:

> When code relies on a constant being a power of 2:
>
> #define FOO 512 /* must be a power of 2 */
>
> it would be nice to be able to do:
>
> BUILD_BUG_ON(!is_power_of_2(FOO));
>
> However applying an inline function does not result in a
> compile-time constant that can be used with BUILD_BUG_ON(), so
> trying that gives results in:
>
> error: bit-field '<anonymous>' width not an integer constant
>
> As suggested by akpm, rather than monkeying around with
> is_power_of_2() and risking gcc warts about constant expressions,
> just create a macro BUILD_BUG_ON_NOT_POWER_OF_2() to encapsulate
> this common requirement.

my normal pedantry coming to the surface, but can we at least assume
that people will use this test to *legitimately* test whether or not
something is a power of two, and not that there is a single bit set
(in the case of mask bits where all settings must be mutually
exclusive)?

there's a lot of this sort of thing throughout the kernel:

(n) != 0 && (((n) & ((n) - 1))

but it's sometimes unclear whether someone is testing for a) power of
two, or b) single bit set. if you're going to introduce that kind of
BUILD BUG (which is a good idea), let's try to not immediately abuse
it semantically. :-)

rday
--

========================================================================
Robert P. J. Day Waterloo, Ontario, CANADA

Linux Consulting, Training and Kernel Pedantry.

Web page: http://crashcourse.ca
Twitter: http://twitter.com/rpjday
========================================================================
--
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/