Skip to contentSkip to conversation

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

PATCH Superseded Bernhard Beschow 2 participants 15 messages Oct 7 – Nov 3

lore
Share & tools
lore
#0 lore raw

v5 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 (commit 1-3) 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 fifth commit fixes the DATA_STAT_AFTER_ERASE bit in SCR and introduces an option to allow to erase blocks to 0x00.

The sixth 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.

I'm picking up this series with the changes indicated in v5 below. Please let me know how I could improve attribution to Christian in case I missed something.

The last two patches are new and are small cleanups.

---
Changes in v5:
- Rebase onto master
- Split patch "hw/sd/sd: Use multi-byte/block writes for block path" into three (first three patches)
- Use sd_blk_{read,write} with additional parameter directly rather than having sd_blk_{read,write}_bounce_buffer
- Drive limits and write protect groups are preserved to be checked on block boundaries only since these checks are redundant in case the SD host transfers one byte at a time.
- WP_VIOLATION is only raised once the first protected block shall be written, rather than immediately at the beginning of a multiple block write which starts with allowed blocks.
- An off-by-one error has been fixed in the same case where one bye too less had been written if a write protected block had been detected.
- There are only two rather than three code paths each handling the multiple block optimization.

Changes in v4:
- Rebase onto master, no changes needed.
- Renames:
- sd_blk_{read,write} -> sd_blk_{read,write}_bounce_buffer
- sd_blk_{read,write}_direct -> sd_blk_{read,write}
- to_erase -> erase_len
- Extract erase logic into sd_blk_erase helper
- Enable erase-blocks-as-zero by default. Add compat for 11.0 and below
to keep it disabled.
- Add cleanup commit to update trace events.
- Link to v3: https://lore.kernel.org/qemu-devel/[email protected]

Changes in v3:
- Rebase onto master, updating read/write path for newly added RBMP
- Split up commit 1 into multiple commits
- change interface to allow "short" read/writes that are continued
by the core later by calling again
- Link to v2: https://lore.kernel.org/qemu-devel/[email protected]

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]

Bernhard Beschow (5):
hw/sd/sd: Transfer up to one block in case of multi-block commands hw/sd/sd: Add buffer argument to sd_blk_{read,write} hw/sd/sd: Use multi-byte/block writes for block path hw/sd/sd: Retype state attribute to SDCardStates hw/sd/sd: Remove unneeded forward declaration

Christian Speich (3):
hw/sd/sdhci: Don't use bounce buffer for ADMA
hw/sd/sd: Add erase-blocks-as-zero option.
hw/sd/sd: Optimize erase blocks as zero.

 hw/core/machine.c |   1 +
 hw/sd/sd.c        | 230 ++++++++++++++++++++++++++++++++++------------
 hw/sd/sdhci.c     | 102 ++++++++++----------
 3 files changed, 225 insertions(+), 108 deletions(-)
Signature · 1 line
2.56.0
#1 lore raw

PATCH v5 1/8 hw/sd/sd: Transfer up to one block in case of multi-block commands

Commit eff58d3d9681 ("hw/sd/sd: Allow multi-byte read/write for generic paths") allowed for transferring multiple bytes at once at the choice of the SD host implementation. Take advantage of that in the multi-block commands CMD18 and CMD25 by transferring up to one block rather than one byte at a time.

Note that the drive limits and write-protect groups were already checked at the block boundary only. In between, bytes were accumulated up to one block and the block was trustfully transferred once full. This patch optimizes the accumulation process to fill a whole block at once if possible, so no further checks are required.

This patch is based on https://lore.kernel.org/qemu-devel/[email protected]/

---
 hw/sd/sd.c | 27 ++++++++++-----------------
 1 file changed, 10 insertions(+), 17 deletions(-)
