Re: [PATCH 2/9] XArray: simplify the calculation of shift

From: Matthew Wilcox
Date: Mon Mar 30 2020 - 09:20:30 EST


On Mon, Mar 30, 2020 at 12:36:36PM +0000, Wei Yang wrote:
> When head is NULL, shift is calculated from max. Currently we use a loop
> to detect how many XA_CHUNK_SHIFT is need to cover max.
>
> To achieve this, we can get number of bits max expands and round it up
> to XA_CHUNK_SHIFT.
>
> Signed-off-by: Wei Yang <richard.weiyang@xxxxxxxxx>
> ---
> lib/xarray.c | 6 +-----
> 1 file changed, 1 insertion(+), 5 deletions(-)
>
> diff --git a/lib/xarray.c b/lib/xarray.c
> index 1d9fab7db8da..6454cf3f5b4c 100644
> --- a/lib/xarray.c
> +++ b/lib/xarray.c
> @@ -560,11 +560,7 @@ static int xas_expand(struct xa_state *xas, void *head)
> unsigned long max = xas_max(xas);
>
> if (!head) {
> - if (max == 0)
> - return 0;
> - while ((max >> shift) >= XA_CHUNK_SIZE)
> - shift += XA_CHUNK_SHIFT;
> - return shift + XA_CHUNK_SHIFT;
> + return roundup(fls_long(max), XA_CHUNK_SHIFT);

This doesn't give the same number. Did you test this?

Consider max = 64. The current code does:

shift = 0;
64 >> 0 >= 64 (true)
shift += 6;
64 >> 6 < 64
return 12

Your replacement does:

fls_long(64) = 6
roundup(6, 6) is 6.

Please be more careful.