diff options
author | Yu-Ping Wu <yupingso@chromium.org> | 2021-12-02 10:54:32 +0800 |
---|---|---|
committer | Felix Held <felix-coreboot@felixheld.de> | 2021-12-08 00:51:43 +0000 |
commit | 00c834dc26348487f40e835630ab11cf30fe30f6 (patch) | |
tree | 7140ac20ca8d8e490f35f31b72636d33d921ed5b /src | |
parent | 04cf42775cca3f300dc3e8240bc70e706f091ca0 (diff) |
lib: Fix log2_ceil() for 0xffffffff
Current log2_ceil(x) is defined as log2(x * 2 - 1). When x is larger
than (1 << 31), (x * 2 - 1) won't fit in u32, leading to incorrect
result. Therefore, correct it as (log2(x - 1) + 1). Also add unit tests
for inline functions in lib.h.
BUG=none
TEST=make tests/lib/lib-test
BRANCH=none
Change-Id: If868f793b909a6ad7fc48a7affac15e2c714fa2e
Signed-off-by: Yu-Ping Wu <yupingso@chromium.org>
Reviewed-on: https://review.coreboot.org/c/coreboot/+/59834
Tested-by: build bot (Jenkins) <no-reply@coreboot.org>
Reviewed-by: Julius Werner <jwerner@chromium.org>
Reviewed-by: Paul Menzel <paulepanter@mailbox.org>
Diffstat (limited to 'src')
-rw-r--r-- | src/include/lib.h | 4 |
1 files changed, 2 insertions, 2 deletions
diff --git a/src/include/lib.h b/src/include/lib.h index 8e8bab55c1..b3cedb571c 100644 --- a/src/include/lib.h +++ b/src/include/lib.h @@ -54,8 +54,8 @@ static inline int log2(u32 x) { return sizeof(x) * 8 - clz(x) - 1; } /* Find First Set: __ffs(1) == 0, __ffs(0) == -1, __ffs(1<<31) == 31 */ static inline int __ffs(u32 x) { return log2(x & (u32)(-(s32)x)); } -/* Integer binary logarithm (rounding up): log2_ceil(0) == -1, log2(5) == 3 */ -static inline int log2_ceil(u32 x) { return (x == 0) ? -1 : log2(x * 2 - 1); } +/* Integer binary logarithm (rounding up): log2_ceil(0) == -1, log2_ceil(5) == 3 */ +static inline int log2_ceil(u32 x) { return (x == 0) ? -1 : log2(x - 1) + 1; } static inline int popcnt64(u64 x) { return __builtin_popcountll(x); } static inline int clz64(u64 x) { return x ? __builtin_clzll(x) : sizeof(x) * 8; } |