Skip to contentSkip to conversation

Add full zoned storage emulation to the qcow2 driver

PATCH Superseded Niklas Cassel 1 participant 8 messages Oct 26 Block layer

v15 of 17 Superseded Latest is v17 →

lore
Share & tools
lore
#0 lore raw

v15 cover Add full zoned storage emulation to the qcow2 driver

This patch series adds 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 pointer values, persistent 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_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 \

Tested with blktests, fio, zbd_state (an internal test suite) and zonefs, comparing a zoned qcow2 image attached via virtio-blk with zloop, null_blk and scsi_debug (passed/failed/skipped):

    +--------------------+----------+---------+-----------+---------+
    | Testrun            | blktests | fio     | zbd_state | zonefs  |
    +--------------------+----------+---------+-----------+---------+
    | zloop              | 9/0/10   | 57/0/18 | 29/0/8    | 113/0/0 |
    | null_blk           | 9/0/10   | 57/0/18 | 29/0/8    | 113/0/0 |
    | scsi_debug         | 10/0/12  | 61/0/14 | 29/0/8    | 113/0/0 |
    | virtio-blk + qcow2 | 9/0/10   | 57/0/18 | 29/0/8    | 113/0/0 |
    +--------------------+----------+---------+-----------+---------+

This series depends on the (still not merged) series "block: fix the zone write granularity and the zone append limit":
https://lore.kernel.org/qemu-devel/[email protected]/

Git branch which includes the dependency series can be found at:
https://github.com/floatious/qemu/tree/qcow2-v15

Based-on: <[email protected]>

v14->v15:
- rebase on the series above, which now contains the v14 patches "block: widen BlockLimits.zone_size to uint64_t" and "virtio-blk: do not merge writes across a zone boundary", and which moves the zone append checks to the block layer
- drop zone.max_append_bytes; zonedmeta_offset moves to bytes 24-31 of the zoned header extension, so images created with v14 are not compatible
- require a version 3 image, a zone size that is a multiple of the cluster size, and a zone capacity that is a multiple of the zone write granularity
- report zone errors with dedicated errnos (new patch) instead of EIO, EINVAL and EBUSY
- manage the zone resources as in NVMe ZNS (2.1.1.4.1) and ZBC-3, and fix OPEN ZONE of a full zone, writes that fill a closed zone, writes from a conventional into a sequential zone, conventional zone and zone capacity reporting, and a shorter last zone
- validate the zoned header extension, and the write pointer table (new patch), when opening an image
- account for the zoned metadata in qemu-img check
- report zone errors with their zone status codes in virtio-blk (new patch)
- extend the iotest with zone errors, zone resources and image checks

Niklas Cassel (3):
block: define errnos for zone protocol errors
qcow2: validate the write pointer table when opening an image
virtio-blk: report zone errors with their zone status codes

Sam Li (4):
docs/qcow2: add the zoned format feature
qcow2: add configurations for zoned format extension
qcow2: add zoned emulation capability
iotests: test the zoned format feature for qcow2 file

 MAINTAINERS                                   |    1 +
 block/io.c                                    |   13 +-
 block/qcow2-cache.c                           |   11 +-
 block/qcow2-refcount.c                        |   18 +
 block/qcow2.c                                 | 1674 ++++++++++++++++-
 block/qcow2.h                                 |   86 +-
 block/trace-events                            |    2 +
 docs/interop/qcow2.rst                        |  115 +-
 docs/system/qemu-block-drivers.rst.inc        |   44 +
 hw/block/block.c                              |    7 +
 hw/block/virtio-blk.c                         |   48 +-
 include/block/block-common.h                  |   16 +
 include/block/block-io.h                      |    6 +
 include/block/block_int-common.h              |   12 +
 include/qemu/osdep.h                          |    3 +
 qapi/block-core.json                          |   86 +-
 tests/qemu-iotests/031.out                    |    8 +-
 tests/qemu-iotests/036.out                    |    4 +-
 tests/qemu-iotests/061.out                    |   14 +-
 tests/qemu-iotests/082.out                    |  108 ++
 tests/qemu-iotests/303.out                    |    4 +-
 tests/qemu-iotests/tests/qcow2-encryption.out |    4 +-
 tests/qemu-iotests/tests/zoned-qcow2          |  362 ++++
 tests/qemu-iotests/tests/zoned-qcow2.out      |  265 +++
 24 files changed, 2874 insertions(+), 37 deletions(-)
 create mode 100755 tests/qemu-iotests/tests/zoned-qcow2
 create mode 100644 tests/qemu-iotests/tests/zoned-qcow2.out
