Skip to contentSkip to conversation

Add full zoned storage emulation to the qcow2 driver

PATCH Superseded Sam Li 3 participants 16 messages Jun 23 – Jul 8 Block layer

v12 of 14 Superseded Latest is v14 →

lore
Share & tools
lore

Sam Li

author
#0 lore raw

v12 cover Add full zoned storage emulation to the qcow2 driver

This patch series add a new extension - zoned format - to the qcow2 driver, allowing full zoned storage emulation on a qcow2 image file. A user can attach such an image to a guest and have it appear as a host-managed zoned block device.

The zoned format is opt-in through a new qcow2 header extension that pins the zone geometry. Behind the extension is a dedicated zoned metadata region that stores one 8-byte write pointer (WP) per zone. The extension is gated by an incompatible bit, so an older qcow2 implementation cannot accidentally open the image.

Each write pointer is routed through the write pointer cache, a Qcow2Cache object. The write pointer cache is written to disk after the qcow2 metadata is written, thus guaranteeing that the write pointer is updated after the corresponding data is written.

Zone states are in memory. Read-only and offline states are device-internal events, which are not modelled in qcow2 emulation for simplicity. The other zone states (closed, empty, full) can be inferred from write poiner values, presistent across QEMU reboots. The open states are kept in memory using open zone lists.

To create a qcow2 file with the zoned format:

    qemu-img create -f qcow2 zbc.qcow2 \
        -o size=768M \
        -o zone.size=64M \
        -o zone.capacity=64M \
        -o zone.conventional_zones=0 \
        -o zone.max_append_bytes=4096 \
        -o zone.max_open_zones=6 \
        -o zone.max_active_zones=8 \
        -o zone.mode=host-managed

Then attach it to a guest via the QEMU command line:

    -blockdev node-name=drive1,driver=qcow2,\
              file.driver=file,file.filename=zbc.qcow2 \
    -device virtio-blk-pci,drive=drive1 \

v11->v12:
- validate the zoned header extension before allocating any zoned metadata
- fix the zoned locking discipline: hold the qcow2 state lock (s->lock) across all zone-state list updates [Stefan]
- reject, instead of aborting on an assertion, a write that reaches the open-zone limit while every open zone is explicitly open
- fix reduced-capacity (zone_capacity < zone_size) handling:
* transition a zone to FULL when the write pointer reaches the zone capacity
* report the zone capacity, not the zone size, in zone_report
- return -EIO rather than -EINVAL for zone write-rule violations
- use int64_t for the zoned-metadata cluster offset and zone_size to avoid truncation on large images
- simplify qcow2_cache_set_dependency() [Stefan]
- virtio-blk: read the zone size through a new blk_get_zone_size() [Stefan]
- docs/QAPI: clarify the max_open_zones / max_active_zones / max_append_bytes descriptions; use warn_report() for recoverable zoned configuration values in qcow2_check_zone_options() [Niklas, Stefan]
- iotests: add qcow2 check updates (303, qcow2-encryption) [Stefan]
- coding style: function opening braces, DEBUG_EXT format specifier

v10->v11:
- add write ordering through write pointer cache [Stefan]
- add new test cases to iotests for zone append write
- add zoned image info to qemu-img --info
- move virtio-blk cross-zone-boundary merge fix into its own patch [Stefan]
- fix specs and docs:
* document bit 59 conventional-zone marker in qcow2.rst [Stefan]
* spell out write ordering for crash consistency [Stefan]
* QAPI: rephrase comments, bump version [Markus]
- fix review comments [Stefan]

v9->v10:
- add cross-boundary constraint for merging writes on zoned devices
- extract call from assert() to fix image creation crash

v8->v9:
- fix compilation err after modifying types

v7->v8:
- sets default values for zoned img confurations [Markus, Damien]
- changes the type of zone_size, zone_capacity from uint32_t to uint64_t [Stefan]
- fix docs [Stefan]
- modify append writes to increase concurrency [Damien, Stefan]
- use tailqueue to track active zones [Stefan]
- fix undefined behavior of ranges_overlap()
- fix the iotest of case 2(1)

v6->v7:
- modify zone resource managemant (style) [Damien]
- fix accessing list with negative index err
- add some tests for zrm in iotests
- address review comments [Markus]

v5->v6:
- fix docs and specs [Eric, Markus, Stefan]
- add general sanity checks for zoned device configurations while creation and opening [Eric]
- fix LRU when implicitly open a zone for a long time [Stefan]

v4->v5:
- add incompatible bit for zoned format [Eric]
- fix and manage zone resources via LRU [Damien]
- renaming functions and fields, spec changes [Markus, Damien]
- add closed zone list
- make qemu iotests for zoned device consecutive [Stefan]

v3->v4:
- use QLIST for implicit, explicit open zones management [Stefan]
- keep zone states in memory and drop state bits in wp metadata structure [Damien, Stefan]
- change zone resource management and iotests accordingly
- add tracing for number of implicit zones
- address review comments [Stefan, Markus]:
* documentation, config, style

v2->v3:
- drop zoned_profile option [Klaus]
- reformat doc comments of qcow2 [Markus]
- add input validation and checks for zoned information [Stefan]
- code style: format, comments, documentation, naming [Stefan]
- add tracing function for wp tracking [Stefan]
- reconstruct io path in check_zone_resources [Stefan]

v1->v2:
- add more tests to qemu-io zoned commands
- make zone append change state to full when wp reaches end
- add documentation to qcow2 zoned extension header
- address review comments (Stefan):
* fix zoned_mata allocation size
* use bitwise or than addition
* fix wp index overflow and locking
* cleanups: comments, naming

Sam Li (5):
docs/qcow2: add the zoned format feature
qcow2: add configurations for zoned format extension
virtio-blk: do not merge writes across a zone boundary
qcow2: add zoned emulation capability
iotests: test the zoned format feature for qcow2 file

 block/block-backend.c                         |   11 +
 block/file-posix.c                            |    2 +-
 block/qcow2-cache.c                           |   11 +-
 block/qcow2-refcount.c                        |    7 +
 block/qcow2.c                                 | 1585 ++++++++++++++++-
 block/qcow2.h                                 |   83 +-
 block/trace-events                            |    2 +
 docs/interop/qcow2.rst                        |  120 +-
 docs/system/qemu-block-drivers.rst.inc        |   47 +
 hw/block/virtio-blk.c                         |   22 +-
 include/block/block_int-common.h              |   15 +-
 include/system/block-backend-io.h             |    1 +
 qapi/block-core.json                          |   91 +-
 tests/qemu-iotests/082.out                    |  126 ++
 tests/qemu-iotests/303.out                    |    4 +-
 tests/qemu-iotests/tests/qcow2-encryption.out |    4 +-
 tests/qemu-iotests/tests/zoned-qcow2          |  209 +++
 tests/qemu-iotests/tests/zoned-qcow2.out      |  191 ++
 18 files changed, 2484 insertions(+), 47 deletions(-)
 create mode 100755 tests/qemu-iotests/tests/zoned-qcow2
 create mode 100644 tests/qemu-iotests/tests/zoned-qcow2.out
Signature · 1 line
2.53.0
author
#1 lore raw

PATCH v12 1/5 docs/qcow2: add the zoned format feature

Add the specs for the zoned format feature of the qcow2 driver. The qcow2 file then can emulate real zoned devices, either passed through by virtio-blk device or NVMe ZNS drive to the guest given zoned information.

---
 docs/system/qemu-block-drivers.rst.inc | 47 ++++++++++++++++++++++++++
 1 file changed, 47 insertions(+)
docs/system/qemu-block-drivers.rst.inc +47 -0
index 675daa72f9..1af968c4fd 100644
@@ -172,6 +172,53 @@ This section describes each format and the options that are supported for it.
     filename`` to check if the NOCOW flag is set or not (Capital 'C' is
     NOCOW flag).
 
+  .. option:: zone.mode
+    If this is set to ``host-managed``, the image is an emulated zoned
+    block device. This option is only valid to emulated zoned device files.
+
+  .. option:: zone.size
+
+    The size of a zone in bytes. The device is divided into zones of this
+    size with the exception of the last zone, which may be smaller.
+    Defaults to ``256 MiB``.
+
+  .. option:: zone.capacity
+
+    The initial capacity value, in bytes, for all zones. The capacity must
+    be less than or equal to zone size. If the last zone is smaller, then
+    its capacity is capped. Defaults to ``zone.size``.
+
+    The zone capacity is per zone and may be different between zones in real
+    devices. QCow2 sets all zones to the same capacity.
+
+  .. option:: zone.conventional_zones
+
+    The number of conventional zones of the zoned device. Defaults to ``0``
+    (all zones are sequential-write-required).
+
+  .. option:: zone.max_active_zones
+
+    The limit of the zones with implicit open, explicit open or closed state.
+
+    The max active zones must be less or equal to the number of SWR
+    (sequential write required) zones of the device. Defaults to ``0``,
+    meaning no limit.
+
+  .. option:: zone.max_open_zones
+
+    The maximal allowed open zones. The max open zones must not be larger than
+    the max active zones. Defaults to ``zone.max_active_zones`` if that is
+    set, otherwise ``0`` (no limit).
+
+    If the limits of open zones or active zones are equal to the number of
+    SWR zones, then it is the same as having no limits.
+
+  .. option:: zone.max_append_bytes
+
+    The number of bytes in a zone append request that can be issued to the
+    device. It must be 512-byte aligned and less than the zone capacity.
+    Defaults to ``64 KiB``.
+
 .. program:: image-formats
 .. option:: qed
 
