Skip to contentSkip to conversation

hw/intc/loongarch_extioi: Fix undefined behaviour with bit array APIs

PATCH In review Peter Maydell 3 participants 7 messages Nov 8, 2024 – Nov 18, 2024

lore
Share & tools
lore
#0 lore raw

cover hw/intc/loongarch_extioi: Fix undefined behaviour with bit array APIs

The primary aim of this series is to fix some undefined behaviour in loongarch_extioi which you can see if you run the functional test loongarch64-virt with a QEMU built with the clang undefined-behaviour sanitizer:

include/qemu/bitops.h:41:5: runtime error: store to misaligned address 0x555559745d9c for type 'unsigned long', which requires 8 byte alignment 0x555559745d9c: note: pointer points here
ff ff ff ff 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

              ^
    #0 0x555556fb81c4 in set_bit include/qemu/bitops.h:41:9
    #1 0x555556fb81c4 in extioi_setirq hw/intc/loongarch_extioi.c:65:9
    #2 0x555556fb6e90 in pch_pic_irq_handler hw/intc/loongarch_pch_pic.c:75:5
    #3 0x555556710265 in serial_ioport_write hw/char/serial.c

The underlying cause of this is a mismatch between our bit array APIs in bitops.h and what QEMU devices tend to want. The bit array APIs are historically based on those from the Linux kernel; they work with underlying storage that is an array of 'unsigned long'. This is fine for the kernel, but awkward for QEMU devices because the 'unsigned long' type varies in size between hosts. That means that you can't use it for a data structure that needs to be migrated between devices and it's awkward for devices where the bit array is visible to the guest (e.g. via a set of registers).

In the Arm GICv3 device I worked around this mismatch by implementing a set of local functions which were like the bitops.h APIs but used a uint32_t array. The loongarch_extioi code attempts to use the stock bitops.h functions by casting the uint32_t* to an unsigned long* when calling them. This doesn't work for two reasons:
* the alignment of uint32_t is less than that of unsigned long, so the pointer isn't guaranteed to be sufficiently aligned; this is the cause of the sanitizer UB error
* on a big-endian host we will get the wrong results because the two halves of the unsigned long will be the opposite way round

In this series I fix this by creating new functions set_bit32(), clear_bit32(), etc in bitops.h which are like the existing ones but work with a bit array whose underlying storage is a uint32_t array. Then we can use these both in the GICv3 (where this is just a cleanup) and in loongarch_extioi (where it fixes the bug).