hw/sd/sd.c +10 -17
index b1b3b1226a..759db66e3d 100644
@@ -2663,7 +2663,6 @@ static size_t sd_write_data(SDState *sd, const void *buf, size_t length)
 {
     unsigned int partition_access;
     int i;
-    const uint8_t *value = buf;
 
     if (!sd->blk || !blk_is_inserted(sd->blk)) {
         return length;
@@ -2695,12 +2694,6 @@ static size_t sd_write_data(SDState *sd, const void *buf, size_t length)
         break;
 
     case 25:  /* CMD25:  WRITE_MULTIPLE_BLOCK */
-        /*
-         * Only read one byte at a time. We will be called again with the
-         * remaining.
-         */
-        length = 1;
-
         if (sd->data_offset == 0) {
             /* Start of the block - let's check the address is valid */
             if (!address_in_range(sd, "WRITE_MULTIPLE_BLOCK",
@@ -2714,7 +2707,11 @@ static size_t sd_write_data(SDState *sd, const void *buf, size_t length)
                 }
             }
         }
-        sd->data[sd->data_offset++] = value[0];
+
+        length = MIN(sd->blk_len - sd->data_offset, length);
+        memcpy(sd->data + sd->data_offset, buf, length);
+        sd->data_offset += length;
+
         if (sd->data_offset >= sd->blk_len) {
             /* TODO: Check CRC before committing */
             sd->state = sd_programming_state;
@@ -2811,7 +2808,6 @@ static size_t sd_read_data(SDState *sd, void *buf, size_t length)
     const uint8_t dummy_byte = 0x00;
     unsigned int partition_access;
     uint32_t io_len;
-    uint8_t *value = buf;
 
     if (!sd->blk || !blk_is_inserted(sd->blk)) {
         memset(buf, dummy_byte, length);
@@ -2851,16 +2847,10 @@ static size_t sd_read_data(SDState *sd, void *buf, size_t length)
         break;
 
     case 18:  /* CMD18:  READ_MULTIPLE_BLOCK */
-        /*
-         * We will only read one byte at a time. We will be called again with
-         * the remaining buffer.
-         */
-        length = 1;
-
         if (sd->data_offset == 0) {
             if (!address_in_range(sd, "READ_MULTIPLE_BLOCK",
                                   sd->data_start, io_len)) {
-                *value = dummy_byte;
+                memset(buf, dummy_byte, length);
                 return length;
             }
             partition_access = sd->ext_csd[EXT_CSD_PART_CONFIG]
@@ -2871,7 +2861,10 @@ static size_t sd_read_data(SDState *sd, void *buf, size_t length)
                 sd_blk_read(sd, sd->data_start, io_len);
             }
         }
-        *value = sd->data[sd->data_offset++];
+
+        length = MIN(io_len - sd->data_offset, length);
+        memcpy(buf, sd->data + sd->data_offset, length);
+        sd->data_offset += length;
 
         if (sd->data_offset >= io_len) {
             sd->data_start += io_len;
Signature · 1 line
2.56.0
#2 lore raw

PATCH v5 2/8 hw/sd/sd: Add buffer argument to sd_blk_{read,write}

In reply to Bernhard Beschow

The next patch offers to skip the s->data bounce buffer for CMD18 and CMD25. Prepare for that by adding a buffer parameter.

Rather than introducing two new wrapper functions, as in the inspiring commit, the additional argument is added at all call sites. This reduces the number of helper functions and matches existing code where multiple sd->* arguments are passed to sd_blk_{read,write}.

This patch is inspired by: https://lore.kernel.org/qemu-devel/[email protected]/

---
 hw/sd/sd.c | 20 +++++++++++---------
 1 file changed, 11 insertions(+), 9 deletions(-)
hw/sd/sd.c +11 -9
index 759db66e3d..bccb839ce6 100644
@@ -1113,20 +1113,22 @@ static const VMStateDescription sd_vmstate = {
     },
 };
 
-static void sd_blk_read(SDState *sd, uint64_t addr, uint32_t len)
+static void sd_blk_read(SDState *sd, void* buf, uint64_t addr,
+                        uint32_t len)
 {
     trace_sdcard_read_block(addr, len);
     addr += sd_part_offset(sd);
-    if (!sd->blk || blk_pread(sd->blk, addr, len, sd->data, 0) < 0) {
+    if (!sd->blk || blk_pread(sd->blk, addr, len, buf, 0) < 0) {
         fprintf(stderr, "sd_blk_read: read error on host side\n");
     }
 }
 
-static void sd_blk_write(SDState *sd, uint64_t addr, uint32_t len)
+static void sd_blk_write(SDState *sd, const void *buf, uint64_t addr,
+                         uint32_t len)
 {
     trace_sdcard_write_block(addr, len);
     addr += sd_part_offset(sd);
-    if (!sd->blk || blk_pwrite(sd->blk, addr, len, sd->data, 0) < 0) {
+    if (!sd->blk || blk_pwrite(sd->blk, addr, len, buf, 0) < 0) {
         fprintf(stderr, "sd_blk_write: write error on host side\n");
     }
 }
@@ -1364,7 +1366,7 @@ static void sd_erase(SDState *sd)
                 continue;
             }
         }
-        sd_blk_write(sd, erase_addr, erase_len);
+        sd_blk_write(sd, sd->data, erase_addr, erase_len);
     }
 }
 
@@ -1985,7 +1987,7 @@ static sd_rsp_type_t sd_cmd_READ_SINGLE_BLOCK(SDState *sd, SDRequest req)
         return sd_r1;
     }
 