Signature · 1 line
2.53.0
author
#2 lore raw

PATCH v12 2/5 qcow2: add configurations for zoned format extension

In reply to Sam Li

To configure the zoned format feature on the qcow2 driver, it requires settings as: the device size, zone model, zone size, zone capacity, number of conventional zones, limits on zone resources (max append bytes, max open zones, and max_active_zones).

To create a qcow2 image with zoned format feature, use command like this:
qemu-img create -f qcow2 zbc.qcow2 -o size=768M \
-o zone.size=64M -o zone.capacity=64M -o zone.conventional_zones=0 \
-o zone.max_append_bytes=4096 -o zone.max_open_zones=6 \
-o zone.max_active_zones=8 -o zone.mode=host-managed

---
 block/file-posix.c               |   2 +-
 block/qcow2.c                    | 335 ++++++++++++++++++++++++++++++-
 block/qcow2.h                    |  83 +++++++-
 docs/interop/qcow2.rst           | 120 ++++++++++-
 include/block/block_int-common.h |  15 +-
 qapi/block-core.json             |  91 ++++++++-
 tests/qemu-iotests/082.out       | 126 ++++++++++++
 7 files changed, 763 insertions(+), 9 deletions(-)
block/file-posix.c +1 -1
index 3c985da94f..ddb159c58b 100644
@@ -3600,7 +3600,7 @@ raw_co_zone_append(BlockDriverState *bs,
 
     if (*offset & zone_size_mask) {
         error_report("sector offset %" PRId64 " is not aligned to zone size "
-                     "%" PRId32 "", *offset / 512, bs->bl.zone_size / 512);
+                     "%" PRId64 "", *offset / 512, bs->bl.zone_size / 512);
         return -EINVAL;
     }
 
block/qcow2.c +332 -3

437 lines not on this page · raw message

block/qcow2.h +82 -1

117 lines not on this page · raw message

docs/interop/qcow2.rst +119 -1

138 lines not on this page · raw message

include/block/block_int-common.h +14 -1
index 147c08155f..349876bc65 100644
@@ -57,6 +57,13 @@
 #define BLOCK_OPT_COMPRESSION_TYPE  "compression_type"
 #define BLOCK_OPT_EXTL2             "extended_l2"
 #define BLOCK_OPT_KEEP_DATA_FILE    "keep_data_file"
+#define BLOCK_OPT_ZONE_MODEL        "zone.mode"
+#define BLOCK_OPT_ZONE_SIZE         "zone.size"
+#define BLOCK_OPT_ZONE_CAPACITY     "zone.capacity"
+#define BLOCK_OPT_CONVENTIONAL_ZONES    "zone.conventional_zones"
+#define BLOCK_OPT_MAX_APPEND_BYTES      "zone.max_append_bytes"
+#define BLOCK_OPT_MAX_ACTIVE_ZONES      "zone.max_active_zones"
+#define BLOCK_OPT_MAX_OPEN_ZONES        "zone.max_open_zones"
 
 #define BLOCK_PROBE_BUF_SIZE        512
 
