Skip to contentSkip to conversation

xen: Rework for_each_set_bit()

PATCH Superseded Andrew Cooper 4 participants 24 messages Jun 25, 2024 – Aug 23, 2024

v1 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
#0 lore raw

cover xen: Rework for_each_set_bit()

for_each_set_bit() is currently horribly inefficient for how we commonly use it. See patch 4 for details.

Andrew Cooper (6):
x86/vmx: Rewrite vmx_sync_pir_to_irr() to be more efficient xen/bitops: Rename for_each_set_bit() to bitmap_for_each() xen/macros: Introduce BUILD_ERROR()
xen/bitops: Introduce for_each_set_bit() ARM/vgic: Use for_each_set_bit() in vgic_set_irqs_pending() x86/xstate: Switch back to for_each_set_bit()

 xen/arch/arm/gic-vgic.c          |  2 +-
 xen/arch/arm/vgic.c              |  8 ++---
 xen/arch/arm/vgic/vgic-mmio-v2.c |  2 +-
 xen/arch/arm/vgic/vgic-mmio.c    | 12 +++----
 xen/arch/x86/cpu-policy.c        | 10 +++---
 xen/arch/x86/hvm/vmx/vmx.c       | 61 +++++++++++++++++++++++++++-----
 xen/arch/x86/xstate.c            |  8 ++---
 xen/common/bitops.c              | 29 +++++++++++++++
 xen/include/xen/bitmap.h         | 12 +++++++
 xen/include/xen/bitops.h         | 35 ++++++++++++------
 xen/include/xen/macros.h         |  2 ++
 xen/include/xen/self-tests.h     |  4 +--
 12 files changed, 142 insertions(+), 43 deletions(-)
Signature · 1 line
2.39.2
#1 lore raw

PATCH 1/6 x86/vmx: Rewrite vmx_sync_pir_to_irr() to be more efficient

There are two issues. First, pi_test_and_clear_on() pulls the cache-line to the CPU and dirties it even if there's nothing outstanding, but the final for_each_set_bit() is O(256) when O(8) would do, and would avoid multiple atomic updates to the same IRR word.

Rewrite it from scratch, explaining what's going on at each step.

Bloat-o-meter reports 177 -> 145 (net -32), but the better aspect is the removal calls to __find_{first,next}_bit() hidden behind for_each_set_bit().

No functional change.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Stefano Stabellini <[email protected]>
CC: Julien Grall <[email protected]>
CC: Volodymyr Babchuk <[email protected]>
CC: Bertrand Marquis <[email protected]>
CC: Michal Orzel <[email protected]>
CC: Oleksii Kurochko <[email protected]>

The main purpose of this is to get rid of for_each_set_bit().

Full side-by-side diff:
https://termbin.com/5wsb

The first loop ends up being unrolled identically, although there's 64bit movs to reload 0 for the xchg which is definitely suboptimal. Opencoding asm ("xchg") without a memory clobber gets to 32bit movs which is an improvement but no ideal. However I didn't fancy going that far.

Also, the entirety of pi_desc is embedded in struct vcpu, which means when we're executing in Xen, the prefetcher is going to be stealing it back from the IOMMU all the time. This is a datastructure which really should *not* be adjacent to all the other misc data in the vcpu.

---
 xen/arch/x86/hvm/vmx/vmx.c | 61 +++++++++++++++++++++++++++++++++-----
 1 file changed, 53 insertions(+), 8 deletions(-)
xen/arch/x86/hvm/vmx/vmx.c +53 -8
index f16faa6a615c..948ad48a4757 100644
@@ -2321,18 +2321,63 @@ static void cf_check vmx_deliver_posted_intr(struct vcpu *v, u8 vector)
 
 static void cf_check vmx_sync_pir_to_irr(struct vcpu *v)
 {
-    struct vlapic *vlapic = vcpu_vlapic(v);
-    unsigned int group, i;
-    DECLARE_BITMAP(pending_intr, X86_NR_VECTORS);
+    struct pi_desc *desc = &v->arch.hvm.vmx.pi_desc;
+    union {
+        uint64_t _64[X86_NR_VECTORS / (sizeof(uint64_t) * 8)];
+        uint32_t _32[X86_NR_VECTORS / (sizeof(uint32_t) * 8)];
+    } vec;
+    uint32_t *irr;
+    bool on;
 
-    if ( !pi_test_and_clear_on(&v->arch.hvm.vmx.pi_desc) )
+    /*
+     * The PIR is a contended cacheline which bounces between the CPU and
+     * IOMMU.  The IOMMU updates the entire PIR atomically, but we can't
+     * express the same on the CPU side, so care has to be taken.
+     *
+     * First, do a plain read of ON.  If the PIR hasn't been modified, this
+     * will keep the cacheline Shared and not pull it Excusive on the CPU.
+     */
+    if ( !pi_test_on(desc) )
         return;
 
-    for ( group = 0; group < ARRAY_SIZE(pending_intr); group++ )
-        pending_intr[group] = pi_get_pir(&v->arch.hvm.vmx.pi_desc, group);
+    /*
+     * Second, if the plain read said that ON was set, we must clear it with
+     * an atomic action.  This will bring the cachline to Exclusive on the
+     * CPU.
+     *
+     * This should always succeed because noone else should be playing with
+     * the PIR behind our back, but assert so just in case.
+     */
+    on = pi_test_and_clear_on(desc);
+    ASSERT(on);
 
-    for_each_set_bit(i, pending_intr, X86_NR_VECTORS)
-        vlapic_set_vector(i, &vlapic->regs->data[APIC_IRR]);
+    /*
+     * The cacheline is now Exclusive on the CPU, and the IOMMU has indicated
+     * (via ON being set) thatat least one vector is pending too.  Atomically
+     * read and clear the entire pending bitmap as fast as we, to reduce the
+     * window that the IOMMU may steal the cacheline back from us.
+     *
+     * It is a performance concern, but not a correctness concern.  If the
+     * IOMMU does steal the cacheline back, we'll just wait to get it back
+     * again.
+     */
+    for ( unsigned int i = 0; i < ARRAY_SIZE(vec._64); ++i )
+        vec._64[i] = xchg(&desc->pir[i], 0);
+
+    /*
+     * Finally, merge the pending vectors into IRR.  The IRR register is
+     * scattered in memory, so we have to do this 32 bits at a time.
+     */
+    irr = (uint32_t *)&vcpu_vlapic(v)->regs->data[APIC_IRR];
+    for ( unsigned int i = 0; i < ARRAY_SIZE(vec._32); ++i )
+    {
+        if ( !vec._32[i] )
+            continue;
+
+        asm ( "lock or %[val], %[irr]"
+              : [irr] "+m" (irr[i * 0x10])
+              : [val] "r" (vec._32[i]) );
+    }
 }
 
 static bool cf_check vmx_test_pir(const struct vcpu *v, uint8_t vec)
Signature · 1 line
2.39.2
#2 lore raw

Re: [PATCH 1/6] x86/vmx: Rewrite vmx_sync_pir_to_irr() to be more efficient

Quoted 4 lines · Andrew Cooper

There are two issues. First, pi_test_and_clear_on() pulls the cache-line to the CPU and dirties it even if there's nothing outstanding, but the final for_each_set_bit() is O(256) when O(8) would do, and would avoid multiple atomic updates to the same IRR word.

The way it's worded (grammar wise) it appears as if the 2nd issue is missing from this description. Perhaps you meant to break the sentence at "but" (and re-word a little what follows), which feels a little unmotivated to me (as a non-native speaker, i.e. may not mean anything) anyway? Or maybe something simply got lost in the middle?