-    sd_blk_read(sd, addr, sd->blk_len);
+    sd_blk_read(sd, sd->data, addr, sd->blk_len);
     return sd_cmd_to_sendingdata(sd, req, addr, NULL, sd->blk_len);
 }
 
@@ -2685,7 +2687,7 @@ static size_t sd_write_data(SDState *sd, const void *buf, size_t length)
         if (sd_generic_write_data(sd, buf, &length)) {
             /* TODO: Check CRC before committing */
             sd->state = sd_programming_state;
-            sd_blk_write(sd, sd->data_start, sd->data_offset);
+            sd_blk_write(sd, sd->data, sd->data_start, sd->data_offset);
             sd->blk_written ++;
             sd->csd[14] |= 0x40;
             /* Bzzzzzzztt .... Operation complete.  */
@@ -2720,7 +2722,7 @@ static size_t sd_write_data(SDState *sd, const void *buf, size_t length)
             if (partition_access == EXT_CSD_PART_CONFIG_ACC_RPMB) {
                 emmc_rpmb_blk_write(sd, sd->data_start, sd->data_offset);
             } else {
-                sd_blk_write(sd, sd->data_start, sd->data_offset);
+                sd_blk_write(sd, sd->data, sd->data_start, sd->data_offset);
             }
             sd->blk_written++;
             sd->data_start += sd->blk_len;
@@ -2858,7 +2860,7 @@ static size_t sd_read_data(SDState *sd, void *buf, size_t length)
             if (partition_access == EXT_CSD_PART_CONFIG_ACC_RPMB) {
                 emmc_rpmb_blk_read(sd, sd->data_start, io_len);
             } else {
-                sd_blk_read(sd, sd->data_start, io_len);
+                sd_blk_read(sd, sd->data, sd->data_start, io_len);
             }
         }
 
Signature · 1 line
2.56.0
Reviewed-by on v5 2/8
#3 lore raw

Re: [PATCH v5 2/8] hw/sd/sd: Add buffer argument to sd_blk_{read,write}

Quoted 8 lines · Bernhard Beschow

The next patch offers to skip the s->data bounce buffer for CMD18 and CMD25. Prepare for that by adding a buffer parameter.

Rather than introducing two new wrapper functions, as in the inspiring commit, the additional argument is added at all call sites. This reduces the number of helper functions and matches existing code where multiple sd->* arguments are passed to sd_blk_{read,write}.

Quoted 7 lines

This patch is inspired by: https://lore.kernel.org/qemu-devel/[email protected]/

---
  hw/sd/sd.c | 20 +++++++++++---------
  1 file changed, 11 insertions(+), 9 deletions(-)
#4 lore raw

PATCH v5 3/8 hw/sd/sd: Use multi-byte/block writes for block path

In reply to Bernhard Beschow

When writing/reading blocks via WRITE/READ_MULTIPLE_BLOCK we try to directly pass this request down to the block layer. This can only be done for properly sized and aligned accesses, other access still use a bounce buffer but still benefit from copying as much data in one memcpy as possible.

RPMB is limited to the slow path using a bounce buffer.

Original patch has been split into multiple ones to help review.

Further changes:
* Drive limits and write protect groups are preserved to be checked on block boundaries only since these checks are redundant in case the SD host transfers one byte at a time.
* WP_VIOLATION is only raised once the first protected block shall be written, rather than immediately at the beginning of a multiple block write which starts with allowed blocks.
* An off-by-one error has been fixed in the same case where one bye too less had been written if a write protected block had been detected.
* There are only two rather than three code paths each handling the multiple block optimization.