Signature · 1 line
2.56.0
#1 lore raw

PATCH v15 1/7 docs/qcow2: add the zoned format feature

From: Sam Li <[email protected]>

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.

---
Changes by Niklas Cassel:
- do not document a zone append size limit, which the driver no longer stores in the image

---
 docs/system/qemu-block-drivers.rst.inc | 44 ++++++++++++++++++++++++++
 1 file changed, 44 insertions(+)
docs/system/qemu-block-drivers.rst.inc +44 -0
index 675daa72f9..70b9b8d1b4 100644
@@ -172,6 +172,50 @@ 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 for 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 maximum allowed active zones (zones in the 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 maximum allowed open zones (zones in the implicit open or explicit
+    open state). 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.
+
 .. program:: image-formats
 .. option:: qed
 
Signature · 1 line
2.56.0
#2 lore raw

PATCH v15 2/7 qcow2: add configurations for zoned format extension

In reply to Niklas Cassel

From: Sam Li <[email protected]>

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 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_open_zones=6 -o zone.max_active_zones=8 \
-o zone.mode=host-managed

---
Changes by Niklas Cassel:
- validate the zoned extension header before it becomes the driver state, so that the clamped resource limits are the ones that take effect
- drop the zone append size limit from the header, the QAPI schema and the format documentation; it described a limit on an operation that the driver derives from the geometry instead
- do not report a zone write granularity; the block layer already requires an append to be a multiple of the sector size, and a coarser granularity belongs to a driver that has a medium with one
- take the zone capacity into account, as bdrv_zone_writable_end(), which bdrv_zone_is_full() then uses
- require the zone size to be a multiple of the cluster size, so that a zone never shares a cluster with another zone, and resetting it can zero its clusters in place
- require version 3 for a zoned image, as the zoned format is an incompatible feature, which a version 2 header cannot express; refuse a zoned extension without the incompatible feature bit when opening

---
 block/io.c                                    |  13 +-
 block/qcow2.c                                 | 363 +++++++++++++++++-
 block/qcow2.h                                 |  84 +++-
 docs/interop/qcow2.rst                        | 115 +++++-
 hw/block/block.c                              |   7 +
 include/block/block-io.h                      |   6 +
 include/block/block_int-common.h              |  12 +
 qapi/block-core.json                          |  86 ++++-
 tests/qemu-iotests/031.out                    |   8 +-
 tests/qemu-iotests/036.out                    |   4 +-
 tests/qemu-iotests/061.out                    |  14 +-
 tests/qemu-iotests/082.out                    | 108 ++++++
 tests/qemu-iotests/303.out                    |   4 +-
 tests/qemu-iotests/tests/qcow2-encryption.out |   4 +-
 14 files changed, 801 insertions(+), 27 deletions(-)
block/io.c +10 -3
index 06b1fc13b9..6e33da7f23 100644
@@ -3400,13 +3400,20 @@ bool bdrv_zone_is_conv(BlockDriverState *bs, uint32_t index)
     return BDRV_ZT_IS_CONV(bs->wps->wp[index]);
 }
 
+uint64_t bdrv_zone_writable_end(BlockDriverState *bs, uint32_t index)
+{
+    uint64_t writable = MIN_NON_ZERO(bs->bl.zone_capacity, bs->bl.zone_size);
+    IO_CODE();
+
+    return MIN((uint64_t)index * bs->bl.zone_size + writable,
+               (uint64_t)bs->total_sectors << BDRV_SECTOR_BITS);
+}
+
 bool bdrv_zone_is_full(BlockDriverState *bs, uint32_t index)
 {
-    uint64_t zone_end = MIN((uint64_t)(index + 1) * bs->bl.zone_size,
-                            (uint64_t)bs->total_sectors << BDRV_SECTOR_BITS);
     IO_CODE();
 
-    return bs->wps->wp[index] >= zone_end;
+    return bs->wps->wp[index] >= bdrv_zone_writable_end(bs, index);
 }
 
 void *qemu_blockalign(BlockDriverState *bs, size_t size)
block/qcow2.c +360 -3

471 lines not on this page · raw message

block/qcow2.h +83 -1

118 lines not on this page · raw message

docs/interop/qcow2.rst +114 -1

133 lines not on this page · raw message

hw/block/block.c +7 -0
index 3bb8121e9e..5b2e44351e 100644
@@ -238,6 +238,13 @@ bool blkconf_check_zoned_geometry(BlockConf *conf, Error **errp)
         return false;
     }
 