Quoted 29 lines
xen/arch/x86/hvm/vmx/vmx.c +16 -4
@@ -2321,18 +2321,63 @@ static void cf_check vmx_deliver_posted_intr(struct vcpu *v, u8 vector)
 
 static void cf_check vmx_sync_pir_to_irr(struct vcpu *v)
 {
-    struct vlapic *vlapic = vcpu_vlapic(v);
-    unsigned int group, i;
-    DECLARE_BITMAP(pending_intr, X86_NR_VECTORS);
+    struct pi_desc *desc = &v->arch.hvm.vmx.pi_desc;
+    union {
+        uint64_t _64[X86_NR_VECTORS / (sizeof(uint64_t) * 8)];
+        uint32_t _32[X86_NR_VECTORS / (sizeof(uint32_t) * 8)];
+    } vec;
+    uint32_t *irr;
+    bool on;
 
-    if ( !pi_test_and_clear_on(&v->arch.hvm.vmx.pi_desc) )
+    /*
+     * The PIR is a contended cacheline which bounces between the CPU and
+     * IOMMU.  The IOMMU updates the entire PIR atomically, but we can't
+     * express the same on the CPU side, so care has to be taken.
+     *
+     * First, do a plain read of ON.  If the PIR hasn't been modified, this
+     * will keep the cacheline Shared and not pull it Excusive on the CPU.
+     */
+    if ( !pi_test_on(desc) )
         return;
 

xen/arch/x86/hvm/vmx/vmx.c static void cf_check vmx_deliver_posted_intr(struct vcpu *v, u8 vector) · line 2350

Quoted 10 lines
xen/arch/x86/hvm/vmx/vmx.c +8 -2
-    for ( group = 0; group < ARRAY_SIZE(pending_intr); group++ )
-        pending_intr[group] = pi_get_pir(&v->arch.hvm.vmx.pi_desc, group);
+    /*
+     * Second, if the plain read said that ON was set, we must clear it with
+     * an atomic action.  This will bring the cachline to Exclusive on the
+     * CPU.
+     *
+     * This should always succeed because noone else should be playing with
+     * the PIR behind our back, but assert so just in case.
+     */

Isn't "playing with" more strict than what is the case, and what we need here? Aiui nothing should _clear this bit_ behind our back, while PIR covers more than just this one bit, and the bit may also become reset immediately after we cleared it.

xen/arch/x86/hvm/vmx/vmx.c static void cf_check vmx_deliver_posted_intr(struct vcpu *v, u8 vector)

Quoted 8 lines
xen/arch/x86/hvm/vmx/vmx.c +5 -2
+    on = pi_test_and_clear_on(desc);
+    ASSERT(on);
 
-    for_each_set_bit(i, pending_intr, X86_NR_VECTORS)
-        vlapic_set_vector(i, &vlapic->regs->data[APIC_IRR]);
+    /*
+     * The cacheline is now Exclusive on the CPU, and the IOMMU has indicated
+     * (via ON being set) thatat least one vector is pending too.

This isn't quite correct aiui, and hence perhaps better not to state it exactly like this: While we're ...

xen/arch/x86/hvm/vmx/vmx.c static void cf_check vmx_deliver_posted_intr(struct vcpu *v, u8 vector) · line 2365

Quoted 10 lines
xen/arch/x86/hvm/vmx/vmx.c +9 -0
 Atomically
+     * read and clear the entire pending bitmap as fast as we, to reduce the
+     * window that the IOMMU may steal the cacheline back from us.
+     *
+     * It is a performance concern, but not a correctness concern.  If the
+     * IOMMU does steal the cacheline back, we'll just wait to get it back
+     * again.
+     */
+    for ( unsigned int i = 0; i < ARRAY_SIZE(vec._64); ++i )
+        vec._64[i] = xchg(&desc->pir[i], 0);

... still ahead of or in this loop, new bits may become set which we then may handle right away. The "on" indication on the next entry into this logic may then be misleading, as we may not find any set bit.

All the code changes look good to me, otoh.

Jan

Quoted 17 lines
xen/arch/x86/hvm/vmx/vmx.c +14 -0
+    /*
+     * Finally, merge the pending vectors into IRR.  The IRR register is
+     * scattered in memory, so we have to do this 32 bits at a time.
+     */
+    irr = (uint32_t *)&vcpu_vlapic(v)->regs->data[APIC_IRR];
+    for ( unsigned int i = 0; i < ARRAY_SIZE(vec._32); ++i )
+    {
+        if ( !vec._32[i] )
+            continue;
+
+        asm ( "lock or %[val], %[irr]"
+              : [irr] "+m" (irr[i * 0x10])
+              : [val] "r" (vec._32[i]) );
+    }
 }
 
 static bool cf_check vmx_test_pir(const struct vcpu *v, uint8_t vec)
#3 lore raw

Re: [PATCH 1/6] x86/vmx: Rewrite vmx_sync_pir_to_irr() to be more efficient

Quoted 10 lines · Jan Beulich
Quoted 4 lines · Andrew Cooper

There are two issues. First, pi_test_and_clear_on() pulls the cache-line to the CPU and dirties it even if there's nothing outstanding, but the final for_each_set_bit() is O(256) when O(8) would do, and would avoid multiple atomic updates to the same IRR word.

The way it's worded (grammar wise) it appears as if the 2nd issue is missing from this description. Perhaps you meant to break the sentence at "but" (and re-word a little what follows), which feels a little unmotivated to me (as a non-native speaker, i.e. may not mean anything) anyway? Or maybe something simply got lost in the middle?

You're right - the grammar is not great.  I'll rework it.

Quoted 30 lines
Quoted 30 lines
xen/arch/x86/hvm/vmx/vmx.c +16 -4
@@ -2321,18 +2321,63 @@ static void cf_check vmx_deliver_posted_intr(struct vcpu *v, u8 vector)
 
 static void cf_check vmx_sync_pir_to_irr(struct vcpu *v)
 {
-    struct vlapic *vlapic = vcpu_vlapic(v);
-    unsigned int group, i;
-    DECLARE_BITMAP(pending_intr, X86_NR_VECTORS);
+    struct pi_desc *desc = &v->arch.hvm.vmx.pi_desc;
+    union {
+        uint64_t _64[X86_NR_VECTORS / (sizeof(uint64_t) * 8)];
+        uint32_t _32[X86_NR_VECTORS / (sizeof(uint32_t) * 8)];
+    } vec;
+    uint32_t *irr;
+    bool on;
 
-    if ( !pi_test_and_clear_on(&v->arch.hvm.vmx.pi_desc) )
+    /*
+     * The PIR is a contended cacheline which bounces between the CPU and
+     * IOMMU.  The IOMMU updates the entire PIR atomically, but we can't
+     * express the same on the CPU side, so care has to be taken.
+     *
+     * First, do a plain read of ON.  If the PIR hasn't been modified, this
+     * will keep the cacheline Shared and not pull it Excusive on the CPU.
+     */
+    if ( !pi_test_on(desc) )
         return;
 
Quoted 14 lines

xen/arch/x86/hvm/vmx/vmx.c static void cf_check vmx_deliver_posted_intr(struct vcpu *v, u8 vector) · line 2350

Quoted 10 lines
xen/arch/x86/hvm/vmx/vmx.c +8 -2
-    for ( group = 0; group < ARRAY_SIZE(pending_intr); group++ )
-        pending_intr[group] = pi_get_pir(&v->arch.hvm.vmx.pi_desc, group);
+    /*
+     * Second, if the plain read said that ON was set, we must clear it with
+     * an atomic action.  This will bring the cachline to Exclusive on the
+     * CPU.
+     *
+     * This should always succeed because noone else should be playing with
+     * the PIR behind our back, but assert so just in case.
+     */

Isn't "playing with" more strict than what is the case, and what we need here? Aiui nothing should _clear this bit_ behind our back, while PIR covers more than just this one bit, and the bit may also become reset immediately after we cleared it.

The IOMMU or other CPU forwarding an IPI strictly sets ON, and this CPU (either the logic here, or microcode when in non-root mode) strictly clears it.

But it is ON specifically that we care about, so I'll make that more clear.

Quoted 22 lines

xen/arch/x86/hvm/vmx/vmx.c static void cf_check vmx_deliver_posted_intr(struct vcpu *v, u8 vector)

Quoted 9 lines
xen/arch/x86/hvm/vmx/vmx.c +5 -2
+    on = pi_test_and_clear_on(desc);
+    ASSERT(on);
 
-    for_each_set_bit(i, pending_intr, X86_NR_VECTORS)
-        vlapic_set_vector(i, &vlapic->regs->data[APIC_IRR]);
+    /*
+     * The cacheline is now Exclusive on the CPU, and the IOMMU has indicated
+     * (via ON being set) thatat least one vector is pending too.

This isn't quite correct aiui, and hence perhaps better not to state it exactly like this: While we're ...

xen/arch/x86/hvm/vmx/vmx.c static void cf_check vmx_deliver_posted_intr(struct vcpu *v, u8 vector) · line 2365

Quoted 10 lines
xen/arch/x86/hvm/vmx/vmx.c +9 -0
 Atomically
+     * read and clear the entire pending bitmap as fast as we, to reduce the
+     * window that the IOMMU may steal the cacheline back from us.
+     *
+     * It is a performance concern, but not a correctness concern.  If the
+     * IOMMU does steal the cacheline back, we'll just wait to get it back
+     * again.
+     */
+    for ( unsigned int i = 0; i < ARRAY_SIZE(vec._64); ++i )
+        vec._64[i] = xchg(&desc->pir[i], 0);
Quoted 3 lines

... still ahead of or in this loop, new bits may become set which we then may handle right away. The "on" indication on the next entry into this logic may then be misleading, as we may not find any set bit.

Hmm.  Yes.

The IOMMU atomically swaps the entire cacheline in one go, so won't produce this state.  However, the SDM algorithm for consuming it says specifically:

1) LOCK AND to clear ON, leaving everything else unmodified
2) 256-bit-granular read&0 PIR, merging into VIRR

Which now I think about it, is almost certainly because the Atom cores only have a 256-bit datapath.

Another Xen CPU sending an IPI sideways will have to do:

    set_bit(pir[vec])
    set_bit(ON)
    IPI(delivery vector)

in this order for everything to work.

ON is the signal for "go and scan the PIR", and (other than exact ordering races during delivery) means that there is a bit set in PIR.

I'll see if I can make this clearer.

Quoted 1 line

All the code changes look good to me, otoh.

Thanks.

~Andrew

#4 lore raw

Re: [PATCH 1/6] x86/vmx: Rewrite vmx_sync_pir_to_irr() to be more efficient