@@ -901,7 +908,13 @@ typedef struct BlockLimits {
     BlockZoneModel zoned;
 
     /* zone size expressed in bytes */
-    uint32_t zone_size;
+    uint64_t zone_size;
+
+    /*
+     * The number of usable logical blocks within the zone, expressed
+     * in bytes. A zone capacity is smaller or equal to the zone size.
+     */
+    uint64_t zone_capacity;
 
     /* total number of zones */
     uint32_t nr_zones;
qapi/block-core.json +89 -2

121 lines not on this page · raw message

tests/qemu-iotests/082.out +126 -0

234 lines not on this page · raw message

Signature · 1 line
2.53.0
#3 lore raw

Re: [PATCH v12 2/5] qcow2: add configurations for zoned format extension

Quoted 29 lines · Sam Li

To configure the zoned format feature on the qcow2 driver, it requires settings as: the device size, zone model, zone size, zone capacity, number of conventional zones, limits on zone resources (max append bytes, max open zones, and max_active_zones).

To create a qcow2 image with zoned format feature, use command like this:
qemu-img create -f qcow2 zbc.qcow2 -o size=768M \

(quoted diff) +0 -3
-o zone.size=64M -o zone.capacity=64M -o zone.conventional_zones=0 \
-o zone.max_append_bytes=4096 -o zone.max_open_zones=6 \
-o zone.max_active_zones=8 -o zone.mode=host-managed
---
 block/file-posix.c               |   2 +-
 block/qcow2.c                    | 335 ++++++++++++++++++++++++++++++-
 block/qcow2.h                    |  83 +++++++-
 docs/interop/qcow2.rst           | 120 ++++++++++-
 include/block/block_int-common.h |  15 +-
 qapi/block-core.json             |  91 ++++++++-
 tests/qemu-iotests/082.out       | 126 ++++++++++++
 7 files changed, 763 insertions(+), 9 deletions(-)
block/file-posix.c +0 -0
index 3c985da94f..ddb159c58b 100644

block/file-posix.c raw_co_zone_append(BlockDriverState *bs, · line 3605

Quoted 7 lines
block/file-posix.c +1 -1
@@ -3600,7 +3600,7 @@ raw_co_zone_append(BlockDriverState *bs,
 
     if (*offset & zone_size_mask) {
         error_report("sector offset %" PRId64 " is not aligned to zone size "
-                     "%" PRId32 "", *offset / 512, bs->bl.zone_size / 512);
+                     "%" PRId64 "", *offset / 512, bs->bl.zone_size / 512);
         return -EINVAL;
     }

I think it would be easier if this change, together with:

block/file-posix.c typedef struct BlockLimits { · line 911

Quoted 6 lines
block/file-posix.c +1 -1
@@ -901,7 +908,13 @@ typedef struct BlockLimits {
     BlockZoneModel zoned;
 
     /* zone size expressed in bytes */
-    uint32_t zone_size;
+    uint64_t zone_size;

was in a separate prep patch earlier in this series.

While I understand the logic behind increasing the zone_size to uint64_t (i.e. to match "struct blk_zone" struct member "len" (representing zone size) in Linux include/uapi/linux/blkzoned.h), this seems like an independent change that should be done to the QEMU block layer, that does not really have anything to do with adding qcow2 zoned support.

Kind regards,
Niklas

author
#4 lore raw

PATCH v12 3/5 virtio-blk: do not merge writes across a zone boundary

In reply to Sam Li

virtio_blk_submit_multireq() fuses adjacent in-zone writes into a single request. On a zoned backend, a merged zone append request that straddles a zone boundary is rejected by the device because each write must stay within a single zone.

Add a bail condition to the merge coalescer: if combining the candidate request into the current batch would cross a zone boundary, flush the current batch and start a new one.

---
 block/block-backend.c             | 11 +++++++++++
 hw/block/virtio-blk.c             | 22 +++++++++++++++++++++-
 include/system/block-backend-io.h |  1 +
 3 files changed, 33 insertions(+), 1 deletion(-)
block/block-backend.c +11 -0
index 37ba7e9fc4..049e70ddcb 100644
@@ -2326,6 +2326,17 @@ uint32_t blk_get_request_alignment(BlockBackend *blk)
     return bs ? bs->bl.request_alignment : BDRV_SECTOR_SIZE;
 }
 
+/*
+ * Returns the zone size in bytes for a zoned backend, or 0 if @blk does
+ * not present zoned geometry.
+ */
+uint64_t blk_get_zone_size(BlockBackend *blk)
+{
+    BlockDriverState *bs = blk_bs(blk);
+    IO_CODE();
+    return bs ? bs->bl.zone_size : 0;
+}
+
 /* Returns the optimal write zeroes alignment, in bytes; guaranteed nonzero */
 uint32_t blk_get_pwrite_zeroes_alignment(BlockBackend *blk)
 {
hw/block/virtio-blk.c +21 -1
index 6b92066aff..39750fa1c0 100644
@@ -294,6 +294,9 @@ static void virtio_blk_submit_multireq(VirtIOBlock *s, MultiReqBuffer *mrb)
     int i = 0, start = 0, num_reqs = 0, niov = 0, nb_sectors = 0;
     uint32_t max_transfer;
     int64_t sector_num = 0;
+    uint64_t zone_size = blk_get_zone_size(s->blk);
+    bool zone_cross;
+    int64_t zone_sector, end_sector;
 
     if (mrb->num_reqs == 1) {
         submit_requests(s, mrb, 0, 1, -1);
@@ -309,17 +312,34 @@ static void virtio_blk_submit_multireq(VirtIOBlock *s, MultiReqBuffer *mrb)
     for (i = 0; i < mrb->num_reqs; i++) {
         VirtIOBlockReq *req = mrb->reqs[i];
         if (num_reqs > 0) {
+            zone_cross = false;
+
+            /*
+             * On zoned backends, a single backend write must not span a zone
+             * boundary. Bail out of merging if combining req into the current
+             * batch would straddle a zone.
+             */
+            if (zone_size > 0) {
+                zone_sector = zone_size / BDRV_SECTOR_SIZE;
+                end_sector = req->sector_num
+                                + req->qiov.size / BDRV_SECTOR_SIZE - 1;
+                zone_cross = (sector_num / zone_sector) !=
+                             (end_sector / zone_sector);
+            }
+
             /*
              * NOTE: We cannot merge the requests in below situations:
              * 1. requests are not sequential
              * 2. merge would exceed maximum number of IOVs
              * 3. merge would exceed maximum transfer length of backend device
+             * 4. merge would cross a zone boundary on a zoned backend
              */
             if (sector_num + nb_sectors != req->sector_num ||
                 niov > blk_get_max_iov(s->blk) - req->qiov.niov ||
                 req->qiov.size > max_transfer ||
                 nb_sectors > (max_transfer -
-                              req->qiov.size) / BDRV_SECTOR_SIZE) {
+                              req->qiov.size) / BDRV_SECTOR_SIZE ||
+                zone_cross) {
                 submit_requests(s, mrb, start, num_reqs, niov);
                 num_reqs = 0;
             }
include/system/block-backend-io.h +1 -0
index fd84723d9d..78d410b8df 100644
@@ -121,6 +121,7 @@ uint32_t blk_get_request_alignment(BlockBackend *blk);
 uint32_t blk_get_pwrite_zeroes_alignment(BlockBackend *blk);
 uint32_t blk_get_max_transfer(BlockBackend *blk);
 uint64_t blk_get_max_hw_transfer(BlockBackend *blk);
+uint64_t blk_get_zone_size(BlockBackend *blk);
 
 int coroutine_fn blk_co_copy_range(BlockBackend *blk_in, int64_t off_in,
                                    BlockBackend *blk_out, int64_t off_out,
Signature · 1 line
2.53.0
Reviewed-by on v12 3/5
#5 lore raw

Re: [PATCH v12 3/5] virtio-blk: do not merge writes across a zone boundary

Quoted 9 lines · Sam Li

virtio_blk_submit_multireq() fuses adjacent in-zone writes into a single request. On a zoned backend, a merged zone append request that straddles a zone boundary is rejected by the device because each write must stay within a single zone.

Add a bail condition to the merge coalescer: if combining the candidate request into the current batch would cross a zone boundary, flush the current batch and start a new one.

Quoted 6 lines
---
 block/block-backend.c             | 11 +++++++++++
 hw/block/virtio-blk.c             | 22 +++++++++++++++++++++-
 include/system/block-backend-io.h |  1 +
 3 files changed, 33 insertions(+), 1 deletion(-)
#6 lore raw

Re: [PATCH v12 3/5] virtio-blk: do not merge writes across a zone boundary

In reply to Sam Li

Hello Sam,

Quoted 24 lines · Sam Li

virtio_blk_submit_multireq() fuses adjacent in-zone writes into a single request. On a zoned backend, a merged zone append request that straddles a zone boundary is rejected by the device because each write must stay within a single zone.

Add a bail condition to the merge coalescer: if combining the candidate request into the current batch would cross a zone boundary, flush the current batch and start a new one.

---
 block/block-backend.c             | 11 +++++++++++
 hw/block/virtio-blk.c             | 22 +++++++++++++++++++++-
 include/system/block-backend-io.h |  1 +
 3 files changed, 33 insertions(+), 1 deletion(-)
block/block-backend.c +0 -0
index 37ba7e9fc4..049e70ddcb 100644
@@ -2326,6 +2326,17 @@ uint32_t blk_get_request_alignment(BlockBackend *blk)
     return bs ? bs->bl.request_alignment : BDRV_SECTOR_SIZE;
 }
 

block/block-backend.c uint32_t blk_get_request_alignment(BlockBackend *blk) · line 2338

Quoted 10 lines
block/block-backend.c +10 -0
+/*
+ * Returns the zone size in bytes for a zoned backend, or 0 if @blk does
+ * not present zoned geometry.
+ */
+uint64_t blk_get_zone_size(BlockBackend *blk)
+{
+    BlockDriverState *bs = blk_bs(blk);
+    IO_CODE();
+    return bs ? bs->bl.zone_size : 0;
+}

Personally, I would add this new API in a separate patch, but either way is fine with me.

Quoted 19 lines
block/block-backend.c +1 -0
+
 /* Returns the optimal write zeroes alignment, in bytes; guaranteed nonzero */
 uint32_t blk_get_pwrite_zeroes_alignment(BlockBackend *blk)
 {
hw/block/virtio-blk.c +3 -0
index 6b92066aff..39750fa1c0 100644
@@ -294,6 +294,9 @@ static void virtio_blk_submit_multireq(VirtIOBlock *s, MultiReqBuffer *mrb)
     int i = 0, start = 0, num_reqs = 0, niov = 0, nb_sectors = 0;
     uint32_t max_transfer;
     int64_t sector_num = 0;
+    uint64_t zone_size = blk_get_zone_size(s->blk);
+    bool zone_cross;
+    int64_t zone_sector, end_sector;
 
     if (mrb->num_reqs == 1) {
         submit_requests(s, mrb, 0, 1, -1);

hw/block/virtio-blk.c static void virtio_blk_submit_multireq(VirtIOBlock *s, MultiReqBuffer *mrb) · line 321

Quoted 10 lines
hw/block/virtio-blk.c +7 -0
@@ -309,17 +312,34 @@ static void virtio_blk_submit_multireq(VirtIOBlock *s, MultiReqBuffer *mrb)
     for (i = 0; i < mrb->num_reqs; i++) {
         VirtIOBlockReq *req = mrb->reqs[i];
         if (num_reqs > 0) {
+            zone_cross = false;
+
+            /*
+             * On zoned backends, a single backend write must not span a zone
+             * boundary. Bail out of merging if combining req into the current
+             * batch would straddle a zone.
+             */

Like Stefan said in v11, as per the virtio spec, this applies to both reads and writes. The code is doing the right thing, but the comment should probably be updated to reflect that.

Kind regards,
Niklas

author
#7 lore raw

Re: [PATCH v12 3/5] virtio-blk: do not merge writes across a zone boundary

Quoted 68 lines · Niklas Cassel

Hello Sam,

Quoted 24 lines · Sam Li

virtio_blk_submit_multireq() fuses adjacent in-zone writes into a single request. On a zoned backend, a merged zone append request that straddles a zone boundary is rejected by the device because each write must stay within a single zone.

Add a bail condition to the merge coalescer: if combining the candidate request into the current batch would cross a zone boundary, flush the current batch and start a new one.

---
 block/block-backend.c             | 11 +++++++++++
 hw/block/virtio-blk.c             | 22 +++++++++++++++++++++-
 include/system/block-backend-io.h |  1 +
 3 files changed, 33 insertions(+), 1 deletion(-)
block/block-backend.c +0 -0
index 37ba7e9fc4..049e70ddcb 100644
@@ -2326,6 +2326,17 @@ uint32_t blk_get_request_alignment(BlockBackend *blk)
     return bs ? bs->bl.request_alignment : BDRV_SECTOR_SIZE;
 }
 

block/block-backend.c uint32_t blk_get_request_alignment(BlockBackend *blk) · line 2338

Quoted 10 lines
block/block-backend.c +10 -0
+/*
+ * Returns the zone size in bytes for a zoned backend, or 0 if @blk does
+ * not present zoned geometry.
+ */
+uint64_t blk_get_zone_size(BlockBackend *blk)
+{
+    BlockDriverState *bs = blk_bs(blk);
+    IO_CODE();
+    return bs ? bs->bl.zone_size : 0;
+}

Personally, I would add this new API in a separate patch, but either way is fine with me.

Quoted 25 lines
block/block-backend.c +1 -0
+
 /* Returns the optimal write zeroes alignment, in bytes; guaranteed nonzero */
 uint32_t blk_get_pwrite_zeroes_alignment(BlockBackend *blk)
 {
hw/block/virtio-blk.c +6 -0
index 6b92066aff..39750fa1c0 100644
@@ -294,6 +294,9 @@ static void virtio_blk_submit_multireq(VirtIOBlock *s, MultiReqBuffer *mrb)
     int i = 0, start = 0, num_reqs = 0, niov = 0, nb_sectors = 0;
     uint32_t max_transfer;
     int64_t sector_num = 0;
+    uint64_t zone_size = blk_get_zone_size(s->blk);
+    bool zone_cross;
+    int64_t zone_sector, end_sector;
 
     if (mrb->num_reqs == 1) {
         submit_requests(s, mrb, 0, 1, -1);
@@ -309,17 +312,34 @@ static void virtio_blk_submit_multireq(VirtIOBlock *s, MultiReqBuffer *mrb)
     for (i = 0; i < mrb->num_reqs; i++) {
         VirtIOBlockReq *req = mrb->reqs[i];
         if (num_reqs > 0) {
+            zone_cross = false;
+
+            /*
Quoted 8 lines

hw/block/virtio-blk.c static void virtio_blk_submit_multireq(VirtIOBlock *s, MultiReqBuffer *mrb) · line 321

Quoted 4 lines
hw/block/virtio-blk.c +4 -0
+             * On zoned backends, a single backend write must not span a zone
+             * boundary. Bail out of merging if combining req into the current
+             * batch would straddle a zone.
+             */

Like Stefan said in v11, as per the virtio spec, this applies to both reads and writes. The code is doing the right thing, but the comment should probably be updated to reflect that.

Ok, thanks! I'll add the reads to the comment.

Quoted 4 lines

Kind regards,
Niklas

author
#8 lore raw

PATCH v12 4/5 qcow2: add zoned emulation capability

In reply to Sam Li

By adding zone operations and zoned metadata, the zoned emulation capability enables full emulation support of zoned device using a qcow2 file. The zoned device metadata includes zone type, zoned device state and write pointer (WP) of each zone, which is stored to an array of unsigned integers.

WP accessor (qcow2_rw_wp_at) routes reads and writes of an 8-byte WP slot through the write pointer cache. The write pointer cache is written to disk after the qcow2 metadata is written, thus guaranteeing that the write pointer is updated after the corresponding data is written. Per-completion cache flush is deferred. The WP cluster reaches disk on the next flush.

Each zone of a zoned device makes state transitions following the zone state machine. The zone state machine mainly describes five states, IMPLICIT OPEN, EXPLICIT OPEN, FULL, EMPTY and CLOSED. READ ONLY and OFFLINE states will generally be affected by device internal events. The operations on zones cause corresponding state changing.

Zoned devices have limits on zone resources, which put constraints on write operations on zones. It is managed by active zone queues following LRU policy.

---
 block/qcow2-cache.c    |   11 +-
 block/qcow2-refcount.c |    7 +
 block/qcow2.c          | 1212 +++++++++++++++++++++++++++++++++++++++-
 block/trace-events     |    2 +
 4 files changed, 1218 insertions(+), 14 deletions(-)
block/qcow2-cache.c +10 -1
index 23d9588b08..73f2be3641 100644
@@ -275,14 +275,23 @@ int qcow2_cache_set_dependency(BlockDriverState *bs, Qcow2Cache *c,
 {
     int ret;
 
+    /*
+     * If the dependency graph is unchanged, nothing to do. This avoids
+     * a synchronous flush on every call below.
+     */
+    if (c->depends == dependency) {
+        return 0;
+    }
+
     if (dependency->depends) {
+        /* Flatten any chain on the dependency side as a cycle-breaker. */
         ret = qcow2_cache_flush_dependency(bs, dependency);
         if (ret < 0) {
             return ret;
         }
     }
 
-    if (c->depends && (c->depends != dependency)) {
+    if (c->depends) {
         ret = qcow2_cache_flush_dependency(bs, c);
         if (ret < 0) {
             return ret;
block/qcow2-refcount.c +7 -0
index 6512cda407..f551726609 100644
@@ -1239,6 +1239,13 @@ int qcow2_write_caches(BlockDriverState *bs)
         }
     }
 
+    if (s->wp_cache) {
+        ret = qcow2_cache_write(bs, s->wp_cache);
+        if (ret < 0) {
+            return ret;
+        }
+    }
+
     return 0;
 }
 
block/qcow2.c +1199 -13

1,318 lines not on this page · raw message

block/trace-events +2 -0
index 950c82d4b8..30a3e303ca 100644
@@ -76,6 +76,8 @@ qcow2_writev_data(void *co, uint64_t offset) "co %p offset 0x%" PRIx64
 qcow2_pwrite_zeroes_start_req(void *co, int64_t offset, int64_t bytes) "co %p offset 0x%" PRIx64 " bytes %" PRId64
 qcow2_pwrite_zeroes(void *co, int64_t offset, int64_t bytes) "co %p offset 0x%" PRIx64 " bytes %" PRId64
 qcow2_skip_cow(void *co, uint64_t offset, int nb_clusters) "co %p offset 0x%" PRIx64 " nb_clusters %d"
+qcow2_wp_tracking(int index, uint64_t wp) "wps[%d]: 0x%" PRIx64
+qcow2_imp_open_zones(uint8_t op, int nrz) "nr_imp_open_zones after op 0x%x: %d"
 
 # qcow2-cluster.c
 qcow2_alloc_clusters_offset(void *co, uint64_t offset, int bytes) "co %p offset 0x%" PRIx64 " bytes %d"
Signature · 1 line
2.53.0
#9 lore raw

Re: [PATCH v12 4/5] qcow2: add zoned emulation capability

Quoted 2 lines · Sam Li

+/*
+ * Read/Write the new wp value for zone index through write pointe

pointe -> pointer

block/qcow2.c qcow2_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes) · line 5337

Quoted 12 lines
block/qcow2.c +12 -0
+static int coroutine_fn
+qcow2_co_zone_report(BlockDriverState *bs, int64_t offset,
+                     unsigned int *nr_zones, BlockZoneDescriptor *zones)
+{
+    BDRVQcow2State *s = bs->opaque;
+    uint64_t zone_size = s->zoned_header.zone_size;
+    uint64_t zone_capacity = s->zoned_header.zone_capacity;
+    int64_t capacity = bs->total_sectors << BDRV_SECTOR_BITS;
+    int64_t size = bs->bl.nr_zones * zone_size;
+    unsigned int nrz;
+    int i = 0;
+    int si;

Should i and si be unsigned int since nr_zones is an unsigned int?

block/qcow2.c qcow2_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes) · line 5546

Quoted 9 lines
block/qcow2.c +9 -0
+static int coroutine_fn GRAPH_RDLOCK
+qcow2_reset_zone(BlockDriverState *bs, uint32_t index,
+                            int64_t len)
+{
+    BDRVQcow2State *s = bs->opaque;
+    int nrz = bs->bl.nr_zones;
+    int64_t zone_size = bs->bl.zone_size;
+    int n, ret = 0;
+    bool any_dirtied = false;

nr_zones is an unsigned int. Variables holding numbers of zones like nrz, i, and n should be unsigned int, too. That way they behave correctly over their full range instead of behaving unexpectedly when they become negative (e.g. in a for loop with i < n).

Quoted 14 lines
block/qcow2.c +14 -0
+
+    qemu_co_mutex_lock(&bs->wps->colock);
+    uint64_t *wp = &bs->wps->wp[index];
+    if (len == bs->total_sectors << BDRV_SECTOR_BITS) {
+        n = nrz;
+        index = 0;
+        wp = &bs->wps->wp[0];
+    } else {
+        n = len / zone_size;
+    }
+
+    for (int i = 0; i < n; ++i) {
+        uint64_t *wp_i = (uint64_t *)(wp + i);
+        uint64_t wpi_v = *wp_i;

block/qcow2.c qcow2_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes) · line 5570

Quoted 10 lines
block/qcow2.c +10 -0
+        if (QCOW2_ZT_IS_CONV(wpi_v)) {
+            continue;
+        }
+
+        /* Reject if any write is in flight for this zone. */
+        if (s->zone_wp_state &&
+            !QTAILQ_EMPTY(&s->zone_wp_state[index + i].in_flight)) {
+            ret = -EBUSY;
+            goto unlock;
+        }

This is a coroutine function and it should yield to wait instead of returning -EBUSY. If -EBUSY is propagated to the guest that would result in unexpected behavior - I think real devices don't do this and the guest will not be prepared to handle -EBUSY.

Quoted 21 lines
block/qcow2.c +21 -0
+
+        qemu_co_mutex_lock(&s->lock);
+        BlockZoneState zs = qcow2_get_zone_state(bs, index + i);
+        switch (zs) {
+        case BLK_ZS_EMPTY:
+            break;
+        case BLK_ZS_IOPEN:
+            qcow2_rm_imp_open_zone(s, index + i);
+            trace_qcow2_imp_open_zones(BLK_ZO_RESET, s->nr_zones_imp_open);
+            break;
+        case BLK_ZS_EOPEN:
+            qcow2_rm_exp_open_zone(s, index + i);
+            break;
+        case BLK_ZS_CLOSED:
+            qcow2_rm_closed_zone(s, index + i);
+            break;
+        case BLK_ZS_FULL:
+            break;
+        default:
+            ret = -EINVAL;
+            qemu_co_mutex_unlock(&s->lock);

block/qcow2.c qcow2_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes) · line 5601

Quoted 10 lines
block/qcow2.c +10 -0
+            goto unlock;
+        }
+        qemu_co_mutex_unlock(&s->lock);
+
+        if (zs == BLK_ZS_EMPTY) {
+            continue;
+        }
+
+        /*
+         * Zero the data extent first. Date write fires before the WP cluster

Date -> Data

Quoted 9 lines
block/qcow2.c +9 -0
+         * hits disk. So the wp advance cannot become durable while stale data
+         * is still readable.
+         */
+        ret = qcow2_co_pwrite_zeroes(bs, (uint64_t)(index + i) * zone_size,
+                                     zone_size, 0);
+        if (ret < 0) {
+            error_report("Failed to clear zone data at zone %u",
+                         index + i);
+            goto unlock;

block/qcow2.c qcow2_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes) · line 5620

Quoted 10 lines
block/qcow2.c +10 -0
+        }
+
+        qemu_co_mutex_lock(&s->lock);
+        qcow2_cache_depends_on_flush(s->wp_cache);
+        qemu_co_mutex_unlock(&s->lock);
+
+        *wp_i = (uint64_t)(index + i) * zone_size;
+        ret = qcow2_rw_wp_at(bs, wp_i, index + i, true);
+        if (ret < 0) {
+            goto unlock;

*wp_i has been modified but the operation will fail. The write pointers in memory and the write pointers in the qcow2 cache and on disk are now inconsistent. I expect the failure semantics to be that the write pointers in memory are consistent with the on-disk write pointers, although I haven't checked specs to see if they say anything about this.

Quoted 9 lines
block/qcow2.c +9 -0
+        }
+        any_dirtied = true;
+    }
+
+    if (any_dirtied) {
+        /* Single flush at the end. */
+        qemu_co_mutex_lock(&s->lock);
+        ret = qcow2_cache_flush(bs, s->wp_cache);
+        qemu_co_mutex_unlock(&s->lock);

block/qcow2.c qcow2_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes) · line 5639

Quoted 10 lines
block/qcow2.c +10 -0
+    }
+
+unlock:
+    qemu_co_mutex_unlock(&bs->wps->colock);
+    return ret;
+}
+
+static int coroutine_fn GRAPH_RDLOCK
+qcow2_co_zone_mgmt(BlockDriverState *bs, BlockZoneOp op,
+                                           int64_t offset, int64_t len)

Indentation is off here.

block/qcow2.c qcow2_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes) · line 5646

Quoted 7 lines
block/qcow2.c +7 -0
+{
+    BDRVQcow2State *s = bs->opaque;
+    int ret = 0;
+    int64_t capacity = bs->total_sectors << BDRV_SECTOR_BITS;
+    int64_t zone_size = s->zoned_header.zone_size;
+    int64_t zone_size_mask = zone_size - 1;
+    uint32_t index = offset / zone_size;

It would be safer to check that this qcow2 image supports zone emulation before getting deeper into this function. zone_size could be 0 here if zone emulation is not enabled and it would cause a divide-by-zero exception.

All block driver zone callbacks in qcow2 should perform this check just in case an emulated device exposes a code path where the guest can perform a zoned operation on a non-zoned BlockDriverState. Alternatively, you could add a generic check in bdrv_co_zone_mgmt() and similar functions.

Quoted 5 lines
block/qcow2.c +5 -0
+    BlockZoneWps *wps = bs->wps;
+
+    if (offset >= capacity) {
+        error_report("offset %" PRId64 " is equal to or greater than the"
+                     "device capacity %" PRId64 "", offset, capacity);

block/qcow2.c qcow2_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes) · line 5661

Quoted 10 lines
block/qcow2.c +10 -0
+        return -EINVAL;
+    }
+
+    if (offset & zone_size_mask) {
+        error_report("sector offset %" PRId64 " is not aligned to zone size"
+                     " %" PRId64 "", offset / 512, zone_size / 512);
+        return -EINVAL;
+    }
+
+    if (((offset + len) < capacity && len & zone_size_mask) ||

Here is how the capacity check is expressed without an integer overflow in block/block-backend.c:blk_check_byte_request():

  if (offset > len || len - offset < bytes) {
                      ^^^^^^^^^^^^^^^^^^^^
      return -EIO;
  }

It would be preferrable to use that form to avoid integer overflow.

Quoted 48 lines
block/qcow2.c +48 -0
+        offset + len > capacity) {
+        error_report("number of sectors %" PRId64 " is not aligned to zone"
+                     " size %" PRId64 "", len / 512, zone_size / 512);
+        return -EINVAL;
+    }
+
+    qemu_co_mutex_lock(&wps->colock);
+    uint64_t wpv = wps->wp[index];
+    qemu_co_mutex_unlock(&wps->colock);
+
+    if (QCOW2_ZT_IS_CONV(wpv)) {
+        /*
+         * ZONE_RESET_ALL is a global operation that is allowed when the
+         * starting zone is conventional; the zone reset path itself skips
+         * conventional zones.
+         */
+        if (op != BLK_ZO_RESET || len != capacity) {
+            error_report("zone mgmt operation 0x%x is not allowed on "
+                         "a conventional zone", op);
+            return -EIO;
+        }
+    }
+
+    switch (op) {
+    case BLK_ZO_OPEN:
+        ret = qcow2_open_zone(bs, index);
+        break;
+    case BLK_ZO_CLOSE:
+        ret = qcow2_close_zone(bs, index);
+        break;
+    case BLK_ZO_FINISH:
+        ret = qcow2_finish_zone(bs, index);
+        break;
+    case BLK_ZO_RESET:
+        ret = qcow2_reset_zone(bs, index, len);
+        break;
+    default:
+        error_report("Unsupported zone op: 0x%x", op);
+        ret = -ENOTSUP;
+        break;
+    }
+    return ret;
+}
+
+static int coroutine_fn GRAPH_RDLOCK
+qcow2_co_zone_append(BlockDriverState *bs, int64_t *offset, QEMUIOVector *qiov,
+                     BdrvRequestFlags flags)
+{

block/qcow2.c qcow2_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes) · line 5719

Quoted 10 lines
block/qcow2.c +10 -0
+    assert(flags == 0);
+    int64_t capacity = bs->total_sectors << BDRV_SECTOR_BITS;
+    int64_t zone_size_mask = bs->bl.zone_size - 1;
+    int64_t iov_len = 0;
+    int64_t len = 0;
+
+    if (*offset >= capacity) {
+        error_report("*offset %" PRId64 " is equal to or greater than the"
+                     "device capacity %" PRId64 "", *offset, capacity);
+        return -EINVAL;

I'm not sure whether this should be -ENOSPC or -EINVAL. Did you look into what is most appropriate? pwrite(2) on Linux returns ENOSPC when writing beyond the end of the block device.

This also applies to other places in this patch that check if offset >= capacity.

block/qcow2.c qcow2_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes) · line 5723

Quoted 4 lines
block/qcow2.c +4 -0
+    }
+
+    /* offset + len should not pass the end of that zone starting from offset */
+    if (*offset & zone_size_mask) {

The comment doesn't match the check that is performed here.

author
#10 lore raw

Re: [PATCH v12 4/5] qcow2: add zoned emulation capability

Quoted 22 lines · Stefan Hajnoczi
Quoted 2 lines · Sam Li

+/*
+ * Read/Write the new wp value for zone index through write pointe

pointe -> pointer

block/qcow2.c qcow2_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes) · line 5337

Quoted 12 lines
block/qcow2.c +12 -0
+static int coroutine_fn
+qcow2_co_zone_report(BlockDriverState *bs, int64_t offset,
+                     unsigned int *nr_zones, BlockZoneDescriptor *zones)
+{
+    BDRVQcow2State *s = bs->opaque;
+    uint64_t zone_size = s->zoned_header.zone_size;
+    uint64_t zone_capacity = s->zoned_header.zone_capacity;
+    int64_t capacity = bs->total_sectors << BDRV_SECTOR_BITS;
+    int64_t size = bs->bl.nr_zones * zone_size;
+    unsigned int nrz;
+    int i = 0;
+    int si;

Should i and si be unsigned int since nr_zones is an unsigned int?

Quoted 14 lines

block/qcow2.c qcow2_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes) · line 5546

Quoted 9 lines
block/qcow2.c +9 -0
+static int coroutine_fn GRAPH_RDLOCK
+qcow2_reset_zone(BlockDriverState *bs, uint32_t index,
+                            int64_t len)
+{
+    BDRVQcow2State *s = bs->opaque;
+    int nrz = bs->bl.nr_zones;
+    int64_t zone_size = bs->bl.zone_size;
+    int n, ret = 0;
+    bool any_dirtied = false;

nr_zones is an unsigned int. Variables holding numbers of zones like nrz, i, and n should be unsigned int, too. That way they behave correctly over their full range instead of behaving unexpectedly when they become negative (e.g. in a for loop with i < n).

Makes sense.

Quoted 22 lines
Quoted 22 lines
block/qcow2.c +21 -0
+
+    qemu_co_mutex_lock(&bs->wps->colock);
+    uint64_t *wp = &bs->wps->wp[index];
+    if (len == bs->total_sectors << BDRV_SECTOR_BITS) {
+        n = nrz;
+        index = 0;
+        wp = &bs->wps->wp[0];
+    } else {
+        n = len / zone_size;
+    }
+
+    for (int i = 0; i < n; ++i) {
+        uint64_t *wp_i = (uint64_t *)(wp + i);
+        uint64_t wpi_v = *wp_i;
+        if (QCOW2_ZT_IS_CONV(wpi_v)) {
+            continue;
+        }
+
+        /* Reject if any write is in flight for this zone. */
+        if (s->zone_wp_state &&
+            !QTAILQ_EMPTY(&s->zone_wp_state[index + i].in_flight)) {
Quoted 8 lines

block/qcow2.c qcow2_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes) · line 5400

Quoted 3 lines
block/qcow2.c +3 -0
+            ret = -EBUSY;
+            goto unlock;
+        }

This is a coroutine function and it should yield to wait instead of returning -EBUSY. If -EBUSY is propagated to the guest that would result in unexpected behavior - I think real devices don't do this and the guest will not be prepared to handle -EBUSY.

You are right. It should yield until drain, then proceed. A zoned null_blk does this.

Quoted 52 lines
Quoted 22 lines
block/qcow2.c +21 -0
+
+        qemu_co_mutex_lock(&s->lock);
+        BlockZoneState zs = qcow2_get_zone_state(bs, index + i);
+        switch (zs) {
+        case BLK_ZS_EMPTY:
+            break;
+        case BLK_ZS_IOPEN:
+            qcow2_rm_imp_open_zone(s, index + i);
+            trace_qcow2_imp_open_zones(BLK_ZO_RESET, s->nr_zones_imp_open);
+            break;
+        case BLK_ZS_EOPEN:
+            qcow2_rm_exp_open_zone(s, index + i);
+            break;
+        case BLK_ZS_CLOSED:
+            qcow2_rm_closed_zone(s, index + i);
+            break;
+        case BLK_ZS_FULL:
+            break;
+        default:
+            ret = -EINVAL;
+            qemu_co_mutex_unlock(&s->lock);

block/qcow2.c qcow2_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes) · line 5601

Quoted 10 lines
block/qcow2.c +10 -0
+            goto unlock;
+        }
+        qemu_co_mutex_unlock(&s->lock);
+
+        if (zs == BLK_ZS_EMPTY) {
+            continue;
+        }
+
+        /*
+         * Zero the data extent first. Date write fires before the WP cluster

Date -> Data

Quoted 17 lines
block/qcow2.c +17 -0
+         * hits disk. So the wp advance cannot become durable while stale data
+         * is still readable.
+         */
+        ret = qcow2_co_pwrite_zeroes(bs, (uint64_t)(index + i) * zone_size,
+                                     zone_size, 0);
+        if (ret < 0) {
+            error_report("Failed to clear zone data at zone %u",
+                         index + i);
+            goto unlock;
+        }
+
+        qemu_co_mutex_lock(&s->lock);
+        qcow2_cache_depends_on_flush(s->wp_cache);
+        qemu_co_mutex_unlock(&s->lock);
+
+        *wp_i = (uint64_t)(index + i) * zone_size;
+        ret = qcow2_rw_wp_at(bs, wp_i, index + i, true);
Quoted 8 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+        if (ret < 0) {
+            goto unlock;

*wp_i has been modified but the operation will fail. The write pointers in memory and the write pointers in the qcow2 cache and on disk are now inconsistent. I expect the failure semantics to be that the write pointers in memory are consistent with the on-disk write pointers, although I haven't checked specs to see if they say anything about this.

Right, on wp-write failure, the in-memory wp needs to be stored so RAM stays consistent with disk.

Quoted 36 lines
Quoted 10 lines
block/qcow2.c +9 -0
+        }
+        any_dirtied = true;
+    }
+
+    if (any_dirtied) {
+        /* Single flush at the end. */
+        qemu_co_mutex_lock(&s->lock);
+        ret = qcow2_cache_flush(bs, s->wp_cache);
+        qemu_co_mutex_unlock(&s->lock);

block/qcow2.c qcow2_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes) · line 5639

Quoted 10 lines
block/qcow2.c +10 -0
+    }
+
+unlock:
+    qemu_co_mutex_unlock(&bs->wps->colock);
+    return ret;
+}
+
+static int coroutine_fn GRAPH_RDLOCK
+qcow2_co_zone_mgmt(BlockDriverState *bs, BlockZoneOp op,
+                                           int64_t offset, int64_t len)

Indentation is off here.

block/qcow2.c qcow2_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes) · line 5646

Quoted 7 lines
block/qcow2.c +7 -0
+{
+    BDRVQcow2State *s = bs->opaque;
+    int ret = 0;
+    int64_t capacity = bs->total_sectors << BDRV_SECTOR_BITS;
+    int64_t zone_size = s->zoned_header.zone_size;
+    int64_t zone_size_mask = zone_size - 1;
+    uint32_t index = offset / zone_size;

It would be safer to check that this qcow2 image supports zone emulation before getting deeper into this function. zone_size could be 0 here if zone emulation is not enabled and it would cause a divide-by-zero exception.

Quoted 5 lines

All block driver zone callbacks in qcow2 should perform this check just in case an emulated device exposes a code path where the guest can perform a zoned operation on a non-zoned BlockDriverState. Alternatively, you could add a generic check in bdrv_co_zone_mgmt() and similar functions.

I'll add this check to bdrv_co_zone_mgmt() to prevent the leak.

Quoted 20 lines
Quoted 6 lines
block/qcow2.c +5 -0
+    BlockZoneWps *wps = bs->wps;
+
+    if (offset >= capacity) {
+        error_report("offset %" PRId64 " is equal to or greater than the"
+                     "device capacity %" PRId64 "", offset, capacity);

block/qcow2.c qcow2_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes) · line 5661

Quoted 10 lines
block/qcow2.c +10 -0
+        return -EINVAL;
+    }
+
+    if (offset & zone_size_mask) {
+        error_report("sector offset %" PRId64 " is not aligned to zone size"
+                     " %" PRId64 "", offset / 512, zone_size / 512);
+        return -EINVAL;
+    }
+
+    if (((offset + len) < capacity && len & zone_size_mask) ||

Here is how the capacity check is expressed without an integer overflow in block/block-backend.c:blk_check_byte_request():

Quoted 6 lines
  if (offset > len || len - offset < bytes) {
                      ^^^^^^^^^^^^^^^^^^^^
      return -EIO;
  }

It would be preferrable to use that form to avoid integer overflow.

Nice approach!

Quoted 64 lines
Quoted 49 lines
block/qcow2.c +48 -0
+        offset + len > capacity) {
+        error_report("number of sectors %" PRId64 " is not aligned to zone"
+                     " size %" PRId64 "", len / 512, zone_size / 512);
+        return -EINVAL;
+    }
+
+    qemu_co_mutex_lock(&wps->colock);
+    uint64_t wpv = wps->wp[index];
+    qemu_co_mutex_unlock(&wps->colock);
+
+    if (QCOW2_ZT_IS_CONV(wpv)) {
+        /*
+         * ZONE_RESET_ALL is a global operation that is allowed when the
+         * starting zone is conventional; the zone reset path itself skips
+         * conventional zones.
+         */
+        if (op != BLK_ZO_RESET || len != capacity) {
+            error_report("zone mgmt operation 0x%x is not allowed on "
+                         "a conventional zone", op);
+            return -EIO;
+        }
+    }
+
+    switch (op) {
+    case BLK_ZO_OPEN:
+        ret = qcow2_open_zone(bs, index);
+        break;
+    case BLK_ZO_CLOSE:
+        ret = qcow2_close_zone(bs, index);
+        break;
+    case BLK_ZO_FINISH:
+        ret = qcow2_finish_zone(bs, index);
+        break;
+    case BLK_ZO_RESET:
+        ret = qcow2_reset_zone(bs, index, len);
+        break;
+    default:
+        error_report("Unsupported zone op: 0x%x", op);
+        ret = -ENOTSUP;
+        break;
+    }
+    return ret;
+}
+
+static int coroutine_fn GRAPH_RDLOCK
+qcow2_co_zone_append(BlockDriverState *bs, int64_t *offset, QEMUIOVector *qiov,
+                     BdrvRequestFlags flags)
+{

block/qcow2.c qcow2_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes) · line 5719

Quoted 10 lines
block/qcow2.c +10 -0
+    assert(flags == 0);
+    int64_t capacity = bs->total_sectors << BDRV_SECTOR_BITS;
+    int64_t zone_size_mask = bs->bl.zone_size - 1;
+    int64_t iov_len = 0;
+    int64_t len = 0;
+
+    if (*offset >= capacity) {
+        error_report("*offset %" PRId64 " is equal to or greater than the"
+                     "device capacity %" PRId64 "", *offset, capacity);
+        return -EINVAL;

I'm not sure whether this should be -ENOSPC or -EINVAL. Did you look into what is most appropriate? pwrite(2) on Linux returns ENOSPC when writing beyond the end of the block device.

Quoted 2 lines

This also applies to other places in this patch that check if offset >= capacity.

Ah, it should be -ENOSPC. That's also what a zoned null_blk device returns when writing at/beyond device capacity.

Quoted 7 lines

block/qcow2.c qcow2_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes) · line 5723

Quoted 5 lines
block/qcow2.c +4 -0
+    }
+
+    /* offset + len should not pass the end of that zone starting from offset */
+    if (*offset & zone_size_mask) {

The comment doesn't match the check that is performed here.

Will fix it.

Thanks for reviewing!

Sam

#11 lore raw

Re: [PATCH v12 4/5] qcow2: add zoned emulation capability

In reply to Sam Li
Quoted 18 lines · Sam Li
block/qcow2.c +18 -0
+static int coroutine_fn GRAPH_RDLOCK
+qcow2_rw_wp_at(BlockDriverState *bs, uint64_t *wp,
+                  int32_t index, bool is_write)
+{
+    BDRVQcow2State *s = bs->opaque;
+    uint64_t wp_byte_off = sizeof(uint64_t) * index;
+    uint64_t cluster_file_off =
+        s->zoned_header.zonedmeta_offset +
+        (wp_byte_off & ~((uint64_t)s->cluster_size - 1));
+    size_t off_in_cluster = wp_byte_off & (s->cluster_size - 1);
+    void *cluster_buf;
+    uint64_t *slot;
+    int ret;
+
+    assert(s->wp_cache != NULL);
+
+    qemu_co_mutex_lock(&s->lock);
+    ret = qcow2_cache_get(bs, s->wp_cache, cluster_file_off, &cluster_buf);

block/qcow2.c qcow2_extract_crypto_opts(QemuOpts *opts, const char *fmt, Error **errp) · line 419

Quoted 10 lines
block/qcow2.c +10 -0
+    if (ret < 0) {
+        qemu_co_mutex_unlock(&s->lock);
+        error_report("Failed to %s WP slot (zone %d): %s",
+                     is_write ? "write" : "read", index, strerror(-ret));
+        return ret;
+    }
+
+    slot = (uint64_t *)((char *)cluster_buf + off_in_cluster);
+    if (is_write) {
+        *slot = *wp;

Missing cpu_to_be64()?

block/qcow2.c qcow2_extract_crypto_opts(QemuOpts *opts, const char *fmt, Error **errp) · line 422

Quoted 3 lines
block/qcow2.c +3 -0
+        qcow2_cache_entry_mark_dirty(s->wp_cache, cluster_buf);
+    } else {
+        *wp = *slot;

Missing be64_to_cpu()?

Quoted 7 lines
block/qcow2.c +7 -0
+static inline int coroutine_fn GRAPH_RDLOCK
+qcow2_refresh_zonedmeta(BlockDriverState *bs)
+{
+    int ret;
+    BDRVQcow2State *s = bs->opaque;
+    uint64_t wps_size = s->zoned_header.nr_zones * sizeof(uint64_t);
+    g_autofree uint64_t *temp = NULL;

block/qcow2.c qcow2_extract_crypto_opts(QemuOpts *opts, const char *fmt, Error **errp) · line 503

Quoted 10 lines
block/qcow2.c +10 -0
+
+    temp = g_new(uint64_t, s->zoned_header.nr_zones);
+    ret = bdrv_pread(bs->file, s->zoned_header.zonedmeta_offset,
+                     wps_size, temp, 0);
+    if (ret < 0) {
+        error_report("Cannot read metadata");
+        return ret;
+    }
+
+    memcpy(bs->wps->wp, temp, wps_size);

Missing be64_to_cpu()?

bs->wps->wp[] is in QEMU's format while temp is in qcow2's format. The representations are not guaranteed to remain the same. An explicit conversion from qcow2's representation to QEMU's representation would be best. You could also use build-time assertions (QEMU_BUILD_BUG_ON()) to check that the qcow2 constants match the QEMU constants.

block/qcow2.c qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset, · line 880

Quoted 10 lines
block/qcow2.c +4 -2
@@ -559,8 +874,34 @@ qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
                            "is wrong");
                 return -EINVAL;
             }
-            if (!qcow2_check_zone_options(&zoned_ext, errp)) {
-                return -EINVAL;
+
+            bs->wps = g_malloc(sizeof(BlockZoneWps)
+                + s->zoned_header.nr_zones * sizeof(uint64_t));
+            ret = qcow2_refresh_zonedmeta(bs);

Is bs->wps freed when qcow2_refresh_zonedmeta() fails?

Quoted 8 lines
block/qcow2.c +4 -0
@@ -4161,6 +4879,45 @@ qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp)
             ret = -EINVAL;
             goto unlock;
         }
+
+        uint32_t nrz = s->zoned_header.nr_zones;
+        zoned_meta_size =  sizeof(uint64_t) * nrz;
+        g_autofree uint64_t *meta = NULL;

block/qcow2.c qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp) · line 4895

