[PATCH] drm/fixed: use fls64() in drm_fixp_msbset()
From: Oarora Etimis
Date: Tue Nov 17 2026 - 06:32:39 EST
Replace the loop with fls64() on the value with the sign folded away.
Output is unchanged. The loop runs once per bit it has to skip, so a
channel value takes it about 47 iterations and 347 executed
instructions. The replacement is 6, and the work is one bit scan: bsr on
x86-64, two bsrl on i386, clz on arm and riscv.
Signed-off-by: Oarora Etimis <oaroraetimis@xxxxxxxxx>
---
drm_fixp_msbset() walks from bit 62 down, one bit at a time, to find the
highest bit that differs from the sign bit. fls64() returns the same
value in one step.
In the other users it is only called a few times, so the loop does not
show. In vkms it runs for every channel of every pixel of every frame,
and a channel value is 16 bits wide, so each run starts 47 compares from
its answer.
Link: https://lore.kernel.org/20261108-lut-v1-0-f762d70ae4cd@xxxxxxxxx
Fold the sign away and let the CPU find the highest set bit. The range
drm_fixp_div() shifts by is unchanged, and the output is bit-identical.
Counted with callgrind, gcc 16.2.1 at -O2 on x86-64, function body only.
---
include/drm/drm_fixed.h | 9 +++------
1 file changed, 3 insertions(+), 6 deletions(-)
diff --git a/include/drm/drm_fixed.h b/include/drm/drm_fixed.h
index 21d822aeed55..7dbe89ca30c6 100644
--- a/include/drm/drm_fixed.h
+++ b/include/drm/drm_fixed.h
@@ -28,6 +28,7 @@
#include <linux/math64.h>
#include <linux/types.h>
#include <linux/wordpart.h>
+#include <linux/bitops.h>
typedef union dfixed {
u32 full;
@@ -121,13 +122,9 @@ static inline int drm_fixp2int_ceil(s64 a)
static inline unsigned drm_fixp_msbset(s64 a)
{
- unsigned shift, sign = (a >> 63) & 1;
+ u64 v = (a < 0) ? ~(u64)a : (u64)a;
- for (shift = 62; shift > 0; --shift)
- if (((a >> shift) & 1) != sign)
- return shift;
-
- return 0;
+ return fls64(v | 1) - 1;
}
static inline s64 drm_fixp_mul(s64 a, s64 b)
---
base-commit: fc72cd52fb284f3707fa36a68ea5a22543a51d71
change-id: 20261113-fixp-msbset-5965c14bcb9b
Best regards,
--
Oarora Etimis <oaroraetimis@xxxxxxxxx>