+    if (!QEMU_IS_ALIGNED(bs->bl.zone_capacity, wg)) {
+        error_setg(errp, "zone capacity %" PRIu64 " is not a multiple of the "
+                   "zone write granularity %" PRIu32,
+                   bs->bl.zone_capacity, wg);
+        return false;
+    }
+
     /*
      * A write pointer that is not a multiple of the write granularity does not
      * fall on a logical block boundary, so the guest can neither read nor write
include/block/block-io.h +6 -0
index f671476f08..deda6cab2b 100644
@@ -134,6 +134,12 @@ uint32_t bdrv_zone_index(BlockDriverState *bs, uint64_t offset);
  * bdrv_zone_is_full() this does not need the write pointer lock.
  */
 bool bdrv_zone_is_conv(BlockDriverState *bs, uint32_t index);
+/*
+ * The offset at which the writable part of a zone ends. That is a zone
+ * capacity beyond the start of the zone, except for a last zone that the
+ * capacity of the device cuts short.
+ */
+uint64_t bdrv_zone_writable_end(BlockDriverState *bs, uint32_t index);
 /*
  * True when the write pointer of a zone has reached the end of the writable
  * part of that zone, so that nothing more can be written to it until it is
include/block/block_int-common.h +12 -0
index 0c7746a544..ff9b36d12b 100644
@@ -57,6 +57,12 @@
 #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_ACTIVE_ZONES      "zone.max_active_zones"
+#define BLOCK_OPT_MAX_OPEN_ZONES        "zone.max_open_zones"
 
 #define BLOCK_PROBE_BUF_SIZE        512
 
@@ -911,6 +917,12 @@ typedef struct BlockLimits {
      */
     uint32_t zone_size_bits;
 
