Block layer patches
Subsystems (2)
[Qemu-devel] [PULL 002/100] block: Guarantee that *file is set on bdrv_get_block_status()
In reply to Kevin WolfFrom: Eric Blake <[email protected]>
We document that *file is valid if the return is not an error and includes BDRV_BLOCK_OFFSET_VALID, but forgot to obey this contract when a driver (such as blkdebug) lacks a callback. Messed up in commit 67a0fd2 (v2.6), when we added the file parameter.
Enhance qemu-iotest 177 to cover this, using a sequence that would print garbage or even SEGV, because it was dererefencing through uninitialized memory. [The resulting test output shows that we have less-than-ideal block status from the blkdebug driver, but that's a separate fix coming up soon.]
Setting *file on all paths that return BDRV_BLOCK_OFFSET_VALID is enough to fix the crash, but we can go one step further: always setting *file, even on error, means that a broken caller that blindly dereferences file without checking for error is now more likely to get a reliable SEGV instead of randomly acting on garbage, making it easier to diagnose such buggy callers. Adding an assertion that file is set where expected doesn't hurt either.
--- block/io.c | 5 +++-- tests/qemu-iotests/177 | 3 +++ tests/qemu-iotests/177.out | 2 ++ 3 files changed, 8 insertions(+), 2 deletions(-)
block/io.c +3 -2
@@ -1734,6 +1734,7 @@ static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs,int64_t n;int64_t ret, ret2; + *file =NULL ; total_sectors =bdrv_nb_sectors (bs);if (total_sectors <0 ) {return total_sectors;
@@ -1757,11 +1758,11 @@ static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs, }if (bs->drv->protocol_name) { ret |=BDRV_BLOCK_OFFSET_VALID | (sector_num *BDRV_SECTOR_SIZE ); + *file = bs; }return ret; } - *file =NULL ;bdrv_inc_in_flight (bs); ret = bs->drv->bdrv_co_get_block_status (bs, sector_num, nb_sectors, pnum, file);
@@ -1771,7 +1772,7 @@ static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs, }if (ret &BDRV_BLOCK_RAW ) { -assert (ret &BDRV_BLOCK_OFFSET_VALID ); +assert (ret &BDRV_BLOCK_OFFSET_VALID && *file); ret =bdrv_co_get_block_status (*file, ret >>BDRV_SECTOR_BITS , *pnum, pnum, file); goto out;
tests/qemu-iotests/177 +3 -0
@@ -43,6 +43,7 @@ _supported_proto file CLUSTER_SIZE=1M size=128M options=driver=blkdebug,image.driver=qcow2 +nested_opts=image.file.driver=file,image.file.filename=$TEST_IMG echo echo "== setting up files =="
@@ -106,6 +107,8 @@ function verify_io() } verify_io | $QEMU_IO -r "$TEST_IMG" | _filter_qemu_io +$QEMU_IMG map --image-opts "$options,$nested_opts,align=4k" \ + | _filter_qemu_img_map _check_test_img
tests/qemu-iotests/177.out +2 -0
@@ -45,5 +45,7 @@ read 30408704/30408704 bytes at offset 80740352 29 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec) read 23068672/23068672 bytes at offset 111149056 22 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec) +Offset Length File +0 0x8000000 json:{"image": {"driver": "IMGFMT", "file": {"driver": "file", "filename": "TEST_DIR/t.IMGFMT"}}, "driver": "blkdebug", "align": "4k"} No errors were found on the image. *** done
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 003/100] block: Simplify use of BDRV_BLOCK_RAW
In reply to Kevin WolfFrom: Eric Blake <[email protected]>
The lone caller that cares about a return of BDRV_BLOCK_RAW (namely, io.c:bdrv_co_get_block_status) completely replaces the return value, so there is no point in passing BDRV_BLOCK_DATA.
--- block/commit.c | 2 +- block/mirror.c | 2 +- block/raw-format.c | 2 +- block/vpc.c | 2 +- include/block/block.h | 6 +++--- 5 files changed, 7 insertions(+), 7 deletions(-)
block/commit.c +1 -1
@@ -253,7 +253,7 @@ static int64_t coroutine_fn bdrv_commit_top_get_block_status( { *pnum = nb_sectors; *file = bs->backing->bs; -return BDRV_BLOCK_RAW |BDRV_BLOCK_OFFSET_VALID |BDRV_BLOCK_DATA | +return BDRV_BLOCK_RAW |BDRV_BLOCK_OFFSET_VALID | (sector_num <<BDRV_SECTOR_BITS ); }
block/mirror.c +1 -1
@@ -1058,7 +1058,7 @@ static int64_t coroutine_fn bdrv_mirror_top_get_block_status( { *pnum = nb_sectors; *file = bs->backing->bs; -return BDRV_BLOCK_RAW |BDRV_BLOCK_OFFSET_VALID |BDRV_BLOCK_DATA | +return BDRV_BLOCK_RAW |BDRV_BLOCK_OFFSET_VALID | (sector_num <<BDRV_SECTOR_BITS ); }
block/raw-format.c +1 -1
@@ -259,7 +259,7 @@ static int64_t coroutine_fn raw_co_get_block_status(BlockDriverState *bs, *pnum = nb_sectors; *file = bs->file->bs; sector_num += s->offset /BDRV_SECTOR_SIZE ; -return BDRV_BLOCK_RAW |BDRV_BLOCK_OFFSET_VALID |BDRV_BLOCK_DATA | +return BDRV_BLOCK_RAW |BDRV_BLOCK_OFFSET_VALID | (sector_num <<BDRV_SECTOR_BITS ); }
block/vpc.c +1 -1
@@ -701,7 +701,7 @@ static int64_t coroutine_fn vpc_co_get_block_status(BlockDriverState *bs,if (be32_to_cpu (footer->type) ==VHD_FIXED ) { *pnum = nb_sectors; *file = bs->file->bs; -return BDRV_BLOCK_RAW |BDRV_BLOCK_OFFSET_VALID |BDRV_BLOCK_DATA | +return BDRV_BLOCK_RAW |BDRV_BLOCK_OFFSET_VALID | (sector_num <<BDRV_SECTOR_BITS ); }
include/block/block.h +3 -3
@@ -132,9 +132,9 @@ typedef struct HDGeometry {* BDRV_BLOCK_EOF: the returned pnum covers through end of file for this layer * * Internal flag: -* BDRV_BLOCK_RAW: used internally to indicate that the request was -* answered by a passthrough driver such as raw and that the -* block layer should recompute the answer from bs->file. +* BDRV_BLOCK_RAW: for use by passthrough drivers, such as raw, to request +* that the block layer recompute the answer from the returned +* BDS; must be accompanied by just BDRV_BLOCK_OFFSET_VALID. * * If BDRV_BLOCK_OFFSET_VALID is set, bits 9-62 (BDRV_BLOCK_OFFSET_MASK) * represent the offset in the returned BDS that is allocated for the
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 004/100] blkdebug: Support .bdrv_co_get_block_status
In reply to Kevin WolfFrom: Eric Blake <[email protected]>
Without a passthrough status of BDRV_BLOCK_RAW, anything wrapped by blkdebug appears 100% allocated as data. Better is treating it the same as the underlying file being wrapped.
Update iotest 177 for the new expected output.
--- block/blkdebug.c | 11 +++++++++++ tests/qemu-iotests/177.out | 5 ++++- 2 files changed, 15 insertions(+), 1 deletion(-)
block/blkdebug.c +11 -0
@@ -641,6 +641,16 @@ static int coroutine_fn blkdebug_co_pdiscard(BlockDriverState *bs,return bdrv_co_pdiscard (bs->file->bs, offset, bytes); } +static int64_t coroutine_fn blkdebug_co_get_block_status( +BlockDriverState *bs,int64_t sector_num,int nb_sectors,int *pnum, +BlockDriverState **file) +{ + *pnum = nb_sectors; + *file = bs->file->bs; +return BDRV_BLOCK_RAW |BDRV_BLOCK_OFFSET_VALID | + (sector_num <<BDRV_SECTOR_BITS ); +} +static void blkdebug_close (BlockDriverState *bs) {BDRVBlkdebugState *s = bs->opaque;
@@ -915,6 +925,7 @@ static BlockDriver bdrv_blkdebug = { .bdrv_co_flush_to_disk = blkdebug_co_flush, .bdrv_co_pwrite_zeroes = blkdebug_co_pwrite_zeroes, .bdrv_co_pdiscard = blkdebug_co_pdiscard, + .bdrv_co_get_block_status = blkdebug_co_get_block_status, .bdrv_debug_event = blkdebug_debug_event, .bdrv_debug_breakpoint = blkdebug_debug_breakpoint,
tests/qemu-iotests/177.out +4 -1
@@ -46,6 +46,9 @@ read 30408704/30408704 bytes at offset 80740352 read 23068672/23068672 bytes at offset 111149056 22 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec) Offset Length File -0 0x8000000 json:{"image": {"driver": "IMGFMT", "file": {"driver": "file", "filename": "TEST_DIR/t.IMGFMT"}}, "driver": "blkdebug", "align": "4k"} +0 0x800000 TEST_DIR/t.IMGFMT +0x900000 0x2400000 TEST_DIR/t.IMGFMT +0x3c00000 0x1100000 TEST_DIR/t.IMGFMT +0x6a00000 0x1600000 TEST_DIR/t.IMGFMT No errors were found on the image. *** done
Signature · 1 line
1.8.3.1
The following changes since commit b11365867568ba954de667a0bfe0945b8f78d6bd:
Merge remote-tracking branch 'remotes/borntraeger/tags/s390x-20170706' into staging (2017-07-06 11:42:59 +0100)
are available in the git repository at:
git://repo.or.cz/qemu/kevin.git tags/for-upstream
for you to fetch changes up to 7d982302db173616d011e07ee43be3b0aae872b1:
Merge remote-tracking branch 'mreitz/tags/pull-block-2017-07-07' into queue-block (2017-07-07 18:11:41 +0200)
----------------------------------------------------------------
Block layer patches
----------------------------------------------------------------
Daniel P. Berrange (26):
qemu-img: drop -e and -6 options from the 'create' & 'convert' commands
block: expose crypto option names / defs to other drivers
block: add ability to set a prefix for opt names
qcow: document another weakness of qcow AES encryption
qcow: require image size to be > 1 for new images
iotests: skip 042 with qcow which dosn't support zero sized images
iotests: skip 048 with qcow which doesn't support resize
block: deprecate "encryption=on" in favor of "encrypt.format=aes"
qcow: make encrypt_sectors encrypt in place
qcow: convert QCow to use QCryptoBlock for encryption
qcow2: make qcow2_encrypt_sectors encrypt in place
qcow2: convert QCow2 to use QCryptoBlock for encryption
qcow2: extend specification to cover LUKS encryption
qcow2: add support for LUKS encryption format
qcow2: add iotests to cover LUKS encryption support
iotests: enable tests 134 and 158 to work with qcow (v1)
block: rip out all traces of password prompting
block: remove all encryption handling APIs
block: pass option prefix down to crypto layer
qcow2: report encryption specific image information
docs: document encryption options for qcow, qcow2 and luks
iotests: skip 159 & 170 with luks format
iotests: fix remainining tests to work with LUKS
iotests: reduce PBKDF iterations when testing LUKS
iotests: add more LUKS hash combination tests
iotests: chown LUKS device before qemu-io launches
Eric Blake (26):
qemu-io: Don't die on second open
block: Guarantee that *file is set on bdrv_get_block_status()
block: Simplify use of BDRV_BLOCK_RAW
blkdebug: Support .bdrv_co_get_block_status
blockjob: Track job ratelimits via bytes, not sectors
trace: Show blockjob actions via bytes, not sectors
stream: Switch stream_populate() to byte-based
stream: Drop reached_end for stream_complete()
stream: Switch stream_run() to byte-based
commit: Switch commit_populate() to byte-based
commit: Switch commit_run() to byte-based
mirror: Switch MirrorBlockJob to byte-based
mirror: Switch mirror_do_zero_or_discard() to byte-based
mirror: Update signature of mirror_clip_sectors()
mirror: Switch mirror_cow_align() to byte-based
mirror: Switch mirror_do_read() to byte-based
mirror: Switch mirror_iteration() to byte-based
block: Drop unused bdrv_round_sectors_to_clusters()
backup: Switch BackupBlockJob to byte-based
backup: Switch block_backup.h to byte-based
backup: Switch backup_do_cow() to byte-based
backup: Switch backup_run() to byte-based
block: Make bdrv_is_allocated() byte-based
block: Minimize raw use of bds->total_sectors
block: Make bdrv_is_allocated_above() byte-based
tests: Avoid non-portable 'echo -ARG'
Hervé Poussineau (13):
vvfat: fix qemu-img map and qemu-img convert
vvfat: replace tabs by 8 spaces
vvfat: fix typos
vvfat: rename useless enumeration values
vvfat: introduce offset_to_bootsector, offset_to_fat and offset_to_root_dir
vvfat: fix field names in FAT12/FAT16 and FAT32 boot sectors
vvfat: always create . and .. entries at first and in that order
vvfat: correctly create long names for non-ASCII filenames
vvfat: correctly create base short names for non-ASCII filenames
vvfat: correctly generate numeric-tail of short file names
vvfat: limit number of entries in root directory in FAT12/FAT16
vvfat: handle KANJI lead byte 0xe5
vvfat: change OEM name to 'MSWIN4.1'
Kevin Wolf (1):
Merge remote-tracking branch 'mreitz/tags/pull-block-2017-07-07' into queue-block
Max Reitz (3):
iotests: 181 does not work for all formats
iotests: Use absolute paths for executables
iotests: Add test for colon handling
Thomas Huth (1):
blockdev: Print a warning for legacy drive options that belong to -device
Vladimir Sementsov-Ogievskiy (30):
specs/qcow2: fix bitmap granularity qemu-specific note specs/qcow2: do not use wording 'bitmap header'
hbitmap: improve dirty iter
tests: add hbitmap iter test
block: fix bdrv_dirty_bitmap_granularity signature block/dirty-bitmap: add deserialize_ones func
qcow2-refcount: rename inc_refcounts() and make it public
qcow2: add bitmaps extension
block/dirty-bitmap: fix comment for BlockDirtyBitmap.disabled field block/dirty-bitmap: add readonly field to BdrvDirtyBitmap
qcow2: autoloading dirty bitmaps
block: refactor bdrv_reopen_commit
block: new bdrv_reopen_bitmaps_rw interface
qcow2: support .bdrv_reopen_bitmaps_rw block/dirty-bitmap: add autoload field to BdrvDirtyBitmap
block: bdrv_close: release bitmaps after drv->bdrv_close
block: introduce persistent dirty bitmaps block/dirty-bitmap: add bdrv_dirty_bitmap_next()
qcow2: add persistent dirty bitmaps support
qcow2: store bitmaps on reopening image as read-only
block: add bdrv_can_store_new_dirty_bitmap
qcow2: add .bdrv_can_store_new_dirty_bitmap
qmp: add persistent flag to block-dirty-bitmap-add
qmp: add autoload parameter to block-dirty-bitmap-add
qmp: add x-debug-block-dirty-bitmap-sha256
iotests: test qcow2 persistent dirty bitmap block/dirty-bitmap: add bdrv_remove_persistent_dirty_bitmap
qcow2: add .bdrv_remove_persistent_dirty_bitmap
qmp: block-dirty-bitmap-remove: remove persistent
block: release persistent bitmaps on inactivate
sochin.jiang (1):
mirror: Fix inconsistent backing AioContext for after mirroring
block.c | 143 +-- block/Makefile.objs | 2 +- block/backup.c | 128 +-- block/blkdebug.c | 11 + block/commit.c | 56 +- block/crypto.c | 97 +- block/crypto.h | 101 ++ block/dirty-bitmap.c | 154 ++- block/io.c | 110 +- block/mirror.c | 310 ++--- block/qapi.c | 2 +- block/qcow.c | 269 ++--- block/qcow2-bitmap.c | 1481 ++++++++++++++++++++++++ block/qcow2-cluster.c | 66 +- block/qcow2-refcount.c | 69 +- block/qcow2.c | 653 +++++++++-- block/qcow2.h | 60 +- block/raw-format.c | 2 +- block/replication.c | 29 +- block/stream.c | 37 +- block/trace-events | 14 +- block/vpc.c | 2 +- block/vvfat.c | 2336 ++++++++++++++++++++------------------ blockdev.c | 124 +- crypto/block-luks.c | 8 +- crypto/block-qcow.c | 8 +- crypto/block.c | 6 +- crypto/blockpriv.h | 2 + docs/interop/qcow2.txt | 111 +- hmp-commands.hx | 2 + hmp.c | 31 - include/block/block.h | 22 +- include/block/block_backup.h | 11 +- include/block/block_int.h | 17 +- include/block/dirty-bitmap.h | 22 +- include/crypto/block.h | 6 +- include/monitor/monitor.h | 7 - include/qapi/error.h | 1 - include/qemu/hbitmap.h | 49 +- include/qemu/osdep.h | 2 - include/qemu/ratelimit.h | 3 +- migration/block.c | 16 +- monitor.c | 68 -- qapi-schema.json | 10 +- qapi/block-core.json | 172 ++- qapi/common.json | 5 +- qemu-doc.texi | 123 +- qemu-img.c | 76 +- qemu-img.texi | 19 +- qemu-io-cmds.c | 70 +- qemu-io.c | 27 +- qemu-options.hx | 13 +- qmp.c | 12 +- tests/Makefile.include | 2 +- tests/multiboot/run_test.sh | 10 +- tests/qemu-iotests/033 | 12 +- tests/qemu-iotests/042 | 2 +- tests/qemu-iotests/048 | 2 +- tests/qemu-iotests/049 | 2 +- tests/qemu-iotests/049.out | 102 +- tests/qemu-iotests/051 | 7 +- tests/qemu-iotests/060.out | 1 + tests/qemu-iotests/068 | 2 +- tests/qemu-iotests/082.out | 284 ++++- tests/qemu-iotests/085.out | 38 +- tests/qemu-iotests/087 | 39 +- tests/qemu-iotests/087.out | 16 +- tests/qemu-iotests/114.out | 5 +- tests/qemu-iotests/120 | 1 + tests/qemu-iotests/126 | 105 ++ tests/qemu-iotests/126.out | 23 + tests/qemu-iotests/134 | 20 +- tests/qemu-iotests/134.out | 10 +- tests/qemu-iotests/140 | 9 +- tests/qemu-iotests/142 | 48 +- tests/qemu-iotests/144.out | 4 +- tests/qemu-iotests/145 | 19 +- tests/qemu-iotests/149 | 25 +- tests/qemu-iotests/149.out | 1002 +++++++++++----- tests/qemu-iotests/153.out | 6 + tests/qemu-iotests/157 | 17 +- tests/qemu-iotests/157.out | 16 +- tests/qemu-iotests/158 | 21 +- tests/qemu-iotests/158.out | 14 +- tests/qemu-iotests/159 | 1 + tests/qemu-iotests/165 | 105 ++ tests/qemu-iotests/165.out | 5 + tests/qemu-iotests/170 | 1 + tests/qemu-iotests/171 | 14 +- tests/qemu-iotests/174 | 2 +- tests/qemu-iotests/177 | 3 + tests/qemu-iotests/177.out | 5 + tests/qemu-iotests/181 | 23 +- tests/qemu-iotests/185.out | 8 +- tests/qemu-iotests/188 | 76 ++ tests/qemu-iotests/188.out | 18 + tests/qemu-iotests/189 | 86 ++ tests/qemu-iotests/189.out | 26 + tests/qemu-iotests/check | 18 +- tests/qemu-iotests/common | 10 +- tests/qemu-iotests/common.config | 11 + tests/qemu-iotests/common.filter | 3 +- tests/qemu-iotests/common.qemu | 9 +- tests/qemu-iotests/common.rc | 3 + tests/qemu-iotests/group | 4 + tests/rocker/all | 10 +- tests/tcg/cris/Makefile | 8 +- tests/test-crypto-block.c | 8 +- tests/test-hbitmap.c | 19 + util/hbitmap.c | 51 +- util/oslib-posix.c | 66 -- util/oslib-win32.c | 24 - 112 files changed, 6714 insertions(+), 2942 deletions(-) create mode 100644 block/crypto.h create mode 100644 block/qcow2-bitmap.c create mode 100755 tests/qemu-iotests/126 create mode 100644 tests/qemu-iotests/126.out create mode 100755 tests/qemu-iotests/165 create mode 100644 tests/qemu-iotests/165.out create mode 100755 tests/qemu-iotests/188 create mode 100644 tests/qemu-iotests/188.out create mode 100755 tests/qemu-iotests/189 create mode 100644 tests/qemu-iotests/189.out
[Qemu-devel] [PULL 001/100] qemu-io: Don't die on second open
From: Eric Blake <[email protected]>
Most callback commands in qemu-io return 0 to keep the interpreter loop running, or 1 to quit immediately. However, open_f() just passed through the return value of openfile(), which has different semantics of returning 0 if a file was opened, or 1 on any failure.
As a result of mixing the return semantics, we are forcing the qemu-io interpreter to exit early on any failures, which is rather annoying when some of the failures are obviously trying to give the user a hint of how to proceed (if we didn't then kill qemu-io out from under the user's feet):
$ qemu-io qemu-io> open foo qemu-io> open foo file open already, try 'help close' $ echo $? 0
In general, we WANT openfile() to report failures, since it is the function used in the form 'qemu-io -c "$something" no_such_file' for performing one or more -c options on a single file, and it is not worth attempting $something if the file itself cannot be opened. So the solution is to fix open_f() to always return 0 (when we are in interactive mode, even failure to open should not end the session), and save the return value of openfile() for command line use in main().
Note, however, that we do have some qemu-iotests that do 'qemu-io -c "open file" -c "$something"'; such tests will now proceed to attempt $something whether or not the open succeeded, the same way as if the two commands had been attempted in interactive mode. As such, the expected output for those tests has to be modified. But it also means that it is now possible to use -c close and have a single qemu-io command line operate on more than one file even without using interactive mode. Although the '-c open' action is a subtle change in behavior, remember that qemu-io is for debugging purposes, so as long as it serves the needs of qemu-iotests while still being reasonable for interactive use, it should not be a problem that we are changing tests to the new behavior.
This has been awkward since at least as far back as commit e3aff4f, in 2009.
--- qemu-io.c | 7 ++++--- tests/qemu-iotests/060.out | 1 + tests/qemu-iotests/114.out | 5 +++-- tests/qemu-iotests/153.out | 6 ++++++ 4 files changed, 14 insertions(+), 5 deletions(-)
qemu-io.c +4 -3
@@ -230,13 +230,14 @@ static int open_f(BlockBackend *blk, int argc, char **argv)qemu_opts_reset (&empty_opts);if (optind == argc -1 ) { -return openfile (argv[optind], flags, writethrough, force_share, opts); +openfile (argv[optind], flags, writethrough, force_share, opts); }else if (optind == argc) { -return openfile (NULL , flags, writethrough, force_share, opts); +openfile (NULL , flags, writethrough, force_share, opts); }else {QDECREF (opts); -return qemuio_command_usage (&open_cmd); +qemuio_command_usage (&open_cmd); } +return 0 ; }static int quit_f (BlockBackend *blk,int argc,char **argv)
tests/qemu-iotests/060.out +1 -0
@@ -21,6 +21,7 @@ Format specific information: refcount bits: 16 corrupt: true can't open device TEST_DIR/t.IMGFMT: IMGFMT: Image is corrupt; cannot be opened read/write +no file open, try 'help open' read 512/512 bytes at offset 0 512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
tests/qemu-iotests/114.out +3 -2
@@ -1,6 +1,6 @@ QA output created by 114 -Formatting 'TEST_DIR/t.IMGFMT.base', fmt=IMGFMT size=67108864 -Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file=TEST_DIR/t.IMGFMT.base +Formatting 'TEST_DIR/t.IMGFMT.base', fmt=IMGFMT size=67108864 +Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file=TEST_DIR/t.IMGFMT.base image: TEST_DIR/t.IMGFMT file format: IMGFMT virtual size: 64M (67108864 bytes)
@@ -8,6 +8,7 @@ cluster_size: 65536 backing file: TEST_DIR/t.IMGFMT.base backing file format: foo can't open device TEST_DIR/t.qcow2: Could not open backing file: Unknown driver 'foo' +no file open, try 'help open' read 4096/4096 bytes at offset 0 4 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec) *** done
tests/qemu-iotests/153.out +6 -0
@@ -33,10 +33,12 @@ Is another process using the image? _qemu_io_wrapper -c open TEST_DIR/t.qcow2 -c read 0 512 can't open device TEST_DIR/t.qcow2: Failed to get "write" lock Is another process using the image? +no file open, try 'help open' _qemu_io_wrapper -c open -r TEST_DIR/t.qcow2 -c read 0 512 can't open device TEST_DIR/t.qcow2: Failed to get shared "write" lock Is another process using the image? +no file open, try 'help open' _qemu_img_wrapper info TEST_DIR/t.qcow2 qemu-img: Could not open 'TEST_DIR/t.qcow2': Failed to get shared "write" lock
@@ -99,6 +101,7 @@ _qemu_io_wrapper -U -r -c read 0 512 TEST_DIR/t.qcow2 _qemu_io_wrapper -c open -U TEST_DIR/t.qcow2 -c read 0 512 can't open device TEST_DIR/t.qcow2: force-share=on can only be used with read-only images +no file open, try 'help open' _qemu_io_wrapper -c open -r -U TEST_DIR/t.qcow2 -c read 0 512
@@ -166,6 +169,7 @@ _qemu_io_wrapper -r -c read 0 512 TEST_DIR/t.qcow2 _qemu_io_wrapper -c open TEST_DIR/t.qcow2 -c read 0 512 can't open device TEST_DIR/t.qcow2: Failed to get "write" lock Is another process using the image? +no file open, try 'help open' _qemu_io_wrapper -c open -r TEST_DIR/t.qcow2 -c read 0 512
@@ -214,6 +218,7 @@ _qemu_io_wrapper -U -r -c read 0 512 TEST_DIR/t.qcow2 _qemu_io_wrapper -c open -U TEST_DIR/t.qcow2 -c read 0 512 can't open device TEST_DIR/t.qcow2: force-share=on can only be used with read-only images +no file open, try 'help open' _qemu_io_wrapper -c open -r -U TEST_DIR/t.qcow2 -c read 0 512
@@ -313,6 +318,7 @@ _qemu_io_wrapper -U -r -c read 0 512 TEST_DIR/t.qcow2 _qemu_io_wrapper -c open -U TEST_DIR/t.qcow2 -c read 0 512 can't open device TEST_DIR/t.qcow2: force-share=on can only be used with read-only images +no file open, try 'help open' _qemu_io_wrapper -c open -r -U TEST_DIR/t.qcow2 -c read 0 512
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 005/100] vvfat: fix qemu-img map and qemu-img convert
In reply to Kevin WolfFrom: Hervé Poussineau <[email protected]>
- bs->total_sectors is the number of sectors of the whole disk
- s->sector_count is the number of sectors of the FAT partition
This fixes the following assert in qemu-img map:
qemu-img.c:2641: get_block_status: Assertion `nb_sectors' failed.
This also fixes an infinite loop in qemu-img convert.
--- block/vvfat.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
block/vvfat.c +1 -2
@@ -2968,8 +2968,7 @@ vvfat_co_pwritev(BlockDriverState *bs, uint64_t offset, uint64_t bytes, static int64_t coroutine_fn vvfat_co_get_block_status(BlockDriverState *bs,int64_t sector_num,int nb_sectors,int *n,BlockDriverState **file) { -BDRVVVFATState * s = bs->opaque; - *n = s->sector_count - sector_num; + *n = bs->total_sectors - sector_num;if (*n > nb_sectors) { *n = nb_sectors; }else if (*n <0 ) {
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 007/100] vvfat: fix typos
In reply to Kevin WolfFrom: Hervé Poussineau <[email protected]>
--- block/vvfat.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
block/vvfat.c +4 -4
@@ -403,9 +403,9 @@ static void init_mbr(BDRVVVFATState *s, int cyls, int heads, int secs)/* FAT12/FAT16/FAT32 */ /* DOS uses different types when partition is LBA, probably to prevent older versions from using CHS on them */ - partition->fs_type= s->fat_type==12 ?0x1 : - s->fat_type==16 ? (lba?0xe :0x06 ): -/*fat_tyoe==32*/ (lba?0xc :0x0b ); + partition->fs_type = s->fat_type ==12 ?0x1 : + s->fat_type ==16 ? (lba ?0xe :0x06 ) : +/*s->fat_type == 32*/ (lba ?0xc :0x0b ); real_mbr->magic[0 ]=0x55 ; real_mbr->magic[1 ]=0xaa ; }
@@ -805,7 +805,7 @@ static int read_directory(BDRVVVFATState* s, int mapping_index) (ROOT_ENTRIES - cur) * sizeof(direntry_t)); } -/* reget the mapping, since s->mapping was possibly realloc()ed */ +/* re-get the mapping, since s->mapping was possibly realloc()ed */ mapping =array_get (&(s->mapping), mapping_index); first_cluster += (s->directory.next - mapping->info.dir.first_dir_index) *0x20 / s->cluster_size;
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 008/100] vvfat: rename useless enumeration values
In reply to Kevin WolfFrom: Hervé Poussineau <[email protected]>
MODE_FAKED and MODE_RENAMED are not and were never used.
--- block/vvfat.c | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-)
block/vvfat.c +8 -5
@@ -286,8 +286,7 @@ typedef struct mapping_t {union {/* offset is * - the offset in the file (in clusters) for a file, or -* - the next cluster of the directory for a directory, and -* - the address of the buffer for a faked entry +* - the next cluster of the directory for a directory */ struct {uint32_t offset;
@@ -300,9 +299,13 @@ typedef struct mapping_t {/* path contains the full path, i.e. it always starts with s->path */ char * path; -enum {MODE_UNDEFINED =0 ,MODE_NORMAL =1 ,MODE_MODIFIED =2 , -MODE_DIRECTORY =4 ,MODE_FAKED =8 , -MODE_DELETED =16 ,MODE_RENAMED =32 } mode; +enum { +MODE_UNDEFINED =0 , +MODE_NORMAL =1 , +MODE_MODIFIED =2 , +MODE_DIRECTORY =4 , +MODE_DELETED =8 , + } mode;int read_only; } mapping_t;
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 010/100] vvfat: fix field names in FAT12/FAT16 and FAT32 boot sectors
In reply to Kevin WolfFrom: Hervé Poussineau <[email protected]>
Specification: "FAT: General overview of on-disk format" v1.03, pages 11-13
--- block/vvfat.c | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-)
block/vvfat.c +14 -7
@@ -217,23 +217,30 @@ typedef struct bootsector_t {union {struct {uint8_t drive_number; -uint8_t current_head; +uint8_t reserved1;uint8_t signature;uint32_t id;uint8_t volume_label[11 ]; +uint8_t fat_type[8 ]; +uint8_t ignored[0x1c0 ]; } QEMU_PACKED fat16;struct {uint32_t sectors_per_fat;uint16_t flags;uint8_t major,minor; -uint32_t first_cluster_of_root_directory; +uint32_t first_cluster_of_root_dir;uint16_t info_sector;uint16_t backup_boot_sector; -uint16_t ignored; +uint8_t reserved[12 ]; +uint8_t drive_number; +uint8_t reserved1; +uint8_t signature; +uint32_t id; +uint8_t volume_label[11 ]; +uint8_t fat_type[8 ]; +uint8_t ignored[0x1a4 ]; } QEMU_PACKED fat32; } u; -uint8_t fat_type[8 ]; -uint8_t ignored[0x1c0 ];uint8_t magic[2 ]; }QEMU_PACKED bootsector_t;
@@ -973,13 +980,13 @@ static int init_directories(BDRVVVFATState* s,/* LATER TODO: if FAT32, this is wrong */ /* drive_number: fda=0, hda=0x80 */ bootsector->u.fat16.drive_number = s->offset_to_bootsector ==0 ?0 :0x80 ; - bootsector->u.fat16.current_head=0 ; bootsector->u.fat16.signature=0x29 ; bootsector->u.fat16.id=cpu_to_le32 (0xfabe1afd );memcpy (bootsector->u.fat16.volume_label, s->volume_label,sizeof (bootsector->u.fat16.volume_label)); -memcpy (bootsector->fat_type,(s->fat_type==12 ?"FAT12 " :s->fat_type==16 ?"FAT16 " :"FAT32 " ),8 ); +memcpy (bootsector->u.fat16.fat_type, + s->fat_type ==12 ?"FAT12 " :"FAT16 " ,8 ); bootsector->magic[0 ]=0x55 ; bootsector->magic[1 ]=0xaa ;return 0 ;
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 011/100] vvfat: always create . and .. entries at first and in that order
In reply to Kevin WolfFrom: Hervé Poussineau <[email protected]>
readdir() doesn't always return . and .. entries at first and in that order. This leads to not creating them at first in the directory, which raises some errors on file system checking utilities like MS-DOS Scandisk.
Specification: "FAT: General overview of on-disk format" v1.03, page 25
--- block/vvfat.c | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-)
block/vvfat.c +11 -2
@@ -727,6 +727,12 @@ static int read_directory(BDRVVVFATState* s, int mapping_index) i = mapping->info.dir.first_dir_index = first_cluster ==0 ?0 : s->directory.next; +if (first_cluster !=0 ) { +/* create the top entries of a subdirectory */ + (void )create_short_and_long_name (s, i,"." ,1 ); + (void )create_short_and_long_name (s, i,".." ,1 ); + } +/* actually read the directory, and allocate the mappings */ while ((entry=readdir (dir))) {unsigned int length=strlen (dirname)+2 +strlen (entry->d_name);
@@ -748,8 +754,11 @@ static int read_directory(BDRVVVFATState* s, int mapping_index) }/* create directory entry for this file */ - direntry=create_short_and_long_name (s, i, entry->d_name, - is_dot || is_dotdot); +if (!is_dot && !is_dotdot) { + direntry =create_short_and_long_name (s, i, entry->d_name,0 ); + }else { + direntry =array_get (&(s->directory), is_dot ? i : i +1 ); + } direntry->attributes=(S_ISDIR (st.st_mode)?0x10 :0x20 ); direntry->reserved[0 ]=direntry->reserved[1 ]=0 ; direntry->ctime=fat_datetime (st.st_ctime,1 );
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 012/100] vvfat: correctly create long names for non-ASCII filenames
In reply to Kevin WolfFrom: Hervé Poussineau <[email protected]>
Assume that input filename is encoded as UTF-8, so correctly create UTF-16 encoding.
--- block/vvfat.c | 38 ++++++++++++++++++-------------------- 1 file changed, 18 insertions(+), 20 deletions(-)
block/vvfat.c +18 -20
@@ -424,28 +424,19 @@ static void init_mbr(BDRVVVFATState *s, int cyls, int heads, int secs)/* direntry functions */ -/* dest is assumed to hold 258 bytes, and pads with 0xffff up to next multiple of 26 */ -static inline int short2long_name (char * dest,const char * src) +static direntry_t *create_long_filename (BDRVVVFATState *s,const char *filename) { -int i; -int len; -for (i=0 ;i<129 && src[i];i++) { - dest[2 *i]=src[i]; - dest[2 *i+1 ]=0 ; +int number_of_entries, i; +glong length; +direntry_t *entry; + +gunichar2 *longname =g_utf8_to_utf16 (filename,-1 ,NULL , &length,NULL ); +if (!longname) { +fprintf (stderr,"vvfat: invalid UTF-8 name: %s\n" , filename); +return NULL ; } - len=2 *i; - dest[2 *i]=dest[2 *i+1 ]=0 ; -for (i=2 *i+2 ;(i%26 );i++) - dest[i]=0xff ; -return len; -} -static inline direntry_t *create_long_filename (BDRVVVFATState * s,const char * filename) -{ -char buffer[258 ]; -int length=short2long_name (buffer,filename), - number_of_entries=(length+25 )/26 ,i; -direntry_t * entry; + number_of_entries = (length *2 +25 ) /26 ;for (i=0 ;i<number_of_entries;i++) { entry=array_get_next (&(s->directory));
@@ -460,8 +451,15 @@ static inline direntry_t* create_long_filename(BDRVVVFATState* s,const char* filelse if (offset<22 ) offset=14 +offset-10 ;else offset=28 +offset-22 ; entry=array_get (&(s->directory),s->directory.next-1 -(i/26 )); - entry->name[offset]=buffer[i]; +if (i >=2 * length +2 ) { + entry->name[offset] =0xff ; + }else if (i %2 ==0 ) { + entry->name[offset] = longname[i /2 ] &0xff ; + }else { + entry->name[offset] = longname[i /2 ] >>8 ; + } } +g_free (longname);return array_get (&(s->directory),s->directory.next-number_of_entries); }
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 009/100] vvfat: introduce offset_to_bootsector, offset_to_fat and offset_to_root_dir
In reply to Kevin WolfFrom: Hervé Poussineau <[email protected]>
- offset_to_bootsector is the number of sectors up to FAT bootsector
- offset_to_fat is the number of sectors up to first File Allocation Table
- offset_to_root_dir is the number of sectors up to root directory sector
Replace first_sectors_number - 1 by offset_to_bootsector. Replace first_sectors_number by offset_to_fat. Replace faked_sectors by offset_to_rootdir.
--- block/vvfat.c | 70 ++++++++++++++++++++++++++++++++++++----------------------- 1 file changed, 43 insertions(+), 27 deletions(-)
block/vvfat.c +43 -27
@@ -319,22 +319,24 @@ static void print_mapping(const struct mapping_t* mapping); typedef struct BDRVVVFATState { CoMutex lock; BlockDriverState* bs; /* pointer to parent */ - unsigned int first_sectors_number; /* 1 for a single partition, 0x40 for a disk with partition table */ unsigned char first_sectors[0x40*0x200]; int fat_type; /* 16 or 32 */ array_t fat,directory,mapping; char volume_label[11]; + uint32_t offset_to_bootsector; /* 0 for floppy, 0x3f for disk */ + unsigned int cluster_size; unsigned int sectors_per_cluster; unsigned int sectors_per_fat; unsigned int sectors_of_root_directory; uint32_t last_cluster_of_root_directory; - unsigned int faked_sectors; /* how many sectors are faked before file data */ uint32_t sector_count; /* total number of sectors of the partition */ uint32_t cluster_count; /* total number of clusters of this partition */ uint32_t max_fat_value; + uint32_t offset_to_fat; + uint32_t offset_to_root_dir; int current_fd; mapping_t* current_mapping;
@@ -393,15 +395,15 @@ static void init_mbr(BDRVVVFATState *s, int cyls, int heads, int secs) partition->attributes=0x80 ;/* bootable */ /* LBA is used when partition is outside the CHS geometry */ - lba =sector2CHS (&partition->start_CHS, s->first_sectors_number -1 , + lba =sector2CHS (&partition->start_CHS, s->offset_to_bootsector, cyls, heads, secs); lba |=sector2CHS (&partition->end_CHS, s->bs->total_sectors -1 , cyls, heads, secs);/*LBA partitions are identified only by start/length_sector_long not by CHS*/ - partition->start_sector_long =cpu_to_le32 (s->first_sectors_number -1 ); + partition->start_sector_long =cpu_to_le32 (s->offset_to_bootsector); partition->length_sector_long =cpu_to_le32 (s->bs->total_sectors - - s->first_sectors_number +1 ); + - s->offset_to_bootsector);/* FAT12/FAT16/FAT32 */ /* DOS uses different types when partition is LBA,
@@ -822,12 +824,12 @@ static int read_directory(BDRVVVFATState* s, int mapping_index)static inline uint32_t sector2cluster (BDRVVVFATState * s,off_t sector_num) { -return (sector_num-s->faked_sectors)/s->sectors_per_cluster; +return (sector_num - s->offset_to_root_dir) / s->sectors_per_cluster; }static inline off_t cluster2sector (BDRVVVFATState * s,uint32_t cluster_num) { -return s->faked_sectors + s->sectors_per_cluster * cluster_num; +return s->offset_to_root_dir + s->sectors_per_cluster * cluster_num; } static int init_directories(BDRVVVFATState* s,
@@ -854,6 +856,9 @@ static int init_directories(BDRVVVFATState* s, i =1 +s->sectors_per_cluster*0x200 *8 /s->fat_type; s->sectors_per_fat=(s->sector_count+i)/i;/* round up */ + s->offset_to_fat = s->offset_to_bootsector +1 ; + s->offset_to_root_dir = s->offset_to_fat + s->sectors_per_fat *2 ; +array_init (&(s->mapping),sizeof (mapping_t));array_init (&(s->directory),sizeof (direntry_t));
@@ -867,7 +872,6 @@ static int init_directories(BDRVVVFATState* s,/* Now build FAT, and write back information into directory */ init_fat (s); - s->faked_sectors=s->first_sectors_number+s->sectors_per_fat*2 ; s->cluster_count=sector2cluster (s, s->sector_count); mapping =array_get_next (&(s->mapping));
@@ -945,7 +949,8 @@ static int init_directories(BDRVVVFATState* s, s->current_mapping =NULL ; - bootsector=(bootsector_t *)(s->first_sectors+(s->first_sectors_number-1 )*0x200 ); + bootsector = (bootsector_t *)(s->first_sectors + + s->offset_to_bootsector *0x200 ); bootsector->jump[0 ]=0xeb ; bootsector->jump[1 ]=0x3e ; bootsector->jump[2 ]=0x90 ;
@@ -956,16 +961,18 @@ static int init_directories(BDRVVVFATState* s, bootsector->number_of_fats=0x2 ;/* number of FATs */ bootsector->root_entries=cpu_to_le16 (s->sectors_of_root_directory*0x10 ); bootsector->total_sectors16=s->sector_count>0xffff ?0 :cpu_to_le16 (s->sector_count); - bootsector->media_type=(s->first_sectors_number>1 ?0xf8 :0xf0 );/* media descriptor (f8=hd, f0=3.5 fd)*/ +/* media descriptor: hard disk=0xf8, floppy=0xf0 */ + bootsector->media_type = (s->offset_to_bootsector >0 ?0xf8 :0xf0 ); s->fat.pointer[0 ] = bootsector->media_type; bootsector->sectors_per_fat=cpu_to_le16 (s->sectors_per_fat); bootsector->sectors_per_track =cpu_to_le16 (secs); bootsector->number_of_heads =cpu_to_le16 (heads); - bootsector->hidden_sectors=cpu_to_le32 (s->first_sectors_number==1 ?0 :0x3f ); + bootsector->hidden_sectors =cpu_to_le32 (s->offset_to_bootsector); bootsector->total_sectors=cpu_to_le32 (s->sector_count>0xffff ?s->sector_count:0 );/* LATER TODO: if FAT32, this is wrong */ - bootsector->u.fat16.drive_number=s->first_sectors_number==1 ?0 :0x80 ;/* fda=0, hda=0x80 */ +/* drive_number: fda=0, hda=0x80 */ + bootsector->u.fat16.drive_number = s->offset_to_bootsector ==0 ?0 :0x80 ; bootsector->u.fat16.current_head=0 ; bootsector->u.fat16.signature=0x29 ; bootsector->u.fat16.id=cpu_to_le32 (0xfabe1afd );
@@ -1122,7 +1129,6 @@ static int vvfat_open(BlockDriverState *bs, QDict *options, int flags, secs = s->fat_type ==12 ?18 :36 ; s->sectors_per_cluster =1 ; } - s->first_sectors_number =1 ; cyls =80 ; heads =2 ; }else {
@@ -1130,7 +1136,7 @@ static int vvfat_open(BlockDriverState *bs, QDict *options, int flags,if (!s->fat_type) { s->fat_type =16 ; } - s->first_sectors_number =0x40 ; + s->offset_to_bootsector =0x3f ; cyls = s->fat_type ==12 ?64 :1024 ; heads =16 ; secs =63 ;
@@ -1166,7 +1172,7 @@ static int vvfat_open(BlockDriverState *bs, QDict *options, int flags,fprintf (stderr,"vvfat %s chs %d,%d,%d\n" , dirname, cyls, heads, secs); - s->sector_count = cyls * heads * secs - (s->first_sectors_number -1 ); + s->sector_count = cyls * heads * secs - s->offset_to_bootsector;if (qemu_opt_get_bool (opts,"rw" , false)) {if (!bdrv_is_read_only (bs)) {
@@ -1196,7 +1202,8 @@ static int vvfat_open(BlockDriverState *bs, QDict *options, int flags, goto fail; } - s->sector_count = s->faked_sectors + s->sectors_per_cluster*s->cluster_count; + s->sector_count = s->offset_to_root_dir + + s->sectors_per_cluster * s->cluster_count;/* Disable migration when vvfat is used rw */ if (s->qcow) {
@@ -1212,7 +1219,7 @@ static int vvfat_open(BlockDriverState *bs, QDict *options, int flags, } } -if (s->first_sectors_number ==0x40 ) { +if (s->offset_to_bootsector >0 ) {init_mbr (s, cyls, heads, secs); }
@@ -1425,15 +1432,24 @@ static int vvfat_read(BlockDriverState *bs, int64_t sector_num, }DLOG (fprintf (stderr,"sector %d not allocated\n" , (int )sector_num)); } -if (sector_num<s->faked_sectors) { -if (sector_num<s->first_sectors_number) -memcpy (buf+i*0x200 ,&(s->first_sectors[sector_num*0x200 ]),0x200 ); -else if (sector_num-s->first_sectors_number<s->sectors_per_fat) -memcpy (buf+i*0x200 ,&(s->fat.pointer[(sector_num-s->first_sectors_number)*0x200 ]),0x200 ); -else if (sector_num-s->first_sectors_number-s->sectors_per_fat<s->sectors_per_fat) -memcpy (buf+i*0x200 ,&(s->fat.pointer[(sector_num-s->first_sectors_number-s->sectors_per_fat)*0x200 ]),0x200 ); +if (sector_num < s->offset_to_root_dir) { +if (sector_num < s->offset_to_fat) { +memcpy (buf + i *0x200 , + &(s->first_sectors[sector_num *0x200 ]), +0x200 ); + }else if (sector_num < s->offset_to_fat + s->sectors_per_fat) { +memcpy (buf + i *0x200 , + &(s->fat.pointer[(sector_num + - s->offset_to_fat) *0x200 ]), +0x200 ); + }else if (sector_num < s->offset_to_root_dir) { +memcpy (buf + i *0x200 , + &(s->fat.pointer[(sector_num - s->offset_to_fat + - s->sectors_per_fat) *0x200 ]), +0x200 ); + } }else { -uint32_t sector=sector_num-s->faked_sectors, +uint32_t sector = sector_num - s->offset_to_root_dir, sector_offset_in_cluster=(sector%s->sectors_per_cluster), cluster_num=sector/s->sectors_per_cluster;if (cluster_num > s->cluster_count ||read_cluster (s, cluster_num) !=0 ) {
@@ -2045,7 +2061,7 @@ DLOG(checkpoint());memcpy (s->fat2, s->fat.pointer, size); } check =vvfat_read (s->bs, - s->first_sectors_number, s->fat2, s->sectors_per_fat); + s->offset_to_fat, s->fat2, s->sectors_per_fat);if (check) {fprintf (stderr,"Could not copy fat\n" );return 0 ;
@@ -2864,7 +2880,7 @@ DLOG(checkpoint());* - do not allow to write non-ASCII filenames */ -if (sector_num < s->first_sectors_number) +if (sector_num < s->offset_to_fat)return -1 ; for (i = sector2cluster(s, sector_num);
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 013/100] vvfat: correctly create base short names for non-ASCII filenames
In reply to Kevin WolfFrom: Hervé Poussineau <[email protected]>
More specifically, create short name from filename and change blacklist of invalid chars to whitelist of valid chars.
Windows 9x also now correctly see long file names of filenames containing a space, but Scandisk still complains about mismatch between SFN and LFN.
[kwolf: Build fix for this intermediate patch (it included declarations
for variables that are only used in the next patch) ]
Specification: "FAT: General overview of on-disk format" v1.03, pages 30-31
--- block/vvfat.c | 104 ++++++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 76 insertions(+), 28 deletions(-)
block/vvfat.c +76 -28
@@ -515,6 +515,80 @@ static void set_begin_of_direntry(direntry_t* direntry, uint32_t begin) direntry->begin_hi =cpu_to_le16 ((begin >>16 ) &0xffff ); } +static uint8_t to_valid_short_char (gunichar c) +{ + c =g_unichar_toupper (c); +if ((c >='0' && c <='9' ) || + (c >='A' && c <='Z' ) || +strchr ("$%'-_@~`!(){}^#&" , c) !=0 ) { +return c; + }else { +return 0 ; + } +} + +static direntry_t *create_short_filename (BDRVVVFATState *s, +const char *filename) +{ +int j =0 ; +direntry_t *entry =array_get_next (&(s->directory)); +const gchar *p, *last_dot =NULL ; +gunichar c; +bool lossy_conversion = false; + +if (!entry) { +return NULL ; + } +memset (entry->name,0x20 ,sizeof (entry->name)); + +/* copy filename and search last dot */ +for (p = filename; ; p =g_utf8_next_char (p)) { + c =g_utf8_get_char (p); +if (c =='\0' ) { +break ; + }else if (c =='.' ) { +if (j ==0 ) { +/* '.' at start of filename */ + lossy_conversion = true; + }else { +if (last_dot) { + lossy_conversion = true; + } + last_dot = p; + } + }else if (!last_dot) { +/* first part of the name; copy it */ +uint8_t v =to_valid_short_char (c); +if (j <8 && v) { + entry->name[j++] = v; + }else { + lossy_conversion = true; + } + } + } + +/* copy extension (if any) */ +if (last_dot) { + j =0 ; +for (p =g_utf8_next_char (last_dot); ; p =g_utf8_next_char (p)) { + c =g_utf8_get_char (p); +if (c =='\0' ) { +break ; + }else { +/* extension; copy it */ +uint8_t v =to_valid_short_char (c); +if (j <3 && v) { + entry->name[8 + (j++)] = v; + }else { + lossy_conversion = true; + } + } + } + } + (void )lossy_conversion; +return entry; +} +/* fat functions */ static inline uint8_t fat_chksum (const direntry_t * entry)
@@ -613,7 +687,7 @@ static inline void init_fat(BDRVVVFATState* s)static inline direntry_t *create_short_and_long_name (BDRVVVFATState * s,unsigned int directory_start,const char * filename,int is_dot) { -int i,j,long_index=s->directory.next; +int long_index = s->directory.next;direntry_t * entry =NULL ;direntry_t * entry_long =NULL ;
@@ -625,33 +699,7 @@ static inline direntry_t* create_short_and_long_name(BDRVVVFATState* s, } entry_long=create_long_filename (s,filename); - - i =strlen (filename); -for (j = i -1 ; j>0 && filename[j]!='.' ;j--); -if (j >0 ) - i = (j >8 ?8 : j); -else if (i >8 ) - i =8 ; - - entry=array_get_next (&(s->directory)); -memset (entry->name,0x20 ,sizeof (entry->name)); -memcpy (entry->name, filename, i); - -if (j >0 ) { -for (i =0 ; i <3 && filename[j +1 + i]; i++) { - entry->name[8 + i] = filename[j +1 + i]; - } - } - -/* upcase & remove unwanted characters */ -for (i=10 ;i>=0 ;i--) { -if (i==10 || i==7 )for (;i>0 && entry->name[i]==' ' ;i--); -if (entry->name[i]<=' ' || entry->name[i]>0x7f - ||strchr (".*?<>|\":/\\[];,+='" ,entry->name[i])) - entry->name[i]='_' ; -else if (entry->name[i]>='a' && entry->name[i]<='z' ) - entry->name[i]+='A' -'a' ; - } + entry =create_short_filename (s, filename);/* mangle duplicates */ while (1 ) {
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 014/100] vvfat: correctly generate numeric-tail of short file names
In reply to Kevin WolfFrom: Hervé Poussineau <[email protected]>
More specifically:
- try without numeric-tail only if LFN didn't have invalid short chars
- start at ~1 (instead of ~0)
- handle case if numeric tail is more than one char (ie > 10)
Windows 9x Scandisk doesn't see anymore mismatches between short file names and long file names for non-ASCII filenames.
Specification: "FAT: General overview of on-disk format" v1.03, page 31
--- block/vvfat.c | 65 ++++++++++++++++++++++++++++------------------------------- 1 file changed, 31 insertions(+), 34 deletions(-)
block/vvfat.c +31 -34
@@ -528,13 +528,15 @@ static uint8_t to_valid_short_char(gunichar c) }static direntry_t *create_short_filename (BDRVVVFATState *s, -const char *filename) +const char *filename, +unsigned int directory_start) { -int j =0 ; +int i, j =0 ;direntry_t *entry =array_get_next (&(s->directory));const gchar *p, *last_dot =NULL ;gunichar c;bool lossy_conversion = false; +char tail[11 ];if (!entry) {return NULL ;
@@ -585,8 +587,32 @@ static direntry_t *create_short_filename(BDRVVVFATState *s, } } } - (void )lossy_conversion; -return entry; + +/* numeric-tail generation */ +for (j =0 ; j <8 ; j++) { +if (entry->name[j] ==' ' ) { +break ; + } + } +for (i = lossy_conversion ?1 :0 ; i <999999 ; i++) { +direntry_t *entry1; +if (i >0 ) { +int len =sprintf (tail,"~%d" , i); +memcpy (entry->name +MIN (j,8 - len), tail, len); + } +for (entry1 =array_get (&(s->directory), directory_start); + entry1 < entry; entry1++) { +if (!is_long_name (entry1) && + !memcmp (entry1->name, entry->name,11 )) { +break ;/* found dupe */ + } + } +if (entry1 == entry) { +/* no dupe found */ +return entry; + } + } +return NULL ; }/* fat functions */
@@ -699,36 +725,7 @@ static inline direntry_t* create_short_and_long_name(BDRVVVFATState* s, } entry_long=create_long_filename (s,filename); - entry =create_short_filename (s, filename); - -/* mangle duplicates */ -while (1 ) { -direntry_t * entry1=array_get (&(s->directory),directory_start); -int j; - -for (;entry1<entry;entry1++) -if (!is_long_name (entry1) && !memcmp (entry1->name,entry->name,11 )) -break ;/* found dupe */ -if (entry1==entry)/* no dupe found */ -break ; - -/* use all 8 characters of name */ -if (entry->name[7 ]==' ' ) { -int j; -for (j=6 ;j>0 && entry->name[j]==' ' ;j--) - entry->name[j]='~' ; - } - -/* increment number */ -for (j=7 ;j>0 && entry->name[j]=='9' ;j--) - entry->name[j]='0' ; -if (j>0 ) { -if (entry->name[j]<'0' || entry->name[j]>'9' ) - entry->name[j]='0' ; -else - entry->name[j]++; - } - } + entry =create_short_filename (s, filename, directory_start);/* calculate checksum; propagate to long name */ if (entry_long) {
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 015/100] vvfat: limit number of entries in root directory in FAT12/FAT16
In reply to Kevin WolfFrom: Hervé Poussineau <[email protected]>
FAT12/FAT16 root directory is two sectors in size, which allows only 512 directory entries. Prevent QEMU startup if too much files exist, instead of overflowing root directory.
Also introduce variable root_entries, which will be required for FAT32.
--- block/vvfat.c | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-)
block/vvfat.c +17 -9
@@ -337,8 +337,9 @@ typedef struct BDRVVVFATState {unsigned int cluster_size;unsigned int sectors_per_cluster;unsigned int sectors_per_fat; -unsigned int sectors_of_root_directory;uint32_t last_cluster_of_root_directory; +/* how many entries are available in root directory (0 for FAT32) */ +uint16_t root_entries;uint32_t sector_count;/* total number of sectors of the partition */ uint32_t cluster_count;/* total number of clusters of this partition */ uint32_t max_fat_value;
@@ -785,6 +786,12 @@ static int read_directory(BDRVVVFATState* s, int mapping_index)int is_dot=!strcmp (entry->d_name,"." );int is_dotdot=!strcmp (entry->d_name,".." ); +if (first_cluster ==0 && s->directory.next >= s->root_entries -1 ) { +fprintf (stderr,"Too many entries in root directory\n" ); +closedir (dir); +return -2 ; + } +if (first_cluster ==0 && (is_dotdot || is_dot))continue ;
@@ -858,15 +865,15 @@ static int read_directory(BDRVVVFATState* s, int mapping_index)memset (direntry,0 ,sizeof (direntry_t)); } -/* TODO: if there are more entries, bootsector has to be adjusted! */ -#define ROOT_ENTRIES (0x02 * 0x10 * s->sectors_per_cluster) -if (mapping_index ==0 && s->directory.next <ROOT_ENTRIES ) { +if (s->fat_type !=32 && + mapping_index ==0 && + s->directory.next < s->root_entries) {/* root directory */ int cur = s->directory.next; -array_ensure_allocated (&(s->directory),ROOT_ENTRIES -1 ); - s->directory.next =ROOT_ENTRIES ; +array_ensure_allocated (&(s->directory), s->root_entries -1 ); + s->directory.next = s->root_entries;memset (array_get (&(s->directory), cur),0 , - (ROOT_ENTRIES - cur) *sizeof (direntry_t)); + (s->root_entries - cur) *sizeof (direntry_t)); }/* re-get the mapping, since s->mapping was possibly realloc()ed */
@@ -931,6 +938,8 @@ static int init_directories(BDRVVVFATState* s,/* Now build FAT, and write back information into directory */ init_fat (s); +/* TODO: if there are more entries, bootsector has to be adjusted! */ + s->root_entries =0x02 *0x10 * s->sectors_per_cluster; s->cluster_count=sector2cluster (s, s->sector_count); mapping =array_get_next (&(s->mapping));
@@ -999,7 +1008,6 @@ static int init_directories(BDRVVVFATState* s, } mapping =array_get (&(s->mapping),0 ); - s->sectors_of_root_directory = mapping->end * s->sectors_per_cluster; s->last_cluster_of_root_directory = mapping->end;/* the FAT signature */
@@ -1018,7 +1026,7 @@ static int init_directories(BDRVVVFATState* s, bootsector->sectors_per_cluster=s->sectors_per_cluster; bootsector->reserved_sectors=cpu_to_le16 (1 ); bootsector->number_of_fats=0x2 ;/* number of FATs */ - bootsector->root_entries=cpu_to_le16 (s->sectors_of_root_directory*0x10 ); + bootsector->root_entries =cpu_to_le16 (s->root_entries); bootsector->total_sectors16=s->sector_count>0xffff ?0 :cpu_to_le16 (s->sector_count);/* media descriptor: hard disk=0xf8, floppy=0xf0 */ bootsector->media_type = (s->offset_to_bootsector >0 ?0xf8 :0xf0 );
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 016/100] vvfat: handle KANJI lead byte 0xe5
In reply to Kevin WolfFrom: Hervé Poussineau <[email protected]>
Specification: "FAT: General overview of on-disk format" v1.03, page 23
--- block/vvfat.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-)
block/vvfat.c +7 -2
@@ -589,6 +589,10 @@ static direntry_t *create_short_filename(BDRVVVFATState *s, } } +if (entry->name[0 ] ==0xe5 ) { + entry->name[0 ] =0x05 ; + } +/* numeric-tail generation */ for (j =0 ; j <8 ; j++) {if (entry->name[j] ==' ' ) {
@@ -709,8 +713,6 @@ static inline void init_fat(BDRVVVFATState* s) } -/* TODO: in create_short_filename, 0xe5->0x05 is not yet handled! */ -/* TODO: in parse_short_filename, 0x05->0xe5 is not yet handled! */ static inline direntry_t *create_short_and_long_name (BDRVVVFATState * s,unsigned int directory_start,const char * filename,int is_dot) {
@@ -1743,6 +1745,9 @@ static int parse_short_name(BDRVVVFATState* s, }else lfn->name[i + j +1 ] ='\0' ; +if (lfn->name[0 ] ==0x05 ) { + lfn->name[0 ] =0xe5 ; + } lfn->len =strlen ((char *)lfn->name);return 0 ;
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 017/100] vvfat: change OEM name to 'MSWIN4.1'
In reply to Kevin WolfFrom: Hervé Poussineau <[email protected]>
According to specification:
"'MSWIN4.1' is the recommanded setting, because it is the setting least likely to cause compatibility problems. If you want to put something else in here, that is your option, but the result may be that some FAT drivers might not recognize the volume."
Specification: "FAT: General overview of on-disk format" v1.03, page 9
--- block/vvfat.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
block/vvfat.c +1 -1
@@ -1023,7 +1023,7 @@ static int init_directories(BDRVVVFATState* s, bootsector->jump[0 ]=0xeb ; bootsector->jump[1 ]=0x3e ; bootsector->jump[2 ]=0x90 ; -memcpy (bootsector->name,"QEMU " ,8 ); +memcpy (bootsector->name,"MSWIN4.1" ,8 ); bootsector->sector_size=cpu_to_le16 (0x200 ); bootsector->sectors_per_cluster=s->sectors_per_cluster; bootsector->reserved_sectors=cpu_to_le16 (1 );
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 018/100] qemu-img: drop -e and -6 options from the 'create' & 'convert' commands
In reply to Kevin WolfFrom: "Daniel P. Berrange" <[email protected]>
The '-e' and '-6' options to the 'create' & 'convert' commands were "deprecated" in favour of the more generic '-o' option many years ago:
commit eec77d9e712bd4157a4e1c0b5a9249d168add738
Author: Jes Sorensen <[email protected]>
Date: Tue Dec 7 17:44:34 2010 +0100
qemu-img: Deprecate obsolete -6 and -e options
Except this was never actually a deprecation, which would imply giving the user a warning while the functionality continues to work for a number of releases before eventual removal. Instead the options were immediately turned into an error + exit. Given that the functionality is already broken, there's no point in keeping these psuedo-deprecation messages around any longer.
--- qemu-img.c | 20 ++------------------ 1 file changed, 2 insertions(+), 18 deletions(-)
qemu-img.c +2 -18
@@ -464,7 +464,7 @@ static int img_create(int argc, char **argv) {"object", required_argument, 0, OPTION_OBJECT}, {0, 0, 0, 0} }; - c =getopt_long (argc, argv,":F:b:f:he6o:q" , + c =getopt_long (argc, argv,":F:b:f:ho:q" , long_options,NULL );if (c ==-1 ) {break ;
@@ -488,14 +488,6 @@ static int img_create(int argc, char **argv)case 'f' : fmt = optarg;break ; -case 'e' : -error_report ("option -e is deprecated, please use \'-o " -"encryption\' instead!" ); - goto fail; -case '6' : -error_report ("option -6 is deprecated, please use \'-o " -"compat6\' instead!" ); - goto fail;case 'o' :if (!is_valid_option_list (optarg)) {error_report ("Invalid option list: %s" , optarg);
@@ -1985,7 +1977,7 @@ static int img_convert(int argc, char **argv) {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS}, {0, 0, 0, 0} }; - c =getopt_long (argc, argv,":hf:O:B:ce6o:s:l:S:pt:T:qnm:WU" , + c =getopt_long (argc, argv,":hf:O:B:co:s:l:S:pt:T:qnm:WU" , long_options,NULL );if (c ==-1 ) {break ;
@@ -2012,14 +2004,6 @@ static int img_convert(int argc, char **argv)case 'c' : s.compressed = true;break ; -case 'e' : -error_report ("option -e is deprecated, please use \'-o " -"encryption\' instead!" ); - goto fail_getopt; -case '6' : -error_report ("option -6 is deprecated, please use \'-o " -"compat6\' instead!" ); - goto fail_getopt;case 'o' :if (!is_valid_option_list (optarg)) {error_report ("Invalid option list: %s" , optarg);
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 019/100] blockdev: Print a warning for legacy drive options that belong to -device
In reply to Kevin WolfFrom: Thomas Huth <[email protected]>
We likely do not want to carry these legacy -drive options along forever. Let's emit a deprecation warning for the -drive options that have a replacement with the -device option, so that the (hopefully few) remaining users are aware of this and can adapt their scripts / behaviour accordingly.
--- blockdev.c | 14 ++++++++++++++ qemu-options.hx | 9 +++++++-- 2 files changed, 21 insertions(+), 2 deletions(-)
blockdev.c +14 -0
@@ -50,6 +50,7 @@#include "qmp-commands.h" #include "block/trace.h" #include "sysemu/arch_init.h" +#include "sysemu/qtest.h" #include "qemu/cutils.h" #include "qemu/help_option.h" #include "qemu/throttle-options.h"
@@ -798,6 +799,9 @@ DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)const char *filename;Error *local_err =NULL ;int i; +const char *deprecated[] = { +"serial" ,"trans" ,"secs" ,"heads" ,"cyls" ,"addr" + };/* Change legacy command line options into QMP ones */ static const struct {
@@ -881,6 +885,16 @@ DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type) "update your scripts.\n"); } +/* Other deprecated options */ +if (!qtest_enabled ()) { +for (i =0 ; i <ARRAY_SIZE (deprecated); i++) { +if (qemu_opt_get (legacy_opts, deprecated[i]) !=NULL ) { +error_report ("'%s' is deprecated, please use the corresponding " +"option of '-device' instead" , deprecated[i]); + } + } + } +/* Media type */ value =qemu_opt_get (legacy_opts,"media" );if (value) {
qemu-options.hx +7 -2
@@ -818,6 +818,8 @@ of available connectors of a given interface type. This option defines the type of the media: disk or cdrom. @item cyls=@var{c},heads=@var{h},secs=@var{s}[,trans=@var{t}] These options have the same definition as they have in @option{-hdachs}. +These parameters are deprecated, use the corresponding parameters +of @code{-device} instead. @item snapshot=@var{snapshot} @var{snapshot} is "on" or "off" and controls snapshot mode for the given drive (see @option{-snapshot}).
@@ -852,9 +854,12 @@ Specify which disk @var{format} will be used rather than detecting the format. Can be used to specify format=raw to avoid interpreting an untrusted format header. @item serial=@var{serial} -This option specifies the serial number to assign to the device. +This option specifies the serial number to assign to the device. This +parameter is deprecated, use the corresponding parameter of @code{-device} +instead. @item addr=@var{addr} -Specify the controller's PCI address (if=virtio only). +Specify the controller's PCI address (if=virtio only). This parameter is +deprecated, use the corresponding parameter of @code{-device} instead. @item werror=@var{action},rerror=@var{action} Specify which @var{action} to take on write and read errors. Valid actions are: "ignore" (ignore the error and try to continue), "stop" (pause QEMU),
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 020/100] blockjob: Track job ratelimits via bytes, not sectors
In reply to Kevin WolfFrom: Eric Blake <[email protected]>
The user interface specifies job rate limits in bytes/second. It's pointless to have our internal representation track things in sectors/second, particularly since we want to move away from sector-based interfaces.
Fix up a doc typo found while verifying that the ratelimit code handles the scaling difference.
Repetition of expressions like 'n * BDRV_SECTOR_SIZE' will be cleaned up later when functions are converted to iterate over images by bytes rather than by sectors.
--- block/backup.c | 5 +++-- block/commit.c | 5 +++-- block/mirror.c | 13 +++++++------ block/stream.c | 5 +++-- include/qemu/ratelimit.h | 3 ++- 5 files changed, 18 insertions(+), 13 deletions(-)
block/backup.c +3 -2
@@ -208,7 +208,7 @@ static void backup_set_speed(BlockJob *job, int64_t speed, Error **errp)error_setg (errp,QERR_INVALID_PARAMETER ,"speed" );return ; } -ratelimit_set_speed (&s->limit, speed /BDRV_SECTOR_SIZE ,SLICE_TIME ); +ratelimit_set_speed (&s->limit, speed,SLICE_TIME ); }static void backup_cleanup_sync_bitmap (BackupBlockJob *job,int ret)
@@ -359,7 +359,8 @@ static bool coroutine_fn yield_and_check(BackupBlockJob *job)*/ if (job->common.speed) {uint64_t delay_ns =ratelimit_calculate_delay (&job->limit, - job->sectors_read); + job->sectors_read * +BDRV_SECTOR_SIZE ); job->sectors_read =0 ;block_job_sleep_ns (&job->common,QEMU_CLOCK_REALTIME , delay_ns); }else {
block/commit.c +3 -2
@@ -209,7 +209,8 @@ static void coroutine_fn commit_run(void *opaque) s->common.offset += n *BDRV_SECTOR_SIZE ;if (copy && s->common.speed) { - delay_ns =ratelimit_calculate_delay (&s->limit, n); + delay_ns =ratelimit_calculate_delay (&s->limit, + n *BDRV_SECTOR_SIZE ); } }
@@ -231,7 +232,7 @@ static void commit_set_speed(BlockJob *job, int64_t speed, Error **errp)error_setg (errp,QERR_INVALID_PARAMETER ,"speed" );return ; } -ratelimit_set_speed (&s->limit, speed /BDRV_SECTOR_SIZE ,SLICE_TIME ); +ratelimit_set_speed (&s->limit, speed,SLICE_TIME ); }static const BlockJobDriver commit_job_driver = {
block/mirror.c +7 -6
@@ -396,7 +396,8 @@ static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s)bitmap_set (s->in_flight_bitmap, sector_num / sectors_per_chunk, nb_chunks);while (nb_chunks >0 && sector_num < end) {int64_t ret; -int io_sectors, io_sectors_acct; +int io_sectors; +int64_t io_bytes_acct;BlockDriverState *file;enum MirrorMethod {MIRROR_METHOD_COPY ,
@@ -444,16 +445,16 @@ static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s)switch (mirror_method) {case MIRROR_METHOD_COPY : io_sectors =mirror_do_read (s, sector_num, io_sectors); - io_sectors_acct = io_sectors; + io_bytes_acct = io_sectors *BDRV_SECTOR_SIZE ;break ;case MIRROR_METHOD_ZERO :case MIRROR_METHOD_DISCARD :mirror_do_zero_or_discard (s, sector_num, io_sectors, mirror_method ==MIRROR_METHOD_DISCARD );if (write_zeroes_ok) { - io_sectors_acct =0 ; + io_bytes_acct =0 ; }else { - io_sectors_acct = io_sectors; + io_bytes_acct = io_sectors *BDRV_SECTOR_SIZE ; }break ;default :
@@ -463,7 +464,7 @@ static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s) sector_num += io_sectors; nb_chunks -=DIV_ROUND_UP (io_sectors, sectors_per_chunk);if (s->common.speed) { - delay_ns =ratelimit_calculate_delay (&s->limit, io_sectors_acct); + delay_ns =ratelimit_calculate_delay (&s->limit, io_bytes_acct); } }return delay_ns;
@@ -929,7 +930,7 @@ static void mirror_set_speed(BlockJob *job, int64_t speed, Error **errp)error_setg (errp,QERR_INVALID_PARAMETER ,"speed" );return ; } -ratelimit_set_speed (&s->limit, speed /BDRV_SECTOR_SIZE ,SLICE_TIME ); +ratelimit_set_speed (&s->limit, speed,SLICE_TIME ); }static void mirror_complete (BlockJob *job,Error **errp)
block/stream.c +3 -2
@@ -191,7 +191,8 @@ static void coroutine_fn stream_run(void *opaque)/* Publish progress */ s->common.offset += n *BDRV_SECTOR_SIZE ;if (copy && s->common.speed) { - delay_ns =ratelimit_calculate_delay (&s->limit, n); + delay_ns =ratelimit_calculate_delay (&s->limit, + n *BDRV_SECTOR_SIZE ); } }
@@ -220,7 +221,7 @@ static void stream_set_speed(BlockJob *job, int64_t speed, Error **errp)error_setg (errp,QERR_INVALID_PARAMETER ,"speed" );return ; } -ratelimit_set_speed (&s->limit, speed /BDRV_SECTOR_SIZE ,SLICE_TIME ); +ratelimit_set_speed (&s->limit, speed,SLICE_TIME ); }static const BlockJobDriver stream_job_driver = {
include/qemu/ratelimit.h +2 -1
@@ -24,7 +24,8 @@ typedef struct {/** Calculate and return delay for next request in ns * -* Record that we sent @p n data units. If we may send more data units +* Record that we sent @n data units (where @n matches the scale chosen +* during ratelimit_set_speed). If we may send more data units * in the current time slice, return 0 (i.e. no delay). Otherwise * return the amount of time (in ns) until the start of the next time * slice that will permit sending the next chunk of data.
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 022/100] stream: Switch stream_populate() to byte-based
In reply to Kevin WolfFrom: Eric Blake <[email protected]>
We are gradually converting to byte-based interfaces, as they are easier to reason about than sector-based. Start by converting an internal function (no semantic change).
--- block/stream.c | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-)
block/stream.c +6 -5
@@ -41,20 +41,20 @@ typedef struct StreamBlockJob { } StreamBlockJob; static int coroutine_fn stream_populate(BlockBackend *blk, -int64_t sector_num,int nb_sectors, +int64_t offset,uint64_t bytes,void *buf) {struct iovec iov = { .iov_base = buf, - .iov_len = nb_sectors *BDRV_SECTOR_SIZE , + .iov_len = bytes, };QEMUIOVector qiov; +assert (bytes <SIZE_MAX );qemu_iovec_init_external (&qiov, &iov,1 );/* Copy-on-read the unallocated clusters */ -return blk_co_preadv (blk, sector_num *BDRV_SECTOR_SIZE , qiov.size, &qiov, -BDRV_REQ_COPY_ON_READ ); +return blk_co_preadv (blk, offset, qiov.size, &qiov,BDRV_REQ_COPY_ON_READ ); } typedef struct {
@@ -171,7 +171,8 @@ static void coroutine_fn stream_run(void *opaque)trace_stream_one_iteration (s, sector_num *BDRV_SECTOR_SIZE , n *BDRV_SECTOR_SIZE , ret);if (copy) { - ret =stream_populate (blk, sector_num, n, buf); + ret =stream_populate (blk, sector_num *BDRV_SECTOR_SIZE , + n *BDRV_SECTOR_SIZE , buf); }if (ret <0 ) { BlockErrorAction action =
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 021/100] trace: Show blockjob actions via bytes, not sectors
In reply to Kevin WolfFrom: Eric Blake <[email protected]>
Upcoming patches are going to switch to byte-based interfaces instead of sector-based. Even worse, trace_backup_do_cow_enter() had a weird mix of cluster and sector indices.
The trace interface is low enough that there are no stability guarantees, and therefore nothing wrong with changing our units, even in cases like trace_backup_do_cow_skip() where we are not changing the trace output. So make the tracing uniformly use bytes.
--- block/backup.c | 16 ++++++++++------ block/commit.c | 3 ++- block/mirror.c | 26 +++++++++++++++++--------- block/stream.c | 3 ++- block/trace-events | 14 +++++++------- 5 files changed, 38 insertions(+), 24 deletions(-)
block/backup.c +10 -6
@@ -102,6 +102,7 @@ static int coroutine_fn backup_do_cow(BackupBlockJob *job,void *bounce_buffer =NULL ;int ret =0 ;int64_t sectors_per_cluster =cluster_size_sectors (job); +int64_t bytes_per_cluster = sectors_per_cluster *BDRV_SECTOR_SIZE ;int64_t start, end;int n;
@@ -110,18 +111,20 @@ static int coroutine_fn backup_do_cow(BackupBlockJob *job, start = sector_num / sectors_per_cluster; end =DIV_ROUND_UP (sector_num + nb_sectors, sectors_per_cluster); -trace_backup_do_cow_enter (job, start, sector_num, nb_sectors); +trace_backup_do_cow_enter (job, start * bytes_per_cluster, + sector_num *BDRV_SECTOR_SIZE , + nb_sectors *BDRV_SECTOR_SIZE );wait_for_overlapping_requests (job, start, end);cow_request_begin (&cow_request, job, start, end);for (; start < end; start++) {if (test_bit (start, job->done_bitmap)) { -trace_backup_do_cow_skip (job, start); +trace_backup_do_cow_skip (job, start * bytes_per_cluster);continue ;/* already copied */ } -trace_backup_do_cow_process (job, start); +trace_backup_do_cow_process (job, start * bytes_per_cluster); n = MIN(sectors_per_cluster, job->common.len / BDRV_SECTOR_SIZE -
@@ -138,7 +141,7 @@ static int coroutine_fn backup_do_cow(BackupBlockJob *job, bounce_qiov.size, &bounce_qiov, is_write_notifier ? BDRV_REQ_NO_SERIALISING : 0);if (ret <0 ) { -trace_backup_do_cow_read_fail (job, start, ret); +trace_backup_do_cow_read_fail (job, start * bytes_per_cluster, ret);if (error_is_read) { *error_is_read = true; }
@@ -154,7 +157,7 @@ static int coroutine_fn backup_do_cow(BackupBlockJob *job, job->compress ? BDRV_REQ_WRITE_COMPRESSED : 0); }if (ret <0 ) { -trace_backup_do_cow_write_fail (job, start, ret); +trace_backup_do_cow_write_fail (job, start * bytes_per_cluster, ret);if (error_is_read) { *error_is_read = false; }
@@ -177,7 +180,8 @@ out:cow_request_end (&cow_request); -trace_backup_do_cow_return (job, sector_num, nb_sectors, ret); +trace_backup_do_cow_return (job, sector_num *BDRV_SECTOR_SIZE , + nb_sectors *BDRV_SECTOR_SIZE , ret);qemu_co_rwlock_unlock (&job->flush_rwlock);
block/commit.c +2 -1
@@ -190,7 +190,8 @@ static void coroutine_fn commit_run(void *opaque)COMMIT_BUFFER_SIZE /BDRV_SECTOR_SIZE , &n); copy = (ret ==1 ); -trace_commit_one_iteration (s, sector_num, n, ret); +trace_commit_one_iteration (s, sector_num *BDRV_SECTOR_SIZE , + n *BDRV_SECTOR_SIZE , ret);if (copy) { ret =commit_populate (s->top, s->base, sector_num, n, buf); bytes_written += n *BDRV_SECTOR_SIZE ;
block/mirror.c +17 -9
@@ -103,7 +103,8 @@ static void mirror_iteration_done(MirrorOp *op, int ret)int64_t chunk_num;int i, nb_chunks, sectors_per_chunk; -trace_mirror_iteration_done (s, op->sector_num, op->nb_sectors, ret); +trace_mirror_iteration_done (s, op->sector_num *BDRV_SECTOR_SIZE , + op->nb_sectors *BDRV_SECTOR_SIZE , ret); s->in_flight--; s->sectors_in_flight -= op->nb_sectors;
@@ -268,7 +269,8 @@ static int mirror_do_read(MirrorBlockJob *s, int64_t sector_num, nb_chunks =DIV_ROUND_UP (nb_sectors, sectors_per_chunk);while (s->buf_free_count < nb_chunks) { -trace_mirror_yield_in_flight (s, sector_num, s->in_flight); +trace_mirror_yield_in_flight (s, sector_num *BDRV_SECTOR_SIZE , + s->in_flight);mirror_wait_for_io (s); }
@@ -294,7 +296,8 @@ static int mirror_do_read(MirrorBlockJob *s, int64_t sector_num,/* Copy the dirty cluster. */ s->in_flight++; s->sectors_in_flight += nb_sectors; -trace_mirror_one_iteration (s, sector_num, nb_sectors); +trace_mirror_one_iteration (s, sector_num *BDRV_SECTOR_SIZE , + nb_sectors *BDRV_SECTOR_SIZE );blk_aio_preadv (source, sector_num *BDRV_SECTOR_SIZE , &op->qiov,0 , mirror_read_complete, op);
@@ -347,14 +350,16 @@ static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s)if (sector_num <0 ) {bdrv_set_dirty_iter (s->dbi,0 ); sector_num =bdrv_dirty_iter_next (s->dbi); -trace_mirror_restart_iter (s,bdrv_get_dirty_count (s->dirty_bitmap)); +trace_mirror_restart_iter (s,bdrv_get_dirty_count (s->dirty_bitmap) * +BDRV_SECTOR_SIZE );assert (sector_num >=0 ); }bdrv_dirty_bitmap_unlock (s->dirty_bitmap); first_chunk = sector_num / sectors_per_chunk;while (test_bit (first_chunk, s->in_flight_bitmap)) { -trace_mirror_yield_in_flight (s, sector_num, s->in_flight); +trace_mirror_yield_in_flight (s, sector_num *BDRV_SECTOR_SIZE , + s->in_flight);mirror_wait_for_io (s); }
@@ -433,7 +438,8 @@ static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s) }while (s->in_flight >=MAX_IN_FLIGHT ) { -trace_mirror_yield_in_flight (s, sector_num, s->in_flight); +trace_mirror_yield_in_flight (s, sector_num *BDRV_SECTOR_SIZE , + s->in_flight);mirror_wait_for_io (s); }
@@ -823,7 +829,8 @@ static void coroutine_fn mirror_run(void *opaque) s->common.iostatus == BLOCK_DEVICE_IO_STATUS_OK) {if (s->in_flight >=MAX_IN_FLIGHT || s->buf_free_count ==0 || (cnt ==0 && s->in_flight >0 )) { -trace_mirror_yield (s, cnt, s->buf_free_count, s->in_flight); +trace_mirror_yield (s, cnt *BDRV_SECTOR_SIZE , + s->buf_free_count, s->in_flight);mirror_wait_for_io (s);continue ; }else if (cnt !=0 ) {
@@ -864,7 +871,7 @@ static void coroutine_fn mirror_run(void *opaque)* whether to switch to target check one last time if I/O has * come in the meanwhile, and if not flush the data to disk. */ -trace_mirror_before_drain (s, cnt); +trace_mirror_before_drain (s, cnt *BDRV_SECTOR_SIZE );bdrv_drained_begin (bs); cnt =bdrv_get_dirty_count (s->dirty_bitmap);
@@ -883,7 +890,8 @@ static void coroutine_fn mirror_run(void *opaque) } ret =0 ; -trace_mirror_before_sleep (s, cnt, s->synced, delay_ns); +trace_mirror_before_sleep (s, cnt *BDRV_SECTOR_SIZE , + s->synced, delay_ns);if (!s->synced) {block_job_sleep_ns (&s->common,QEMU_CLOCK_REALTIME , delay_ns);if (block_job_is_cancelled (&s->common)) {
block/stream.c +2 -1
@@ -168,7 +168,8 @@ static void coroutine_fn stream_run(void *opaque) copy = (ret ==1 ); } -trace_stream_one_iteration (s, sector_num, n, ret); +trace_stream_one_iteration (s, sector_num *BDRV_SECTOR_SIZE , + n *BDRV_SECTOR_SIZE , ret);if (copy) { ret =stream_populate (blk, sector_num, n, buf); }
block/trace-events +7 -7
@@ -15,11 +15,11 @@ bdrv_co_pwrite_zeroes(void *bs, int64_t offset, int count, int flags) "bs %p off bdrv_co_do_copy_on_readv(void *bs, int64_t offset, unsigned int bytes, int64_t cluster_offset, unsigned int cluster_bytes) "bs %p offset %"PRId64" bytes %u cluster_offset %"PRId64" cluster_bytes %u" # block/stream.c -stream_one_iteration(void *s, int64_t sector_num, int nb_sectors, int is_allocated) "s %p sector_num %"PRId64" nb_sectors %d is_allocated %d" +stream_one_iteration(void *s, int64_t offset, uint64_t bytes, int is_allocated) "s %p offset %" PRId64 " bytes %" PRIu64 " is_allocated %d" stream_start(void *bs, void *base, void *s) "bs %p base %p s %p" # block/commit.c -commit_one_iteration(void *s, int64_t sector_num, int nb_sectors, int is_allocated) "s %p sector_num %"PRId64" nb_sectors %d is_allocated %d" +commit_one_iteration(void *s, int64_t offset, uint64_t bytes, int is_allocated) "s %p offset %" PRId64 " bytes %" PRIu64 " is_allocated %d" commit_start(void *bs, void *base, void *top, void *s) "bs %p base %p top %p s %p" # block/mirror.c
@@ -28,14 +28,14 @@ mirror_restart_iter(void *s, int64_t cnt) "s %p dirty count %"PRId64 mirror_before_flush(void *s) "s %p" mirror_before_drain(void *s, int64_t cnt) "s %p dirty count %"PRId64 mirror_before_sleep(void *s, int64_t cnt, int synced, uint64_t delay_ns) "s %p dirty count %"PRId64" synced %d delay %"PRIu64"ns" -mirror_one_iteration(void *s, int64_t sector_num, int nb_sectors) "s %p sector_num %"PRId64" nb_sectors %d" -mirror_iteration_done(void *s, int64_t sector_num, int nb_sectors, int ret) "s %p sector_num %"PRId64" nb_sectors %d ret %d" +mirror_one_iteration(void *s, int64_t offset, uint64_t bytes) "s %p offset %" PRId64 " bytes %" PRIu64 +mirror_iteration_done(void *s, int64_t offset, uint64_t bytes, int ret) "s %p offset %" PRId64 " bytes %" PRIu64 " ret %d" mirror_yield(void *s, int64_t cnt, int buf_free_count, int in_flight) "s %p dirty count %"PRId64" free buffers %d in_flight %d" -mirror_yield_in_flight(void *s, int64_t sector_num, int in_flight) "s %p sector_num %"PRId64" in_flight %d" +mirror_yield_in_flight(void *s, int64_t offset, int in_flight) "s %p offset %" PRId64 " in_flight %d" # block/backup.c -backup_do_cow_enter(void *job, int64_t start, int64_t sector_num, int nb_sectors) "job %p start %"PRId64" sector_num %"PRId64" nb_sectors %d" -backup_do_cow_return(void *job, int64_t sector_num, int nb_sectors, int ret) "job %p sector_num %"PRId64" nb_sectors %d ret %d" +backup_do_cow_enter(void *job, int64_t start, int64_t offset, uint64_t bytes) "job %p start %" PRId64 " offset %" PRId64 " bytes %" PRIu64 +backup_do_cow_return(void *job, int64_t offset, uint64_t bytes, int ret) "job %p offset %" PRId64 " bytes %" PRIu64 " ret %d" backup_do_cow_skip(void *job, int64_t start) "job %p start %"PRId64 backup_do_cow_process(void *job, int64_t start) "job %p start %"PRId64 backup_do_cow_read_fail(void *job, int64_t start, int ret) "job %p start %"PRId64" ret %d"
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 023/100] stream: Drop reached_end for stream_complete()
In reply to Kevin WolfFrom: Eric Blake <[email protected]>
stream_complete() skips the work of rewriting the backing file if the job was cancelled, if data->reached_end is false, or if there was an error detected (non-zero data->ret) during the streaming. But note that in stream_run(), data->reached_end is only set if the loop ran to completion, and data->ret is only 0 in two cases:
either the loop ran to completion (possibly by cancellation, but stream_complete checks for that), or we took an early goto out because there is no bs->backing. Thus, we can preserve the same semantics without the use of reached_end, by merely checking for bs->backing (and logically, if there was no backing file, streaming is a no-op, so there is no backing file to rewrite).
--- block/stream.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-)
block/stream.c +1 -3
@@ -59,7 +59,6 @@ static int coroutine_fn stream_populate(BlockBackend *blk,typedef struct {int ret; -bool reached_end; }StreamCompleteData ;static void stream_complete (BlockJob *job,void *opaque)
@@ -70,7 +69,7 @@ static void stream_complete(BlockJob *job, void *opaque)BlockDriverState *base = s->base;Error *local_err =NULL ; -if (!block_job_is_cancelled (&s->common) && data->reached_end && +if (!block_job_is_cancelled (&s->common) && bs->backing && data->ret ==0 ) {const char *base_id =NULL , *base_fmt =NULL ;if (base) {
@@ -211,7 +210,6 @@ out:/* Modify backing chain and close BDSes in main loop */ data =g_malloc (sizeof (*data)); data->ret = ret; - data->reached_end = sector_num == end;block_job_defer_to_main_loop (&s->common, stream_complete, data); }
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 024/100] stream: Switch stream_run() to byte-based
In reply to Kevin WolfFrom: Eric Blake <[email protected]>
We are gradually converting to byte-based interfaces, as they are easier to reason about than sector-based. Change the internal loop iteration of streaming to track by bytes instead of sectors (although we are still guaranteed that we iterate by steps that are sector-aligned).
--- block/stream.c | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-)
block/stream.c +9 -13
@@ -107,12 +107,11 @@ static void coroutine_fn stream_run(void *opaque)BlockBackend *blk = s->common.blk;BlockDriverState *bs =blk_bs (blk);BlockDriverState *base = s->base; -int64_t sector_num =0 ; -int64_t end =-1 ; +int64_t offset =0 ;uint64_t delay_ns =0 ;int error =0 ;int ret =0 ; -int n =0 ; +int n =0 ;/* sectors */ void *buf;if (!bs->backing) {
@@ -125,7 +124,6 @@ static void coroutine_fn stream_run(void *opaque) goto out; } - end = s->common.len >>BDRV_SECTOR_BITS ; buf =qemu_blockalign (bs,STREAM_BUFFER_SIZE );/* Turn on copy-on-read for the whole block device so that guest read
@@ -137,7 +135,7 @@ static void coroutine_fn stream_run(void *opaque)bdrv_enable_copy_on_read (bs); } -for (sector_num =0 ; sector_num < end; sector_num += n) { +for ( ; offset < s->common.len; offset += n *BDRV_SECTOR_SIZE ) {bool copy;/* Note that even when no rate limit is applied we need to yield
@@ -150,28 +148,26 @@ static void coroutine_fn stream_run(void *opaque) copy = false; - ret =bdrv_is_allocated (bs, sector_num, + ret =bdrv_is_allocated (bs, offset /BDRV_SECTOR_SIZE ,STREAM_BUFFER_SIZE /BDRV_SECTOR_SIZE , &n);if (ret ==1 ) {/* Allocated in the top, no need to copy. */ }else if (ret >=0 ) {/* Copy if allocated in the intermediate images. Limit to the -* known-unallocated area [sector_num, sector_num+n). */ +* known-unallocated area [offset, offset+n*BDRV_SECTOR_SIZE). */ ret =bdrv_is_allocated_above (backing_bs (bs), base, - sector_num, n, &n); + offset /BDRV_SECTOR_SIZE , n, &n);/* Finish early if end of backing file has been reached */ if (ret ==0 && n ==0 ) { - n = end - sector_num; + n = (s->common.len - offset) /BDRV_SECTOR_SIZE ; } copy = (ret ==1 ); } -trace_stream_one_iteration (s, sector_num *BDRV_SECTOR_SIZE , - n *BDRV_SECTOR_SIZE , ret); +trace_stream_one_iteration (s, offset, n *BDRV_SECTOR_SIZE , ret);if (copy) { - ret =stream_populate (blk, sector_num *BDRV_SECTOR_SIZE , - n *BDRV_SECTOR_SIZE , buf); + ret =stream_populate (blk, offset, n *BDRV_SECTOR_SIZE , buf); }if (ret <0 ) { BlockErrorAction action =
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 025/100] commit: Switch commit_populate() to byte-based
In reply to Kevin WolfFrom: Eric Blake <[email protected]>
We are gradually converting to byte-based interfaces, as they are easier to reason about than sector-based. Start by converting an internal function (no semantic change).
--- block/commit.c | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-)
block/commit.c +8 -7
@@ -47,26 +47,25 @@ typedef struct CommitBlockJob { } CommitBlockJob; static int coroutine_fn commit_populate(BlockBackend *bs, BlockBackend *base, -int64_t sector_num,int nb_sectors, +int64_t offset,uint64_t bytes,void *buf) {int ret =0 ;QEMUIOVector qiov;struct iovec iov = { .iov_base = buf, - .iov_len = nb_sectors *BDRV_SECTOR_SIZE , + .iov_len = bytes, }; +assert (bytes <SIZE_MAX );qemu_iovec_init_external (&qiov, &iov,1 ); - ret =blk_co_preadv (bs, sector_num *BDRV_SECTOR_SIZE , - qiov.size, &qiov,0 ); + ret =blk_co_preadv (bs, offset, qiov.size, &qiov,0 );if (ret <0 ) {return ret; } - ret =blk_co_pwritev (base, sector_num *BDRV_SECTOR_SIZE , - qiov.size, &qiov,0 ); + ret =blk_co_pwritev (base, offset, qiov.size, &qiov,0 );if (ret <0 ) {return ret; }
@@ -193,7 +192,9 @@ static void coroutine_fn commit_run(void *opaque)trace_commit_one_iteration (s, sector_num *BDRV_SECTOR_SIZE , n *BDRV_SECTOR_SIZE , ret);if (copy) { - ret =commit_populate (s->top, s->base, sector_num, n, buf); + ret =commit_populate (s->top, s->base, + sector_num *BDRV_SECTOR_SIZE , + n *BDRV_SECTOR_SIZE , buf); bytes_written += n *BDRV_SECTOR_SIZE ; }if (ret <0 ) {
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 026/100] commit: Switch commit_run() to byte-based
In reply to Kevin WolfFrom: Eric Blake <[email protected]>
We are gradually converting to byte-based interfaces, as they are easier to reason about than sector-based. Change the internal loop iteration of committing to track by bytes instead of sectors (although we are still guaranteed that we iterate by steps that are sector-aligned).
--- block/commit.c | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-)
block/commit.c +6 -10
@@ -143,17 +143,16 @@ static void coroutine_fn commit_run(void *opaque) {CommitBlockJob *s = opaque;CommitCompleteData *data; -int64_t sector_num, end; +int64_t offset;uint64_t delay_ns =0 ;int ret =0 ; -int n =0 ; +int n =0 ;/* sectors */ void *buf =NULL ;int bytes_written =0 ;int64_t base_len; ret = s->common.len =blk_getlength (s->top); -if (s->common.len <0 ) { goto out; }
@@ -170,10 +169,9 @@ static void coroutine_fn commit_run(void *opaque) } } - end = s->common.len >>BDRV_SECTOR_BITS ; buf =blk_blockalign (s->top,COMMIT_BUFFER_SIZE ); -for (sector_num =0 ; sector_num < end; sector_num += n) { +for (offset =0 ; offset < s->common.len; offset += n *BDRV_SECTOR_SIZE ) {bool copy;/* Note that even when no rate limit is applied we need to yield
@@ -185,15 +183,13 @@ static void coroutine_fn commit_run(void *opaque) }/* Copy if allocated above the base */ ret =bdrv_is_allocated_above (blk_bs (s->top),blk_bs (s->base), - sector_num, + offset /BDRV_SECTOR_SIZE ,COMMIT_BUFFER_SIZE /BDRV_SECTOR_SIZE , &n); copy = (ret ==1 ); -trace_commit_one_iteration (s, sector_num *BDRV_SECTOR_SIZE , - n *BDRV_SECTOR_SIZE , ret); +trace_commit_one_iteration (s, offset, n *BDRV_SECTOR_SIZE , ret);if (copy) { - ret =commit_populate (s->top, s->base, - sector_num *BDRV_SECTOR_SIZE , + ret =commit_populate (s->top, s->base, offset, n *BDRV_SECTOR_SIZE , buf); bytes_written += n *BDRV_SECTOR_SIZE ; }
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 028/100] mirror: Switch mirror_do_zero_or_discard() to byte-based
In reply to Kevin WolfFrom: Eric Blake <[email protected]>
We are gradually converting to byte-based interfaces, as they are easier to reason about than sector-based. Convert another internal function (no semantic change).
--- block/mirror.c | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-)
block/mirror.c +11 -9
@@ -305,8 +305,8 @@ static int mirror_do_read(MirrorBlockJob *s, int64_t sector_num, }static void mirror_do_zero_or_discard (MirrorBlockJob *s, -int64_t sector_num, -int nb_sectors, +int64_t offset, +uint64_t bytes,bool is_discard) {MirrorOp *op;
@@ -315,16 +315,16 @@ static void mirror_do_zero_or_discard(MirrorBlockJob *s,* so the freeing in mirror_iteration_done is nop. */ op =g_new0 (MirrorOp,1 ); op->s = s; - op->offset = sector_num *BDRV_SECTOR_SIZE ; - op->bytes = nb_sectors *BDRV_SECTOR_SIZE ; + op->offset = offset; + op->bytes = bytes; s->in_flight++; - s->bytes_in_flight += nb_sectors *BDRV_SECTOR_SIZE ; + s->bytes_in_flight += bytes;if (is_discard) { -blk_aio_pdiscard (s->target, sector_num <<BDRV_SECTOR_BITS , +blk_aio_pdiscard (s->target, offset, op->bytes, mirror_write_complete, op); }else { -blk_aio_pwrite_zeroes (s->target, sector_num *BDRV_SECTOR_SIZE , +blk_aio_pwrite_zeroes (s->target, offset, op->bytes, s->unmap ?BDRV_REQ_MAY_UNMAP :0 , mirror_write_complete, op); }
@@ -453,7 +453,8 @@ static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s)break ;case MIRROR_METHOD_ZERO :case MIRROR_METHOD_DISCARD : -mirror_do_zero_or_discard (s, sector_num, io_sectors, +mirror_do_zero_or_discard (s, sector_num *BDRV_SECTOR_SIZE , + io_sectors *BDRV_SECTOR_SIZE , mirror_method ==MIRROR_METHOD_DISCARD );if (write_zeroes_ok) { io_bytes_acct =0 ;
@@ -657,7 +658,8 @@ static int coroutine_fn mirror_dirty_init(MirrorBlockJob *s)continue ; } -mirror_do_zero_or_discard (s, sector_num, nb_sectors, false); +mirror_do_zero_or_discard (s, sector_num *BDRV_SECTOR_SIZE , + nb_sectors *BDRV_SECTOR_SIZE , false); sector_num += nb_sectors; }
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 029/100] mirror: Update signature of mirror_clip_sectors()
In reply to Kevin WolfFrom: Eric Blake <[email protected]>
Rather than having a void function that modifies its input in-place as the output, change the signature to reduce a layer of indirection and return the result.
--- block/mirror.c | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-)
block/mirror.c +8 -7
@@ -176,12 +176,12 @@ static void mirror_read_complete(void *opaque, int ret)aio_context_release (blk_get_aio_context (s->common.blk)); } -static inline void mirror_clip_sectors (MirrorBlockJob *s, -int64_t sector_num, -int *nb_sectors) +static inline int mirror_clip_sectors (MirrorBlockJob *s, +int64_t sector_num, +int nb_sectors) { - *nb_sectors =MIN (*nb_sectors, - s->bdev_length /BDRV_SECTOR_SIZE - sector_num); +return MIN (nb_sectors, + s->bdev_length /BDRV_SECTOR_SIZE - sector_num); }/* Round sector_num and/or nb_sectors to target cluster if COW is needed, and
@@ -216,7 +216,8 @@ static int mirror_cow_align(MirrorBlockJob *s, }/* Clipping may result in align_nb_sectors unaligned to chunk boundary, but * that doesn't matter because it's already the end of source image. */ -mirror_clip_sectors (s, align_sector_num, &align_nb_sectors); + align_nb_sectors =mirror_clip_sectors (s, align_sector_num, + align_nb_sectors); ret = align_sector_num + align_nb_sectors - (*sector_num + *nb_sectors); *sector_num = align_sector_num;
@@ -445,7 +446,7 @@ static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s)return 0 ; } -mirror_clip_sectors (s, sector_num, &io_sectors); + io_sectors =mirror_clip_sectors (s, sector_num, io_sectors);switch (mirror_method) {case MIRROR_METHOD_COPY : io_sectors =mirror_do_read (s, sector_num, io_sectors);
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 027/100] mirror: Switch MirrorBlockJob to byte-based
In reply to Kevin WolfFrom: Eric Blake <[email protected]>
We are gradually converting to byte-based interfaces, as they are easier to reason about than sector-based. Continue by converting an internal structure (no semantic change), and all references to the buffer size.
Add an assertion that our use of s->granularity >> BDRV_SECTOR_BITS (necessary for interaction with sector-based dirty bitmaps, until a later patch converts those to be byte-based) does not suffer from truncation problems.
[checkpatch has a false positive on use of MIN() in this patch]
--- block/mirror.c | 84 +++++++++++++++++++++++++++++----------------------------- 1 file changed, 42 insertions(+), 42 deletions(-)
block/mirror.c +42 -42
@@ -24,9 +24,8 @@#define SLICE_TIME 100000000ULL/* ns */ #define MAX_IN_FLIGHT 16 -#define MAX_IO_SECTORS ((1 << 20) >> BDRV_SECTOR_BITS)/* 1 Mb */ -#define DEFAULT_MIRROR_BUF_SIZE \ - (MAX_IN_FLIGHT * MAX_IO_SECTORS * BDRV_SECTOR_SIZE) +#define MAX_IO_BYTES (1 << 20)/* 1 Mb */ +#define DEFAULT_MIRROR_BUF_SIZE (MAX_IN_FLIGHT * MAX_IO_BYTES)/* The mirroring buffer is a list of granularity-sized chunks. * Free chunks are organized in a list.
@@ -67,11 +66,11 @@ typedef struct MirrorBlockJob {uint64_t last_pause_ns;unsigned long *in_flight_bitmap;int in_flight; -int64_t sectors_in_flight; +int64_t bytes_in_flight;int ret;bool unmap;bool waiting_for_io; -int target_cluster_sectors; +int target_cluster_size;int max_iov;bool initial_zeroing_ongoing; } MirrorBlockJob;
@@ -79,8 +78,8 @@ typedef struct MirrorBlockJob {typedef struct MirrorOp {MirrorBlockJob *s;QEMUIOVector qiov; -int64_t sector_num; -int nb_sectors; +int64_t offset; +uint64_t bytes; }MirrorOp ; static BlockErrorAction mirror_error_action(MirrorBlockJob *s, bool read,
@@ -101,13 +100,12 @@ static void mirror_iteration_done(MirrorOp *op, int ret)MirrorBlockJob *s = op->s;struct iovec *iov;int64_t chunk_num; -int i, nb_chunks, sectors_per_chunk; +int i, nb_chunks; -trace_mirror_iteration_done (s, op->sector_num *BDRV_SECTOR_SIZE , - op->nb_sectors *BDRV_SECTOR_SIZE , ret); +trace_mirror_iteration_done (s, op->offset, op->bytes, ret); s->in_flight--; - s->sectors_in_flight -= op->nb_sectors; + s->bytes_in_flight -= op->bytes; iov = op->qiov.iov;for (i =0 ; i < op->qiov.niov; i++) {MirrorBuffer *buf = (MirrorBuffer *) iov[i].iov_base;
@@ -115,16 +113,15 @@ static void mirror_iteration_done(MirrorOp *op, int ret) s->buf_free_count++; } - sectors_per_chunk = s->granularity >>BDRV_SECTOR_BITS ; - chunk_num = op->sector_num / sectors_per_chunk; - nb_chunks =DIV_ROUND_UP (op->nb_sectors, sectors_per_chunk); + chunk_num = op->offset / s->granularity; + nb_chunks =DIV_ROUND_UP (op->bytes, s->granularity);bitmap_clear (s->in_flight_bitmap, chunk_num, nb_chunks);if (ret >=0 ) {if (s->cow_bitmap) {bitmap_set (s->cow_bitmap, chunk_num, nb_chunks); }if (!s->initial_zeroing_ongoing) { - s->common.offset += (uint64_t )op->nb_sectors *BDRV_SECTOR_SIZE ; + s->common.offset += op->bytes; } }qemu_iovec_destroy (&op->qiov);
@@ -144,7 +141,8 @@ static void mirror_write_complete(void *opaque, int ret)if (ret <0 ) {BlockErrorAction action; -bdrv_set_dirty_bitmap (s->dirty_bitmap, op->sector_num, op->nb_sectors); +bdrv_set_dirty_bitmap (s->dirty_bitmap, op->offset >>BDRV_SECTOR_BITS , + op->bytes >>BDRV_SECTOR_BITS ); action =mirror_error_action (s, false, -ret);if (action ==BLOCK_ERROR_ACTION_REPORT && s->ret >=0 ) { s->ret = ret;
@@ -163,7 +161,8 @@ static void mirror_read_complete(void *opaque, int ret)if (ret <0 ) {BlockErrorAction action; -bdrv_set_dirty_bitmap (s->dirty_bitmap, op->sector_num, op->nb_sectors); +bdrv_set_dirty_bitmap (s->dirty_bitmap, op->offset >>BDRV_SECTOR_BITS , + op->bytes >>BDRV_SECTOR_BITS ); action =mirror_error_action (s, true, -ret);if (action ==BLOCK_ERROR_ACTION_REPORT && s->ret >=0 ) { s->ret = ret;
@@ -171,7 +170,7 @@ static void mirror_read_complete(void *opaque, int ret)mirror_iteration_done (op, ret); }else { -blk_aio_pwritev (s->target, op->sector_num *BDRV_SECTOR_SIZE , &op->qiov, +blk_aio_pwritev (s->target, op->offset, &op->qiov,0 , mirror_write_complete, op); }aio_context_release (blk_get_aio_context (s->common.blk));
@@ -211,7 +210,8 @@ static int mirror_cow_align(MirrorBlockJob *s, align_nb_sectors = max_sectors;if (need_cow) { align_nb_sectors =QEMU_ALIGN_DOWN (align_nb_sectors, - s->target_cluster_sectors); + s->target_cluster_size >> +BDRV_SECTOR_BITS ); } }/* Clipping may result in align_nb_sectors unaligned to chunk boundary, but
@@ -277,8 +277,8 @@ static int mirror_do_read(MirrorBlockJob *s, int64_t sector_num,/* Allocate a MirrorOp that is used as an AIO callback. */ op =g_new (MirrorOp,1 ); op->s = s; - op->sector_num = sector_num; - op->nb_sectors = nb_sectors; + op->offset = sector_num *BDRV_SECTOR_SIZE ; + op->bytes = nb_sectors *BDRV_SECTOR_SIZE ;/* Now make a QEMUIOVector taking enough granularity-sized chunks * from s->buf_free.
@@ -295,7 +295,7 @@ static int mirror_do_read(MirrorBlockJob *s, int64_t sector_num,/* Copy the dirty cluster. */ s->in_flight++; - s->sectors_in_flight += nb_sectors; + s->bytes_in_flight += nb_sectors *BDRV_SECTOR_SIZE ;trace_mirror_one_iteration (s, sector_num *BDRV_SECTOR_SIZE , nb_sectors *BDRV_SECTOR_SIZE );
@@ -315,19 +315,17 @@ static void mirror_do_zero_or_discard(MirrorBlockJob *s,* so the freeing in mirror_iteration_done is nop. */ op =g_new0 (MirrorOp,1 ); op->s = s; - op->sector_num = sector_num; - op->nb_sectors = nb_sectors; + op->offset = sector_num *BDRV_SECTOR_SIZE ; + op->bytes = nb_sectors *BDRV_SECTOR_SIZE ; s->in_flight++; - s->sectors_in_flight += nb_sectors; + s->bytes_in_flight += nb_sectors *BDRV_SECTOR_SIZE ;if (is_discard) {blk_aio_pdiscard (s->target, sector_num <<BDRV_SECTOR_BITS , - op->nb_sectors <<BDRV_SECTOR_BITS , - mirror_write_complete, op); + op->bytes, mirror_write_complete, op); }else {blk_aio_pwrite_zeroes (s->target, sector_num *BDRV_SECTOR_SIZE , - op->nb_sectors *BDRV_SECTOR_SIZE , - s->unmap ?BDRV_REQ_MAY_UNMAP :0 , + op->bytes, s->unmap ?BDRV_REQ_MAY_UNMAP :0 , mirror_write_complete, op); } }
@@ -342,8 +340,7 @@ static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s)int64_t end = s->bdev_length /BDRV_SECTOR_SIZE ;int sectors_per_chunk = s->granularity >>BDRV_SECTOR_BITS ;bool write_zeroes_ok =bdrv_can_write_zeroes_with_unmap (blk_bs (s->target)); -int max_io_sectors =MAX ((s->buf_size >>BDRV_SECTOR_BITS ) /MAX_IN_FLIGHT , -MAX_IO_SECTORS ); +int max_io_bytes =MAX (s->buf_size /MAX_IN_FLIGHT ,MAX_IO_BYTES );bdrv_dirty_bitmap_lock (s->dirty_bitmap); sector_num =bdrv_dirty_iter_next (s->dbi);
@@ -415,9 +412,10 @@ static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s) nb_chunks * sectors_per_chunk, &io_sectors, &file);if (ret <0 ) { - io_sectors =MIN (nb_chunks * sectors_per_chunk, max_io_sectors); + io_sectors =MIN (nb_chunks * sectors_per_chunk, + max_io_bytes >>BDRV_SECTOR_BITS ); }else if (ret &BDRV_BLOCK_DATA ) { - io_sectors =MIN (io_sectors, max_io_sectors); + io_sectors =MIN (io_sectors, max_io_bytes >>BDRV_SECTOR_BITS ); } io_sectors -= io_sectors % sectors_per_chunk;
@@ -719,7 +717,6 @@ static void coroutine_fn mirror_run(void *opaque)char backing_filename[2 ];/* we only need 2 characters because we are only checking for a NULL string */ int ret =0 ; -int target_cluster_size =BDRV_SECTOR_SIZE ;if (block_job_is_cancelled (&s->common)) { goto immediate_exit;
@@ -771,14 +768,15 @@ static void coroutine_fn mirror_run(void *opaque)bdrv_get_backing_filename (target_bs, backing_filename,sizeof (backing_filename));if (!bdrv_get_info (target_bs, &bdi) && bdi.cluster_size) { - target_cluster_size = bdi.cluster_size; + s->target_cluster_size = bdi.cluster_size; + }else { + s->target_cluster_size =BDRV_SECTOR_SIZE ; } -if (backing_filename[0 ] && !target_bs->backing - && s->granularity < target_cluster_size) { - s->buf_size =MAX (s->buf_size, target_cluster_size); +if (backing_filename[0 ] && !target_bs->backing && + s->granularity < s->target_cluster_size) { + s->buf_size =MAX (s->buf_size, s->target_cluster_size); s->cow_bitmap =bitmap_new (length); } - s->target_cluster_sectors = target_cluster_size >>BDRV_SECTOR_BITS ; s->max_iov =MIN (bs->bl.max_iov, target_bs->bl.max_iov); s->buf =qemu_try_blockalign (bs, s->buf_size);
@@ -814,10 +812,10 @@ static void coroutine_fn mirror_run(void *opaque) cnt =bdrv_get_dirty_count (s->dirty_bitmap);/* s->common.offset contains the number of bytes already processed so * far, cnt is the number of dirty sectors remaining and -* s->sectors_in_flight is the number of sectors currently being +* s->bytes_in_flight is the number of bytes currently being * processed; together those are the current total operation length */ - s->common.len = s->common.offset + - (cnt + s->sectors_in_flight) *BDRV_SECTOR_SIZE ; + s->common.len = s->common.offset + s->bytes_in_flight + + cnt *BDRV_SECTOR_SIZE ;/* Note that even when no rate limit is applied we need to yield * periodically with no pending I/O so that bdrv_drain_all() returns.
@@ -1150,6 +1148,8 @@ static void mirror_start_job(const char *job_id, BlockDriverState *bs, }assert ((granularity & (granularity -1 )) ==0 ); +/* Granularity must be large enough for sector-based dirty bitmap */ +assert (granularity >=BDRV_SECTOR_SIZE );if (buf_size <0 ) {error_setg (errp,"Invalid parameter 'buf-size'" );
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 030/100] mirror: Switch mirror_cow_align() to byte-based
In reply to Kevin WolfFrom: Eric Blake <[email protected]>
We are gradually converting to byte-based interfaces, as they are easier to reason about than sector-based. Convert another internal function (no semantic change), and add mirror_clip_bytes() as a counterpart to mirror_clip_sectors(). Some of the conversion is a bit tricky, requiring temporaries to convert between units; it will be cleared up in a following patch.
--- block/mirror.c | 63 ++++++++++++++++++++++++++++++++++------------------------ 1 file changed, 37 insertions(+), 26 deletions(-)
block/mirror.c +37 -26
@@ -176,6 +176,15 @@ static void mirror_read_complete(void *opaque, int ret)aio_context_release (blk_get_aio_context (s->common.blk)); } +/* Clip bytes relative to offset to not exceed end-of-file */ +static inline int64_t mirror_clip_bytes (MirrorBlockJob *s, +int64_t offset, +int64_t bytes) +{ +return MIN (bytes, s->bdev_length - offset); +} + +/* Clip nb_sectors relative to sector_num to not exceed end-of-file */ static inline int mirror_clip_sectors (MirrorBlockJob *s,int64_t sector_num,int nb_sectors)
@@ -184,44 +193,38 @@ static inline int mirror_clip_sectors(MirrorBlockJob *s, s->bdev_length / BDRV_SECTOR_SIZE - sector_num); } -/* Round sector_num and/or nb_sectors to target cluster if COW is needed, and -* return the offset of the adjusted tail sector against original. */ -static int mirror_cow_align (MirrorBlockJob *s, -int64_t *sector_num, -int *nb_sectors) +/* Round offset and/or bytes to target cluster if COW is needed, and +* return the offset of the adjusted tail against original. */ +static int mirror_cow_align (MirrorBlockJob *s,int64_t *offset, +unsigned int *bytes) {bool need_cow;int ret =0 ; -int chunk_sectors = s->granularity >>BDRV_SECTOR_BITS ; -int64_t align_sector_num = *sector_num; -int align_nb_sectors = *nb_sectors; -int max_sectors = chunk_sectors * s->max_iov; +int64_t align_offset = *offset; +unsigned int align_bytes = *bytes; +int max_bytes = s->granularity * s->max_iov; - need_cow = !test_bit (*sector_num / chunk_sectors, s->cow_bitmap); - need_cow |= !test_bit ((*sector_num + *nb_sectors -1 ) / chunk_sectors, + need_cow = !test_bit (*offset / s->granularity, s->cow_bitmap); + need_cow |= !test_bit ((*offset + *bytes -1 ) / s->granularity, s->cow_bitmap);if (need_cow) { -bdrv_round_sectors_to_clusters (blk_bs (s->target), *sector_num, - *nb_sectors, &align_sector_num, - &align_nb_sectors); +bdrv_round_to_clusters (blk_bs (s->target), *offset, *bytes, + &align_offset, &align_bytes); } -if (align_nb_sectors > max_sectors) { - align_nb_sectors = max_sectors; +if (align_bytes > max_bytes) { + align_bytes = max_bytes;if (need_cow) { - align_nb_sectors =QEMU_ALIGN_DOWN (align_nb_sectors, - s->target_cluster_size >> -BDRV_SECTOR_BITS ); + align_bytes =QEMU_ALIGN_DOWN (align_bytes, s->target_cluster_size); } } -/* Clipping may result in align_nb_sectors unaligned to chunk boundary, but +/* Clipping may result in align_bytes unaligned to chunk boundary, but * that doesn't matter because it's already the end of source image. */ - align_nb_sectors =mirror_clip_sectors (s, align_sector_num, - align_nb_sectors); + align_bytes =mirror_clip_bytes (s, align_offset, align_bytes); - ret = align_sector_num + align_nb_sectors - (*sector_num + *nb_sectors); - *sector_num = align_sector_num; - *nb_sectors = align_nb_sectors; + ret = align_offset + align_bytes - (*offset + *bytes); + *offset = align_offset; + *bytes = align_bytes;assert (ret >=0 );return ret; }
@@ -257,10 +260,18 @@ static int mirror_do_read(MirrorBlockJob *s, int64_t sector_num, nb_sectors =MIN (s->buf_size >>BDRV_SECTOR_BITS , nb_sectors); nb_sectors =MIN (max_sectors, nb_sectors);assert (nb_sectors); +assert (nb_sectors <BDRV_REQUEST_MAX_SECTORS ); ret = nb_sectors;if (s->cow_bitmap) { - ret +=mirror_cow_align (s, §or_num, &nb_sectors); +int64_t offset = sector_num *BDRV_SECTOR_SIZE ; +unsigned int bytes = nb_sectors *BDRV_SECTOR_SIZE ; +int gap; + + gap =mirror_cow_align (s, &offset, &bytes); + sector_num = offset /BDRV_SECTOR_SIZE ; + nb_sectors = bytes /BDRV_SECTOR_SIZE ; + ret += gap /BDRV_SECTOR_SIZE ; }assert (nb_sectors <<BDRV_SECTOR_BITS <= s->buf_size);/* The sector range must meet granularity because:
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 006/100] vvfat: replace tabs by 8 spaces
In reply to Kevin WolfFrom: Hervé Poussineau <[email protected]>
This was a complete mess. On 2299 indented lines:
- 1329 were with spaces only
- 617 with tabulations only
- 353 with spaces and tabulations
--- block/vvfat.c | 2054 ++++++++++++++++++++++++++++----------------------------- 1 file changed, 1027 insertions(+), 1027 deletions(-)
block/vvfat.c +1027 -1027
@@ -100,12 +100,12 @@ static inline void* array_get(array_t* array,unsigned int index) {static inline int array_ensure_allocated (array_t * array,int index) {if ((index +1 ) * array->item_size > array->size) { -int new_size = (index +32 ) * array->item_size; - array->pointer =g_realloc (array->pointer, new_size); -if (!array->pointer) -return -1 ; - array->size = new_size; - array->next = index +1 ; +int new_size = (index +32 ) * array->item_size; + array->pointer =g_realloc (array->pointer, new_size); +if (!array->pointer) +return -1 ; + array->size = new_size; + array->next = index +1 ; }return 0 ;
@@ -115,7 +115,7 @@ static inline void* array_get_next(array_t* array) {unsigned int next = array->next;if (array_ensure_allocated (array, next) <0 ) -return NULL ; +return NULL ; array->next = next +1 ;return array_get (array, next);
@@ -123,15 +123,15 @@ static inline void* array_get_next(array_t* array) {static inline void *array_insert (array_t * array,unsigned int index,unsigned int count) {if ((array->next+count)*array->item_size>array->size) { -int increment=count*array->item_size; - array->pointer=g_realloc (array->pointer,array->size+increment); -if (!array->pointer) +int increment=count*array->item_size; + array->pointer=g_realloc (array->pointer,array->size+increment); +if (!array->pointer)return NULL ; - array->size+=increment; + array->size+=increment; }memmove (array->pointer+(index+count)*array->item_size, - array->pointer+index*array->item_size, - (array->next-index)*array->item_size); + array->pointer+index*array->item_size, + (array->next-index)*array->item_size); array->next+=count;return array->pointer+index*array->item_size; }
@@ -146,12 +146,12 @@ static inline int array_roll(array_t* array,int index_to,int index_from,int counint is;if (!array || - index_to<0 || index_to>=array->next || - index_from<0 || index_from>=array->next) -return -1 ; + index_to<0 || index_to>=array->next || + index_from<0 || index_from>=array->next) +return -1 ;if (index_to==index_from) -return 0 ; +return 0 ; is=array->item_size; from=array->pointer+index_from*is;
@@ -160,9 +160,9 @@ static inline int array_roll(array_t* array,int index_to,int index_from,int counmemcpy (buf,from,is*count);if (index_to<index_from) -memmove (to+is*count,to,from-to); +memmove (to+is*count,to,from-to);else -memmove (from,from+is*count,to-from); +memmove (from,from+is*count,to-from);memcpy (to,buf,is*count);
@@ -177,7 +177,7 @@ static inline int array_remove_slice(array_t* array,int index, int count)assert (count >0 );assert (index + count <= array->next);if (array_roll (array,array->next-1 ,index,count)) -return -1 ; +return -1 ; array->next -= count;return 0 ; }
@@ -216,21 +216,21 @@ typedef struct bootsector_t {uint32_t total_sectors;union {struct { -uint8_t drive_number; -uint8_t current_head; -uint8_t signature; -uint32_t id; -uint8_t volume_label[11 ]; - } QEMU_PACKED fat16; -struct { -uint32_t sectors_per_fat; -uint16_t flags; -uint8_t major,minor; -uint32_t first_cluster_of_root_directory; -uint16_t info_sector; -uint16_t backup_boot_sector; -uint16_t ignored; - } QEMU_PACKED fat32; +uint8_t drive_number; +uint8_t current_head; +uint8_t signature; +uint32_t id; +uint8_t volume_label[11 ]; + } QEMU_PACKED fat16; +struct { +uint32_t sectors_per_fat; +uint16_t flags; +uint8_t major,minor; +uint32_t first_cluster_of_root_directory; +uint16_t info_sector; +uint16_t backup_boot_sector; +uint16_t ignored; + } QEMU_PACKED fat32; } u;uint8_t fat_type[8 ];uint8_t ignored[0x1c0 ];
@@ -284,25 +284,25 @@ typedef struct mapping_t {/* the clusters of a file may be in any order; this points to the first */ int first_mapping_index;union { -/* offset is -* - the offset in the file (in clusters) for a file, or -* - the next cluster of the directory for a directory, and -* - the address of the buffer for a faked entry -*/ -struct { -uint32_t offset; - } file; -struct { -int parent_mapping_index; -int first_dir_index; - } dir; +/* offset is +* - the offset in the file (in clusters) for a file, or +* - the next cluster of the directory for a directory, and +* - the address of the buffer for a faked entry +*/ +struct { +uint32_t offset; + } file; +struct { +int parent_mapping_index; +int first_dir_index; + } dir; } info;/* path contains the full path, i.e. it always starts with s->path */ char * path;enum {MODE_UNDEFINED =0 ,MODE_NORMAL =1 ,MODE_MODIFIED =2 , -MODE_DIRECTORY =4 ,MODE_FAKED =8 , -MODE_DELETED =16 ,MODE_RENAMED =32 } mode; +MODE_DIRECTORY =4 ,MODE_FAKED =8 , +MODE_DELETED =16 ,MODE_RENAMED =32 } mode;int read_only; } mapping_t;
@@ -419,12 +419,12 @@ static inline int short2long_name(char* dest,const char* src)int len;for (i=0 ;i<129 && src[i];i++) { dest[2 *i]=src[i]; - dest[2 *i+1 ]=0 ; + dest[2 *i+1 ]=0 ; } len=2 *i; dest[2 *i]=dest[2 *i+1 ]=0 ;for (i=2 *i+2 ;(i%26 );i++) - dest[i]=0xff ; + dest[i]=0xff ;return len; }
@@ -436,19 +436,19 @@ static inline direntry_t* create_long_filename(BDRVVVFATState* s,const char* fildirentry_t * entry;for (i=0 ;i<number_of_entries;i++) { - entry=array_get_next (&(s->directory)); - entry->attributes=0xf ; - entry->reserved[0 ]=0 ; - entry->begin=0 ; - entry->name[0 ]=(number_of_entries-i)|(i==0 ?0x40 :0 ); + entry=array_get_next (&(s->directory)); + entry->attributes=0xf ; + entry->reserved[0 ]=0 ; + entry->begin=0 ; + entry->name[0 ]=(number_of_entries-i)|(i==0 ?0x40 :0 ); }for (i=0 ;i<26 *number_of_entries;i++) { -int offset=(i%26 ); -if (offset<10 ) offset=1 +offset; -else if (offset<22 ) offset=14 +offset-10 ; -else offset=28 +offset-22 ; - entry=array_get (&(s->directory),s->directory.next-1 -(i/26 )); - entry->name[offset]=buffer[i]; +int offset=(i%26 ); +if (offset<10 ) offset=1 +offset; +else if (offset<22 ) offset=14 +offset-10 ; +else offset=28 +offset-22 ; + entry=array_get (&(s->directory),s->directory.next-1 -(i/26 )); + entry->name[offset]=buffer[i]; }return array_get (&(s->directory),s->directory.next-number_of_entries); }
@@ -471,7 +471,7 @@ static char is_long_name(const direntry_t* direntry)static char is_short_name (const direntry_t * direntry) {return !is_volume_label (direntry) && !is_long_name (direntry) - && !is_free (direntry); + && !is_free (direntry); }static char is_directory (const direntry_t * direntry)
@@ -527,73 +527,73 @@ static uint16_t fat_datetime(time_t time,int return_time) { t = &t1;localtime_r (&time,t);if (return_time) -return cpu_to_le16 ((t->tm_sec/2 )|(t->tm_min<<5 )|(t->tm_hour<<11 )); +return cpu_to_le16 ((t->tm_sec/2 )|(t->tm_min<<5 )|(t->tm_hour<<11 ));return cpu_to_le16 ((t->tm_mday)|((t->tm_mon+1 )<<5 )|((t->tm_year-80 )<<9 )); }static inline void fat_set (BDRVVVFATState * s,unsigned int cluster,uint32_t value) {if (s->fat_type==32 ) { -uint32_t * entry=array_get (&(s->fat),cluster); - *entry=cpu_to_le32 (value); +uint32_t * entry=array_get (&(s->fat),cluster); + *entry=cpu_to_le32 (value); }else if (s->fat_type==16 ) { -uint16_t * entry=array_get (&(s->fat),cluster); - *entry=cpu_to_le16 (value&0xffff ); +uint16_t * entry=array_get (&(s->fat),cluster); + *entry=cpu_to_le16 (value&0xffff ); }else { -int offset = (cluster*3 /2 ); -unsigned char * p =array_get (&(s->fat), offset); +int offset = (cluster*3 /2 ); +unsigned char * p =array_get (&(s->fat), offset);switch (cluster&1 ) { -case 0 : - p[0 ] = value&0xff ; - p[1 ] = (p[1 ]&0xf0 ) | ((value>>8 )&0xf ); -break ; -case 1 : - p[0 ] = (p[0 ]&0xf ) | ((value&0xf )<<4 ); - p[1 ] = (value>>4 ); -break ; - } +case 0 : + p[0 ] = value&0xff ; + p[1 ] = (p[1 ]&0xf0 ) | ((value>>8 )&0xf ); +break ; +case 1 : + p[0 ] = (p[0 ]&0xf ) | ((value&0xf )<<4 ); + p[1 ] = (value>>4 ); +break ; + } } }static inline uint32_t fat_get (BDRVVVFATState * s,unsigned int cluster) {if (s->fat_type==32 ) { -uint32_t * entry=array_get (&(s->fat),cluster); -return le32_to_cpu (*entry); +uint32_t * entry=array_get (&(s->fat),cluster); +return le32_to_cpu (*entry); }else if (s->fat_type==16 ) { -uint16_t * entry=array_get (&(s->fat),cluster); -return le16_to_cpu (*entry); +uint16_t * entry=array_get (&(s->fat),cluster); +return le16_to_cpu (*entry); }else { -const uint8_t * x=(uint8_t *)(s->fat.pointer)+cluster*3 /2 ; -return ((x[0 ]|(x[1 ]<<8 ))>>(cluster&1 ?4 :0 ))&0x0fff ; +const uint8_t * x=(uint8_t *)(s->fat.pointer)+cluster*3 /2 ; +return ((x[0 ]|(x[1 ]<<8 ))>>(cluster&1 ?4 :0 ))&0x0fff ; } }static inline int fat_eof (BDRVVVFATState * s,uint32_t fat_entry) {if (fat_entry>s->max_fat_value-8 ) -return -1 ; +return -1 ;return 0 ; }static inline void init_fat (BDRVVVFATState * s) {if (s->fat_type ==12 ) { -array_init (&(s->fat),1 ); -array_ensure_allocated (&(s->fat), - s->sectors_per_fat *0x200 *3 /2 -1 ); +array_init (&(s->fat),1 ); +array_ensure_allocated (&(s->fat), + s->sectors_per_fat *0x200 *3 /2 -1 ); }else { -array_init (&(s->fat),(s->fat_type==32 ?4 :2 )); -array_ensure_allocated (&(s->fat), - s->sectors_per_fat *0x200 / s->fat.item_size -1 ); +array_init (&(s->fat),(s->fat_type==32 ?4 :2 )); +array_ensure_allocated (&(s->fat), + s->sectors_per_fat *0x200 / s->fat.item_size -1 ); }memset (s->fat.pointer,0 ,s->fat.size);switch (s->fat_type) { -case 12 : s->max_fat_value=0xfff ;break ; -case 16 : s->max_fat_value=0xffff ;break ; -case 32 : s->max_fat_value=0x0fffffff ;break ; -default : s->max_fat_value=0 ;/* error... */ +case 12 : s->max_fat_value=0xfff ;break ; +case 16 : s->max_fat_value=0xffff ;break ; +case 32 : s->max_fat_value=0x0fffffff ;break ; +default : s->max_fat_value=0 ;/* error... */ } }
@@ -601,17 +601,17 @@ static inline void init_fat(BDRVVVFATState* s)/* TODO: in create_short_filename, 0xe5->0x05 is not yet handled! */ /* TODO: in parse_short_filename, 0x05->0xe5 is not yet handled! */ static inline direntry_t *create_short_and_long_name (BDRVVVFATState * s, -unsigned int directory_start,const char * filename,int is_dot) +unsigned int directory_start,const char * filename,int is_dot) {int i,j,long_index=s->directory.next;direntry_t * entry =NULL ;direntry_t * entry_long =NULL ;if (is_dot) { - entry=array_get_next (&(s->directory)); + entry=array_get_next (&(s->directory));memset (entry->name,0x20 ,sizeof (entry->name)); -memcpy (entry->name,filename,strlen (filename)); -return entry; +memcpy (entry->name,filename,strlen (filename)); +return entry; } entry_long=create_long_filename (s,filename);
@@ -619,9 +619,9 @@ static inline direntry_t* create_short_and_long_name(BDRVVVFATState* s, i =strlen (filename);for (j = i -1 ; j>0 && filename[j]!='.' ;j--);if (j >0 ) - i = (j >8 ?8 : j); + i = (j >8 ?8 : j);else if (i >8 ) - i =8 ; + i =8 ; entry=array_get_next (&(s->directory));memset (entry->name,0x20 ,sizeof (entry->name));
@@ -635,53 +635,53 @@ static inline direntry_t* create_short_and_long_name(BDRVVVFATState* s,/* upcase & remove unwanted characters */ for (i=10 ;i>=0 ;i--) { -if (i==10 || i==7 )for (;i>0 && entry->name[i]==' ' ;i--); -if (entry->name[i]<=' ' || entry->name[i]>0x7f - ||strchr (".*?<>|\":/\\[];,+='" ,entry->name[i])) - entry->name[i]='_' ; +if (i==10 || i==7 )for (;i>0 && entry->name[i]==' ' ;i--); +if (entry->name[i]<=' ' || entry->name[i]>0x7f + ||strchr (".*?<>|\":/\\[];,+='" ,entry->name[i])) + entry->name[i]='_' ;else if (entry->name[i]>='a' && entry->name[i]<='z' ) entry->name[i]+='A' -'a' ; }/* mangle duplicates */ while (1 ) { -direntry_t * entry1=array_get (&(s->directory),directory_start); -int j; - -for (;entry1<entry;entry1++) -if (!is_long_name (entry1) && !memcmp (entry1->name,entry->name,11 )) -break ;/* found dupe */ -if (entry1==entry)/* no dupe found */ -break ; - -/* use all 8 characters of name */ -if (entry->name[7 ]==' ' ) { -int j; -for (j=6 ;j>0 && entry->name[j]==' ' ;j--) - entry->name[j]='~' ; - } - -/* increment number */ -for (j=7 ;j>0 && entry->name[j]=='9' ;j--) - entry->name[j]='0' ; -if (j>0 ) { -if (entry->name[j]<'0' || entry->name[j]>'9' ) - entry->name[j]='0' ; -else - entry->name[j]++; - } +direntry_t * entry1=array_get (&(s->directory),directory_start); +int j; + +for (;entry1<entry;entry1++) +if (!is_long_name (entry1) && !memcmp (entry1->name,entry->name,11 )) +break ;/* found dupe */ +if (entry1==entry)/* no dupe found */ +break ; + +/* use all 8 characters of name */ +if (entry->name[7 ]==' ' ) { +int j; +for (j=6 ;j>0 && entry->name[j]==' ' ;j--) + entry->name[j]='~' ; + } + +/* increment number */ +for (j=7 ;j>0 && entry->name[j]=='9' ;j--) + entry->name[j]='0' ; +if (j>0 ) { +if (entry->name[j]<'0' || entry->name[j]>'9' ) + entry->name[j]='0' ; +else + entry->name[j]++; + } }/* calculate checksum; propagate to long name */ if (entry_long) {uint8_t chksum=fat_chksum (entry); -/* calculate anew, because realloc could have taken place */ - entry_long=array_get (&(s->directory),long_index); -while (entry_long<entry &&is_long_name (entry_long)) { - entry_long->reserved[1 ]=chksum; - entry_long++; - } +/* calculate anew, because realloc could have taken place */ + entry_long=array_get (&(s->directory),long_index); +while (entry_long<entry &&is_long_name (entry_long)) { + entry_long->reserved[1 ]=chksum; + entry_long++; + } }return entry;
@@ -708,80 +708,80 @@ static int read_directory(BDRVVVFATState* s, int mapping_index)assert (mapping->mode &MODE_DIRECTORY );if (!dir) { - mapping->end = mapping->begin; -return -1 ; + mapping->end = mapping->begin; +return -1 ; } i = mapping->info.dir.first_dir_index = - first_cluster ==0 ?0 : s->directory.next; + first_cluster ==0 ?0 : s->directory.next;/* actually read the directory, and allocate the mappings */ while ((entry=readdir (dir))) { -unsigned int length=strlen (dirname)+2 +strlen (entry->d_name); +unsigned int length=strlen (dirname)+2 +strlen (entry->d_name);char * buffer; -direntry_t * direntry; +direntry_t * direntry;struct stat st; -int is_dot=!strcmp (entry->d_name,"." ); -int is_dotdot=!strcmp (entry->d_name,".." ); +int is_dot=!strcmp (entry->d_name,"." ); +int is_dotdot=!strcmp (entry->d_name,".." ); -if (first_cluster ==0 && (is_dotdot || is_dot)) -continue ; +if (first_cluster ==0 && (is_dotdot || is_dot)) +continue ; - buffer =g_malloc (length); -snprintf (buffer,length,"%s/%s" ,dirname,entry->d_name); + buffer =g_malloc (length); +snprintf (buffer,length,"%s/%s" ,dirname,entry->d_name); -if (stat (buffer,&st)<0 ) { +if (stat (buffer,&st)<0 ) {g_free (buffer);continue ; - } - -/* create directory entry for this file */ - direntry=create_short_and_long_name (s, i, entry->d_name, - is_dot || is_dotdot); - direntry->attributes=(S_ISDIR (st.st_mode)?0x10 :0x20 ); - direntry->reserved[0 ]=direntry->reserved[1 ]=0 ; - direntry->ctime=fat_datetime (st.st_ctime,1 ); - direntry->cdate=fat_datetime (st.st_ctime,0 ); - direntry->adate=fat_datetime (st.st_atime,0 ); - direntry->begin_hi=0 ; - direntry->mtime=fat_datetime (st.st_mtime,1 ); - direntry->mdate=fat_datetime (st.st_mtime,0 ); -if (is_dotdot) -set_begin_of_direntry (direntry, first_cluster_of_parent); -else if (is_dot) -set_begin_of_direntry (direntry, first_cluster); -else - direntry->begin=0 ;/* do that later */ + } + +/* create directory entry for this file */ + direntry=create_short_and_long_name (s, i, entry->d_name, + is_dot || is_dotdot); + direntry->attributes=(S_ISDIR (st.st_mode)?0x10 :0x20 ); + direntry->reserved[0 ]=direntry->reserved[1 ]=0 ; + direntry->ctime=fat_datetime (st.st_ctime,1 ); + direntry->cdate=fat_datetime (st.st_ctime,0 ); + direntry->adate=fat_datetime (st.st_atime,0 ); + direntry->begin_hi=0 ; + direntry->mtime=fat_datetime (st.st_mtime,1 ); + direntry->mdate=fat_datetime (st.st_mtime,0 ); +if (is_dotdot) +set_begin_of_direntry (direntry, first_cluster_of_parent); +else if (is_dot) +set_begin_of_direntry (direntry, first_cluster); +else + direntry->begin=0 ;/* do that later */ if (st.st_size >0x7fffffff ) { -fprintf (stderr,"File %s is larger than 2GB\n" , buffer); +fprintf (stderr,"File %s is larger than 2GB\n" , buffer);g_free (buffer);closedir (dir); -return -2 ; +return -2 ; } - direntry->size=cpu_to_le32 (S_ISDIR (st.st_mode)?0 :st.st_size); - -/* create mapping for this file */ -if (!is_dot && !is_dotdot && (S_ISDIR (st.st_mode) || st.st_size)) { - s->current_mapping =array_get_next (&(s->mapping)); - s->current_mapping->begin=0 ; - s->current_mapping->end=st.st_size; -/* -* we get the direntry of the most recent direntry, which -* contains the short name and all the relevant information. -*/ - s->current_mapping->dir_index=s->directory.next-1 ; - s->current_mapping->first_mapping_index =-1 ; -if (S_ISDIR (st.st_mode)) { - s->current_mapping->mode =MODE_DIRECTORY ; - s->current_mapping->info.dir.parent_mapping_index = - mapping_index; - }else { - s->current_mapping->mode =MODE_UNDEFINED ; - s->current_mapping->info.file.offset =0 ; - } - s->current_mapping->path=buffer; - s->current_mapping->read_only = - (st.st_mode & (S_IWUSR |S_IWGRP |S_IWOTH )) ==0 ; + direntry->size=cpu_to_le32 (S_ISDIR (st.st_mode)?0 :st.st_size); + +/* create mapping for this file */ +if (!is_dot && !is_dotdot && (S_ISDIR (st.st_mode) || st.st_size)) { + s->current_mapping =array_get_next (&(s->mapping)); + s->current_mapping->begin=0 ; + s->current_mapping->end=st.st_size; +/* +* we get the direntry of the most recent direntry, which +* contains the short name and all the relevant information. +*/ + s->current_mapping->dir_index=s->directory.next-1 ; + s->current_mapping->first_mapping_index =-1 ; +if (S_ISDIR (st.st_mode)) { + s->current_mapping->mode =MODE_DIRECTORY ; + s->current_mapping->info.dir.parent_mapping_index = + mapping_index; + }else { + s->current_mapping->mode =MODE_UNDEFINED ; + s->current_mapping->info.file.offset =0 ; + } + s->current_mapping->path=buffer; + s->current_mapping->read_only = + (st.st_mode & (S_IWUSR |S_IWGRP |S_IWOTH )) ==0 ; }else {g_free (buffer); }
@@ -790,25 +790,25 @@ static int read_directory(BDRVVVFATState* s, int mapping_index)/* fill with zeroes up to the end of the cluster */ while (s->directory.next%(0x10 *s->sectors_per_cluster)) { -direntry_t * direntry=array_get_next (&(s->directory)); -memset (direntry,0 ,sizeof (direntry_t)); +direntry_t * direntry=array_get_next (&(s->directory)); +memset (direntry,0 ,sizeof (direntry_t)); }/* TODO: if there are more entries, bootsector has to be adjusted! */ #define ROOT_ENTRIES (0x02 * 0x10 * s->sectors_per_cluster)if (mapping_index ==0 && s->directory.next <ROOT_ENTRIES ) { -/* root directory */ -int cur = s->directory.next; -array_ensure_allocated (&(s->directory),ROOT_ENTRIES -1 ); - s->directory.next =ROOT_ENTRIES ; -memset (array_get (&(s->directory), cur),0 , - (ROOT_ENTRIES - cur) *sizeof (direntry_t)); +/* root directory */ +int cur = s->directory.next; +array_ensure_allocated (&(s->directory),ROOT_ENTRIES -1 ); + s->directory.next =ROOT_ENTRIES ; +memset (array_get (&(s->directory), cur),0 , + (ROOT_ENTRIES - cur) *sizeof (direntry_t)); }/* reget the mapping, since s->mapping was possibly realloc()ed */ mapping =array_get (&(s->mapping), mapping_index); first_cluster += (s->directory.next - mapping->info.dir.first_dir_index) - *0x20 / s->cluster_size; + *0x20 / s->cluster_size; mapping->end = first_cluster; direntry =array_get (&(s->directory), mapping->dir_index);
@@ -856,8 +856,8 @@ static int init_directories(BDRVVVFATState* s,/* add volume label */ { -direntry_t * entry=array_get_next (&(s->directory)); - entry->attributes=0x28 ;/* archive | volume label */ +direntry_t * entry=array_get_next (&(s->directory)); + entry->attributes=0x28 ;/* archive | volume label */ memcpy (entry->name, s->volume_label,sizeof (entry->name)); }
@@ -875,61 +875,61 @@ static int init_directories(BDRVVVFATState* s, mapping->path =g_strdup (dirname); i =strlen (mapping->path);if (i >0 && mapping->path[i -1 ] =='/' ) - mapping->path[i -1 ] ='\0' ; + mapping->path[i -1 ] ='\0' ; mapping->mode =MODE_DIRECTORY ; mapping->read_only =0 ; s->path = mapping->path;for (i =0 , cluster =0 ; i < s->mapping.next; i++) { -/* MS-DOS expects the FAT to be 0 for the root directory -* (except for the media byte). */ -/* LATER TODO: still true for FAT32? */ -int fix_fat = (i !=0 ); - mapping =array_get (&(s->mapping), i); +/* MS-DOS expects the FAT to be 0 for the root directory +* (except for the media byte). */ +/* LATER TODO: still true for FAT32? */ +int fix_fat = (i !=0 ); + mapping =array_get (&(s->mapping), i);if (mapping->mode &MODE_DIRECTORY ) { - mapping->begin = cluster; -if (read_directory (s, i)) { + mapping->begin = cluster; +if (read_directory (s, i)) {error_setg (errp,"Could not read directory %s" , mapping->path); -return -1 ; - } - mapping =array_get (&(s->mapping), i); - }else { -assert (mapping->mode ==MODE_UNDEFINED ); - mapping->mode=MODE_NORMAL ; - mapping->begin = cluster; -if (mapping->end >0 ) { -direntry_t * direntry =array_get (&(s->directory), - mapping->dir_index); - - mapping->end = cluster +1 + (mapping->end-1 )/s->cluster_size; -set_begin_of_direntry (direntry, mapping->begin); - }else { - mapping->end = cluster +1 ; - fix_fat =0 ; - } - } - -assert (mapping->begin < mapping->end); - -/* next free cluster */ - cluster = mapping->end; - -if (cluster > s->cluster_count) { +return -1 ; + } + mapping =array_get (&(s->mapping), i); + }else { +assert (mapping->mode ==MODE_UNDEFINED ); + mapping->mode=MODE_NORMAL ; + mapping->begin = cluster; +if (mapping->end >0 ) { +direntry_t * direntry =array_get (&(s->directory), + mapping->dir_index); + + mapping->end = cluster +1 + (mapping->end-1 )/s->cluster_size; +set_begin_of_direntry (direntry, mapping->begin); + }else { + mapping->end = cluster +1 ; + fix_fat =0 ; + } + } + +assert (mapping->begin < mapping->end); + +/* next free cluster */ + cluster = mapping->end; + +if (cluster > s->cluster_count) {error_setg (errp,"Directory does not fit in FAT%d (capacity %.2f MB)" , s->fat_type, s->sector_count /2000.0 );return -1 ; - } + } -/* fix fat for entry */ -if (fix_fat) { -int j; -for (j = mapping->begin; j < mapping->end -1 ; j++) -fat_set (s, j, j+1 ); -fat_set (s, mapping->end -1 , s->max_fat_value); - } +/* fix fat for entry */ +if (fix_fat) { +int j; +for (j = mapping->begin; j < mapping->end -1 ; j++) +fat_set (s, j, j+1 ); +fat_set (s, mapping->end -1 , s->max_fat_value); + } } mapping =array_get (&(s->mapping),0 );
@@ -1135,7 +1135,7 @@ static int vvfat_open(BlockDriverState *bs, QDict *options, int flags,switch (s->fat_type) {case 32 : -fprintf (stderr,"Big fat greek warning: FAT32 has not been tested. " +fprintf (stderr,"Big fat greek warning: FAT32 has not been tested. " "You are welcome to do so!\n" );break ;case 16 :
@@ -1229,11 +1229,11 @@ static void vvfat_refresh_limits(BlockDriverState *bs, Error **errp)static inline void vvfat_close_current_file (BDRVVVFATState *s) {if (s->current_mapping) { - s->current_mapping =NULL ; -if (s->current_fd) { -qemu_close (s->current_fd); - s->current_fd =0 ; - } + s->current_mapping =NULL ; +if (s->current_fd) { +qemu_close (s->current_fd); + s->current_fd =0 ; + } } s->current_cluster =-1 ; }
@@ -1245,26 +1245,26 @@ static inline int find_mapping_for_cluster_aux(BDRVVVFATState* s,int cluster_num {while (1 ) {int index3; -mapping_t * mapping; - index3=(index1+index2)/2 ; - mapping=array_get (&(s->mapping),index3); -assert (mapping->begin < mapping->end); -if (mapping->begin>=cluster_num) { -assert (index2!=index3 || index2==0 ); -if (index2==index3) -return index1; - index2=index3; - }else { -if (index1==index3) -return mapping->end<=cluster_num ? index2 : index1; - index1=index3; - } -assert (index1<=index2); - DLOG(mapping=array_get(&(s->mapping),index1); -assert (mapping->begin<=cluster_num); -assert (index2 >= s->mapping.next || - ((mapping =array_get (&(s->mapping),index2)) && - mapping->end>cluster_num))); +mapping_t * mapping; + index3=(index1+index2)/2 ; + mapping=array_get (&(s->mapping),index3); +assert (mapping->begin < mapping->end); +if (mapping->begin>=cluster_num) { +assert (index2!=index3 || index2==0 ); +if (index2==index3) +return index1; + index2=index3; + }else { +if (index1==index3) +return mapping->end<=cluster_num ? index2 : index1; + index1=index3; + } +assert (index1<=index2); + DLOG(mapping=array_get(&(s->mapping),index1); +assert (mapping->begin<=cluster_num); +assert (index2 >= s->mapping.next || + ((mapping =array_get (&(s->mapping),index2)) && + mapping->end>cluster_num))); } }
@@ -1284,16 +1284,16 @@ static inline mapping_t* find_mapping_for_cluster(BDRVVVFATState* s,int cluster_static int open_file (BDRVVVFATState * s,mapping_t * mapping) {if (!mapping) -return -1 ; +return -1 ;if (!s->current_mapping || -strcmp (s->current_mapping->path,mapping->path)) { -/* open file */ -int fd =qemu_open (mapping->path,O_RDONLY |O_BINARY |O_LARGEFILE ); -if (fd<0 ) -return -1 ; -vvfat_close_current_file (s); - s->current_fd = fd; - s->current_mapping = mapping; +strcmp (s->current_mapping->path,mapping->path)) { +/* open file */ +int fd =qemu_open (mapping->path,O_RDONLY |O_BINARY |O_LARGEFILE ); +if (fd<0 ) +return -1 ; +vvfat_close_current_file (s); + s->current_fd = fd; + s->current_mapping = mapping; }return 0 ; }
@@ -1301,47 +1301,47 @@ static int open_file(BDRVVVFATState* s,mapping_t* mapping)static inline int read_cluster (BDRVVVFATState *s,int cluster_num) {if (s->current_cluster != cluster_num) { -int result=0 ; -off_t offset; -assert (!s->current_mapping || s->current_fd || (s->current_mapping->mode &MODE_DIRECTORY )); -if (!s->current_mapping - || s->current_mapping->begin>cluster_num - || s->current_mapping->end<=cluster_num) { -/* binary search of mappings for file */ -mapping_t * mapping=find_mapping_for_cluster (s,cluster_num); - -assert (!mapping || (cluster_num>=mapping->begin && cluster_num<mapping->end)); - -if (mapping && mapping->mode &MODE_DIRECTORY ) { -vvfat_close_current_file (s); - s->current_mapping = mapping; +int result=0 ; +off_t offset; +assert (!s->current_mapping || s->current_fd || (s->current_mapping->mode &MODE_DIRECTORY )); +if (!s->current_mapping + || s->current_mapping->begin>cluster_num + || s->current_mapping->end<=cluster_num) { +/* binary search of mappings for file */ +mapping_t * mapping=find_mapping_for_cluster (s,cluster_num); + +assert (!mapping || (cluster_num>=mapping->begin && cluster_num<mapping->end)); + +if (mapping && mapping->mode &MODE_DIRECTORY ) { +vvfat_close_current_file (s); + s->current_mapping = mapping; read_cluster_directory: - offset = s->cluster_size*(cluster_num-s->current_mapping->begin); - s->cluster = (unsigned char *)s->directory.pointer+offset - +0x20 *s->current_mapping->info.dir.first_dir_index; -assert (((s->cluster-(unsigned char *)s->directory.pointer)%s->cluster_size)==0 ); -assert ((char *)s->cluster+s->cluster_size <= s->directory.pointer+s->directory.next*s->directory.item_size); - s->current_cluster = cluster_num; -return 0 ; - } - -if (open_file (s,mapping)) -return -2 ; - }else if (s->current_mapping->mode &MODE_DIRECTORY ) - goto read_cluster_directory; - -assert (s->current_fd); - - offset=s->cluster_size*(cluster_num-s->current_mapping->begin)+s->current_mapping->info.file.offset; -if (lseek (s->current_fd, offset,SEEK_SET )!=offset) -return -3 ; - s->cluster=s->cluster_buffer; - result=read (s->current_fd,s->cluster,s->cluster_size); -if (result<0 ) { - s->current_cluster =-1 ; -return -1 ; - } - s->current_cluster = cluster_num; + offset = s->cluster_size*(cluster_num-s->current_mapping->begin); + s->cluster = (unsigned char *)s->directory.pointer+offset + +0x20 *s->current_mapping->info.dir.first_dir_index; +assert (((s->cluster-(unsigned char *)s->directory.pointer)%s->cluster_size)==0 ); +assert ((char *)s->cluster+s->cluster_size <= s->directory.pointer+s->directory.next*s->directory.item_size); + s->current_cluster = cluster_num; +return 0 ; + } + +if (open_file (s,mapping)) +return -2 ; + }else if (s->current_mapping->mode &MODE_DIRECTORY ) + goto read_cluster_directory; + +assert (s->current_fd); + + offset=s->cluster_size*(cluster_num-s->current_mapping->begin)+s->current_mapping->info.file.offset; +if (lseek (s->current_fd, offset,SEEK_SET )!=offset) +return -3 ; + s->cluster=s->cluster_buffer; + result=read (s->current_fd,s->cluster,s->cluster_size); +if (result<0 ) { + s->current_cluster =-1 ; +return -1 ; + } + s->current_cluster = cluster_num; }return 0 ; }
@@ -1354,28 +1354,28 @@ static void print_direntry(const direntry_t* direntry)fprintf (stderr,"direntry %p: " , direntry);if (!direntry) -return ; +return ;if (is_long_name (direntry)) { -unsigned char * c=(unsigned char *)direntry; -int i; - for(i=1;i<11 && c[i] && c[i]!=0xff;i+=2) +unsigned char * c=(unsigned char *)direntry; +int i; + for(i=1;i<11 && c[i] && c[i]!=0xff;i+=2)#define ADD_CHAR (c) {buffer[j] = (c); if (buffer[j] < ' ') buffer[j] = 0xb0; j++;} -ADD_CHAR (c[i]); -for (i=14 ;i<26 && c[i] && c[i]!=0xff ;i+=2 ) -ADD_CHAR (c[i]); -for (i=28 ;i<32 && c[i] && c[i]!=0xff ;i+=2 ) -ADD_CHAR (c[i]); - buffer[j] =0 ; -fprintf (stderr,"%s\n" , buffer); +ADD_CHAR (c[i]); +for (i=14 ;i<26 && c[i] && c[i]!=0xff ;i+=2 ) +ADD_CHAR (c[i]); +for (i=28 ;i<32 && c[i] && c[i]!=0xff ;i+=2 ) +ADD_CHAR (c[i]); + buffer[j] =0 ; +fprintf (stderr,"%s\n" , buffer); }else { -int i; -for (i=0 ;i<11 ;i++) -ADD_CHAR (direntry->name[i]); - buffer[j] =0 ; -fprintf (stderr,"%s attributes=0x%02x begin=%d size=%d\n" , - buffer, - direntry->attributes, -begin_of_direntry (direntry),le32_to_cpu (direntry->size)); +int i; +for (i=0 ;i<11 ;i++) +ADD_CHAR (direntry->name[i]); + buffer[j] =0 ; +fprintf (stderr,"%s attributes=0x%02x begin=%d size=%d\n" , + buffer, + direntry->attributes, +begin_of_direntry (direntry),le32_to_cpu (direntry->size)); } }
@@ -1387,9 +1387,9 @@ static void print_mapping(const mapping_t* mapping) mapping->first_mapping_index, mapping->path, mapping->mode);if (mapping->mode &MODE_DIRECTORY ) -fprintf (stderr,"parent_mapping_index = %d, first_dir_index = %d\n" , mapping->info.dir.parent_mapping_index, mapping->info.dir.first_dir_index); +fprintf (stderr,"parent_mapping_index = %d, first_dir_index = %d\n" , mapping->info.dir.parent_mapping_index, mapping->info.dir.first_dir_index);else - fprintf(stderr, "offset = %d\n", mapping->info.file.offset); + fprintf(stderr, "offset = %d\n", mapping->info.file.offset); }#endif
@@ -1400,10 +1400,10 @@ static int vvfat_read(BlockDriverState *bs, int64_t sector_num,int i;for (i=0 ;i<nb_sectors;i++,sector_num++) { -if (sector_num >= bs->total_sectors) -return -1 ; -if (s->qcow) { -int n; +if (sector_num >= bs->total_sectors) +return -1 ; +if (s->qcow) { +int n;int ret; ret =bdrv_is_allocated (s->qcow->bs, sector_num, nb_sectors - i, &n);
@@ -1421,25 +1421,25 @@ static int vvfat_read(BlockDriverState *bs, int64_t sector_num,continue ; }DLOG (fprintf (stderr,"sector %d not allocated\n" , (int )sector_num)); - } -if (sector_num<s->faked_sectors) { -if (sector_num<s->first_sectors_number) -memcpy (buf+i*0x200 ,&(s->first_sectors[sector_num*0x200 ]),0x200 ); -else if (sector_num-s->first_sectors_number<s->sectors_per_fat) -memcpy (buf+i*0x200 ,&(s->fat.pointer[(sector_num-s->first_sectors_number)*0x200 ]),0x200 ); -else if (sector_num-s->first_sectors_number-s->sectors_per_fat<s->sectors_per_fat) -memcpy (buf+i*0x200 ,&(s->fat.pointer[(sector_num-s->first_sectors_number-s->sectors_per_fat)*0x200 ]),0x200 ); - }else { -uint32_t sector=sector_num-s->faked_sectors, - sector_offset_in_cluster=(sector%s->sectors_per_cluster), - cluster_num=sector/s->sectors_per_cluster; -if (cluster_num > s->cluster_count ||read_cluster (s, cluster_num) !=0 ) { -/* LATER TODO: strict: return -1; */ -memset (buf+i*0x200 ,0 ,0x200 ); -continue ; - } -memcpy (buf+i*0x200 ,s->cluster+sector_offset_in_cluster*0x200 ,0x200 ); - } + } +if (sector_num<s->faked_sectors) { +if (sector_num<s->first_sectors_number) +memcpy (buf+i*0x200 ,&(s->first_sectors[sector_num*0x200 ]),0x200 ); +else if (sector_num-s->first_sectors_number<s->sectors_per_fat) +memcpy (buf+i*0x200 ,&(s->fat.pointer[(sector_num-s->first_sectors_number)*0x200 ]),0x200 ); +else if (sector_num-s->first_sectors_number-s->sectors_per_fat<s->sectors_per_fat) +memcpy (buf+i*0x200 ,&(s->fat.pointer[(sector_num-s->first_sectors_number-s->sectors_per_fat)*0x200 ]),0x200 ); + }else { +uint32_t sector=sector_num-s->faked_sectors, + sector_offset_in_cluster=(sector%s->sectors_per_cluster), + cluster_num=sector/s->sectors_per_cluster; +if (cluster_num > s->cluster_count ||read_cluster (s, cluster_num) !=0 ) { +/* LATER TODO: strict: return -1; */ +memset (buf+i*0x200 ,0 ,0x200 ); +continue ; + } +memcpy (buf+i*0x200 ,s->cluster+sector_offset_in_cluster*0x200 ,0x200 ); + } }return 0 ; }
@@ -1497,14 +1497,14 @@ vvfat_co_preadv(BlockDriverState *bs, uint64_t offset, uint64_t bytes,typedef struct commit_t {char * path;union { -struct {uint32_t cluster; } rename; -struct {int dir_index;uint32_t modified_offset; } writeout; -struct {uint32_t first_cluster; } new_file; -struct {uint32_t cluster; } mkdir; +struct {uint32_t cluster; } rename; +struct {int dir_index;uint32_t modified_offset; } writeout; +struct {uint32_t first_cluster; } new_file; +struct {uint32_t cluster; } mkdir; } param;/* DELETEs and RMDIRs are handled differently: see handle_deletes() */ enum { -ACTION_RENAME ,ACTION_WRITEOUT ,ACTION_NEW_FILE ,ACTION_MKDIR +ACTION_RENAME ,ACTION_WRITEOUT ,ACTION_NEW_FILE ,ACTION_MKDIR } action; }commit_t ;
@@ -1513,19 +1513,19 @@ static void clear_commits(BDRVVVFATState* s)int i;DLOG (fprintf (stderr,"clear_commits (%d commits)\n" , s->commits.next));for (i =0 ; i < s->commits.next; i++) { -commit_t * commit =array_get (&(s->commits), i); -assert (commit->path || commit->action ==ACTION_WRITEOUT ); -if (commit->action !=ACTION_WRITEOUT ) { -assert (commit->path); +commit_t * commit =array_get (&(s->commits), i); +assert (commit->path || commit->action ==ACTION_WRITEOUT ); +if (commit->action !=ACTION_WRITEOUT ) { +assert (commit->path);g_free (commit->path); - }else -assert (commit->path ==NULL ); + }else +assert (commit->path ==NULL ); } s->commits.next =0 ; }static void schedule_rename (BDRVVVFATState * s, -uint32_t cluster,char * new_path) +uint32_t cluster,char * new_path) {commit_t * commit =array_get_next (&(s->commits)); commit->path = new_path;
@@ -1534,7 +1534,7 @@ static void schedule_rename(BDRVVVFATState* s, }static void schedule_writeout (BDRVVVFATState * s, -int dir_index,uint32_t modified_offset) +int dir_index,uint32_t modified_offset) {commit_t * commit =array_get_next (&(s->commits)); commit->path =NULL ;
@@ -1544,7 +1544,7 @@ static void schedule_writeout(BDRVVVFATState* s, }static void schedule_new_file (BDRVVVFATState * s, -char * path,uint32_t first_cluster) +char * path,uint32_t first_cluster) {commit_t * commit =array_get_next (&(s->commits)); commit->path = path;
@@ -1579,72 +1579,72 @@ static void lfn_init(long_file_name* lfn)/* return 0 if parsed successfully, > 0 if no long name, < 0 if error */ static int parse_long_name (long_file_name * lfn, -const direntry_t * direntry) +const direntry_t * direntry) {int i, j, offset;const unsigned char * pointer = (const unsigned char *)direntry;if (!is_long_name (direntry)) -return 1 ; +return 1 ;if (pointer[0 ] &0x40 ) { - lfn->sequence_number = pointer[0 ] &0x3f ; - lfn->checksum = pointer[13 ]; - lfn->name[0 ] =0 ; - lfn->name[lfn->sequence_number *13 ] =0 ; + lfn->sequence_number = pointer[0 ] &0x3f ; + lfn->checksum = pointer[13 ]; + lfn->name[0 ] =0 ; + lfn->name[lfn->sequence_number *13 ] =0 ; }else if ((pointer[0 ] &0x3f ) != --lfn->sequence_number) -return -1 ; +return -1 ;else if (pointer[13 ] != lfn->checksum) -return -2 ; +return -2 ;else if (pointer[12 ] || pointer[26 ] || pointer[27 ]) -return -3 ; +return -3 ; offset =13 * (lfn->sequence_number -1 );for (i =0 , j =1 ; i <13 ; i++, j+=2 ) { -if (j ==11 ) - j =14 ; -else if (j ==26 ) - j =28 ; +if (j ==11 ) + j =14 ; +else if (j ==26 ) + j =28 ; -if (pointer[j+1 ] ==0 ) - lfn->name[offset + i] = pointer[j]; -else if (pointer[j+1 ] !=0xff || (pointer[0 ] &0x40 ) ==0 ) -return -4 ; -else - lfn->name[offset + i] =0 ; +if (pointer[j+1 ] ==0 ) + lfn->name[offset + i] = pointer[j]; +else if (pointer[j+1 ] !=0xff || (pointer[0 ] &0x40 ) ==0 ) +return -4 ; +else + lfn->name[offset + i] =0 ; }if (pointer[0 ] &0x40 ) - lfn->len = offset +strlen ((char *)lfn->name + offset); + lfn->len = offset +strlen ((char *)lfn->name + offset);return 0 ; }/* returns 0 if successful, >0 if no short_name, and <0 on error */ static int parse_short_name (BDRVVVFATState * s, -long_file_name * lfn,direntry_t * direntry) +long_file_name * lfn,direntry_t * direntry) {int i, j;if (!is_short_name (direntry)) -return 1 ; +return 1 ;for (j =7 ; j >=0 && direntry->name[j] ==' ' ; j--);for (i =0 ; i <= j; i++) { -if (direntry->name[i] <=' ' || direntry->name[i] >0x7f ) -return -1 ; -else if (s->downcase_short_names) - lfn->name[i] =qemu_tolower (direntry->name[i]); -else - lfn->name[i] = direntry->name[i]; +if (direntry->name[i] <=' ' || direntry->name[i] >0x7f ) +return -1 ; +else if (s->downcase_short_names) + lfn->name[i] =qemu_tolower (direntry->name[i]); +else + lfn->name[i] = direntry->name[i]; }for (j =2 ; j >=0 && direntry->name[8 + j] ==' ' ; j--) { }if (j >=0 ) { - lfn->name[i++] ='.' ; - lfn->name[i + j +1 ] ='\0' ; -for (;j >=0 ; j--) { + lfn->name[i++] ='.' ; + lfn->name[i + j +1 ] ='\0' ; +for (;j >=0 ; j--) {uint8_t c = direntry->name[8 + j];if (c <=' ' || c >0x7f ) {return -2 ;
@@ -1653,9 +1653,9 @@ static int parse_short_name(BDRVVVFATState* s, }else { lfn->name[i + j] = c; } - } + } }else - lfn->name[i + j +1 ] ='\0' ; + lfn->name[i + j +1 ] ='\0' ; lfn->len =strlen ((char *)lfn->name);
@@ -1663,13 +1663,13 @@ static int parse_short_name(BDRVVVFATState* s, }static inline uint32_t modified_fat_get (BDRVVVFATState * s, -unsigned int cluster) +unsigned int cluster) {if (cluster < s->last_cluster_of_root_directory) { -if (cluster +1 == s->last_cluster_of_root_directory) -return s->max_fat_value; -else -return cluster +1 ; +if (cluster +1 == s->last_cluster_of_root_directory) +return s->max_fat_value; +else +return cluster +1 ; }if (s->fat_type==32 ) {
@@ -1713,9 +1713,9 @@ static const char* get_basename(const char* path) {char * basename =strrchr (path,'/' );if (basename ==NULL ) -return path; +return path;else -return basename +1 ;/* strip '/' */ +return basename +1 ;/* strip '/' */ }/*
@@ -1740,7 +1740,7 @@ typedef enum {* assumed to be *not* deleted (and *only* those). */ static uint32_t get_cluster_count_for_direntry (BDRVVVFATState * s, -direntry_t * direntry,const char * path) +direntry_t * direntry,const char * path) {/* * This is a little bit tricky:
@@ -1773,85 +1773,85 @@ static uint32_t get_cluster_count_for_direntry(BDRVVVFATState* s,/* the root directory */ if (cluster_num ==0 ) -return 0 ; +return 0 ;/* write support */ if (s->qcow) { - basename2 =get_basename (path); + basename2 =get_basename (path); - mapping =find_mapping_for_cluster (s, cluster_num); + mapping =find_mapping_for_cluster (s, cluster_num); -if (mapping) { -const char * basename; +if (mapping) { +const char * basename; -assert (mapping->mode &MODE_DELETED ); - mapping->mode &= ~MODE_DELETED ; +assert (mapping->mode &MODE_DELETED ); + mapping->mode &= ~MODE_DELETED ; - basename =get_basename (mapping->path); + basename =get_basename (mapping->path); -assert (mapping->mode &MODE_NORMAL ); +assert (mapping->mode &MODE_NORMAL ); -/* rename */ -if (strcmp (basename, basename2)) -schedule_rename (s, cluster_num,g_strdup (path)); - }else if (is_file (direntry)) -/* new file */ -schedule_new_file (s,g_strdup (path), cluster_num); -else { +/* rename */ +if (strcmp (basename, basename2)) +schedule_rename (s, cluster_num,g_strdup (path)); + }else if (is_file (direntry)) +/* new file */ +schedule_new_file (s,g_strdup (path), cluster_num); +else {abort (); -return 0 ; - } +return 0 ; + } }while (1 ) { -if (s->qcow) { -if (!copy_it &&cluster_was_modified (s, cluster_num)) { -if (mapping ==NULL || - mapping->begin > cluster_num || - mapping->end <= cluster_num) - mapping =find_mapping_for_cluster (s, cluster_num); +if (s->qcow) { +if (!copy_it &&cluster_was_modified (s, cluster_num)) { +if (mapping ==NULL || + mapping->begin > cluster_num || + mapping->end <= cluster_num) + mapping =find_mapping_for_cluster (s, cluster_num); -if (mapping && - (mapping->mode &MODE_DIRECTORY ) ==0 ) { +if (mapping && + (mapping->mode &MODE_DIRECTORY ) ==0 ) { -/* was modified in qcow */ -if (offset != mapping->info.file.offset + s->cluster_size - * (cluster_num - mapping->begin)) { -/* offset of this cluster in file chain has changed */ +/* was modified in qcow */ +if (offset != mapping->info.file.offset + s->cluster_size + * (cluster_num - mapping->begin)) { +/* offset of this cluster in file chain has changed */ abort (); - copy_it =1 ; - }else if (offset ==0 ) { -const char * basename =get_basename (mapping->path); + copy_it =1 ; + }else if (offset ==0 ) { +const char * basename =get_basename (mapping->path); -if (strcmp (basename, basename2)) - copy_it =1 ; - first_mapping_index =array_index (&(s->mapping), mapping); - } +if (strcmp (basename, basename2)) + copy_it =1 ; + first_mapping_index =array_index (&(s->mapping), mapping); + } -if (mapping->first_mapping_index != first_mapping_index - && mapping->info.file.offset >0 ) { +if (mapping->first_mapping_index != first_mapping_index + && mapping->info.file.offset >0 ) {abort (); - copy_it =1 ; - } - -/* need to write out? */ -if (!was_modified &&is_file (direntry)) { - was_modified =1 ; -schedule_writeout (s, mapping->dir_index, offset); - } - } - } - -if (copy_it) { -int i, dummy; -/* -* This is horribly inefficient, but that is okay, since -* it is rarely executed, if at all. -*/ -int64_t offset =cluster2sector (s, cluster_num); - -vvfat_close_current_file (s); + copy_it =1 ; + } + +/* need to write out? */ +if (!was_modified &&is_file (direntry)) { + was_modified =1 ; +schedule_writeout (s, mapping->dir_index, offset); + } + } + } + +if (copy_it) { +int i, dummy; +/* +* This is horribly inefficient, but that is okay, since +* it is rarely executed, if at all. +*/ +int64_t offset =cluster2sector (s, cluster_num); + +vvfat_close_current_file (s);for (i =0 ; i < s->sectors_per_cluster; i++) {int res;
@@ -1870,22 +1870,22 @@ static uint32_t get_cluster_count_for_direntry(BDRVVVFATState* s, } } } - } - } + } + } - ret++; -if (s->used_clusters[cluster_num] &USED_ANY ) -return 0 ; - s->used_clusters[cluster_num] =USED_FILE ; + ret++; +if (s->used_clusters[cluster_num] &USED_ANY ) +return 0 ; + s->used_clusters[cluster_num] =USED_FILE ; - cluster_num =modified_fat_get (s, cluster_num); + cluster_num =modified_fat_get (s, cluster_num); -if (fat_eof (s, cluster_num)) -return ret; -else if (cluster_num <2 || cluster_num > s->max_fat_value -16 ) -return -1 ; +if (fat_eof (s, cluster_num)) +return ret; +else if (cluster_num <2 || cluster_num > s->max_fat_value -16 ) +return -1 ; - offset += s->cluster_size; + offset += s->cluster_size; } }
@@ -1895,7 +1895,7 @@ static uint32_t get_cluster_count_for_direntry(BDRVVVFATState* s,* used by the directory, its subdirectories and their files. */ static int check_directory_consistency (BDRVVVFATState *s, -int cluster_num,const char * path) +int cluster_num,const char * path) {int ret =0 ;unsigned char * cluster =g_malloc (s->cluster_size);
@@ -1912,104 +1912,104 @@ static int check_directory_consistency(BDRVVVFATState *s, path2[path_len +1 ] ='\0' ;if (mapping) { -const char * basename =get_basename (mapping->path); -const char * basename2 =get_basename (path); +const char * basename =get_basename (mapping->path); +const char * basename2 =get_basename (path); -assert (mapping->mode &MODE_DIRECTORY ); +assert (mapping->mode &MODE_DIRECTORY ); -assert (mapping->mode &MODE_DELETED ); - mapping->mode &= ~MODE_DELETED ; +assert (mapping->mode &MODE_DELETED ); + mapping->mode &= ~MODE_DELETED ; -if (strcmp (basename, basename2)) -schedule_rename (s, cluster_num,g_strdup (path)); +if (strcmp (basename, basename2)) +schedule_rename (s, cluster_num,g_strdup (path)); }else -/* new directory */ -schedule_mkdir (s, cluster_num,g_strdup (path)); +/* new directory */ +schedule_mkdir (s, cluster_num,g_strdup (path));lfn_init (&lfn);do { -int i; -int subret =0 ; +int i; +int subret =0 ; - ret++; + ret++; -if (s->used_clusters[cluster_num] &USED_ANY ) { -fprintf (stderr,"cluster %d used more than once\n" , (int )cluster_num); +if (s->used_clusters[cluster_num] &USED_ANY ) { +fprintf (stderr,"cluster %d used more than once\n" , (int )cluster_num); goto fail; - } - s->used_clusters[cluster_num] =USED_DIRECTORY ; + } + s->used_clusters[cluster_num] =USED_DIRECTORY ;DLOG (fprintf (stderr,"read cluster %d (sector %d)\n" , (int )cluster_num, (int )cluster2sector (s, cluster_num))); - subret =vvfat_read (s->bs,cluster2sector (s, cluster_num), cluster, - s->sectors_per_cluster); -if (subret) { -fprintf (stderr,"Error fetching direntries\n" ); - fail: + subret =vvfat_read (s->bs,cluster2sector (s, cluster_num), cluster, + s->sectors_per_cluster); +if (subret) { +fprintf (stderr,"Error fetching direntries\n" ); + fail:g_free (cluster); -return 0 ; - } +return 0 ; + } -for (i =0 ; i <0x10 * s->sectors_per_cluster; i++) { -int cluster_count =0 ; +for (i =0 ; i <0x10 * s->sectors_per_cluster; i++) { +int cluster_count =0 ; DLOG(fprintf(stderr, "check direntry %d:\n", i); print_direntry(direntries + i)); -if (is_volume_label (direntries + i) ||is_dot (direntries + i) || -is_free (direntries + i)) -continue ; - - subret =parse_long_name (&lfn, direntries + i); -if (subret <0 ) { -fprintf (stderr,"Error in long name\n" ); - goto fail; - } -if (subret ==0 ||is_free (direntries + i)) -continue ; - -if (fat_chksum (direntries+i) != lfn.checksum) { - subret =parse_short_name (s, &lfn, direntries + i); -if (subret <0 ) { -fprintf (stderr,"Error in short name (%d)\n" , subret); - goto fail; - } -if (subret >0 || !strcmp ((char *)lfn.name,"." ) - || !strcmp ((char *)lfn.name,".." )) -continue ; - } - lfn.checksum =0x100 ;/* cannot use long name twice */ - -if (path_len +1 + lfn.len >=PATH_MAX ) { -fprintf (stderr,"Name too long: %s/%s\n" , path, lfn.name); - goto fail; - } +if (is_volume_label (direntries + i) ||is_dot (direntries + i) || +is_free (direntries + i)) +continue ; + + subret =parse_long_name (&lfn, direntries + i); +if (subret <0 ) { +fprintf (stderr,"Error in long name\n" ); + goto fail; + } +if (subret ==0 ||is_free (direntries + i)) +continue ; + +if (fat_chksum (direntries+i) != lfn.checksum) { + subret =parse_short_name (s, &lfn, direntries + i); +if (subret <0 ) { +fprintf (stderr,"Error in short name (%d)\n" , subret); + goto fail; + } +if (subret >0 || !strcmp ((char *)lfn.name,"." ) + || !strcmp ((char *)lfn.name,".." )) +continue ; + } + lfn.checksum =0x100 ;/* cannot use long name twice */ + +if (path_len +1 + lfn.len >=PATH_MAX ) { +fprintf (stderr,"Name too long: %s/%s\n" , path, lfn.name); + goto fail; + }pstrcpy (path2 + path_len +1 ,sizeof (path2) - path_len -1 , (char *)lfn.name); -if (is_directory (direntries + i)) { -if (begin_of_direntry (direntries + i) ==0 ) { - DLOG(fprintf(stderr, "invalid begin for directory: %s\n", path2); print_direntry(direntries + i)); - goto fail; - } - cluster_count =check_directory_consistency (s, -begin_of_direntry (direntries + i), path2); -if (cluster_count ==0 ) { - DLOG(fprintf(stderr, "problem in directory %s:\n", path2); print_direntry(direntries + i)); - goto fail; - } - }else if (is_file (direntries + i)) { -/* check file size with FAT */ - cluster_count =get_cluster_count_for_direntry (s, direntries + i, path2); -if (cluster_count != +if (is_directory (direntries + i)) { +if (begin_of_direntry (direntries + i) ==0 ) { + DLOG(fprintf(stderr, "invalid begin for directory: %s\n", path2); print_direntry(direntries + i)); + goto fail; + } + cluster_count =check_directory_consistency (s, +begin_of_direntry (direntries + i), path2); +if (cluster_count ==0 ) { + DLOG(fprintf(stderr, "problem in directory %s:\n", path2); print_direntry(direntries + i)); + goto fail; + } + }else if (is_file (direntries + i)) { +/* check file size with FAT */ + cluster_count =get_cluster_count_for_direntry (s, direntries + i, path2); +if (cluster_count !=DIV_ROUND_UP (le32_to_cpu (direntries[i].size), s->cluster_size)) { -DLOG (fprintf (stderr,"Cluster count mismatch\n" )); - goto fail; - } - }else +DLOG (fprintf (stderr,"Cluster count mismatch\n" )); + goto fail; + } + }else abort ();/* cluster_count = 0; */ - ret += cluster_count; - } + ret += cluster_count; + } - cluster_num =modified_fat_get (s, cluster_num); + cluster_num =modified_fat_get (s, cluster_num); }while (!fat_eof (s, cluster_num));g_free (cluster);
@@ -2037,81 +2037,81 @@ DLOG(checkpoint());* - if all is fine, return number of used clusters */ if (s->fat2 ==NULL ) { -int size =0x200 * s->sectors_per_fat; - s->fat2 =g_malloc (size); -memcpy (s->fat2, s->fat.pointer, size); +int size =0x200 * s->sectors_per_fat; + s->fat2 =g_malloc (size); +memcpy (s->fat2, s->fat.pointer, size); } check =vvfat_read (s->bs, - s->first_sectors_number, s->fat2, s->sectors_per_fat); + s->first_sectors_number, s->fat2, s->sectors_per_fat);if (check) { -fprintf (stderr,"Could not copy fat\n" ); -return 0 ; +fprintf (stderr,"Could not copy fat\n" ); +return 0 ; }assert (s->used_clusters);for (i =0 ; i <sector2cluster (s, s->sector_count); i++) - s->used_clusters[i] &= ~USED_ANY ; + s->used_clusters[i] &= ~USED_ANY ;clear_commits (s);/* mark every mapped file/directory as deleted. * (check_directory_consistency() will unmark those still present). */ if (s->qcow) -for (i =0 ; i < s->mapping.next; i++) { -mapping_t * mapping =array_get (&(s->mapping), i); -if (mapping->first_mapping_index <0 ) - mapping->mode |=MODE_DELETED ; - } +for (i =0 ; i < s->mapping.next; i++) { +mapping_t * mapping =array_get (&(s->mapping), i); +if (mapping->first_mapping_index <0 ) + mapping->mode |=MODE_DELETED ; + } used_clusters_count =check_directory_consistency (s,0 , s->path);if (used_clusters_count <=0 ) { -DLOG (fprintf (stderr,"problem in directory\n" )); -return 0 ; +DLOG (fprintf (stderr,"problem in directory\n" )); +return 0 ; } check = s->last_cluster_of_root_directory;for (i = check; i <sector2cluster (s, s->sector_count); i++) { -if (modified_fat_get (s, i)) { -if (!s->used_clusters[i]) { -DLOG (fprintf (stderr,"FAT was modified (%d), but cluster is not used?\n" , i)); -return 0 ; - } - check++; - } +if (modified_fat_get (s, i)) { +if (!s->used_clusters[i]) { +DLOG (fprintf (stderr,"FAT was modified (%d), but cluster is not used?\n" , i)); +return 0 ; + } + check++; + } -if (s->used_clusters[i] ==USED_ALLOCATED ) { -/* allocated, but not used... */ -DLOG (fprintf (stderr,"unused, modified cluster: %d\n" , i)); -return 0 ; - } +if (s->used_clusters[i] ==USED_ALLOCATED ) { +/* allocated, but not used... */ +DLOG (fprintf (stderr,"unused, modified cluster: %d\n" , i)); +return 0 ; + } }if (check != used_clusters_count) -return 0 ; +return 0 ;return used_clusters_count; }static inline void adjust_mapping_indices (BDRVVVFATState * s, -int offset,int adjust) +int offset,int adjust) {int i;for (i =0 ; i < s->mapping.next; i++) { -mapping_t * mapping =array_get (&(s->mapping), i); +mapping_t * mapping =array_get (&(s->mapping), i);#define ADJUST_MAPPING_INDEX (name) \ - if (mapping->name >= offset) \ - mapping->name += adjust + if (mapping->name >= offset) \ + mapping->name += adjust -ADJUST_MAPPING_INDEX (first_mapping_index); -if (mapping->mode &MODE_DIRECTORY ) -ADJUST_MAPPING_INDEX (info.dir.parent_mapping_index); +ADJUST_MAPPING_INDEX (first_mapping_index); +if (mapping->mode &MODE_DIRECTORY ) +ADJUST_MAPPING_INDEX (info.dir.parent_mapping_index); } }/* insert or update mapping */ static mapping_t *insert_mapping (BDRVVVFATState * s, -uint32_t begin,uint32_t end) +uint32_t begin,uint32_t end) {/* * - find mapping where mapping->begin >= begin,
@@ -2125,15 +2125,15 @@ static mapping_t* insert_mapping(BDRVVVFATState* s,mapping_t * first_mapping =array_get (&(s->mapping),0 );if (index < s->mapping.next && (mapping =array_get (&(s->mapping), index)) - && mapping->begin < begin) { - mapping->end = begin; - index++; - mapping =array_get (&(s->mapping), index); + && mapping->begin < begin) { + mapping->end = begin; + index++; + mapping =array_get (&(s->mapping), index); }if (index >= s->mapping.next || mapping->begin > begin) { - mapping =array_insert (&(s->mapping), index,1 ); - mapping->path =NULL ; -adjust_mapping_indices (s, index,+1 ); + mapping =array_insert (&(s->mapping), index,1 ); + mapping->path =NULL ; +adjust_mapping_indices (s, index,+1 ); } mapping->begin = begin;
@@ -2145,8 +2145,8 @@ assert(index + 1 >= s->mapping.next || next_mapping->begin >= end)));if (s->current_mapping && first_mapping != (mapping_t *)s->mapping.pointer) - s->current_mapping =array_get (&(s->mapping), - s->current_mapping - first_mapping); + s->current_mapping =array_get (&(s->mapping), + s->current_mapping - first_mapping);return mapping; }
@@ -2168,8 +2168,8 @@ static int remove_mapping(BDRVVVFATState* s, int mapping_index)adjust_mapping_indices (s, mapping_index,-1 );if (s->current_mapping && first_mapping != (mapping_t *)s->mapping.pointer) - s->current_mapping =array_get (&(s->mapping), - s->current_mapping - first_mapping); + s->current_mapping =array_get (&(s->mapping), + s->current_mapping - first_mapping);return 0 ; }
@@ -2178,17 +2178,17 @@ static void adjust_dirindices(BDRVVVFATState* s, int offset, int adjust) {int i;for (i =0 ; i < s->mapping.next; i++) { -mapping_t * mapping =array_get (&(s->mapping), i); -if (mapping->dir_index >= offset) - mapping->dir_index += adjust; -if ((mapping->mode &MODE_DIRECTORY ) && - mapping->info.dir.first_dir_index >= offset) - mapping->info.dir.first_dir_index += adjust; +mapping_t * mapping =array_get (&(s->mapping), i); +if (mapping->dir_index >= offset) + mapping->dir_index += adjust; +if ((mapping->mode &MODE_DIRECTORY ) && + mapping->info.dir.first_dir_index >= offset) + mapping->info.dir.first_dir_index += adjust; } }static direntry_t *insert_direntries (BDRVVVFATState * s, -int dir_index,int count) +int dir_index,int count) {/* * make room in s->directory,
@@ -2196,7 +2196,7 @@ static direntry_t* insert_direntries(BDRVVVFATState* s,*/ direntry_t * result =array_insert (&(s->directory), dir_index, count);if (result ==NULL ) -return NULL ; +return NULL ;adjust_dirindices (s, dir_index, count);return result; }
@@ -2205,7 +2205,7 @@ static int remove_direntries(BDRVVVFATState* s, int dir_index, int count) {int ret =array_remove_slice (&(s->directory), dir_index, count);if (ret) -return ret; +return ret;adjust_dirindices (s, dir_index, -count);return 0 ; }
@@ -2217,7 +2217,7 @@ static int remove_direntries(BDRVVVFATState* s, int dir_index, int count)* adjusted) */ static int commit_mappings (BDRVVVFATState * s, -uint32_t first_cluster,int dir_index) +uint32_t first_cluster,int dir_index) {mapping_t * mapping =find_mapping_for_cluster (s, first_cluster);direntry_t * direntry =array_get (&(s->directory), dir_index);
@@ -2230,71 +2230,71 @@ static int commit_mappings(BDRVVVFATState* s, mapping->first_mapping_index =-1 ; mapping->dir_index = dir_index; mapping->mode = (dir_index <=0 ||is_directory (direntry)) ? -MODE_DIRECTORY :MODE_NORMAL ; +MODE_DIRECTORY :MODE_NORMAL ;while (!fat_eof (s, cluster)) { -uint32_t c, c1; - -for (c = cluster, c1 =modified_fat_get (s, c); c +1 == c1; - c = c1, c1 =modified_fat_get (s, c1)); - - c++; -if (c > mapping->end) { -int index =array_index (&(s->mapping), mapping); -int i, max_i = s->mapping.next - index; -for (i =1 ; i < max_i && mapping[i].begin < c; i++); -while (--i >0 ) -remove_mapping (s, index +1 ); - } -assert (mapping ==array_get (&(s->mapping), s->mapping.next -1 ) - || mapping[1 ].begin >= c); - mapping->end = c; - -if (!fat_eof (s, c1)) { -int i =find_mapping_for_cluster_aux (s, c1,0 , s->mapping.next); -mapping_t * next_mapping = i >= s->mapping.next ?NULL : -array_get (&(s->mapping), i); - -if (next_mapping ==NULL || next_mapping->begin > c1) { -int i1 =array_index (&(s->mapping), mapping); - - next_mapping =insert_mapping (s, c1, c1+1 ); - -if (c1 < c) - i1++; - mapping =array_get (&(s->mapping), i1); - } - - next_mapping->dir_index = mapping->dir_index; - next_mapping->first_mapping_index = - mapping->first_mapping_index <0 ? -array_index (&(s->mapping), mapping) : - mapping->first_mapping_index; - next_mapping->path = mapping->path; - next_mapping->mode = mapping->mode; - next_mapping->read_only = mapping->read_only; -if (mapping->mode &MODE_DIRECTORY ) { - next_mapping->info.dir.parent_mapping_index = - mapping->info.dir.parent_mapping_index; - next_mapping->info.dir.first_dir_index = - mapping->info.dir.first_dir_index + -0x10 * s->sectors_per_cluster * - (mapping->end - mapping->begin); - }else - next_mapping->info.file.offset = mapping->info.file.offset + - mapping->end - mapping->begin; - - mapping = next_mapping; - } - - cluster = c1; +uint32_t c, c1; + +for (c = cluster, c1 =modified_fat_get (s, c); c +1 == c1; + c = c1, c1 =modified_fat_get (s, c1)); + + c++; +if (c > mapping->end) { +int index =array_index (&(s->mapping), mapping); +int i, max_i = s->mapping.next - index; +for (i =1 ; i < max_i && mapping[i].begin < c; i++); +while (--i >0 ) +remove_mapping (s, index +1 ); + } +assert (mapping ==array_get (&(s->mapping), s->mapping.next -1 ) + || mapping[1 ].begin >= c); + mapping->end = c; + +if (!fat_eof (s, c1)) { +int i =find_mapping_for_cluster_aux (s, c1,0 , s->mapping.next); +mapping_t * next_mapping = i >= s->mapping.next ?NULL : +array_get (&(s->mapping), i); + +if (next_mapping ==NULL || next_mapping->begin > c1) { +int i1 =array_index (&(s->mapping), mapping); + + next_mapping =insert_mapping (s, c1, c1+1 ); + +if (c1 < c) + i1++; + mapping =array_get (&(s->mapping), i1); + } + + next_mapping->dir_index = mapping->dir_index; + next_mapping->first_mapping_index = + mapping->first_mapping_index <0 ? +array_index (&(s->mapping), mapping) : + mapping->first_mapping_index; + next_mapping->path = mapping->path; + next_mapping->mode = mapping->mode; + next_mapping->read_only = mapping->read_only; +if (mapping->mode &MODE_DIRECTORY ) { + next_mapping->info.dir.parent_mapping_index = + mapping->info.dir.parent_mapping_index; + next_mapping->info.dir.first_dir_index = + mapping->info.dir.first_dir_index + +0x10 * s->sectors_per_cluster * + (mapping->end - mapping->begin); + }else + next_mapping->info.file.offset = mapping->info.file.offset + + mapping->end - mapping->begin; + + mapping = next_mapping; + } + + cluster = c1; }return 0 ; }static int commit_direntries (BDRVVVFATState * s, -int dir_index,int parent_mapping_index) +int dir_index,int parent_mapping_index) {direntry_t * direntry =array_get (&(s->directory), dir_index);uint32_t first_cluster = dir_index ==0 ?0 :begin_of_direntry (direntry);
@@ -2319,58 +2319,58 @@ DLOG(fprintf(stderr, "commit_direntries for %s, parent_mapping_index %d\n", mapp mapping->info.dir.parent_mapping_index = parent_mapping_index;if (first_cluster ==0 ) { - old_cluster_count = new_cluster_count = - s->last_cluster_of_root_directory; + old_cluster_count = new_cluster_count = + s->last_cluster_of_root_directory; }else { -for (old_cluster_count =0 , c = first_cluster; !fat_eof (s, c); - c =fat_get (s, c)) - old_cluster_count++; +for (old_cluster_count =0 , c = first_cluster; !fat_eof (s, c); + c =fat_get (s, c)) + old_cluster_count++; -for (new_cluster_count =0 , c = first_cluster; !fat_eof (s, c); - c =modified_fat_get (s, c)) - new_cluster_count++; +for (new_cluster_count =0 , c = first_cluster; !fat_eof (s, c); + c =modified_fat_get (s, c)) + new_cluster_count++; }if (new_cluster_count > old_cluster_count) { -if (insert_direntries (s, - current_dir_index + factor * old_cluster_count, - factor * (new_cluster_count - old_cluster_count)) ==NULL ) -return -1 ; +if (insert_direntries (s, + current_dir_index + factor * old_cluster_count, + factor * (new_cluster_count - old_cluster_count)) ==NULL ) +return -1 ; }else if (new_cluster_count < old_cluster_count) -remove_direntries (s, - current_dir_index + factor * new_cluster_count, - factor * (old_cluster_count - new_cluster_count)); +remove_direntries (s, + current_dir_index + factor * new_cluster_count, + factor * (old_cluster_count - new_cluster_count));for (c = first_cluster; !fat_eof (s, c); c =modified_fat_get (s, c)) {direntry_t *first_direntry; -void * direntry =array_get (&(s->directory), current_dir_index); -int ret =vvfat_read (s->bs,cluster2sector (s, c), direntry, - s->sectors_per_cluster); -if (ret) -return ret; +void * direntry =array_get (&(s->directory), current_dir_index); +int ret =vvfat_read (s->bs,cluster2sector (s, c), direntry, + s->sectors_per_cluster); +if (ret) +return ret;/* The first directory entry on the filesystem is the volume name */ first_direntry = (direntry_t *) s->directory.pointer;assert (!memcmp (first_direntry->name, s->volume_label,11 )); - current_dir_index += factor; + current_dir_index += factor; } ret =commit_mappings (s, first_cluster, dir_index);if (ret) -return ret; +return ret;/* recurse */ for (i =0 ; i < factor * new_cluster_count; i++) { - direntry =array_get (&(s->directory), first_dir_index + i); -if (is_directory (direntry) && !is_dot (direntry)) { - mapping =find_mapping_for_cluster (s, first_cluster); -assert (mapping->mode &MODE_DIRECTORY ); - ret =commit_direntries (s, first_dir_index + i, -array_index (&(s->mapping), mapping)); -if (ret) -return ret; - } + direntry =array_get (&(s->directory), first_dir_index + i); +if (is_directory (direntry) && !is_dot (direntry)) { + mapping =find_mapping_for_cluster (s, first_cluster); +assert (mapping->mode &MODE_DIRECTORY ); + ret =commit_direntries (s, first_dir_index + i, +array_index (&(s->mapping), mapping)); +if (ret) +return ret; + } }return 0 ;
@@ -2379,7 +2379,7 @@ DLOG(fprintf(stderr, "commit_direntries for %s, parent_mapping_index %d\n", mapp/* commit one file (adjust contents, adjust mapping), return first_mapping_index */ static int commit_one_file (BDRVVVFATState * s, -int dir_index,uint32_t offset) +int dir_index,uint32_t offset) {direntry_t * direntry =array_get (&(s->directory), dir_index);uint32_t c =begin_of_direntry (direntry);
@@ -2394,14 +2394,14 @@ static int commit_one_file(BDRVVVFATState* s,assert ((offset % s->cluster_size) ==0 );for (i = s->cluster_size; i < offset; i += s->cluster_size) - c =modified_fat_get (s, c); + c =modified_fat_get (s, c); fd =qemu_open (mapping->path,O_RDWR |O_CREAT |O_BINARY ,0666 );if (fd <0 ) { -fprintf (stderr,"Could not open %s... (%s, %d)\n" , mapping->path, -strerror (errno), errno); +fprintf (stderr,"Could not open %s... (%s, %d)\n" , mapping->path, +strerror (errno), errno);g_free (cluster); -return fd; +return fd; }if (offset >0 ) {if (lseek (fd, offset,SEEK_SET ) != offset) {
@@ -2412,18 +2412,18 @@ static int commit_one_file(BDRVVVFATState* s, }while (offset < size) { -uint32_t c1; -int rest_size = (size - offset > s->cluster_size ? - s->cluster_size : size - offset); -int ret; +uint32_t c1; +int rest_size = (size - offset > s->cluster_size ? + s->cluster_size : size - offset); +int ret; - c1 =modified_fat_get (s, c); + c1 =modified_fat_get (s, c); -assert ((size - offset ==0 &&fat_eof (s, c)) || - (size > offset && c >=2 && !fat_eof (s, c))); +assert ((size - offset ==0 &&fat_eof (s, c)) || + (size > offset && c >=2 && !fat_eof (s, c))); - ret =vvfat_read (s->bs,cluster2sector (s, c), - (uint8_t *)cluster, (rest_size +0x1ff ) /0x200 ); + ret =vvfat_read (s->bs,cluster2sector (s, c), + (uint8_t *)cluster, (rest_size +0x1ff ) /0x200 );if (ret <0 ) {qemu_close (fd);
@@ -2437,8 +2437,8 @@ static int commit_one_file(BDRVVVFATState* s,return -2 ; } - offset += rest_size; - c = c1; + offset += rest_size; + c = c1; }if (ftruncate (fd, size)) {
@@ -2459,18 +2459,18 @@ static void check1(BDRVVVFATState* s) {int i;for (i =0 ; i < s->mapping.next; i++) { -mapping_t * mapping =array_get (&(s->mapping), i); -if (mapping->mode &MODE_DELETED ) { -fprintf (stderr,"deleted\n" ); -continue ; - } -assert (mapping->dir_index < s->directory.next); -direntry_t * direntry =array_get (&(s->directory), mapping->dir_index); -assert (mapping->begin ==begin_of_direntry (direntry) || mapping->first_mapping_index >=0 ); -if (mapping->mode &MODE_DIRECTORY ) { -assert (mapping->info.dir.first_dir_index +0x10 * s->sectors_per_cluster * (mapping->end - mapping->begin) <= s->directory.next); -assert ((mapping->info.dir.first_dir_index % (0x10 * s->sectors_per_cluster)) ==0 ); - } +mapping_t * mapping =array_get (&(s->mapping), i); +if (mapping->mode &MODE_DELETED ) { +fprintf (stderr,"deleted\n" ); +continue ; + } +assert (mapping->dir_index < s->directory.next); +direntry_t * direntry =array_get (&(s->directory), mapping->dir_index); +assert (mapping->begin ==begin_of_direntry (direntry) || mapping->first_mapping_index >=0 ); +if (mapping->mode &MODE_DIRECTORY ) { +assert (mapping->info.dir.first_dir_index +0x10 * s->sectors_per_cluster * (mapping->end - mapping->begin) <= s->directory.next); +assert ((mapping->info.dir.first_dir_index % (0x10 * s->sectors_per_cluster)) ==0 ); + } } }
@@ -2481,43 +2481,43 @@ static void check2(BDRVVVFATState* s)int first_mapping =-1 ;for (i =0 ; i < s->directory.next; i++) { -direntry_t * direntry =array_get (&(s->directory), i); - -if (is_short_name (direntry) &&begin_of_direntry (direntry)) { -mapping_t * mapping =find_mapping_for_cluster (s,begin_of_direntry (direntry)); -assert (mapping); -assert (mapping->dir_index == i ||is_dot (direntry)); -assert (mapping->begin ==begin_of_direntry (direntry) ||is_dot (direntry)); - } - -if ((i % (0x10 * s->sectors_per_cluster)) ==0 ) { -/* cluster start */ -int j, count =0 ; - -for (j =0 ; j < s->mapping.next; j++) { -mapping_t * mapping =array_get (&(s->mapping), j); -if (mapping->mode &MODE_DELETED ) -continue ; -if (mapping->mode &MODE_DIRECTORY ) { -if (mapping->info.dir.first_dir_index <= i && mapping->info.dir.first_dir_index +0x10 * s->sectors_per_cluster > i) { -assert (++count ==1 ); -if (mapping->first_mapping_index ==-1 ) - first_mapping =array_index (&(s->mapping), mapping); -else -assert (first_mapping == mapping->first_mapping_index); -if (mapping->info.dir.parent_mapping_index <0 ) -assert (j ==0 ); -else { -mapping_t * parent =array_get (&(s->mapping), mapping->info.dir.parent_mapping_index); -assert (parent->mode &MODE_DIRECTORY ); -assert (parent->info.dir.first_dir_index < mapping->info.dir.first_dir_index); - } - } - } - } -if (count ==0 ) - first_mapping =-1 ; - } +direntry_t * direntry =array_get (&(s->directory), i); + +if (is_short_name (direntry) &&begin_of_direntry (direntry)) { +mapping_t * mapping =find_mapping_for_cluster (s,begin_of_direntry (direntry)); +assert (mapping); +assert (mapping->dir_index == i ||is_dot (direntry)); +assert (mapping->begin ==begin_of_direntry (direntry) ||is_dot (direntry)); + } + +if ((i % (0x10 * s->sectors_per_cluster)) ==0 ) { +/* cluster start */ +int j, count =0 ; + +for (j =0 ; j < s->mapping.next; j++) { +mapping_t * mapping =array_get (&(s->mapping), j); +if (mapping->mode &MODE_DELETED ) +continue ; +if (mapping->mode &MODE_DIRECTORY ) { +if (mapping->info.dir.first_dir_index <= i && mapping->info.dir.first_dir_index +0x10 * s->sectors_per_cluster > i) { +assert (++count ==1 ); +if (mapping->first_mapping_index ==-1 ) + first_mapping =array_index (&(s->mapping), mapping); +else +assert (first_mapping == mapping->first_mapping_index); +if (mapping->info.dir.parent_mapping_index <0 ) +assert (j ==0 ); +else { +mapping_t * parent =array_get (&(s->mapping), mapping->info.dir.parent_mapping_index); +assert (parent->mode &MODE_DIRECTORY ); +assert (parent->info.dir.first_dir_index < mapping->info.dir.first_dir_index); + } + } + } + } +if (count ==0 ) + first_mapping =-1 ; + } } }#endif
@@ -2529,63 +2529,63 @@ static int handle_renames_and_mkdirs(BDRVVVFATState* s)#ifdef DEBUG fprintf (stderr,"handle_renames\n" );for (i =0 ; i < s->commits.next; i++) { -commit_t * commit =array_get (&(s->commits), i); -fprintf (stderr,"%d, %s (%d, %d)\n" , i, commit->path ? commit->path :"(null)" , commit->param.rename.cluster, commit->action); +commit_t * commit =array_get (&(s->commits), i); +fprintf (stderr,"%d, %s (%d, %d)\n" , i, commit->path ? commit->path :"(null)" , commit->param.rename.cluster, commit->action); }#endif for (i =0 ; i < s->commits.next;) { -commit_t * commit =array_get (&(s->commits), i); -if (commit->action ==ACTION_RENAME ) { -mapping_t * mapping =find_mapping_for_cluster (s, - commit->param.rename.cluster); -char * old_path = mapping->path; - -assert (commit->path); - mapping->path = commit->path; -if (rename (old_path, mapping->path)) -return -2 ; - -if (mapping->mode &MODE_DIRECTORY ) { -int l1 =strlen (mapping->path); -int l2 =strlen (old_path); -int diff = l1 - l2; -direntry_t * direntry =array_get (&(s->directory), - mapping->info.dir.first_dir_index); -uint32_t c = mapping->begin; -int i =0 ; - -/* recurse */ -while (!fat_eof (s, c)) { -do { -direntry_t * d = direntry + i; - -if (is_file (d) || (is_directory (d) && !is_dot (d))) { -mapping_t * m =find_mapping_for_cluster (s, -begin_of_direntry (d)); -int l =strlen (m->path); -char * new_path =g_malloc (l + diff +1 ); - -assert (!strncmp (m->path, mapping->path, l2)); +commit_t * commit =array_get (&(s->commits), i); +if (commit->action ==ACTION_RENAME ) { +mapping_t * mapping =find_mapping_for_cluster (s, + commit->param.rename.cluster); +char * old_path = mapping->path; + +assert (commit->path); + mapping->path = commit->path; +if (rename (old_path, mapping->path)) +return -2 ; + +if (mapping->mode &MODE_DIRECTORY ) { +int l1 =strlen (mapping->path); +int l2 =strlen (old_path); +int diff = l1 - l2; +direntry_t * direntry =array_get (&(s->directory), + mapping->info.dir.first_dir_index); +uint32_t c = mapping->begin; +int i =0 ; + +/* recurse */ +while (!fat_eof (s, c)) { +do { +direntry_t * d = direntry + i; + +if (is_file (d) || (is_directory (d) && !is_dot (d))) { +mapping_t * m =find_mapping_for_cluster (s, +begin_of_direntry (d)); +int l =strlen (m->path); +char * new_path =g_malloc (l + diff +1 ); + +assert (!strncmp (m->path, mapping->path, l2));pstrcpy (new_path, l + diff +1 , mapping->path);pstrcpy (new_path + l1, l + diff +1 - l1, m->path + l2); -schedule_rename (s, m->begin, new_path); - } - i++; - }while ((i % (0x10 * s->sectors_per_cluster)) !=0 ); - c =fat_get (s, c); - } - } +schedule_rename (s, m->begin, new_path); + } + i++; + }while ((i % (0x10 * s->sectors_per_cluster)) !=0 ); + c =fat_get (s, c); + } + }g_free (old_path); -array_remove (&(s->commits), i); -continue ; - }else if (commit->action ==ACTION_MKDIR ) { -mapping_t * mapping; -int j, parent_path_len; +array_remove (&(s->commits), i); +continue ; + }else if (commit->action ==ACTION_MKDIR ) { +mapping_t * mapping; +int j, parent_path_len;#ifdef __MINGW32__if (mkdir (commit->path))
@@ -2595,37 +2595,37 @@ static int handle_renames_and_mkdirs(BDRVVVFATState* s)return -5 ;#endif - mapping =insert_mapping (s, commit->param.mkdir.cluster, - commit->param.mkdir.cluster +1 ); -if (mapping ==NULL ) -return -6 ; - - mapping->mode =MODE_DIRECTORY ; - mapping->read_only =0 ; - mapping->path = commit->path; - j = s->directory.next; -assert (j); -insert_direntries (s, s->directory.next, -0x10 * s->sectors_per_cluster); - mapping->info.dir.first_dir_index = j; - - parent_path_len =strlen (commit->path) - -strlen (get_basename (commit->path)) -1 ; -for (j =0 ; j < s->mapping.next; j++) { -mapping_t * m =array_get (&(s->mapping), j); -if (m->first_mapping_index <0 && m != mapping && - !strncmp (m->path, mapping->path, parent_path_len) && -strlen (m->path) == parent_path_len) -break ; - } -assert (j < s->mapping.next); - mapping->info.dir.parent_mapping_index = j; - -array_remove (&(s->commits), i); -continue ; - } - - i++; + mapping =insert_mapping (s, commit->param.mkdir.cluster, + commit->param.mkdir.cluster +1 ); +if (mapping ==NULL ) +return -6 ; + + mapping->mode =MODE_DIRECTORY ; + mapping->read_only =0 ; + mapping->path = commit->path; + j = s->directory.next; +assert (j); +insert_direntries (s, s->directory.next, +0x10 * s->sectors_per_cluster); + mapping->info.dir.first_dir_index = j; + + parent_path_len =strlen (commit->path) + -strlen (get_basename (commit->path)) -1 ; +for (j =0 ; j < s->mapping.next; j++) { +mapping_t * m =array_get (&(s->mapping), j); +if (m->first_mapping_index <0 && m != mapping && + !strncmp (m->path, mapping->path, parent_path_len) && +strlen (m->path) == parent_path_len) +break ; + } +assert (j < s->mapping.next); + mapping->info.dir.parent_mapping_index = j; + +array_remove (&(s->commits), i); +continue ; + } + + i++; }return 0 ; }
@@ -2640,75 +2640,75 @@ static int handle_commits(BDRVVVFATState* s)vvfat_close_current_file (s);for (i =0 ; !fail && i < s->commits.next; i++) { -commit_t * commit =array_get (&(s->commits), i); -switch (commit->action) { -case ACTION_RENAME :case ACTION_MKDIR : +commit_t * commit =array_get (&(s->commits), i); +switch (commit->action) { +case ACTION_RENAME :case ACTION_MKDIR :abort (); - fail =-2 ; -break ; -case ACTION_WRITEOUT : { + fail =-2 ; +break ; +case ACTION_WRITEOUT : {#ifndef NDEBUG /* these variables are only used by assert() below */ -direntry_t * entry =array_get (&(s->directory), - commit->param.writeout.dir_index); -uint32_t begin =begin_of_direntry (entry); -mapping_t * mapping =find_mapping_for_cluster (s, begin); +direntry_t * entry =array_get (&(s->directory), + commit->param.writeout.dir_index); +uint32_t begin =begin_of_direntry (entry); +mapping_t * mapping =find_mapping_for_cluster (s, begin);#endif -assert (mapping); -assert (mapping->begin == begin); -assert (commit->path ==NULL ); - -if (commit_one_file (s, commit->param.writeout.dir_index, - commit->param.writeout.modified_offset)) - fail =-3 ; - -break ; - } -case ACTION_NEW_FILE : { -int begin = commit->param.new_file.first_cluster; -mapping_t * mapping =find_mapping_for_cluster (s, begin); -direntry_t * entry; -int i; - -/* find direntry */ -for (i =0 ; i < s->directory.next; i++) { - entry =array_get (&(s->directory), i); -if (is_file (entry) &&begin_of_direntry (entry) == begin) -break ; - } - -if (i >= s->directory.next) { - fail =-6 ; -continue ; - } - -/* make sure there exists an initial mapping */ -if (mapping && mapping->begin != begin) { - mapping->end = begin; - mapping =NULL ; - } -if (mapping ==NULL ) { - mapping =insert_mapping (s, begin, begin+1 ); - } -/* most members will be fixed in commit_mappings() */ -assert (commit->path); - mapping->path = commit->path; - mapping->read_only =0 ; - mapping->mode =MODE_NORMAL ; - mapping->info.file.offset =0 ; - -if (commit_one_file (s, i,0 )) - fail =-7 ; - -break ; - } -default : +assert (mapping); +assert (mapping->begin == begin); +assert (commit->path ==NULL ); + +if (commit_one_file (s, commit->param.writeout.dir_index, + commit->param.writeout.modified_offset)) + fail =-3 ; + +break ; + } +case ACTION_NEW_FILE : { +int begin = commit->param.new_file.first_cluster; +mapping_t * mapping =find_mapping_for_cluster (s, begin); +direntry_t * entry; +int i; + +/* find direntry */ +for (i =0 ; i < s->directory.next; i++) { + entry =array_get (&(s->directory), i); +if (is_file (entry) &&begin_of_direntry (entry) == begin) +break ; + } + +if (i >= s->directory.next) { + fail =-6 ; +continue ; + } + +/* make sure there exists an initial mapping */ +if (mapping && mapping->begin != begin) { + mapping->end = begin; + mapping =NULL ; + } +if (mapping ==NULL ) { + mapping =insert_mapping (s, begin, begin+1 ); + } +/* most members will be fixed in commit_mappings() */ +assert (commit->path); + mapping->path = commit->path; + mapping->read_only =0 ; + mapping->mode =MODE_NORMAL ; + mapping->info.file.offset =0 ; + +if (commit_one_file (s, i,0 )) + fail =-7 ; + +break ; + } +default :abort (); - } + } }if (i >0 &&array_remove_slice (&(s->commits),0 , i)) -return -1 ; +return -1 ;return fail; }
@@ -2719,53 +2719,53 @@ static int handle_deletes(BDRVVVFATState* s)/* delete files corresponding to mappings marked as deleted */ /* handle DELETEs and unused mappings (modified_fat_get(s, mapping->begin) == 0) */ while (deferred && deleted) { - deferred =0 ; - deleted =0 ; - -for (i =1 ; i < s->mapping.next; i++) { -mapping_t * mapping =array_get (&(s->mapping), i); -if (mapping->mode &MODE_DELETED ) { -direntry_t * entry =array_get (&(s->directory), - mapping->dir_index); - -if (is_free (entry)) { -/* remove file/directory */ -if (mapping->mode &MODE_DIRECTORY ) { -int j, next_dir_index = s->directory.next, - first_dir_index = mapping->info.dir.first_dir_index; - -if (rmdir (mapping->path) <0 ) { -if (errno ==ENOTEMPTY ) { - deferred++; -continue ; - }else -return -5 ; - } - -for (j =1 ; j < s->mapping.next; j++) { -mapping_t * m =array_get (&(s->mapping), j); -if (m->mode &MODE_DIRECTORY && - m->info.dir.first_dir_index > - first_dir_index && - m->info.dir.first_dir_index < - next_dir_index) - next_dir_index = - m->info.dir.first_dir_index; - } -remove_direntries (s, first_dir_index, - next_dir_index - first_dir_index); - - deleted++; - } - }else { -if (unlink (mapping->path)) -return -4 ; - deleted++; - } - DLOG(fprintf(stderr, "DELETE (%d)\n", i); print_mapping(mapping); print_direntry(entry)); -remove_mapping (s, i); - } - } + deferred =0 ; + deleted =0 ; + +for (i =1 ; i < s->mapping.next; i++) { +mapping_t * mapping =array_get (&(s->mapping), i); +if (mapping->mode &MODE_DELETED ) { +direntry_t * entry =array_get (&(s->directory), + mapping->dir_index); + +if (is_free (entry)) { +/* remove file/directory */ +if (mapping->mode &MODE_DIRECTORY ) { +int j, next_dir_index = s->directory.next, + first_dir_index = mapping->info.dir.first_dir_index; + +if (rmdir (mapping->path) <0 ) { +if (errno ==ENOTEMPTY ) { + deferred++; +continue ; + }else +return -5 ; + } + +for (j =1 ; j < s->mapping.next; j++) { +mapping_t * m =array_get (&(s->mapping), j); +if (m->mode &MODE_DIRECTORY && + m->info.dir.first_dir_index > + first_dir_index && + m->info.dir.first_dir_index < + next_dir_index) + next_dir_index = + m->info.dir.first_dir_index; + } +remove_direntries (s, first_dir_index, + next_dir_index - first_dir_index); + + deleted++; + } + }else { +if (unlink (mapping->path)) +return -4 ; + deleted++; + } + DLOG(fprintf(stderr, "DELETE (%d)\n", i); print_mapping(mapping); print_direntry(entry)); +remove_mapping (s, i); + } + } }return 0 ;
@@ -2785,15 +2785,15 @@ static int do_commit(BDRVVVFATState* s)/* the real meat are the commits. Nothing to do? Move along! */ if (s->commits.next ==0 ) -return 0 ; +return 0 ;vvfat_close_current_file (s); ret =handle_renames_and_mkdirs (s);if (ret) { -fprintf (stderr,"Error handling renames (%d)\n" , ret); +fprintf (stderr,"Error handling renames (%d)\n" , ret);abort (); -return ret; +return ret; }/* copy FAT (with bdrv_read) */
@@ -2802,23 +2802,23 @@ static int do_commit(BDRVVVFATState* s)/* recurse direntries from root (using bs->bdrv_read) */ ret =commit_direntries (s,0 ,-1 );if (ret) { -fprintf (stderr,"Fatal: error while committing (%d)\n" , ret); +fprintf (stderr,"Fatal: error while committing (%d)\n" , ret);abort (); -return ret; +return ret; } ret =handle_commits (s);if (ret) { -fprintf (stderr,"Error handling commits (%d)\n" , ret); +fprintf (stderr,"Error handling commits (%d)\n" , ret);abort (); -return ret; +return ret; } ret =handle_deletes (s);if (ret) { -fprintf (stderr,"Error deleting\n" ); +fprintf (stderr,"Error deleting\n" );abort (); -return ret; +return ret; }if (s->qcow->bs->drv->bdrv_make_empty) {
@@ -2836,7 +2836,7 @@ static int try_commit(BDRVVVFATState* s)vvfat_close_current_file (s);DLOG (checkpoint ());if (!is_consistent (s)) -return -1 ; +return -1 ;return do_commit (s); }
@@ -2862,56 +2862,56 @@ DLOG(checkpoint());*/ if (sector_num < s->first_sectors_number) -return -1 ; +return -1 ;for (i =sector2cluster (s, sector_num); - i <=sector2cluster (s, sector_num + nb_sectors -1 );) { -mapping_t * mapping =find_mapping_for_cluster (s, i); -if (mapping) { -if (mapping->read_only) { -fprintf (stderr,"Tried to write to write-protected file %s\n" , - mapping->path); -return -1 ; - } - -if (mapping->mode &MODE_DIRECTORY ) { -int begin =cluster2sector (s, i); -int end = begin + s->sectors_per_cluster, k; -int dir_index; -const direntry_t * direntries; -long_file_name lfn; - -lfn_init (&lfn); - -if (begin < sector_num) - begin = sector_num; -if (end > sector_num + nb_sectors) - end = sector_num + nb_sectors; - dir_index = mapping->dir_index + -0x10 * (begin - mapping->begin * s->sectors_per_cluster); - direntries = (direntry_t *)(buf +0x200 * (begin - sector_num)); - -for (k =0 ; k < (end - begin) *0x10 ; k++) { -/* do not allow non-ASCII filenames */ -if (parse_long_name (&lfn, direntries + k) <0 ) { -fprintf (stderr,"Warning: non-ASCII filename\n" ); -return -1 ; - } -/* no access to the direntry of a read-only file */ -else if (is_short_name (direntries+k) && - (direntries[k].attributes &1 )) { -if (memcmp (direntries + k, -array_get (&(s->directory), dir_index + k), -sizeof (direntry_t))) { -fprintf (stderr,"Warning: tried to write to write-protected file\n" ); -return -1 ; - } - } - } - } - i = mapping->end; - }else - i++; + i <=sector2cluster (s, sector_num + nb_sectors -1 );) { +mapping_t * mapping =find_mapping_for_cluster (s, i); +if (mapping) { +if (mapping->read_only) { +fprintf (stderr,"Tried to write to write-protected file %s\n" , + mapping->path); +return -1 ; + } + +if (mapping->mode &MODE_DIRECTORY ) { +int begin =cluster2sector (s, i); +int end = begin + s->sectors_per_cluster, k; +int dir_index; +const direntry_t * direntries; +long_file_name lfn; + +lfn_init (&lfn); + +if (begin < sector_num) + begin = sector_num; +if (end > sector_num + nb_sectors) + end = sector_num + nb_sectors; + dir_index = mapping->dir_index + +0x10 * (begin - mapping->begin * s->sectors_per_cluster); + direntries = (direntry_t *)(buf +0x200 * (begin - sector_num)); + +for (k =0 ; k < (end - begin) *0x10 ; k++) { +/* do not allow non-ASCII filenames */ +if (parse_long_name (&lfn, direntries + k) <0 ) { +fprintf (stderr,"Warning: non-ASCII filename\n" ); +return -1 ; + } +/* no access to the direntry of a read-only file */ +else if (is_short_name (direntries+k) && + (direntries[k].attributes &1 )) { +if (memcmp (direntries + k, +array_get (&(s->directory), dir_index + k), +sizeof (direntry_t))) { +fprintf (stderr,"Warning: tried to write to write-protected file\n" ); +return -1 ; + } + } + } + } + i = mapping->end; + }else + i++; }/*
@@ -2920,14 +2920,14 @@ DLOG(checkpoint());DLOG (fprintf (stderr,"Write to qcow backend: %d + %d\n" , (int )sector_num, nb_sectors)); ret =bdrv_write (s->qcow, sector_num, buf, nb_sectors);if (ret <0 ) { -fprintf (stderr,"Error writing to qcow backend\n" ); -return ret; +fprintf (stderr,"Error writing to qcow backend\n" ); +return ret; }for (i =sector2cluster (s, sector_num); - i <=sector2cluster (s, sector_num + nb_sectors -1 ); i++) -if (i >=0 ) - s->used_clusters[i] |=USED_ALLOCATED ; + i <=sector2cluster (s, sector_num + nb_sectors -1 ); i++) +if (i >=0 ) + s->used_clusters[i] |=USED_ALLOCATED ;DLOG (checkpoint ());/* TODO: add timeout */
@@ -2966,7 +2966,7 @@ vvfat_co_pwritev(BlockDriverState *bs, uint64_t offset, uint64_t bytes, } static int64_t coroutine_fn vvfat_co_get_block_status(BlockDriverState *bs, -int64_t sector_num,int nb_sectors,int *n,BlockDriverState **file) +int64_t sector_num,int nb_sectors,int *n,BlockDriverState **file) { *n = bs->total_sectors - sector_num;if (*n > nb_sectors) {
@@ -3145,13 +3145,13 @@ static void checkpoint(void) {assert (!vvv->current_mapping || vvv->current_fd || (vvv->current_mapping->mode &MODE_DIRECTORY ));#if 0 if (((direntry_t *)vvv->directory.pointer)[1 ].attributes !=0xf ) -fprintf (stderr,"Nonono!\n" ); +fprintf (stderr,"Nonono!\n" );mapping_t * mapping;direntry_t * direntry;assert (vvv->mapping.size >= vvv->mapping.item_size * vvv->mapping.next);assert (vvv->directory.size >= vvv->directory.item_size * vvv->directory.next);if (vvv->mapping.next<47 ) -return ; +return ;assert ((mapping =array_get (&(vvv->mapping),47 )));assert (mapping->dir_index < vvv->directory.next); direntry =array_get (&(vvv->directory), mapping->dir_index);
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 031/100] mirror: Switch mirror_do_read() to byte-based
In reply to Kevin WolfFrom: Eric Blake <[email protected]>
We are gradually converting to byte-based interfaces, as they are easier to reason about than sector-based. Convert another internal function, preserving all existing semantics, and adding one more assertion that things are still sector-aligned (so that conversions to sectors in mirror_read_complete don't need to round).
--- block/mirror.c | 74 ++++++++++++++++++++++++++-------------------------------- 1 file changed, 33 insertions(+), 41 deletions(-)
block/mirror.c +33 -41
@@ -196,7 +196,7 @@ static inline int mirror_clip_sectors(MirrorBlockJob *s,/* Round offset and/or bytes to target cluster if COW is needed, and * return the offset of the adjusted tail against original. */ static int mirror_cow_align (MirrorBlockJob *s,int64_t *offset, -unsigned int *bytes) +uint64_t *bytes) {bool need_cow;int ret =0 ;
@@ -204,6 +204,7 @@ static int mirror_cow_align(MirrorBlockJob *s, int64_t *offset,unsigned int align_bytes = *bytes;int max_bytes = s->granularity * s->max_iov; +assert (*bytes <INT_MAX ); need_cow = !test_bit (*offset / s->granularity, s->cow_bitmap); need_cow |= !test_bit ((*offset + *bytes -1 ) / s->granularity, s->cow_bitmap);
@@ -238,59 +239,51 @@ static inline void mirror_wait_for_io(MirrorBlockJob *s) }/* Submit async read while handling COW. -* Returns: The number of sectors copied after and including sector_num, -* excluding any sectors copied prior to sector_num due to alignment. -* This will be nb_sectors if no alignment is necessary, or -* (new_end - sector_num) if tail is rounded up or down due to +* Returns: The number of bytes copied after and including offset, +* excluding any bytes copied prior to offset due to alignment. +* This will be @bytes if no alignment is necessary, or +* (new_end - offset) if tail is rounded up or down due to * alignment or buffer limit. */ -static int mirror_do_read (MirrorBlockJob *s,int64_t sector_num, -int nb_sectors) +static uint64_t mirror_do_read (MirrorBlockJob *s,int64_t offset, +uint64_t bytes) {BlockBackend *source = s->common.blk; -int sectors_per_chunk, nb_chunks; -int ret; +int nb_chunks; +uint64_t ret;MirrorOp *op; -int max_sectors; +uint64_t max_bytes; - sectors_per_chunk = s->granularity >>BDRV_SECTOR_BITS ; - max_sectors = sectors_per_chunk * s->max_iov; + max_bytes = s->granularity * s->max_iov;/* We can only handle as much as buf_size at a time. */ - nb_sectors =MIN (s->buf_size >>BDRV_SECTOR_BITS , nb_sectors); - nb_sectors =MIN (max_sectors, nb_sectors); -assert (nb_sectors); -assert (nb_sectors <BDRV_REQUEST_MAX_SECTORS ); - ret = nb_sectors; + bytes =MIN (s->buf_size,MIN (max_bytes, bytes)); +assert (bytes); +assert (bytes <BDRV_REQUEST_MAX_BYTES ); + ret = bytes;if (s->cow_bitmap) { -int64_t offset = sector_num *BDRV_SECTOR_SIZE ; -unsigned int bytes = nb_sectors *BDRV_SECTOR_SIZE ; -int gap; - - gap =mirror_cow_align (s, &offset, &bytes); - sector_num = offset /BDRV_SECTOR_SIZE ; - nb_sectors = bytes /BDRV_SECTOR_SIZE ; - ret += gap /BDRV_SECTOR_SIZE ; + ret +=mirror_cow_align (s, &offset, &bytes); } -assert (nb_sectors <<BDRV_SECTOR_BITS <= s->buf_size); -/* The sector range must meet granularity because: +assert (bytes <= s->buf_size); +/* The offset is granularity-aligned because: * 1) Caller passes in aligned values; * 2) mirror_cow_align is used only when target cluster is larger. */ -assert (!(sector_num % sectors_per_chunk)); - nb_chunks =DIV_ROUND_UP (nb_sectors, sectors_per_chunk); +assert (QEMU_IS_ALIGNED (offset, s->granularity)); +/* The range is sector-aligned, since bdrv_getlength() rounds up. */ +assert (QEMU_IS_ALIGNED (bytes,BDRV_SECTOR_SIZE )); + nb_chunks =DIV_ROUND_UP (bytes, s->granularity);while (s->buf_free_count < nb_chunks) { -trace_mirror_yield_in_flight (s, sector_num *BDRV_SECTOR_SIZE , - s->in_flight); +trace_mirror_yield_in_flight (s, offset, s->in_flight);mirror_wait_for_io (s); }/* Allocate a MirrorOp that is used as an AIO callback. */ op =g_new (MirrorOp,1 ); op->s = s; - op->offset = sector_num *BDRV_SECTOR_SIZE ; - op->bytes = nb_sectors *BDRV_SECTOR_SIZE ; + op->offset = offset; + op->bytes = bytes;/* Now make a QEMUIOVector taking enough granularity-sized chunks * from s->buf_free.
@@ -298,7 +291,7 @@ static int mirror_do_read(MirrorBlockJob *s, int64_t sector_num,qemu_iovec_init (&op->qiov, nb_chunks);while (nb_chunks-- >0 ) {MirrorBuffer *buf =QSIMPLEQ_FIRST (&s->buf_free); -size_t remaining = nb_sectors *BDRV_SECTOR_SIZE - op->qiov.size; +size_t remaining = bytes - op->qiov.size;QSIMPLEQ_REMOVE_HEAD (&s->buf_free, next); s->buf_free_count--;
@@ -307,12 +300,10 @@ static int mirror_do_read(MirrorBlockJob *s, int64_t sector_num,/* Copy the dirty cluster. */ s->in_flight++; - s->bytes_in_flight += nb_sectors *BDRV_SECTOR_SIZE ; -trace_mirror_one_iteration (s, sector_num *BDRV_SECTOR_SIZE , - nb_sectors *BDRV_SECTOR_SIZE ); + s->bytes_in_flight += bytes; +trace_mirror_one_iteration (s, offset, bytes); -blk_aio_preadv (source, sector_num *BDRV_SECTOR_SIZE , &op->qiov,0 , - mirror_read_complete, op); +blk_aio_preadv (source, offset, &op->qiov,0 , mirror_read_complete, op);return ret; }
@@ -460,8 +451,9 @@ static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s) io_sectors =mirror_clip_sectors (s, sector_num, io_sectors);switch (mirror_method) {case MIRROR_METHOD_COPY : - io_sectors =mirror_do_read (s, sector_num, io_sectors); - io_bytes_acct = io_sectors *BDRV_SECTOR_SIZE ; + io_bytes_acct =mirror_do_read (s, sector_num *BDRV_SECTOR_SIZE , + io_sectors *BDRV_SECTOR_SIZE ); + io_sectors = io_bytes_acct /BDRV_SECTOR_SIZE ;break ;case MIRROR_METHOD_ZERO :case MIRROR_METHOD_DISCARD :
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 033/100] block: Drop unused bdrv_round_sectors_to_clusters()
In reply to Kevin WolfFrom: Eric Blake <[email protected]>
Now that the last user [mirror_iteration()] has converted to using bytes, we no longer need a function to round sectors to clusters.
--- block/io.c | 21 --------------------- include/block/block.h | 4 ---- 2 files changed, 25 deletions(-)
block/io.c +0 -21
@@ -419,27 +419,6 @@ static void mark_request_serialising(BdrvTrackedRequest *req, uint64_t align) }/** -* Round a region to cluster boundaries (sector-based) -*/ -void bdrv_round_sectors_to_clusters (BlockDriverState *bs, -int64_t sector_num,int nb_sectors, -int64_t *cluster_sector_num, -int *cluster_nb_sectors) -{ -BlockDriverInfo bdi; - -if (bdrv_get_info (bs, &bdi) <0 || bdi.cluster_size ==0 ) { - *cluster_sector_num = sector_num; - *cluster_nb_sectors = nb_sectors; - }else { -int64_t c = bdi.cluster_size /BDRV_SECTOR_SIZE ; - *cluster_sector_num =QEMU_ALIGN_DOWN (sector_num, c); - *cluster_nb_sectors =QEMU_ALIGN_UP (sector_num - *cluster_sector_num + - nb_sectors, c); - } -} - -/** * Round a region to cluster boundaries */ void bdrv_round_to_clusters(BlockDriverState *bs,
include/block/block.h +0 -4
@@ -475,10 +475,6 @@ const char *bdrv_get_device_or_node_name(const BlockDriverState *bs);int bdrv_get_flags (BlockDriverState *bs);int bdrv_get_info (BlockDriverState *bs,BlockDriverInfo *bdi);ImageInfoSpecific *bdrv_get_specific_info (BlockDriverState *bs); -void bdrv_round_sectors_to_clusters (BlockDriverState *bs, -int64_t sector_num,int nb_sectors, -int64_t *cluster_sector_num, -int *cluster_nb_sectors); void bdrv_round_to_clusters(BlockDriverState *bs, int64_t offset, unsigned int bytes, int64_t *cluster_offset,
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 032/100] mirror: Switch mirror_iteration() to byte-based
In reply to Kevin WolfFrom: Eric Blake <[email protected]>
We are gradually converting to byte-based interfaces, as they are easier to reason about than sector-based. Change the internal loop iteration of mirroring to track by bytes instead of sectors (although we are still guaranteed that we iterate by steps that are both sector-aligned and multiples of the granularity). Drop the now-unused mirror_clip_sectors().
--- block/mirror.c | 105 +++++++++++++++++++++++++-------------------------------- 1 file changed, 46 insertions(+), 59 deletions(-)
block/mirror.c +46 -59
@@ -184,15 +184,6 @@ static inline int64_t mirror_clip_bytes(MirrorBlockJob *s,return MIN (bytes, s->bdev_length - offset); } -/* Clip nb_sectors relative to sector_num to not exceed end-of-file */ -static inline int mirror_clip_sectors (MirrorBlockJob *s, -int64_t sector_num, -int nb_sectors) -{ -return MIN (nb_sectors, - s->bdev_length /BDRV_SECTOR_SIZE - sector_num); -} -/* Round offset and/or bytes to target cluster if COW is needed, and * return the offset of the adjusted tail against original. */ static int mirror_cow_align(MirrorBlockJob *s, int64_t *offset,
@@ -336,30 +327,28 @@ static void mirror_do_zero_or_discard(MirrorBlockJob *s, static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s) {BlockDriverState *source = s->source; -int64_t sector_num, first_chunk; +int64_t offset, first_chunk;uint64_t delay_ns =0 ;/* At least the first dirty chunk is mirrored in one iteration. */ int nb_chunks =1 ; -int64_t end = s->bdev_length /BDRV_SECTOR_SIZE ;int sectors_per_chunk = s->granularity >>BDRV_SECTOR_BITS ;bool write_zeroes_ok =bdrv_can_write_zeroes_with_unmap (blk_bs (s->target));int max_io_bytes =MAX (s->buf_size /MAX_IN_FLIGHT ,MAX_IO_BYTES );bdrv_dirty_bitmap_lock (s->dirty_bitmap); - sector_num =bdrv_dirty_iter_next (s->dbi); -if (sector_num <0 ) { + offset =bdrv_dirty_iter_next (s->dbi) *BDRV_SECTOR_SIZE ; +if (offset <0 ) {bdrv_set_dirty_iter (s->dbi,0 ); - sector_num =bdrv_dirty_iter_next (s->dbi); + offset =bdrv_dirty_iter_next (s->dbi) *BDRV_SECTOR_SIZE ;trace_mirror_restart_iter (s,bdrv_get_dirty_count (s->dirty_bitmap) *BDRV_SECTOR_SIZE ); -assert (sector_num >=0 ); +assert (offset >=0 ); }bdrv_dirty_bitmap_unlock (s->dirty_bitmap); - first_chunk = sector_num / sectors_per_chunk; + first_chunk = offset / s->granularity;while (test_bit (first_chunk, s->in_flight_bitmap)) { -trace_mirror_yield_in_flight (s, sector_num *BDRV_SECTOR_SIZE , - s->in_flight); +trace_mirror_yield_in_flight (s, offset, s->in_flight);mirror_wait_for_io (s); }
@@ -368,25 +357,26 @@ static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s)/* Find the number of consective dirty chunks following the first dirty * one, and wait for in flight requests in them. */ bdrv_dirty_bitmap_lock (s->dirty_bitmap); -while (nb_chunks * sectors_per_chunk < (s->buf_size >>BDRV_SECTOR_BITS )) { +while (nb_chunks * s->granularity < s->buf_size) {int64_t next_dirty; -int64_t next_sector = sector_num + nb_chunks * sectors_per_chunk; -int64_t next_chunk = next_sector / sectors_per_chunk; -if (next_sector >= end || - !bdrv_get_dirty_locked (source, s->dirty_bitmap, next_sector)) { +int64_t next_offset = offset + nb_chunks * s->granularity; +int64_t next_chunk = next_offset / s->granularity; +if (next_offset >= s->bdev_length || + !bdrv_get_dirty_locked (source, s->dirty_bitmap, + next_offset >>BDRV_SECTOR_BITS )) {break ; }if (test_bit (next_chunk, s->in_flight_bitmap)) {break ; } - next_dirty =bdrv_dirty_iter_next (s->dbi); -if (next_dirty > next_sector || next_dirty <0 ) { + next_dirty =bdrv_dirty_iter_next (s->dbi) *BDRV_SECTOR_SIZE ; +if (next_dirty > next_offset || next_dirty <0 ) {/* The bitmap iterator's cache is stale, refresh it */ -bdrv_set_dirty_iter (s->dbi, next_sector); - next_dirty =bdrv_dirty_iter_next (s->dbi); +bdrv_set_dirty_iter (s->dbi, next_offset >>BDRV_SECTOR_BITS ); + next_dirty =bdrv_dirty_iter_next (s->dbi) *BDRV_SECTOR_SIZE ; } -assert (next_dirty == next_sector); +assert (next_dirty == next_offset); nb_chunks++; }
@@ -394,14 +384,15 @@ static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s)* calling bdrv_get_block_status_above could yield - if some blocks are * marked dirty in this window, we need to know. */ -bdrv_reset_dirty_bitmap_locked (s->dirty_bitmap, sector_num, - nb_chunks * sectors_per_chunk); +bdrv_reset_dirty_bitmap_locked (s->dirty_bitmap, offset >>BDRV_SECTOR_BITS , + nb_chunks * sectors_per_chunk);bdrv_dirty_bitmap_unlock (s->dirty_bitmap); -bitmap_set (s->in_flight_bitmap, sector_num / sectors_per_chunk, nb_chunks); -while (nb_chunks >0 && sector_num < end) { +bitmap_set (s->in_flight_bitmap, offset / s->granularity, nb_chunks); +while (nb_chunks >0 && offset < s->bdev_length) {int64_t ret;int io_sectors; +unsigned int io_bytes;int64_t io_bytes_acct;BlockDriverState *file; enum MirrorMethod {
@@ -410,28 +401,28 @@ static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s)MIRROR_METHOD_DISCARD } mirror_method = MIRROR_METHOD_COPY; -assert (!(sector_num % sectors_per_chunk)); - ret =bdrv_get_block_status_above (source,NULL , sector_num, +assert (!(offset % s->granularity)); + ret =bdrv_get_block_status_above (source,NULL , + offset >>BDRV_SECTOR_BITS , nb_chunks * sectors_per_chunk, &io_sectors, &file); + io_bytes = io_sectors *BDRV_SECTOR_SIZE ;if (ret <0 ) { - io_sectors =MIN (nb_chunks * sectors_per_chunk, - max_io_bytes >>BDRV_SECTOR_BITS ); + io_bytes =MIN (nb_chunks * s->granularity, max_io_bytes); }else if (ret &BDRV_BLOCK_DATA ) { - io_sectors =MIN (io_sectors, max_io_bytes >>BDRV_SECTOR_BITS ); + io_bytes =MIN (io_bytes, max_io_bytes); } - io_sectors -= io_sectors % sectors_per_chunk; -if (io_sectors < sectors_per_chunk) { - io_sectors = sectors_per_chunk; + io_bytes -= io_bytes % s->granularity; +if (io_bytes < s->granularity) { + io_bytes = s->granularity; }else if (ret >=0 && !(ret &BDRV_BLOCK_DATA )) { -int64_t target_sector_num; -int target_nb_sectors; -bdrv_round_sectors_to_clusters (blk_bs (s->target), sector_num, - io_sectors, &target_sector_num, - &target_nb_sectors); -if (target_sector_num == sector_num && - target_nb_sectors == io_sectors) { +int64_t target_offset; +unsigned int target_bytes; +bdrv_round_to_clusters (blk_bs (s->target), offset, io_bytes, + &target_offset, &target_bytes); +if (target_offset == offset && + target_bytes == io_bytes) { mirror_method = ret &BDRV_BLOCK_ZERO ?MIRROR_METHOD_ZERO :MIRROR_METHOD_DISCARD ;
@@ -439,8 +430,7 @@ static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s) }while (s->in_flight >=MAX_IN_FLIGHT ) { -trace_mirror_yield_in_flight (s, sector_num *BDRV_SECTOR_SIZE , - s->in_flight); +trace_mirror_yield_in_flight (s, offset, s->in_flight);mirror_wait_for_io (s); }
@@ -448,30 +438,27 @@ static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s)return 0 ; } - io_sectors =mirror_clip_sectors (s, sector_num, io_sectors); + io_bytes =mirror_clip_bytes (s, offset, io_bytes);switch (mirror_method) {case MIRROR_METHOD_COPY : - io_bytes_acct =mirror_do_read (s, sector_num *BDRV_SECTOR_SIZE , - io_sectors *BDRV_SECTOR_SIZE ); - io_sectors = io_bytes_acct /BDRV_SECTOR_SIZE ; + io_bytes = io_bytes_acct =mirror_do_read (s, offset, io_bytes);break ;case MIRROR_METHOD_ZERO :case MIRROR_METHOD_DISCARD : -mirror_do_zero_or_discard (s, sector_num *BDRV_SECTOR_SIZE , - io_sectors *BDRV_SECTOR_SIZE , +mirror_do_zero_or_discard (s, offset, io_bytes, mirror_method ==MIRROR_METHOD_DISCARD );if (write_zeroes_ok) { io_bytes_acct =0 ; }else { - io_bytes_acct = io_sectors *BDRV_SECTOR_SIZE ; + io_bytes_acct = io_bytes; }break ;default :abort (); } -assert (io_sectors); - sector_num += io_sectors; - nb_chunks -=DIV_ROUND_UP (io_sectors, sectors_per_chunk); +assert (io_bytes); + offset += io_bytes; + nb_chunks -=DIV_ROUND_UP (io_bytes, s->granularity);if (s->common.speed) { delay_ns =ratelimit_calculate_delay (&s->limit, io_bytes_acct); }
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 034/100] backup: Switch BackupBlockJob to byte-based
In reply to Kevin WolfFrom: Eric Blake <[email protected]>
We are gradually converting to byte-based interfaces, as they are easier to reason about than sector-based. Continue by converting an internal structure (no semantic change), and all references to tracking progress. Drop a redundant local variable bytes_per_cluster.
--- block/backup.c | 33 +++++++++++++++------------------ 1 file changed, 15 insertions(+), 18 deletions(-)
block/backup.c +15 -18
@@ -39,7 +39,7 @@ typedef struct BackupBlockJob {BlockdevOnError on_source_error;BlockdevOnError on_target_error;CoRwlock flush_rwlock; -uint64_t sectors_read; +uint64_t bytes_read;unsigned long *done_bitmap;int64_t cluster_size;bool compress;
@@ -102,16 +102,15 @@ static int coroutine_fn backup_do_cow(BackupBlockJob *job,void *bounce_buffer =NULL ;int ret =0 ;int64_t sectors_per_cluster =cluster_size_sectors (job); -int64_t bytes_per_cluster = sectors_per_cluster *BDRV_SECTOR_SIZE ; -int64_t start, end; -int n; +int64_t start, end;/* clusters */ +int n;/* bytes */ qemu_co_rwlock_rdlock (&job->flush_rwlock); start = sector_num / sectors_per_cluster; end =DIV_ROUND_UP (sector_num + nb_sectors, sectors_per_cluster); -trace_backup_do_cow_enter (job, start * bytes_per_cluster, +trace_backup_do_cow_enter (job, start * job->cluster_size, sector_num *BDRV_SECTOR_SIZE , nb_sectors *BDRV_SECTOR_SIZE );
@@ -120,28 +119,27 @@ static int coroutine_fn backup_do_cow(BackupBlockJob *job,for (; start < end; start++) {if (test_bit (start, job->done_bitmap)) { -trace_backup_do_cow_skip (job, start * bytes_per_cluster); +trace_backup_do_cow_skip (job, start * job->cluster_size);continue ;/* already copied */ } -trace_backup_do_cow_process (job, start * bytes_per_cluster); +trace_backup_do_cow_process (job, start * job->cluster_size); - n =MIN (sectors_per_cluster, - job->common.len /BDRV_SECTOR_SIZE - - start * sectors_per_cluster); + n =MIN (job->cluster_size, + job->common.len - start * job->cluster_size);if (!bounce_buffer) { bounce_buffer =blk_blockalign (blk, job->cluster_size); } iov.iov_base = bounce_buffer; - iov.iov_len = n *BDRV_SECTOR_SIZE ; + iov.iov_len = n;qemu_iovec_init_external (&bounce_qiov, &iov,1 ); ret =blk_co_preadv (blk, start * job->cluster_size, bounce_qiov.size, &bounce_qiov, is_write_notifier ?BDRV_REQ_NO_SERIALISING :0 );if (ret <0 ) { -trace_backup_do_cow_read_fail (job, start * bytes_per_cluster, ret); +trace_backup_do_cow_read_fail (job, start * job->cluster_size, ret);if (error_is_read) { *error_is_read = true; }
@@ -157,7 +155,7 @@ static int coroutine_fn backup_do_cow(BackupBlockJob *job, job->compress ? BDRV_REQ_WRITE_COMPRESSED : 0); }if (ret <0 ) { -trace_backup_do_cow_write_fail (job, start * bytes_per_cluster, ret); +trace_backup_do_cow_write_fail (job, start * job->cluster_size, ret);if (error_is_read) { *error_is_read = false; }
@@ -169,8 +167,8 @@ static int coroutine_fn backup_do_cow(BackupBlockJob *job,/* Publish progress, guest I/O counts as progress too. Note that the * offset field is an opaque progress value, it is not a disk offset. */ - job->sectors_read += n; - job->common.offset += n *BDRV_SECTOR_SIZE ; + job->bytes_read += n; + job->common.offset += n; } out:
@@ -363,9 +361,8 @@ static bool coroutine_fn yield_and_check(BackupBlockJob *job)*/ if (job->common.speed) {uint64_t delay_ns =ratelimit_calculate_delay (&job->limit, - job->sectors_read * -BDRV_SECTOR_SIZE ); - job->sectors_read =0 ; + job->bytes_read); + job->bytes_read =0 ;block_job_sleep_ns (&job->common,QEMU_CLOCK_REALTIME , delay_ns); }else {block_job_sleep_ns (&job->common,QEMU_CLOCK_REALTIME ,0 );
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 035/100] backup: Switch block_backup.h to byte-based
In reply to Kevin WolfFrom: Eric Blake <[email protected]>
We are gradually converting to byte-based interfaces, as they are easier to reason about than sector-based. Continue by converting the public interface to backup jobs (no semantic change), including a change to CowRequest to track by bytes instead of cluster indices.
Note that this does not change the difference between the public interface (starting point, and size of the subsequent range) and the internal interface (starting and end points).
--- block/backup.c | 31 +++++++++++++++---------------- block/replication.c | 12 ++++++++---- include/block/block_backup.h | 11 +++++------ 3 files changed, 28 insertions(+), 26 deletions(-)
block/backup.c +15 -16
@@ -64,7 +64,7 @@ static void coroutine_fn wait_for_overlapping_requests(BackupBlockJob *job, do { retry = false; QLIST_FOREACH(req, &job->inflight_reqs, list) { - if (end > req->start && start < req->end) { + if (end > req->start_byte && start < req->end_byte) { qemu_co_queue_wait(&req->wait_queue, NULL); retry = true; break;
@@ -75,10 +75,10 @@ static void coroutine_fn wait_for_overlapping_requests(BackupBlockJob *job,/* Keep track of an in-flight request */ static void cow_request_begin (CowRequest *req,BackupBlockJob *job, -int64_t start,int64_t end) +int64_t start,int64_t end) { - req->start = start; - req->end = end; + req->start_byte = start; + req->end_byte = end;qemu_co_queue_init (&req->wait_queue);QLIST_INSERT_HEAD (&job->inflight_reqs, req, list); }
@@ -114,8 +114,10 @@ static int coroutine_fn backup_do_cow(BackupBlockJob *job, sector_num *BDRV_SECTOR_SIZE , nb_sectors * BDRV_SECTOR_SIZE); -wait_for_overlapping_requests (job, start, end); -cow_request_begin (&cow_request, job, start, end); +wait_for_overlapping_requests (job, start * job->cluster_size, + end * job->cluster_size); +cow_request_begin (&cow_request, job, start * job->cluster_size, + end * job->cluster_size);for (; start < end; start++) {if (test_bit (start, job->done_bitmap)) {
@@ -277,32 +279,29 @@ void backup_do_checkpoint(BlockJob *job, Error **errp)bitmap_zero (backup_job->done_bitmap, len); } -void backup_wait_for_overlapping_requests (BlockJob *job,int64_t sector_num, -int nb_sectors) +void backup_wait_for_overlapping_requests (BlockJob *job,int64_t offset, +uint64_t bytes) {BackupBlockJob *backup_job =container_of (job, BackupBlockJob, common); -int64_t sectors_per_cluster =cluster_size_sectors (backup_job);int64_t start, end;assert (job->driver->job_type ==BLOCK_JOB_TYPE_BACKUP ); - start = sector_num / sectors_per_cluster; - end =DIV_ROUND_UP (sector_num + nb_sectors, sectors_per_cluster); + start =QEMU_ALIGN_DOWN (offset, backup_job->cluster_size); + end =QEMU_ALIGN_UP (offset + bytes, backup_job->cluster_size);wait_for_overlapping_requests (backup_job, start, end); }void backup_cow_request_begin (CowRequest *req,BlockJob *job, -int64_t sector_num, -int nb_sectors) +int64_t offset,uint64_t bytes) {BackupBlockJob *backup_job =container_of (job, BackupBlockJob, common); -int64_t sectors_per_cluster =cluster_size_sectors (backup_job);int64_t start, end;assert (job->driver->job_type ==BLOCK_JOB_TYPE_BACKUP ); - start = sector_num / sectors_per_cluster; - end =DIV_ROUND_UP (sector_num + nb_sectors, sectors_per_cluster); + start =QEMU_ALIGN_DOWN (offset, backup_job->cluster_size); + end =QEMU_ALIGN_UP (offset + bytes, backup_job->cluster_size);cow_request_begin (req, backup_job, start, end); }
block/replication.c +8 -4
@@ -234,10 +234,14 @@ static coroutine_fn int replication_co_readv(BlockDriverState *bs, }if (job) { -backup_wait_for_overlapping_requests (child->bs->job, sector_num, - remaining_sectors); -backup_cow_request_begin (&req, child->bs->job, sector_num, - remaining_sectors); +uint64_t remaining_bytes = remaining_sectors *BDRV_SECTOR_SIZE ; + +backup_wait_for_overlapping_requests (child->bs->job, + sector_num *BDRV_SECTOR_SIZE , + remaining_bytes); +backup_cow_request_begin (&req, child->bs->job, + sector_num *BDRV_SECTOR_SIZE , + remaining_bytes); ret =bdrv_co_readv (bs->file, sector_num, remaining_sectors, qiov);backup_cow_request_end (&req);
include/block/block_backup.h +5 -6
@@ -21,17 +21,16 @@#include "block/block_int.h" typedef struct CowRequest { -int64_t start; -int64_t end; +int64_t start_byte; +int64_t end_byte;QLIST_ENTRY (CowRequest) list;CoQueue wait_queue;/* coroutines blocked on this request */ }CowRequest ; -void backup_wait_for_overlapping_requests (BlockJob *job,int64_t sector_num, -int nb_sectors); +void backup_wait_for_overlapping_requests (BlockJob *job,int64_t offset, +uint64_t bytes);void backup_cow_request_begin (CowRequest *req,BlockJob *job, -int64_t sector_num, -int nb_sectors); +int64_t offset,uint64_t bytes);void backup_cow_request_end (CowRequest *req);void backup_do_checkpoint (BlockJob *job,Error **errp);
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 037/100] backup: Switch backup_run() to byte-based
In reply to Kevin WolfFrom: Eric Blake <[email protected]>
We are gradually converting to byte-based interfaces, as they are easier to reason about than sector-based. Change the internal loop iteration of backups to track by bytes instead of sectors (although we are still guaranteed that we iterate by steps that are cluster-aligned).
--- block/backup.c | 32 +++++++++++++++----------------- 1 file changed, 15 insertions(+), 17 deletions(-)
block/backup.c +15 -17
@@ -370,11 +370,10 @@ static int coroutine_fn backup_run_incremental(BackupBlockJob *job)int ret =0 ;int clusters_per_iter;uint32_t granularity; -int64_t sector; +int64_t offset;int64_t cluster;int64_t end;int64_t last_cluster =-1 ; -int64_t sectors_per_cluster =cluster_size_sectors (job);BdrvDirtyBitmapIter *dbi; granularity =bdrv_dirty_bitmap_granularity (job->sync_bitmap);
@@ -382,8 +381,8 @@ static int coroutine_fn backup_run_incremental(BackupBlockJob *job) dbi =bdrv_dirty_iter_new (job->sync_bitmap,0 );/* Find the next dirty sector(s) */ -while ((sector =bdrv_dirty_iter_next (dbi)) !=-1 ) { - cluster = sector / sectors_per_cluster; +while ((offset =bdrv_dirty_iter_next (dbi) *BDRV_SECTOR_SIZE ) >=0 ) { + cluster = offset / job->cluster_size;/* Fake progress updates for any clusters we skipped */ if (cluster != last_cluster +1 ) {
@@ -410,7 +409,8 @@ static int coroutine_fn backup_run_incremental(BackupBlockJob *job)/* If the bitmap granularity is smaller than the backup granularity, * we need to advance the iterator pointer to the next cluster. */ if (granularity < job->cluster_size) { -bdrv_set_dirty_iter (dbi, cluster * sectors_per_cluster); +bdrv_set_dirty_iter (dbi, + cluster * job->cluster_size /BDRV_SECTOR_SIZE ); } last_cluster = cluster -1 ;
@@ -432,17 +432,15 @@ static void coroutine_fn backup_run(void *opaque)BackupBlockJob *job = opaque;BackupCompleteData *data;BlockDriverState *bs =blk_bs (job->common.blk); -int64_t start, end; +int64_t offset;int64_t sectors_per_cluster =cluster_size_sectors (job);int ret =0 ;QLIST_INIT (&job->inflight_reqs);qemu_co_rwlock_init (&job->flush_rwlock); - start =0 ; - end =DIV_ROUND_UP (job->common.len, job->cluster_size); - - job->done_bitmap =bitmap_new (end); + job->done_bitmap =bitmap_new (DIV_ROUND_UP (job->common.len, + job->cluster_size)); job->before_write.notify = backup_before_write_notify;bdrv_add_before_write_notifier (bs, &job->before_write);
@@ -457,7 +455,8 @@ static void coroutine_fn backup_run(void *opaque) ret =backup_run_incremental (job); }else {/* Both FULL and TOP SYNC_MODE's require copying.. */ -for (; start < end; start++) { +for (offset =0 ; offset < job->common.len; + offset += job->cluster_size) {bool error_is_read;int alloced =0 ;
@@ -480,8 +479,8 @@ static void coroutine_fn backup_run(void *opaque)* needed but at some point that is always the case. */ alloced =bdrv_is_allocated (bs, - start * sectors_per_cluster + i, - sectors_per_cluster - i, &n); + (offset >>BDRV_SECTOR_BITS ) + i, + sectors_per_cluster - i, &n); i += n;if (alloced || n ==0 ) {
@@ -499,9 +498,8 @@ static void coroutine_fn backup_run(void *opaque)if (alloced <0 ) { ret = alloced; }else { - ret =backup_do_cow (job, start * job->cluster_size, - job->cluster_size, &error_is_read, - false); + ret =backup_do_cow (job, offset, job->cluster_size, + &error_is_read, false); }if (ret <0 ) {/* Depending on error action, fail now or retry cluster */
@@ -510,7 +508,7 @@ static void coroutine_fn backup_run(void *opaque)if (action ==BLOCK_ERROR_ACTION_REPORT ) {break ; }else { - start--; + offset -= job->cluster_size;continue ; } }
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 039/100] block: Minimize raw use of bds->total_sectors
In reply to Kevin WolfFrom: Eric Blake <[email protected]>
bdrv_is_allocated_above() was relying on intermediate->total_sectors, which is a field that can have stale contents depending on the value of intermediate->has_variable_length. An audit shows that we are safe (we were first calling through bdrv_co_get_block_status() which in turn calls bdrv_nb_sectors() and therefore just refreshed the current length), but it's nicer to favor our accessor functions to avoid having to repeat such an audit, even if it means refresh_total_sectors() is called more frequently.
--- block/io.c | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-)
block/io.c +6 -8
@@ -1947,6 +1947,7 @@ int bdrv_is_allocated_above(BlockDriverState *top, intermediate = top;while (intermediate && intermediate != base) {int64_t pnum_inter; +int64_t size_inter;int psectors_inter; ret = bdrv_is_allocated(intermediate, sector_num * BDRV_SECTOR_SIZE,
@@ -1962,15 +1963,12 @@ int bdrv_is_allocated_above(BlockDriverState *top,return 1 ; } -/* -* [sector_num, nb_sectors] is unallocated on top but intermediate -* might have -* -* [sector_num+x, nr_sectors] allocated. -*/ + size_inter =bdrv_nb_sectors (intermediate); +if (size_inter <0 ) { +return size_inter; + }if (n > psectors_inter && - (intermediate == top || - sector_num + psectors_inter < intermediate->total_sectors)) { + (intermediate == top || sector_num + psectors_inter < size_inter)) { n = psectors_inter; }
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 036/100] backup: Switch backup_do_cow() to byte-based
In reply to Kevin WolfFrom: Eric Blake <[email protected]>
We are gradually converting to byte-based interfaces, as they are easier to reason about than sector-based. Convert another internal function (no semantic change).
--- block/backup.c | 62 ++++++++++++++++++++++++---------------------------------- 1 file changed, 26 insertions(+), 36 deletions(-)
block/backup.c +26 -36
@@ -91,7 +91,7 @@ static void cow_request_end(CowRequest *req) } static int coroutine_fn backup_do_cow(BackupBlockJob *job, -int64_t sector_num,int nb_sectors, +int64_t offset,uint64_t bytes,bool *error_is_read,bool is_write_notifier) {
@@ -101,34 +101,28 @@ static int coroutine_fn backup_do_cow(BackupBlockJob *job,QEMUIOVector bounce_qiov;void *bounce_buffer =NULL ;int ret =0 ; -int64_t sectors_per_cluster =cluster_size_sectors (job); -int64_t start, end;/* clusters */ +int64_t start, end;/* bytes */ int n;/* bytes */ qemu_co_rwlock_rdlock (&job->flush_rwlock); - start = sector_num / sectors_per_cluster; - end =DIV_ROUND_UP (sector_num + nb_sectors, sectors_per_cluster); + start =QEMU_ALIGN_DOWN (offset, job->cluster_size); + end =QEMU_ALIGN_UP (bytes + offset, job->cluster_size); -trace_backup_do_cow_enter (job, start * job->cluster_size, - sector_num *BDRV_SECTOR_SIZE , - nb_sectors *BDRV_SECTOR_SIZE ); +trace_backup_do_cow_enter (job, start, offset, bytes); -wait_for_overlapping_requests (job, start * job->cluster_size, - end * job->cluster_size); -cow_request_begin (&cow_request, job, start * job->cluster_size, - end * job->cluster_size); +wait_for_overlapping_requests (job, start, end); +cow_request_begin (&cow_request, job, start, end); -for (; start < end; start++) { -if (test_bit (start, job->done_bitmap)) { -trace_backup_do_cow_skip (job, start * job->cluster_size); +for (; start < end; start += job->cluster_size) { +if (test_bit (start / job->cluster_size, job->done_bitmap)) { +trace_backup_do_cow_skip (job, start);continue ;/* already copied */ } -trace_backup_do_cow_process (job, start * job->cluster_size); +trace_backup_do_cow_process (job, start); - n =MIN (job->cluster_size, - job->common.len - start * job->cluster_size); + n =MIN (job->cluster_size, job->common.len - start);if (!bounce_buffer) { bounce_buffer =blk_blockalign (blk, job->cluster_size);
@@ -137,11 +131,10 @@ static int coroutine_fn backup_do_cow(BackupBlockJob *job, iov.iov_len = n;qemu_iovec_init_external (&bounce_qiov, &iov,1 ); - ret =blk_co_preadv (blk, start * job->cluster_size, - bounce_qiov.size, &bounce_qiov, + ret =blk_co_preadv (blk, start, bounce_qiov.size, &bounce_qiov, is_write_notifier ?BDRV_REQ_NO_SERIALISING :0 );if (ret <0 ) { -trace_backup_do_cow_read_fail (job, start * job->cluster_size, ret); +trace_backup_do_cow_read_fail (job, start, ret);if (error_is_read) { *error_is_read = true; }
@@ -149,22 +142,22 @@ static int coroutine_fn backup_do_cow(BackupBlockJob *job, }if (buffer_is_zero (iov.iov_base, iov.iov_len)) { - ret =blk_co_pwrite_zeroes (job->target, start * job->cluster_size, + ret =blk_co_pwrite_zeroes (job->target, start, bounce_qiov.size,BDRV_REQ_MAY_UNMAP ); }else { - ret =blk_co_pwritev (job->target, start * job->cluster_size, + ret =blk_co_pwritev (job->target, start, bounce_qiov.size, &bounce_qiov, job->compress ?BDRV_REQ_WRITE_COMPRESSED :0 ); }if (ret <0 ) { -trace_backup_do_cow_write_fail (job, start * job->cluster_size, ret); +trace_backup_do_cow_write_fail (job, start, ret);if (error_is_read) { *error_is_read = false; } goto out; } -set_bit (start, job->done_bitmap); +set_bit (start / job->cluster_size, job->done_bitmap);/* Publish progress, guest I/O counts as progress too. Note that the * offset field is an opaque progress value, it is not a disk offset.
@@ -180,8 +173,7 @@ out:cow_request_end (&cow_request); -trace_backup_do_cow_return (job, sector_num *BDRV_SECTOR_SIZE , - nb_sectors *BDRV_SECTOR_SIZE , ret); +trace_backup_do_cow_return (job, offset, bytes, ret);qemu_co_rwlock_unlock (&job->flush_rwlock);
@@ -194,14 +186,12 @@ static int coroutine_fn backup_before_write_notify( {BackupBlockJob *job =container_of (notifier, BackupBlockJob, before_write);BdrvTrackedRequest *req = opaque; -int64_t sector_num = req->offset >>BDRV_SECTOR_BITS ; -int nb_sectors = req->bytes >>BDRV_SECTOR_BITS ;assert (req->bs ==blk_bs (job->common.blk)); -assert ((req->offset & (BDRV_SECTOR_SIZE -1 )) ==0 ); -assert ((req->bytes & (BDRV_SECTOR_SIZE -1 )) ==0 ); +assert (QEMU_IS_ALIGNED (req->offset,BDRV_SECTOR_SIZE )); +assert (QEMU_IS_ALIGNED (req->bytes,BDRV_SECTOR_SIZE )); -return backup_do_cow (job, sector_num, nb_sectors,NULL , true); +return backup_do_cow (job, req->offset, req->bytes,NULL , true); }static void backup_set_speed (BlockJob *job,int64_t speed,Error **errp)
@@ -406,8 +396,8 @@ static int coroutine_fn backup_run_incremental(BackupBlockJob *job)if (yield_and_check (job)) { goto out; } - ret =backup_do_cow (job, cluster * sectors_per_cluster, - sectors_per_cluster, &error_is_read, + ret =backup_do_cow (job, cluster * job->cluster_size, + job->cluster_size, &error_is_read, false);if ((ret <0 ) && backup_error_action(job, error_is_read, -ret) ==
@@ -509,8 +499,8 @@ static void coroutine_fn backup_run(void *opaque)if (alloced <0 ) { ret = alloced; }else { - ret =backup_do_cow (job, start * sectors_per_cluster, - sectors_per_cluster, &error_is_read, + ret =backup_do_cow (job, start * job->cluster_size, + job->cluster_size, &error_is_read, false); }if (ret <0 ) {
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 040/100] block: Make bdrv_is_allocated_above() byte-based
In reply to Kevin WolfFrom: Eric Blake <[email protected]>
We are gradually moving away from sector-based interfaces, towards byte-based. In the common case, allocation is unlikely to ever use values that are not naturally sector-aligned, but it is possible that byte-based values will let us be more precise about allocation at the end of an unaligned file that can do byte-based access.
Changing the signature of the function to use int64_t *pnum ensures that the compiler enforces that all callers are updated. For now, the io.c layer still assert()s that all callers are sector-aligned, but that can be relaxed when a later patch implements byte-based block status. Therefore, for the most part this patch is just the addition of scaling at the callers followed by inverse scaling at bdrv_is_allocated(). But some code, particularly stream_run(), gets a lot simpler because it no longer has to mess with sectors. Leave comments where we can further simplify by switching to byte-based iterations, once later patches eliminate the need for sector-aligned operations.
For ease of review, bdrv_is_allocated() was tackled separately.
--- block/commit.c | 20 ++++++++------------ block/io.c | 38 ++++++++++++++++++-------------------- block/mirror.c | 8 +++++++- block/replication.c | 17 ++++++++++++----- block/stream.c | 23 +++++++++-------------- include/block/block.h | 2 +- qemu-img.c | 13 ++++++++++--- 7 files changed, 65 insertions(+), 56 deletions(-)
block/commit.c +8 -12
@@ -146,7 +146,7 @@ static void coroutine_fn commit_run(void *opaque)int64_t offset;uint64_t delay_ns =0 ;int ret =0 ; -int n =0 ;/* sectors */ +int64_t n =0 ;/* bytes */ void *buf =NULL ;int bytes_written =0 ;int64_t base_len;
@@ -171,7 +171,7 @@ static void coroutine_fn commit_run(void *opaque) buf =blk_blockalign (s->top,COMMIT_BUFFER_SIZE ); -for (offset =0 ; offset < s->common.len; offset += n *BDRV_SECTOR_SIZE ) { +for (offset =0 ; offset < s->common.len; offset += n) {bool copy;/* Note that even when no rate limit is applied we need to yield
@@ -183,15 +183,12 @@ static void coroutine_fn commit_run(void *opaque) }/* Copy if allocated above the base */ ret =bdrv_is_allocated_above (blk_bs (s->top),blk_bs (s->base), - offset /BDRV_SECTOR_SIZE , -COMMIT_BUFFER_SIZE /BDRV_SECTOR_SIZE , - &n); + offset,COMMIT_BUFFER_SIZE , &n); copy = (ret ==1 ); -trace_commit_one_iteration (s, offset, n *BDRV_SECTOR_SIZE , ret); +trace_commit_one_iteration (s, offset, n, ret);if (copy) { - ret =commit_populate (s->top, s->base, offset, - n *BDRV_SECTOR_SIZE , buf); - bytes_written += n *BDRV_SECTOR_SIZE ; + ret =commit_populate (s->top, s->base, offset, n, buf); + bytes_written += n; }if (ret <0 ) { BlockErrorAction action =
@@ -204,11 +201,10 @@ static void coroutine_fn commit_run(void *opaque) } }/* Publish progress */ - s->common.offset += n *BDRV_SECTOR_SIZE ; + s->common.offset += n;if (copy && s->common.speed) { - delay_ns =ratelimit_calculate_delay (&s->limit, - n *BDRV_SECTOR_SIZE ); + delay_ns =ratelimit_calculate_delay (&s->limit, n); } }
block/io.c +18 -20
@@ -1926,50 +1926,48 @@ int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t offset,/* * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP] * -* Return true if the given sector is allocated in any image between -* BASE and TOP (inclusive). BASE can be NULL to check if the given -* sector is allocated in any image of the chain. Return false otherwise, +* Return true if (a prefix of) the given range is allocated in any image +* between BASE and TOP (inclusive). BASE can be NULL to check if the given +* offset is allocated in any image of the chain. Return false otherwise, * or negative errno on failure. * -* 'pnum' is set to the number of sectors (including and immediately following -* the specified sector) that are known to be in the same -* allocated/unallocated state. +* 'pnum' is set to the number of bytes (including and immediately +* following the specified offset) that are known to be in the same +* allocated/unallocated state. Note that a subsequent call starting +* at 'offset + *pnum' may return the same allocation status (in other +* words, the result is not necessarily the maximum possible range); +* but 'pnum' will only be 0 when end of file is reached. * */ int bdrv_is_allocated_above (BlockDriverState *top,BlockDriverState *base, -int64_t sector_num, -int nb_sectors,int *pnum) +int64_t offset,int64_t bytes,int64_t *pnum) {BlockDriverState *intermediate; -int ret, n = nb_sectors; +int ret; +int64_t n = bytes; intermediate = top;while (intermediate && intermediate != base) {int64_t pnum_inter;int64_t size_inter; -int psectors_inter; - ret =bdrv_is_allocated (intermediate, sector_num *BDRV_SECTOR_SIZE , - nb_sectors *BDRV_SECTOR_SIZE , - &pnum_inter); + ret =bdrv_is_allocated (intermediate, offset, bytes, &pnum_inter);if (ret <0 ) {return ret; } -assert (pnum_inter <INT_MAX *BDRV_SECTOR_SIZE ); - psectors_inter = pnum_inter >>BDRV_SECTOR_BITS ;if (ret) { - *pnum = psectors_inter; + *pnum = pnum_inter;return 1 ; } - size_inter =bdrv_nb_sectors (intermediate); + size_inter =bdrv_getlength (intermediate);if (size_inter <0 ) {return size_inter; } -if (n > psectors_inter && - (intermediate == top || sector_num + psectors_inter < size_inter)) { - n = psectors_inter; +if (n > pnum_inter && + (intermediate == top || offset + pnum_inter < size_inter)) { + n = pnum_inter; } intermediate =backing_bs (intermediate);
block/mirror.c +7 -1
@@ -621,6 +621,7 @@ static int coroutine_fn mirror_dirty_init(MirrorBlockJob *s)BlockDriverState *bs = s->source;BlockDriverState *target_bs =blk_bs (s->target);int ret, n; +int64_t count; end = s->bdev_length /BDRV_SECTOR_SIZE ;
@@ -670,11 +671,16 @@ static int coroutine_fn mirror_dirty_init(MirrorBlockJob *s)return 0 ; } - ret =bdrv_is_allocated_above (bs, base, sector_num, nb_sectors, &n); + ret =bdrv_is_allocated_above (bs, base, sector_num *BDRV_SECTOR_SIZE , + nb_sectors *BDRV_SECTOR_SIZE , &count);if (ret <0 ) {return ret; } +/* TODO: Relax this once bdrv_is_allocated_above and dirty +* bitmaps no longer require sector alignment. */ +assert (QEMU_IS_ALIGNED (count,BDRV_SECTOR_SIZE )); + n = count >>BDRV_SECTOR_BITS ;assert (n >0 );if (ret ==1 ) {bdrv_set_dirty_bitmap (s->dirty_bitmap, sector_num, n);
block/replication.c +12 -5
@@ -264,7 +264,8 @@ static coroutine_fn int replication_co_writev(BlockDriverState *bs,BdrvChild *top = bs->file;BdrvChild *base = s->secondary_disk;BdrvChild *target; -int ret, n; +int ret; +int64_t n; ret =replication_get_io_status (s);if (ret <0 ) {
@@ -283,14 +284,20 @@ static coroutine_fn int replication_co_writev(BlockDriverState *bs,*/ qemu_iovec_init (&hd_qiov, qiov->niov);while (remaining_sectors >0 ) { - ret =bdrv_is_allocated_above (top->bs, base->bs, sector_num, - remaining_sectors, &n); +int64_t count; + + ret =bdrv_is_allocated_above (top->bs, base->bs, + sector_num *BDRV_SECTOR_SIZE , + remaining_sectors *BDRV_SECTOR_SIZE , + &count);if (ret <0 ) { goto out1; } +assert (QEMU_IS_ALIGNED (count,BDRV_SECTOR_SIZE )); + n = count >>BDRV_SECTOR_BITS ;qemu_iovec_reset (&hd_qiov); -qemu_iovec_concat (&hd_qiov, qiov, bytes_done, n *BDRV_SECTOR_SIZE ); +qemu_iovec_concat (&hd_qiov, qiov, bytes_done, count); target = ret ? top : base; ret =bdrv_co_writev (target, sector_num, n, &hd_qiov);
@@ -300,7 +307,7 @@ static coroutine_fn int replication_co_writev(BlockDriverState *bs, remaining_sectors -= n; sector_num += n; - bytes_done += n *BDRV_SECTOR_SIZE ; + bytes_done += count; } out1:
block/stream.c +9 -14
@@ -111,7 +111,7 @@ static void coroutine_fn stream_run(void *opaque)uint64_t delay_ns =0 ;int error =0 ;int ret =0 ; -int n =0 ;/* sectors */ +int64_t n =0 ;/* bytes */ void *buf;if (!bs->backing) {
@@ -135,9 +135,8 @@ static void coroutine_fn stream_run(void *opaque)bdrv_enable_copy_on_read (bs); } -for ( ; offset < s->common.len; offset += n *BDRV_SECTOR_SIZE ) { +for ( ; offset < s->common.len; offset += n) {bool copy; -int64_t count =0 ;/* Note that even when no rate limit is applied we need to yield * with no pending I/O here so that bdrv_drain_all() returns.
@@ -149,28 +148,25 @@ static void coroutine_fn stream_run(void *opaque) copy = false; - ret =bdrv_is_allocated (bs, offset,STREAM_BUFFER_SIZE , &count); -/* TODO relax this once bdrv_is_allocated does not enforce sectors */ -assert (QEMU_IS_ALIGNED (count,BDRV_SECTOR_SIZE )); - n = count >>BDRV_SECTOR_BITS ; + ret =bdrv_is_allocated (bs, offset,STREAM_BUFFER_SIZE , &n);if (ret ==1 ) {/* Allocated in the top, no need to copy. */ }else if (ret >=0 ) {/* Copy if allocated in the intermediate images. Limit to the * known-unallocated area [offset, offset+n*BDRV_SECTOR_SIZE). */ ret =bdrv_is_allocated_above (backing_bs (bs), base, - offset /BDRV_SECTOR_SIZE , n, &n); + offset, n, &n);/* Finish early if end of backing file has been reached */ if (ret ==0 && n ==0 ) { - n = (s->common.len - offset) /BDRV_SECTOR_SIZE ; + n = s->common.len - offset; } copy = (ret ==1 ); } -trace_stream_one_iteration (s, offset, n *BDRV_SECTOR_SIZE , ret); +trace_stream_one_iteration (s, offset, n, ret);if (copy) { - ret =stream_populate (blk, offset, n *BDRV_SECTOR_SIZE , buf); + ret =stream_populate (blk, offset, n, buf); }if (ret <0 ) { BlockErrorAction action =
@@ -189,10 +185,9 @@ static void coroutine_fn stream_run(void *opaque) ret =0 ;/* Publish progress */ - s->common.offset += n *BDRV_SECTOR_SIZE ; + s->common.offset += n;if (copy && s->common.speed) { - delay_ns =ratelimit_calculate_delay (&s->limit, - n *BDRV_SECTOR_SIZE ); + delay_ns =ratelimit_calculate_delay (&s->limit, n); } }
include/block/block.h +1 -1
@@ -430,7 +430,7 @@ int64_t bdrv_get_block_status_above(BlockDriverState *bs,int bdrv_is_allocated (BlockDriverState *bs,int64_t offset,int64_t bytes,int64_t *pnum);int bdrv_is_allocated_above (BlockDriverState *top,BlockDriverState *base, -int64_t sector_num,int nb_sectors,int *pnum); +int64_t offset,int64_t bytes,int64_t *pnum);bool bdrv_is_read_only (BlockDriverState *bs);bool bdrv_is_writable (BlockDriverState *bs);
qemu-img.c +10 -3
@@ -1508,12 +1508,16 @@ static int img_compare(int argc, char **argv) }for (;;) { +int64_t count; + nb_sectors =sectors_to_process (total_sectors_over, sector_num);if (nb_sectors <=0 ) {break ; } - ret =bdrv_is_allocated_above (blk_bs (blk_over),NULL , sector_num, - nb_sectors, &pnum); + ret =bdrv_is_allocated_above (blk_bs (blk_over),NULL , + sector_num *BDRV_SECTOR_SIZE , + nb_sectors *BDRV_SECTOR_SIZE , + &count);if (ret <0 ) { ret =3 ; error_report("Sector allocation test failed for %s",
@@ -1521,7 +1525,10 @@ static int img_compare(int argc, char **argv) goto out; } - nb_sectors = pnum; +/* TODO relax this once bdrv_is_allocated_above does not enforce +* sector alignment */ +assert (QEMU_IS_ALIGNED (count,BDRV_SECTOR_SIZE )); + nb_sectors = count >>BDRV_SECTOR_BITS ;if (ret) { ret =check_empty_sectors (blk_over, sector_num, nb_sectors, filename_over, buf1, quiet);
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 038/100] block: Make bdrv_is_allocated() byte-based
In reply to Kevin WolfFrom: Eric Blake <[email protected]>
We are gradually moving away from sector-based interfaces, towards byte-based. In the common case, allocation is unlikely to ever use values that are not naturally sector-aligned, but it is possible that byte-based values will let us be more precise about allocation at the end of an unaligned file that can do byte-based access.
Changing the signature of the function to use int64_t *pnum ensures that the compiler enforces that all callers are updated. For now, the io.c layer still assert()s that all callers are sector-aligned on input and that *pnum is sector-aligned on return to the caller, but that can be relaxed when a later patch implements byte-based block status. Therefore, this code adds usages like DIV_ROUND_UP(,BDRV_SECTOR_SIZE) to callers that still want aligned values, where the call might reasonbly give non-aligned results in the future; on the other hand, no rounding is needed for callers that should just continue to work with byte alignment.
For the most part this patch is just the addition of scaling at the callers followed by inverse scaling at bdrv_is_allocated(). But some code, particularly bdrv_commit(), gets a lot simpler because it no longer has to mess with sectors; also, it is now possible to pass NULL if the caller does not care how much of the image is allocated beyond the initial offset. Leave comments where we can further simplify once a later patch eliminates the need for sector-aligned requests through bdrv_is_allocated().
For ease of review, bdrv_is_allocated_above() will be tackled separately.
--- block/backup.c | 17 ++++--------- block/commit.c | 21 +++++++--------- block/io.c | 54 ++++++++++++++++++++++++++------------- block/stream.c | 7 ++++-- block/vvfat.c | 34 ++++++++++++++----------- include/block/block.h | 4 +-- migration/block.c | 16 +++++++----- qemu-img.c | 8 +++++- qemu-io-cmds.c | 70 +++++++++++++++++++++++---------------------------- 9 files changed, 126 insertions(+), 105 deletions(-)
block/backup.c +5 -12
@@ -47,12 +47,6 @@ typedef struct BackupBlockJob { QLIST_HEAD(, CowRequest) inflight_reqs; } BackupBlockJob; -/* Size of a cluster in sectors, instead of bytes. */ -static inline int64_t cluster_size_sectors (BackupBlockJob *job) -{ -return job->cluster_size /BDRV_SECTOR_SIZE ; -} -/* See if in-flight requests overlap and wait for them to complete */ static void coroutine_fn wait_for_overlapping_requests(BackupBlockJob *job, int64_t start,
@@ -433,7 +427,6 @@ static void coroutine_fn backup_run(void *opaque)BackupCompleteData *data;BlockDriverState *bs =blk_bs (job->common.blk);int64_t offset; -int64_t sectors_per_cluster =cluster_size_sectors (job);int ret =0 ;QLIST_INIT (&job->inflight_reqs);
@@ -465,12 +458,13 @@ static void coroutine_fn backup_run(void *opaque) }if (job->sync_mode ==MIRROR_SYNC_MODE_TOP ) { -int i, n; +int i; +int64_t n;/* Check to see if these blocks are already in the * backing file. */ -for (i =0 ; i < sectors_per_cluster;) { +for (i =0 ; i < job->cluster_size;) {/* bdrv_is_allocated() only returns true/false based * on the first set of sectors it comes across that * are are all in the same state.
@@ -478,9 +472,8 @@ static void coroutine_fn backup_run(void *opaque)* backup cluster length. We end up copying more than * needed but at some point that is always the case. */ alloced = -bdrv_is_allocated (bs, - (offset >>BDRV_SECTOR_BITS ) + i, - sectors_per_cluster - i, &n); +bdrv_is_allocated (bs, offset + i, + job->cluster_size - i, &n); i += n;if (alloced || n ==0 ) {
block/commit.c +9 -12
@@ -443,7 +443,7 @@ fail: } -#define COMMIT_BUF_SECTORS 2048 +#define COMMIT_BUF_SIZE (2048 * BDRV_SECTOR_SIZE)/* commit COW file into the raw image */ int bdrv_commit (BlockDriverState *bs)
@@ -452,8 +452,9 @@ int bdrv_commit(BlockDriverState *bs)BlockDriverState *backing_file_bs =NULL ;BlockDriverState *commit_top_bs =NULL ;BlockDriver *drv = bs->drv; -int64_t sector, total_sectors, length, backing_length; -int n, ro, open_flags; +int64_t offset, length, backing_length; +int ro, open_flags; +int64_t n;int ret =0 ;uint8_t *buf =NULL ;Error *local_err =NULL ;
@@ -531,30 +532,26 @@ int bdrv_commit(BlockDriverState *bs) } } - total_sectors = length >>BDRV_SECTOR_BITS ; -/* blk_try_blockalign() for src will choose an alignment that works for * backing as well, so no need to compare the alignment manually. */ - buf =blk_try_blockalign (src,COMMIT_BUF_SECTORS *BDRV_SECTOR_SIZE ); + buf =blk_try_blockalign (src,COMMIT_BUF_SIZE );if (buf ==NULL ) { ret = -ENOMEM ; goto ro_cleanup; } -for (sector =0 ; sector < total_sectors; sector += n) { - ret =bdrv_is_allocated (bs, sector,COMMIT_BUF_SECTORS , &n); +for (offset =0 ; offset < length; offset += n) { + ret =bdrv_is_allocated (bs, offset,COMMIT_BUF_SIZE , &n);if (ret <0 ) { goto ro_cleanup; }if (ret) { - ret =blk_pread (src, sector *BDRV_SECTOR_SIZE , buf, - n *BDRV_SECTOR_SIZE ); + ret =blk_pread (src, offset, buf, n);if (ret <0 ) { goto ro_cleanup; } - ret =blk_pwrite (backing, sector *BDRV_SECTOR_SIZE , buf, - n *BDRV_SECTOR_SIZE ,0 ); + ret =blk_pwrite (backing, offset, buf, n,0 );if (ret <0 ) { goto ro_cleanup; }
block/io.c +36 -18
98 lines not on this page · raw message
block/stream.c +5 -2
@@ -137,6 +137,7 @@ static void coroutine_fn stream_run(void *opaque)for ( ; offset < s->common.len; offset += n *BDRV_SECTOR_SIZE ) {bool copy; +int64_t count =0 ;/* Note that even when no rate limit is applied we need to yield * with no pending I/O here so that bdrv_drain_all() returns.
@@ -148,8 +149,10 @@ static void coroutine_fn stream_run(void *opaque) copy = false; - ret =bdrv_is_allocated (bs, offset /BDRV_SECTOR_SIZE , -STREAM_BUFFER_SIZE /BDRV_SECTOR_SIZE , &n); + ret =bdrv_is_allocated (bs, offset,STREAM_BUFFER_SIZE , &count); +/* TODO relax this once bdrv_is_allocated does not enforce sectors */ +assert (QEMU_IS_ALIGNED (count,BDRV_SECTOR_SIZE )); + n = count >>BDRV_SECTOR_BITS ;if (ret ==1 ) {/* Allocated in the top, no need to copy. */ }else if (ret >=0 ) {
block/vvfat.c +20 -14
@@ -1482,24 +1482,27 @@ static int vvfat_read(BlockDriverState *bs, int64_t sector_num,if (sector_num >= bs->total_sectors)return -1 ;if (s->qcow) { -int n; +int64_t n;int ret; - ret =bdrv_is_allocated (s->qcow->bs, sector_num, - nb_sectors - i, &n); + ret =bdrv_is_allocated (s->qcow->bs, sector_num *BDRV_SECTOR_SIZE , + (nb_sectors - i) *BDRV_SECTOR_SIZE , &n);if (ret <0 ) {return ret; }if (ret) { -DLOG (fprintf (stderr,"sectors %d+%d allocated\n" , - (int )sector_num, n)); -if (bdrv_read (s->qcow, sector_num, buf + i *0x200 , n)) { +DLOG (fprintf (stderr,"sectors %" PRId64"+%" PRId64 +" allocated\n" , sector_num, + n >>BDRV_SECTOR_BITS )); +if (bdrv_read (s->qcow, sector_num, buf + i *0x200 , + n >>BDRV_SECTOR_BITS )) {return -1 ; } - i += n -1 ; - sector_num += n -1 ; + i += (n >>BDRV_SECTOR_BITS ) -1 ; + sector_num += (n >>BDRV_SECTOR_BITS ) -1 ;continue ; } -DLOG (fprintf (stderr,"sector %d not allocated\n" , (int )sector_num)); +DLOG (fprintf (stderr,"sector %" PRId64" not allocated\n" , + sector_num)); }if (sector_num < s->offset_to_root_dir) {if (sector_num < s->offset_to_fat) {
@@ -1779,7 +1782,7 @@ static inline bool cluster_was_modified(BDRVVVFATState *s, uint32_t cluster_num) {int was_modified =0 ; -int i, dummy; +int i;if (s->qcow ==NULL ) {return 0 ;
@@ -1787,8 +1790,9 @@ static inline bool cluster_was_modified(BDRVVVFATState *s,for (i =0 ; !was_modified && i < s->sectors_per_cluster; i++) { was_modified =bdrv_is_allocated (s->qcow->bs, -cluster2sector (s, cluster_num) + i, -1 , &dummy); + (cluster2sector (s, cluster_num) + + i) *BDRV_SECTOR_SIZE , +BDRV_SECTOR_SIZE ,NULL ); }/*
@@ -1935,7 +1939,7 @@ static uint32_t get_cluster_count_for_direntry(BDRVVVFATState* s, }if (copy_it) { -int i, dummy; +int i;/* * This is horribly inefficient, but that is okay, since * it is rarely executed, if at all.
@@ -1946,7 +1950,9 @@ static uint32_t get_cluster_count_for_direntry(BDRVVVFATState* s,for (i =0 ; i < s->sectors_per_cluster; i++) {int res; - res =bdrv_is_allocated (s->qcow->bs, offset + i,1 , &dummy); + res =bdrv_is_allocated (s->qcow->bs, + (offset + i) *BDRV_SECTOR_SIZE , +BDRV_SECTOR_SIZE ,NULL );if (res <0 ) {return -1 ; }
include/block/block.h +2 -2
@@ -427,8 +427,8 @@ int64_t bdrv_get_block_status_above(BlockDriverState *bs,int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file); -int bdrv_is_allocated (BlockDriverState *bs,int64_t sector_num,int nb_sectors, -int *pnum); +int bdrv_is_allocated (BlockDriverState *bs,int64_t offset,int64_t bytes, +int64_t *pnum);int bdrv_is_allocated_above (BlockDriverState *top,BlockDriverState *base,int64_t sector_num,int nb_sectors,int *pnum);
migration/block.c +10 -6
@@ -34,7 +34,7 @@#define BLK_MIG_FLAG_PROGRESS 0x04#define BLK_MIG_FLAG_ZERO_BLOCK 0x08 -#define MAX_IS_ALLOCATED_SEARCH 65536 +#define MAX_IS_ALLOCATED_SEARCH (65536 * BDRV_SECTOR_SIZE)#define MAX_INFLIGHT_IO 512
@@ -267,16 +267,20 @@ static int mig_save_device_bulk(QEMUFile *f, BlkMigDevState *bmds)BlockBackend *bb = bmds->blk;BlkMigBlock *blk;int nr_sectors; +int64_t count;if (bmds->shared_base) {qemu_mutex_lock_iothread ();aio_context_acquire (blk_get_aio_context (bb)); -/* Skip unallocated sectors; intentionally treats failure as -* an allocated sector */ +/* Skip unallocated sectors; intentionally treats failure or +* partial sector as an allocated sector */ while (cur_sector < total_sectors && - !bdrv_is_allocated (blk_bs (bb), cur_sector, -MAX_IS_ALLOCATED_SEARCH , &nr_sectors)) { - cur_sector += nr_sectors; + !bdrv_is_allocated (blk_bs (bb), cur_sector *BDRV_SECTOR_SIZE , +MAX_IS_ALLOCATED_SEARCH , &count)) { +if (count <BDRV_SECTOR_SIZE ) { +break ; + } + cur_sector += count >>BDRV_SECTOR_BITS ; }aio_context_release (blk_get_aio_context (bb));qemu_mutex_unlock_iothread ();
qemu-img.c +7 -1
@@ -3258,6 +3258,7 @@ static int img_rebase(int argc, char **argv)int64_t new_backing_num_sectors =0 ;uint64_t sector;int n; +int64_t count;float local_progress =0 ; buf_old =blk_blockalign (blk,IO_BUF_SIZE );
@@ -3305,12 +3306,17 @@ static int img_rebase(int argc, char **argv) }/* If the cluster is allocated, we don't need to take action */ - ret =bdrv_is_allocated (bs, sector, n, &n); + ret =bdrv_is_allocated (bs, sector <<BDRV_SECTOR_BITS , + n <<BDRV_SECTOR_BITS , &count);if (ret <0 ) {error_report ("error while reading image metadata: %s" ,strerror (-ret)); goto out; } +/* TODO relax this once bdrv_is_allocated does not enforce +* sector alignment */ +assert (QEMU_IS_ALIGNED (count,BDRV_SECTOR_SIZE )); + n = count >>BDRV_SECTOR_BITS ;if (ret) {continue ; }
qemu-io-cmds.c +32 -38
142 lines not on this page · raw message
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 044/100] qcow: require image size to be > 1 for new images
In reply to Kevin WolfFrom: "Daniel P. Berrange" <[email protected]>
The qcow driver refuses to open images which are less than 2 bytes in size, but will happily create such images. Add a check in the create path to avoid this discrepancy.
Message-id: [email protected]
--- block/qcow.c | 6 ++++++ 1 file changed, 6 insertions(+)
block/qcow.c +6 -0
@@ -811,6 +811,12 @@ static int qcow_create(const char *filename, QemuOpts *opts, Error **errp)/* Read out options */ total_size =ROUND_UP (qemu_opt_get_size_del (opts,BLOCK_OPT_SIZE ,0 ),BDRV_SECTOR_SIZE ); +if (total_size ==0 ) { +error_setg (errp,"Image size is too small, cannot be zero length" ); + ret = -EINVAL ; + goto cleanup; + } + backing_file =qemu_opt_get_del (opts,BLOCK_OPT_BACKING_FILE );if (qemu_opt_get_bool_del (opts,BLOCK_OPT_ENCRYPT , false)) { flags |=BLOCK_FLAG_ENCRYPT ;
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 042/100] block: add ability to set a prefix for opt names
In reply to Kevin WolfFrom: "Daniel P. Berrange" <[email protected]>
When integrating the crypto support with qcow/qcow2, we don't want to use the bare LUKS option names "hash-alg", "key-secret", etc. We need to namespace them to match the nested QAPI schema.
e.g. "encrypt.hash-alg", "encrypt.key-secret"
so that they don't clash with any general qcow options at a later date.
Message-id: [email protected]
--- block/crypto.c | 16 ++++++++-------- block/crypto.h | 40 ++++++++++++++++++++-------------------- 2 files changed, 28 insertions(+), 28 deletions(-)
block/crypto.c +8 -8
@@ -129,7 +129,7 @@ static QemuOptsList block_crypto_runtime_opts_luks = { .name = "crypto", .head = QTAILQ_HEAD_INITIALIZER(block_crypto_runtime_opts_luks.head), .desc = { - BLOCK_CRYPTO_OPT_DEF_LUKS_KEY_SECRET, + BLOCK_CRYPTO_OPT_DEF_LUKS_KEY_SECRET(""), {/* end of list */ } }, };
@@ -144,13 +144,13 @@ static QemuOptsList block_crypto_create_opts_luks = { .type = QEMU_OPT_SIZE, .help = "Virtual disk size" }, - BLOCK_CRYPTO_OPT_DEF_LUKS_KEY_SECRET, -BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG , -BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE , -BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG , -BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG , -BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG , - BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME, + BLOCK_CRYPTO_OPT_DEF_LUKS_KEY_SECRET(""), + BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG(""), + BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE(""), + BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG(""), + BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG(""), + BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG(""), + BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME(""), {/* end of list */ } }, };
block/crypto.h +20 -20
@@ -29,51 +29,51 @@#define BLOCK_CRYPTO_OPT_LUKS_HASH_ALG "hash-alg"#define BLOCK_CRYPTO_OPT_LUKS_ITER_TIME "iter-time" -#define BLOCK_CRYPTO_OPT_DEF_LUKS_KEY_SECRET \ +#define BLOCK_CRYPTO_OPT_DEF_LUKS_KEY_SECRET (prefix) \ { \ - .name = BLOCK_CRYPTO_OPT_LUKS_KEY_SECRET, \ + .name = prefix BLOCK_CRYPTO_OPT_LUKS_KEY_SECRET, \ .type = QEMU_OPT_STRING, \ .help = "ID of the secret that provides the keyslot passphrase", \ } -#define BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG \ +#define BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG (prefix) \ { \ - .name = BLOCK_CRYPTO_OPT_LUKS_CIPHER_ALG, \ + .name = prefix BLOCK_CRYPTO_OPT_LUKS_CIPHER_ALG, \ .type = QEMU_OPT_STRING, \ .help = "Name of encryption cipher algorithm", \ } -#define BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE \ - { \ - .name = BLOCK_CRYPTO_OPT_LUKS_CIPHER_MODE, \ - .type = QEMU_OPT_STRING, \ - .help = "Name of encryption cipher mode", \ +#define BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE (prefix) \ + { \ + .name = prefix BLOCK_CRYPTO_OPT_LUKS_CIPHER_MODE, \ + .type = QEMU_OPT_STRING, \ + .help = "Name of encryption cipher mode", \ } -#define BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG \ - { \ - .name = BLOCK_CRYPTO_OPT_LUKS_IVGEN_ALG, \ - .type = QEMU_OPT_STRING, \ - .help = "Name of IV generator algorithm", \ +#define BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG (prefix) \ + { \ + .name = prefix BLOCK_CRYPTO_OPT_LUKS_IVGEN_ALG, \ + .type = QEMU_OPT_STRING, \ + .help = "Name of IV generator algorithm", \ } -#define BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG \ +#define BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG (prefix) \ { \ - .name = BLOCK_CRYPTO_OPT_LUKS_IVGEN_HASH_ALG, \ + .name = prefix BLOCK_CRYPTO_OPT_LUKS_IVGEN_HASH_ALG, \ .type = QEMU_OPT_STRING, \ .help = "Name of IV generator hash algorithm", \ } -#define BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG \ +#define BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG (prefix) \ { \ - .name = BLOCK_CRYPTO_OPT_LUKS_HASH_ALG, \ + .name = prefix BLOCK_CRYPTO_OPT_LUKS_HASH_ALG, \ .type = QEMU_OPT_STRING, \ .help = "Name of encryption hash algorithm", \ } -#define BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME \ +#define BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME (prefix) \ { \ - .name = BLOCK_CRYPTO_OPT_LUKS_ITER_TIME, \ + .name = prefix BLOCK_CRYPTO_OPT_LUKS_ITER_TIME, \ .type = QEMU_OPT_NUMBER, \ .help = "Time to spend in PBKDF in milliseconds", \ }
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 043/100] qcow: document another weakness of qcow AES encryption
In reply to Kevin WolfFrom: "Daniel P. Berrange" <[email protected]>
Document that use of guest virtual sector numbers as the basis for the initialization vectors is a potential weakness, when combined with internal snapshots or multiple images using the same passphrase. This fixes the formatting of the itemized list too.
Message-id: [email protected]
--- qemu-img.texi | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-)
qemu-img.texi +16 -3
@@ -567,16 +567,29 @@ The use of encryption in qcow and qcow2 images is considered to be flawed by modern cryptography standards, suffering from a number of design problems: @itemize @minus -@item The AES-CBC cipher is used with predictable initialization vectors based +@item +The AES-CBC cipher is used with predictable initialization vectors based on the sector number. This makes it vulnerable to chosen plaintext attacks which can reveal the existence of encrypted data. -@item The user passphrase is directly used as the encryption key. A poorly +@item +The user passphrase is directly used as the encryption key. A poorly chosen or short passphrase will compromise the security of the encryption. -@item In the event of the passphrase being compromised there is no way to +@item +In the event of the passphrase being compromised there is no way to change the passphrase to protect data in any qcow images. The files must be cloned, using a different encryption passphrase in the new file. The original file must then be securely erased using a program like shred, though even this is ineffective with many modern storage technologies. +@item +Initialization vectors used to encrypt sectors are based on the +guest virtual sector number, instead of the host physical sector. When +a disk image has multiple internal snapshots this means that data in +multiple physical sectors is encrypted with the same initialization +vector. With the CBC mode, this opens the possibility of watermarking +attacks if the attack can collect multiple sectors encrypted with the +same IV and some predictable data. Having multiple qcow2 images with +the same passphrase also exposes this weakness since the passphrase +is directly used as the key. @end itemize Use of qcow / qcow2 encryption is thus strongly discouraged. Users are
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 045/100] iotests: skip 042 with qcow which dosn't support zero sized images
In reply to Kevin WolfFrom: "Daniel P. Berrange" <[email protected]>
Test 042 is designed to verify operation with zero sized images. Such images are not supported with qcow (v1), so this test has always failed.
Message-id: [email protected]
--- tests/qemu-iotests/042 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
tests/qemu-iotests/042 +1 -1
@@ -37,7 +37,7 @@ trap "_cleanup; exit \$status" 0 1 2 3 15 . ./common.rc . ./common.filter -_supported_fmt qcow2 qcow qed +_supported_fmt qcow2 qed _supported_proto file _supported_os Linux
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 041/100] block: expose crypto option names / defs to other drivers
In reply to Kevin WolfFrom: "Daniel P. Berrange" <[email protected]>
The block/crypto.c defines a set of QemuOpts that provide parameters for encryption. This will also be needed by the qcow/qcow2 integration, so expose the relevant pieces in a new block/crypto.h header. Some helper methods taking QemuOpts are changed to take QDict to simplify usage in other places.
Message-id: [email protected]
--- block/crypto.c | 82 +++++++++++++++++----------------------------------- block/crypto.h | 91 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 117 insertions(+), 56 deletions(-) create mode 100644 block/crypto.h
block/crypto.c +26 -56
@@ -24,16 +24,10 @@#include "sysemu/block-backend.h" #include "crypto/block.h" #include "qapi/opts-visitor.h" +#include "qapi/qobject-input-visitor.h" #include "qapi-visit.h" #include "qapi/error.h" - -#define BLOCK_CRYPTO_OPT_LUKS_KEY_SECRET "key-secret" -#define BLOCK_CRYPTO_OPT_LUKS_CIPHER_ALG "cipher-alg" -#define BLOCK_CRYPTO_OPT_LUKS_CIPHER_MODE "cipher-mode" -#define BLOCK_CRYPTO_OPT_LUKS_IVGEN_ALG "ivgen-alg" -#define BLOCK_CRYPTO_OPT_LUKS_IVGEN_HASH_ALG "ivgen-hash-alg" -#define BLOCK_CRYPTO_OPT_LUKS_HASH_ALG "hash-alg" -#define BLOCK_CRYPTO_OPT_LUKS_ITER_TIME "iter-time" +#include "block/crypto.h" typedef struct BlockCrypto BlockCrypto ;
@@ -135,11 +129,7 @@ static QemuOptsList block_crypto_runtime_opts_luks = { .name = "crypto", .head = QTAILQ_HEAD_INITIALIZER(block_crypto_runtime_opts_luks.head), .desc = { - { - .name = BLOCK_CRYPTO_OPT_LUKS_KEY_SECRET, - .type = QEMU_OPT_STRING, - .help = "ID of the secret that provides the encryption key", - }, + BLOCK_CRYPTO_OPT_DEF_LUKS_KEY_SECRET, {/* end of list */ } }, };
@@ -154,49 +144,21 @@ static QemuOptsList block_crypto_create_opts_luks = { .type = QEMU_OPT_SIZE, .help = "Virtual disk size" }, - { - .name = BLOCK_CRYPTO_OPT_LUKS_KEY_SECRET, - .type = QEMU_OPT_STRING, - .help = "ID of the secret that provides the encryption key", - }, - { - .name = BLOCK_CRYPTO_OPT_LUKS_CIPHER_ALG, - .type = QEMU_OPT_STRING, - .help = "Name of encryption cipher algorithm", - }, - { - .name = BLOCK_CRYPTO_OPT_LUKS_CIPHER_MODE, - .type = QEMU_OPT_STRING, - .help = "Name of encryption cipher mode", - }, - { - .name = BLOCK_CRYPTO_OPT_LUKS_IVGEN_ALG, - .type = QEMU_OPT_STRING, - .help = "Name of IV generator algorithm", - }, - { - .name = BLOCK_CRYPTO_OPT_LUKS_IVGEN_HASH_ALG, - .type = QEMU_OPT_STRING, - .help = "Name of IV generator hash algorithm", - }, - { - .name = BLOCK_CRYPTO_OPT_LUKS_HASH_ALG, - .type = QEMU_OPT_STRING, - .help = "Name of encryption hash algorithm", - }, - { - .name = BLOCK_CRYPTO_OPT_LUKS_ITER_TIME, - .type = QEMU_OPT_NUMBER, - .help = "Time to spend in PBKDF in milliseconds", - }, + BLOCK_CRYPTO_OPT_DEF_LUKS_KEY_SECRET, +BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG , +BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE , +BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG , +BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG , +BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG , + BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME, { /* end of list */ } }, }; -static QCryptoBlockOpenOptions * +QCryptoBlockOpenOptions *block_crypto_open_opts_init (QCryptoBlockFormat format, - QemuOpts *opts, +QDict *opts,Error **errp) {Visitor *v;
@@ -206,7 +168,7 @@ block_crypto_open_opts_init(QCryptoBlockFormat format, ret =g_new0 (QCryptoBlockOpenOptions,1 ); ret->format = format; - v =opts_visitor_new (opts); + v =qobject_input_visitor_new_keyval (QOBJECT (opts));visit_start_struct (v,NULL ,NULL ,0 , &local_err);if (local_err) {
@@ -240,9 +202,9 @@ block_crypto_open_opts_init(QCryptoBlockFormat format, } -static QCryptoBlockCreateOptions * +QCryptoBlockCreateOptions *block_crypto_create_opts_init (QCryptoBlockFormat format, -QemuOpts *opts, +QDict *opts,Error **errp) {Visitor *v;
@@ -252,7 +214,7 @@ block_crypto_create_opts_init(QCryptoBlockFormat format, ret =g_new0 (QCryptoBlockCreateOptions,1 ); ret->format = format; - v =opts_visitor_new (opts); + v =qobject_input_visitor_new_keyval (QOBJECT (opts));visit_start_struct (v,NULL ,NULL ,0 , &local_err);if (local_err) {
@@ -299,6 +261,7 @@ static int block_crypto_open_generic(QCryptoBlockFormat format,int ret = -EINVAL ;QCryptoBlockOpenOptions *open_opts =NULL ;unsigned int cflags =0 ; +QDict *cryptoopts =NULL ; bs->file =bdrv_open_child (NULL , options,"file" , bs, &child_file, false, errp);
@@ -313,7 +276,9 @@ static int block_crypto_open_generic(QCryptoBlockFormat format, goto cleanup; } - open_opts =block_crypto_open_opts_init (format, opts, errp); + cryptoopts =qemu_opts_to_qdict (opts,NULL ); + + open_opts =block_crypto_open_opts_init (format, cryptoopts, errp);if (!open_opts) { goto cleanup; }
@@ -337,6 +302,7 @@ static int block_crypto_open_generic(QCryptoBlockFormat format, ret =0 ; cleanup: +QDECREF (cryptoopts);qapi_free_QCryptoBlockOpenOptions (open_opts);return ret; }
@@ -356,8 +322,11 @@ static int block_crypto_create_generic(QCryptoBlockFormat format, .opts = opts, .filename = filename, }; +QDict *cryptoopts; + + cryptoopts =qemu_opts_to_qdict (opts,NULL ); - create_opts =block_crypto_create_opts_init (format, opts, errp); + create_opts =block_crypto_create_opts_init (format, cryptoopts, errp);if (!create_opts) {return -1 ; }
@@ -375,6 +344,7 @@ static int block_crypto_create_generic(QCryptoBlockFormat format, ret =0 ; cleanup: +QDECREF (cryptoopts);qcrypto_block_free (crypto);blk_unref (data.blk);qapi_free_QCryptoBlockCreateOptions (create_opts);
block/crypto.h new file +91 -0
91 lines not on this page · raw message
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 046/100] iotests: skip 048 with qcow which doesn't support resize
In reply to Kevin WolfFrom: "Daniel P. Berrange" <[email protected]>
Test 048 is designed to verify data preservation during an image resize. The qcow (v1) format impl has never supported resize so always fails.
Message-id: [email protected]
--- tests/qemu-iotests/048 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
tests/qemu-iotests/048 +1 -1
@@ -46,7 +46,7 @@ _compare() . ./common.filter . ./common.pattern -_supported_fmt raw qcow qcow2 qed luks +_supported_fmt raw qcow2 qed luks _supported_proto file _supported_os Linux
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 052/100] qcow2: extend specification to cover LUKS encryption
In reply to Kevin WolfFrom: "Daniel P. Berrange" <[email protected]>
Update the qcow2 specification to describe how the LUKS header is placed inside a qcow2 file, when using LUKS encryption for the qcow2 payload instead of the legacy AES-CBC encryption
Message-id: [email protected]
--- docs/interop/qcow2.txt | 103 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+)
docs/interop/qcow2.txt +103 -0
@@ -45,6 +45,7 @@ The first cluster of a qcow2 image contains the file header: 32 - 35: crypt_method 0 for no encryption 1 for AES encryption + 2 for LUKS encryption 36 - 39: l1_size Number of entries in the active L1 table
@@ -135,6 +136,7 @@ be stored. Each extension has a structure like the following: 0xE2792ACA - Backing file format name 0x6803f857 - Feature name table 0x23852875 - Bitmaps extension + 0x0537be77 - Full disk encryption header pointer other - Unknown header extension, can be safely ignored
@@ -207,6 +209,107 @@ The fields of the bitmaps extension are: Offset into the image file at which the bitmap directory starts. Must be aligned to a cluster boundary. +== Full disk encryption header pointer == + +The full disk encryption header must be present if, and only if, the +'crypt_method' header requires metadata. Currently this is only true +of the 'LUKS' crypt method. The header extension must be absent for +other methods. + +This header provides the offset at which the crypt method can store +its additional data, as well as the length of such data. + + Byte 0 - 7: Offset into the image file at which the encryption + header starts in bytes. Must be aligned to a cluster + boundary. + Byte 8 - 15: Length of the written encryption header in bytes. + Note actual space allocated in the qcow2 file may + be larger than this value, since it will be rounded + to the nearest multiple of the cluster size. Any + unused bytes in the allocated space will be initialized + to 0. + +For the LUKS crypt method, the encryption header works as follows. + +The first 592 bytes of the header clusters will contain the LUKS +partition header. This is then followed by the key material data areas. +The size of the key material data areas is determined by the number of +stripes in the key slot and key size. Refer to the LUKS format +specification ('docs/on-disk-format.pdf' in the cryptsetup source +package) for details of the LUKS partition header format. + +In the LUKS partition header, the "payload-offset" field will be +calculated as normal for the LUKS spec. ie the size of the LUKS +header, plus key material regions, plus padding, relative to the +start of the LUKS header. This offset value is not required to be +qcow2 cluster aligned. Its value is currently never used in the +context of qcow2, since the qcow2 file format itself defines where +the real payload offset is, but none the less a valid payload offset +should always be present. + +In the LUKS key slots header, the "key-material-offset" is relative +to the start of the LUKS header clusters in the qcow2 container, +not the start of the qcow2 file. + +Logically the layout looks like + + +-----------------------------+ + | QCow2 header | + | QCow2 header extension X | + | QCow2 header extension FDE | + | QCow2 header extension ... | + | QCow2 header extension Z | + +-----------------------------+ + | ....other QCow2 tables.... | + . . + . . + +-----------------------------+ + | +-------------------------+ | + | | LUKS partition header | | + | +-------------------------+ | + | | LUKS key material 1 | | + | +-------------------------+ | + | | LUKS key material 2 | | + | +-------------------------+ | + | | LUKS key material ... | | + | +-------------------------+ | + | | LUKS key material 8 | | + | +-------------------------+ | + +-----------------------------+ + | QCow2 cluster payload | + . . + . . + . . + | | + +-----------------------------+ + +== Data encryption == + +When an encryption method is requested in the header, the image payload +data must be encrypted/decrypted on every write/read. The image headers +and metadata are never encrypted. + +The algorithms used for encryption vary depending on the method + + - AES: + + The AES cipher, in CBC mode, with 256 bit keys. + + Initialization vectors generated using plain64 method, with + the virtual disk sector as the input tweak. + + This format is no longer supported in QEMU system emulators, due + to a number of design flaws affecting its security. It is only + supported in the command line tools for the sake of back compatibility + and data liberation. + + - LUKS: + + The algorithms are specified in the LUKS header. + + Initialization vectors generated using the method specified + in the LUKS header, with the physical disk sector as the + input tweak. == Host cluster management ==
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 049/100] qcow: convert QCow to use QCryptoBlock for encryption
In reply to Kevin WolfFrom: "Daniel P. Berrange" <[email protected]>
This converts the qcow driver to make use of the QCryptoBlock APIs for encrypting image content. This is only wired up to permit use of the legacy QCow encryption format. Users who wish to have the strong LUKS format should switch to qcow2 instead.
With this change it is now required to use the QCryptoSecret object for providing passwords, instead of the current block password APIs / interactive prompting.
$QEMU \
-object secret,id=sec0,file=/home/berrange/encrypted.pw \
-drive file=/home/berrange/encrypted.qcow,encrypt.format=aes,\
encrypt.key-secret=sec0Though note that running QEMU system emulators with the AES encryption is no longer supported, so while the above syntax is valid, QEMU will refuse to actually run the VM in this particular example.
Likewise when creating images with the legacy AES-CBC format
qemu-img create -f qcow \
--object secret,id=sec0,file=/home/berrange/encrypted.pw \
-o encrypt.format=aes,encrypt.key-secret=sec0 \
/home/berrange/encrypted.qcow 64MMessage-id: [email protected]
--- block/crypto.c | 10 +++ block/crypto.h | 20 ++++-- block/qcow.c | 198 +++++++++++++++++++++++++-------------------------- qapi/block-core.json | 38 +++++++++- 4 files changed, 158 insertions(+), 108 deletions(-)
block/crypto.c +10 -0
@@ -181,6 +181,11 @@ block_crypto_open_opts_init(QCryptoBlockFormat format, v, &ret->u.luks, &local_err);break ; +case Q_CRYPTO_BLOCK_FORMAT_QCOW : +visit_type_QCryptoBlockOptionsQCow_members ( + v, &ret->u.qcow, &local_err); +break ; +default :error_setg (&local_err,"Unsupported block format %d" , format);break ;
@@ -227,6 +232,11 @@ block_crypto_create_opts_init(QCryptoBlockFormat format, v, &ret->u.luks, &local_err);break ; +case Q_CRYPTO_BLOCK_FORMAT_QCOW : +visit_type_QCryptoBlockOptionsQCow_members ( + v, &ret->u.qcow, &local_err); +break ; +default :error_setg (&local_err,"Unsupported block format %d" , format);break ;
block/crypto.h +15 -5
@@ -21,6 +21,19 @@#ifndef BLOCK_CRYPTO_H__ #define BLOCK_CRYPTO_H__ +#define BLOCK_CRYPTO_OPT_DEF_KEY_SECRET (prefix, helpstr) \ + { \ + .name = prefix BLOCK_CRYPTO_OPT_QCOW_KEY_SECRET, \ + .type = QEMU_OPT_STRING, \ + .help = helpstr, \ + } + +#define BLOCK_CRYPTO_OPT_QCOW_KEY_SECRET "key-secret" + +#define BLOCK_CRYPTO_OPT_DEF_QCOW_KEY_SECRET (prefix) \ + BLOCK_CRYPTO_OPT_DEF_KEY_SECRET(prefix, \ + "ID of the secret that provides the AES encryption key") +#define BLOCK_CRYPTO_OPT_LUKS_KEY_SECRET "key-secret"#define BLOCK_CRYPTO_OPT_LUKS_CIPHER_ALG "cipher-alg"#define BLOCK_CRYPTO_OPT_LUKS_CIPHER_MODE "cipher-mode"
@@ -30,11 +43,8 @@#define BLOCK_CRYPTO_OPT_LUKS_ITER_TIME "iter-time"#define BLOCK_CRYPTO_OPT_DEF_LUKS_KEY_SECRET (prefix) \ - { \ - .name = prefix BLOCK_CRYPTO_OPT_LUKS_KEY_SECRET, \ - .type = QEMU_OPT_STRING, \ - .help = "ID of the secret that provides the keyslot passphrase", \ - } + BLOCK_CRYPTO_OPT_DEF_KEY_SECRET(prefix, \ + "ID of the secret that provides the keyslot passphrase")#define BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG (prefix) \ { \
block/qcow.c +96 -102
330 lines not on this page · raw message
qapi/block-core.json +37 -1
@@ -2282,6 +2282,42 @@ 'mode': 'Qcow2OverlapCheckMode' } } ## +# @BlockdevQcowEncryptionFormat: +# +# @aes: AES-CBC with plain64 initialization vectors +# +# Since: 2.10 +## +{ 'enum': 'BlockdevQcowEncryptionFormat', + 'data': [ 'aes' ] } + +## +# @BlockdevQcowEncryption: +# +# Since: 2.10 +## +{ 'union': 'BlockdevQcowEncryption', + 'base': { 'format': 'BlockdevQcowEncryptionFormat' }, + 'discriminator': 'format', + 'data': { 'aes': 'QCryptoBlockOptionsQCow' } } + +## +# @BlockdevOptionsQcow: +# +# Driver specific block device options for qcow. +# +# @encrypt: Image decryption options. Mandatory for +# encrypted images, except when doing a metadata-only +# probe of the image. +# +# Since: 2.10 +## +{ 'struct': 'BlockdevOptionsQcow', + 'base': 'BlockdevOptionsGenericCOWFormat', + 'data': { '*encrypt': 'BlockdevQcowEncryption' } } + + +## # @BlockdevOptionsQcow2: # # Driver specific block device options for qcow2.
@@ -2976,7 +3012,7 @@ 'null-co': 'BlockdevOptionsNull', 'parallels': 'BlockdevOptionsGenericFormat', 'qcow2': 'BlockdevOptionsQcow2', - 'qcow': 'BlockdevOptionsGenericCOWFormat', + 'qcow': 'BlockdevOptionsQcow', 'qed': 'BlockdevOptionsGenericCOWFormat', 'quorum': 'BlockdevOptionsQuorum', 'raw': 'BlockdevOptionsRaw',
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 050/100] qcow2: make qcow2_encrypt_sectors encrypt in place
In reply to Kevin WolfFrom: "Daniel P. Berrange" <[email protected]>
Instead of requiring separate input/output buffers for encrypting data, change qcow2_encrypt_sectors() to assume use of a single buffer, encrypting in place. The current callers all used the same buffer for input/output already.
Message-id: [email protected]
--- block/qcow2-cluster.c | 17 ++++++----------- block/qcow2.c | 4 ++-- block/qcow2.h | 3 +-- 3 files changed, 9 insertions(+), 15 deletions(-)
block/qcow2-cluster.c +6 -11
@@ -358,11 +358,9 @@ static int count_contiguous_clusters_unallocated(int nb_clusters, }/* The crypt function is compatible with the linux cryptoloop -algorithm for < 4 GB images. NOTE: out_buf == in_buf is -supported */ +algorithm for < 4 GB images. */ int qcow2_encrypt_sectors (BDRVQcow2State *s,int64_t sector_num, -uint8_t *out_buf,const uint8_t *in_buf, -int nb_sectors,bool enc, +uint8_t *buf,int nb_sectors,bool enc,Error **errp) {union {
@@ -382,14 +380,12 @@ int qcow2_encrypt_sectors(BDRVQcow2State *s, int64_t sector_num, }if (enc) { ret =qcrypto_cipher_encrypt (s->cipher, - in_buf, - out_buf, + buf, buf,512 , errp); }else { ret =qcrypto_cipher_decrypt (s->cipher, - in_buf, - out_buf, + buf, buf,512 , errp); }
@@ -397,8 +393,7 @@ int qcow2_encrypt_sectors(BDRVQcow2State *s, int64_t sector_num,return -1 ; } sector_num++; - in_buf +=512 ; - out_buf +=512 ; + buf +=512 ; }return 0 ; }
@@ -446,7 +441,7 @@ static bool coroutine_fn do_perform_cow_encrypt(BlockDriverState *bs,assert (s->cipher);assert ((offset_in_cluster & ~BDRV_SECTOR_MASK ) ==0 );assert ((bytes & ~BDRV_SECTOR_MASK ) ==0 ); -if (qcow2_encrypt_sectors (s, sector, buffer, buffer, +if (qcow2_encrypt_sectors (s, sector, buffer, bytes >>BDRV_SECTOR_BITS , true,NULL ) <0 ) {return false; }
block/qcow2.c +2 -2
@@ -1543,7 +1543,7 @@ static coroutine_fn int qcow2_co_preadv(BlockDriverState *bs, uint64_t offset,assert ((cur_bytes & (BDRV_SECTOR_SIZE -1 )) ==0 );Error *err =NULL ;if (qcow2_encrypt_sectors (s, offset >>BDRV_SECTOR_BITS , - cluster_data, cluster_data, + cluster_data, cur_bytes >>BDRV_SECTOR_BITS , false, &err) <0 ) {error_free (err);
@@ -1677,7 +1677,7 @@ static coroutine_fn int qcow2_co_pwritev(BlockDriverState *bs, uint64_t offset,qemu_iovec_to_buf (&hd_qiov,0 , cluster_data, hd_qiov.size);if (qcow2_encrypt_sectors (s, offset >>BDRV_SECTOR_BITS , - cluster_data, cluster_data, + cluster_data, cur_bytes >>BDRV_SECTOR_BITS , true, &err) <0 ) {error_free (err);
block/qcow2.h +1 -2
@@ -545,8 +545,7 @@ int qcow2_grow_l1_table(BlockDriverState *bs, uint64_t min_size,int qcow2_write_l1_entry (BlockDriverState *bs,int l1_index);int qcow2_decompress_cluster (BlockDriverState *bs,uint64_t cluster_offset);int qcow2_encrypt_sectors (BDRVQcow2State *s,int64_t sector_num, -uint8_t *out_buf,const uint8_t *in_buf, -int nb_sectors,bool enc,Error **errp); +uint8_t *buf,int nb_sectors,bool enc,Error **errp);int qcow2_get_cluster_offset (BlockDriverState *bs,uint64_t offset,unsigned int *bytes,uint64_t *cluster_offset);
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 055/100] iotests: enable tests 134 and 158 to work with qcow (v1)
In reply to Kevin WolfFrom: "Daniel P. Berrange" <[email protected]>
The 138 and 158 iotests exercise the legacy qcow2 aes encryption code path and they work fine with qcow v1 too.
Message-id: [email protected]
--- tests/qemu-iotests/134 | 2 +- tests/qemu-iotests/158 | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-)
tests/qemu-iotests/134 +1 -1
@@ -37,7 +37,7 @@ trap "_cleanup; exit \$status" 0 1 2 3 15 . ./common.rc . ./common.filter -_supported_fmt qcow2 +_supported_fmt qcow qcow2 _supported_proto generic _unsupported_proto vxhs _supported_os Linux
tests/qemu-iotests/158 +1 -1
@@ -37,7 +37,7 @@ trap "_cleanup; exit \$status" 0 1 2 3 15 . ./common.rc . ./common.filter -_supported_fmt qcow2 +_supported_fmt qcow qcow2 _supported_proto generic _unsupported_proto vxhs _supported_os Linux
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 048/100] qcow: make encrypt_sectors encrypt in place
In reply to Kevin WolfFrom: "Daniel P. Berrange" <[email protected]>
Instead of requiring separate input/output buffers for encrypting data, change encrypt_sectors() to assume use of a single buffer, encrypting in place. One current caller uses the same buffer for input/output already and the other two callers are easily converted to do so.
Message-id: [email protected]
--- block/qcow.c | 45 +++++++++++++++------------------------------ 1 file changed, 15 insertions(+), 30 deletions(-)
block/qcow.c +15 -30
@@ -322,11 +322,10 @@ static int qcow_set_key(BlockDriverState *bs, const char *key) }/* The crypt function is compatible with the linux cryptoloop -algorithm for < 4 GB images. NOTE: out_buf == in_buf is -supported */ +algorithm for < 4 GB images. */ static int encrypt_sectors (BDRVQcowState *s,int64_t sector_num, -uint8_t *out_buf,const uint8_t *in_buf, -int nb_sectors,bool enc,Error **errp) +uint8_t *buf,int nb_sectors,bool enc, +Error **errp) {union {uint64_t ll[2 ];
@@ -345,14 +344,12 @@ static int encrypt_sectors(BDRVQcowState *s, int64_t sector_num, }if (enc) { ret =qcrypto_cipher_encrypt (s->cipher, - in_buf, - out_buf, + buf, buf,512 , errp); }else { ret =qcrypto_cipher_decrypt (s->cipher, - in_buf, - out_buf, + buf, buf,512 , errp); }
@@ -360,8 +357,7 @@ static int encrypt_sectors(BDRVQcowState *s, int64_t sector_num,return -1 ; } sector_num++; - in_buf +=512 ; - out_buf +=512 ; + buf +=512 ; }return 0 ; }
@@ -481,13 +477,12 @@ static uint64_t get_cluster_offset(BlockDriverState *bs,uint64_t start_sect;assert (s->cipher); start_sect = (offset & ~(s->cluster_size -1 )) >>9 ; -memset (s->cluster_data +512 ,0x00 ,512 );for (i =0 ; i < s->cluster_sectors; i++) {if (i < n_start || i >= n_end) {Error *err =NULL ; +memset (s->cluster_data,0x00 ,512 );if (encrypt_sectors (s, start_sect + i, - s->cluster_data, - s->cluster_data +512 ,1 , + s->cluster_data,1 , true, &err) <0 ) {error_free (err); errno =EIO ;
@@ -665,7 +660,7 @@ static coroutine_fn int qcow_co_readv(BlockDriverState *bs, int64_t sector_num, }if (bs->encrypted) {assert (s->cipher); -if (encrypt_sectors (s, sector_num, buf, buf, +if (encrypt_sectors (s, sector_num, buf, n, false, &err) <0 ) { goto fail; }
@@ -700,9 +695,7 @@ static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num,BDRVQcowState *s = bs->opaque;int index_in_cluster;uint64_t cluster_offset; -const uint8_t *src_buf;int ret =0 , n; -uint8_t *cluster_data =NULL ;struct iovec hd_iov;QEMUIOVector hd_qiov;uint8_t *buf;
@@ -710,7 +703,9 @@ static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num, s->cluster_cache_offset =-1 ;/* disable compressed cache */ -if (qiov->niov >1 ) { +/* We must always copy the iov when encrypting, so we +* don't modify the original data buffer during encryption */ +if (bs->encrypted || qiov->niov >1 ) { buf = orig_buf =qemu_try_blockalign (bs, qiov->size);if (buf ==NULL ) {return -ENOMEM ;
@@ -740,21 +735,14 @@ static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num,if (bs->encrypted) {Error *err =NULL ;assert (s->cipher); -if (!cluster_data) { - cluster_data =g_malloc0 (s->cluster_size); - } -if (encrypt_sectors (s, sector_num, cluster_data, buf, - n, true, &err) <0 ) { +if (encrypt_sectors (s, sector_num, buf, n, true, &err) <0 ) {error_free (err); ret = -EIO ;break ; } - src_buf = cluster_data; - }else { - src_buf = buf; } - hd_iov.iov_base = (void *)src_buf; + hd_iov.iov_base = (void *)buf; hd_iov.iov_len = n *512 ;qemu_iovec_init_external (&hd_qiov, &hd_iov,1 );qemu_co_mutex_unlock (&s->lock);
@@ -773,10 +761,7 @@ static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num, }qemu_co_mutex_unlock (&s->lock); -if (qiov->niov >1 ) { -qemu_vfree (orig_buf); - } -g_free (cluster_data); +qemu_vfree (orig_buf);return ret; }
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 054/100] qcow2: add iotests to cover LUKS encryption support
In reply to Kevin WolfFrom: "Daniel P. Berrange" <[email protected]>
This extends the 087 iotest to cover LUKS encryption when doing blockdev-add.
Two further tests are added to validate read/write of LUKS encrypted images with a single file and with a backing file.
Message-id: [email protected]
--- tests/qemu-iotests/087 | 35 ++++++++++++++++++- tests/qemu-iotests/087.out | 14 +++++++- tests/qemu-iotests/188 | 76 ++++++++++++++++++++++++++++++++++++++++ tests/qemu-iotests/188.out | 18 ++++++++++ tests/qemu-iotests/189 | 86 ++++++++++++++++++++++++++++++++++++++++++++++ tests/qemu-iotests/189.out | 26 ++++++++++++++ tests/qemu-iotests/group | 2 ++ 7 files changed, 255 insertions(+), 2 deletions(-) create mode 100755 tests/qemu-iotests/188 create mode 100644 tests/qemu-iotests/188.out create mode 100755 tests/qemu-iotests/189 create mode 100644 tests/qemu-iotests/189.out
tests/qemu-iotests/087 +34 -1
@@ -119,7 +119,7 @@ run_qemu <<EOF EOF echo -echo === Encrypted image === +echo === Encrypted image QCow === echo _make_test_img --object secret,id=sec0,data=123456 -o encryption=on,encrypt.key-secret=sec0 $size
@@ -152,6 +152,39 @@ run_qemu <<EOF EOF echo +echo === Encrypted image LUKS === +echo + +_make_test_img --object secret,id=sec0,data=123456 -o encrypt.format=luks,encrypt.key-secret=sec0 $size +run_qemu <<EOF +{ "execute": "qmp_capabilities" } +{ "execute": "object-add", + "arguments": { + "qom-type": "secret", + "id": "sec0", + "props": { + "data": "123456" + } + } +} +{ "execute": "blockdev-add", + "arguments": { + "driver": "$IMGFMT", + "node-name": "disk", + "file": { + "driver": "file", + "filename": "$TEST_IMG" + }, + "encrypt": { + "format": "luks", + "key-secret": "sec0" + } + } + } +{ "execute": "quit" } +EOF + +echo echo === Missing driver === echo
tests/qemu-iotests/087.out +13 -1
@@ -32,7 +32,7 @@ QMP_VERSION {"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "SHUTDOWN", "data": {"guest": false}} -=== Encrypted image === +=== Encrypted image QCow === Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 encryption=on encrypt.key-secret=sec0 Testing:
@@ -44,6 +44,18 @@ QMP_VERSION {"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "SHUTDOWN", "data": {"guest": false}} +=== Encrypted image LUKS === + +Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 encrypt.format=luks encrypt.key-secret=sec0 +Testing: +QMP_VERSION +{"return": {}} +{"return": {}} +{"return": {}} +{"return": {}} +{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "SHUTDOWN", "data": {"guest": false}} + + === Missing driver === Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 encryption=on encrypt.key-secret=sec0
tests/qemu-iotests/188 new file +76 -0
76 lines not on this page · raw message
tests/qemu-iotests/188.out new file +18 -0
@@ -0,0 +1,18 @@ +QA output created by 188 +Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=16777216 encrypt.format=luks encrypt.key-secret=sec0 encrypt.iter-time=10 + +== reading whole image == +read 16777216/16777216 bytes at offset 0 +16 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec) + +== rewriting whole image == +wrote 16777216/16777216 bytes at offset 0 +16 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec) + +== verify pattern == +read 16777216/16777216 bytes at offset 0 +16 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec) + +== verify open failure with wrong password == +can't open: Invalid password, cannot unlock any keyslot +*** done
tests/qemu-iotests/189 new file +86 -0
86 lines not on this page · raw message
tests/qemu-iotests/189.out new file +26 -0
@@ -0,0 +1,26 @@ +QA output created by 189 +== create base == +Formatting 'TEST_DIR/t.IMGFMT.base', fmt=IMGFMT size=16777216 encrypt.format=luks encrypt.key-secret=sec0 encrypt.iter-time=10 + +== writing whole image == +wrote 16777216/16777216 bytes at offset 0 +16 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec) + +== verify pattern == +read 16777216/16777216 bytes at offset 0 +16 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec) +== create overlay == +Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=16777216 backing_file=TEST_DIR/t.IMGFMT.base encrypt.format=luks encrypt.key-secret=sec1 encrypt.iter-time=10 + +== writing part of a cluster == +wrote 1024/1024 bytes at offset 0 +1 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec) + +== verify pattern == +read 1024/1024 bytes at offset 0 +1 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec) + +== verify pattern == +read 64512/64512 bytes at offset 1024 +63 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec) +*** done
tests/qemu-iotests/group +2 -0
@@ -176,3 +176,5 @@ 182 rw auto quick 183 rw auto migration 185 rw auto +188 rw auto quick +189 rw auto quick
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 061/100] iotests: 181 does not work for all formats
In reply to Kevin WolfFrom: Max Reitz <[email protected]>
Test 181 only works for formats which support live migration (naturally, as it is a live migration test). Disable it for all formats which do not.
Message-id: [email protected]
--- tests/qemu-iotests/181 | 2 ++ 1 file changed, 2 insertions(+)
tests/qemu-iotests/181 +2 -0
@@ -43,6 +43,8 @@ trap "_cleanup; exit \$status" 0 1 2 3 15 . ./common.qemu _supported_fmt generic +# Formats that do not support live migration +_unsupported_fmt qcow vdi vhdx vmdk vpc vvfat _supported_proto generic _supported_os Linux
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 047/100] block: deprecate "encryption=on" in favor of "encrypt.format=aes"
In reply to Kevin WolfFrom: "Daniel P. Berrange" <[email protected]>
Historically the qcow & qcow2 image formats supported a property "encryption=on" to enable their built-in AES encryption. We'll soon be supporting LUKS for qcow2, so need a more general purpose way to enable encryption, with a choice of formats.
This introduces an "encrypt.format" option, which will later be joined by a number of other "encrypt.XXX" options. The use of a "encrypt." prefix instead of "encrypt-" is done to facilitate mapping to a nested QAPI schema at later date.
e.g. the preferred syntax is now
qemu-img create -f qcow2 -o encrypt.format=aes demo.qcow2
Message-id: [email protected]
--- block/qcow.c | 31 ++++++++++++--- block/qcow2.c | 34 ++++++++++++---- include/block/block_int.h | 2 +- qemu-img.c | 4 +- tests/qemu-iotests/049.out | 98 +++++++++++++++++++++++----------------------- tests/qemu-iotests/082.out | 95 ++++++++++++++++++++++++++++---------------- tests/qemu-iotests/085.out | 38 +++++++++--------- tests/qemu-iotests/144.out | 4 +- tests/qemu-iotests/185.out | 8 ++-- 9 files changed, 191 insertions(+), 123 deletions(-)
block/qcow.c +25 -6
@@ -803,10 +803,10 @@ static int qcow_create(const char *filename, QemuOpts *opts, Error **errp)uint8_t *tmp;int64_t total_size =0 ;char *backing_file =NULL ; -int flags =0 ;Error *local_err =NULL ;int ret;BlockBackend *qcow_blk; +const char *encryptfmt =NULL ;/* Read out options */ total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
@@ -818,8 +818,16 @@ static int qcow_create(const char *filename, QemuOpts *opts, Error **errp) } backing_file =qemu_opt_get_del (opts,BLOCK_OPT_BACKING_FILE ); -if (qemu_opt_get_bool_del (opts,BLOCK_OPT_ENCRYPT , false)) { - flags |=BLOCK_FLAG_ENCRYPT ; + encryptfmt =qemu_opt_get_del (opts,BLOCK_OPT_ENCRYPT_FORMAT ); +if (encryptfmt) { +if (qemu_opt_get (opts,BLOCK_OPT_ENCRYPT )) { +error_setg (errp,"Options " BLOCK_OPT_ENCRYPT " and " +BLOCK_OPT_ENCRYPT_FORMAT " are mutually exclusive" ); + ret = -EINVAL ; + goto cleanup; + } + }else if (qemu_opt_get_bool_del (opts,BLOCK_OPT_ENCRYPT , false)) { + encryptfmt ="aes" ; } ret =bdrv_create_file (filename, opts, &local_err);
@@ -873,7 +881,13 @@ static int qcow_create(const char *filename, QemuOpts *opts, Error **errp) l1_size = (total_size + (1LL << shift) -1 ) >> shift; header.l1_table_offset =cpu_to_be64 (header_size); -if (flags &BLOCK_FLAG_ENCRYPT ) { +if (encryptfmt) { +if (!g_str_equal (encryptfmt,"aes" )) { +error_setg (errp,"Unknown encryption format '%s', expected 'aes'" , + encryptfmt); + ret = -EINVAL ; + goto exit; + } header.crypt_method =cpu_to_be32 (QCOW_CRYPT_AES ); }else { header.crypt_method =cpu_to_be32 (QCOW_CRYPT_NONE );
@@ -1047,8 +1061,13 @@ static QemuOptsList qcow_create_opts = { { .name = BLOCK_OPT_ENCRYPT, .type = QEMU_OPT_BOOL, - .help = "Encrypt the image", - .def_value_str = "off" + .help = "Encrypt the image with format 'aes'. (Deprecated " + "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)", + }, + { + .name = BLOCK_OPT_ENCRYPT_FORMAT, + .type = QEMU_OPT_STRING, + .help = "Encrypt the image, format choices: 'aes'", }, {/* end of list */ } }
block/qcow2.c +27 -7
@@ -2144,7 +2144,7 @@ static int qcow2_create2(const char *filename, int64_t total_size, const char *backing_file, const char *backing_format, int flags, size_t cluster_size, PreallocMode prealloc, QemuOpts *opts, int version, int refcount_order, - Error **errp) + const char *encryptfmt, Error **errp) { int cluster_bits;QDict *options;
@@ -2273,7 +2273,13 @@ static int qcow2_create2(const char *filename, int64_t total_size, .header_length = cpu_to_be32(sizeof(*header)), }; -if (flags &BLOCK_FLAG_ENCRYPT ) { +if (encryptfmt) { +if (!g_str_equal (encryptfmt,"aes" )) { +error_setg (errp,"Unknown encryption format '%s', expected 'aes'" , + encryptfmt); + ret = -EINVAL ; + goto out; + } header->crypt_method =cpu_to_be32 (QCOW_CRYPT_AES ); }else { header->crypt_method =cpu_to_be32 (QCOW_CRYPT_NONE );
@@ -2402,6 +2408,7 @@ static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp)int version =3 ;uint64_t refcount_bits =16 ;int refcount_order; +const char *encryptfmt =NULL ;Error *local_err =NULL ;int ret;
@@ -2410,8 +2417,16 @@ static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp) BDRV_SECTOR_SIZE); backing_file =qemu_opt_get_del (opts,BLOCK_OPT_BACKING_FILE ); backing_fmt =qemu_opt_get_del (opts,BLOCK_OPT_BACKING_FMT ); -if (qemu_opt_get_bool_del (opts,BLOCK_OPT_ENCRYPT , false)) { - flags |=BLOCK_FLAG_ENCRYPT ; + encryptfmt =qemu_opt_get_del (opts,BLOCK_OPT_ENCRYPT_FORMAT ); +if (encryptfmt) { +if (qemu_opt_get_del (opts,BLOCK_OPT_ENCRYPT )) { +error_setg (errp,"Options " BLOCK_OPT_ENCRYPT " and " +BLOCK_OPT_ENCRYPT_FORMAT " are mutually exclusive" ); + ret = -EINVAL ; + goto finish; + } + }else if (qemu_opt_get_bool_del (opts,BLOCK_OPT_ENCRYPT , false)) { + encryptfmt ="aes" ; } cluster_size =qemu_opt_get_size_del (opts,BLOCK_OPT_CLUSTER_SIZE ,DEFAULT_CLUSTER_SIZE );
@@ -2477,7 +2492,7 @@ static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp) ret =qcow2_create2 (filename, size, backing_file, backing_fmt, flags, cluster_size, prealloc, opts, version, refcount_order, - &local_err); + encryptfmt, &local_err);error_propagate (errp, local_err); finish:
@@ -3431,8 +3446,13 @@ static QemuOptsList qcow2_create_opts = { { .name = BLOCK_OPT_ENCRYPT, .type = QEMU_OPT_BOOL, - .help = "Encrypt the image", - .def_value_str ="off" + .help = "Encrypt the image with format 'aes'. (Deprecated " + "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)", + }, + { + .name = BLOCK_OPT_ENCRYPT_FORMAT, + .type = QEMU_OPT_STRING, + .help = "Encrypt the image, format choices: 'aes'", }, { .name = BLOCK_OPT_CLUSTER_SIZE,
include/block/block_int.h +1 -1
@@ -37,11 +37,11 @@#include "qemu/main-loop.h" #include "qemu/throttle.h" -#define BLOCK_FLAG_ENCRYPT 1#define BLOCK_FLAG_LAZY_REFCOUNTS 8#define BLOCK_OPT_SIZE "size"#define BLOCK_OPT_ENCRYPT "encryption" +#define BLOCK_OPT_ENCRYPT_FORMAT "encrypt.format"#define BLOCK_OPT_COMPAT6 "compat6"#define BLOCK_OPT_HWVERSION "hwversion"#define BLOCK_OPT_BACKING_FILE "backing_file"
qemu-img.c +3 -1
@@ -2264,6 +2264,8 @@ static int img_convert(int argc, char **argv)if (s.compressed) {bool encryption =qemu_opt_get_bool (opts,BLOCK_OPT_ENCRYPT , false); +const char *encryptfmt = +qemu_opt_get (opts,BLOCK_OPT_ENCRYPT_FORMAT );const char *preallocation =qemu_opt_get (opts,BLOCK_OPT_PREALLOC );
@@ -2273,7 +2275,7 @@ static int img_convert(int argc, char **argv) goto out; } -if (encryption) { +if (encryption || encryptfmt) {error_report ("Compression and encryption not supported at " "the same time" ); ret =-1 ;
tests/qemu-iotests/049.out +49 -49
217 lines not on this page · raw message
tests/qemu-iotests/082.out +61 -34
295 lines not on this page · raw message
tests/qemu-iotests/085.out +19 -19
@@ -11,7 +11,7 @@ Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 === Create a single snapshot on virtio0 === -Formatting 'TEST_DIR/1-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/t.qcow2.1 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16 +Formatting 'TEST_DIR/1-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/t.qcow2.1 backing_fmt=qcow2 cluster_size=65536 lazy_refcounts=off refcount_bits=16 {"return": {}} === Invalid command - missing device and nodename ===
@@ -25,32 +25,32 @@ Formatting 'TEST_DIR/1-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file === Create several transactional group snapshots === -Formatting 'TEST_DIR/2-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/1-snapshot-v0.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16 -Formatting 'TEST_DIR/2-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/t.qcow2.2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16 +Formatting 'TEST_DIR/2-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/1-snapshot-v0.qcow2 backing_fmt=qcow2 cluster_size=65536 lazy_refcounts=off refcount_bits=16 +Formatting 'TEST_DIR/2-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/t.qcow2.2 backing_fmt=qcow2 cluster_size=65536 lazy_refcounts=off refcount_bits=16 {"return": {}} -Formatting 'TEST_DIR/3-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/2-snapshot-v0.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16 -Formatting 'TEST_DIR/3-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/2-snapshot-v1.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16 +Formatting 'TEST_DIR/3-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/2-snapshot-v0.qcow2 backing_fmt=qcow2 cluster_size=65536 lazy_refcounts=off refcount_bits=16 +Formatting 'TEST_DIR/3-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/2-snapshot-v1.qcow2 backing_fmt=qcow2 cluster_size=65536 lazy_refcounts=off refcount_bits=16 {"return": {}} -Formatting 'TEST_DIR/4-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/3-snapshot-v0.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16 -Formatting 'TEST_DIR/4-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/3-snapshot-v1.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16 +Formatting 'TEST_DIR/4-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/3-snapshot-v0.qcow2 backing_fmt=qcow2 cluster_size=65536 lazy_refcounts=off refcount_bits=16 +Formatting 'TEST_DIR/4-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/3-snapshot-v1.qcow2 backing_fmt=qcow2 cluster_size=65536 lazy_refcounts=off refcount_bits=16 {"return": {}} -Formatting 'TEST_DIR/5-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/4-snapshot-v0.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16 -Formatting 'TEST_DIR/5-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/4-snapshot-v1.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16 +Formatting 'TEST_DIR/5-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/4-snapshot-v0.qcow2 backing_fmt=qcow2 cluster_size=65536 lazy_refcounts=off refcount_bits=16 +Formatting 'TEST_DIR/5-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/4-snapshot-v1.qcow2 backing_fmt=qcow2 cluster_size=65536 lazy_refcounts=off refcount_bits=16 {"return": {}} -Formatting 'TEST_DIR/6-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/5-snapshot-v0.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16 -Formatting 'TEST_DIR/6-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/5-snapshot-v1.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16 +Formatting 'TEST_DIR/6-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/5-snapshot-v0.qcow2 backing_fmt=qcow2 cluster_size=65536 lazy_refcounts=off refcount_bits=16 +Formatting 'TEST_DIR/6-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/5-snapshot-v1.qcow2 backing_fmt=qcow2 cluster_size=65536 lazy_refcounts=off refcount_bits=16 {"return": {}} -Formatting 'TEST_DIR/7-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/6-snapshot-v0.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16 -Formatting 'TEST_DIR/7-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/6-snapshot-v1.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16 +Formatting 'TEST_DIR/7-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/6-snapshot-v0.qcow2 backing_fmt=qcow2 cluster_size=65536 lazy_refcounts=off refcount_bits=16 +Formatting 'TEST_DIR/7-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/6-snapshot-v1.qcow2 backing_fmt=qcow2 cluster_size=65536 lazy_refcounts=off refcount_bits=16 {"return": {}} -Formatting 'TEST_DIR/8-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/7-snapshot-v0.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16 -Formatting 'TEST_DIR/8-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/7-snapshot-v1.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16 +Formatting 'TEST_DIR/8-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/7-snapshot-v0.qcow2 backing_fmt=qcow2 cluster_size=65536 lazy_refcounts=off refcount_bits=16 +Formatting 'TEST_DIR/8-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/7-snapshot-v1.qcow2 backing_fmt=qcow2 cluster_size=65536 lazy_refcounts=off refcount_bits=16 {"return": {}} -Formatting 'TEST_DIR/9-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/8-snapshot-v0.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16 -Formatting 'TEST_DIR/9-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/8-snapshot-v1.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16 +Formatting 'TEST_DIR/9-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/8-snapshot-v0.qcow2 backing_fmt=qcow2 cluster_size=65536 lazy_refcounts=off refcount_bits=16 +Formatting 'TEST_DIR/9-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/8-snapshot-v1.qcow2 backing_fmt=qcow2 cluster_size=65536 lazy_refcounts=off refcount_bits=16 {"return": {}} -Formatting 'TEST_DIR/10-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/9-snapshot-v0.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16 -Formatting 'TEST_DIR/10-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/9-snapshot-v1.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16 +Formatting 'TEST_DIR/10-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/9-snapshot-v0.qcow2 backing_fmt=qcow2 cluster_size=65536 lazy_refcounts=off refcount_bits=16 +Formatting 'TEST_DIR/10-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/9-snapshot-v1.qcow2 backing_fmt=qcow2 cluster_size=65536 lazy_refcounts=off refcount_bits=16 {"return": {}} === Create a couple of snapshots using blockdev-snapshot ===
tests/qemu-iotests/144.out +2 -2
@@ -7,7 +7,7 @@ Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=536870912 === Performing Live Snapshot 1 === {"return": {}} -Formatting 'TEST_DIR/tmp.qcow2', fmt=qcow2 size=536870912 backing_file=TEST_DIR/t.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16 +Formatting 'TEST_DIR/tmp.qcow2', fmt=qcow2 size=536870912 backing_file=TEST_DIR/t.qcow2 backing_fmt=qcow2 cluster_size=65536 lazy_refcounts=off refcount_bits=16 {"return": {}} === Performing block-commit on active layer ===
@@ -19,6 +19,6 @@ Formatting 'TEST_DIR/tmp.qcow2', fmt=qcow2 size=536870912 backing_file=TEST_DIR/ === Performing Live Snapshot 2 === -Formatting 'TEST_DIR/tmp2.qcow2', fmt=qcow2 size=536870912 backing_file=TEST_DIR/t.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16 +Formatting 'TEST_DIR/tmp2.qcow2', fmt=qcow2 size=536870912 backing_file=TEST_DIR/t.qcow2 backing_fmt=qcow2 cluster_size=65536 lazy_refcounts=off refcount_bits=16 {"return": {}} *** done
tests/qemu-iotests/185.out +4 -4
@@ -7,12 +7,12 @@ Formatting 'TEST_DIR/t.IMGFMT.base', fmt=IMGFMT size=67108864 === Creating backing chain === -Formatting 'TEST_DIR/t.qcow2.mid', fmt=qcow2 size=67108864 backing_file=TEST_DIR/t.qcow2.base backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16 +Formatting 'TEST_DIR/t.qcow2.mid', fmt=qcow2 size=67108864 backing_file=TEST_DIR/t.qcow2.base backing_fmt=qcow2 cluster_size=65536 lazy_refcounts=off refcount_bits=16 {"return": {}} wrote 4194304/4194304 bytes at offset 0 4 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec) {"return": ""} -Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 backing_file=TEST_DIR/t.qcow2.mid backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16 +Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 backing_file=TEST_DIR/t.qcow2.mid backing_fmt=qcow2 cluster_size=65536 lazy_refcounts=off refcount_bits=16 {"return": {}} === Start commit job and exit qemu ===
@@ -33,7 +33,7 @@ Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 backing_file=TEST_DIR/t.q === Start mirror job and exit qemu === {"return": {}} -Formatting 'TEST_DIR/t.qcow2.copy', fmt=qcow2 size=67108864 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16 +Formatting 'TEST_DIR/t.qcow2.copy', fmt=qcow2 size=67108864 cluster_size=65536 lazy_refcounts=off refcount_bits=16 {"return": {}} {"return": {}} {"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "SHUTDOWN", "data": {"guest": false}}
@@ -42,7 +42,7 @@ Formatting 'TEST_DIR/t.qcow2.copy', fmt=qcow2 size=67108864 encryption=off clust === Start backup job and exit qemu === {"return": {}} -Formatting 'TEST_DIR/t.qcow2.copy', fmt=qcow2 size=67108864 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16 +Formatting 'TEST_DIR/t.qcow2.copy', fmt=qcow2 size=67108864 cluster_size=65536 lazy_refcounts=off refcount_bits=16 {"return": {}} {"return": {}} {"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "SHUTDOWN", "data": {"guest": false}}
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 056/100] block: rip out all traces of password prompting
In reply to Kevin WolfFrom: "Daniel P. Berrange" <[email protected]>
Now that qcow & qcow2 are wired up to get encryption keys via the QCryptoSecret object, nothing is relying on the interactive prompting for passwords. All the code related to password prompting can thus be ripped out.
Message-id: [email protected]
--- hmp.c | 31 --------------------- include/monitor/monitor.h | 7 ----- include/qemu/osdep.h | 2 -- monitor.c | 68 ----------------------------------------------- qapi-schema.json | 10 +------ qemu-img.c | 31 --------------------- qemu-io.c | 20 -------------- qmp.c | 12 +-------- util/oslib-posix.c | 66 --------------------------------------------- util/oslib-win32.c | 24 ----------------- 10 files changed, 2 insertions(+), 269 deletions(-)
hmp.c +0 -31
@@ -1088,37 +1088,12 @@ void hmp_ringbuf_read(Monitor *mon, const QDict *qdict)g_free (data); } -static void hmp_cont_cb (void *opaque,int err) -{ -if (!err) { -qmp_cont (NULL ); - } -} - -static bool key_is_missing (const BlockInfo *bdev) -{ -return (bdev->inserted && bdev->inserted->encryption_key_missing); -} -void hmp_cont (Monitor *mon,const QDict *qdict) { -BlockInfoList *bdev_list, *bdev;Error *err =NULL ; - bdev_list =qmp_query_block (NULL ); -for (bdev = bdev_list; bdev; bdev = bdev->next) { -if (key_is_missing (bdev->value)) { -monitor_read_block_device_key (mon, bdev->value->device, - hmp_cont_cb,NULL ); - goto out; - } - } -qmp_cont (&err);hmp_handle_error (mon, &err); - -out: -qapi_free_BlockInfoList (bdev_list); }void hmp_system_wakeup (Monitor *mon,const QDict *qdict)
@@ -1741,12 +1716,6 @@ void hmp_change(Monitor *mon, const QDict *qdict)qmp_blockdev_change_medium (true, device, false,NULL , target, !!arg, arg, !!read_only, read_only_mode, &err); -if (err && -error_get_class (err) ==ERROR_CLASS_DEVICE_ENCRYPTED ) { -error_free (err); -monitor_read_block_device_key (mon, device,NULL ,NULL ); -return ; - } }hmp_handle_error (mon, &err);
include/monitor/monitor.h +0 -7
@@ -23,13 +23,6 @@ void monitor_cleanup(void);int monitor_suspend (Monitor *mon);void monitor_resume (Monitor *mon); -int monitor_read_bdrv_key_start (Monitor *mon,BlockDriverState *bs, -BlockCompletionFunc *completion_cb, -void *opaque); -int monitor_read_block_device_key (Monitor *mon,const char *device, -BlockCompletionFunc *completion_cb, -void *opaque); -int monitor_get_fd (Monitor *mon,const char *fdname,Error **errp);int monitor_fd_param (Monitor *mon,const char *fdname,Error **errp);
include/qemu/osdep.h +0 -2
@@ -457,8 +457,6 @@ void qemu_set_tty_echo(int fd, bool echo);void os_mem_prealloc (int fd,char *area,size_t sz,int smp_cpus,Error **errp); -int qemu_read_password (char *buf,int buf_size); -/** * qemu_get_pid_name: * @pid: pid of a process
monitor.c +0 -68
74 lines not on this page · raw message
qapi-schema.json +1 -9
@@ -2431,8 +2431,6 @@ # Since: 0.14.0 # # Returns: If successful, nothing -# If QEMU was started with an encrypted block device and a key has -# not yet been set, DeviceEncrypted. # # Notes: This command will succeed if the guest is currently running. It # will also succeed if the guest is in the "inmigrate" state; in
@@ -2713,8 +2711,7 @@ # * This command is stateless, this means that commands that depend # on state information (such as getfd) might not work # -# * Commands that prompt the user for data (eg. 'cont' when the block -# device is encrypted) don't currently work +# * Commands that prompt the user for data don't currently work # # Example: #
@@ -3019,11 +3016,6 @@ # # Returns: Nothing on success. # If @device is not a valid block device, DeviceNotFound -# If the new block device is encrypted, DeviceEncrypted. Note that -# if this error is returned, the device has been opened successfully -# and an additional call to @block_passwd is required to set the -# device's password. The behavior of reads and writes to the block -# device between when these calls are executed is undefined. # # Notes: This interface is deprecated, and it is strongly recommended that you # avoid using it. For changing block devices, use
qemu-img.c +0 -31
@@ -260,29 +260,6 @@ static int print_block_option_help(const char *filename, const char *fmt) } -static int img_open_password (BlockBackend *blk,const char *filename, -int flags,bool quiet) -{ -BlockDriverState *bs; -char password[256 ]; - - bs =blk_bs (blk); -if (bdrv_is_encrypted (bs) &&bdrv_key_required (bs) && - !(flags &BDRV_O_NO_IO )) { -qprintf (quiet,"Disk image '%s' is encrypted.\n" , filename); -if (qemu_read_password (password,sizeof (password)) <0 ) { -error_report ("No password given" ); -return -1 ; - } -if (bdrv_set_key (bs, password) <0 ) { -error_report ("invalid password" ); -return -1 ; - } - } -return 0 ; -} - -static BlockBackend *img_open_opts (const char *optstr,QemuOpts *opts,int flags,bool writethrough,bool quiet,bool force_share)
@@ -307,10 +284,6 @@ static BlockBackend *img_open_opts(const char *optstr, }blk_set_enable_write_cache (blk, !writethrough); -if (img_open_password (blk, optstr, flags, quiet) <0 ) { -blk_unref (blk); -return NULL ; - }return blk; }
@@ -340,10 +313,6 @@ static BlockBackend *img_open_file(const char *filename, }blk_set_enable_write_cache (blk, !writethrough); -if (img_open_password (blk, filename, flags, quiet) <0 ) { -blk_unref (blk); -return NULL ; - }return blk; }
qemu-io.c +0 -20
@@ -58,7 +58,6 @@ static int openfile(char *name, int flags, bool writethrough, bool force_share, QDict *opts) {Error *local_err =NULL ; -BlockDriverState *bs;if (qemuio_blk) {error_report ("file open already, try 'help close'" );
@@ -85,28 +84,9 @@ static int openfile(char *name, int flags, bool writethrough, bool force_share,return 1 ; } - bs =blk_bs (qemuio_blk); -if (bdrv_is_encrypted (bs) &&bdrv_key_required (bs)) { -char password[256 ]; -printf ("Disk image '%s' is encrypted.\n" , name); -if (qemu_read_password (password,sizeof (password)) <0 ) { -error_report ("No password given" ); - goto error; - } -if (bdrv_set_key (bs, password) <0 ) { -error_report ("invalid password" ); - goto error; - } - } -blk_set_enable_write_cache (qemuio_blk, !writethrough);return 0 ; - - error: -blk_unref (qemuio_blk); - qemuio_blk =NULL ; -return 1 ; }static void open_help (void )
qmp.c +1 -11
@@ -164,10 +164,8 @@ SpiceInfo *qmp_query_spice(Error **errp)void qmp_cont (Error **errp) { -Error *local_err =NULL ;BlockBackend *blk; -BlockDriverState *bs; -BdrvNextIterator it; +Error *local_err =NULL ;/* if there is a dump in background, we should wait until the dump * finished */
@@ -187,14 +185,6 @@ void qmp_cont(Error **errp)blk_iostatus_reset (blk); } -for (bs =bdrv_first (&it); bs; bs =bdrv_next (&it)) { -bdrv_add_key (bs,NULL , &local_err); -if (local_err) { -error_propagate (errp, local_err); -return ; - } - } -/* Continuing after completed migration. Images have been inactivated to * allow the destination to take control. Need to get control back now. *
util/oslib-posix.c +0 -66
72 lines not on this page · raw message
util/oslib-win32.c +0 -24
@@ -552,30 +552,6 @@ void os_mem_prealloc(int fd, char *area, size_t memory, int smp_cpus, } -/* XXX: put correct support for win32 */ -int qemu_read_password (char *buf,int buf_size) -{ -int c, i; - -printf ("Password: " ); -fflush (stdout); - i =0 ; -for (;;) { - c =getchar (); -if (c <0 ) { - buf[i] ='\0' ; -return -1 ; - }else if (c =='\n' ) { -break ; - }else if (i < (buf_size -1 )) { - buf[i++] = c; - } - } - buf[i] ='\0' ; -return 0 ; -} - -char *qemu_get_pid_name (pid_t pid) {/* XXX Implement me */
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 059/100] qcow2: report encryption specific image information
In reply to Kevin WolfFrom: "Daniel P. Berrange" <[email protected]>
Currently 'qemu-img info' reports a simple "encrypted: yes" field. This is not very useful now that qcow2 can support multiple encryption formats. Users want to know which format is in use and some data related to it.
Wire up usage of the qcrypto_block_get_info() method so that 'qemu-img info' can report about the encryption format and parameters in use
$ qemu-img create \
--object secret,id=sec0,data=123456 \
-o encrypt.format=luks,encrypt.key-secret=sec0 \
-f qcow2 demo.qcow2 1G
Formatting 'demo.qcow2', fmt=qcow2 size=1073741824 \
encryption=off encrypt.format=luks encrypt.key-secret=sec0 \
cluster_size=65536 lazy_refcounts=off refcount_bits=16 $ qemu-img info demo.qcow2
image: demo.qcow2
file format: qcow2
virtual size: 1.0G (1073741824 bytes)
disk size: 480K
encrypted: yes
cluster_size: 65536
Format specific information:
compat: 1.1
lazy refcounts: false
refcount bits: 16
encrypt:
ivgen alg: plain64
hash alg: sha256
cipher alg: aes-256
uuid: 3fa930c4-58c8-4ef7-b3c5-314bb5af21f3
format: luks
cipher mode: xts
slots:
[0]:
active: true
iters: 1839058
key offset: 4096
stripes: 4000
[1]:
active: false
key offset: 262144
[2]:
active: false
key offset: 520192
[3]:
active: false
key offset: 778240
[4]:
active: false
key offset: 1036288
[5]:
active: false
key offset: 1294336
[6]:
active: false
key offset: 1552384
[7]:
active: false
key offset: 1810432
payload offset: 2068480
master key iters: 438487
corrupt: falseWith the legacy "AES" encryption we just report the format name
$ qemu-img create \
--object secret,id=sec0,data=123456 \
-o encrypt.format=aes,encrypt.key-secret=sec0 \
-f qcow2 demo.qcow2 1G
Formatting 'demo.qcow2', fmt=qcow2 size=1073741824 \
encryption=off encrypt.format=aes encrypt.key-secret=sec0 \
cluster_size=65536 lazy_refcounts=off refcount_bits=16 $ ./qemu-img info demo.qcow2
image: demo.qcow2
file format: qcow2
virtual size: 1.0G (1073741824 bytes)
disk size: 196K
encrypted: yes
cluster_size: 65536
Format specific information:
compat: 1.1
lazy refcounts: false
refcount bits: 16
encrypt:
format: aes
corrupt: falseMessage-id: [email protected]
--- block/qcow2.c | 32 +++++++++++++++++++++++++++++++- qapi/block-core.json | 27 ++++++++++++++++++++++++++- 2 files changed, 57 insertions(+), 2 deletions(-)
block/qcow2.c +31 -1
@@ -3241,8 +3241,14 @@ static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)static ImageInfoSpecific *qcow2_get_specific_info (BlockDriverState *bs) {BDRVQcow2State *s = bs->opaque; -ImageInfoSpecific *spec_info =g_new (ImageInfoSpecific,1 ); +ImageInfoSpecific *spec_info; +QCryptoBlockInfo *encrypt_info =NULL ; +if (s->crypto !=NULL ) { + encrypt_info =qcrypto_block_get_info (s->crypto, &error_abort); + } + + spec_info =g_new (ImageInfoSpecific,1 ); *spec_info = (ImageInfoSpecific ){ .type =IMAGE_INFO_SPECIFIC_KIND_QCOW2 , .u.qcow2.data =g_new (ImageInfoSpecificQCow2,1 ),
@@ -3269,6 +3275,30 @@ static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)assert (false); } +if (encrypt_info) { +ImageInfoSpecificQCow2Encryption *qencrypt = +g_new (ImageInfoSpecificQCow2Encryption,1 ); +switch (encrypt_info->format) { +case Q_CRYPTO_BLOCK_FORMAT_QCOW : + qencrypt->format =BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES ; + qencrypt->u.aes = encrypt_info->u.qcow; +break ; +case Q_CRYPTO_BLOCK_FORMAT_LUKS : + qencrypt->format =BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS ; + qencrypt->u.luks = encrypt_info->u.luks; +break ; +default : +abort (); + } +/* Since we did shallow copy above, erase any pointers +* in the original info */ +memset (&encrypt_info->u,0 ,sizeof (encrypt_info->u)); +qapi_free_QCryptoBlockInfo (encrypt_info); + + spec_info->u.qcow2.data->has_encrypt = true; + spec_info->u.qcow2.data->encrypt = qencrypt; + } +return spec_info; }
qapi/block-core.json +26 -1
@@ -33,6 +33,27 @@ 'vm-clock-sec': 'int', 'vm-clock-nsec': 'int' } } ## +# @ImageInfoSpecificQCow2EncryptionBase: +# +# @format: The encryption format +# +# Since: 2.10 +## +{ 'struct': 'ImageInfoSpecificQCow2EncryptionBase', + 'data': { 'format': 'BlockdevQcow2EncryptionFormat'}} + +## +# @ImageInfoSpecificQCow2Encryption: +# +# Since: 2.10 +## +{ 'union': 'ImageInfoSpecificQCow2Encryption', + 'base': 'ImageInfoSpecificQCow2EncryptionBase', + 'discriminator': 'format', + 'data': { 'aes': 'QCryptoBlockInfoQCow', + 'luks': 'QCryptoBlockInfoLUKS' } } + +## # @ImageInfoSpecificQCow2: # # @compat: compatibility level
@@ -44,6 +65,9 @@ # # @refcount-bits: width of a refcount entry in bits (since 2.3) # +# @encrypt: details about encryption parameters; only set if image +# is encrypted (since 2.10) +# # Since: 1.7 ## { 'struct': 'ImageInfoSpecificQCow2',
@@ -51,7 +75,8 @@ 'compat': 'str', '*lazy-refcounts': 'bool', '*corrupt': 'bool', - 'refcount-bits': 'int' + 'refcount-bits': 'int', + '*encrypt': 'ImageInfoSpecificQCow2Encryption' } } ##
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 057/100] block: remove all encryption handling APIs
In reply to Kevin WolfFrom: "Daniel P. Berrange" <[email protected]>
Now that all encryption keys must be provided upfront via the QCryptoSecret API and associated block driver properties there is no need for any explicit encryption handling APIs in the block layer. Encryption can be handled transparently within the block driver. We only retain an API for querying whether an image is encrypted or not, since that is a potentially useful piece of metadata to report to the user.
Message-id: [email protected]
--- block.c | 77 +---------------------------------------------- block/crypto.c | 1 - block/qapi.c | 2 +- block/qcow.c | 8 ++++- block/qcow2.c | 1 - blockdev.c | 37 ++--------------------- hmp-commands.hx | 2 ++ include/block/block.h | 3 -- include/block/block_int.h | 1 - include/qapi/error.h | 1 - qapi/block-core.json | 37 ++--------------------- qapi/common.json | 5 +-- 12 files changed, 16 insertions(+), 159 deletions(-)
block.c +1 -76
@@ -2573,15 +2573,7 @@ static BlockDriverState *bdrv_open_inherit(const char *filename, goto close_and_fail; } -if (!bdrv_key_required (bs)) { -bdrv_parent_cb_change_media (bs, true); - }else if (!runstate_check (RUN_STATE_PRELAUNCH ) - && !runstate_check (RUN_STATE_INMIGRATE ) - && !runstate_check (RUN_STATE_PAUSED )) {/* HACK */ -error_setg (errp, -"Guest must be stopped for opening of encrypted image" ); - goto close_and_fail; - } +bdrv_parent_cb_change_media (bs, true);QDECREF (options);
@@ -3072,7 +3064,6 @@ static void bdrv_close(BlockDriverState *bs) bs->backing_format[0 ] ='\0' ; bs->total_sectors =0 ; bs->encrypted = false; - bs->valid_key = false; bs->sg = false;QDECREF (bs->options);QDECREF (bs->explicit_options);
@@ -3502,72 +3493,6 @@ bool bdrv_is_encrypted(BlockDriverState *bs)return bs->encrypted; } -bool bdrv_key_required (BlockDriverState *bs) -{ -BdrvChild *backing = bs->backing; - -if (backing && backing->bs->encrypted && !backing->bs->valid_key) { -return true; - } -return (bs->encrypted && !bs->valid_key); -} - -int bdrv_set_key (BlockDriverState *bs,const char *key) -{ -int ret; -if (bs->backing && bs->backing->bs->encrypted) { - ret =bdrv_set_key (bs->backing->bs, key); -if (ret <0 ) -return ret; -if (!bs->encrypted) -return 0 ; - } -if (!bs->encrypted) { -return -EINVAL ; - }else if (!bs->drv || !bs->drv->bdrv_set_key) { -return -ENOMEDIUM ; - } - ret = bs->drv->bdrv_set_key (bs, key); -if (ret <0 ) { - bs->valid_key = false; - }else if (!bs->valid_key) { -/* call the change callback now, we skipped it on open */ - bs->valid_key = true; -bdrv_parent_cb_change_media (bs, true); - } -return ret; -} - -/* -* Provide an encryption key for @bs. -* If @key is non-null: -* If @bs is not encrypted, fail. -* Else if the key is invalid, fail. -* Else set @bs's key to @key, replacing the existing key, if any. -* If @key is null: -* If @bs is encrypted and still lacks a key, fail. -* Else do nothing. -* On failure, store an error object through @errp if non-null. -*/ -void bdrv_add_key (BlockDriverState *bs,const char *key,Error **errp) -{ -if (key) { -if (!bdrv_is_encrypted (bs)) { -error_setg (errp,"Node '%s' is not encrypted" , -bdrv_get_device_or_node_name (bs)); - }else if (bdrv_set_key (bs, key) <0 ) { -error_setg (errp,QERR_INVALID_PASSWORD ); - } - }else { -if (bdrv_key_required (bs)) { -error_set (errp,ERROR_CLASS_DEVICE_ENCRYPTED , -"'%s' (%s) is encrypted" , -bdrv_get_device_or_node_name (bs), -bdrv_get_encrypted_filename (bs)); - } - } -} -const char *bdrv_get_format_name (BlockDriverState *bs) {return bs->drv ? bs->drv->format_name :NULL ;
block/crypto.c +0 -1
@@ -308,7 +308,6 @@ static int block_crypto_open_generic(QCryptoBlockFormat format, } bs->encrypted = true; - bs->valid_key = true; ret =0 ; cleanup:
block/qapi.c +1 -1
@@ -45,7 +45,7 @@ BlockDeviceInfo *bdrv_block_device_info(BlockBackend *blk, info->ro = bs->read_only; info->drv =g_strdup (bs->drv->format_name); info->encrypted = bs->encrypted; - info->encryption_key_missing =bdrv_key_required (bs); + info->encryption_key_missing = false; info->cache =g_new (BlockdevCacheInfo,1 ); *info->cache = (BlockdevCacheInfo ) {
block/qcow.c +7 -1
@@ -220,7 +220,13 @@ static int qcow_open(BlockDriverState *bs, QDict *options, int flags, goto fail; } bs->encrypted = true; - bs->valid_key = true; + }else { +if (encryptfmt) { +error_setg (errp,"No encryption in image header, but options " +"specified format '%s'" , encryptfmt); + ret = -EINVAL ; + goto fail; + } } s->cluster_bits = header.cluster_bits; s->cluster_size =1 << s->cluster_bits;
block/qcow2.c +0 -1
@@ -1171,7 +1171,6 @@ static int qcow2_do_open(BlockDriverState *bs, QDict *options, int flags, } bs->encrypted = true; - bs->valid_key = true; } s->l2_bits = s->cluster_bits -3 ;/* L2 is always one cluster */
blockdev.c +2 -35
@@ -593,10 +593,6 @@ static BlockBackend *blockdev_init(const char *file, QDict *bs_opts, bs->detect_zeroes = detect_zeroes; -if (bdrv_key_required (bs)) { - autostart =0 ; - } -block_acct_setup (blk_get_stats (blk), account_invalid, account_failed);if (!parse_stats_intervals (blk_get_stats (blk), interval_list, errp)) {
@@ -2265,24 +2261,8 @@ void qmp_block_passwd(bool has_device, const char *device, bool has_node_name, const char *node_name, const char *password, Error **errp) { - Error *local_err = NULL; -BlockDriverState *bs; -AioContext *aio_context; - - bs =bdrv_lookup_bs (has_device ? device :NULL , - has_node_name ? node_name :NULL , - &local_err); -if (local_err) { -error_propagate (errp, local_err); -return ; - } - - aio_context =bdrv_get_aio_context (bs); -aio_context_acquire (aio_context); - -bdrv_add_key (bs, password, errp); - -aio_context_release (aio_context); + error_setg(errp, + "Setting block passwords directly is no longer supported"); }/*
@@ -2591,12 +2571,6 @@ void qmp_blockdev_change_medium(bool has_device, const char *device, goto fail; } -bdrv_add_key (medium_bs,NULL , &err); -if (err) { -error_propagate (errp, err); - goto fail; - } - rc =do_open_tray (has_device ? device :NULL , has_id ? id :NULL , false, &err);
@@ -3866,13 +3840,6 @@ void qmp_blockdev_add(BlockdevOptions *options, Error **errp)QTAILQ_INSERT_TAIL (&monitor_bdrv_states, bs, monitor_list); -if (bs &&bdrv_key_required (bs)) { -QTAILQ_REMOVE (&monitor_bdrv_states, bs, monitor_list); -bdrv_unref (bs); -error_setg (errp,"blockdev-add doesn't support encrypted devices" ); - goto fail; - } - fail:visit_free (v); }
hmp-commands.hx +2 -0
@@ -1646,6 +1646,8 @@ STEXI @item block_passwd @var{device} @var{password} @findex block_passwd Set the encrypted device @var{device} password to @var{password} + +This command is now obsolete and will always return an error since 2.10 ETEXI {
include/block/block.h +0 -3
@@ -464,9 +464,6 @@ BlockDriverState *bdrv_next(BdrvNextIterator *it);BlockDriverState *bdrv_next_monitor_owned (BlockDriverState *bs);bool bdrv_is_encrypted (BlockDriverState *bs); -bool bdrv_key_required (BlockDriverState *bs); -int bdrv_set_key (BlockDriverState *bs,const char *key); -void bdrv_add_key (BlockDriverState *bs,const char *key,Error **errp);void bdrv_iterate_format (void (*it)(void *opaque,const char *name),void *opaque);const char *bdrv_get_node_name (const BlockDriverState *bs);
include/block/block_int.h +0 -1
@@ -529,7 +529,6 @@ struct BlockDriverState {int open_flags;/* flags used to open the file, re-used for re-open */ bool read_only;/* if true, the media is read only */ bool encrypted;/* if true, the media is encrypted */ -bool valid_key;/* if true, a valid encryption key has been set */ bool sg;/* if true, the device is a /dev/sg* */ bool probed;/* if true, format was probed rather than specified */ bool force_share;/* if true, always allow all shared permissions */
include/qapi/error.h +0 -1
@@ -125,7 +125,6 @@ typedef enum ErrorClass { ERROR_CLASS_GENERIC_ERROR = QAPI_ERROR_CLASS_GENERICERROR, ERROR_CLASS_COMMAND_NOT_FOUND = QAPI_ERROR_CLASS_COMMANDNOTFOUND, - ERROR_CLASS_DEVICE_ENCRYPTED = QAPI_ERROR_CLASS_DEVICEENCRYPTED, ERROR_CLASS_DEVICE_NOT_ACTIVE = QAPI_ERROR_CLASS_DEVICENOTACTIVE, ERROR_CLASS_DEVICE_NOT_FOUND = QAPI_ERROR_CLASS_DEVICENOTFOUND, ERROR_CLASS_KVM_MISSING_CAP = QAPI_ERROR_CLASS_KVMMISSINGCAP,
qapi/block-core.json +2 -35
@@ -259,8 +259,7 @@ # # @encrypted: true if the backing device is encrypted # -# @encryption_key_missing: true if the backing device is encrypted but an -# valid encryption key is missing +# @encryption_key_missing: Deprecated; always false # # @detect_zeroes: detect and optimize zero writes (Since 2.1) #
@@ -946,39 +945,7 @@ # This command sets the password of a block device that has not been open # with a password and requires one. # -# The two cases where this can happen are a block device is created through -# QEMU's initial command line or a block device is changed through the legacy -# @change interface. -# -# In the event that the block device is created through the initial command -# line, the VM will start in the stopped state regardless of whether '-S' is -# used. The intention is for a management tool to query the block devices to -# determine which ones are encrypted, set the passwords with this command, and -# then start the guest with the @cont command. -# -# Either @device or @node-name must be set but not both. -# -# @device: the name of the block backend device to set the password on -# -# @node-name: graph node name to set the password on (Since 2.0) -# -# @password: the password to use for the device -# -# Returns: nothing on success -# If @device is not a valid block device, DeviceNotFound -# If @device is not encrypted, DeviceNotEncrypted -# -# Notes: Not all block formats support encryption and some that do are not -# able to validate that a password is correct. Disk corruption may -# occur if an invalid password is specified. -# -# Since: 0.14.0 -# -# Example: -# -# -> { "execute": "block_passwd", "arguments": { "device": "ide0-hd0", -# "password": "12345" } } -# <- { "return": {} } +# This command is now obsolete and will always return an error since 2.10 # ## { 'command': 'block_passwd', 'data': {'*device': 'str',
qapi/common.json +1 -4
@@ -14,9 +14,6 @@ # # @CommandNotFound: the requested command has not been found # -# @DeviceEncrypted: the requested operation can't be fulfilled because the -# selected device is encrypted -# # @DeviceNotActive: a device has failed to be become active # # @DeviceNotFound: the requested device has not been found
@@ -28,7 +25,7 @@ ## { 'enum': 'QapiErrorClass', # Keep this in sync with ErrorClass in error.h - 'data': [ 'GenericError', 'CommandNotFound', 'DeviceEncrypted', + 'data': [ 'GenericError', 'CommandNotFound', 'DeviceNotActive', 'DeviceNotFound', 'KVMMissingCap' ] } ##
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 058/100] block: pass option prefix down to crypto layer
In reply to Kevin WolfFrom: "Daniel P. Berrange" <[email protected]>
While the crypto layer uses a fixed option name "key-secret", the upper block layer may have a prefix on the options. e.g. "encrypt.key-secret", in order to avoid clashes between crypto option names & other block option names. To ensure the crypto layer can report accurate error messages, we must tell it what option name prefix was used.
Message-id: [email protected]
--- block/crypto.c | 4 ++-- block/qcow.c | 7 ++++--- block/qcow2.c | 8 ++++---- crypto/block-luks.c | 8 ++++++-- crypto/block-qcow.c | 8 ++++++-- crypto/block.c | 6 ++++-- crypto/blockpriv.h | 2 ++ include/crypto/block.h | 6 +++++- tests/test-crypto-block.c | 8 ++++---- 9 files changed, 37 insertions(+), 20 deletions(-)
block/crypto.c +2 -2
@@ -296,7 +296,7 @@ static int block_crypto_open_generic(QCryptoBlockFormat format,if (flags &BDRV_O_NO_IO ) { cflags |=QCRYPTO_BLOCK_OPEN_NO_IO ; } - crypto->block = qcrypto_block_open(open_opts, + crypto->block = qcrypto_block_open(open_opts, NULL, block_crypto_read_func, bs, cflags,
@@ -340,7 +340,7 @@ static int block_crypto_create_generic(QCryptoBlockFormat format,return -1 ; } - crypto = qcrypto_block_create(create_opts, + crypto = qcrypto_block_create(create_opts, NULL, block_crypto_init_func, block_crypto_write_func, &data,
block/qcow.c +4 -3
@@ -208,8 +208,8 @@ static int qcow_open(BlockDriverState *bs, QDict *options, int flags,if (flags &BDRV_O_NO_IO ) { cflags |=QCRYPTO_BLOCK_OPEN_NO_IO ; } - s->crypto =qcrypto_block_open (crypto_opts,NULL ,NULL , - cflags, errp); + s->crypto =qcrypto_block_open (crypto_opts,"encrypt." , +NULL ,NULL , cflags, errp);if (!s->crypto) { ret = -EINVAL ; goto fail;
@@ -866,7 +866,8 @@ static int qcow_create(const char *filename, QemuOpts *opts, Error **errp) goto exit; } - crypto =qcrypto_block_create (crypto_opts,NULL ,NULL ,NULL , errp); + crypto =qcrypto_block_create (crypto_opts,"encrypt." , +NULL ,NULL ,NULL , errp);if (!crypto) { ret = -EINVAL ; goto exit;
block/qcow2.c +4 -4
@@ -279,7 +279,7 @@ static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,if (flags &BDRV_O_NO_IO ) { cflags |=QCRYPTO_BLOCK_OPEN_NO_IO ; } - s->crypto =qcrypto_block_open (s->crypto_opts, + s->crypto =qcrypto_block_open (s->crypto_opts,"encrypt." , qcow2_crypto_hdr_read_func, bs, cflags, errp);if (!s->crypto) {
@@ -1313,8 +1313,8 @@ static int qcow2_do_open(BlockDriverState *bs, QDict *options, int flags,if (flags &BDRV_O_NO_IO ) { cflags |=QCRYPTO_BLOCK_OPEN_NO_IO ; } - s->crypto =qcrypto_block_open (s->crypto_opts,NULL ,NULL , - cflags, errp); + s->crypto =qcrypto_block_open (s->crypto_opts,"encrypt." , +NULL ,NULL , cflags, errp);if (!s->crypto) { ret = -EINVAL ; goto fail;
@@ -2318,7 +2318,7 @@ static int qcow2_set_up_encryption(BlockDriverState *bs, const char *encryptfmt, } s->crypt_method_header = fmt; - crypto =qcrypto_block_create (cryptoopts, + crypto =qcrypto_block_create (cryptoopts,"encrypt." , qcow2_crypto_hdr_init_func, qcow2_crypto_hdr_write_func, bs, errp);
crypto/block-luks.c +6 -2
@@ -638,6 +638,7 @@ qcrypto_block_luks_find_key(QCryptoBlock *block, static int qcrypto_block_luks_open(QCryptoBlock *block, QCryptoBlockOpenOptions *options, + const char *optprefix, QCryptoBlockReadFunc readfunc, void *opaque, unsigned int flags,
@@ -661,7 +662,8 @@ qcrypto_block_luks_open(QCryptoBlock *block,if (!(flags &QCRYPTO_BLOCK_OPEN_NO_IO )) {if (!options->u.luks.key_secret) { -error_setg (errp,"Parameter 'key-secret' is required for cipher" ); +error_setg (errp,"Parameter '%skey-secret' is required for cipher" , + optprefix ? optprefix :"" );return -1 ; } password = qcrypto_secret_lookup_as_utf8(
@@ -885,6 +887,7 @@ qcrypto_block_luks_uuid_gen(uint8_t *uuidstr) static int qcrypto_block_luks_create(QCryptoBlock *block, QCryptoBlockCreateOptions *options, + const char *optprefix, QCryptoBlockInitFunc initfunc, QCryptoBlockWriteFunc writefunc, void *opaque,
@@ -937,7 +940,8 @@ qcrypto_block_luks_create(QCryptoBlock *block,* be silently ignored, for compatibility with dm-crypt */ if (!options->u.luks.key_secret) { -error_setg (errp,"Parameter 'key-secret' is required for cipher" ); +error_setg (errp,"Parameter '%skey-secret' is required for cipher" , + optprefix ? optprefix :"" );return -1 ; } password =qcrypto_secret_lookup_as_utf8 (luks_opts.key_secret, errp);
crypto/block-qcow.c +6 -2
@@ -94,6 +94,7 @@ qcrypto_block_qcow_init(QCryptoBlock *block, static int qcrypto_block_qcow_open(QCryptoBlock *block, QCryptoBlockOpenOptions *options, + const char *optprefix, QCryptoBlockReadFunc readfunc G_GNUC_UNUSED, void *opaque G_GNUC_UNUSED, unsigned int flags,
@@ -104,7 +105,8 @@ qcrypto_block_qcow_open(QCryptoBlock *block, }else {if (!options->u.qcow.key_secret) {error_setg (errp, -"Parameter 'key-secret' is required for cipher" ); +"Parameter '%skey-secret' is required for cipher" , + optprefix ? optprefix :"" );return -1 ; } return qcrypto_block_qcow_init(block,
@@ -116,13 +118,15 @@ qcrypto_block_qcow_open(QCryptoBlock *block,static int qcrypto_block_qcow_create (QCryptoBlock *block,QCryptoBlockCreateOptions *options, +const char *optprefix, QCryptoBlockInitFunc initfunc G_GNUC_UNUSED, QCryptoBlockWriteFunc writefunc G_GNUC_UNUSED, void *opaque G_GNUC_UNUSED,Error **errp) {if (!options->u.qcow.key_secret) { -error_setg (errp,"Parameter 'key-secret' is required for cipher" ); +error_setg (errp,"Parameter '%skey-secret' is required for cipher" , + optprefix ? optprefix :"" );return -1 ; }/* QCow2 has no special header, since everything is hardwired */
crypto/block.c +4 -2
@@ -48,6 +48,7 @@ bool qcrypto_block_has_format(QCryptoBlockFormat format, QCryptoBlock *qcrypto_block_open(QCryptoBlockOpenOptions *options, + const char *optprefix, QCryptoBlockReadFunc readfunc, void *opaque, unsigned int flags,
@@ -67,7 +68,7 @@ QCryptoBlock *qcrypto_block_open(QCryptoBlockOpenOptions *options, block->driver = qcrypto_block_drivers[options->format]; -if (block->driver->open (block, options, +if (block->driver->open (block, options, optprefix, readfunc, opaque, flags, errp) <0 ) {g_free (block);return NULL ;
@@ -78,6 +79,7 @@ QCryptoBlock *qcrypto_block_open(QCryptoBlockOpenOptions *options, QCryptoBlock *qcrypto_block_create(QCryptoBlockCreateOptions *options, + const char *optprefix, QCryptoBlockInitFunc initfunc, QCryptoBlockWriteFunc writefunc, void *opaque,
@@ -97,7 +99,7 @@ QCryptoBlock *qcrypto_block_create(QCryptoBlockCreateOptions *options, block->driver = qcrypto_block_drivers[options->format]; -if (block->driver->create (block, options, initfunc, +if (block->driver->create (block, options, optprefix, initfunc, writefunc, opaque, errp) <0 ) {g_free (block);return NULL ;
crypto/blockpriv.h +2 -0
@@ -41,6 +41,7 @@ struct QCryptoBlock {struct QCryptoBlockDriver { int (*open)(QCryptoBlock *block, QCryptoBlockOpenOptions *options, + const char *optprefix, QCryptoBlockReadFunc readfunc, void *opaque, unsigned int flags,
@@ -48,6 +49,7 @@ struct QCryptoBlockDriver { int (*create)(QCryptoBlock *block, QCryptoBlockCreateOptions *options, + const char *optprefix, QCryptoBlockInitFunc initfunc, QCryptoBlockWriteFunc writefunc, void *opaque,
include/crypto/block.h +5 -1
@@ -71,6 +71,7 @@ typedef enum {/** * qcrypto_block_open: * @options: the encryption options +* @optprefix: name prefix for options * @readfunc: callback for reading data from the volume * @opaque: data to pass to @readfunc * @flags: bitmask of QCryptoBlockOpenFlags values
@@ -102,6 +103,7 @@ typedef enum {* Returns: a block encryption format, or NULL on error */ QCryptoBlock *qcrypto_block_open(QCryptoBlockOpenOptions *options, + const char *optprefix, QCryptoBlockReadFunc readfunc, void *opaque, unsigned int flags,
@@ -109,7 +111,8 @@ QCryptoBlock *qcrypto_block_open(QCryptoBlockOpenOptions *options,/** * qcrypto_block_create: -* @format: the encryption format +* @options: the encryption options +* @optprefix: name prefix for options * @initfunc: callback for initializing volume header * @writefunc: callback for writing data to the volume header * @opaque: data to pass to @initfunc and @writefunc
@@ -133,6 +136,7 @@ QCryptoBlock *qcrypto_block_open(QCryptoBlockOpenOptions *options,* Returns: a block encryption format, or NULL on error */ QCryptoBlock *qcrypto_block_create(QCryptoBlockCreateOptions *options, + const char *optprefix, QCryptoBlockInitFunc initfunc, QCryptoBlockWriteFunc writefunc, void *opaque,
tests/test-crypto-block.c +4 -4
@@ -281,7 +281,7 @@ static void test_block(gconstpointer opaque)memset (&header,0 ,sizeof (header));buffer_init (&header,"header" ); - blk = qcrypto_block_create(data->create_opts, + blk = qcrypto_block_create(data->create_opts, NULL, test_block_init_func, test_block_write_func, &header,
@@ -300,7 +300,7 @@ static void test_block(gconstpointer opaque)object_unparent (sec);/* Ensure we can't open without the secret */ - blk = qcrypto_block_open(data->open_opts, + blk = qcrypto_block_open(data->open_opts, NULL, test_block_read_func, &header, 0,
@@ -308,7 +308,7 @@ static void test_block(gconstpointer opaque)g_assert (blk ==NULL );/* Ensure we can't open without the secret, unless NO_IO */ - blk = qcrypto_block_open(data->open_opts, + blk = qcrypto_block_open(data->open_opts, NULL, test_block_read_func, &header, QCRYPTO_BLOCK_OPEN_NO_IO,
@@ -322,7 +322,7 @@ static void test_block(gconstpointer opaque)/* Now open for real with secret */ sec =test_block_secret (); - blk = qcrypto_block_open(data->open_opts, + blk = qcrypto_block_open(data->open_opts, NULL, test_block_read_func, &header, 0,
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 060/100] docs: document encryption options for qcow, qcow2 and luks
In reply to Kevin WolfFrom: "Daniel P. Berrange" <[email protected]>
Expand the image format docs to cover the new options for the qcow, qcow2 and luks disk image formats
Message-id: [email protected]
--- qemu-doc.texi | 123 ++++++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 115 insertions(+), 8 deletions(-)
qemu-doc.texi +115 -8
@@ -540,10 +540,20 @@ File name of a base image (see @option{create} subcommand) @item backing_fmt Image format of the base image @item encryption -If this option is set to @code{on}, the image is encrypted with 128-bit AES-CBC. +This option is deprecated and equivalent to @code{encrypt.format=aes} -The use of encryption in qcow and qcow2 images is considered to be flawed by -modern cryptography standards, suffering from a number of design problems: +@item encrypt.format + +If this is set to @code{luks}, it requests that the qcow2 payload (not +qcow2 header) be encrypted using the LUKS format. The passphrase to +use to unlock the LUKS key slot is given by the @code{encrypt.key-secret} +parameter. LUKS encryption parameters can be tuned with the other +@code{encrypt.*} parameters. + +If this is set to @code{aes}, the image is encrypted with 128-bit AES-CBC. +The encryption key is given by the @code{encrypt.key-secret} parameter. +This encryption format is considered to be flawed by modern cryptography +standards, suffering from a number of design problems: @itemize @minus @item The AES-CBC cipher is used with predictable initialization vectors based
@@ -558,10 +568,45 @@ original file must then be securely erased using a program like shred, though even this is ineffective with many modern storage technologies. @end itemize -Use of qcow / qcow2 encryption with QEMU is deprecated, and support for -it will go away in a future release. Users are recommended to use an -alternative encryption technology such as the Linux dm-crypt / LUKS -system. +The use of this is no longer supported in system emulators. Support only +remains in the command line utilities, for the purposes of data liberation +and interoperability with old versions of QEMU. The @code{luks} format +should be used instead. + +@item encrypt.key-secret + +Provides the ID of a @code{secret} object that contains the passphrase +(@code{encrypt.format=luks}) or encryption key (@code{encrypt.format=aes}). + +@item encrypt.cipher-alg + +Name of the cipher algorithm and key length. Currently defaults +to @code{aes-256}. Only used when @code{encrypt.format=luks}. + +@item encrypt.cipher-mode + +Name of the encryption mode to use. Currently defaults to @code{xts}. +Only used when @code{encrypt.format=luks}. + +@item encrypt.ivgen-alg + +Name of the initialization vector generator algorithm. Currently defaults +to @code{plain64}. Only used when @code{encrypt.format=luks}. + +@item encrypt.ivgen-hash-alg + +Name of the hash algorithm to use with the initialization vector generator +(if required). Defaults to @code{sha256}. Only used when @code{encrypt.format=luks}. + +@item encrypt.hash-alg + +Name of the hash algorithm to use for PBKDF algorithm +Defaults to @code{sha256}. Only used when @code{encrypt.format=luks}. + +@item encrypt.iter-time + +Amount of time, in milliseconds, to use for PBKDF algorithm per key slot. +Defaults to @code{2000}. Only used when @code{encrypt.format=luks}. @item cluster_size Changes the qcow2 cluster size (must be between 512 and 2M). Smaller cluster
@@ -636,7 +681,69 @@ Supported options: @item backing_file File name of a base image (see @option{create} subcommand) @item encryption -If this option is set to @code{on}, the image is encrypted. +This option is deprecated and equivalent to @code{encrypt.format=aes} + +@item encrypt.format +If this is set to @code{aes}, the image is encrypted with 128-bit AES-CBC. +The encryption key is given by the @code{encrypt.key-secret} parameter. +This encryption format is considered to be flawed by modern cryptography +standards, suffering from a number of design problems enumerated previously +against the @code{qcow2} image format. + +The use of this is no longer supported in system emulators. Support only +remains in the command line utilities, for the purposes of data liberation +and interoperability with old versions of QEMU. + +Users requiring native encryption should use the @code{qcow2} format +instead with @code{encrypt.format=luks}. + +@item encrypt.key-secret + +Provides the ID of a @code{secret} object that contains the encryption +key (@code{encrypt.format=aes}). + +@end table + +@item luks + +LUKS v1 encryption format, compatible with Linux dm-crypt/cryptsetup + +Supported options: +@table @code + +@item key-secret + +Provides the ID of a @code{secret} object that contains the passphrase. + +@item cipher-alg + +Name of the cipher algorithm and key length. Currently defaults +to @code{aes-256}. + +@item cipher-mode + +Name of the encryption mode to use. Currently defaults to @code{xts}. + +@item ivgen-alg + +Name of the initialization vector generator algorithm. Currently defaults +to @code{plain64}. + +@item ivgen-hash-alg + +Name of the hash algorithm to use with the initialization vector generator +(if required). Defaults to @code{sha256}. + +@item hash-alg + +Name of the hash algorithm to use for PBKDF algorithm +Defaults to @code{sha256}. + +@item iter-time + +Amount of time, in milliseconds, to use for PBKDF algorithm per key slot. +Defaults to @code{2000}. + @end table @item vdi
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 062/100] mirror: Fix inconsistent backing AioContext for after mirroring
In reply to Kevin WolfFrom: "sochin.jiang" <[email protected]>
mirror_complete opens the backing chain, which should have the same AioContext as the top when using iothreads. Make the code guarantee this, which fixes a failed assertion in bdrv_attach_child.
Message-id: [email protected]
--- block.c | 1 + 1 file changed, 1 insertion(+)
block.c +1 -0
@@ -2185,6 +2185,7 @@ int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options, ret = -EINVAL ; goto free_exit; } +bdrv_set_aio_context (backing_hd,bdrv_get_aio_context (bs));/* Hook up the backing file link; drop our reference, bs owns the * backing_hd reference now */
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 051/100] qcow2: convert QCow2 to use QCryptoBlock for encryption
In reply to Kevin WolfFrom: "Daniel P. Berrange" <[email protected]>
This converts the qcow2 driver to make use of the QCryptoBlock APIs for encrypting image content, using the legacy QCow2 AES scheme.
With this change it is now required to use the QCryptoSecret object for providing passwords, instead of the current block password APIs / interactive prompting.
$QEMU \
-object secret,id=sec0,file=/home/berrange/encrypted.pw \
-drive file=/home/berrange/encrypted.qcow2,encrypt.key-secret=sec0The test 087 could be simplified since there is no longer a difference in behaviour when using blockdev_add with encrypted images for the running vs stopped CPU state.
Message-id: [email protected]
--- block/qcow2-cluster.c | 47 +--------- block/qcow2.c | 226 ++++++++++++++++++++++++++++++--------------- block/qcow2.h | 5 +- qapi/block-core.json | 27 +++++- tests/qemu-iotests/049 | 2 +- tests/qemu-iotests/049.out | 4 +- tests/qemu-iotests/082.out | 27 ++++++ tests/qemu-iotests/087 | 28 +++--- tests/qemu-iotests/087.out | 12 +-- tests/qemu-iotests/134 | 18 +++- tests/qemu-iotests/134.out | 10 +- tests/qemu-iotests/158 | 19 ++-- tests/qemu-iotests/158.out | 14 +-- tests/qemu-iotests/common | 10 +- 14 files changed, 263 insertions(+), 186 deletions(-)
block/qcow2-cluster.c +3 -44
@@ -357,47 +357,6 @@ static int count_contiguous_clusters_unallocated(int nb_clusters,return i; } -/* The crypt function is compatible with the linux cryptoloop -algorithm for < 4 GB images. */ -int qcow2_encrypt_sectors (BDRVQcow2State *s,int64_t sector_num, -uint8_t *buf,int nb_sectors,bool enc, -Error **errp) -{ -union { -uint64_t ll[2 ]; -uint8_t b[16 ]; - } ivec; -int i; -int ret; - -for (i =0 ; i < nb_sectors; i++) { - ivec.ll[0 ] =cpu_to_le64 (sector_num); - ivec.ll[1 ] =0 ; -if (qcrypto_cipher_setiv (s->cipher, - ivec.b,G_N_ELEMENTS (ivec.b), - errp) <0 ) { -return -1 ; - } -if (enc) { - ret =qcrypto_cipher_encrypt (s->cipher, - buf, buf, -512 , - errp); - }else { - ret =qcrypto_cipher_decrypt (s->cipher, - buf, buf, -512 , - errp); - } -if (ret <0 ) { -return -1 ; - } - sector_num++; - buf +=512 ; - } -return 0 ; -} - static int coroutine_fn do_perform_cow_read(BlockDriverState *bs, uint64_t src_cluster_offset, unsigned offset_in_cluster,
@@ -438,11 +397,11 @@ static bool coroutine_fn do_perform_cow_encrypt(BlockDriverState *bs,BDRVQcow2State *s = bs->opaque;int64_t sector = (src_cluster_offset + offset_in_cluster) >>BDRV_SECTOR_BITS ; -assert (s->cipher);assert ((offset_in_cluster & ~BDRV_SECTOR_MASK ) ==0 );assert ((bytes & ~BDRV_SECTOR_MASK ) ==0 ); -if (qcow2_encrypt_sectors (s, sector, buffer, - bytes >>BDRV_SECTOR_BITS , true,NULL ) <0 ) { +assert (s->crypto); +if (qcrypto_block_encrypt (s->crypto, sector, buffer, + bytes,NULL ) <0 ) {return false; } }
block/qcow2.c +152 -74
414 lines not on this page · raw message
block/qcow2.h +3 -2
@@ -25,7 +25,7 @@#ifndef BLOCK_QCOW2_H #define BLOCK_QCOW2_H -#include "crypto/cipher.h" +#include "crypto/block.h" #include "qemu/coroutine.h" //#define DEBUG_ALLOC
@@ -257,7 +257,8 @@ typedef struct BDRVQcow2State {CoMutex lock; -QCryptoCipher *cipher;/* current cipher, NULL if no key yet */ +QCryptoBlockOpenOptions *crypto_opts;/* Disk encryption runtime options */ +QCryptoBlock *crypto;/* Disk encryption format driver */ uint32_t crypt_method_header;uint64_t snapshots_offset;int snapshots_size;
qapi/block-core.json +25 -2
@@ -2317,6 +2317,26 @@ 'data': { '*encrypt': 'BlockdevQcowEncryption' } } + +## +# @BlockdevQcow2EncryptionFormat: +# @aes: AES-CBC with plain64 initialization venctors +# +# Since: 2.10 +## +{ 'enum': 'BlockdevQcow2EncryptionFormat', + 'data': [ 'aes' ] } + +## +# @BlockdevQcow2Encryption: +# +# Since: 2.10 +## +{ 'union': 'BlockdevQcow2Encryption', + 'base': { 'format': 'BlockdevQcow2EncryptionFormat' }, + 'discriminator': 'format', + 'data': { 'aes': 'QCryptoBlockOptionsQCow' } } + ## # @BlockdevOptionsQcow2: #
@@ -2351,6 +2371,9 @@ # @cache-clean-interval: clean unused entries in the L2 and refcount # caches. The interval is in seconds. The default value # is 0 and it disables this feature (since 2.5) +# @encrypt: Image decryption options. Mandatory for +# encrypted images, except when doing a metadata-only +# probe of the image. (since 2.10) # # Since: 2.9 ##
@@ -2364,8 +2387,8 @@ '*cache-size': 'int', '*l2-cache-size': 'int', '*refcount-cache-size': 'int', - '*cache-clean-interval': 'int' } } - + '*cache-clean-interval': 'int', + '*encrypt': 'BlockdevQcow2Encryption' } } ## # @BlockdevOptionsSsh:
tests/qemu-iotests/049 +1 -1
@@ -106,7 +106,7 @@ test_qemu_img create -f $IMGFMT -o preallocation=1234 "$TEST_IMG" 64M echo "== Check encryption option ==" echo test_qemu_img create -f $IMGFMT -o encryption=off "$TEST_IMG" 64M -test_qemu_img create -f $IMGFMT -o encryption=on "$TEST_IMG" 64M +test_qemu_img create -f $IMGFMT --object secret,id=sec0,data=123456 -o encryption=on,encrypt.key-secret=sec0 "$TEST_IMG" 64M echo "== Check lazy_refcounts option (only with v3) ==" echo
tests/qemu-iotests/049.out +2 -2
@@ -190,8 +190,8 @@ Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 cluster_size=65536 preall qemu-img create -f qcow2 -o encryption=off TEST_DIR/t.qcow2 64M Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16 -qemu-img create -f qcow2 -o encryption=on TEST_DIR/t.qcow2 64M -Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 encryption=on cluster_size=65536 lazy_refcounts=off refcount_bits=16 +qemu-img create -f qcow2 --object secret,id=sec0,data=123456 -o encryption=on,encrypt.key-secret=sec0 TEST_DIR/t.qcow2 64M +Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 encryption=on encrypt.key-secret=sec0 cluster_size=65536 lazy_refcounts=off refcount_bits=16 == Check lazy_refcounts option (only with v3) ==
tests/qemu-iotests/082.out +27 -0
@@ -50,6 +50,7 @@ backing_file File name of a base image backing_fmt Image format of the base image encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes) encrypt.format Encrypt the image, format choices: 'aes' +encrypt.key-secret ID of the secret that provides the AES encryption key cluster_size qcow2 cluster size preallocation Preallocation mode (allowed values: off, metadata, falloc, full) lazy_refcounts Postpone refcount updates
@@ -64,6 +65,7 @@ backing_file File name of a base image backing_fmt Image format of the base image encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes) encrypt.format Encrypt the image, format choices: 'aes' +encrypt.key-secret ID of the secret that provides the AES encryption key cluster_size qcow2 cluster size preallocation Preallocation mode (allowed values: off, metadata, falloc, full) lazy_refcounts Postpone refcount updates
@@ -78,6 +80,7 @@ backing_file File name of a base image backing_fmt Image format of the base image encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes) encrypt.format Encrypt the image, format choices: 'aes' +encrypt.key-secret ID of the secret that provides the AES encryption key cluster_size qcow2 cluster size preallocation Preallocation mode (allowed values: off, metadata, falloc, full) lazy_refcounts Postpone refcount updates
@@ -92,6 +95,7 @@ backing_file File name of a base image backing_fmt Image format of the base image encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes) encrypt.format Encrypt the image, format choices: 'aes' +encrypt.key-secret ID of the secret that provides the AES encryption key cluster_size qcow2 cluster size preallocation Preallocation mode (allowed values: off, metadata, falloc, full) lazy_refcounts Postpone refcount updates
@@ -106,6 +110,7 @@ backing_file File name of a base image backing_fmt Image format of the base image encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes) encrypt.format Encrypt the image, format choices: 'aes' +encrypt.key-secret ID of the secret that provides the AES encryption key cluster_size qcow2 cluster size preallocation Preallocation mode (allowed values: off, metadata, falloc, full) lazy_refcounts Postpone refcount updates
@@ -120,6 +125,7 @@ backing_file File name of a base image backing_fmt Image format of the base image encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes) encrypt.format Encrypt the image, format choices: 'aes' +encrypt.key-secret ID of the secret that provides the AES encryption key cluster_size qcow2 cluster size preallocation Preallocation mode (allowed values: off, metadata, falloc, full) lazy_refcounts Postpone refcount updates
@@ -134,6 +140,7 @@ backing_file File name of a base image backing_fmt Image format of the base image encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes) encrypt.format Encrypt the image, format choices: 'aes' +encrypt.key-secret ID of the secret that provides the AES encryption key cluster_size qcow2 cluster size preallocation Preallocation mode (allowed values: off, metadata, falloc, full) lazy_refcounts Postpone refcount updates
@@ -148,6 +155,7 @@ backing_file File name of a base image backing_fmt Image format of the base image encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes) encrypt.format Encrypt the image, format choices: 'aes' +encrypt.key-secret ID of the secret that provides the AES encryption key cluster_size qcow2 cluster size preallocation Preallocation mode (allowed values: off, metadata, falloc, full) lazy_refcounts Postpone refcount updates
@@ -177,6 +185,7 @@ backing_file File name of a base image backing_fmt Image format of the base image encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes) encrypt.format Encrypt the image, format choices: 'aes' +encrypt.key-secret ID of the secret that provides the AES encryption key cluster_size qcow2 cluster size preallocation Preallocation mode (allowed values: off, metadata, falloc, full) lazy_refcounts Postpone refcount updates
@@ -240,6 +249,7 @@ backing_file File name of a base image backing_fmt Image format of the base image encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes) encrypt.format Encrypt the image, format choices: 'aes' +encrypt.key-secret ID of the secret that provides the AES encryption key cluster_size qcow2 cluster size preallocation Preallocation mode (allowed values: off, metadata, falloc, full) lazy_refcounts Postpone refcount updates
@@ -254,6 +264,7 @@ backing_file File name of a base image backing_fmt Image format of the base image encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes) encrypt.format Encrypt the image, format choices: 'aes' +encrypt.key-secret ID of the secret that provides the AES encryption key cluster_size qcow2 cluster size preallocation Preallocation mode (allowed values: off, metadata, falloc, full) lazy_refcounts Postpone refcount updates
@@ -268,6 +279,7 @@ backing_file File name of a base image backing_fmt Image format of the base image encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes) encrypt.format Encrypt the image, format choices: 'aes' +encrypt.key-secret ID of the secret that provides the AES encryption key cluster_size qcow2 cluster size preallocation Preallocation mode (allowed values: off, metadata, falloc, full) lazy_refcounts Postpone refcount updates
@@ -282,6 +294,7 @@ backing_file File name of a base image backing_fmt Image format of the base image encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes) encrypt.format Encrypt the image, format choices: 'aes' +encrypt.key-secret ID of the secret that provides the AES encryption key cluster_size qcow2 cluster size preallocation Preallocation mode (allowed values: off, metadata, falloc, full) lazy_refcounts Postpone refcount updates
@@ -296,6 +309,7 @@ backing_file File name of a base image backing_fmt Image format of the base image encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes) encrypt.format Encrypt the image, format choices: 'aes' +encrypt.key-secret ID of the secret that provides the AES encryption key cluster_size qcow2 cluster size preallocation Preallocation mode (allowed values: off, metadata, falloc, full) lazy_refcounts Postpone refcount updates
@@ -310,6 +324,7 @@ backing_file File name of a base image backing_fmt Image format of the base image encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes) encrypt.format Encrypt the image, format choices: 'aes' +encrypt.key-secret ID of the secret that provides the AES encryption key cluster_size qcow2 cluster size preallocation Preallocation mode (allowed values: off, metadata, falloc, full) lazy_refcounts Postpone refcount updates
@@ -324,6 +339,7 @@ backing_file File name of a base image backing_fmt Image format of the base image encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes) encrypt.format Encrypt the image, format choices: 'aes' +encrypt.key-secret ID of the secret that provides the AES encryption key cluster_size qcow2 cluster size preallocation Preallocation mode (allowed values: off, metadata, falloc, full) lazy_refcounts Postpone refcount updates
@@ -338,6 +354,7 @@ backing_file File name of a base image backing_fmt Image format of the base image encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes) encrypt.format Encrypt the image, format choices: 'aes' +encrypt.key-secret ID of the secret that provides the AES encryption key cluster_size qcow2 cluster size preallocation Preallocation mode (allowed values: off, metadata, falloc, full) lazy_refcounts Postpone refcount updates
@@ -367,6 +384,7 @@ backing_file File name of a base image backing_fmt Image format of the base image encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes) encrypt.format Encrypt the image, format choices: 'aes' +encrypt.key-secret ID of the secret that provides the AES encryption key cluster_size qcow2 cluster size preallocation Preallocation mode (allowed values: off, metadata, falloc, full) lazy_refcounts Postpone refcount updates
@@ -427,6 +445,7 @@ backing_file File name of a base image backing_fmt Image format of the base image encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes) encrypt.format Encrypt the image, format choices: 'aes' +encrypt.key-secret ID of the secret that provides the AES encryption key cluster_size qcow2 cluster size preallocation Preallocation mode (allowed values: off, metadata, falloc, full) lazy_refcounts Postpone refcount updates
@@ -441,6 +460,7 @@ backing_file File name of a base image backing_fmt Image format of the base image encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes) encrypt.format Encrypt the image, format choices: 'aes' +encrypt.key-secret ID of the secret that provides the AES encryption key cluster_size qcow2 cluster size preallocation Preallocation mode (allowed values: off, metadata, falloc, full) lazy_refcounts Postpone refcount updates
@@ -455,6 +475,7 @@ backing_file File name of a base image backing_fmt Image format of the base image encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes) encrypt.format Encrypt the image, format choices: 'aes' +encrypt.key-secret ID of the secret that provides the AES encryption key cluster_size qcow2 cluster size preallocation Preallocation mode (allowed values: off, metadata, falloc, full) lazy_refcounts Postpone refcount updates
@@ -469,6 +490,7 @@ backing_file File name of a base image backing_fmt Image format of the base image encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes) encrypt.format Encrypt the image, format choices: 'aes' +encrypt.key-secret ID of the secret that provides the AES encryption key cluster_size qcow2 cluster size preallocation Preallocation mode (allowed values: off, metadata, falloc, full) lazy_refcounts Postpone refcount updates
@@ -483,6 +505,7 @@ backing_file File name of a base image backing_fmt Image format of the base image encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes) encrypt.format Encrypt the image, format choices: 'aes' +encrypt.key-secret ID of the secret that provides the AES encryption key cluster_size qcow2 cluster size preallocation Preallocation mode (allowed values: off, metadata, falloc, full) lazy_refcounts Postpone refcount updates
@@ -497,6 +520,7 @@ backing_file File name of a base image backing_fmt Image format of the base image encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes) encrypt.format Encrypt the image, format choices: 'aes' +encrypt.key-secret ID of the secret that provides the AES encryption key cluster_size qcow2 cluster size preallocation Preallocation mode (allowed values: off, metadata, falloc, full) lazy_refcounts Postpone refcount updates
@@ -511,6 +535,7 @@ backing_file File name of a base image backing_fmt Image format of the base image encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes) encrypt.format Encrypt the image, format choices: 'aes' +encrypt.key-secret ID of the secret that provides the AES encryption key cluster_size qcow2 cluster size preallocation Preallocation mode (allowed values: off, metadata, falloc, full) lazy_refcounts Postpone refcount updates
@@ -525,6 +550,7 @@ backing_file File name of a base image backing_fmt Image format of the base image encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes) encrypt.format Encrypt the image, format choices: 'aes' +encrypt.key-secret ID of the secret that provides the AES encryption key cluster_size qcow2 cluster size preallocation Preallocation mode (allowed values: off, metadata, falloc, full) lazy_refcounts Postpone refcount updates
@@ -556,6 +582,7 @@ backing_file File name of a base image backing_fmt Image format of the base image encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes) encrypt.format Encrypt the image, format choices: 'aes' +encrypt.key-secret ID of the secret that provides the AES encryption key cluster_size qcow2 cluster size preallocation Preallocation mode (allowed values: off, metadata, falloc, full) lazy_refcounts Postpone refcount updates
tests/qemu-iotests/087 +13 -15
@@ -122,24 +122,18 @@ echo echo === Encrypted image === echo -_make_test_img -o encryption=on $size -run_qemu -S <<EOF +_make_test_img --object secret,id=sec0,data=123456 -o encryption=on,encrypt.key-secret=sec0 $size +run_qemu <<EOF { "execute": "qmp_capabilities" } -{ "execute": "blockdev-add", +{ "execute": "object-add", "arguments": { - "driver": "$IMGFMT", - "node-name": "disk", - "file": { - "driver": "file", - "filename": "$TEST_IMG" + "qom-type": "secret", + "id": "sec0", + "props": { + "data": "123456" } - } } -{ "execute": "quit" } -EOF - -run_qemu <<EOF -{ "execute": "qmp_capabilities" } +} { "execute": "blockdev-add", "arguments": { "driver": "$IMGFMT",
@@ -147,6 +141,10 @@ run_qemu <<EOF "file": { "driver": "file", "filename": "$TEST_IMG" + }, + "encrypt": { + "format": "aes", + "key-secret": "sec0" } } }
@@ -157,7 +155,7 @@ echo echo === Missing driver === echo -_make_test_img -o encryption=on $size +_make_test_img --object secret,id=sec0,data=123456 -o encryption=on,encrypt.key-secret=sec0 $size run_qemu -S <<EOF { "execute": "qmp_capabilities" } { "execute": "blockdev-add",
tests/qemu-iotests/087.out +3 -9
@@ -34,17 +34,11 @@ QMP_VERSION === Encrypted image === -Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 encryption=on -Testing: -S -QMP_VERSION -{"return": {}} -{"error": {"class": "GenericError", "desc": "Use of AES-CBC encrypted IMGFMT images is no longer supported in system emulators"}} -{"return": {}} -{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "SHUTDOWN", "data": {"guest": false}} - +Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 encryption=on encrypt.key-secret=sec0 Testing: QMP_VERSION {"return": {}} +{"return": {}} {"error": {"class": "GenericError", "desc": "Use of AES-CBC encrypted IMGFMT images is no longer supported in system emulators"}} {"return": {}} {"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "SHUTDOWN", "data": {"guest": false}}
@@ -52,7 +46,7 @@ QMP_VERSION === Missing driver === -Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 encryption=on +Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 encryption=on encrypt.key-secret=sec0 Testing: -S QMP_VERSION {"return": {}}
tests/qemu-iotests/134 +13 -5
@@ -44,23 +44,31 @@ _supported_os Linux size=128M -IMGOPTS="encryption=on" _make_test_img $size + +SECRET="secret,id=sec0,data=astrochicken" +SECRETALT="secret,id=sec0,data=platypus" + +_make_test_img --object $SECRET -o "encryption=on,encrypt.key-secret=sec0" $size + +IMGSPEC="driver=$IMGFMT,file.filename=$TEST_IMG,encrypt.key-secret=sec0" + +QEMU_IO_OPTIONS=$QEMU_IO_OPTIONS_NO_FMT echo echo "== reading whole image ==" -echo "astrochicken" | $QEMU_IO -c "read 0 $size" "$TEST_IMG" | _filter_qemu_io | _filter_testdir +$QEMU_IO --object $SECRET -c "read 0 $size" --image-opts $IMGSPEC | _filter_qemu_io | _filter_testdir echo echo "== rewriting whole image ==" -echo "astrochicken" | $QEMU_IO -c "write -P 0xa 0 $size" "$TEST_IMG" | _filter_qemu_io | _filter_testdir +$QEMU_IO --object $SECRET -c "write -P 0xa 0 $size" --image-opts $IMGSPEC | _filter_qemu_io | _filter_testdir echo echo "== verify pattern ==" -echo "astrochicken" | $QEMU_IO -c "read -P 0xa 0 $size" "$TEST_IMG" | _filter_qemu_io | _filter_testdir +$QEMU_IO --object $SECRET -c "read -P 0xa 0 $size" --image-opts $IMGSPEC | _filter_qemu_io | _filter_testdir echo echo "== verify pattern failure with wrong password ==" -echo "platypus" | $QEMU_IO -c "read -P 0xa 0 $size" "$TEST_IMG" | _filter_qemu_io | _filter_testdir +$QEMU_IO --object $SECRETALT -c "read -P 0xa 0 $size" --image-opts $IMGSPEC | _filter_qemu_io | _filter_testdir # success, all done
tests/qemu-iotests/134.out +1 -9
@@ -1,27 +1,19 @@ QA output created by 134 -Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 encryption=on +Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 encryption=on encrypt.key-secret=sec0 == reading whole image == -Disk image 'TEST_DIR/t.qcow2' is encrypted. -password: read 134217728/134217728 bytes at offset 0 128 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec) == rewriting whole image == -Disk image 'TEST_DIR/t.qcow2' is encrypted. -password: wrote 134217728/134217728 bytes at offset 0 128 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec) == verify pattern == -Disk image 'TEST_DIR/t.qcow2' is encrypted. -password: read 134217728/134217728 bytes at offset 0 128 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec) == verify pattern failure with wrong password == -Disk image 'TEST_DIR/t.qcow2' is encrypted. -password: Pattern verification failed at offset 0, 134217728 bytes read 134217728/134217728 bytes at offset 0 128 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
tests/qemu-iotests/158 +12 -7
@@ -45,34 +45,39 @@ _supported_os Linux size=128M TEST_IMG_BASE=$TEST_IMG.base +SECRET="secret,id=sec0,data=astrochicken" TEST_IMG_SAVE=$TEST_IMG TEST_IMG=$TEST_IMG_BASE echo "== create base ==" -IMGOPTS="encryption=on" _make_test_img $size +_make_test_img --object $SECRET -o "encryption=on,encrypt.key-secret=sec0" $size TEST_IMG=$TEST_IMG_SAVE +IMGSPECBASE="driver=$IMGFMT,file.filename=$TEST_IMG_BASE,encrypt.key-secret=sec0" +IMGSPEC="driver=$IMGFMT,file.filename=$TEST_IMG,backing.driver=$IMGFMT,backing.file.filename=$TEST_IMG_BASE,backing.encrypt.key-secret=sec0,encrypt.key-secret=sec0" +QEMU_IO_OPTIONS=$QEMU_IO_OPTIONS_NO_FMT + echo echo "== writing whole image ==" -echo "astrochicken" | $QEMU_IO -c "write -P 0xa 0 $size" "$TEST_IMG_BASE" | _filter_qemu_io | _filter_testdir +$QEMU_IO --object $SECRET -c "write -P 0xa 0 $size" --image-opts $IMGSPECBASE | _filter_qemu_io | _filter_testdir echo echo "== verify pattern ==" -echo "astrochicken" | $QEMU_IO -c "read -P 0xa 0 $size" "$TEST_IMG_BASE" | _filter_qemu_io | _filter_testdir +$QEMU_IO --object $SECRET -c "read -P 0xa 0 $size" --image-opts $IMGSPECBASE | _filter_qemu_io | _filter_testdir echo "== create overlay ==" -IMGOPTS="encryption=on" _make_test_img -b "$TEST_IMG_BASE" $size +_make_test_img --object $SECRET -o "encryption=on,encrypt.key-secret=sec0" -b "$TEST_IMG_BASE" $size echo echo "== writing part of a cluster ==" -echo "astrochicken" | $QEMU_IO -c "write -P 0xe 0 1024" "$TEST_IMG" | _filter_qemu_io | _filter_testdir +$QEMU_IO --object $SECRET -c "write -P 0xe 0 1024" --image-opts $IMGSPEC | _filter_qemu_io | _filter_testdir echo echo "== verify pattern ==" -echo "astrochicken" | $QEMU_IO -c "read -P 0xe 0 1024" "$TEST_IMG" | _filter_qemu_io | _filter_testdir +$QEMU_IO --object $SECRET -c "read -P 0xe 0 1024" --image-opts $IMGSPEC | _filter_qemu_io | _filter_testdir echo echo "== verify pattern ==" -echo "astrochicken" | $QEMU_IO -c "read -P 0xa 1024 64512" "$TEST_IMG" | _filter_qemu_io | _filter_testdir +$QEMU_IO --object $SECRET -c "read -P 0xa 1024 64512" --image-opts $IMGSPEC | _filter_qemu_io | _filter_testdir # success, all done
tests/qemu-iotests/158.out +2 -12
@@ -1,36 +1,26 @@ QA output created by 158 == create base == -Formatting 'TEST_DIR/t.IMGFMT.base', fmt=IMGFMT size=134217728 encryption=on +Formatting 'TEST_DIR/t.IMGFMT.base', fmt=IMGFMT size=134217728 encryption=on encrypt.key-secret=sec0 == writing whole image == -Disk image 'TEST_DIR/t.qcow2.base' is encrypted. -password: wrote 134217728/134217728 bytes at offset 0 128 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec) == verify pattern == -Disk image 'TEST_DIR/t.qcow2.base' is encrypted. -password: read 134217728/134217728 bytes at offset 0 128 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec) == create overlay == -Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 backing_file=TEST_DIR/t.IMGFMT.base encryption=on +Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 backing_file=TEST_DIR/t.IMGFMT.base encryption=on encrypt.key-secret=sec0 == writing part of a cluster == -Disk image 'TEST_DIR/t.qcow2' is encrypted. -password: wrote 1024/1024 bytes at offset 0 1 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec) == verify pattern == -Disk image 'TEST_DIR/t.qcow2' is encrypted. -password: read 1024/1024 bytes at offset 0 1 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec) == verify pattern == -Disk image 'TEST_DIR/t.qcow2' is encrypted. -password: read 64512/64512 bytes at offset 1024 63 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec) *** done
tests/qemu-iotests/common +6 -4
@@ -50,6 +50,7 @@ export IMGPROTO=file export IMGOPTS="" export CACHEMODE="writeback" export QEMU_IO_OPTIONS="" +export QEMU_IO_OPTIONS_NO_FMT="" export CACHEMODE_IS_DEFAULT=true export QEMU_OPTIONS="-nodefaults -machine accel=qtest" export VALGRIND_QEMU=
@@ -413,10 +414,11 @@ BEGIN { for (t='$start'; t<='$end'; t++) printf "%03d\n",t }' \ done # Set qemu-io cache mode with $CACHEMODE we have -if [ "$IMGOPTSSYNTAX" = "true" ]; then - QEMU_IO_OPTIONS="$QEMU_IO_OPTIONS --cache $CACHEMODE" -else - QEMU_IO_OPTIONS="$QEMU_IO_OPTIONS -f $IMGFMT --cache $CACHEMODE" +QEMU_IO_OPTIONS="$QEMU_IO_OPTIONS --cache $CACHEMODE" + +QEMU_IO_OPTIONS_NO_FMT="$QEMU_IO_OPTIONS" +if [ "$IMGOPTSSYNTAX" != "true" ]; then + QEMU_IO_OPTIONS="$QEMU_IO_OPTIONS -f $IMGFMT" fi # Set default options for qemu-img create -o if they were not specified
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 063/100] specs/qcow2: fix bitmap granularity qemu-specific note
In reply to Kevin WolfFrom: Vladimir Sementsov-Ogievskiy <[email protected]>
Message-id: [email protected]
--- docs/interop/qcow2.txt | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
docs/interop/qcow2.txt +1 -2
@@ -575,8 +575,7 @@ Structure of a bitmap directory entry: 17: granularity_bits Granularity bits. Valid values: 0 - 63. - Note: Qemu currently doesn't support granularity_bits - greater than 31. + Note: Qemu currently supports only values 9 - 31. Granularity is calculated as granularity = 1 << granularity_bits
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 064/100] specs/qcow2: do not use wording 'bitmap header'
In reply to Kevin WolfFrom: Vladimir Sementsov-Ogievskiy <[email protected]>
A bitmap directory entry is sometimes called a 'bitmap header'. This patch leaves only one name - 'bitmap directory entry'. The name 'bitmap header' creates misunderstandings with 'qcow2 header' and 'qcow2 bitmap header extension' (which is extension of qcow2 header)
Message-id: [email protected]
--- docs/interop/qcow2.txt | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-)
docs/interop/qcow2.txt +2 -3
@@ -203,7 +203,7 @@ The fields of the bitmaps extension are: 8 - 15: bitmap_directory_size Size of the bitmap directory in bytes. It is the cumulative - size of all (nb_bitmaps) bitmap headers. + size of all (nb_bitmaps) bitmap directory entries. 16 - 23: bitmap_directory_offset Offset into the image file at which the bitmap directory
@@ -529,8 +529,7 @@ Each bitmap saved in the image is described in a bitmap directory entry. The bitmap directory is a contiguous area in the image file, whose starting offset and length are given by the header extension fields bitmap_directory_offset and bitmap_directory_size. The entries of the bitmap directory have variable -length, depending on the lengths of the bitmap name and extra data. These -entries are also called bitmap headers. +length, depending on the lengths of the bitmap name and extra data. Structure of a bitmap directory entry:
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 066/100] tests: add hbitmap iter test
In reply to Kevin WolfFrom: Vladimir Sementsov-Ogievskiy <[email protected]>
Test that hbitmap iter is resistant to bitmap resetting.
Message-id: [email protected]
--- tests/test-hbitmap.c | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+)
tests/test-hbitmap.c +19 -0
@@ -909,6 +909,22 @@ static void hbitmap_test_add(const char *testpath, hbitmap_test_teardown); } +static void test_hbitmap_iter_and_reset (TestHBitmapData *data, +const void *unused) +{ +HBitmapIter hbi; + +hbitmap_test_init (data,L1 *2 ,0 ); +hbitmap_set (data->hb,0 , data->size); + +hbitmap_iter_init (&hbi, data->hb,BITS_PER_LONG -1 ); + +hbitmap_iter_next (&hbi); + +hbitmap_reset_all (data->hb); +hbitmap_iter_next (&hbi); +} +int main (int argc,char **argv) {g_test_init (&argc, &argv,NULL );
@@ -966,6 +982,9 @@ int main(int argc, char **argv) test_hbitmap_serialize_part);hbitmap_test_add ("/hbitmap/serialize/zeroes" , test_hbitmap_serialize_zeroes); + +hbitmap_test_add ("/hbitmap/iter/iter_and_reset" , + test_hbitmap_iter_and_reset);g_test_run ();return 0 ;
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 067/100] block: fix bdrv_dirty_bitmap_granularity signature
In reply to Kevin WolfFrom: Vladimir Sementsov-Ogievskiy <[email protected]>
Make getter signature const-correct. This allows other functions with const dirty bitmap parameter use bdrv_dirty_bitmap_granularity().
Message-id: [email protected]
--- block/dirty-bitmap.c | 2 +- include/block/dirty-bitmap.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-)
block/dirty-bitmap.c +1 -1
@@ -455,7 +455,7 @@ uint32_t bdrv_get_default_bitmap_granularity(BlockDriverState *bs)return granularity; } -uint32_t bdrv_dirty_bitmap_granularity (BdrvDirtyBitmap *bitmap) +uint32_t bdrv_dirty_bitmap_granularity (const BdrvDirtyBitmap *bitmap) {return BDRV_SECTOR_SIZE <<hbitmap_granularity (bitmap->bitmap); }
include/block/dirty-bitmap.h +1 -1
@@ -29,7 +29,7 @@ void bdrv_disable_dirty_bitmap(BdrvDirtyBitmap *bitmap);void bdrv_enable_dirty_bitmap (BdrvDirtyBitmap *bitmap);BlockDirtyInfoList *bdrv_query_dirty_bitmaps (BlockDriverState *bs);uint32_t bdrv_get_default_bitmap_granularity (BlockDriverState *bs); -uint32_t bdrv_dirty_bitmap_granularity (BdrvDirtyBitmap *bitmap); +uint32_t bdrv_dirty_bitmap_granularity (const BdrvDirtyBitmap *bitmap);uint32_t bdrv_dirty_bitmap_meta_granularity (BdrvDirtyBitmap *bitmap);bool bdrv_dirty_bitmap_enabled (BdrvDirtyBitmap *bitmap);bool bdrv_dirty_bitmap_frozen (BdrvDirtyBitmap *bitmap);
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 068/100] block/dirty-bitmap: add deserialize_ones func
In reply to Kevin WolfFrom: Vladimir Sementsov-Ogievskiy <[email protected]>
Add bdrv_dirty_bitmap_deserialize_ones() function, which is needed for qcow2 bitmap loading, to handle unallocated bitmap parts, marked as all-ones.
Message-id: [email protected]
--- block/dirty-bitmap.c | 7 +++++++ include/block/dirty-bitmap.h | 3 +++ include/qemu/hbitmap.h | 15 +++++++++++++++ util/hbitmap.c | 17 +++++++++++++++++ 4 files changed, 42 insertions(+)
block/dirty-bitmap.c +7 -0
@@ -586,6 +586,13 @@ void bdrv_dirty_bitmap_deserialize_zeroes(BdrvDirtyBitmap *bitmap,hbitmap_deserialize_zeroes (bitmap->bitmap, start, count, finish); } +void bdrv_dirty_bitmap_deserialize_ones (BdrvDirtyBitmap *bitmap, +uint64_t start,uint64_t count, +bool finish) +{ +hbitmap_deserialize_ones (bitmap->bitmap, start, count, finish); +} +void bdrv_dirty_bitmap_deserialize_finish (BdrvDirtyBitmap *bitmap) {hbitmap_deserialize_finish (bitmap->bitmap);
include/block/dirty-bitmap.h +3 -0
@@ -66,6 +66,9 @@ void bdrv_dirty_bitmap_deserialize_part(BdrvDirtyBitmap *bitmap,void bdrv_dirty_bitmap_deserialize_zeroes (BdrvDirtyBitmap *bitmap,uint64_t start,uint64_t count,bool finish); +void bdrv_dirty_bitmap_deserialize_ones (BdrvDirtyBitmap *bitmap, +uint64_t start,uint64_t count, +bool finish);void bdrv_dirty_bitmap_deserialize_finish (BdrvDirtyBitmap *bitmap);/* Functions that require manual locking. */
include/qemu/hbitmap.h +15 -0
@@ -229,6 +229,21 @@ void hbitmap_deserialize_zeroes(HBitmap *hb, uint64_t start, uint64_t count, bool finish);/** +* hbitmap_deserialize_ones +* @hb: HBitmap to operate on. +* @start: First bit to restore. +* @count: Number of bits to restore. +* @finish: Whether to call hbitmap_deserialize_finish automatically. +* +* Fills the bitmap with ones. +* +* If @finish is false, caller must call hbitmap_serialize_finish before using +* the bitmap. +*/ +void hbitmap_deserialize_ones (HBitmap *hb,uint64_t start,uint64_t count, +bool finish); + +/** * hbitmap_deserialize_finish * @hb: HBitmap to operate on. *
util/hbitmap.c +17 -0
@@ -551,6 +551,23 @@ void hbitmap_deserialize_zeroes(HBitmap *hb, uint64_t start, uint64_t count, } } +void hbitmap_deserialize_ones (HBitmap *hb,uint64_t start,uint64_t count, +bool finish) +{ +uint64_t el_count; +unsigned long *first; + +if (!count) { +return ; + } +serialization_chunk (hb, start, count, &first, &el_count); + +memset (first,0xff , el_count *sizeof (unsigned long )); +if (finish) { +hbitmap_deserialize_finish (hb); + } +} +void hbitmap_deserialize_finish (HBitmap *bitmap) {int64_t i, size, prev_size;
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 053/100] qcow2: add support for LUKS encryption format
In reply to Kevin WolfFrom: "Daniel P. Berrange" <[email protected]>
This adds support for using LUKS as an encryption format with the qcow2 file, using the new encrypt.format parameter to request "luks" format. e.g.
# qemu-img create --object secret,data=123456,id=sec0 \
-f qcow2 -o encrypt.format=luks,encrypt.key-secret=sec0 \
test.qcow2 10GThe legacy "encryption=on" parameter still results in creation of the old qcow2 AES format (and is equivalent to the new 'encryption-format=aes'). e.g. the following are equivalent:
# qemu-img create --object secret,data=123456,id=sec0 \
-f qcow2 -o encryption=on,encrypt.key-secret=sec0 \
test.qcow2 10G # qemu-img create --object secret,data=123456,id=sec0 \
-f qcow2 -o encryption-format=aes,encrypt.key-secret=sec0 \
test.qcow2 10GWith the LUKS format it is necessary to store the LUKS partition header and key material in the QCow2 file. This data can be many MB in size, so cannot go into the QCow2 header region directly. Thus the spec defines a FDE (Full Disk Encryption) header extension that specifies the offset of a set of clusters to hold the FDE headers, as well as the length of that region. The LUKS header is thus stored in these extra allocated clusters before the main image payload.
Aside from all the cryptographic differences implied by use of the LUKS format, there is one further key difference between the use of legacy AES and LUKS encryption in qcow2. For LUKS, the initialiazation vectors are generated using the host physical sector as the input, rather than the guest virtual sector. This guarantees unique initialization vectors for all sectors when qcow2 internal snapshots are used, thus giving stronger protection against watermarking attacks.
Message-id: [email protected]
--- block/qcow2-cluster.c | 14 ++- block/qcow2-refcount.c | 10 ++ block/qcow2.c | 268 ++++++++++++++++++++++++++++++++++++++------ block/qcow2.h | 9 ++ qapi/block-core.json | 5 +- tests/qemu-iotests/082.out | 270 ++++++++++++++++++++++++++++++++++++--------- 6 files changed, 484 insertions(+), 92 deletions(-)
block/qcow2-cluster.c +9 -5
@@ -389,13 +389,16 @@ static int coroutine_fn do_perform_cow_read(BlockDriverState *bs, static bool coroutine_fn do_perform_cow_encrypt(BlockDriverState *bs,uint64_t src_cluster_offset, +uint64_t cluster_offset,unsigned offset_in_cluster,uint8_t *buffer,unsigned bytes) {if (bytes && bs->encrypted) {BDRVQcow2State *s = bs->opaque; -int64_t sector = (src_cluster_offset + offset_in_cluster) +int64_t sector = (s->crypt_physical_offset ? + (cluster_offset + offset_in_cluster) : + (src_cluster_offset + offset_in_cluster)) >>BDRV_SECTOR_BITS ;assert ((offset_in_cluster & ~BDRV_SECTOR_MASK ) ==0 );assert ((bytes & ~BDRV_SECTOR_MASK ) ==0 );
@@ -788,10 +791,11 @@ static int perform_cow(BlockDriverState *bs, QCowL2Meta *m)/* Encrypt the data if necessary before writing it */ if (bs->encrypted) { -if (!do_perform_cow_encrypt (bs, m->offset, start->offset, - start_buffer, start->nb_bytes) || - !do_perform_cow_encrypt (bs, m->offset, end->offset, - end_buffer, end->nb_bytes)) { +if (!do_perform_cow_encrypt (bs, m->offset, m->alloc_offset, + start->offset, start_buffer, + start->nb_bytes) || + !do_perform_cow_encrypt (bs, m->offset, m->alloc_offset, + end->offset, end_buffer, end->nb_bytes)) { ret = -EIO ; goto fail; }
block/qcow2-refcount.c +10 -0
@@ -1856,6 +1856,16 @@ static int calculate_refcounts(BlockDriverState *bs, BdrvCheckResult *res,return ret; } +/* encryption */ +if (s->crypto_header.length) { + ret =inc_refcounts (bs, res, refcount_table, nb_clusters, + s->crypto_header.offset, + s->crypto_header.length); +if (ret <0 ) { +return ret; + } + } +return check_refblocks (bs, res, fix, rebuild, refcount_table, nb_clusters); }
block/qcow2.c +237 -31
394 lines not on this page · raw message
block/qcow2.h +9 -0
@@ -36,6 +36,7 @@#define QCOW_CRYPT_NONE 0#define QCOW_CRYPT_AES 1 +#define QCOW_CRYPT_LUKS 2#define QCOW_MAX_CRYPT_CLUSTERS 32#define QCOW_MAX_SNAPSHOTS 65536
@@ -163,6 +164,11 @@ typedef struct QCowSnapshot {struct Qcow2Cache ;typedef struct Qcow2Cache Qcow2Cache ; +typedef struct Qcow2CryptoHeaderExtension { +uint64_t offset; +uint64_t length; +} QEMU_PACKED Qcow2CryptoHeaderExtension; + typedef struct Qcow2UnknownHeaderExtension { uint32_t magic; uint32_t len;
@@ -257,8 +263,11 @@ typedef struct BDRVQcow2State {CoMutex lock; +Qcow2CryptoHeaderExtension crypto_header;/* QCow2 header extension */ QCryptoBlockOpenOptions *crypto_opts;/* Disk encryption runtime options */ QCryptoBlock *crypto;/* Disk encryption format driver */ +bool crypt_physical_offset;/* Whether to use virtual or physical offset +for encryption initialization vector tweak */ uint32_t crypt_method_header;uint64_t snapshots_offset;int snapshots_size;
qapi/block-core.json +3 -2
@@ -2325,7 +2325,7 @@ # Since: 2.10 ## { 'enum': 'BlockdevQcow2EncryptionFormat', - 'data': [ 'aes' ] } + 'data': [ 'aes', 'luks' ] } ## # @BlockdevQcow2Encryption:
@@ -2335,7 +2335,8 @@ { 'union': 'BlockdevQcow2Encryption', 'base': { 'format': 'BlockdevQcow2EncryptionFormat' }, 'discriminator': 'format', - 'data': { 'aes': 'QCryptoBlockOptionsQCow' } } + 'data': { 'aes': 'QCryptoBlockOptionsQCow', + 'luks': 'QCryptoBlockOptionsLUKS'} } ## # @BlockdevOptionsQcow2:
tests/qemu-iotests/082.out +216 -54
432 lines not on this page · raw message
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 069/100] qcow2-refcount: rename inc_refcounts() and make it public
In reply to Kevin WolfFrom: Vladimir Sementsov-Ogievskiy <[email protected]>
This is needed for the following patch, which will introduce refcounts checking for qcow2 bitmaps.
Message-id: [email protected] [mreitz: s/inc_refcounts/qcow2_inc_refcounts_imrt/ in one more (new)
place]
--- block/qcow2-refcount.c | 59 ++++++++++++++++++++++++++------------------------ block/qcow2.h | 4 ++++ 2 files changed, 35 insertions(+), 28 deletions(-)
block/qcow2-refcount.c +31 -28
@@ -1323,11 +1323,10 @@ static int realloc_refcount_array(BDRVQcow2State *s, void **array,* * Modifies the number of errors in res. */ -static int inc_refcounts (BlockDriverState *bs, -BdrvCheckResult *res, -void **refcount_table, -int64_t *refcount_table_size, -int64_t offset,int64_t size) +int qcow2_inc_refcounts_imrt (BlockDriverState *bs,BdrvCheckResult *res, +void **refcount_table, +int64_t *refcount_table_size, +int64_t offset,int64_t size) {BDRVQcow2State *s = bs->opaque;uint64_t start, last, cluster_offset, k, refcount;
@@ -1420,8 +1419,9 @@ static int check_refcounts_l2(BlockDriverState *bs, BdrvCheckResult *res, nb_csectors = ((l2_entry >> s->csize_shift) & s->csize_mask) +1 ; l2_entry &= s->cluster_offset_mask; - ret =inc_refcounts (bs, res, refcount_table, refcount_table_size, - l2_entry & ~511 , nb_csectors *512 ); + ret =qcow2_inc_refcounts_imrt (bs, res, + refcount_table, refcount_table_size, + l2_entry & ~511 , nb_csectors *512 );if (ret <0 ) { goto fail; }
@@ -1454,8 +1454,9 @@ static int check_refcounts_l2(BlockDriverState *bs, BdrvCheckResult *res, }/* Mark cluster as used */ - ret =inc_refcounts (bs, res, refcount_table, refcount_table_size, - offset, s->cluster_size); + ret =qcow2_inc_refcounts_imrt (bs, res, + refcount_table, refcount_table_size, + offset, s->cluster_size);if (ret <0 ) { goto fail; }
@@ -1508,8 +1509,8 @@ static int check_refcounts_l1(BlockDriverState *bs, l1_size2 = l1_size *sizeof (uint64_t );/* Mark L1 table as used */ - ret =inc_refcounts (bs, res, refcount_table, refcount_table_size, - l1_table_offset, l1_size2); + ret =qcow2_inc_refcounts_imrt (bs, res, refcount_table, refcount_table_size, + l1_table_offset, l1_size2);if (ret <0 ) { goto fail; }
@@ -1538,8 +1539,9 @@ static int check_refcounts_l1(BlockDriverState *bs,if (l2_offset) {/* Mark L2 table as used */ l2_offset &=L1E_OFFSET_MASK ; - ret =inc_refcounts (bs, res, refcount_table, refcount_table_size, - l2_offset, s->cluster_size); + ret =qcow2_inc_refcounts_imrt (bs, res, + refcount_table, refcount_table_size, + l2_offset, s->cluster_size);if (ret <0 ) { goto fail; }
@@ -1757,14 +1759,15 @@ static int check_refblocks(BlockDriverState *bs, BdrvCheckResult *res, } res->corruptions_fixed++; - ret =inc_refcounts (bs, res, refcount_table, nb_clusters, - offset, s->cluster_size); + ret =qcow2_inc_refcounts_imrt (bs, res, + refcount_table, nb_clusters, + offset, s->cluster_size);if (ret <0 ) {return ret; }/* No need to check whether the refcount is now greater than 1: * This area was just allocated and zeroed, so it can only be -* exactly 1 after inc_refcounts() */ +* exactly 1 after qcow2_inc_refcounts_imrt() */ continue ; resize_fail:
@@ -1779,8 +1782,8 @@ resize_fail: }if (offset !=0 ) { - ret =inc_refcounts (bs, res, refcount_table, nb_clusters, - offset, s->cluster_size); + ret =qcow2_inc_refcounts_imrt (bs, res, refcount_table, nb_clusters, + offset, s->cluster_size);if (ret <0 ) {return ret; }
@@ -1820,8 +1823,8 @@ static int calculate_refcounts(BlockDriverState *bs, BdrvCheckResult *res, }/* header */ - ret =inc_refcounts (bs, res, refcount_table, nb_clusters, -0 , s->cluster_size); + ret =qcow2_inc_refcounts_imrt (bs, res, refcount_table, nb_clusters, +0 , s->cluster_size);if (ret <0 ) {return ret; }
@@ -1842,25 +1845,25 @@ static int calculate_refcounts(BlockDriverState *bs, BdrvCheckResult *res,return ret; } } - ret =inc_refcounts (bs, res, refcount_table, nb_clusters, - s->snapshots_offset, s->snapshots_size); + ret =qcow2_inc_refcounts_imrt (bs, res, refcount_table, nb_clusters, + s->snapshots_offset, s->snapshots_size);if (ret <0 ) {return ret; }/* refcount data */ - ret =inc_refcounts (bs, res, refcount_table, nb_clusters, - s->refcount_table_offset, - s->refcount_table_size *sizeof (uint64_t )); + ret =qcow2_inc_refcounts_imrt (bs, res, refcount_table, nb_clusters, + s->refcount_table_offset, + s->refcount_table_size *sizeof (uint64_t ));if (ret <0 ) {return ret; }/* encryption */ if (s->crypto_header.length) { - ret =inc_refcounts (bs, res, refcount_table, nb_clusters, - s->crypto_header.offset, - s->crypto_header.length); + ret =qcow2_inc_refcounts_imrt (bs, res, refcount_table, nb_clusters, + s->crypto_header.offset, + s->crypto_header.length);if (ret <0 ) {return ret; }
block/qcow2.h +4 -0
@@ -544,6 +544,10 @@ int qcow2_check_metadata_overlap(BlockDriverState *bs, int ign, int64_t offset, int64_t size);int qcow2_pre_write_overlap_check (BlockDriverState *bs,int ign,int64_t offset,int64_t size); +int qcow2_inc_refcounts_imrt (BlockDriverState *bs,BdrvCheckResult *res, +void **refcount_table, +int64_t *refcount_table_size, +int64_t offset,int64_t size); int qcow2_change_refcount_order(BlockDriverState *bs, int refcount_order, BlockDriverAmendStatusCB *status_cb,
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 065/100] hbitmap: improve dirty iter
In reply to Kevin WolfFrom: Vladimir Sementsov-Ogievskiy <[email protected]>
Make dirty iter resistant to resetting bits in corresponding HBitmap.
Message-id: [email protected]
--- include/qemu/hbitmap.h | 26 ++++---------------------- util/hbitmap.c | 23 ++++++++++++++++++++++- 2 files changed, 26 insertions(+), 23 deletions(-)
include/qemu/hbitmap.h +4 -22
@@ -256,10 +256,9 @@ void hbitmap_free(HBitmap *hb);* the lowest-numbered bit that is set in @hb, starting at @first. * * Concurrent setting of bits is acceptable, and will at worst cause the -* iteration to miss some of those bits. Resetting bits before the current -* position of the iterator is also okay. However, concurrent resetting of -* bits can lead to unexpected behavior if the iterator has not yet reached -* those bits. +* iteration to miss some of those bits. +* +* The concurrent resetting of bits is OK. */ void hbitmap_iter_init (HBitmapIter *hbi,const HBitmap *hb,uint64_t first);
@@ -298,24 +297,7 @@ void hbitmap_free_meta(HBitmap *hb);* Return the next bit that is set in @hbi's associated HBitmap, * or -1 if all remaining bits are zero. */ -static inline int64_t hbitmap_iter_next (HBitmapIter *hbi) -{ -unsigned long cur = hbi->cur[HBITMAP_LEVELS -1 ]; -int64_t item; - -if (cur ==0 ) { - cur =hbitmap_iter_skip_words (hbi); -if (cur ==0 ) { -return -1 ; - } - } - -/* The next call will resume work from the next bit. */ - hbi->cur[HBITMAP_LEVELS -1 ] = cur & (cur -1 ); - item = ((uint64_t )hbi->pos <<BITS_PER_LEVEL ) +ctzl (cur); - -return item << hbi->granularity; -} +int64_t hbitmap_iter_next (HBitmapIter *hbi);/** * hbitmap_iter_next_word:
util/hbitmap.c +22 -1
@@ -106,8 +106,9 @@ unsigned long hbitmap_iter_skip_words(HBitmapIter *hbi)unsigned long cur;do { - cur = hbi->cur[--i]; + i--; pos >>=BITS_PER_LEVEL ; + cur = hbi->cur[i] & hb->levels[i][pos]; }while (cur ==0 );/* Check for end of iteration. We always use fewer than BITS_PER_LONG
@@ -139,6 +140,26 @@ unsigned long hbitmap_iter_skip_words(HBitmapIter *hbi)return cur; } +int64_t hbitmap_iter_next (HBitmapIter *hbi) +{ +unsigned long cur = hbi->cur[HBITMAP_LEVELS -1 ] & + hbi->hb->levels[HBITMAP_LEVELS -1 ][hbi->pos]; +int64_t item; + +if (cur ==0 ) { + cur =hbitmap_iter_skip_words (hbi); +if (cur ==0 ) { +return -1 ; + } + } + +/* The next call will resume work from the next bit. */ + hbi->cur[HBITMAP_LEVELS -1 ] = cur & (cur -1 ); + item = ((uint64_t )hbi->pos <<BITS_PER_LEVEL ) +ctzl (cur); + +return item << hbi->granularity; +} +void hbitmap_iter_init (HBitmapIter *hbi,const HBitmap *hb,uint64_t first) {unsigned i, bit;
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 071/100] block/dirty-bitmap: fix comment for BlockDirtyBitmap.disabled field
In reply to Kevin WolfFrom: Vladimir Sementsov-Ogievskiy <[email protected]>
Message-id: [email protected]
--- block/dirty-bitmap.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
block/dirty-bitmap.c +2 -1
@@ -43,7 +43,8 @@ struct BdrvDirtyBitmap {BdrvDirtyBitmap *successor;/* Anonymous child; implies frozen status */ char *name;/* Optional non-empty unique ID */ int64_t size;/* Size of the bitmap (Number of sectors) */ -bool disabled;/* Bitmap is read-only */ +bool disabled;/* Bitmap is disabled. It ignores all writes to +the device */ int active_iterators;/* How many iterators are active */ QLIST_ENTRY (BdrvDirtyBitmap) list; };
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 072/100] block/dirty-bitmap: add readonly field to BdrvDirtyBitmap
In reply to Kevin WolfFrom: Vladimir Sementsov-Ogievskiy <[email protected]>
It will be needed in following commits for persistent bitmaps. If bitmap is loaded from read-only storage (and we can't mark it "in use" in this storage) corresponding BdrvDirtyBitmap should be read-only.
Message-id: [email protected]
--- block/dirty-bitmap.c | 36 ++++++++++++++++++++++++++++++++++++ block/io.c | 8 ++++++++ blockdev.c | 6 ++++++ include/block/dirty-bitmap.h | 4 ++++ 4 files changed, 54 insertions(+)
block/dirty-bitmap.c +36 -0
@@ -46,6 +46,12 @@ struct BdrvDirtyBitmap {bool disabled;/* Bitmap is disabled. It ignores all writes to the device */ int active_iterators;/* How many iterators are active */ +bool readonly;/* Bitmap is read-only. This field also +prevents the respective image from being +modified (i.e. blocks writes and discards). +Such operations must fail and both the image +and this bitmap must remain unchanged while +this flag is set. */ QLIST_ENTRY (BdrvDirtyBitmap) list; };
@@ -505,6 +511,7 @@ void bdrv_set_dirty_bitmap_locked(BdrvDirtyBitmap *bitmap, int64_t cur_sector, int64_t nr_sectors) {assert (bdrv_dirty_bitmap_enabled (bitmap )); +assert (!bdrv_dirty_bitmap_readonly (bitmap));hbitmap_set (bitmap->bitmap, cur_sector, nr_sectors); }
@@ -521,6 +528,7 @@ void bdrv_reset_dirty_bitmap_locked(BdrvDirtyBitmap *bitmap, int64_t cur_sector, int64_t nr_sectors) {assert (bdrv_dirty_bitmap_enabled (bitmap )); +assert (!bdrv_dirty_bitmap_readonly (bitmap));hbitmap_reset (bitmap->bitmap, cur_sector, nr_sectors); }
@@ -535,6 +543,7 @@ void bdrv_reset_dirty_bitmap(BdrvDirtyBitmap *bitmap,void bdrv_clear_dirty_bitmap (BdrvDirtyBitmap *bitmap,HBitmap **out) {assert (bdrv_dirty_bitmap_enabled (bitmap)); +assert (!bdrv_dirty_bitmap_readonly (bitmap));bdrv_dirty_bitmap_lock (bitmap);if (!out) {hbitmap_reset_all (bitmap->bitmap);
@@ -551,6 +560,7 @@ void bdrv_undo_clear_dirty_bitmap(BdrvDirtyBitmap *bitmap, HBitmap *in) {HBitmap *tmp = bitmap->bitmap;assert (bdrv_dirty_bitmap_enabled (bitmap)); +assert (!bdrv_dirty_bitmap_readonly (bitmap)); bitmap->bitmap = in;hbitmap_free (tmp); }
@@ -613,6 +623,7 @@ void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,if (!bdrv_dirty_bitmap_enabled (bitmap)) {continue ; } +assert (!bdrv_dirty_bitmap_readonly (bitmap));hbitmap_set (bitmap->bitmap, cur_sector, nr_sectors); }bdrv_dirty_bitmaps_unlock (bs);
@@ -635,3 +646,28 @@ int64_t bdrv_get_meta_dirty_count(BdrvDirtyBitmap *bitmap) {return hbitmap_count (bitmap->meta); } + +bool bdrv_dirty_bitmap_readonly (const BdrvDirtyBitmap *bitmap) +{ +return bitmap->readonly; +} + +/* Called with BQL taken. */ +void bdrv_dirty_bitmap_set_readonly (BdrvDirtyBitmap *bitmap,bool value) +{ +qemu_mutex_lock (bitmap->mutex); + bitmap->readonly = value; +qemu_mutex_unlock (bitmap->mutex); +} + +bool bdrv_has_readonly_bitmaps (BlockDriverState *bs) +{ +BdrvDirtyBitmap *bm; + QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) { +if (bm->readonly) { +return true; + } + } + +return false; +}
block/io.c +8 -0
@@ -1315,6 +1315,10 @@ static int coroutine_fn bdrv_aligned_pwritev(BdrvChild *child,uint64_t bytes_remaining = bytes;int max_transfer; +if (bdrv_has_readonly_bitmaps (bs)) { +return -EPERM ; + } +assert (is_power_of_2 (align));assert ((offset & (align -1 )) ==0 );assert ((bytes & (align -1 )) ==0 );
@@ -2287,6 +2291,10 @@ int coroutine_fn bdrv_co_pdiscard(BlockDriverState *bs, int64_t offset,return -ENOMEDIUM ; } +if (bdrv_has_readonly_bitmaps (bs)) { +return -EPERM ; + } + ret =bdrv_check_byte_request (bs, offset, bytes);if (ret <0 ) {return ret;
blockdev.c +6 -0
@@ -2033,6 +2033,9 @@ static void block_dirty_bitmap_clear_prepare(BlkActionState *common, }else if (!bdrv_dirty_bitmap_enabled (state->bitmap)) {error_setg (errp,"Cannot clear a disabled bitmap" );return ; + }else if (bdrv_dirty_bitmap_readonly (state->bitmap)) { +error_setg (errp,"Cannot clear a readonly bitmap" ); +return ; }bdrv_clear_dirty_bitmap (state->bitmap, &state->backup);
@@ -2779,6 +2782,9 @@ void qmp_block_dirty_bitmap_clear(const char *node, const char *name,"Bitmap '%s' is currently disabled and cannot be cleared" , name);return ; + }else if (bdrv_dirty_bitmap_readonly (bitmap)) { +error_setg (errp,"Bitmap '%s' is readonly and cannot be cleared" , name); +return ; }bdrv_clear_dirty_bitmap (bitmap,NULL );
include/block/dirty-bitmap.h +4 -0
@@ -71,6 +71,8 @@ void bdrv_dirty_bitmap_deserialize_ones(BdrvDirtyBitmap *bitmap, bool finish);void bdrv_dirty_bitmap_deserialize_finish (BdrvDirtyBitmap *bitmap); +void bdrv_dirty_bitmap_set_readonly (BdrvDirtyBitmap *bitmap,bool value); +/* Functions that require manual locking. */ void bdrv_dirty_bitmap_lock (BdrvDirtyBitmap *bitmap);void bdrv_dirty_bitmap_unlock (BdrvDirtyBitmap *bitmap);
@@ -85,5 +87,7 @@ void bdrv_set_dirty_iter(BdrvDirtyBitmapIter *hbi, int64_t sector_num);int64_t bdrv_get_dirty_count (BdrvDirtyBitmap *bitmap);int64_t bdrv_get_meta_dirty_count (BdrvDirtyBitmap *bitmap);void bdrv_dirty_bitmap_truncate (BlockDriverState *bs); +bool bdrv_dirty_bitmap_readonly (const BdrvDirtyBitmap *bitmap); +bool bdrv_has_readonly_bitmaps (BlockDriverState *bs);#endif
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 074/100] block: refactor bdrv_reopen_commit
In reply to Kevin WolfFrom: Vladimir Sementsov-Ogievskiy <[email protected]>
Add bs local variable to simplify code.
Message-id: [email protected]
--- block.c | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-)
block.c +8 -6
@@ -2982,9 +2982,11 @@ error:void bdrv_reopen_commit (BDRVReopenState *reopen_state) {BlockDriver *drv; +BlockDriverState *bs;assert (reopen_state !=NULL ); - drv = reopen_state->bs->drv; + bs = reopen_state->bs; + drv = bs->drv;assert (drv !=NULL );/* If there are any driver level actions to take */
@@ -2993,13 +2995,13 @@ void bdrv_reopen_commit(BDRVReopenState *reopen_state) }/* set BDS specific flags now */ -QDECREF (reopen_state->bs->explicit_options); +QDECREF (bs->explicit_options); - reopen_state->bs->explicit_options = reopen_state->explicit_options; - reopen_state->bs->open_flags = reopen_state->flags; - reopen_state->bs->read_only = !(reopen_state->flags &BDRV_O_RDWR ); + bs->explicit_options = reopen_state->explicit_options; + bs->open_flags = reopen_state->flags; + bs->read_only = !(reopen_state->flags &BDRV_O_RDWR ); -bdrv_refresh_limits (reopen_state->bs,NULL ); +bdrv_refresh_limits (bs,NULL ); }/*
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 078/100] block: bdrv_close: release bitmaps after drv->bdrv_close
In reply to Kevin WolfFrom: Vladimir Sementsov-Ogievskiy <[email protected]>
Release bitmaps after 'if (bs->drv) { ... }' block. This will allow format driver to save persistent bitmaps, which will appear in following commits.
Message-id: [email protected]
--- block.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
block.c +3 -3
@@ -3054,9 +3054,6 @@ static void bdrv_close(BlockDriverState *bs)bdrv_flush (bs);bdrv_drain (bs);/* in case flush left pending I/O */ -bdrv_release_named_dirty_bitmaps (bs); -assert (QLIST_EMPTY (&bs->dirty_bitmaps)); -if (bs->drv) {BdrvChild *child, *next;
@@ -3094,6 +3091,9 @@ static void bdrv_close(BlockDriverState *bs) bs->full_open_options =NULL ; } +bdrv_release_named_dirty_bitmaps (bs); +assert (QLIST_EMPTY (&bs->dirty_bitmaps)); + QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {g_free (ban); }
Signature · 1 line
1.8.3.1
[Qemu-devel] [PULL 070/100] qcow2: add bitmaps extension
In reply to Kevin WolfFrom: Vladimir Sementsov-Ogievskiy <[email protected]>
Add bitmap extension as specified in docs/specs/qcow2.txt. For now, just mirror extension header into Qcow2 state and check constraints. Also, calculate refcounts for qcow2 bitmaps, to not break qemu-img check.
For now, disable image resize if it has bitmaps. It will be fixed later.
Message-id: [email protected]
--- block/Makefile.objs | 2 +- block/qcow2-bitmap.c | 439 +++++++++++++++++++++++++++++++++++++++++++++++++ block/qcow2-refcount.c | 6 + block/qcow2.c | 125 +++++++++++++- block/qcow2.h | 27 +++ 5 files changed, 593 insertions(+), 6 deletions(-) create mode 100644 block/qcow2-bitmap.c
block/Makefile.objs +1 -1
@@ -1,5 +1,5 @@ block-obj-y += raw-format.o qcow.o vdi.o vmdk.o cloop.o bochs.o vpc.o vvfat.o dmg.o -block-obj-y += qcow2.o qcow2-refcount.o qcow2-cluster.o qcow2-snapshot.o qcow2-cache.o +block-obj-y += qcow2.o qcow2-refcount.o qcow2-cluster.o qcow2-snapshot.o qcow2-cache.o qcow2-bitmap.o block-obj-y += qed.o qed-l2-cache.o qed-table.o qed-cluster.o block-obj-y += qed-check.o block-obj-y += vhdx.o vhdx-endian.o vhdx-log.o
block/qcow2-bitmap.c new file +439 -0
439 lines not on this page · raw message
block/qcow2-refcount.c +6 -0
@@ -1869,6 +1869,12 @@ static int calculate_refcounts(BlockDriverState *bs, BdrvCheckResult *res, } } +/* bitmaps */ + ret =qcow2_check_bitmaps_refcounts (bs, res, refcount_table, nb_clusters); +if (ret <0 ) { +return ret; + } +return check_refblocks (bs, res, fix, rebuild, refcount_table, nb_clusters); }
block/qcow2.c +120 -5
184 lines not on this page · raw message
block/qcow2.h +27 -0
@@ -53,6 +53,10 @@* space for snapshot names and IDs */ #define QCOW_MAX_SNAPSHOTS_SIZE (1024 * QCOW_MAX_SNAPSHOTS) +/* Bitmap header extension constraints */ +#define QCOW2_MAX_BITMAPS 65535 +#define QCOW2_MAX_BITMAP_DIRECTORY_SIZE (1024 * QCOW2_MAX_BITMAPS) +/* indicate that the refcount of the referenced cluster is exactly one. */ #define QCOW_OFLAG_COPIED (1ULL << 63)/* indicate that the cluster is compressed (they never have the copied flag) */
@@ -201,6 +205,14 @@ enum { QCOW2_COMPAT_FEAT_MASK = QCOW2_COMPAT_LAZY_REFCOUNTS, }; +/* Autoclear feature bits */ +enum { +QCOW2_AUTOCLEAR_BITMAPS_BITNR =0 , +QCOW2_AUTOCLEAR_BITMAPS =1 <<QCOW2_AUTOCLEAR_BITMAPS_BITNR , + +QCOW2_AUTOCLEAR_MASK =QCOW2_AUTOCLEAR_BITMAPS , +}; +enum qcow2_discard_type {QCOW2_DISCARD_NEVER =0 ,QCOW2_DISCARD_ALWAYS ,
@@ -228,6 +240,13 @@ typedef uint64_t Qcow2GetRefcountFunc(const void *refcount_array,typedef void Qcow2SetRefcountFunc (void *refcount_array,uint64_t index,uint64_t value); +typedef struct Qcow2BitmapHeaderExt { +uint32_t nb_bitmaps; +uint32_t reserved32; +uint64_t bitmap_directory_size; +uint64_t bitmap_directory_offset; +} QEMU_PACKED Qcow2BitmapHeaderExt; + typedef struct BDRVQcow2State { int cluster_bits; int cluster_size;
@@ -274,6 +293,10 @@ typedef struct BDRVQcow2State {unsigned int nb_snapshots;QCowSnapshot *snapshots; +uint32_t nb_bitmaps; +uint64_t bitmap_directory_size; +uint64_t bitmap_directory_offset; +int flags;int qcow_version;bool use_lazy_refcounts;
@@ -618,4 +641,8 @@ int qcow2_cache_get_empty(BlockDriverState *bs, Qcow2Cache *c, uint64_t offset, void **table);void qcow2_cache_put (BlockDriverState *bs,Qcow2Cache *c,void **table); +/* qcow2-bitmap.c functions */ +int qcow2_check_bitmaps_refcounts (BlockDriverState *bs,BdrvCheckResult *res, +void **refcount_table, +int64_t *refcount_table_size);#endif
Signature · 1 line
1.8.3.1