Re: [PATCH v2 1/3] lib/find_bit: introduce FIND_FIRST_BIT() macro

From: Andy Shevchenko
Date: Wed Aug 24 2022 - 05:10:44 EST


On Wed, Aug 24, 2022 at 4:51 AM Yury Norov <yury.norov@xxxxxxxxx> wrote:
>
> Now that we have many flavors of find_first_bit(), and expect even more,
> it's better to have one macro that generates optimal code for all and makes
> maintaining of slightly different functions simpler.
>
> The logic common to all versions is moved to the new macro, and all the
> flavors are generated by providing an EXPRESSION macro-parameter, like
> in this example:
>
> #define FIND_FIRST_BIT(EXPRESSION, size) ...
>
> find_first_ornot_and_bit(addr1, addr2, addr3, size)
> {
> return FIND_NEXT_BIT(addr1[idx] | ~addr2[idx] & addr3[idx], size);
> }
>
> The EXPRESSION may be of any complexity, as soon as it only refers
> the bitmap(s) and an iterator idx.
>
> The 'word_op' is here to allow the macro to generate code for _le
> versions on big-endian machines; used in the following patches.

...

> +#ifndef word_op
> +#define word_op
> +#endif

Not sure about the naming without namespace. Perhaps __ffs_word_op?

> +#define FIND_FIRST_BIT(EXPRESSION, size) \
> +({ \
> + unsigned long idx, val, sz = (size); \
> + \
> + for (idx = 0; idx * BITS_PER_LONG < sz; idx++) { \

I think we can do slightly better:

for (unsigned long idx = 0; idx < sz; idx += BITS_PER_LONG) {
unsigned long val;

> + val = (EXPRESSION); \
> + if (val) { \
> + sz = min(idx * BITS_PER_LONG + __ffs(word_op(val)), sz);\

sz = min(idx + __ffs(...));

> + break; \
> + } \
> + } \
> + \
> + sz; \
> +})


--
With Best Regards,
Andy Shevchenko