+    /*
+     * 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 +84 -2

116 lines not on this page · raw message

tests/qemu-iotests/031.out +4 -4
index 0054c2ed97..02a68b34f7 100644
@@ -117,7 +117,7 @@ header_length             112
 
 Header extension:
 magic                     0x6803f857 (Feature table)
-length                    384
+length                    432
 data                      <binary>
 
 Header extension:
@@ -150,7 +150,7 @@ header_length             112
 
 Header extension:
 magic                     0x6803f857 (Feature table)
-length                    384
+length                    432
 data                      <binary>
 
 Header extension:
@@ -164,7 +164,7 @@ No errors were found on the image.
 
 magic                     0x514649fb
 version                   3
-backing_file_offset       0x240
+backing_file_offset       0x270
 backing_file_size         0x17
 cluster_bits              16
 size                      67108864
@@ -188,7 +188,7 @@ data                      'host_device'
 
 Header extension:
 magic                     0x6803f857 (Feature table)
-length                    384
+length                    432
 data                      <binary>
 
 Header extension:
tests/qemu-iotests/036.out +2 -2
index 1fa7cad28d..3ee310bb61 100644
@@ -26,7 +26,7 @@ compatible_features       []
 autoclear_features        [63]
 Header extension:
 magic                     0x6803f857 (Feature table)
-length                    384
+length                    432
 data                      <binary>
 
 
@@ -38,7 +38,7 @@ compatible_features       []
 autoclear_features        []
 Header extension:
 magic                     0x6803f857 (Feature table)
-length                    384
+length                    432
 data                      <binary>
 
 *** done
tests/qemu-iotests/061.out +7 -7
index 951c6bf3e6..08bc08dd25 100644
@@ -26,7 +26,7 @@ header_length             112
 
 Header extension:
 magic                     0x6803f857 (Feature table)
-length                    384
+length                    432
 data                      <binary>
 
 magic                     0x514649fb
@@ -84,7 +84,7 @@ header_length             112
 
 Header extension:
 magic                     0x6803f857 (Feature table)
-length                    384
+length                    432
 data                      <binary>
 
 magic                     0x514649fb
@@ -140,7 +140,7 @@ header_length             112
 
 Header extension:
 magic                     0x6803f857 (Feature table)
-length                    384
+length                    432
 data                      <binary>
 
 ERROR cluster 5 refcount=0 reference=1
@@ -195,7 +195,7 @@ header_length             112
 
 Header extension:
 magic                     0x6803f857 (Feature table)
-length                    384
+length                    432
 data                      <binary>
 
 magic                     0x514649fb
@@ -264,7 +264,7 @@ header_length             112
 
 Header extension:
 magic                     0x6803f857 (Feature table)
-length                    384
+length                    432
 data                      <binary>
 
 read 65536/65536 bytes at offset 44040192
@@ -326,7 +326,7 @@ header_length             112
 
 Header extension:
 magic                     0x6803f857 (Feature table)
-length                    384
+length                    432
 data                      <binary>
 
 ERROR cluster 5 refcount=0 reference=1
@@ -355,7 +355,7 @@ header_length             112
 
 Header extension:
 magic                     0x6803f857 (Feature table)
-length                    384
+length                    432
 data                      <binary>
 
 read 131072/131072 bytes at offset 0
tests/qemu-iotests/082.out +108 -0

216 lines not on this page · raw message

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
Signature · 1 line
2.56.0
#3 lore raw

PATCH v15 3/7 block: define errnos for zone protocol errors

In reply to Niklas Cassel

A block driver that emulates zones (e.g. qcow2 with the zoned format feature) rejects requests that violate the zone protocol, and the device model has to report each of these to the guest with the matching zone error (ZAC/ZBC sense data, virtio-blk zone status codes, ...). It can only do so if each condition comes with an errno of its own, rather than a generic one such as EIO.

Define one for each condition:

  BLK_ZE_UNALIGNED_WRITE  ESPIPE        write not at the write pointer
  BLK_ZE_BOUNDARY         ERANGE        write past the zone capacity
  BLK_ZE_OPEN_RESOURCE    ETOOMANYREFS  open zone limit reached
  BLK_ZE_ACTIVE_RESOURCE  EOVERFLOW     active zone limit reached

ETOOMANYREFS and EOVERFLOW are what Linux returns for BLK_STS_ZONE_OPEN_RESOURCE and BLK_STS_ZONE_ACTIVE_RESOURCE, so a host zoned device used through file-posix already reports the same values. For the boundary case, ERANGE is used rather than EFBIG, which the host file system can legitimately return for an image file.

A write that is not at the write pointer gets ESPIPE, which file and block device I/O never return, rather than EINVAL, which a zoned driver also uses for invalid requests such as an invalid zone state transition. So a device model can map each of these errnos to its zone error without having to know which request failed.

ETOOMANYREFS is not POSIX, so provide a fallback for hosts that lack it.

---
 include/block/block-common.h | 16 ++++++++++++++++
 include/qemu/osdep.h         |  3 +++
 2 files changed, 19 insertions(+)
include/block/block-common.h +16 -0
index 3932ff8615..6e4b2eb3ce 100644
@@ -125,6 +125,22 @@ typedef struct BlockZoneDescriptor {
     BlockZoneState state;
 } BlockZoneDescriptor;
 
+/*
+ * Errors that zoned block drivers report for zone protocol violations, as
+ * positive errno values (drivers return them negated). Each condition has an
+ * errno of its own that zoned block drivers do not return for anything else,
+ * so that device models can report the matching zone error to the guest
+ * whichever request failed. In particular, EINVAL is not used, as it also
+ * reports invalid requests, such as an invalid zone state transition. The
+ * zone resource errors are the errnos Linux uses for BLK_STS_ZONE_OPEN_RESOURCE
+ * and BLK_STS_ZONE_ACTIVE_RESOURCE, so a host zoned device accessed through
+ * file-posix reports the same values.
+ */
+#define BLK_ZE_UNALIGNED_WRITE  ESPIPE       /* write not at write pointer */
+#define BLK_ZE_BOUNDARY         ERANGE       /* write past zone capacity */
+#define BLK_ZE_OPEN_RESOURCE    ETOOMANYREFS /* open zone limit reached */
+#define BLK_ZE_ACTIVE_RESOURCE  EOVERFLOW    /* active zone limit reached */
+
 /*
  * Track write pointers of a zone in bytes.
  */
include/qemu/osdep.h +3 -0
index 50c7ce33b6..7925c28ac3 100644
@@ -345,6 +345,9 @@ void QEMU_ERROR("code path is reachable")
 #if !defined(ESHUTDOWN)
 #define ESHUTDOWN 4099
 #endif