Quoted 106 lines · Andrew Cooper
Quoted 10 lines · Jan Beulich
Quoted 4 lines · Andrew Cooper

There are two issues. First, pi_test_and_clear_on() pulls the cache-line to the CPU and dirties it even if there's nothing outstanding, but the final for_each_set_bit() is O(256) when O(8) would do, and would avoid multiple atomic updates to the same IRR word.

The way it's worded (grammar wise) it appears as if the 2nd issue is missing from this description. Perhaps you meant to break the sentence at "but" (and re-word a little what follows), which feels a little unmotivated to me (as a non-native speaker, i.e. may not mean anything) anyway? Or maybe something simply got lost in the middle?

You're right - the grammar is not great.  I'll rework it.

Quoted 29 lines
Quoted 29 lines
xen/arch/x86/hvm/vmx/vmx.c +16 -4
@@ -2321,18 +2321,63 @@ static void cf_check vmx_deliver_posted_intr(struct vcpu *v, u8 vector)
 
 static void cf_check vmx_sync_pir_to_irr(struct vcpu *v)
 {
-    struct vlapic *vlapic = vcpu_vlapic(v);
-    unsigned int group, i;
-    DECLARE_BITMAP(pending_intr, X86_NR_VECTORS);
+    struct pi_desc *desc = &v->arch.hvm.vmx.pi_desc;
+    union {
+        uint64_t _64[X86_NR_VECTORS / (sizeof(uint64_t) * 8)];
+        uint32_t _32[X86_NR_VECTORS / (sizeof(uint32_t) * 8)];
+    } vec;
+    uint32_t *irr;
+    bool on;
 
-    if ( !pi_test_and_clear_on(&v->arch.hvm.vmx.pi_desc) )
+    /*
+     * The PIR is a contended cacheline which bounces between the CPU and
+     * IOMMU.  The IOMMU updates the entire PIR atomically, but we can't
+     * express the same on the CPU side, so care has to be taken.
+     *
+     * First, do a plain read of ON.  If the PIR hasn't been modified, this
+     * will keep the cacheline Shared and not pull it Excusive on the CPU.
+     */
+    if ( !pi_test_on(desc) )
         return;
 
Quoted 14 lines

xen/arch/x86/hvm/vmx/vmx.c static void cf_check vmx_deliver_posted_intr(struct vcpu *v, u8 vector) · line 2350

Quoted 10 lines
xen/arch/x86/hvm/vmx/vmx.c +8 -2
-    for ( group = 0; group < ARRAY_SIZE(pending_intr); group++ )
-        pending_intr[group] = pi_get_pir(&v->arch.hvm.vmx.pi_desc, group);
+    /*
+     * Second, if the plain read said that ON was set, we must clear it with
+     * an atomic action.  This will bring the cachline to Exclusive on the
+     * CPU.
+     *
+     * This should always succeed because noone else should be playing with
+     * the PIR behind our back, but assert so just in case.
+     */

Isn't "playing with" more strict than what is the case, and what we need here? Aiui nothing should _clear this bit_ behind our back, while PIR covers more than just this one bit, and the bit may also become reset immediately after we cleared it.

The IOMMU or other CPU forwarding an IPI strictly sets ON, and this CPU (either the logic here, or microcode when in non-root mode) strictly clears it.

But it is ON specifically that we care about, so I'll make that more clear.

Quoted 21 lines

xen/arch/x86/hvm/vmx/vmx.c static void cf_check vmx_deliver_posted_intr(struct vcpu *v, u8 vector)

Quoted 8 lines
xen/arch/x86/hvm/vmx/vmx.c +5 -2
+    on = pi_test_and_clear_on(desc);
+    ASSERT(on);
 
-    for_each_set_bit(i, pending_intr, X86_NR_VECTORS)
-        vlapic_set_vector(i, &vlapic->regs->data[APIC_IRR]);
+    /*
+     * The cacheline is now Exclusive on the CPU, and the IOMMU has indicated
+     * (via ON being set) thatat least one vector is pending too.

This isn't quite correct aiui, and hence perhaps better not to state it exactly like this: While we're ...

xen/arch/x86/hvm/vmx/vmx.c static void cf_check vmx_deliver_posted_intr(struct vcpu *v, u8 vector) · line 2365

Quoted 10 lines
xen/arch/x86/hvm/vmx/vmx.c +9 -0
 Atomically
+     * read and clear the entire pending bitmap as fast as we, to reduce the
+     * window that the IOMMU may steal the cacheline back from us.
+     *
+     * It is a performance concern, but not a correctness concern.  If the
+     * IOMMU does steal the cacheline back, we'll just wait to get it back
+     * again.
+     */
+    for ( unsigned int i = 0; i < ARRAY_SIZE(vec._64); ++i )
+        vec._64[i] = xchg(&desc->pir[i], 0);
Quoted 3 lines

... still ahead of or in this loop, new bits may become set which we then may handle right away. The "on" indication on the next entry into this logic may then be misleading, as we may not find any set bit.

Hmm.  Yes.

The IOMMU atomically swaps the entire cacheline in one go, so won't produce this state.  However, the SDM algorithm for consuming it says specifically:

1) LOCK AND to clear ON, leaving everything else unmodified
2) 256-bit-granular read&0 PIR, merging into VIRR

Which now I think about it, is almost certainly because the Atom cores only have a 256-bit datapath.

Another Xen CPU sending an IPI sideways will have to do:

    set_bit(pir[vec])
    set_bit(ON)
    IPI(delivery vector)

in this order for everything to work.

Quoted 8 lines

ON is the signal for "go and scan the PIR", and (other than exact ordering races during delivery) means that there is a bit set in PIR.

I'll see if I can make this clearer.

Quoted 1 line

All the code changes look good to me, otoh.

Thanks.

One final thing.

This logic here depends on interrupts not being enabled between these atomic actions, and entering non-root mode.

Specifically, Xen must not service a pending delivery-notification vector between this point and the VMEntry microcode repeating the same scan on the PIR Descriptor.

Getting this wrong means that we'll miss the delivery of vectors which arrive between here and the next time something causes a delivery-notification vector to be sent.

However, I've got no idea how to reasonably express this with assertions.  We could in principle have a per-cpu "mustn't enable interrupts" flag, checked in local_irq_enable/restore(), but it only works in HVM context, and gets too messy IMO.

~Andrew

#5 lore raw

Re: [PATCH 1/6] x86/vmx: Rewrite vmx_sync_pir_to_irr() to be more efficient

Quoted 9 lines · Andrew Cooper

One final thing.

This logic here depends on interrupts not being enabled between these atomic actions, and entering non-root mode.

Specifically, Xen must not service a pending delivery-notification vector between this point and the VMEntry microcode repeating the same scan on the PIR Descriptor.

Quoted 8 lines

Getting this wrong means that we'll miss the delivery of vectors which arrive between here and the next time something causes a delivery-notification vector to be sent.

However, I've got no idea how to reasonably express this with assertions.  We could in principle have a per-cpu "mustn't enable interrupts" flag, checked in local_irq_enable/restore(), but it only works in HVM context, and gets too messy IMO.

I agree. It's also nothing this patch changes; it was like this before already. If and when we can think of a good way of expressing it, then surely we could improve things here.

Jan

#6 lore raw

PATCH 2/6 xen/bitops: Rename for_each_set_bit() to bitmap_for_each()

In reply to Andrew Cooper

The current implementation wants to take an in-memory bitmap. However, all ARM callers and all-but-1 x86 callers spill a scalar to the stack in order to use the "generic arbitrary bitmap" helpers under the hood.

This functions, but it's far from ideal.

Rename the construct and move it into bitmap.h, because having an iterator for an arbitrary bitmap is a useful thing.

This will allow us to re-implement for_each_set_bit() to be more appropriate for scalar values.

No functional change.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Stefano Stabellini <[email protected]>
CC: Julien Grall <[email protected]>
CC: Volodymyr Babchuk <[email protected]>
CC: Bertrand Marquis <[email protected]>
CC: Michal Orzel <[email protected]>
CC: Oleksii Kurochko <[email protected]>

---
 xen/arch/arm/gic-vgic.c          |  2 +-
 xen/arch/arm/vgic.c              |  6 +++---
 xen/arch/arm/vgic/vgic-mmio-v2.c |  2 +-
 xen/arch/arm/vgic/vgic-mmio.c    | 12 ++++++------
 xen/arch/x86/cpu-policy.c        |  8 ++++----
 xen/arch/x86/xstate.c            |  4 ++--
 xen/include/xen/bitmap.h         | 12 ++++++++++++
 xen/include/xen/bitops.h         | 11 -----------
 8 files changed, 29 insertions(+), 28 deletions(-)