Quoted 10 lines
block/qcow2.c +10 -0
+        meta = g_new0(uint64_t, nrz);
+
+        for (i = 0; i < s->zoned_header.conventional_zones; ++i) {
+            meta[i] = i * s->zoned_header.zone_size;
+            meta[i] |= 1ULL << 59;
+        }
+
+        for (; i < nrz; ++i) {
+            meta[i] = i * s->zoned_header.zone_size;
+        }

Missing cpu_to_be64()?

author
#12 lore raw

Re: [PATCH v12 4/5] qcow2: add zoned emulation capability

Quoted 59 lines · Stefan Hajnoczi
Quoted 18 lines · Sam Li
block/qcow2.c +18 -0
+static int coroutine_fn GRAPH_RDLOCK
+qcow2_rw_wp_at(BlockDriverState *bs, uint64_t *wp,
+                  int32_t index, bool is_write)
+{
+    BDRVQcow2State *s = bs->opaque;
+    uint64_t wp_byte_off = sizeof(uint64_t) * index;
+    uint64_t cluster_file_off =
+        s->zoned_header.zonedmeta_offset +
+        (wp_byte_off & ~((uint64_t)s->cluster_size - 1));
+    size_t off_in_cluster = wp_byte_off & (s->cluster_size - 1);
+    void *cluster_buf;
+    uint64_t *slot;
+    int ret;
+
+    assert(s->wp_cache != NULL);
+
+    qemu_co_mutex_lock(&s->lock);
+    ret = qcow2_cache_get(bs, s->wp_cache, cluster_file_off, &cluster_buf);

block/qcow2.c qcow2_extract_crypto_opts(QemuOpts *opts, const char *fmt, Error **errp) · line 419

Quoted 10 lines
block/qcow2.c +10 -0
+    if (ret < 0) {
+        qemu_co_mutex_unlock(&s->lock);
+        error_report("Failed to %s WP slot (zone %d): %s",
+                     is_write ? "write" : "read", index, strerror(-ret));
+        return ret;
+    }
+
+    slot = (uint64_t *)((char *)cluster_buf + off_in_cluster);
+    if (is_write) {
+        *slot = *wp;

Missing cpu_to_be64()?

block/qcow2.c qcow2_extract_crypto_opts(QemuOpts *opts, const char *fmt, Error **errp) · line 422

Quoted 3 lines
block/qcow2.c +3 -0
+        qcow2_cache_entry_mark_dirty(s->wp_cache, cluster_buf);
+    } else {
+        *wp = *slot;

Missing be64_to_cpu()?

Quoted 7 lines
block/qcow2.c +7 -0
+static inline int coroutine_fn GRAPH_RDLOCK
+qcow2_refresh_zonedmeta(BlockDriverState *bs)
+{
+    int ret;
+    BDRVQcow2State *s = bs->opaque;
+    uint64_t wps_size = s->zoned_header.nr_zones * sizeof(uint64_t);
+    g_autofree uint64_t *temp = NULL;

block/qcow2.c qcow2_extract_crypto_opts(QemuOpts *opts, const char *fmt, Error **errp) · line 503

Quoted 10 lines
block/qcow2.c +10 -0
+
+    temp = g_new(uint64_t, s->zoned_header.nr_zones);
+    ret = bdrv_pread(bs->file, s->zoned_header.zonedmeta_offset,
+                     wps_size, temp, 0);
+    if (ret < 0) {
+        error_report("Cannot read metadata");
+        return ret;
+    }
+
+    memcpy(bs->wps->wp, temp, wps_size);

Missing be64_to_cpu()?

Quoted 5 lines

bs->wps->wp[] is in QEMU's format while temp is in qcow2's format. The representations are not guaranteed to remain the same. An explicit conversion from qcow2's representation to QEMU's representation would be best. You could also use build-time assertions (QEMU_BUILD_BUG_ON()) to check that the qcow2 constants match the QEMU constants.

Another idea is making the wps for qcow2 follow the same format as the block layer's. If there are more bits of a write pointer used, changes can be performed on the qemu's representation.

Quoted 33 lines

block/qcow2.c qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset, · line 880

Quoted 11 lines
block/qcow2.c +4 -2
@@ -559,8 +874,34 @@ qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
                            "is wrong");
                 return -EINVAL;
             }
-            if (!qcow2_check_zone_options(&zoned_ext, errp)) {
-                return -EINVAL;
+
+            bs->wps = g_malloc(sizeof(BlockZoneWps)
+                + s->zoned_header.nr_zones * sizeof(uint64_t));
+            ret = qcow2_refresh_zonedmeta(bs);

Is bs->wps freed when qcow2_refresh_zonedmeta() fails?

Quoted 8 lines
block/qcow2.c +4 -0
@@ -4161,6 +4879,45 @@ qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp)
             ret = -EINVAL;
             goto unlock;
         }