(There are other uses of set_bit() in the loongarch_extioi code but I have left those alone because they define the bitmaps as arrays of unsigned long so they are at least consistent. I do wonder if it's really OK not to migrate those bitmaps, though.)

thanks
-- PMM

Peter Maydell (3):
bitops.h: Define bit operations on 'uint32_t' arrays hw/intc/arm_gicv3: Use bitops.h uint32_t bit array functions hw/intc/loongarch_extioi: Use set_bit32() and clear_bit32() for s->isr

 include/hw/intc/arm_gicv3_common.h |  54 +++------
 include/qemu/bitmap.h              |   8 ++
 include/qemu/bitops.h              | 172 ++++++++++++++++++++++++++++-
 hw/intc/loongarch_extioi.c         |  11 +-
 4 files changed, 194 insertions(+), 51 deletions(-)
Signature · 1 line
2.34.1
#1 lore raw

PATCH 1/3 bitops.h: Define bit operations on 'uint32_t' arrays

Currently bitops.h defines a set of operations that work on arbitrary-length bit arrays. However (largely because they originally came from the Linux kernel) the bit array storage is an array of 'unsigned long'. This is OK for the kernel and even for parts of QEMU where we don't really care about the underlying storage format, but it is not good for devices, where we often want to expose the storage to the guest and so need a type that is not variably-sized between host OSes.

We already have a workaround for this in the GICv3 model:
arm_gicv3_common.h defines equivalents of the bit operations that work on uint32_t. It turns out that we should also be using something similar in hw/intc/loongarch_extioi.c, which currently casts a pointer to a uint32_t array to 'unsigned long *' in extio_setirq(), which is both undefined behaviour and not correct on a big-endian host.

Define equivalents of the set_bit() function family which work with a uint32_t array.

(Cc stable because we're about to provide a bugfix to loongarch_extioi which will depend on this commit.)

---
 include/qemu/bitmap.h |   8 ++
 include/qemu/bitops.h | 172 +++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 177 insertions(+), 3 deletions(-)
include/qemu/bitmap.h +8 -0
index 1cf288445f3..14e51e50a9f 100644
@@ -69,6 +69,14 @@
 #define DECLARE_BITMAP(name,bits)                  \
         unsigned long name[BITS_TO_LONGS(bits)]
 
+/*
+ * This is for use with the bit32 versions of set_bit() etc;
+ * we don't currently support the full range of bitmap operations
+ * on bitmaps backed by an array of uint32_t.
+ */
+#define DECLARE_BITMAP32(name,bits)             \
+        uint32_t name[BITS_TO_U32S(bits)]
+
 #define small_nbits(nbits)                      \
         ((nbits) <= BITS_PER_LONG)
 
include/qemu/bitops.h +169 -3

191 lines not on this page · raw message

Signature · 1 line
2.34.1
#2 lore raw

PATCH 2/3 hw/intc/arm_gicv3: Use bitops.h uint32_t bit array functions

In reply to Peter Maydell

Now we have official uint32_t bit array functions in bitops.h, use them instead of the hand-rolled local versions.

We retain gic_bmp_replace_bit() because bitops doesn't provide that specific functionality.

---
 include/hw/intc/arm_gicv3_common.h | 54 ++++++++----------------------
 1 file changed, 14 insertions(+), 40 deletions(-)
include/hw/intc/arm_gicv3_common.h +14 -40
index cd09bee3bc4..a3d6a0e5077 100644
@@ -51,13 +51,13 @@
 /* Maximum number of list registers (architectural limit) */
 #define GICV3_LR_MAX 16
 
-/* For some distributor fields we want to model the array of 32-bit
+/*
+ * For some distributor fields we want to model the array of 32-bit
  * register values which hold various bitmaps corresponding to enabled,
- * pending, etc bits. These macros and functions facilitate that; the
- * APIs are generally modelled on the generic bitmap.h functions
- * (which are unsuitable here because they use 'unsigned long' as the
- * underlying storage type, which is very awkward when you need to
- * access the data as 32-bit values.)
+ * pending, etc bits. We use the set_bit32() etc family of functions
+ * from bitops.h for this. For a few cases we need to implement some
+ * extra operations.
+ *
  * Each bitmap contains a bit for each interrupt. Although there is
  * space for the PPIs and SGIs, those bits (the first 32) are never
  * used as that state lives in the redistributor. The unused bits are
@@ -65,39 +65,13 @@
  * avoids bugs where we forget to subtract GIC_INTERNAL from an
  * interrupt number.
  */
-#define GICV3_BMP_SIZE DIV_ROUND_UP(GICV3_MAXIRQ, 32)
-
-#define GIC_DECLARE_BITMAP(name) \
-    uint32_t name[GICV3_BMP_SIZE]
-
-#define GIC_BIT_MASK(nr) (1U << ((nr) % 32))
-#define GIC_BIT_WORD(nr) ((nr) / 32)
-
-static inline void gic_bmp_set_bit(int nr, uint32_t *addr)
-{
-    uint32_t mask = GIC_BIT_MASK(nr);
-    uint32_t *p = addr + GIC_BIT_WORD(nr);
-
-    *p |= mask;
-}
-
-static inline void gic_bmp_clear_bit(int nr, uint32_t *addr)
-{
-    uint32_t mask = GIC_BIT_MASK(nr);
-    uint32_t *p = addr + GIC_BIT_WORD(nr);
-
-    *p &= ~mask;
-}
-
-static inline int gic_bmp_test_bit(int nr, const uint32_t *addr)
-{
-    return 1U & (addr[GIC_BIT_WORD(nr)] >> (nr & 31));
-}
+#define GIC_DECLARE_BITMAP(name) DECLARE_BITMAP32(name, GICV3_MAXIRQ)
+#define GICV3_BMP_SIZE BITS_TO_U32S(GICV3_MAXIRQ)
 
 static inline void gic_bmp_replace_bit(int nr, uint32_t *addr, int val)
 {
-    uint32_t mask = GIC_BIT_MASK(nr);
-    uint32_t *p = addr + GIC_BIT_WORD(nr);
+    uint32_t mask = BIT32_MASK(nr);
+    uint32_t *p = addr + BIT32_WORD(nr);
 
     *p &= ~mask;
     *p |= (val & 1U) << (nr % 32);
@@ -106,7 +80,7 @@ static inline void gic_bmp_replace_bit(int nr, uint32_t *addr, int val)
 /* Return a pointer to the 32-bit word containing the specified bit. */
 static inline uint32_t *gic_bmp_ptr32(uint32_t *addr, int nr)
 {
-    return addr + GIC_BIT_WORD(nr);
+    return addr + BIT32_WORD(nr);
 }
 
 typedef struct GICv3State GICv3State;
@@ -301,15 +275,15 @@ struct GICv3State {
 #define GICV3_BITMAP_ACCESSORS(BMP)                                     \
     static inline void gicv3_gicd_##BMP##_set(GICv3State *s, int irq)   \
     {                                                                   \
-        gic_bmp_set_bit(irq, s->BMP);                                   \
+        set_bit32(irq, s->BMP);                                         \
     }                                                                   \
     static inline int gicv3_gicd_##BMP##_test(GICv3State *s, int irq)   \
     {                                                                   \
-        return gic_bmp_test_bit(irq, s->BMP);                           \
+        return test_bit32(irq, s->BMP);                                 \
     }                                                                   \
     static inline void gicv3_gicd_##BMP##_clear(GICv3State *s, int irq) \
     {                                                                   \
-        gic_bmp_clear_bit(irq, s->BMP);                                 \
+        clear_bit32(irq, s->BMP);                                       \
     }                                                                   \
     static inline void gicv3_gicd_##BMP##_replace(GICv3State *s,        \
                                                   int irq, int value)   \
Signature · 1 line
2.34.1
#3 lore raw

PATCH 3/3 hw/intc/loongarch_extioi: Use set_bit32() and clear_bit32() for s->isr

In reply to Peter Maydell

In extioi_setirq() we try to operate on a bit array stored as an array of uint32_t using the set_bit() and clear_bit() functions by casting the pointer to 'unsigned long *'.
This has two problems:
* the alignment of 'uint32_t' is less than that of 'unsigned long' so we pass an insufficiently aligned pointer, which is undefined behaviour
* on big-endian hosts the 64-bit 'unsigned long' will have its two halves the wrong way around, and we will produce incorrect results

The undefined behaviour is shown by the clang undefined-behaviour sanitizer when running the loongarch64-virt functional test:

/mnt/nvmedisk/linaro/qemu-from-laptop/qemu/include/qemu/bitops.h:41:5: runtime error: store to misaligned address 0x555559745d9c for type 'unsigned long', which requires 8 byte alignment 0x555559745d9c: note: pointer points here
ff ff ff ff 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

              ^
    #0 0x555556fb81c4 in set_bit /mnt/nvmedisk/linaro/qemu-from-laptop/qemu/include/qemu/bitops.h:41:9
    #1 0x555556fb81c4 in extioi_setirq /mnt/nvmedisk/linaro/qemu-from-laptop/qemu/build/clang/../../hw/intc/loongarch_extioi.c:65:9
    #2 0x555556fb6e90 in pch_pic_irq_handler /mnt/nvmedisk/linaro/qemu-from-laptop/qemu/build/clang/../../hw/intc/loongarch_pch_pic.c:75:5
    #3 0x555556710265 in serial_ioport_write /mnt/nvmedisk/linaro/qemu-from-laptop/qemu/build/clang/../../hw/char/serial.c

Fix these problems by using set_bit32() and clear_bit32(), which work with bit arrays stored as an array of uint32_t.

Fixes cbff2db1e92f8759 ("hw/intc: Add LoongArch extioi interrupt controller(EIOINTC)")
---
 hw/intc/loongarch_extioi.c | 11 +++--------
 1 file changed, 3 insertions(+), 8 deletions(-)
hw/intc/loongarch_extioi.c +3 -8
index 02dc4e6db3b..97d1af5ccc2 100644
@@ -57,14 +57,9 @@ static void extioi_setirq(void *opaque, int irq, int level)
     LoongArchExtIOI *s = LOONGARCH_EXTIOI(opaque);
     trace_loongarch_extioi_setirq(irq, level);
     if (level) {
-        /*
-         * s->isr should be used in vmstate structure,
-         * but it not support 'unsigned long',
-         * so we have to switch it.
-         */
-        set_bit(irq, (unsigned long *)s->isr);
+        set_bit32(irq, s->isr);
     } else {
-        clear_bit(irq, (unsigned long *)s->isr);
+        clear_bit32(irq, s->isr);
     }
     extioi_update_irq(s, irq, level);
 }
@@ -154,7 +149,7 @@ static inline void extioi_update_sw_coremap(LoongArchExtIOI *s, int irq,
             continue;
         }
 
-        if (notify && test_bit(irq + i, (unsigned long *)s->isr)) {
+        if (notify && test_bit32(irq + i, s->isr)) {
             /*
              * lower irq at old cpu and raise irq at new cpu
              */
Signature · 1 line
2.34.1
Reviewed-by on v1 3/3
#4 lore raw

Re: [PATCH 3/3] hw/intc/loongarch_extioi: Use set_bit32() and clear_bit32() for s->isr

Quoted 56 lines · Peter Maydell

In extioi_setirq() we try to operate on a bit array stored as an array of uint32_t using the set_bit() and clear_bit() functions by casting the pointer to 'unsigned long *'.
This has two problems:
* the alignment of 'uint32_t' is less than that of 'unsigned long' so we pass an insufficiently aligned pointer, which is undefined behaviour
* on big-endian hosts the 64-bit 'unsigned long' will have its two halves the wrong way around, and we will produce incorrect results

The undefined behaviour is shown by the clang undefined-behaviour sanitizer when running the loongarch64-virt functional test:

/mnt/nvmedisk/linaro/qemu-from-laptop/qemu/include/qemu/bitops.h:41:5: runtime error: store to misaligned address 0x555559745d9c for type 'unsigned long', which requires 8 byte alignment 0x555559745d9c: note: pointer points here
ff ff ff ff 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

               ^
     #0 0x555556fb81c4 in set_bit /mnt/nvmedisk/linaro/qemu-from-laptop/qemu/include/qemu/bitops.h:41:9
     #1 0x555556fb81c4 in extioi_setirq /mnt/nvmedisk/linaro/qemu-from-laptop/qemu/build/clang/../../hw/intc/loongarch_extioi.c:65:9
     #2 0x555556fb6e90 in pch_pic_irq_handler /mnt/nvmedisk/linaro/qemu-from-laptop/qemu/build/clang/../../hw/intc/loongarch_pch_pic.c:75:5
     #3 0x555556710265 in serial_ioport_write /mnt/nvmedisk/linaro/qemu-from-laptop/qemu/build/clang/../../hw/char/serial.c

Fix these problems by using set_bit32() and clear_bit32(), which work with bit arrays stored as an array of uint32_t.

Fixes cbff2db1e92f8759 ("hw/intc: Add LoongArch extioi interrupt controller(EIOINTC)")
---
  hw/intc/loongarch_extioi.c | 11 +++--------
  1 file changed, 3 insertions(+), 8 deletions(-)
hw/intc/loongarch_extioi.c +2 -7
index 02dc4e6db3b..97d1af5ccc2 100644
@@ -57,14 +57,9 @@ static void extioi_setirq(void *opaque, int irq, int level)
      LoongArchExtIOI *s = LOONGARCH_EXTIOI(opaque);
      trace_loongarch_extioi_setirq(irq, level);
      if (level) {
-        /*
-         * s->isr should be used in vmstate structure,
-         * but it not support 'unsigned long',
-         * so we have to switch it.
-         */
-        set_bit(irq, (unsigned long *)s->isr);
+        set_bit32(irq, s->isr);
      } else {
-        clear_bit(irq, (unsigned long *)s->isr);
+        clear_bit32(irq, s->isr);
      }
      extioi_update_irq(s, irq, level);
  }

hw/intc/loongarch_extioi.c static inline void extioi_update_sw_coremap(LoongArchExtIOI *s, int irq, · line 155

Quoted 8 lines
hw/intc/loongarch_extioi.c +1 -1
@@ -154,7 +149,7 @@ static inline void extioi_update_sw_coremap(LoongArchExtIOI *s, int irq,
              continue;
          }
 
-        if (notify && test_bit(irq + i, (unsigned long *)s->isr)) {
+        if (notify && test_bit32(irq + i, s->isr)) {
              /*
               * lower irq at old cpu and raise irq at new cpu
               */

Hi Peter,

Thanks for finding and fixing this issue, it looks good to me.

Regards
Bibo Mao

#5 lore raw
In reply to Peter Maydell

Any chance of a review on patches 1 and 2 here? (I guess I should have cc'd qemu-arm on this, since patch 2 is for GICv3.)

thanks
-- PMM

Quoted 60 lines · Peter Maydell

The primary aim of this series is to fix some undefined behaviour in loongarch_extioi which you can see if you run the functional test loongarch64-virt with a QEMU built with the clang undefined-behaviour sanitizer:

include/qemu/bitops.h:41:5: runtime error: store to misaligned address 0x555559745d9c for type 'unsigned long', which requires 8 byte alignment 0x555559745d9c: note: pointer points here
ff ff ff ff 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

              ^
    #0 0x555556fb81c4 in set_bit include/qemu/bitops.h:41:9
    #1 0x555556fb81c4 in extioi_setirq hw/intc/loongarch_extioi.c:65:9
    #2 0x555556fb6e90 in pch_pic_irq_handler hw/intc/loongarch_pch_pic.c:75:5
    #3 0x555556710265 in serial_ioport_write hw/char/serial.c

The underlying cause of this is a mismatch between our bit array APIs in bitops.h and what QEMU devices tend to want. The bit array APIs are historically based on those from the Linux kernel; they work with underlying storage that is an array of 'unsigned long'. This is fine for the kernel, but awkward for QEMU devices because the 'unsigned long' type varies in size between hosts. That means that you can't use it for a data structure that needs to be migrated between devices and it's awkward for devices where the bit array is visible to the guest (e.g. via a set of registers).

In the Arm GICv3 device I worked around this mismatch by implementing a set of local functions which were like the bitops.h APIs but used a uint32_t array. The loongarch_extioi code attempts to use the stock bitops.h functions by casting the uint32_t* to an unsigned long* when calling them. This doesn't work for two reasons:
* the alignment of uint32_t is less than that of unsigned long, so the pointer isn't guaranteed to be sufficiently aligned; this is the cause of the sanitizer UB error
* on a big-endian host we will get the wrong results because the two halves of the unsigned long will be the opposite way round

In this series I fix this by creating new functions set_bit32(), clear_bit32(), etc in bitops.h which are like the existing ones but work with a bit array whose underlying storage is a uint32_t array. Then we can use these both in the GICv3 (where this is just a cleanup) and in loongarch_extioi (where it fixes the bug).

(There are other uses of set_bit() in the loongarch_extioi code but I have left those alone because they define the bitmaps as arrays of unsigned long so they are at least consistent. I do wonder if it's really OK not to migrate those bitmaps, though.)

thanks
-- PMM

Peter Maydell (3):
bitops.h: Define bit operations on 'uint32_t' arrays hw/intc/arm_gicv3: Use bitops.h uint32_t bit array functions hw/intc/loongarch_extioi: Use set_bit32() and clear_bit32() for s->isr

 include/hw/intc/arm_gicv3_common.h |  54 +++------
 include/qemu/bitmap.h              |   8 ++
 include/qemu/bitops.h              | 172 ++++++++++++++++++++++++++++-
 hw/intc/loongarch_extioi.c         |  11 +-
 4 files changed, 194 insertions(+), 51 deletions(-)