Skip to contentSkip to conversation

virt/kvm: Replace unsafe shift check with __builtin_clzll()

PATCH New Peng Hao 1 participant 1 message Dec 23, 2025 KVM

lore
Share & tools
lore

Peng Hao

author
#0 lore raw

PATCH 1/1 virt/kvm: Replace unsafe shift check with __builtin_clzll()

From: Super User <[email protected]>

The (mask << x >> x) == mask pattern to check for shift overflow is considered undefined behavior by modern compilers and can be optimized away incorrectly.

Replace it with a safe and explicit check using __builtin_clzll() to ensure the left shift does not discard any bits. This avoids UB and is more robust.

---
 virt/kvm/dirty_ring.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
virt/kvm/dirty_ring.c +1 -1
index 02bc6b00d76c..926a4c0115d1 100644
@@ -171,7 +171,7 @@ int kvm_dirty_ring_reset(struct kvm *kvm, struct kvm_dirty_ring *ring,
 
 				/* Backwards visit, careful about overflows! */
 				if (delta > -BITS_PER_LONG && delta < 0 &&
-				(mask << -delta >> -delta) == mask) {
+				(unsigned long)-delta <= __builtin_clzll(mask)) {
 					cur_offset = next_offset;
 					mask = (mask << -delta) | 1;
 					continue;
Signature · 1 line
2.49.0