qcow2: Suppress data-file WRITE during creation
v2 cover qcow2: Suppress data-file WRITE during creation
Hi,
Some people want to create a qcow2 image for an existing raw image while that raw image is in use by a VM. That is, the raw image is attached to a guest device, and the new qcow2 image is supposed to use it as its raw external data file.
This series makes that work by relaxing the permissions taken by the qcow2 driver on the external data file during qcow2 image creation, i.e. no longer taking the WRITE flag (unless preallocation was requested), which allows simultaneous use of the file e.g. as a raw image attached to the VM.
The v1 cover letter with some more info is here:
https://lists.nongnu.org/archive/html/qemu-block/2026-02/msg00090.html
v2:
- Drop the new flags, use BDRV_O_NO_IO and !BDRV_O_RESIZE instead
- This necessitates making qcow2_do_open() attach the data-file child even with BDRV_O_NO_IO if the "data-file" option is a string (i.e. a node name), that's patch 2
- It also requires bypassing the block layer for resizing the qcow2 image, i.e. we need to call qcow2_co_truncate() directly instead of going through blk_co_truncate(), that's patch 4
- Fixed the typing in patch 3 for a subtraction (should have cast both new_length and m->offset to int64_t, not just the latter)
- Proper locking around bdrv_co_getlength()
- Check bdrv_co_getlength() against (int64_t)qcow2_opts->size to catch error cases (instead of not casting the latter and having the former underflow)
- Fixed f-string compatibility in the new test
git-backport-diff against v1:
Key:
[----] : patches are identical
[####] : number of functional differences between upstream/downstream patch [down] : patch is downstream-only
The flags [FC] indicate (F)unctional and (C)ontextual differences, respectively
001/6:[----] [--] 'qcow2: Skip data-file resize if possible' 002/6:[down] 'qcow2: Always attach data-file given by node name' 003/6:[0006] [FC] 'qcow2: Preallocation: Do not COW after disk end' 004/6:[down] 'qcow2: Call qcow2_co_truncate() directly' 005/6:[0058] [FC] 'qcow2: Suppress data-file WRITE/RESIZE if possible' 006/6:[0030] [FC] 'iotests: Add qcow2-live-data-file test'
Hanna Czenczek (6):
qcow2: Skip data-file resize if possible
qcow2: Always attach data-file given by node name
qcow2: Preallocation: Do not COW after disk end
qcow2: Call qcow2_co_truncate() directly
qcow2: Suppress data-file WRITE/RESIZE if possible
iotests: Add qcow2-live-data-file test
block/qcow2.c | 145 +- tests/qemu-iotests/125 | 17 +- tests/qemu-iotests/206.out | 6 +- tests/qemu-iotests/tests/qcow2-live-data-file | 280 ++ .../tests/qcow2-live-data-file.out | 2904 +++++++++++++++++ 5 files changed, 3324 insertions(+), 28 deletions(-) create mode 100755 tests/qemu-iotests/tests/qcow2-live-data-file create mode 100644 tests/qemu-iotests/tests/qcow2-live-data-file.out
Signature · 1 line
2.53.0
PATCH v2 1/6 qcow2: Skip data-file resize if possible
With PREALLOC_MODE_OFF, we currently always resize the data file to the right length. This is definitely not necessary if it already has the correct length, and if @exact is false, we also don't need to shrink it.
This is what other preallocation modes already do: preallocate_co() only increases the data file size if it is too small, but never shrinks it. (And note that for raw data files, PREALLOC_MODE_OFF is silently turned into PREALLOC_MODE_METADATA, so this commit only changes behavior for non-raw external data files.)
For the next commits, having all preallocation modes behave the same will make it easier to decide when we can skip taking the RESIZE permission on the data-file child.
--- block/qcow2.c | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-)
block/qcow2.c +11 -4
@@ -4572,15 +4572,22 @@ qcow2_co_truncate(BlockDriverState *bs, int64_t offset, bool exact,switch (prealloc) {case PREALLOC_MODE_OFF :if (has_data_file (bs)) { +int64_t data_file_length =bdrv_co_getlength (s->data_file->bs); +/* * If the caller wants an exact resize, the external data * file should be resized to the exact target size, too, * so we pass @exact here. +* Without @exact, we leave it as-is if it is already big enough. +* Implicitly handle bdrv_co_getlength() errors by resizing. */ - ret =bdrv_co_truncate (s->data_file, offset, exact, prealloc,0 , - errp); -if (ret <0 ) { - goto fail; +if (data_file_length < offset || + (exact && data_file_length != offset)) { + ret =bdrv_co_truncate (s->data_file, offset, exact, prealloc,0 , + errp); +if (ret <0 ) { + goto fail; + } } }break ;
Signature · 1 line
2.53.0
PATCH v2 2/6 qcow2: Always attach data-file given by node name
In reply to Hanna CzenczekWith BDRV_O_NO_IO, we suppress opening data-file to prevent opening unchecked paths through qemu-img info. However, a future commit will make qcow2_co_create() pass BDRV_O_NO_IO for the new image if possible, and then we need data-file attached to be able to query its size.
qcow2_co_create() already has the data-file open, so it specifies it by node name; and if we get the data-file by node name, there is no security risk attaching it because it is already open.
So check whether the data-file option is a string, i.e. a node name, and if so, allow attaching it despite BDRV_O_NO_IO.
--- block/qcow2.c | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-)
block/qcow2.c +18 -8
@@ -1410,6 +1410,7 @@ qcow2_do_open(BlockDriverState *bs, QDict *options, int flags,uint64_t ext_end;uint64_t l1_vm_state_index;bool update_header = false; +bool suppress_data_file = false; ret =bdrv_co_pread (bs->file,0 ,sizeof (header), &header,0 );if (ret <0 ) {
@@ -1719,14 +1720,23 @@ qcow2_do_open(BlockDriverState *bs, QDict *options, int flags, goto fail; } -if (open_data_file && (flags &BDRV_O_NO_IO )) { -/* -* Don't open the data file for 'qemu-img info' so that it can be used -* to verify that an untrusted qcow2 image doesn't refer to external -* files. -* -* Note: This still makes has_data_file() return true. -*/ +/* +* Don't open the data file for 'qemu-img info' so that it can be used +* to verify that an untrusted qcow2 image doesn't refer to external +* files. +* +* Exception: If the data-file option is a node name, attaching that +* node will not open a new file, so cannot pose a security risk. +* +* Note: This still makes has_data_file() return true. +*/ +if (flags &BDRV_O_NO_IO ) { +QObject *data_file =qdict_get (options,"data-file" ); + suppress_data_file = + !data_file ||qobject_type (data_file) !=QTYPE_QSTRING ; + } + +if (open_data_file && suppress_data_file) {if (s->incompatible_features &QCOW2_INCOMPAT_DATA_FILE ) { s->data_file =NULL ; }else {
Signature · 1 line
2.53.0
PATCH v2 3/6 qcow2: Preallocation: Do not COW after disk end
In reply to Hanna CzenczekWhen creating/resizing an image with/to a non-cluster-aligned length, we currently implicitly COW the cluster tail after the guest disk end. That is unnecessary, but more importantly, when creating a qcow2 image for a pre-existing external raw data file, we should not write to it unless data preallocation was requested.
So far, writing to the data file past the guest disk end during qcow2 image creation may just be a peculiarity. But this series will make qcow2 use the BDRV_O_NO_IO flag to suppress taking the WRITE flag on the data file during image creation, to allow users to create a qcow2 image with an existing raw image as its data file that is currently in use by the VM (i.e. the WRITE flag is unshared). To make this work, we really must not write to the data file at all during creation, unless data preallocation (falloc/full) has been requested.
(The comment added in this commit therefore primarily reasons with the use of that flag, and how we must not break it. Admittedly, that only makes sense after the corresponding patch in this series.)
Note that this means that creating/resizing images with/to a guest disk size that is not aligned to clusters will create a partial data cluster at the image end when preallocating (except for falloc/full preallocation without a data file). I think that is fine, similarly to how creating a non-preallocated image will generally leave a partial cluster at the end, too (the L1 table).
It does mean iotest 125 needs to be adjusted, though.
--- block/qcow2.c | 18 ++++++++++++++++++ tests/qemu-iotests/125 | 17 +++++++++++------ 2 files changed, 29 insertions(+), 6 deletions(-)
block/qcow2.c +18 -0
@@ -3378,7 +3378,25 @@ preallocate_co(BlockDriverState *bs, uint64_t offset, uint64_t new_length, }for (m = meta; m !=NULL ; m = m->next) { +int64_t disk_end_ofs; + m->prealloc = true; + +/* +* Do not COW beyond the supposed image end: There is no point, and +* it could break BDRV_O_NO_IO from qcow2_co_create(): +* qcow2_alloc_host_offset() does not COW anything for the range we +* pass, but everything outside. If growing to a non-cluster +* aligned size, it will thus request COW beyond the image end, +* breaking the BDRV_O_NO_IO promise. +* (As long as the @offset passed to this function was aligned to +* full clusters, that is the only possible instance of COW. With +* qcow2_co_create(), it's always 0, so always aligned.) +*/ + disk_end_ofs = (int64_t )new_length - (int64_t )m->offset; +if (m->cow_end.offset + m->cow_end.nb_bytes > disk_end_ofs) { + m->cow_end.nb_bytes =MAX (disk_end_ofs - m->cow_end.offset,0 ); + } } ret =qcow2_handle_l2meta (bs, &meta, true);
tests/qemu-iotests/125 +11 -6
@@ -172,10 +172,10 @@ done # Test image resizing using preallocation and unaligned offsets $QEMU_IMG create -f raw "$TEST_IMG.base" 128k | _filter_img_create $QEMU_IO -c 'write -q -P 1 0 128k' -f raw "$TEST_IMG.base" -for orig_size in 31k 33k; do - for dst_size in 96k 128k; do +for orig_size in $((31 * 1024)) $((33 * 1024)); do + for dst_size in $((96 * 1024)) $((128 * 1024)); do for prealloc in metadata full; do - echo "--- Resizing image from $orig_size to $dst_size (preallocation=$prealloc) ---" + echo "--- Resizing image from $((orig_size / 1024))k to $((dst_size / 1024))k (preallocation=$prealloc) ---" _make_test_img -F raw -b "$TEST_IMG.base" -o cluster_size=64k "$orig_size" $QEMU_IMG resize -f "$IMGFMT" --preallocation="$prealloc" "$TEST_IMG" "$dst_size" # The first part of the image should contain data from the backing file
@@ -183,10 +183,15 @@ for orig_size in 31k 33k; do # The resized part of the image should contain zeroes $QEMU_IO -c "read -q -P 0 ${orig_size} 63k" "$TEST_IMG" # If the image does not have an external data file we can also verify its - # actual size. The resized image should have 7 clusters: - # header, L1 table, L2 table, refcount table, refcount block, 2 data clusters + # actual size. The resized image should have 5 metadata clusters + # (header, L1 table, L2 table, refcount table, refcount block) + # plus the data. We round up that data to full clusters for full + # preallocation, but not for metadata preallocation. if ! _get_data_file "$TEST_IMG" > /dev/null; then - expected_file_length=$((65536 * 7)) + expected_file_length=$((65536 * 5 + dst_size)) + if [ "$prealloc" = full ]; then + expected_file_length=$(((expected_file_length + 65535) / 65536 * 65536)) + fi file_length=$(stat -c '%s' "$TEST_IMG_FILE") if [ "$file_length" != "$expected_file_length" ]; then echo "ERROR: file length $file_length (expected $expected_file_length)"
Signature · 1 line
2.53.0
PATCH v2 4/6 qcow2: Call qcow2_co_truncate() directly
In reply to Hanna Czenczekbdrv_co_truncate() checks that BDRV_O_NO_IO is not set and that the RESIZE permission is available. However, after this series:
- We want to set the BDRV_O_NO_IO flag in cases where we can ensure that no I/O will occur to/from the data file, to allow concurrent use of the data file while a qcow2 metadata image is put on top.
- We want to take the RESIZE permission only when we are actually going to resize the data file, i.e. when it is not big enough yet.
By calling qcow2_co_truncate() directly, we bypass these checks. That is OK because qcow2_co_create() is the sole owner and user of this qcow2 BDS. (For example, taking the right permissions on it does not matter if it is impossible for there to be another user.)
Note that qcow2_co_truncate() takes a signed int64_t, whereas qcow2_opts->size is uint64_t, so we should add an explicit check for overflow. iotest 206's output changes accordingly.
--- block/qcow2.c | 17 +++++++++++++++-- tests/qemu-iotests/206.out | 6 +++--- 2 files changed, 18 insertions(+), 5 deletions(-)
block/qcow2.c +15 -2
@@ -82,6 +82,10 @@ qcow2_co_preadv_compressed(BlockDriverState *bs,QEMUIOVector *qiov, size_t qiov_offset); +static int coroutine_fn GRAPH_RDLOCK +qcow2_co_truncate (BlockDriverState *bs,int64_t offset,bool exact, +PreallocMode prealloc,BdrvRequestFlags flags,Error **errp); +static int qcow2_probe (const uint8_t *buf,int buf_size,const char *filename) {const QCowHeader *cow_header = (const void *)buf;
@@ -3657,6 +3661,13 @@ qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp) goto out; } +if (qcow2_opts->size >BDRV_MAX_LENGTH ) { +error_setg (errp,"Image size must not exceed %" PRId64" bytes" , +BDRV_MAX_LENGTH ); + ret = -EINVAL ; + goto out; + } +if (qcow2_opts->has_version) {switch (qcow2_opts->version) {case BLOCKDEV_QCOW2_VERSION_V2 :
@@ -3939,8 +3950,10 @@ qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp) }/* Okay, now that we have a valid image, let's give it the right size */ - ret =blk_co_truncate (blk, qcow2_opts->size, false, - qcow2_opts->preallocation,0 , errp); +bdrv_graph_co_rdlock (); + ret =qcow2_co_truncate (blk_bs (blk), qcow2_opts->size, false, + qcow2_opts->preallocation,0 , errp); +bdrv_graph_co_rdunlock ();if (ret <0 ) {error_prepend (errp,"Could not resize image: " ); goto out;
tests/qemu-iotests/206.out +3 -3
@@ -169,19 +169,19 @@ Job failed: Image size must be a multiple of 512 bytes {"execute": "blockdev-create", "arguments": {"job-id": "job0", "options": {"driver": "qcow2", "file": "node0", "size": 18446744073709551104}}} {"return": {}} -Job failed: Could not resize image: Image size cannot be negative +Job failed: Image size must not exceed 9223372035781033984 bytes {"execute": "job-dismiss", "arguments": {"id": "job0"}} {"return": {}} {"execute": "blockdev-create", "arguments": {"job-id": "job0", "options": {"driver": "qcow2", "file": "node0", "size": 9223372036854775808}}} {"return": {}} -Job failed: Could not resize image: Image size cannot be negative +Job failed: Image size must not exceed 9223372035781033984 bytes {"execute": "job-dismiss", "arguments": {"id": "job0"}} {"return": {}} {"execute": "blockdev-create", "arguments": {"job-id": "job0", "options": {"driver": "qcow2", "file": "node0", "size": 9223372036854775296}}} {"return": {}} -Job failed: Could not resize image: offset(9223372036854775296) exceeds maximum(9223372035781033984) +Job failed: Image size must not exceed 9223372035781033984 bytes {"execute": "job-dismiss", "arguments": {"id": "job0"}} {"return": {}}
Signature · 1 line
2.53.0
PATCH v2 5/6 qcow2: Suppress data-file WRITE/RESIZE if possible
In reply to Hanna CzenczekWhen formatting a qcow2 image, we only need the WRITE permission on the data-file child to preallocate data, so for metadata-only preallocation (or none at all), we can suppress that permission via the BDRV_O_NO_IO flag. That promises to actually not do any I/O at all, but writing is actually the only thing we would do, so it applies. (BDRV_O_NO_IO does not preclude reading/writing from/to the metadata file.)
Similarly, we will only resize the data-file if it is currently smaller than the supposed virtual disk size; so it is already big enough, we can suppress the RESIZE permission by removing the BDRV_O_RESIZE flag.
This commit allows creating a qcow2 image with an existing raw image as its external data file while that raw image is in use by the VM.
--- block/qcow2.c | 69 +++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 64 insertions(+), 5 deletions(-)
block/qcow2.c +64 -5
@@ -3641,6 +3641,7 @@ qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp)size_t cluster_size;int version;int refcount_order; +int blk_flags;uint64_t *refcount_table;int ret;uint8_t compression_type =QCOW2_COMPRESSION_TYPE_ZLIB ;
@@ -3908,20 +3909,48 @@ qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp)* table) */ options =qdict_new (); + blk_flags =BDRV_O_RDWR |BDRV_O_RESIZE |BDRV_O_NO_FLUSH ;qdict_put_str (options,"driver" ,"qcow2" );qdict_put_str (options,"file" , bs->node_name);if (data_bs) {qdict_put_str (options,"data-file" , data_bs->node_name); + +/* +* If possible, suppress all permissions we can. We must keep the +* BDRV_O_RDWR flag because the metadata child must still be written, +* but we can add BDRV_O_NO_IO if we know that the data file child will +* not receive any I/O, to suppress taking the WRITE permission on it. +* We can only do so as long as none of the operations on `blk` will +* do I/O on the data file. Such I/O accesses can only happen during +* resize (which grows the image from length 0 to qcow2_opts->size) with +* data preallocation. So as long as no data preallocation has been +* requested, BDRV_O_NO_IO will work. +*/ +if (qcow2_opts->preallocation ==PREALLOC_MODE_METADATA || + qcow2_opts->preallocation ==PREALLOC_MODE_OFF ) { + blk_flags |=BDRV_O_NO_IO ; + } + +/* +* Similarly for BDRV_O_RESIZE: Suppressing it means we will not take +* the RESIZE permission. The data-file child is only grown if too +* small, never shrunk; so if it already is big enough, no need for +* BDRV_O_RESIZE. +*/ +bdrv_graph_co_rdlock (); +if (bdrv_co_getlength (data_bs) >= (int64_t )qcow2_opts->size) { + blk_flags &= ~BDRV_O_RESIZE ; + } +bdrv_graph_co_rdunlock (); } - blk =blk_co_new_open (NULL ,NULL , options, -BDRV_O_RDWR |BDRV_O_RESIZE |BDRV_O_NO_FLUSH , - errp); + blk =blk_co_new_open (NULL ,NULL , options, blk_flags, errp);if (blk ==NULL ) { ret = -EIO ; goto out; }bdrv_graph_co_rdlock (); +/* BDRV_O_NO_IO note: No data-file I/O */ ret =qcow2_alloc_clusters (blk_bs (blk),3 * cluster_size);if (ret <0 ) {bdrv_graph_co_rdunlock ();
@@ -3940,7 +3969,10 @@ qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp) s->image_data_file =g_strdup (data_bs->filename); } -/* Create a full header (including things like feature table) */ +/* +* Create a full header (including things like feature table). +* BDRV_O_NO_IO note: No data-file I/O +*/ ret =qcow2_update_header (blk_bs (blk));bdrv_graph_co_rdunlock ();
@@ -3949,7 +3981,13 @@ qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp) goto out; } -/* Okay, now that we have a valid image, let's give it the right size */ +/* +* Okay, now that we have a valid image, let's give it the right size. +* BDRV_O_NO_IO note: This will only read/write from/to data-file if data +* preallocation has been requested. +* BDRV_O_RESIZE note: We pass @exact = false, so the data-file is only +* resized if it is smaller than qcow2_opts->size. +*/ bdrv_graph_co_rdlock (); ret =qcow2_co_truncate (blk_bs (blk), qcow2_opts->size, false, qcow2_opts->preallocation,0 , errp);
@@ -3968,6 +4006,7 @@ qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp) }bdrv_graph_co_rdlock (); +/* BDRV_O_NO_IO note: No data-file I/O */ ret =bdrv_co_change_backing_file (blk_bs (blk), qcow2_opts->backing_file, backing_format, false);bdrv_graph_co_rdunlock ();
@@ -3983,6 +4022,7 @@ qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp)/* Want encryption? There you go. */ if (qcow2_opts->encrypt) {bdrv_graph_co_rdlock (); +/* BDRV_O_NO_IO note: No data-file I/O */ ret =qcow2_set_up_encryption (blk_bs (blk), qcow2_opts->encrypt, errp);bdrv_graph_co_rdunlock ();
@@ -4481,6 +4521,15 @@ fail:return ret; } +/** +* Resize the qcow2 image. +* To support BDRV_O_NO_IO and !BDRV_O_RESIZE from qcow2_co_create(), this +* function must: +* - If @exact is false, resize an external data file only if its size is less +* than @offset +* - Only access (write to) an external data file if @prealloc prescribes data +* preallocation (FALLOC/FULL). +*/ static int coroutine_fn GRAPH_RDLOCKqcow2_co_truncate (BlockDriverState *bs,int64_t offset,bool exact,PreallocMode prealloc,BdrvRequestFlags flags,Error **errp)
@@ -4634,6 +4683,11 @@ qcow2_co_truncate(BlockDriverState *bs, int64_t offset, bool exact,break ;case PREALLOC_MODE_METADATA : +/* +* Note for BDRV_O_NO_IO and !BDRV_O_RESIZE: This will not do I/O on an +* external data file, and will only resize it if its current length is +* less than `offset`. +*/ ret =preallocate_co (bs, old_length, offset, prealloc, errp);if (ret <0 ) { goto fail;
@@ -4652,6 +4706,11 @@ qcow2_co_truncate(BlockDriverState *bs, int64_t offset, bool exact,/* With a data file, preallocation means just allocating the metadata * and forwarding the truncate request to the data file */ if (has_data_file (bs)) { +/* +* Note for BDRV_O_NO_IO and !BDRV_O_RESIZE: This *will* write data +* to an external data file, but only resize it if its current +* length is less than `offset`. +*/ ret =preallocate_co (bs, old_length, offset, prealloc, errp);if (ret <0 ) { goto fail;
Signature · 1 line
2.53.0
PATCH v2 6/6 iotests: Add qcow2-live-data-file test
In reply to Hanna CzenczekWhile a raw image is attached to a VM, create a pure-metadata qcow2 image with that raw image as its data file, and then replace the raw image by the qcow2 image.
--- tests/qemu-iotests/tests/qcow2-live-data-file | 280 ++ .../tests/qcow2-live-data-file.out | 2904 +++++++++++++++++ 2 files changed, 3184 insertions(+) create mode 100755 tests/qemu-iotests/tests/qcow2-live-data-file create mode 100644 tests/qemu-iotests/tests/qcow2-live-data-file.out
tests/qemu-iotests/tests/qcow2-live-data-file new file +280 -0
@@ -0,0 +1,280 @@ +#!/usr/bin/env python3 +# group: rw +# +# Given a raw image file already attached to a VM, create a qcow2 file with +# that image as its external (raw) data file, and replace the raw image by +# the qcow2 image. +# +# Copyright (C) 2026 Red Hat, Inc. +# +# SPDX-License-Identifier: GPL-2.0-or-later +# +# Creator/Owner: Hanna Czenczek <[email protected]> + +from enum import Enum, auto +import re +import iotests +from iotests import log, qemu_img, qemu_img_log, qemu_io_log + +iotests.script_initialize( + supported_fmts=['qcow2'], + unsupported_imgopts=['compat'], +) + +DISK_SIZE = 64 * 1024 * 1024 + +class CreateException(Exception): + pass + +class GuestDiskType(Enum): + VIRTIO_BLK = auto() + SCSI_HD = auto() + SCSI_CD = auto() + +def do_test( + vm: iotests.VM, + with_raw_node: bool, + guest_disk_type: GuestDiskType, + preallocation: str, + qcow2_size: int, + raw_img_path: str, + qcow2_img_path: str, +) -> None: + log('=== do_test() ===') + log(f' - with_raw_node={with_raw_node}') + log(f' - guest_disk_type={guest_disk_type}') + log(f' - preallocation={preallocation}') + log(f' - qcow2_size={qcow2_size}') + + log('') + log('--- Setting up raw image ---') + qemu_img('create', '-f', 'raw', raw_img_path, str(DISK_SIZE)) + + log('') + log('--- Launching VM ---') + + vm.add_blockdev(vm.qmp_to_opts({ + 'driver': 'file', + 'node-name': 'protocol', + 'filename': raw_img_path, + })) + + if with_raw_node: + vm.add_blockdev(vm.qmp_to_opts({ + 'driver': 'raw', + 'node-name': 'raw', + 'file': 'protocol', + })) + raw_node = 'raw' + else: + raw_node = 'protocol' + + dev_id = 'sda' + qom_path = f'/machine/peripheral/{dev_id}' + if guest_disk_type == GuestDiskType.VIRTIO_BLK: + vm.add_device(f'virtio-blk,id={dev_id},drive={raw_node}') + dev_id = f'{qom_path}/virtio-backend' + elif guest_disk_type == GuestDiskType.SCSI_HD: + vm.add_device('virtio-scsi') + vm.add_device(f'scsi-hd,id={dev_id},drive={raw_node}') + elif guest_disk_type == GuestDiskType.SCSI_CD: + vm.add_device('virtio-scsi') + vm.add_device(f'scsi-cd,id={dev_id},drive={raw_node}') + + vm.launch() + + log('') + log('--- Creating qcow2 image ---') + + create_and_open(vm, { + 'driver': 'file', + 'filename': qcow2_img_path, + }, { + 'size': 0, + }, { + 'node-name': 'qcow2-protocol', + }) + + create_and_open(vm, { + 'driver': 'qcow2', + 'file': 'qcow2-protocol', + 'data-file': 'protocol', + }, { + 'data-file-raw': True, + 'size': qcow2_size, + 'preallocation': preallocation, + }, { + 'node-name': 'qcow2', + }) + + cmd = 'aio_write -P 42 0 4M' + log(f'[HMP qemu-io: {cmd}]') + log(vm.qmp( + 'human-monitor-command', + command_line=f'qemu-io -d {dev_id} "{cmd}"', + )) + + if with_raw_node: + log('[blockdev-reopen]') + log(vm.qmp('blockdev-reopen', { + 'options': [{ + 'driver': 'raw', + 'node-name': 'raw', + 'file': 'qcow2', + }], + })) + else: + log('[qom-set]') + log(vm.qmp('qom-set', { + 'path': qom_path, + 'property': 'drive', + 'value': 'qcow2', + })) + + cmd = 'aio_flush' + log(f'[HMP qemu-io: {cmd}]') + log(vm.qmp( + 'human-monitor-command', + command_line=f'qemu-io -d {dev_id} {cmd}', + )) + + vm.shutdown() + + qlog = vm.get_log() + if qlog is not None: + log('[qemu log]') + qlog = iotests.filter_qemu_io(iotests.filter_qtest(qlog)) + log(qlog) + + log('[qemu-img check]') + qemu_img_log('check', '-f', 'qcow2', qcow2_img_path) + + cmd = 'read -P 42 0 4M' + log(f'[qemu-io: {cmd}]') + qemu_io_log(qcow2_img_path, '-c', cmd) + +def create_and_open( + vm: iotests.VM, + base_options: dict[str, object], + create_options: dict[str, object], + open_options: dict[str, object], +) -> None: + driver = base_options['driver'] + log(f'[blockdev-create: {driver}]') + log(vm.qmp('blockdev-create', { + 'job-id': 'create', + 'options': base_options | create_options, + })) + + while True: + event = vm.event_wait( + name='JOB_STATUS_CHANGE', + match={'data': {'id': 'create'}}, + ) + assert event is not None + status = event['data']['status'] + log(f' -> {status}') + if status == 'aborting': + jobs = vm.qmp('query-jobs')['return'] + job_info = next(job for job in jobs if job['id'] == 'create') + error = re.sub(r'#block\d+', '#blockXXX', job_info['error']) + log(f'blockdev-create failed: {error}') + raise CreateException(error) + if status == 'concluded': + break + + log('[job-dismiss]') + log(vm.qmp('job-dismiss', id='create')) + log('[blockdev-add]') + log(vm.qmp('blockdev-add', base_options | open_options)) + +def verify_exception( + exception: CreateException, + conflicting_permissions: list[str], + with_raw_node: bool, + guest_disk_type: GuestDiskType, +) -> None: + if with_raw_node: + user = "node 'raw'" + user_child = 'file' + elif guest_disk_type == GuestDiskType.VIRTIO_BLK: + user = "block device '/machine/peripheral/sda/virtio-backend'" + user_child = 'root' + else: + user = "block device 'sda'" + user_child = 'root' + + refstr = ( + "Permission conflict on node 'protocol': permissions " + f"'{', '.join(conflicting_permissions)}' are both required by node " + "'#blockXXX' (uses node 'protocol' as 'data-file' child) and unshared " + f"by {user} (uses node 'protocol' as '{user_child}' child)." + ) + + if str(exception) != refstr: + log("Exception differs from reference:") + log(f'Is: {exception}') + log(f'Expected: {refstr}') + assert str(exception) == refstr + +def run_test( + with_raw_node: bool, + guest_disk_type: GuestDiskType, + preallocation: str, + qcow2_size: int, +) -> None: + with iotests.FilePath('raw.img') as raw_img_path, \ + iotests.FilePath('metadata.qcow2') as qcow2_img_path, \ + iotests.VM() as vm: + try: + do_test( + vm, + with_raw_node, + guest_disk_type, + preallocation, + qcow2_size, + raw_img_path, + qcow2_img_path, + ) + except CreateException as e: + expected_conflicting_perms = [] + + if preallocation in ('falloc', 'full'): + # Data preallocation must fail because it must write to the + # data file, requiring the WRITE permission. + # For a data file, the WRITE permission implies the RESIZE + # permission. CD does not allow resizing, so it will conflict + # on both WRITE and RESIZE. + if guest_disk_type == GuestDiskType.SCSI_CD: + expected_conflicting_perms += ['write', 'resize'] + else: + expected_conflicting_perms += ['write'] + elif guest_disk_type == GuestDiskType.SCSI_CD and \ + qcow2_size > DISK_SIZE: + # CD does not allow resizing, but creating a bigger qcow2 image + # would require growing the raw image, necessitating the RESIZE + # permission. (Creating a smaller qcow2 however will not + # shrink it.) + expected_conflicting_perms += ['resize'] + + if not expected_conflicting_perms: + raise e + + verify_exception(e, expected_conflicting_perms, + with_raw_node, guest_disk_type) + log('(Handled expected exception)') + log('') + + +def run_all_test_combinations(): + for with_raw_node in (False, True): + for guest_disk_type in GuestDiskType: + for preallocation in ('off', 'metadata', 'falloc', 'full'): + # Sprinkle in -512 and +512 to verify that non-cluster-aligned + # sizes work, too + for qcow2_size in (DISK_SIZE, DISK_SIZE // 2 - 512, + DISK_SIZE * 2 + 512): + run_test(with_raw_node, guest_disk_type, preallocation, + qcow2_size) + +run_all_test_combinations()
tests/qemu-iotests/tests/qcow2-live-data-file.out new file +2904 -0
2,720 lines not on this page · raw message
The rest of this diff is not shown. View the raw message.
Signature · 1 line
2.53.0
Part of the diff is not shown here. View the raw message.