+
+        uint32_t nrz = s->zoned_header.nr_zones;
+        zoned_meta_size =  sizeof(uint64_t) * nrz;
+        g_autofree uint64_t *meta = NULL;

block/qcow2.c qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp) · line 4895

Quoted 10 lines
block/qcow2.c +10 -0
+        meta = g_new0(uint64_t, nrz);
+
+        for (i = 0; i < s->zoned_header.conventional_zones; ++i) {
+            meta[i] = i * s->zoned_header.zone_size;
+            meta[i] |= 1ULL << 59;
+        }
+
+        for (; i < nrz; ++i) {
+            meta[i] = i * s->zoned_header.zone_size;
+        }

Missing cpu_to_be64()?

author
#13 lore raw

PATCH v12 5/5 iotests: test the zoned format feature for qcow2 file

In reply to Sam Li

The zoned format feature can be tested by:

$ tests/qemu-iotests/check -qcow2 zoned-qcow2
---
 tests/qemu-iotests/303.out                    |   4 +-
 tests/qemu-iotests/tests/qcow2-encryption.out |   4 +-
 tests/qemu-iotests/tests/zoned-qcow2          | 209 ++++++++++++++++++
 tests/qemu-iotests/tests/zoned-qcow2.out      | 191 ++++++++++++++++
 4 files changed, 404 insertions(+), 4 deletions(-)
 create mode 100755 tests/qemu-iotests/tests/zoned-qcow2
 create mode 100644 tests/qemu-iotests/tests/zoned-qcow2.out
