Skip to contentSkip to conversation

hw/sd: Improve performance of read/write/erase

PATCH Superseded Christian Speich 2 participants 7 messages Dec 2, 2025 – Feb 1

v2 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

v2 cover hw/sd: Improve performance of read/write/erase

This patch series improves the performance of read/write/erase operations on sdcards.

This is done by increasing the maximum buffer size that is worked on. From 1 byte (master) to 512 bytes (first commit) to larger than 512 (adma commit).

Testing on my system with fio I see the following rough performance values in MiB/s.

read write readwrite
master: 6 6 3/ 3
first commit: 51 43 23/ 23
second commit: 392 180 144/143

Tested on a 2GiB raw image with:
fio --filename=/dev/mmcblk0 --direct=1 --runtime=60 --time_based --bs=128k --rw={mode}

The adma values are somewhat unstable but always >100MiB/s, I'm not sure why but I guess it has something to do with the host side caching.

The third commit fixes the DATA_STAT_AFTER_ERASE bit in SCR and introduces an option to allow to erase blocks to 0x00.

The fourth commit optimizes block erase when erase-blocks-as-zero=true is used, by passing the zeroing request down the to the block device. Erasing 2GiB now takes 0.1s instead of 26s.

---
Changes in v2:
- Properly set DATA_STAT_AFTER_ERASE in SCR
- Add erase-blocks-as-zero option to allow the user to switch between
0x00 and 0xFF for erased blocks.
- Link to v1: https://lore.kernel.org/qemu-devel/[email protected]

---
Christian Speich (4):
hw/sd: Switch from byte-wise to buf+len read/writes hw/sd/sdhci: Don't use bounce buffer for ADMA hw/sd/sdcard: Add erase-blocks-as-zero option. hw/sd/sdcard: Optimize erase blocks as zero.

 hw/sd/core.c       |  16 +--
 hw/sd/sd.c         | 308 +++++++++++++++++++++++++++++++++++++++++------------
 hw/sd/sdhci.c      | 102 ++++++++++--------
 include/hw/sd/sd.h |  13 +--
 4 files changed, 307 insertions(+), 132 deletions(-)

---
base-commit: e7c1e8043a69c5a8efa39d4f9d111f7c72c076e6
change-id: 20250912-sdcard-performance-b4-d908bbb5a004

Best regards,

Signature · 1 line
Christian Speich <[email protected]>
#1 lore raw

PATCH v2 1/4 hw/sd: Switch from byte-wise to buf+len read/writes

Currently, each read/write is eventually split into individual bytes and then later reconstructed into blocks. Byte-wise operation is always bad for performance.

This patch switches from the read_byte/write_byte primitives to read_data/write_data which take a buf + length that should be filled. Byte-wise operation is still supported via sdbus_{read,write}_byte.

As before, arbitrarily sized and aligned data can be passed. The new primitives try to pass the largest possible buffer down to the block layer. This enhances speed and if possible avoids the local bounce buffer.

---
 hw/sd/core.c       |  16 +---
 hw/sd/sd.c         | 257 +++++++++++++++++++++++++++++++++++++++++------------
 include/hw/sd/sd.h |  13 +--
 3 files changed, 209 insertions(+), 77 deletions(-)
hw/sd/core.c +4 -12
index d3c9017445e01c2885a115656ecf23dc336d3b0f..5f05748b9942d5a359d7dee3e0369cf96fc3571b 100644
@@ -113,22 +113,18 @@ void sdbus_write_byte(SDBus *sdbus, uint8_t value)
     if (card) {
         SDCardClass *sc = SDMMC_COMMON_GET_CLASS(card);
 
-        sc->write_byte(card, value);
+        sc->write_data(card, &value, 1);
     }
 }
 
 void sdbus_write_data(SDBus *sdbus, const void *buf, size_t length)
 {
     SDState *card = get_card(sdbus);
-    const uint8_t *data = buf;
 
     if (card) {
         SDCardClass *sc = SDMMC_COMMON_GET_CLASS(card);
 
-        for (size_t i = 0; i < length; i++) {
-            trace_sdbus_write(sdbus_name(sdbus), data[i]);
-            sc->write_byte(card, data[i]);
-        }
+        sc->write_data(card, buf, length);
     }
 }
 
@@ -140,7 +136,7 @@ uint8_t sdbus_read_byte(SDBus *sdbus)
     if (card) {
         SDCardClass *sc = SDMMC_COMMON_GET_CLASS(card);
 
-        value = sc->read_byte(card);
+        sc->read_data(card, &value, 1);
     }
     trace_sdbus_read(sdbus_name(sdbus), value);
 