+#if !defined(ETOOMANYREFS)
+#define ETOOMANYREFS 4100
+#endif
 
 #define RETRY_ON_EINTR(expr) \
     (__extension__                                          \
Signature · 1 line
2.56.0
#4 lore raw

PATCH v15 4/7 qcow2: add zoned emulation capability

In reply to Niklas Cassel

From: Sam Li <[email protected]>

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.

---
Changes by Niklas Cassel:
- account for the zoned metadata in the refcount check, so that qemu-img check does not report the clusters it occupies as leaked
- reset and report the last zone of an image whose size is not a multiple of the zone size, which is shorter than the others
- clamp the write pointer that a zone finish leaves behind to the end of the writable part of the zone
- drop the zone append size limit, which the geometry now bounds
- report zone errors with the errnos from block-common.h instead of EIO, EINVAL and EBUSY: BLK_ZE_UNALIGNED_WRITE, BLK_ZE_BOUNDARY, BLK_ZE_OPEN_RESOURCE and BLK_ZE_ACTIVE_RESOURCE
- manage the zone resources as in the NVMe ZNS specification (2.1.1.4.1): a write to an empty zone checks the active zone limit also when the open zone limit is not reached, OPEN ZONE of an empty zone checks the open zone limit too, and an implicitly open zone is closed to make room regardless of the active zone limit, as it remains active
- manage the open zone resources for FINISH ZONE of an empty zone, as ZBC requires (ZBC-3 4.5.3.2.4)
- check the zone capacity before the zone resources, so that a write past the zone capacity does not close another zone
- drop the redundant zone capacity check for zone appends
- shorten two comments that were longer than 80 columns
- report the length of a conventional zone as its capacity, as the whole zone is writable; Linux refuses a disk with a conventional zone whose capacity is smaller than its length
- refuse a write that starts in a conventional zone and reaches a sequential zone, without writing any data (ZAC-3 4.7.2)
- remove a closed zone from the closed list when a write fills it, so that it no longer counts as an active zone

---
 block/qcow2-cache.c    |   11 +-
 block/qcow2-refcount.c |   18 +
 block/qcow2.c          | 1244 +++++++++++++++++++++++++++++++++++++++-
 block/qcow2.h          |    2 +
 block/trace-events     |    2 +
 5 files changed, 1271 insertions(+), 6 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 +18 -0
index df7f6d2f23..0f20fa353e 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;
 }
 
@@ -2304,6 +2311,17 @@ calculate_refcounts(BlockDriverState *bs, BdrvCheckResult *res,
         }
     }
 
+    /* zoned metadata */
+    if (s->zoned_header.zoned != QCOW2_Z_NONE) {
+        ret = qcow2_inc_refcounts_imrt(bs, res, refcount_table, nb_clusters,
+                                       s->zoned_header.zonedmeta_offset,
+                                       (int64_t)s->zoned_header.nr_zones *
+                                       sizeof(uint64_t));
+        if (ret < 0) {
+            return ret;
+        }
+    }
+
     /* bitmaps */
     ret = qcow2_check_bitmaps_refcounts(bs, res, refcount_table,
                                         nb_clusters, fix);
block/qcow2.c +1239 -5

1,347 lines not on this page · raw message

block/qcow2.h +2 -0
index 7757b98385..0092eb9e3d 100644
@@ -296,6 +296,8 @@ typedef struct Qcow2ZoneWPState {
     QTAILQ_HEAD(, Qcow2WPReq) in_flight;
     /* PENDING reqs, sorted by lba */
     QTAILQ_HEAD(, Qcow2WPReq) completed_pending;
+    /* zone mgmt ops wait here until in_flight has drained */
+    CoQueue drain;
 } Qcow2ZoneWPState;
 
 typedef struct Qcow2UnknownHeaderExtension {
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.56.0
#5 lore raw

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

In reply to Niklas Cassel

From: Sam Li <[email protected]>

The zoned format feature can be tested by:

$ tests/qemu-iotests/check -qcow2 zoned-qcow2

---
Changes by Niklas Cassel:
- drop the zone append size limit from the image the test creates
- test, on a second image with zone resource limits, that each zone error is reported with its own errno, and the zone resource management of writes, OPEN ZONE and FINISH ZONE
- test that a zoned image needs version 3 and zones of whole clusters, and that resetting a zone leaves the data of the other zones alone
- test that a closed zone that a write fills no longer counts as an active zone
- list the test in the qcow2 section of MAINTAINERS

---
 MAINTAINERS                              |   1 +
 tests/qemu-iotests/tests/zoned-qcow2     | 322 +++++++++++++++++++++++
 tests/qemu-iotests/tests/zoned-qcow2.out | 258 ++++++++++++++++++
 3 files changed, 581 insertions(+)
 create mode 100755 tests/qemu-iotests/tests/zoned-qcow2
 create mode 100644 tests/qemu-iotests/tests/zoned-qcow2.out
MAINTAINERS +1 -0
index 4ca1751e30..f870adfb11 100644
@@ -4518,6 +4518,7 @@ L: [email protected]
 S: Supported
 F: block/qcow2*
 F: docs/interop/qcow2.rst
+F: tests/qemu-iotests/tests/zoned-qcow2*
 
 qcow
 M: Kevin Wolf <[email protected]>
tests/qemu-iotests/tests/zoned-qcow2 new file +322 -0

322 lines not on this page · raw message

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

258 lines not on this page · raw message

Signature · 1 line
2.56.0
#6 lore raw

PATCH v15 6/7 qcow2: validate the write pointer table when opening an image

In reply to Niklas Cassel

The write pointer table is image content, and qcow2_refresh_zonedmeta() byte swaps it straight into bs->wps without looking at it. Every other zoned field is checked before it becomes driver state, but the table that those fields describe is not.

A write pointer is the offset that an append to its zone is written to. qcow2_co_pwv_part() takes it as start_offset and only rejects a pointer that reaches past the end of its zone, so a pointer that sits below the start of its zone passes and the data is written into an earlier zone that the guest never asked to write. The write pointer is then stored back, spreading the damage. A pointer that is not sector aligned is equally unusable: it is reported to a guest shifted right by BDRV_SECTOR_BITS, so the guest is told about a position it can never write to and the zone can only be recovered by resetting it.

Check the table against the geometry the header already declares: the conventional bit is set for exactly the zones the header calls conventional, a conventional zone records its own start, and the write pointer of a sequential zone is sector aligned and within the writable part of that zone, which is shorter for the last zone of an image whose capacity is not a multiple of the zone size.

---
 block/qcow2.c                            | 67 ++++++++++++++++++++++++
 tests/qemu-iotests/tests/zoned-qcow2     | 40 ++++++++++++++
 tests/qemu-iotests/tests/zoned-qcow2.out |  9 +++-
 3 files changed, 115 insertions(+), 1 deletion(-)
block/qcow2.c +67 -0
index 225ca1775e..8d4ea97172 100644
@@ -520,6 +520,67 @@ qcow2_refresh_zonedmeta(BlockDriverState *bs)
     return 0;
 }
 