---
 hw/sd/sd.c | 147 +++++++++++++++++++++++++++++++++++++++++------------
 1 file changed, 114 insertions(+), 33 deletions(-)
hw/sd/sd.c +114 -33
index bccb839ce6..6e2bb8ff2d 100644
@@ -2702,36 +2702,84 @@ static size_t sd_write_data(SDState *sd, const void *buf, size_t length)
                                   sd->data_start, sd->blk_len)) {
                 break;
             }
+
+            /* Limit writing data to our device size */
+            length = MIN(sd->size - sd->data_start, length);
+
             if (sd->size <= SDSC_MAX_CAPACITY) {
                 if (sd_wp_addr(sd, sd->data_start)) {
                     sd->card_status |= WP_VIOLATION;
                     break;
                 }
+
+                /*
+                 * Check if any covered address violates WP. If so, limit our
+                 * write up to the allowed address.
+                 */
+                for (uint64_t addr = ROUND_UP(sd->data_start + 1, WPGROUP_SIZE);
+                     addr < sd->data_start + length;
+                     addr += WPGROUP_SIZE) {
+                    if (sd_wp_addr(sd, addr)) {
+                        length = addr - sd->data_start;
+                        break;
+                    }
+                }
             }
         }
 
-        length = MIN(sd->blk_len - sd->data_offset, length);
-        memcpy(sd->data + sd->data_offset, buf, length);
-        sd->data_offset += length;
+        partition_access = sd->ext_csd[EXT_CSD_PART_CONFIG]
+                            & EXT_CSD_PART_CONFIG_ACC_MASK;
 