@@ -150,15 +146,11 @@ uint8_t sdbus_read_byte(SDBus *sdbus)
 void sdbus_read_data(SDBus *sdbus, void *buf, size_t length)
 {
     SDState *card = get_card(sdbus);
-    uint8_t *data = buf;
 
     if (card) {
         SDCardClass *sc = SDMMC_COMMON_GET_CLASS(card);
 
-        for (size_t i = 0; i < length; i++) {
-            data[i] = sc->read_byte(card);
-            trace_sdbus_read(sdbus_name(sdbus), data[i]);
-        }
+        sc->read_data(card, buf, length);
     }
 }
 
hw/sd/sd.c +198 -59

412 lines not on this page · raw message

include/hw/sd/sd.h +7 -6
index 91b5c40a5f893ee41cff21ebbe78d7dfa753d94e..56cd30391bfefd867f4ce97a58de5cc0acd84e97 100644
@@ -107,22 +107,23 @@ struct SDCardClass {
     size_t (*do_command)(SDState *sd, SDRequest *req,
                          uint8_t *resp, size_t respsz);
     /**
-     * Write a byte to a SD card.
+     * Write data to a SD card.
      * @sd: card
-     * @value: byte to write
+     * @value: data to write
      *
      * Write a byte on the data lines of a SD card.
      */
-    void (*write_byte)(SDState *sd, uint8_t value);
+    void (*write_data)(SDState *sd, const void* buf, size_t len);
     /**
-     * Read a byte from a SD card.
+     * Read data from a SD card.
      * @sd: card
      *
-     * Read a byte from the data lines of a SD card.
+     * Read data from the data lines of a SD card. The requestes length is
+     * always filled even if an error occours.
      *
      * Return: byte value read
      */
-    uint8_t (*read_byte)(SDState *sd);
+    void (*read_data)(SDState *sd, void* buf, size_t len);
     bool (*receive_ready)(SDState *sd);
     bool (*data_ready)(SDState *sd);
     void (*set_voltage)(SDState *sd, uint16_t millivolts);
Signature · 1 line
2.43.0
#2 lore raw

PATCH v2 2/4 hw/sd/sdhci: Don't use bounce buffer for ADMA

In reply to Christian Speich

Currently, ADMA will temporarily store data into a local bounce buffer when transferring it. This will produce unneeded copies of the data and limit us to the bounce buffer size for each step.

This patch now maps the requested DMA address and passes this buffer directly to sdbus_{read,write}_data. This allows to pass much larger buffers down to increase the performance. sdbus_{read,write}_data is already able to handle arbitrary length and alignments, so we do not need to ensure this.

---
 hw/sd/sdhci.c | 102 +++++++++++++++++++++++++++++++---------------------------
 1 file changed, 55 insertions(+), 47 deletions(-)
hw/sd/sdhci.c +55 -47
index 3c897e54b721075a3ebd215e027fb73a65ff39b2..94ba23a8da990e69fd59c039e4fdd25b98929dfd 100644
@@ -774,7 +774,7 @@ static void get_adma_description(SDHCIState *s, ADMADescr *dscr)
 
 static void sdhci_do_adma(SDHCIState *s)
 {
-    unsigned int begin, length;
+    unsigned int length;
     const uint16_t block_size = s->blksize & BLOCK_SIZE_MASK;
     const MemTxAttrs attrs = { .memory = true };
     ADMADescr dscr = {};
@@ -816,66 +816,74 @@ static void sdhci_do_adma(SDHCIState *s)
             if (s->trnmod & SDHC_TRNS_READ) {
                 s->prnsts |= SDHC_DOING_READ;
                 while (length) {
-                    if (s->data_count == 0) {
-                        sdbus_read_data(&s->sdbus, s->fifo_buffer, block_size);
-                    }
-                    begin = s->data_count;
-                    if ((length + begin) < block_size) {
-                        s->data_count = length + begin;
-                        length = 0;
-                     } else {
-                        s->data_count = block_size;
-                        length -= block_size - begin;
-                    }
-                    res = dma_memory_write(s->dma_as, dscr.addr,
-                                           &s->fifo_buffer[begin],
-                                           s->data_count - begin,
-                                           attrs);
-                    if (res != MEMTX_OK) {
+                    dma_addr_t dma_len = length;
+
+                    void *buf = dma_memory_map(s->dma_as, dscr.addr, &dma_len,
+                                               DMA_DIRECTION_FROM_DEVICE,
+                                               attrs);
+
+                    if (buf == NULL) {
+                        res = MEMTX_ERROR;
                         break;
+                    } else {
+                        res = MEMTX_OK;
                     }
-                    dscr.addr += s->data_count - begin;
-                    if (s->data_count == block_size) {
-                        s->data_count = 0;
-                        if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {
-                            s->blkcnt--;
-                            if (s->blkcnt == 0) {
-                                break;
-                            }
+
+                    sdbus_read_data(&s->sdbus, buf, dma_len);
+                    length -= dma_len;
+                    dscr.addr += dma_len;
+
+                    dma_memory_unmap(s->dma_as, buf, dma_len,
+                                     DMA_DIRECTION_FROM_DEVICE, dma_len);
+
+                    if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {
+                        size_t transfered = s->data_count + dma_len;
+
+                        s->blkcnt -= transfered / block_size;
+                        s->data_count = transfered % block_size;
+
+                        if (s->blkcnt == 0) {
+                            s->data_count = 0;
+                            break;
                         }
                     }
                 }
             } else {
                 s->prnsts |= SDHC_DOING_WRITE;
                 while (length) {
-                    begin = s->data_count;
-                    if ((length + begin) < block_size) {
-                        s->data_count = length + begin;
-                        length = 0;
-                     } else {
-                        s->data_count = block_size;
-                        length -= block_size - begin;
-                    }
-                    res = dma_memory_read(s->dma_as, dscr.addr,
-                                          &s->fifo_buffer[begin],
-                                          s->data_count - begin,
-                                          attrs);
-                    if (res != MEMTX_OK) {
+                    dma_addr_t dma_len = length;
+
+                    void *buf = dma_memory_map(s->dma_as, dscr.addr, &dma_len,
+                                               DMA_DIRECTION_TO_DEVICE, attrs);
+
+                    if (buf == NULL) {
+                        res = MEMTX_ERROR;
                         break;
+                    } else {
+                        res = MEMTX_OK;
                     }
-                    dscr.addr += s->data_count - begin;
-                    if (s->data_count == block_size) {
-                        sdbus_write_data(&s->sdbus, s->fifo_buffer, block_size);
-                        s->data_count = 0;
-                        if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {
-                            s->blkcnt--;
-                            if (s->blkcnt == 0) {
-                                break;
-                            }
+
+                    sdbus_write_data(&s->sdbus, buf, dma_len);
+                    length -= dma_len;
+                    dscr.addr += dma_len;
+
+                    dma_memory_unmap(s->dma_as, buf, dma_len,
+                                     DMA_DIRECTION_TO_DEVICE, dma_len);
+
+                    if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {
+                        size_t transfered = s->data_count + dma_len;
+
+                        s->blkcnt -= transfered / block_size;
+                        s->data_count = transfered % block_size;
+
+                        if (s->blkcnt == 0) {
+                            s->data_count = 0;
+                            break;
                         }
                     }
                 }
             }
+
             if (res != MEMTX_OK) {
                 s->data_count = 0;
                 if (s->errintstsen & SDHC_EISEN_ADMAERR) {
Signature · 1 line
2.43.0
#3 lore raw

PATCH v2 3/4 hw/sd/sdcard: Add erase-blocks-as-zero option.

In reply to Christian Speich

Currently, erased blocks are filled with 0xFF. However SCR Bit 55 (DATA_STAT_AFTER_ERASE) indicates that an erase produces zeros. One of them is wrong.

This patch does two things.

First it fixes the reporting of DATA_STAT_AFTER_ERASE in SCR to correctly reflect the content of erased blocks. We also increase the Product Revision (REV in CID) to indicate to the guest that DATA_STAT_AFTER_ERASE is now reliable.

Secondly, we introduce a erase-blocks-as-zero option, which allows the user to choose if erased blocks should contain 0xFF or 0x00. The default is still 0xFF to remain compatible with current users.

---
 hw/sd/sd.c | 15 +++++++++++++--
 1 file changed, 13 insertions(+), 2 deletions(-)
hw/sd/sd.c +13 -2
index 23764ed99f36cf39ee7abe02f08e51897c05e718..af7e40faf67c66995b2b615080265dc31da150a6 100644
@@ -139,6 +139,7 @@ struct SDState {
     /* Static properties */
 
     uint8_t spec_version;
+    bool erase_blocks_as_zero;
     uint64_t boot_part_size;
     BlockBackend *blk;
     uint8_t boot_config;
@@ -409,6 +410,9 @@ static void sd_set_scr(SDState *sd)
     sd->scr[0] |= 2;            /* Spec Version 2.00 or Version 3.0X */
     sd->scr[1] = (2 << 4)       /* SDSC Card (Security Version 1.01) */
                  | 0b0101;      /* 1-bit or 4-bit width bus modes */
+    if (!sd->erase_blocks_as_zero) {
+        sd->scr[1] |= (1 << 7); /* DATA_STAT_AFTER_ERASE: Erase produces 0xFF */
+    }
     sd->scr[2] = 0x00;          /* Extended Security is not supported. */
     if (sd->spec_version >= SD_PHY_SPECv3_01_VERS) {
         sd->scr[2] |= 1 << 7;   /* Spec Version 3.0X */
@@ -426,7 +430,7 @@ static void sd_set_scr(SDState *sd)
 #define MID     0xaa
 #define OID     "XY"
 #define PNM     "QEMU!"
-#define PRV     0x01
+#define PRV     0x02
 #define MDT_YR  2006
 #define MDT_MON 2
 
@@ -1115,7 +1119,12 @@ static void sd_erase(SDState *sd)
     sd->erase_end = INVALID_ADDRESS;
     sd->csd[14] |= 0x40;
 
-    memset(sd->data, 0xff, erase_len);
+    if (sd->erase_blocks_as_zero) {
+        memset(sd->data, 0x0, erase_len);
+    } else {
+        memset(sd->data, 0xFF, erase_len);
+    }
+
     for (erase_addr = erase_start; erase_addr <= erase_end;
          erase_addr += erase_len) {
         if (sdsc) {
@@ -2971,6 +2980,8 @@ static void emmc_realize(DeviceState *dev, Error **errp)
 
 static const Property sdmmc_common_properties[] = {
     DEFINE_PROP_DRIVE("drive", SDState, blk),
+    DEFINE_PROP_BOOL("erase-blocks-as-zero", SDState, erase_blocks_as_zero,
+                     false),
 };
 
 static const Property sd_properties[] = {
Signature · 1 line
2.43.0
#4 lore raw

PATCH v2 4/4 hw/sd/sdcard: Optimize erase blocks as zero.

In reply to Christian Speich

When erasing blocks as zero, we can use optimized block functions to achieve this.

These allow us to request a large rage to be zeroed, possible optimizing this operation and freeing disk space for sparsesly stored images.

This only is possible when erase-blocks-as-zero=true is used and can provide a significant performance boost. The case where 0xFF is used during erase is as slow as before.

---
 hw/sd/sd.c | 44 ++++++++++++++++++++++++++++++++++----------
 1 file changed, 34 insertions(+), 10 deletions(-)
hw/sd/sd.c +34 -10
index af7e40faf67c66995b2b615080265dc31da150a6..7fa8e90d36b3b04666de9dfefad5830cb2252b1f 100644
@@ -1083,6 +1083,17 @@ static void sd_blk_write(SDState *sd, uint64_t addr, uint32_t len)
     sd_blk_write_direct(sd, sd->data, addr, len);
 }
 
+/* Requires sd->buf to be filled with 0xFF */
+static void sd_erase_ff(SDState *sd, uint64_t addr, size_t len)
+{
+    int erase_len = 1 << HWBLOCK_SHIFT;
+    uint64_t erase_addr;
+
+    for (erase_addr = addr; erase_addr < addr + len; erase_addr += erase_len) {
+        sd_blk_write(sd, erase_addr, erase_len);
+    }
+}
+
 static void sd_erase(SDState *sd)
 {
     uint64_t erase_start = sd->erase_start;
@@ -1090,7 +1101,6 @@ static void sd_erase(SDState *sd)
     bool sdsc = true;
     uint64_t wpnum;
     uint64_t erase_addr;
-    int erase_len = 1 << HWBLOCK_SHIFT;
 
     trace_sdcard_erase(sd->erase_start, sd->erase_end);
     if (sd->erase_start == INVALID_ADDRESS
@@ -1119,24 +1129,38 @@ static void sd_erase(SDState *sd)
     sd->erase_end = INVALID_ADDRESS;
     sd->csd[14] |= 0x40;
 
-    if (sd->erase_blocks_as_zero) {
-        memset(sd->data, 0x0, erase_len);
-    } else {
-        memset(sd->data, 0xFF, erase_len);
+    if (!sd->erase_blocks_as_zero) {
+        memset(sd->data, 0xFF, 1 << HWBLOCK_SHIFT);
     }
 
-    for (erase_addr = erase_start; erase_addr <= erase_end;
-         erase_addr += erase_len) {
-        if (sdsc) {
-            /* Only SDSC cards support write protect groups */
+    /* Only SDSC cards support write protect groups */
+    if (sdsc) {
+        for (erase_addr = erase_start; erase_addr <= erase_end;
+             erase_addr = ROUND_UP(erase_addr + 1, WPGROUP_SIZE)) {
+            uint64_t wp_group_end = ROUND_UP(erase_addr + 1, WPGROUP_SIZE) - 1;
+            size_t to_erase = MIN(erase_end, wp_group_end) - erase_addr;
+
             wpnum = sd_addr_to_wpnum(erase_addr);
             assert(wpnum < sd->wp_group_bits);
             if (test_bit(wpnum, sd->wp_group_bmap)) {
                 sd->card_status |= WP_ERASE_SKIP;
                 continue;
             }
+
+            if (sd->erase_blocks_as_zero) {
+                blk_pwrite_zeroes(sd->blk, erase_addr + sd_part_offset(sd),
+                                  to_erase, 0);
+            } else {
+                sd_erase_ff(sd, erase_addr, to_erase);
+            }
+        }
+    } else {
+        if (sd->erase_blocks_as_zero) {
+            blk_pwrite_zeroes(sd->blk, erase_start + sd_part_offset(sd),
+                              erase_end - erase_start, 0);
+        } else {
+            sd_erase_ff(sd, erase_start, erase_end - erase_start);
         }
-        sd_blk_write(sd, erase_addr, erase_len);
     }
 }
 
Signature · 1 line
2.43.0
#5 lore raw
In reply to Christian Speich

ping?

I'll rebase it soon as it won't apply cleanly anymore, but I'd like to know if this patch is generally going in an right direction?

Greetings,
Christian

Quoted 57 lines · Christian Speich

This patch series improves the performance of read/write/erase operations on sdcards.

This is done by increasing the maximum buffer size that is worked on.

Quoted 1 line

From 1 byte (master) to 512 bytes (first commit) to larger than 512

(adma commit).

Testing on my system with fio I see the following rough performance values in MiB/s.

read write readwrite
master: 6 6 3/ 3
first commit: 51 43 23/ 23
second commit: 392 180 144/143

Tested on a 2GiB raw image with:
fio --filename=/dev/mmcblk0 --direct=1 --runtime=60 --time_based --bs=128k --rw={mode}

The adma values are somewhat unstable but always >100MiB/s, I'm not sure why but I guess it has something to do with the host side caching.

The third commit fixes the DATA_STAT_AFTER_ERASE bit in SCR and introduces an option to allow to erase blocks to 0x00.

The fourth commit optimizes block erase when erase-blocks-as-zero=true is used, by passing the zeroing request down the to the block device. Erasing 2GiB now takes 0.1s instead of 26s.

---
Changes in v2:
- Properly set DATA_STAT_AFTER_ERASE in SCR
- Add erase-blocks-as-zero option to allow the user to switch between
0x00 and 0xFF for erased blocks.
- Link to v1: https://lore.kernel.org/qemu-devel/[email protected]

---
Christian Speich (4):
hw/sd: Switch from byte-wise to buf+len read/writes hw/sd/sdhci: Don't use bounce buffer for ADMA hw/sd/sdcard: Add erase-blocks-as-zero option. hw/sd/sdcard: Optimize erase blocks as zero.

 hw/sd/core.c       |  16 +--
 hw/sd/sd.c         | 308 +++++++++++++++++++++++++++++++++++++++++------------
 hw/sd/sdhci.c      | 102 ++++++++++--------
 include/hw/sd/sd.h |  13 +--
 4 files changed, 307 insertions(+), 132 deletions(-)

---
base-commit: e7c1e8043a69c5a8efa39d4f9d111f7c72c076e6
change-id: 20250912-sdcard-performance-b4-d908bbb5a004

Best regards,

Signature · 1 line
Christian Speich <[email protected]>
#6 lore raw

Hi Christian,

Quoted 4 lines · Christian Speich

ping?

I'll rebase it soon as it won't apply cleanly anymore, but I'd like to know if this patch is generally going in an right direction?

Sorry for the delay. I'm happy with your series. The only issue I have is patch #1 is too big, making it hard to review withing missing something. If you can split it, better, otherwise just send rebased v3 and I'll try to split myself during review, and post as v4 for you do double check before merging.

Thanks for this speedup improvement!

Phil.

Quoted 3 lines

Greetings,
Christian