+/*
+ * The write pointer table is image content and cannot be trusted. Check it
+ * against the zone geometry, which qcow2_check_zone_options() has already
+ * validated. The write pointer of a zone is the offset that an append to that
+ * zone is written to, so a corrupted table would otherwise misdirect a write:
+ * qcow2_co_pwv_part() only rejects a pointer that reaches beyond the end of
+ * its zone, and one that points below the start of its zone would send the
+ * data to a zone that the guest never asked to write.
+ */
+static bool qcow2_check_zonedmeta(BlockDriverState *bs, Error **errp)
+{
+    BDRVQcow2State *s = bs->opaque;
+    uint32_t conv_zones = s->zoned_header.conventional_zones;
+    uint64_t zone_size = s->zoned_header.zone_size;
+    uint64_t capacity = (uint64_t)bs->total_sectors * BDRV_SECTOR_SIZE;
+
+    for (uint32_t i = 0; i < s->zoned_header.nr_zones; i++) {
+        uint64_t wp = bs->wps->wp[i];
+        uint64_t zone_start = (uint64_t)i * zone_size;
+        bool is_conv = QCOW2_ZT_IS_CONV(wp);
+        uint64_t zone_end;
+
+        if (is_conv != (i < conv_zones)) {
+            error_setg(errp, "Zone %" PRIu32 " contradicts the header, which "
+                       "declares the first %" PRIu32 " zones conventional",
+                       i, conv_zones);
+            return false;
+        }
+
+        if (is_conv) {
+            if (QCOW2_GET_WP(wp) != zone_start) {
+                error_setg(errp, "Conventional zone %" PRIu32 " has write "
+                           "pointer 0x%" PRIx64 " instead of the zone start "
+                           "0x%" PRIx64, i, (uint64_t)QCOW2_GET_WP(wp),
+                           zone_start);
+                return false;
+            }
+            continue;
+        }
+
+        /* The last zone is shorter when the capacity is not zone aligned */
+        zone_end = zone_start + MIN(s->zoned_header.zone_capacity,
+                                    capacity - zone_start);
+
+        if (wp < zone_start || wp > zone_end) {
+            error_setg(errp, "Zone %" PRIu32 " has write pointer 0x%" PRIx64
+                       " outside its writable range 0x%" PRIx64 "..0x%" PRIx64,
+                       i, wp, zone_start, zone_end);
+            return false;
+        }
+
+        if (!QEMU_IS_ALIGNED(wp, BDRV_SECTOR_SIZE)) {
+            error_setg(errp, "Zone %" PRIu32 " has write pointer 0x%" PRIx64
+                       " that is not sector aligned", i, wp);
+            return false;
+        }
+    }
+
+    return true;
+}
+
 /*
  * Returns true if zone_opt is valid for an image with clusters of
  * @cluster_size bytes, false otherwise.
@@ -938,6 +999,12 @@ qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
                 return ret;
             }
 
+            if (!qcow2_check_zonedmeta(bs, errp)) {
+                g_free(bs->wps);
+                bs->wps = NULL;
+                return -EINVAL;
+            }
+
             s->zone_list_entries = g_new0(Qcow2ZoneListEntry,
                                           zoned_ext.nr_zones);
             QTAILQ_INIT(&s->exp_open_zones);
tests/qemu-iotests/tests/zoned-qcow2 +40 -0
index cc89bd5337..0d25d47940 100755
@@ -316,6 +316,46 @@ zo 3M 1M
 zrp 0 4
 EOF
 
+echo
+echo "case 9: a corrupted write pointer table is rejected"
+$QEMU_IO $IMG -c "zrs 0 768M"
+
+# Walk the header extensions to find the zoned one, and read the offset of
+# the write pointer table out of it, rather than relying on a fixed layout.
+ext_off=$(peek_file_be "$file_name" 100 4)
+while true; do
+    ext_magic=$(peek_file_be "$file_name" $ext_off 4)
+    ext_len=$(peek_file_be "$file_name" $((ext_off + 4)) 4)
+    if [ "$ext_magic" -eq 0 ]; then
+        echo "no zoned header extension found"
+        break
+    fi
+    if [ "$ext_magic" -eq $((0x007a6264)) ]; then
+        # zoned(1) reserved(3) nr_zones(4) zone_size(8) zone_capacity(8)
+        wps=$(peek_file_be "$file_name" $((ext_off + 8 + 24)) 8)
+        break
+    fi
+    ext_off=$((ext_off + 8 + (ext_len + 7) / 8 * 8))
+done
+
+# Zone 3 starts at 0xc000000. A write pointer below the start of its own zone
+# is the dangerous one: an append would be redirected into an earlier zone.
+poke_file_be "$file_name" $((wps + 8 * 3)) 8 0
+$QEMU_IO $IMG -c "zrp 0 1"
+poke_file_be "$file_name" $((wps + 8 * 3)) 8 $((0xc000000))
+
+poke_file_be "$file_name" $((wps + 8 * 1)) 8 $((0x4000200 + 1))
+$QEMU_IO $IMG -c "zrp 0 1"
+poke_file_be "$file_name" $((wps + 8 * 1)) 8 $((0x4000000))
+
+# Set the conventional bit on a zone the header declares sequential
+poke_file_be "$file_name" $((wps + 8 * 2)) 1 $((0x80))
+$QEMU_IO $IMG -c "zrp 0 1"
+poke_file_be "$file_name" $((wps + 8 * 2)) 1 0
+
+echo "after restoring the table:"
+$QEMU_IO $IMG -c "zrp 0 1"
+
 # success, all done
 echo "*** done"
 rm -f $seq.full
tests/qemu-iotests/tests/zoned-qcow2.out +8 -1
index 0ac4934a62..f34af0102e 100644
@@ -255,4 +255,11 @@ qemu-io> qemu-io> qemu-io> start: 0x0, len 0x800, cap 0x800, wptr 0x800, zcond:1
 start: 0x800, len 0x800, cap 0x800, wptr 0x808, zcond:4, [type: 2]
 start: 0x1000, len 0x800, cap 0x800, wptr 0x1008, zcond:2, [type: 2]
 start: 0x1800, len 0x800, cap 0x800, wptr 0x1800, zcond:3, [type: 2]
-qemu-io> *** done
+qemu-io>
+case 9: a corrupted write pointer table is rejected
+qemu-io: can't open: Zone 3 has write pointer 0x0 outside its writable range 0xc000000..0x10000000
+qemu-io: can't open: Zone 1 has write pointer 0x4000201 that is not sector aligned
+qemu-io: can't open: Zone 2 contradicts the header, which declares the first 0 zones conventional
+after restoring the table:
+start: 0x0, len 0x20000, cap 0x20000, wptr 0x0, zcond:1, [type: 2]
+*** done
Signature · 1 line
2.56.0
#7 lore raw

PATCH v15 7/7 virtio-blk: report zone errors with their zone status codes

In reply to Niklas Cassel

virtio-blk completes a failed write with VIRTIO_BLK_S_IOERR, and a failed zone append or zone management request with VIRTIO_BLK_S_ZONE_INVALID_CMD. It never reports the zone status codes that virtio 1.4 (5.2.6.2) requires for a write off the write pointer or for a request that exceeds a zone resource limit.

When VIRTIO_BLK_F_ZONED is negotiated, map the zone errors of the block layer to them:

  BLK_ZE_UNALIGNED_WRITE  VIRTIO_BLK_S_ZONE_UNALIGNED_WP
  BLK_ZE_BOUNDARY         VIRTIO_BLK_S_ZONE_INVALID_CMD
  BLK_ZE_OPEN_RESOURCE    VIRTIO_BLK_S_ZONE_OPEN_RESOURCE
  BLK_ZE_ACTIVE_RESOURCE  VIRTIO_BLK_S_ZONE_ACTIVE_RESOURCE

Other errors keep their status code. A FINISH that exceeds a zone resource limit also gets a zone resource status code, which 5.2.6 defines for any zone operation. Zone errors of writes are reported regardless of the rerror/werror policy, as they are the deterministic result of the request.

---
 hw/block/virtio-blk.c | 48 +++++++++++++++++++++++++++++++++++++++----
 1 file changed, 44 insertions(+), 4 deletions(-)
hw/block/virtio-blk.c +44 -4
index 536d71a91a..1d35997f7e 100644
@@ -68,11 +68,44 @@ void virtio_blk_req_complete(VirtIOBlockReq *req, unsigned char status)
     virtio_notify(vdev, req->vq);
 }
 
+/*
+ * Map a zone error (see include/block/block-common.h) to its virtio-blk
+ * status, or return VIRTIO_BLK_S_OK if @error is not one.
+ */
+static uint8_t virtio_blk_zone_status(VirtIOBlock *s, int error)
+{
+    if (!virtio_vdev_has_feature(VIRTIO_DEVICE(s), VIRTIO_BLK_F_ZONED)) {
+        return VIRTIO_BLK_S_OK;
+    }
+
+    switch (error) {
+    case BLK_ZE_UNALIGNED_WRITE:
+        return VIRTIO_BLK_S_ZONE_UNALIGNED_WP;
+    case BLK_ZE_BOUNDARY:
+        return VIRTIO_BLK_S_ZONE_INVALID_CMD;
+    case BLK_ZE_OPEN_RESOURCE:
+        return VIRTIO_BLK_S_ZONE_OPEN_RESOURCE;
+    case BLK_ZE_ACTIVE_RESOURCE:
+        return VIRTIO_BLK_S_ZONE_ACTIVE_RESOURCE;
+    default:
+        return VIRTIO_BLK_S_OK;
+    }
+}
+
 static int virtio_blk_handle_rw_error(VirtIOBlockReq *req, int error,
                                       bool is_read)
 {
     VirtIOBlock *s = req->dev;
-    BlockErrorAction action = blk_get_error_action(s->blk, is_read, error);
+    uint8_t zone_status = virtio_blk_zone_status(s, error);
+    /*
+     * Zone errors are the deterministic result of the request, so they are
+     * reported whatever the rerror/werror policy: stopping the VM would only
+     * make the request fail the same way again when it is retried on resume,
+     * and ignoring the error would hide the failure from the guest.
+     */
+    BlockErrorAction action = zone_status != VIRTIO_BLK_S_OK ?
+                              BLOCK_ERROR_ACTION_REPORT :
+                              blk_get_error_action(s->blk, is_read, error);
 
     if (action == BLOCK_ERROR_ACTION_STOP) {
         /* Break the link as the next request is going to be parsed from the
@@ -84,7 +117,8 @@ static int virtio_blk_handle_rw_error(VirtIOBlockReq *req, int error,
             s->rq = req;
         }
     } else if (action == BLOCK_ERROR_ACTION_REPORT) {
-        virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);
+        virtio_blk_req_complete(req, zone_status != VIRTIO_BLK_S_OK ?
+                                     zone_status : VIRTIO_BLK_S_IOERR);
         block_acct_failed(blk_get_stats(s->blk), &req->acct);
         g_free(req);
     }
@@ -767,7 +801,10 @@ static void virtio_blk_zone_mgmt_complete(void *opaque, int ret)
     trace_virtio_blk_zone_mgmt_complete(vdev, req,ret);
 
     if (ret) {
-        err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
+        err_status = virtio_blk_zone_status(s, -ret);
+        if (err_status == VIRTIO_BLK_S_OK) {
+            err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
+        }
     }
 
     virtio_blk_req_complete(req, err_status);
@@ -827,7 +864,10 @@ static void virtio_blk_zone_append_complete(void *opaque, int ret)
     uint8_t err_status = VIRTIO_BLK_S_OK;
 
     if (ret) {
-        err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
+        err_status = virtio_blk_zone_status(s, -ret);
+        if (err_status == VIRTIO_BLK_S_OK) {
+            err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
+        }
         goto out;
     }
 
Signature · 1 line
2.56.0