xen/arch/arm/gic-vgic.c +1 -1
index b99e28722425..0dfff76a238e 100644
@@ -111,7 +111,7 @@ static unsigned int gic_find_unused_lr(struct vcpu *v,
     {
         unsigned int used_lr;
 
-        for_each_set_bit(used_lr, lr_mask, nr_lrs)
+        bitmap_for_each(used_lr, lr_mask, nr_lrs)
         {
             gic_hw_ops->read_lr(used_lr, &lr_val);
             if ( lr_val.virq == p->irq )
xen/arch/arm/vgic.c +3 -3
index c04fc4f83f96..57519e834d78 100644
@@ -429,7 +429,7 @@ void vgic_set_irqs_pending(struct vcpu *v, uint32_t r, unsigned int rank)
     /* LPIs will never be set pending via this function */
     ASSERT(!is_lpi(32 * rank + 31));
 
-    for_each_set_bit( i, &mask, 32 )
+    bitmap_for_each( i, &mask, 32 )
     {
         unsigned int irq = i + 32 * rank;
 
@@ -483,7 +483,7 @@ bool vgic_to_sgi(struct vcpu *v, register_t sgir, enum gic_sgi_mode irqmode,
         perfc_incr(vgic_sgi_list);
         base = target->aff1 << 4;
         bitmap = target->list;
-        for_each_set_bit( i, &bitmap, sizeof(target->list) * 8 )
+        bitmap_for_each( i, &bitmap, sizeof(target->list) * 8 )
         {
             vcpuid = base + i;
             if ( vcpuid >= d->max_vcpus || d->vcpu[vcpuid] == NULL ||
@@ -728,7 +728,7 @@ void vgic_check_inflight_irqs_pending(struct domain *d, struct vcpu *v,
     const unsigned long mask = r;
     unsigned int i;
 
-    for_each_set_bit( i, &mask, 32 )
+    bitmap_for_each( i, &mask, 32 )
     {
         struct pending_irq *p;
         struct vcpu *v_target;
xen/arch/arm/vgic/vgic-mmio-v2.c +1 -1
index 2e507b10fed5..82d0c22b39fc 100644
@@ -108,7 +108,7 @@ static void vgic_mmio_write_sgir(struct vcpu *source_vcpu,
         return;
     }
 
-    for_each_set_bit( vcpu_id, &targets, 8 )
+    bitmap_for_each( vcpu_id, &targets, 8 )
     {
         struct vcpu *vcpu = d->vcpu[vcpu_id];
         struct vgic_irq *irq = vgic_get_irq(d, vcpu, intid);
xen/arch/arm/vgic/vgic-mmio.c +6 -6
index 5d935a73013e..b023ecc20066 100644
@@ -71,7 +71,7 @@ void vgic_mmio_write_senable(struct vcpu *vcpu,
     uint32_t intid = VGIC_ADDR_TO_INTID(addr, 1);
     unsigned int i;
 
-    for_each_set_bit( i, &val, len * 8 )
+    bitmap_for_each( i, &val, len * 8 )
     {
         struct vgic_irq *irq = vgic_get_irq(vcpu->domain, vcpu, intid + i);
         unsigned long flags;
@@ -116,7 +116,7 @@ void vgic_mmio_write_cenable(struct vcpu *vcpu,
     uint32_t intid = VGIC_ADDR_TO_INTID(addr, 1);
     unsigned int i;
 
-    for_each_set_bit( i, &val, len * 8 )
+    bitmap_for_each( i, &val, len * 8 )
     {
         struct vgic_irq *irq;
         unsigned long flags;
@@ -186,7 +186,7 @@ void vgic_mmio_write_spending(struct vcpu *vcpu,
     unsigned long flags;
     irq_desc_t *desc;
 
-    for_each_set_bit( i, &val, len * 8 )
+    bitmap_for_each( i, &val, len * 8 )
     {
         struct vgic_irq *irq = vgic_get_irq(vcpu->domain, vcpu, intid + i);
 
@@ -234,7 +234,7 @@ void vgic_mmio_write_cpending(struct vcpu *vcpu,
     unsigned long flags;
     irq_desc_t *desc;
 
-    for_each_set_bit( i, &val, len * 8 )
+    bitmap_for_each( i, &val, len * 8 )
     {
         struct vgic_irq *irq = vgic_get_irq(vcpu->domain, vcpu, intid + i);
 
@@ -328,7 +328,7 @@ void vgic_mmio_write_cactive(struct vcpu *vcpu,
     uint32_t intid = VGIC_ADDR_TO_INTID(addr, 1);
     unsigned int i;
 
-    for_each_set_bit( i, &val, len * 8 )
+    bitmap_for_each( i, &val, len * 8 )
     {
         struct vgic_irq *irq = vgic_get_irq(vcpu->domain, vcpu, intid + i);
 
@@ -358,7 +358,7 @@ void vgic_mmio_write_sactive(struct vcpu *vcpu,
     uint32_t intid = VGIC_ADDR_TO_INTID(addr, 1);
     unsigned int i;
 
-    for_each_set_bit( i, &val, len * 8 )
+    bitmap_for_each( i, &val, len * 8 )
     {
         struct vgic_irq *irq = vgic_get_irq(vcpu->domain, vcpu, intid + i);
 
xen/arch/x86/cpu-policy.c +4 -4
index 304dc20cfab8..cd53bac777dc 100644
@@ -157,7 +157,7 @@ static void zero_leaves(struct cpuid_leaf *l,
 
 static void sanitise_featureset(uint32_t *fs)
 {
-    /* for_each_set_bit() uses unsigned longs.  Extend with zeroes. */
+    /* bitmap_for_each() uses unsigned longs.  Extend with zeroes. */
     uint32_t disabled_features[
         ROUNDUP(FSCAPINTS, sizeof(unsigned long)/sizeof(uint32_t))] = {};
     unsigned int i;
@@ -174,8 +174,8 @@ static void sanitise_featureset(uint32_t *fs)
         disabled_features[i] = ~fs[i] & deep_features[i];
     }
 
-    for_each_set_bit(i, (void *)disabled_features,
-                     sizeof(disabled_features) * 8)
+    bitmap_for_each(i, (void *)disabled_features,
+                    sizeof(disabled_features) * 8)
     {
         const uint32_t *dfs = x86_cpu_policy_lookup_deep_deps(i);
         unsigned int j;
@@ -237,7 +237,7 @@ static void recalculate_xstate(struct cpu_policy *p)
     /* Subleafs 2+ */
     xstates &= ~XSTATE_FP_SSE;
     BUILD_BUG_ON(ARRAY_SIZE(p->xstate.comp) < 63);
-    for_each_set_bit ( i, &xstates, 63 )
+    bitmap_for_each ( i, &xstates, 63 )
     {
         /*
          * Pass through size (eax) and offset (ebx) directly.  Visbility of
xen/arch/x86/xstate.c +2 -2
index 68cdd8fcf021..da9053c0a262 100644
@@ -606,7 +606,7 @@ unsigned int xstate_uncompressed_size(uint64_t xcr0)
      * with respect their index.
      */
     xcr0 &= ~(X86_XCR0_SSE | X86_XCR0_X87);
-    for_each_set_bit ( i, &xcr0, 63 )
+    bitmap_for_each ( i, &xcr0, 63 )
     {
         const struct xstate_component *c = &raw_cpu_policy.xstate.comp[i];
         unsigned int s = c->offset + c->size;
@@ -634,7 +634,7 @@ unsigned int xstate_compressed_size(uint64_t xstates)
      * componenets require aligning to 64 first.
      */
     xstates &= ~(X86_XCR0_SSE | X86_XCR0_X87);
-    for_each_set_bit ( i, &xstates, 63 )
+    bitmap_for_each ( i, &xstates, 63 )
     {
         const struct xstate_component *c = &raw_cpu_policy.xstate.comp[i];
 
xen/include/xen/bitmap.h +12 -0
index b9f980e91930..5dd7db5be9e7 100644
@@ -271,6 +271,18 @@ static inline void bitmap_clear(unsigned long *map, unsigned int start,
 #undef bitmap_switch
 #undef bitmap_bytes
 
+/**
+ * bitmap_for_each - iterate over every set bit in a memory region
+ * @iter: The integer iterator
+ * @addr: The address to base the search on
+ * @size: The maximum size to search
+ */
+#define bitmap_for_each(iter, addr, size)                        \
+    for ( (iter) = find_first_bit(addr, size);                   \
+          (iter) < (size);                                       \
+          (iter) = find_next_bit(addr, size, (iter) + 1) )
+
+
 struct xenctl_bitmap;
 int xenctl_bitmap_to_bitmap(unsigned long *bitmap,
                             const struct xenctl_bitmap *xenctl_bitmap,
xen/include/xen/bitops.h +0 -11
index 6a5e28730a25..24de0835b7ab 100644
@@ -248,17 +248,6 @@ static inline __u32 ror32(__u32 word, unsigned int shift)
 #define __L16(x) (((x) & 0x0000ff00U) ? ( 8 + __L8( (x) >> 8))  : __L8( x))
 #define ilog2(x) (((x) & 0xffff0000U) ? (16 + __L16((x) >> 16)) : __L16(x))
 
-/**
- * for_each_set_bit - iterate over every set bit in a memory region
- * @bit: The integer iterator
- * @addr: The address to base the search on
- * @size: The maximum size to search
- */
-#define for_each_set_bit(bit, addr, size)               \
-    for ( (bit) = find_first_bit(addr, size);           \
-          (bit) < (size);                               \
-          (bit) = find_next_bit(addr, size, (bit) + 1) )
-
 #define BIT_WORD(nr) ((nr) / BITS_PER_LONG)
 
 #endif /* XEN_BITOPS_H */
Signature · 1 line
2.39.2
Reviewed-by on v1 2/6
#7 lore raw

Re: [PATCH 2/6] xen/bitops: Rename for_each_set_bit() to bitmap_for_each()

Quoted 9 lines · Andrew Cooper

The current implementation wants to take an in-memory bitmap. However, all ARM callers and all-but-1 x86 callers spill a scalar to the stack in order to use the "generic arbitrary bitmap" helpers under the hood.

This functions, but it's far from ideal.

Rename the construct and move it into bitmap.h, because having an iterator for an arbitrary bitmap is a useful thing.

Quoted 6 lines

This will allow us to re-implement for_each_set_bit() to be more appropriate for scalar values.

No functional change.

with one cosmetic request: While doing the rename, would you mind sorting style? Not necessarily uniformly across the entire patch, but at individual sites presently using "impossible" formatting. IOW ...

xen/arch/arm/gic-vgic.c static unsigned int gic_find_unused_lr(struct vcpu *v, · line 114

Quoted 8 lines
xen/arch/arm/gic-vgic.c +1 -1
@@ -111,7 +111,7 @@ static unsigned int gic_find_unused_lr(struct vcpu *v,
     {
         unsigned int used_lr;
 
-        for_each_set_bit(used_lr, lr_mask, nr_lrs)
+        bitmap_for_each(used_lr, lr_mask, nr_lrs)

... while this one's fine (treating bitmap_for_each as ordinary identifier) and while xstate.c is also fine (treating it as pseudo-keyword), ...

xen/arch/arm/vgic.c void vgic_set_irqs_pending(struct vcpu *v, uint32_t r, unsigned int rank) · line 433

Quoted 9 lines
xen/arch/arm/vgic.c +1 -1
@@ -429,7 +429,7 @@ void vgic_set_irqs_pending(struct vcpu *v, uint32_t r, unsigned int rank)
     /* LPIs will never be set pending via this function */
     ASSERT(!is_lpi(32 * rank + 31));
 
-    for_each_set_bit( i, &mask, 32 )
+    bitmap_for_each( i, &mask, 32 )
     {

... this isn't possible formatting according to our style: Either there are no blanks immediately inside the parentheses, or there also is one ahead of the opening one.

Thanks, Jan

Acked-by on v1 2/6
#8 lore raw

Re: [PATCH 2/6] xen/bitops: Rename for_each_set_bit() to bitmap_for_each()

In reply to Andrew Cooper
Quoted 11 lines · Andrew Cooper

The current implementation wants to take an in-memory bitmap. However, all ARM callers and all-but-1 x86 callers spill a scalar to the stack in order to use the "generic arbitrary bitmap" helpers under the hood.

This functions, but it's far from ideal.

Rename the construct and move it into bitmap.h, because having an iterator for an arbitrary bitmap is a useful thing.

Quoted 6 lines

This will allow us to re-implement for_each_set_bit() to be more appropriate for scalar values.

No functional change.

~Michal

#9 lore raw

PATCH 3/6 xen/macros: Introduce BUILD_ERROR()

In reply to Andrew Cooper

... and use it in self-tests.h.

This is intended to replace constructs such as __bitop_bad_size(). It produces a better diagnostic, and is MISRA-friendly.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Stefano Stabellini <[email protected]>
CC: Julien Grall <[email protected]>
CC: Volodymyr Babchuk <[email protected]>
CC: Bertrand Marquis <[email protected]>
CC: Michal Orzel <[email protected]>
CC: Oleksii Kurochko <[email protected]>

RFC for-4.19. This can be used to not introduce new MISRA violations when adjusting __bitop_bad_size(). It's safe to pull out of this series.

---
 xen/include/xen/macros.h     | 2 ++
 xen/include/xen/self-tests.h | 4 ++--
 2 files changed, 4 insertions(+), 2 deletions(-)
xen/include/xen/macros.h +2 -0
index ec89f4654fcf..8441d7e7d66a 100644
@@ -59,6 +59,8 @@
 #define BUILD_BUG_ON(cond) ((void)BUILD_BUG_ON_ZERO(cond))
 #endif
 
+#define BUILD_ERROR(msg) asm ( ".error \"" msg "\"" )
+
 /* Hide a value from the optimiser. */
 #define HIDE(x)                                 \
     ({                                          \
xen/include/xen/self-tests.h +2 -2
index 42a4cc4d17fe..4bc322b7f2a6 100644
@@ -22,9 +22,9 @@
         typeof(fn(val)) real = fn(val);                                 \
                                                                         \
         if ( !__builtin_constant_p(real) )                              \
-            asm ( ".error \"'" STR(fn(val)) "' not compile-time constant\"" ); \
+            BUILD_ERROR("'" STR(fn(val)) "' not compile-time constant"); \
         else if ( real != res )                                         \
-            asm ( ".error \"Compile time check '" STR(fn(val) == res) "' failed\"" ); \
+            BUILD_ERROR("Compile time check '" STR(fn(val) == res) "' failed"); \
     } while ( 0 )
 #else
 #define COMPILE_CHECK(fn, val, res)
Signature · 1 line
2.39.2
Reviewed-by on v1 3/6
#10 lore raw

Re: [PATCH for-4.19? 3/6] xen/macros: Introduce BUILD_ERROR()

xen/include/xen/macros.h line 62

Quoted 7 lines · Andrew Cooper
xen/include/xen/macros.h +1 -0
@@ -59,6 +59,8 @@
 #define BUILD_BUG_ON(cond) ((void)BUILD_BUG_ON_ZERO(cond))
 #endif
 
+#define BUILD_ERROR(msg) asm ( ".error \"" msg "\"" )

I think this wants a comment, and one even beyond what is said for BUILD_BUG_ON(). This is primarily to make clear to people when to use which, i.e. I consider it important to mention here that it is intended for code which, in the normal case, we expect to be DCE-d. The nature of the condition used is also a relevant factor, as in some cases BUILD_BUG_ON() simply cannot be used because something that really is compile time constant isn't an integer constant expression. With something to this effect:

I have another question / suggestion, though.

xen/include/xen/self-tests.h line 28

Quoted 12 lines
xen/include/xen/self-tests.h +2 -2
@@ -22,9 +22,9 @@
         typeof(fn(val)) real = fn(val);                                 \
                                                                         \
         if ( !__builtin_constant_p(real) )                              \
-            asm ( ".error \"'" STR(fn(val)) "' not compile-time constant\"" ); \
+            BUILD_ERROR("'" STR(fn(val)) "' not compile-time constant"); \
         else if ( real != res )                                         \
-            asm ( ".error \"Compile time check '" STR(fn(val) == res) "' failed\"" ); \
+            BUILD_ERROR("Compile time check '" STR(fn(val) == res) "' failed"); \
     } while ( 0 )

While right here leaving the condition outside of the macro is perhaps more natural, considering a case where there's just an if() I wonder whether we shouldn't also (only?) have BUILD_ERROR_ON(), better paralleling BUILD_BUG_ON():

    BUILD_ERROR_ON(!__builtin_constant_p(real),
                   "'" STR(fn(val)) "' not compile-time constant");

It then becomes questionable whether a string literal needs passing, or whether instead the condition couldn't just be stringified while passing to the asm():

    BUILD_ERROR_ON(!__builtin_constant_p(real));

The thing could even "return" the predicate, permitting

    if ( !BUILD_ERROR_ON(!__builtin_constant_p(real) )
        BUILD_ERROR_ON(real != res);

I realize though that there may be issues from this with unused values being diagnosed by compiler and/or Eclair, when the "return value" is not of interest.

I'd be fine with the respective transformation to be left for 4.20, though. Yet of course churn-wise it would be better to get into final shape right away.

Jan

#11 lore raw

Re: [PATCH for-4.19? 3/6] xen/macros: Introduce BUILD_ERROR()

Quoted 16 lines · Jan Beulich

xen/include/xen/macros.h line 62

Quoted 7 lines · Andrew Cooper
xen/include/xen/macros.h +1 -0
@@ -59,6 +59,8 @@
 #define BUILD_BUG_ON(cond) ((void)BUILD_BUG_ON_ZERO(cond))
 #endif
 
+#define BUILD_ERROR(msg) asm ( ".error \"" msg "\"" )

I think this wants a comment, and one even beyond what is said for BUILD_BUG_ON(). This is primarily to make clear to people when to use which, i.e. I consider it important to mention here that it is intended for code which, in the normal case, we expect to be DCE-d. The nature of the condition used is also a relevant factor, as in some cases BUILD_BUG_ON() simply cannot be used because something that really is compile time constant isn't an integer constant expression. With something to this effect:

Quoted 1 line

Done, thanks.

Quoted 19 lines

I have another question / suggestion, though.

xen/include/xen/self-tests.h line 28

Quoted 12 lines
xen/include/xen/self-tests.h +2 -2
@@ -22,9 +22,9 @@
         typeof(fn(val)) real = fn(val);                                 \
                                                                         \
         if ( !__builtin_constant_p(real) )                              \
-            asm ( ".error \"'" STR(fn(val)) "' not compile-time constant\"" ); \
+            BUILD_ERROR("'" STR(fn(val)) "' not compile-time constant"); \
         else if ( real != res )                                         \
-            asm ( ".error \"Compile time check '" STR(fn(val) == res) "' failed\"" ); \
+            BUILD_ERROR("Compile time check '" STR(fn(val) == res) "' failed"); \
     } while ( 0 )

While right here leaving the condition outside of the macro is perhaps more natural, considering a case where there's just an if() I wonder whether we shouldn't also (only?) have BUILD_ERROR_ON(), better paralleling BUILD_BUG_ON():

Right now none of the uses in this series, nor any of the MISRA conversions away __bad_*() want an _ON() form.

Nothing stops us adding an _ON() form in the future if a reasonable usecase appears, but right now there's no need.

~Andrew

#12 lore raw

Re: [PATCH for-4.19? 3/6] xen/macros: Introduce BUILD_ERROR()

In reply to Andrew Cooper
Quoted 17 lines · Andrew Cooper

... and use it in self-tests.h.

This is intended to replace constructs such as __bitop_bad_size(). It
produces a better diagnostic, and is MISRA-friendly.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Stefano Stabellini <[email protected]>
CC: Julien Grall <[email protected]>
CC: Volodymyr Babchuk <[email protected]>
CC: Bertrand Marquis <[email protected]>
CC: Michal Orzel <[email protected]>
CC: Oleksii Kurochko <[email protected]>

Quoted 3 lines

RFC for-4.19.  This can be used to not introduce new MISRA violations when
adjusting __bitop_bad_size().  It's safe to pull out of this series.

We can consider this patch to be in 4.19 release if necessary Acked will be recieved:

~ Oleksii

Quoted 44 lines

---
 xen/include/xen/macros.h     | 2 ++ xen/include/xen/self-tests.h | 4 ++--

 2 files changed, 4 insertions(+), 2 deletions(-)
xen/include/xen/macros.h +0 -0
index ec89f4654fcf..8441d7e7d66a 100644
@@ -59,6 +59,8 @@
  #define BUILD_BUG_ON(cond) ((void)BUILD_BUG_ON_ZERO(cond))
  #endif

xen/include/xen/macros.h +2 -0
+#define BUILD_ERROR(msg) asm ( ".error \"" msg "\"" )
+

 /* Hide a value from the optimiser. */ #define HIDE(x)                                 \
     ({                                          \

xen/include/xen/self- renamed from xen/include/xen/self-tests.h +0 -0

tests.h
index 42a4cc4d17fe..4bc322b7f2a6 100644

xen/include/xen/self-tests.h +0 -0
@@ -22,9 +22,9 @@

         typeof(fn(val)) real =
fn(val);                                 \

    \
         if ( !__builtin_constant_p(real)
)                              \
-            asm ( ".error \"'" STR(fn(val)) "' not compile-time constant\"" ); \
+            BUILD_ERROR("'" STR(fn(val)) "' not compile-time constant"); \
         else if ( real != res
)                                         \
-            asm ( ".error \"Compile time check '" STR(fn(val) == res) "' failed\"" ); \
+            BUILD_ERROR("Compile time check '" STR(fn(val) == res) "' failed"); \
     } while ( 0 )
 #else
 #define COMPILE_CHECK(fn, val, res)

#13 lore raw

PATCH 4/6 xen/bitops: Introduce for_each_set_bit()

In reply to Andrew Cooper

The prior version (renamed to bitmap_for_each()) was inefficeint when used over a scalar, but this is the more common usage even before accounting for the many opencoded forms.

Introduce a new version which operates on scalars only and does so without spilling them to memory. This in turn requires the addition of a type-generic form of ffs().

Add testing for the new construct alongside the ffs/fls testing.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Stefano Stabellini <[email protected]>
CC: Julien Grall <[email protected]>
CC: Volodymyr Babchuk <[email protected]>
CC: Bertrand Marquis <[email protected]>
CC: Michal Orzel <[email protected]>
CC: Oleksii Kurochko <[email protected]>

The naming of ffs_g() is taken from the new compiler builtins which are using a g suffix to mean type-generic.

---
 xen/common/bitops.c      | 29 +++++++++++++++++++++++++++++
 xen/include/xen/bitops.h | 24 ++++++++++++++++++++++++
 2 files changed, 53 insertions(+)
xen/common/bitops.c +29 -0
index 94a8983af99c..9e532f0d87aa 100644
@@ -84,8 +84,37 @@ static void __init test_fls(void)
     CHECK(fls64, 0x8000000000000001ULL, 64);
 }
 
+static void __init test_for_each_set_bit(void)
+{
+    unsigned int  ui,  ui_res = 0;
+    unsigned long ul,  ul_res = 0;
+    uint64_t      ull, ull_res = 0;
+
+    ui = HIDE(0x80008001U);
+    for_each_set_bit ( i, ui )
+        ui_res |= 1U << i;
+
+    if ( ui != ui_res )
+        panic("for_each_set_bit(uint) expected %#x, got %#x\n", ui, ui_res);
+
+    ul = HIDE(1UL << (BITS_PER_LONG - 1) | 1);
+    for_each_set_bit ( i, ul )
+        ul_res |= 1UL << i;
+
+    if ( ul != ul_res )
+        panic("for_each_set_bit(ulong) expected %#lx, got %#lx\n", ul, ul_res);
+
+    ull = HIDE(0x8000000180000001ULL);
+    for_each_set_bit ( i, ull )
+        ull_res |= 1ULL << i;
+
+    if ( ull != ull_res )
+        panic("for_each_set_bit(uint64) expected %#"PRIx64", got %#"PRIx64"\n", ull, ull_res);
+}
+
 static void __init __constructor test_bitops(void)
 {
     test_ffs();
     test_fls();
+    test_for_each_set_bit();
 }
xen/include/xen/bitops.h +24 -0
index 24de0835b7ab..84ffcb8d57bc 100644
@@ -56,6 +56,16 @@ static always_inline __pure unsigned int ffs64(uint64_t x)
         return !x || (uint32_t)x ? ffs(x) : ffs(x >> 32) + 32;
 }
 
+/*
+ * A type-generic ffs() which picks the appropriate ffs{,l,64}() based on it's
+ * argument.
+ */
+#define ffs_g(x)                                        \
+    sizeof(x) <= sizeof(int) ? ffs(x) :                 \
+        sizeof(x) <= sizeof(long) ? ffsl(x) :           \
+        sizeof(x) <= sizeof(uint64_t) ? ffs64(x) :      \
+        ({ BUILD_ERROR("ffs_g() Bad input type"); 0; })
+
 static always_inline __pure unsigned int fls(unsigned int x)
 {
     if ( __builtin_constant_p(x) )
@@ -92,6 +102,20 @@ static always_inline __pure unsigned int fls64(uint64_t x)
     }
 }
 
+/*
+ * for_each_set_bit() - Iterate over all set bits in a scalar value.
+ *
+ * @iter An iterator name.  Scoped is within the loop only.
+ * @val  A scalar value to iterate over.
+ *
+ * A copy of @val is taken internally.
+ */
+#define for_each_set_bit(iter, val)                     \
+    for ( typeof(val) __v = (val); __v; )               \
+        for ( unsigned int (iter);                      \
+              __v && ((iter) = ffs_g(__v) - 1, true);   \
+              __v &= __v - 1 )
+
 /* --------------------- Please tidy below here --------------------- */
 
 #ifndef find_next_bit
Signature · 1 line
2.39.2
Reviewed-by on v1 4/6
#14 lore raw

Re: [PATCH 4/6] xen/bitops: Introduce for_each_set_bit()

Quoted 11 lines · Andrew Cooper

The prior version (renamed to bitmap_for_each()) was inefficeint when used over a scalar, but this is the more common usage even before accounting for the many opencoded forms.

Introduce a new version which operates on scalars only and does so without spilling them to memory. This in turn requires the addition of a type-generic form of ffs().

Add testing for the new construct alongside the ffs/fls testing.

with two remarks:

Quoted 2 lines

The naming of ffs_g() is taken from the new compiler builtins which are using a g suffix to mean type-generic.

As you say, a g suffix, not a _g one; gcc14 documents __builtin_ffsg(). (Seeing it exists I wonder whether we wouldn't want to use it when available, and only fall back to the macro for older versions.) Any specific reason you use _g?

Quoted 5 lines
xen/include/xen/bitops.h +0 -0
@@ -56,6 +56,16 @@ static always_inline __pure unsigned int ffs64(uint64_t x)
         return !x || (uint32_t)x ? ffs(x) : ffs(x >> 32) + 32;
 }

xen/include/xen/bitops.h static always_inline __pure unsigned int ffs64(uint64_t x) · line 67

Quoted 10 lines
xen/include/xen/bitops.h +9 -0
 
+/*
+ * A type-generic ffs() which picks the appropriate ffs{,l,64}() based on it's
+ * argument.
+ */
+#define ffs_g(x)                                        \
+    sizeof(x) <= sizeof(int) ? ffs(x) :                 \
+        sizeof(x) <= sizeof(long) ? ffsl(x) :           \
+        sizeof(x) <= sizeof(uint64_t) ? ffs64(x) :      \
+        ({ BUILD_ERROR("ffs_g() Bad input type"); 0; })

Related to the patch introducing it: I can see how BUILD_ERROR_ON() may be deemed sub-optimal here. Nevertheless I think we should be able to find some common ground there.

Jan

#15 lore raw

Re: [PATCH 4/6] xen/bitops: Introduce for_each_set_bit()

Quoted 5 lines · Jan Beulich
Quoted 4 lines · Andrew Cooper

The prior version (renamed to bitmap_for_each()) was inefficeint when used over a scalar, but this is the more common usage even before accounting for the many opencoded forms.

Quoted 8 lines
Quoted 7 lines

Introduce a new version which operates on scalars only and does so without spilling them to memory. This in turn requires the addition of a type-generic form of ffs().

Add testing for the new construct alongside the ffs/fls testing.

Thanks.

Quoted 8 lines

with two remarks:

Quoted 2 lines

The naming of ffs_g() is taken from the new compiler builtins which are using a g suffix to mean type-generic.

As you say, a g suffix, not a _g one; gcc14 documents __builtin_ffsg(). (Seeing it exists I wonder whether we wouldn't want to use it when available, and only fall back to the macro for older versions.) Any specific reason you use _g?

Legibility.  It's bad enough with the l() and ll() forms (which get worse with the hweight() series, and I can't find a nice option).

The other option I considered was have ffs() be the generic one, and have ffsi() for the int variant, but now we're in active contradiction with the builtin scheme, rather than merely opting not to use it.

I don't expect this to get much use in practice.  Use of this in regular code mixing ints and longs is almost certainly a bug on behalf of the programmer.

~Andrew

#16 lore raw

Re: [PATCH 4/6] xen/bitops: Introduce for_each_set_bit()

In reply to Andrew Cooper
Quoted 5 lines · Andrew Cooper
xen/include/xen/bitops.h +0 -0
@@ -56,6 +56,16 @@ static always_inline __pure unsigned int ffs64(uint64_t x)
         return !x || (uint32_t)x ? ffs(x) : ffs(x >> 32) + 32;
 }

xen/include/xen/bitops.h static always_inline __pure unsigned int ffs64(uint64_t x) · line 67

Quoted 10 lines
xen/include/xen/bitops.h +9 -0
 
+/*
+ * A type-generic ffs() which picks the appropriate ffs{,l,64}() based on it's
+ * argument.
+ */
+#define ffs_g(x)                                        \
+    sizeof(x) <= sizeof(int) ? ffs(x) :                 \
+        sizeof(x) <= sizeof(long) ? ffsl(x) :           \
+        sizeof(x) <= sizeof(uint64_t) ? ffs64(x) :      \
+        ({ BUILD_ERROR("ffs_g() Bad input type"); 0; })

I guess the lack of parentheses around the entire construct might be the reason for the problems you're seeing, as that ...

Quoted 6 lines
xen/include/xen/bitops.h +2 -0
@@ -92,6 +102,20 @@ static always_inline __pure unsigned int fls64(uint64_t x)
     }
 }
 
+/*
+ * for_each_set_bit() - Iterate over all set bits in a scalar value.

xen/include/xen/bitops.h static always_inline __pure unsigned int fls64(uint64_t x) · line 116

Quoted 10 lines
xen/include/xen/bitops.h +10 -0
+ *
+ * @iter An iterator name.  Scoped is within the loop only.
+ * @val  A scalar value to iterate over.
+ *
+ * A copy of @val is taken internally.
+ */
+#define for_each_set_bit(iter, val)                     \
+    for ( typeof(val) __v = (val); __v; )               \
+        for ( unsigned int (iter);                      \
+              __v && ((iter) = ffs_g(__v) - 1, true);   \

... affects what effect the "- 1" here has.

Jan

#17 lore raw

Re: [PATCH 4/6] xen/bitops: Introduce for_each_set_bit()

Quoted 23 lines · Jan Beulich
Quoted 5 lines · Andrew Cooper
xen/include/xen/bitops.h +0 -0
@@ -56,6 +56,16 @@ static always_inline __pure unsigned int ffs64(uint64_t x)
         return !x || (uint32_t)x ? ffs(x) : ffs(x >> 32) + 32;
 }

xen/include/xen/bitops.h static always_inline __pure unsigned int ffs64(uint64_t x) · line 67

Quoted 10 lines
xen/include/xen/bitops.h +9 -0
 
+/*
+ * A type-generic ffs() which picks the appropriate ffs{,l,64}() based on it's
+ * argument.
+ */
+#define ffs_g(x)                                        \
+    sizeof(x) <= sizeof(int) ? ffs(x) :                 \
+        sizeof(x) <= sizeof(long) ? ffsl(x) :           \
+        sizeof(x) <= sizeof(uint64_t) ? ffs64(x) :      \
+        ({ BUILD_ERROR("ffs_g() Bad input type"); 0; })

I guess the lack of parentheses around the entire construct might be the reason for the problems you're seeing, as that ...

Quoted 4 lines
xen/include/xen/bitops.h +0 -0
@@ -92,6 +102,20 @@ static always_inline __pure unsigned int fls64(uint64_t x)
     }
 }
 
Quoted 13 lines

xen/include/xen/bitops.h static always_inline __pure unsigned int fls64(uint64_t x) · line 116

Quoted 12 lines
xen/include/xen/bitops.h +12 -0
+/*
+ * for_each_set_bit() - Iterate over all set bits in a scalar value.
+ *
+ * @iter An iterator name.  Scoped is within the loop only.
+ * @val  A scalar value to iterate over.
+ *
+ * A copy of @val is taken internally.
+ */
+#define for_each_set_bit(iter, val)                     \
+    for ( typeof(val) __v = (val); __v; )               \
+        for ( unsigned int (iter);                      \
+              __v && ((iter) = ffs_g(__v) - 1, true);   \

... affects what effect the "- 1" here has.

Yes, it was this.

After fixing the bracketing, everything is green.
https://gitlab.com/xen-project/people/andyhhp/xen/-/pipelines/1349243540

~Andrew

#18 lore raw

PATCH 5/6 ARM/vgic: Use for_each_set_bit() in vgic_set_irqs_pending()

In reply to Andrew Cooper

... which is better optimised for scalar values, rather than using the arbitrary-sized bitmap helpers.

For ARM32:

add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-16 (-16)

  Function                                     old     new   delta
  vgic_set_irqs_pending                        284     268     -16

including removing calls to _find_{first,next}_bit_le(), and two stack-spilled words too.

For ARM64:

add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-40 (-40)

  Function                                     old     new   delta
  vgic_set_irqs_pending                        268     228     -40

including removing three calls to find_next_bit().

---
CC: Stefano Stabellini <[email protected]>
CC: Julien Grall <[email protected]>
CC: Volodymyr Babchuk <[email protected]>
CC: Bertrand Marquis <[email protected]>
CC: Michal Orzel <[email protected]>

TODO: These were debug builds, and I need to redo the analysis with release builds. Also extend to the other examples.

---
 xen/arch/arm/vgic.c | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)
xen/arch/arm/vgic.c +1 -3
index 57519e834d78..c060676aee78 100644
@@ -421,15 +421,13 @@ void vgic_enable_irqs(struct vcpu *v, uint32_t r, unsigned int n)
 
 void vgic_set_irqs_pending(struct vcpu *v, uint32_t r, unsigned int rank)
 {
-    const unsigned long mask = r;
-    unsigned int i;
     /* The first rank is always per-vCPU */
     bool private = rank == 0;
 
     /* LPIs will never be set pending via this function */
     ASSERT(!is_lpi(32 * rank + 31));
 
-    bitmap_for_each( i, &mask, 32 )
+    for_each_set_bit ( i, r )
     {
         unsigned int irq = i + 32 * rank;
 
Signature · 1 line
2.39.2
Reviewed-by on v1 5/6
#19 lore raw

Re: [PATCH 5/6] ARM/vgic: Use for_each_set_bit() in vgic_set_irqs_pending()

Quoted 16 lines · Andrew Cooper

... which is better optimised for scalar values, rather than using the arbitrary-sized bitmap helpers.

For ARM32:

add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-16 (-16)

  Function                                     old     new   delta
  vgic_set_irqs_pending                        284     268     -16

including removing calls to _find_{first,next}_bit_le(), and two stack-spilled words too.

For ARM64:

Quoted 7 lines

add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-40 (-40)

  Function                                     old     new   delta
  vgic_set_irqs_pending                        268     228     -40

including removing three calls to find_next_bit().

~Michal

#20 lore raw

PATCH 6/6 x86/xstate: Switch back to for_each_set_bit()

In reply to Andrew Cooper

In all 3 examples, we're iterating over a scaler. No caller can pass the COMPRESSED flag in, so the upper bound of 63, as opposed to 64, doesn't matter.

This alone produces:

add/remove: 0/0 grow/shrink: 0/4 up/down: 0/-161 (-161)
Function old new delta

  compress_xsave_states                         66      58      -8
  xstate_uncompressed_size                     119      71     -48
  xstate_compressed_size                       124      76     -48

recalculate_xstate 347 290 -57

where xstate_{un,}compressed_size() have practically halved in size despite being small before.

The change in compress_xsave_states() is unexpected. The function is almost entirely dead code, and within what remains there's a smaller stack frame. I suspect it's leftovers that the optimiser couldn't fully discard.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Stefano Stabellini <[email protected]>
CC: Julien Grall <[email protected]>
CC: Volodymyr Babchuk <[email protected]>
CC: Bertrand Marquis <[email protected]>
CC: Michal Orzel <[email protected]>
CC: Oleksii Kurochko <[email protected]>

---
 xen/arch/x86/cpu-policy.c | 4 ++--
 xen/arch/x86/xstate.c     | 8 ++++----
 2 files changed, 6 insertions(+), 6 deletions(-)
xen/arch/x86/cpu-policy.c +2 -2
index cd53bac777dc..fa55f6073089 100644
@@ -193,7 +193,7 @@ static void sanitise_featureset(uint32_t *fs)
 static void recalculate_xstate(struct cpu_policy *p)
 {
     uint64_t xstates = XSTATE_FP_SSE;
-    unsigned int i, ecx_mask = 0, Da1 = p->xstate.Da1;
+    unsigned int ecx_mask = 0, Da1 = p->xstate.Da1;
 
     /*
      * The Da1 leaf is the only piece of information preserved in the common
@@ -237,7 +237,7 @@ static void recalculate_xstate(struct cpu_policy *p)
     /* Subleafs 2+ */
     xstates &= ~XSTATE_FP_SSE;
     BUILD_BUG_ON(ARRAY_SIZE(p->xstate.comp) < 63);
-    bitmap_for_each ( i, &xstates, 63 )
+    for_each_set_bit ( i, xstates )
     {
         /*
          * Pass through size (eax) and offset (ebx) directly.  Visbility of
xen/arch/x86/xstate.c +4 -4
index da9053c0a262..88dbfbeafacd 100644
@@ -589,7 +589,7 @@ static bool valid_xcr0(uint64_t xcr0)
 
 unsigned int xstate_uncompressed_size(uint64_t xcr0)
 {
-    unsigned int size = XSTATE_AREA_MIN_SIZE, i;
+    unsigned int size = XSTATE_AREA_MIN_SIZE;
 
     /* Non-XCR0 states don't exist in an uncompressed image. */
     ASSERT((xcr0 & ~X86_XCR0_STATES) == 0);
@@ -606,7 +606,7 @@ unsigned int xstate_uncompressed_size(uint64_t xcr0)
      * with respect their index.
      */
     xcr0 &= ~(X86_XCR0_SSE | X86_XCR0_X87);
-    bitmap_for_each ( i, &xcr0, 63 )
+    for_each_set_bit ( i, xcr0 )
     {
         const struct xstate_component *c = &raw_cpu_policy.xstate.comp[i];
         unsigned int s = c->offset + c->size;
@@ -621,7 +621,7 @@ unsigned int xstate_uncompressed_size(uint64_t xcr0)
 
 unsigned int xstate_compressed_size(uint64_t xstates)
 {
-    unsigned int i, size = XSTATE_AREA_MIN_SIZE;
+    unsigned int size = XSTATE_AREA_MIN_SIZE;
 
     if ( xstates == 0 )
         return 0;
@@ -634,7 +634,7 @@ unsigned int xstate_compressed_size(uint64_t xstates)
      * componenets require aligning to 64 first.
      */
     xstates &= ~(X86_XCR0_SSE | X86_XCR0_X87);
-    bitmap_for_each ( i, &xstates, 63 )
+    for_each_set_bit ( i, xstates )
     {
         const struct xstate_component *c = &raw_cpu_policy.xstate.comp[i];
 
Signature · 1 line
2.39.2
Reviewed-by on v1 6/6
#21 lore raw

Re: [PATCH 6/6] x86/xstate: Switch back to for_each_set_bit()

Quoted 3 lines · Andrew Cooper

In all 3 examples, we're iterating over a scaler. No caller can pass the COMPRESSED flag in, so the upper bound of 63, as opposed to 64, doesn't matter.

Not sure, maybe more a language question (for my education): Is "can" really appropriate here? In recalculate_xstate() we calculate the value ourselves, but in the two other cases the value is incoming to the functions. Architecturally those value should not have bit 63 set, but that's weaker than "can" according to my understanding. I'd be fine with "may", for example.

Quoted 9 lines

This alone produces:

add/remove: 0/0 grow/shrink: 0/4 up/down: 0/-161 (-161)
Function old new delta

  compress_xsave_states                         66      58      -8
  xstate_uncompressed_size                     119      71     -48
  xstate_compressed_size                       124      76     -48

recalculate_xstate 347 290 -57

Quoted 8 lines

where xstate_{un,}compressed_size() have practically halved in size despite being small before.

The change in compress_xsave_states() is unexpected. The function is almost entirely dead code, and within what remains there's a smaller stack frame. I suspect it's leftovers that the optimiser couldn't fully discard.

Other than the above:

Jan

#22 lore raw

Re: [PATCH 6/6] x86/xstate: Switch back to for_each_set_bit()

Quoted 6 lines · Jan Beulich
Quoted 3 lines · Andrew Cooper

In all 3 examples, we're iterating over a scaler. No caller can pass the COMPRESSED flag in, so the upper bound of 63, as opposed to 64, doesn't matter.

Not sure, maybe more a language question (for my education): Is "can" really appropriate here?

It's not the greatest choice, but it's not objectively wrong either.

Quoted 5 lines

In recalculate_xstate() we calculate the
value ourselves, but in the two other cases the value is incoming to the functions. Architecturally those value should not have bit 63 set, but that's weaker than "can" according to my understanding. I'd be fine with "may", for example.

There's an ASSERT() in xstate_uncompressed_size() which covers the property, but most if the justification comes from the fact that the callers pass in values which are really loaded into hardware registers.

But it is certainly more accurate to say that callers don't pass the flag in.

There isn't an ASSERT() in xstate_compressed_size(), but I suppose I could fold this in:

xen/arch/x86/xstate.c +0 -0
index 88dbfbeafacd..f72f14626b7d 100644
@@ -623,6 +623,8 @@ unsigned int xstate_compressed_size(uint64_t xstates)

 {
     unsigned int size = XSTATE_AREA_MIN_SIZE;

+    ASSERT((xstates & ~(X86_XCR0_STATES | X86_XSS_STATES)) == 0); +
     if ( xstates == 0 )
         return 0;

which brings it more in line with xstate_uncompressed_size(), and has a side effect of confirming the absence of the COMPRESSED bit.

Thoughts?

Quoted 12 lines
Quoted 12 lines

This alone produces:

add/remove: 0/0 grow/shrink: 0/4 up/down: 0/-161 (-161)
Function old new delta

  compress_xsave_states                         66      58      -8
  xstate_uncompressed_size                     119      71     -48
  xstate_compressed_size                       124      76     -48

recalculate_xstate 347 290 -57

where xstate_{un,}compressed_size() have practically halved in size despite being small before.

Quoted 7 lines
Quoted 5 lines

The change in compress_xsave_states() is unexpected. The function is almost entirely dead code, and within what remains there's a smaller stack frame. I suspect it's leftovers that the optimiser couldn't fully discard.

Other than the above:

Thanks.

~Andrew

#23 lore raw

Re: [PATCH 6/6] x86/xstate: Switch back to for_each_set_bit()

Quoted 40 lines · Andrew Cooper
Quoted 6 lines · Jan Beulich
Quoted 3 lines · Andrew Cooper

In all 3 examples, we're iterating over a scaler. No caller can pass the COMPRESSED flag in, so the upper bound of 63, as opposed to 64, doesn't matter.

Not sure, maybe more a language question (for my education): Is "can" really appropriate here?

It's not the greatest choice, but it's not objectively wrong either.

Quoted 5 lines

In recalculate_xstate() we calculate the
value ourselves, but in the two other cases the value is incoming to the functions. Architecturally those value should not have bit 63 set, but that's weaker than "can" according to my understanding. I'd be fine with "may", for example.

There's an ASSERT() in xstate_uncompressed_size() which covers the property, but most if the justification comes from the fact that the callers pass in values which are really loaded into hardware registers.

But it is certainly more accurate to say that callers don't pass the flag in.

There isn't an ASSERT() in xstate_compressed_size(), but I suppose I could fold this in:

xen/arch/x86/xstate.c +0 -0
index 88dbfbeafacd..f72f14626b7d 100644
@@ -623,6 +623,8 @@ unsigned int xstate_compressed_size(uint64_t xstates)
  {
      unsigned int size = XSTATE_AREA_MIN_SIZE;


+    ASSERT((xstates & ~(X86_XCR0_STATES | X86_XSS_STATES)) == 0); +
     if ( xstates == 0 )
         return 0;

Quoted 4 lines

which brings it more in line with xstate_uncompressed_size(), and has a side effect of confirming the absence of the COMPRESSED bit.

Thoughts?

Definitely fine with me.

Jan