tests/qemu-iotests/303.out +2 -2
index b3c70827b7..684a481cae 100644
@@ -47,7 +47,7 @@ header_length             112
 
 Header extension:
 magic                     0x6803f857 (Feature table)
-length                    384
+length                    432
 data                      <binary>
 
 Header extension:
@@ -133,7 +133,7 @@ wrote 1048576/1048576 bytes at offset 7340032
     {
         "name": "Feature table",
         "magic": 1745090647,
-        "length": 384,
+        "length": 432,
         "data_str": "<binary>"
     },
     {
tests/qemu-iotests/tests/qcow2-encryption.out +2 -2
index 9b549dc2ab..8be3e57f6e 100644
@@ -10,7 +10,7 @@ data                      <binary>
 
 Header extension:
 magic                     0x6803f857 (Feature table)
-length                    384
+length                    432
 data                      <binary>
 
 image: TEST_DIR/t.IMGFMT
@@ -24,7 +24,7 @@ No errors were found on the image.
 
 Header extension:
 magic                     0x6803f857 (Feature table)
-length                    384
+length                    432
 data                      <binary>
 
 qemu-img: Could not open 'TEST_DIR/t.IMGFMT': Missing CRYPTO header for crypt method 2
tests/qemu-iotests/tests/zoned-qcow2 new file +209 -0

209 lines not on this page · raw message

tests/qemu-iotests/tests/zoned-qcow2.out new file +191 -0

191 lines not on this page · raw message

Signature · 1 line
2.53.0
#14 lore raw
In reply to Sam Li

Hello Sam,

Again, thank you so much for spending your spare time on this!

Quoted 57 lines · Sam Li

This patch series add a new extension - zoned format - to the qcow2 driver, allowing full zoned storage emulation on a qcow2 image file. A user can attach such an image to a guest and have it appear as a host-managed zoned block device.

The zoned format is opt-in through a new qcow2 header extension that pins the zone geometry. Behind the extension is a dedicated zoned metadata region that stores one 8-byte write pointer (WP) per zone. The extension is gated by an incompatible bit, so an older qcow2 implementation cannot accidentally open the image.

Each write pointer is routed through the write pointer cache, a Qcow2Cache object. The write pointer cache is written to disk after the qcow2 metadata is written, thus guaranteeing that the write pointer is updated after the corresponding data is written.

Zone states are in memory. Read-only and offline states are device-internal events, which are not modelled in qcow2 emulation for simplicity. The other zone states (closed, empty, full) can be inferred from write poiner values, presistent across QEMU reboots. The open states are kept in memory using open zone lists.

To create a qcow2 file with the zoned format:

    qemu-img create -f qcow2 zbc.qcow2 \
        -o size=768M \
        -o zone.size=64M \
        -o zone.capacity=64M \
        -o zone.conventional_zones=0 \
        -o zone.max_append_bytes=4096 \
        -o zone.max_open_zones=6 \
        -o zone.max_active_zones=8 \
        -o zone.mode=host-managed

Then attach it to a guest via the QEMU command line:

    -blockdev node-name=drive1,driver=qcow2,\
              file.driver=file,file.filename=zbc.qcow2 \
    -device virtio-blk-pci,drive=drive1 \

v11->v12:
- validate the zoned header extension before allocating any zoned metadata
- fix the zoned locking discipline: hold the qcow2 state lock (s->lock) across all zone-state list updates [Stefan]
- reject, instead of aborting on an assertion, a write that reaches the open-zone limit while every open zone is explicitly open
- fix reduced-capacity (zone_capacity < zone_size) handling:
* transition a zone to FULL when the write pointer reaches the zone capacity
* report the zone capacity, not the zone size, in zone_report
- return -EIO rather than -EINVAL for zone write-rule violations
- use int64_t for the zoned-metadata cluster offset and zone_size to avoid truncation on large images
- simplify qcow2_cache_set_dependency() [Stefan]
- virtio-blk: read the zone size through a new blk_get_zone_size() [Stefan]

Quoted 3 lines

- docs/QAPI: clarify the max_open_zones / max_active_zones / max_append_bytes descriptions; use warn_report() for recoverable zoned configuration values in qcow2_check_zone_options() [Niklas, Stefan]

I'm sorry, but to me, it looks like patch 1/5 in v12 is identical to v11.

Did you perhaps forget to do git add or something?

Kind regards,
Niklas

author
#15 lore raw

Hi Niklas,

Quoted 63 lines · Niklas Cassel

Hello Sam,

Again, thank you so much for spending your spare time on this!

Quoted 56 lines · Sam Li

This patch series add a new extension - zoned format - to the qcow2 driver, allowing full zoned storage emulation on a qcow2 image file. A user can attach such an image to a guest and have it appear as a host-managed zoned block device.

The zoned format is opt-in through a new qcow2 header extension that pins the zone geometry. Behind the extension is a dedicated zoned metadata region that stores one 8-byte write pointer (WP) per zone. The extension is gated by an incompatible bit, so an older qcow2 implementation cannot accidentally open the image.

Each write pointer is routed through the write pointer cache, a Qcow2Cache object. The write pointer cache is written to disk after the qcow2 metadata is written, thus guaranteeing that the write pointer is updated after the corresponding data is written.

Zone states are in memory. Read-only and offline states are device-internal events, which are not modelled in qcow2 emulation for simplicity. The other zone states (closed, empty, full) can be inferred from write poiner values, presistent across QEMU reboots. The open states are kept in memory using open zone lists.

To create a qcow2 file with the zoned format:

    qemu-img create -f qcow2 zbc.qcow2 \
        -o size=768M \
        -o zone.size=64M \
        -o zone.capacity=64M \
        -o zone.conventional_zones=0 \
        -o zone.max_append_bytes=4096 \
        -o zone.max_open_zones=6 \
        -o zone.max_active_zones=8 \
        -o zone.mode=host-managed

Then attach it to a guest via the QEMU command line:

    -blockdev node-name=drive1,driver=qcow2,\
              file.driver=file,file.filename=zbc.qcow2 \
    -device virtio-blk-pci,drive=drive1 \

v11->v12:
- validate the zoned header extension before allocating any zoned metadata
- fix the zoned locking discipline: hold the qcow2 state lock (s->lock) across all zone-state list updates [Stefan]
- reject, instead of aborting on an assertion, a write that reaches the open-zone limit while every open zone is explicitly open
- fix reduced-capacity (zone_capacity < zone_size) handling:
* transition a zone to FULL when the write pointer reaches the zone capacity
* report the zone capacity, not the zone size, in zone_report
- return -EIO rather than -EINVAL for zone write-rule violations
- use int64_t for the zoned-metadata cluster offset and zone_size to avoid truncation on large images
- simplify qcow2_cache_set_dependency() [Stefan]
- virtio-blk: read the zone size through a new blk_get_zone_size() [Stefan]

Quoted 7 lines
Quoted 3 lines

- docs/QAPI: clarify the max_open_zones / max_active_zones / max_append_bytes descriptions; use warn_report() for recoverable zoned configuration values in qcow2_check_zone_options() [Niklas, Stefan]

I'm sorry, but to me, it looks like patch 1/5 in v12 is identical to v11.

Did you perhaps forget to do git add or something?

Ah! I made a mistake of mixing changes of patch 1/5 to 2/5. I'll send a new version. Thanks for checking.

Best regards,
Sam