-        if (sd->data_offset >= sd->blk_len) {
-            /* TODO: Check CRC before committing */
-            sd->state = sd_programming_state;
-            partition_access = sd->ext_csd[EXT_CSD_PART_CONFIG]
-                    & EXT_CSD_PART_CONFIG_ACC_MASK;
-            if (partition_access == EXT_CSD_PART_CONFIG_ACC_RPMB) {
-                emmc_rpmb_blk_write(sd, sd->data_start, sd->data_offset);
-            } else {
-                sd_blk_write(sd, sd->data, sd->data_start, sd->data_offset);
+        if (length < sd->blk_len || sd->data_offset > 0
+            || partition_access == EXT_CSD_PART_CONFIG_ACC_RPMB) {
+            /* Partial write or RPMB (single block only for now) */
+            length = MIN(sd->blk_len - sd->data_offset, length);
+
+            memcpy(sd->data + sd->data_offset, buf, length);
+            sd->data_offset += length;
+
+            if (sd->data_offset >= sd->blk_len) {
+                sd->state = sd_programming_state;
+                if (partition_access == EXT_CSD_PART_CONFIG_ACC_RPMB) {
+                    emmc_rpmb_blk_write(sd, sd->data_start, sd->data_offset);
+                } else {
+                    sd_blk_write(sd, sd->data, sd->data_start, sd->data_offset);
+                }
+                sd->blk_written++;
+                sd->data_start += sd->blk_len;
+                sd->data_offset = 0;
+                sd->csd[14] |= 0x40;
+
+                /* Bzzzzzzztt .... Operation complete.  */
+                if (sd->multi_blk_cnt != 0) {
+                    if (--sd->multi_blk_cnt == 0) {
+                        /* Stop! */
+                        sd->state = sd_transfer_state;
+                        break;
+                    }
+                }
+
+                sd->state = sd_receivingdata_state;
             }
-            sd->blk_written++;
-            sd->data_start += sd->blk_len;
-            sd->data_offset = 0;
+        } else {
+            /* Write multiple of block sizes */
+            length = QEMU_ALIGN_DOWN(length, sd->blk_len);
+
+            /* For limited writes, only write the requested block count. */
+            if (sd->multi_blk_cnt != 0) {
+                length = MIN(length, sd->multi_blk_cnt * sd->blk_len);
+            }
+
+            sd->state = sd_programming_state;
+            sd_blk_write(sd, buf, sd->data_start, length);
+            sd->blk_written += length / sd->blk_len;
+            sd->data_start += length;
             sd->csd[14] |= 0x40;
 
-            /* Bzzzzzzztt .... Operation complete.  */
             if (sd->multi_blk_cnt != 0) {
-                if (--sd->multi_blk_cnt == 0) {
+                sd->multi_blk_cnt -= length / sd->blk_len;
+
+                if (sd->multi_blk_cnt == 0) {
                     /* Stop! */
                     sd->state = sd_transfer_state;
                     break;
@@ -2740,6 +2788,7 @@ static size_t sd_write_data(SDState *sd, const void *buf, size_t length)
 
             sd->state = sd_receivingdata_state;
         }
+
         break;
 
     case 26:  /* CMD26:  PROGRAM_CID */
@@ -2855,28 +2904,60 @@ static size_t sd_read_data(SDState *sd, void *buf, size_t length)
                 memset(buf, dummy_byte, length);
                 return length;
             }
-            partition_access = sd->ext_csd[EXT_CSD_PART_CONFIG]
-                    & EXT_CSD_PART_CONFIG_ACC_MASK;
-            if (partition_access == EXT_CSD_PART_CONFIG_ACC_RPMB) {
-                emmc_rpmb_blk_read(sd, sd->data_start, io_len);
-            } else {
-                sd_blk_read(sd, sd->data, sd->data_start, io_len);
-            }
         }
 
-        length = MIN(io_len - sd->data_offset, length);
-        memcpy(buf, sd->data + sd->data_offset, length);
-        sd->data_offset += length;
+        /* Limit reading data to our device size */
+        length = MIN(sd->size - sd->data_start, length);
+
+        partition_access = sd->ext_csd[EXT_CSD_PART_CONFIG]
+                & EXT_CSD_PART_CONFIG_ACC_MASK;
+
+        if (length < io_len || sd->data_offset > 0
+            || partition_access == EXT_CSD_PART_CONFIG_ACC_RPMB) {
+            /* Partial read or RPMB (single block only for now) */
+            if (sd->data_offset == 0) {
+                /* Fill the buffer */
+                if (partition_access == EXT_CSD_PART_CONFIG_ACC_RPMB) {
+                    emmc_rpmb_blk_read(sd, sd->data_start, io_len);
+                } else {
+                    sd_blk_read(sd, sd->data, sd->data_start, io_len);
+                }
+            }
+
+            length = MIN(io_len - sd->data_offset, length);
+            memcpy(buf, sd->data + sd->data_offset, length);
+            sd->data_offset += length;
 
-        if (sd->data_offset >= io_len) {
-            sd->data_start += io_len;
-            sd->data_offset = 0;
+            if (sd->data_offset >= io_len) {
+                sd->data_start += io_len;
+                sd->data_offset = 0;
 
+                if (sd->multi_blk_cnt != 0) {
+                    if (--sd->multi_blk_cnt == 0) {
+                        /* Stop! */
+                        sd->state = sd_transfer_state;
+                        break;
+                    }
+                }
+            }
+        } else {
+            /* Read multiple of block sizes */
+            length = QEMU_ALIGN_DOWN(length, io_len);
+
+            /* For limited reads, only read the requested block count. */
             if (sd->multi_blk_cnt != 0) {
-                if (--sd->multi_blk_cnt == 0) {
-                    /* Stop! */
+                length = MIN(length, sd->multi_blk_cnt * io_len);
+            }
+
+            sd_blk_read(sd, buf, sd->data_start, length);
+
+            sd->data_start += length;
+
+            if (sd->multi_blk_cnt != 0) {
+                sd->multi_blk_cnt -= length / io_len;
+
+                if (sd->multi_blk_cnt == 0) {
                     sd->state = sd_transfer_state;
-                    break;
                 }
             }
         }
Signature · 1 line
2.56.0
#5 lore raw

PATCH v5 4/8 hw/sd/sdhci: Don't use bounce buffer for ADMA

In reply to Bernhard Beschow

From: Christian Speich <[email protected]>

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 bd74c60f72..2f52b252ce 100644
@@ -852,7 +852,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 = {};
@@ -894,66 +894,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.56.0
#6 lore raw

PATCH v5 5/8 hw/sd/sd: Add erase-blocks-as-zero option.

In reply to Bernhard Beschow

From: Christian Speich <[email protected]>

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.

Move global compat property
{ "sdmmc-common", "erase-blocks-as-zero", "false" }
to 11.1 section.

---
 hw/core/machine.c |  1 +
 hw/sd/sd.c        | 15 +++++++++++++--
 2 files changed, 14 insertions(+), 2 deletions(-)
hw/core/machine.c +1 -0
index d9ac4b419a..7b0be16444 100644
@@ -41,6 +41,7 @@
 #include "hw/arm/smmuv3.h"
 
 GlobalProperty hw_compat_11_1[] = {
+    { "sdmmc-common", "erase-blocks-as-zero", "false" },
     { "sysbus-ehci-usb", "x-migrate-fetch-addr-64bit", "off" },
     { "pci-ehci-usb", "x-migrate-fetch-addr-64bit", "off" },
 };
hw/sd/sd.c +13 -2
index 6e2bb8ff2d..c40097924c 100644
@@ -162,6 +162,7 @@ struct SDState {
     /* Static properties */
 
     uint8_t spec_version;
+    bool erase_blocks_as_zero;
     uint64_t boot_part_size;
     uint64_t rpmb_part_size;
     BlockBackend *blk;
@@ -440,6 +441,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 */
@@ -457,7 +461,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
 
@@ -1354,7 +1358,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) {
@@ -3281,6 +3290,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,
+                     true),
 };
 
 static const Property sd_properties[] = {
Signature · 1 line
2.56.0
#7 lore raw

PATCH v5 6/8 hw/sd/sd: Optimize erase blocks as zero.

In reply to Bernhard Beschow

From: Christian Speich <[email protected]>

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 | 43 +++++++++++++++++++++++++++++++++----------
 1 file changed, 33 insertions(+), 10 deletions(-)
hw/sd/sd.c +33 -10
index c40097924c..03c51b0291 100644
@@ -1322,6 +1322,26 @@ exit:
     trace_sdcard_rpmb_write_block(req, lduw_be_p(&sd->rpmb.result.result));
 }
 
+/* Requires sd->data 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, sd->data, erase_addr, erase_len);
+    }
+}
+
+static void sd_blk_erase(SDState *sd, uint64_t addr, size_t len)
+{
+    if (sd->erase_blocks_as_zero) {
+        blk_pwrite_zeroes(sd->blk, addr + sd_part_offset(sd), len, 0);
+    } else {
+        sd_erase_ff(sd, addr, len);
+    }
+}
+
 static void sd_erase(SDState *sd)
 {
     uint64_t erase_start = sd->erase_start;
@@ -1329,7 +1349,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
@@ -1358,24 +1377,28 @@ 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 erase_len = 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;
             }
+
+            sd_blk_erase(sd, erase_addr, erase_len);
         }
-        sd_blk_write(sd, sd->data, erase_addr, erase_len);
+    } else {
+        sd_blk_erase(sd, erase_start, erase_end - erase_start);
     }
 }
 
Signature · 1 line
2.56.0
#8 lore raw

PATCH v5 7/8 hw/sd/sd: Retype state attribute to SDCardStates

In reply to Bernhard Beschow

An enumeration is checked by the compiler, so is more robust. It also helps auto-completion, so is more ergonomic. Change the state attribute to be of type enum SDCardStates rather than int32_t to achieve both.

---
 hw/sd/sd.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
hw/sd/sd.c +1 -1
index 03c51b0291..6295e7a942 100644
@@ -172,7 +172,7 @@ struct SDState {
 
     /* Runtime changeables */
 
-    int32_t state;    /* current card state, one of SDCardStates */
+    enum SDCardStates state; /* current card state */
     uint32_t vhs;
     bool wp_switch;
     unsigned long *wp_group_bmap;
Signature · 1 line
2.56.0
Reviewed-by on v5 7/8
#9 lore raw

Re: [PATCH v5 7/8] hw/sd/sd: Retype state attribute to SDCardStates

Quoted 8 lines · Bernhard Beschow

An enumeration is checked by the compiler, so is more robust. It also helps auto-completion, so is more ergonomic. Change the state attribute to be of type enum SDCardStates rather than int32_t to achieve both.

---
  hw/sd/sd.c | 2 +-
  1 file changed, 1 insertion(+), 1 deletion(-)
#10 lore raw

PATCH v5 8/8 hw/sd/sd: Remove unneeded forward declaration

In reply to Bernhard Beschow

No need for a forward declaration of sd_realize() since it is only used after its definition.

---
 hw/sd/sd.c | 2 --
 1 file changed, 2 deletions(-)
hw/sd/sd.c +0 -2
index 6295e7a942..e6452226bc 100644
@@ -209,8 +209,6 @@ struct SDState {
     char *preset_auth_key;
 };
 
-static void sd_realize(DeviceState *dev, Error **errp);
-
 static const SDProto sd_proto_spi;
 static const SDProto sd_proto_emmc;
 
Signature · 1 line
2.56.0
Reviewed-by on v5 8/8
#11 lore raw

Re: [PATCH v5 8/8] hw/sd/sd: Remove unneeded forward declaration

Quoted 13 lines · Bernhard Beschow

No need for a forward declaration of sd_realize() since it is only used after its definition.

---
  hw/sd/sd.c | 2 --
  1 file changed, 2 deletions(-)
hw/sd/sd.c +0 -0
index 6295e7a942..e6452226bc 100644

hw/sd/sd.c struct SDState { · line 212

Quoted 4 lines
hw/sd/sd.c +0 -1
@@ -209,8 +209,6 @@ struct SDState {
      char *preset_auth_key;
  };
 
-static void sd_realize(DeviceState *dev, Error **errp);

Indeed, since commit bda21477f523 ("hw/sd: Remove unused legacy functions, stop killing mammoths").

#12 lore raw
In reply to Bernhard Beschow

Am 6. Oktober 2026 09:44:39 UTC schrieb Bernhard Beschow <[email protected]>:

Quoted 96 lines

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 (commit 1-3) 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 fifth commit fixes the DATA_STAT_AFTER_ERASE bit in SCR and

introduces an option to allow to erase blocks to 0x00.

The sixth 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.

I'm picking up this series with the changes indicated in v5 below. Please let

me know how I could improve attribution to Christian in case I missed something.

The last two patches are new and are small cleanups.

---

Changes in v5:

- Rebase onto master

- Split patch "hw/sd/sd: Use multi-byte/block writes for block path" into three

(first three patches)

- Use sd_blk_{read,write} with additional parameter directly rather than having

sd_blk_{read,write}_bounce_buffer

- Drive limits and write protect groups are preserved to be checked on block

boundaries only since these checks are redundant in case the SD host

transfers one byte at a time.

- WP_VIOLATION is only raised once the first protected block shall be written,

rather than immediately at the beginning of a multiple block write which

starts with allowed blocks.

Quoted 8 lines

- An off-by-one error has been fixed in the same case where one bye too less

had been written if a write protected block had been detected.

- There are only two rather than three code paths each handling the multiple

block optimization.

Ping

Quoted 91 lines

Changes in v4:

- Rebase onto master, no changes needed.

- Renames:

- sd_blk_{read,write} -> sd_blk_{read,write}_bounce_buffer

- sd_blk_{read,write}_direct -> sd_blk_{read,write}

- to_erase -> erase_len

- Extract erase logic into sd_blk_erase helper

- Enable erase-blocks-as-zero by default. Add compat for 11.0 and below

to keep it disabled.

- Add cleanup commit to update trace events.

- Link to v3: https://lore.kernel.org/qemu-devel/[email protected]

Changes in v3:

- Rebase onto master, updating read/write path for newly added RBMP

- Split up commit 1 into multiple commits

- change interface to allow "short" read/writes that are continued

by the core later by calling again

- Link to v2: https://lore.kernel.org/qemu-devel/[email protected]

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]

Bernhard Beschow (5):

hw/sd/sd: Transfer up to one block in case of multi-block commands

hw/sd/sd: Add buffer argument to sd_blk_{read,write}

hw/sd/sd: Use multi-byte/block writes for block path

hw/sd/sd: Retype state attribute to SDCardStates

hw/sd/sd: Remove unneeded forward declaration

Christian Speich (3):

hw/sd/sdhci: Don't use bounce buffer for ADMA

hw/sd/sd: Add erase-blocks-as-zero option.

hw/sd/sd: Optimize erase blocks as zero.

hw/core/machine.c | 1 +

hw/sd/sd.c | 230 ++++++++++++++++++++++++++++++++++------------

hw/sd/sdhci.c | 102 ++++++++++----------

3 files changed, 225 insertions(+), 108 deletions(-)

-- >
2.56.0

#13 lore raw

Am 16. Oktober 2026 14:28:18 UTC schrieb Bernhard Beschow <[email protected]>:

Quoted 101 lines

Am 6. Oktober 2026 09:44:39 UTC schrieb Bernhard Beschow <[email protected]>:

Quoted 98 lines

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 (commit 1-3) 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 fifth commit fixes the DATA_STAT_AFTER_ERASE bit in SCR and

introduces an option to allow to erase blocks to 0x00.

The sixth 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.

I'm picking up this series with the changes indicated in v5 below. Please let

me know how I could improve attribution to Christian in case I missed something.

The last two patches are new and are small cleanups.

---

Changes in v5:

- Rebase onto master

- Split patch "hw/sd/sd: Use multi-byte/block writes for block path" into three

(first three patches)

- Use sd_blk_{read,write} with additional parameter directly rather than having

sd_blk_{read,write}_bounce_buffer

- Drive limits and write protect groups are preserved to be checked on block

boundaries only since these checks are redundant in case the SD host

transfers one byte at a time.

- WP_VIOLATION is only raised once the first protected block shall be written,

rather than immediately at the beginning of a multiple block write which

starts with allowed blocks.

- An off-by-one error has been fixed in the same case where one bye too less

Quoted 8 lines
Quoted 6 lines

had been written if a write protected block had been detected.

- There are only two rather than three code paths each handling the multiple

block optimization.

Ping

Ping^2

Quoted 92 lines
Quoted 92 lines

Changes in v4:

- Rebase onto master, no changes needed.

- Renames:

- sd_blk_{read,write} -> sd_blk_{read,write}_bounce_buffer

- sd_blk_{read,write}_direct -> sd_blk_{read,write}

- to_erase -> erase_len

- Extract erase logic into sd_blk_erase helper

- Enable erase-blocks-as-zero by default. Add compat for 11.0 and below

to keep it disabled.

- Add cleanup commit to update trace events.

- Link to v3: https://lore.kernel.org/qemu-devel/[email protected]

Changes in v3:

- Rebase onto master, updating read/write path for newly added RBMP

- Split up commit 1 into multiple commits

- change interface to allow "short" read/writes that are continued

by the core later by calling again

- Link to v2: https://lore.kernel.org/qemu-devel/[email protected]

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]

Bernhard Beschow (5):

hw/sd/sd: Transfer up to one block in case of multi-block commands

hw/sd/sd: Add buffer argument to sd_blk_{read,write}

hw/sd/sd: Use multi-byte/block writes for block path

hw/sd/sd: Retype state attribute to SDCardStates

hw/sd/sd: Remove unneeded forward declaration

Christian Speich (3):

hw/sd/sdhci: Don't use bounce buffer for ADMA

hw/sd/sd: Add erase-blocks-as-zero option.

hw/sd/sd: Optimize erase blocks as zero.

hw/core/machine.c | 1 +

hw/sd/sd.c | 230 ++++++++++++++++++++++++++++++++++------------

hw/sd/sdhci.c | 102 ++++++++++----------

3 files changed, 225 insertions(+), 108 deletions(-)

-- >
2.56.0

#14 lore raw
In reply to Bernhard Beschow
Quoted 28 lines · Bernhard Beschow

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 (commit 1-3) 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 fifth commit fixes the DATA_STAT_AFTER_ERASE bit in SCR and introduces an option to allow to erase blocks to 0x00.

The sixth 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.

Quoted 6 lines

I'm picking up this series with the changes indicated in v5 below. Please let me know how I could improve attribution to Christian in case I missed something.

The last two patches are new and are small cleanups.

Thanks Bernhard for respinning. I also had a local branch where I was working the fixes needed for v4; I'm taking your v5 and will respin as v6.

Quoted 18 lines

---
Changes in v5:
- Rebase onto master
- Split patch "hw/sd/sd: Use multi-byte/block writes for block path" into three (first three patches)
- Use sd_blk_{read,write} with additional parameter directly rather than having sd_blk_{read,write}_bounce_buffer
- Drive limits and write protect groups are preserved to be checked on block boundaries only since these checks are redundant in case the SD host transfers one byte at a time.
- WP_VIOLATION is only raised once the first protected block shall be written, rather than immediately at the beginning of a multiple block write which starts with allowed blocks.
- An off-by-one error has been fixed in the same case where one bye too less had been written if a write protected block had been detected.
- There are only two rather than three code paths each handling the multiple block optimization.