]> git.proxmox.com Git - mirror_qemu.git/blame - block/vdi.c
block: convert bdrv_invalidate_cache callback to coroutine_fn
[mirror_qemu.git] / block / vdi.c
CommitLineData
9aebd98a
SW
1/*
2 * Block driver for the Virtual Disk Image (VDI) format
3 *
641543b7 4 * Copyright (c) 2009, 2012 Stefan Weil
9aebd98a
SW
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 2 of the License, or
9 * (at your option) version 3 or any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 *
19 * Reference:
20 * http://forums.virtualbox.org/viewtopic.php?t=8046
21 *
22 * This driver supports create / read / write operations on VDI images.
23 *
24 * Todo (see also TODO in code):
25 *
26 * Some features like snapshots are still missing.
27 *
28 * Deallocation of zero-filled blocks and shrinking images are missing, too
29 * (might be added to common block layer).
30 *
31 * Allocation of blocks could be optimized (less writes to block map and
32 * header).
33 *
dc6fb73d 34 * Read and write of adjacent blocks could be done in one operation
9aebd98a
SW
35 * (current code uses one operation per block (1 MiB).
36 *
37 * The code is not thread safe (missing locks for changes in header and
38 * block table, no problem with current QEMU).
39 *
40 * Hints:
41 *
42 * Blocks (VDI documentation) correspond to clusters (QEMU).
43 * QEMU's backing files could be implemented using VDI snapshot files (TODO).
44 * VDI snapshot files may also contain the complete machine state.
45 * Maybe this machine state can be converted to QEMU PC machine snapshot data.
46 *
47 * The driver keeps a block cache (little endian entries) in memory.
48 * For the standard block size (1 MiB), a 1 TiB disk will use 4 MiB RAM,
49 * so this seems to be reasonable.
50 */
51
80c71a24 52#include "qemu/osdep.h"
da34e65c 53#include "qapi/error.h"
737e150e 54#include "block/block_int.h"
a08f0c3b 55#include "sysemu/block-backend.h"
1de7afc9 56#include "qemu/module.h"
922a01a0 57#include "qemu/option.h"
58369e22 58#include "qemu/bswap.h"
795c40b8 59#include "migration/blocker.h"
10817bf0 60#include "qemu/coroutine.h"
f348b6d1 61#include "qemu/cutils.h"
7c6f55b6 62#include "qemu/uuid.h"
9aebd98a
SW
63
64/* Code configuration options. */
65
66/* Enable debug messages. */
67//~ #define CONFIG_VDI_DEBUG
68
69/* Support write operations on VDI images. */
70#define CONFIG_VDI_WRITE
71
72/* Support non-standard block (cluster) size. This is untested.
73 * Maybe it will be needed for very large images.
74 */
75//~ #define CONFIG_VDI_BLOCK_SIZE
76
77/* Support static (fixed, pre-allocated) images. */
78#define CONFIG_VDI_STATIC_IMAGE
79
80/* Command line option for static images. */
81#define BLOCK_OPT_STATIC "static"
82
83#define KiB 1024
84#define MiB (KiB * KiB)
85
86#define SECTOR_SIZE 512
99cce9fa 87#define DEFAULT_CLUSTER_SIZE (1 * MiB)
9aebd98a
SW
88
89#if defined(CONFIG_VDI_DEBUG)
b80666bf 90#define VDI_DEBUG 1
9aebd98a 91#else
b80666bf 92#define VDI_DEBUG 0
9aebd98a
SW
93#endif
94
b80666bf
EB
95#define logout(fmt, ...) \
96 do { \
97 if (VDI_DEBUG) { \
98 fprintf(stderr, "vdi\t%-24s" fmt, __func__, ##__VA_ARGS__); \
99 } \
100 } while (0)
101
9aebd98a
SW
102/* Image signature. */
103#define VDI_SIGNATURE 0xbeda107f
104
105/* Image version. */
106#define VDI_VERSION_1_1 0x00010001
107
108/* Image type. */
109#define VDI_TYPE_DYNAMIC 1
110#define VDI_TYPE_STATIC 2
111
112/* Innotek / SUN images use these strings in header.text:
113 * "<<< innotek VirtualBox Disk Image >>>\n"
114 * "<<< Sun xVM VirtualBox Disk Image >>>\n"
115 * "<<< Sun VirtualBox Disk Image >>>\n"
116 * The value does not matter, so QEMU created images use a different text.
117 */
118#define VDI_TEXT "<<< QEMU VM Virtual Disk Image >>>\n"
119
c794b4e0
ES
120/* A never-allocated block; semantically arbitrary content. */
121#define VDI_UNALLOCATED 0xffffffffU
122
123/* A discarded (no longer allocated) block; semantically zero-filled. */
124#define VDI_DISCARDED 0xfffffffeU
125
126#define VDI_IS_ALLOCATED(X) ((X) < VDI_DISCARDED)
9aebd98a 127
d20418ee
HR
128/* The bmap will take up VDI_BLOCKS_IN_IMAGE_MAX * sizeof(uint32_t) bytes; since
129 * the bmap is read and written in a single operation, its size needs to be
130 * limited to INT_MAX; furthermore, when opening an image, the bmap size is
131 * rounded up to be aligned on BDRV_SECTOR_SIZE.
132 * Therefore this should satisfy the following:
133 * VDI_BLOCKS_IN_IMAGE_MAX * sizeof(uint32_t) + BDRV_SECTOR_SIZE == INT_MAX + 1
134 * (INT_MAX + 1 is the first value not representable as an int)
135 * This guarantees that any value below or equal to the constant will, when
136 * multiplied by sizeof(uint32_t) and rounded up to a BDRV_SECTOR_SIZE boundary,
137 * still be below or equal to INT_MAX. */
138#define VDI_BLOCKS_IN_IMAGE_MAX \
139 ((unsigned)((INT_MAX + 1u - BDRV_SECTOR_SIZE) / sizeof(uint32_t)))
63fa06dc
JC
140#define VDI_DISK_SIZE_MAX ((uint64_t)VDI_BLOCKS_IN_IMAGE_MAX * \
141 (uint64_t)DEFAULT_CLUSTER_SIZE)
142
9aebd98a
SW
143typedef struct {
144 char text[0x40];
145 uint32_t signature;
146 uint32_t version;
147 uint32_t header_size;
148 uint32_t image_type;
149 uint32_t image_flags;
150 char description[256];
151 uint32_t offset_bmap;
152 uint32_t offset_data;
153 uint32_t cylinders; /* disk geometry, unused here */
154 uint32_t heads; /* disk geometry, unused here */
155 uint32_t sectors; /* disk geometry, unused here */
156 uint32_t sector_size;
157 uint32_t unused1;
158 uint64_t disk_size;
159 uint32_t block_size;
160 uint32_t block_extra; /* unused here */
161 uint32_t blocks_in_image;
162 uint32_t blocks_allocated;
7c6f55b6
FZ
163 QemuUUID uuid_image;
164 QemuUUID uuid_last_snap;
165 QemuUUID uuid_link;
166 QemuUUID uuid_parent;
9aebd98a 167 uint64_t unused2[7];
8368febd 168} QEMU_PACKED VdiHeader;
9aebd98a
SW
169
170typedef struct {
9aebd98a
SW
171 /* The block map entries are little endian (even in memory). */
172 uint32_t *bmap;
173 /* Size of block (bytes). */
174 uint32_t block_size;
9aebd98a
SW
175 /* First sector of block map. */
176 uint32_t bmap_sector;
4ff9786c 177 /* VDI header (converted to host endianness). */
9aebd98a 178 VdiHeader header;
fc9d106c 179
1e886639 180 CoRwlock bmap_lock;
f0ab6f10 181
fc9d106c 182 Error *migration_blocker;
9aebd98a
SW
183} BDRVVdiState;
184
9aebd98a
SW
185static void vdi_header_to_cpu(VdiHeader *header)
186{
187 le32_to_cpus(&header->signature);
188 le32_to_cpus(&header->version);
189 le32_to_cpus(&header->header_size);
190 le32_to_cpus(&header->image_type);
191 le32_to_cpus(&header->image_flags);
192 le32_to_cpus(&header->offset_bmap);
193 le32_to_cpus(&header->offset_data);
194 le32_to_cpus(&header->cylinders);
195 le32_to_cpus(&header->heads);
196 le32_to_cpus(&header->sectors);
197 le32_to_cpus(&header->sector_size);
198 le64_to_cpus(&header->disk_size);
199 le32_to_cpus(&header->block_size);
200 le32_to_cpus(&header->block_extra);
201 le32_to_cpus(&header->blocks_in_image);
202 le32_to_cpus(&header->blocks_allocated);
7c6f55b6
FZ
203 qemu_uuid_bswap(&header->uuid_image);
204 qemu_uuid_bswap(&header->uuid_last_snap);
205 qemu_uuid_bswap(&header->uuid_link);
206 qemu_uuid_bswap(&header->uuid_parent);
9aebd98a
SW
207}
208
209static void vdi_header_to_le(VdiHeader *header)
210{
211 cpu_to_le32s(&header->signature);
212 cpu_to_le32s(&header->version);
213 cpu_to_le32s(&header->header_size);
214 cpu_to_le32s(&header->image_type);
215 cpu_to_le32s(&header->image_flags);
216 cpu_to_le32s(&header->offset_bmap);
217 cpu_to_le32s(&header->offset_data);
218 cpu_to_le32s(&header->cylinders);
219 cpu_to_le32s(&header->heads);
220 cpu_to_le32s(&header->sectors);
221 cpu_to_le32s(&header->sector_size);
222 cpu_to_le64s(&header->disk_size);
223 cpu_to_le32s(&header->block_size);
224 cpu_to_le32s(&header->block_extra);
225 cpu_to_le32s(&header->blocks_in_image);
226 cpu_to_le32s(&header->blocks_allocated);
7c6f55b6
FZ
227 qemu_uuid_bswap(&header->uuid_image);
228 qemu_uuid_bswap(&header->uuid_last_snap);
229 qemu_uuid_bswap(&header->uuid_link);
230 qemu_uuid_bswap(&header->uuid_parent);
9aebd98a
SW
231}
232
233#if defined(CONFIG_VDI_DEBUG)
234static void vdi_header_print(VdiHeader *header)
235{
236 char uuid[37];
237 logout("text %s", header->text);
9f0470bb 238 logout("signature 0x%08x\n", header->signature);
9aebd98a
SW
239 logout("header size 0x%04x\n", header->header_size);
240 logout("image type 0x%04x\n", header->image_type);
241 logout("image flags 0x%04x\n", header->image_flags);
242 logout("description %s\n", header->description);
243 logout("offset bmap 0x%04x\n", header->offset_bmap);
244 logout("offset data 0x%04x\n", header->offset_data);
245 logout("cylinders 0x%04x\n", header->cylinders);
246 logout("heads 0x%04x\n", header->heads);
247 logout("sectors 0x%04x\n", header->sectors);
248 logout("sector size 0x%04x\n", header->sector_size);
249 logout("image size 0x%" PRIx64 " B (%" PRIu64 " MiB)\n",
250 header->disk_size, header->disk_size / MiB);
251 logout("block size 0x%04x\n", header->block_size);
252 logout("block extra 0x%04x\n", header->block_extra);
253 logout("blocks tot. 0x%04x\n", header->blocks_in_image);
254 logout("blocks all. 0x%04x\n", header->blocks_allocated);
255 uuid_unparse(header->uuid_image, uuid);
256 logout("uuid image %s\n", uuid);
257 uuid_unparse(header->uuid_last_snap, uuid);
258 logout("uuid snap %s\n", uuid);
259 uuid_unparse(header->uuid_link, uuid);
260 logout("uuid link %s\n", uuid);
261 uuid_unparse(header->uuid_parent, uuid);
262 logout("uuid parent %s\n", uuid);
263}
264#endif
265
4534ff54
KW
266static int vdi_check(BlockDriverState *bs, BdrvCheckResult *res,
267 BdrvCheckMode fix)
9aebd98a
SW
268{
269 /* TODO: additional checks possible. */
270 BDRVVdiState *s = (BDRVVdiState *)bs->opaque;
9aebd98a
SW
271 uint32_t blocks_allocated = 0;
272 uint32_t block;
273 uint32_t *bmap;
274 logout("\n");
275
4534ff54
KW
276 if (fix) {
277 return -ENOTSUP;
278 }
279
5839e53b 280 bmap = g_try_new(uint32_t, s->header.blocks_in_image);
17cce735
KW
281 if (s->header.blocks_in_image && bmap == NULL) {
282 res->check_errors++;
283 return -ENOMEM;
284 }
285
9aebd98a
SW
286 memset(bmap, 0xff, s->header.blocks_in_image * sizeof(uint32_t));
287
288 /* Check block map and value of blocks_allocated. */
289 for (block = 0; block < s->header.blocks_in_image; block++) {
290 uint32_t bmap_entry = le32_to_cpu(s->bmap[block]);
c794b4e0 291 if (VDI_IS_ALLOCATED(bmap_entry)) {
9aebd98a
SW
292 if (bmap_entry < s->header.blocks_in_image) {
293 blocks_allocated++;
c794b4e0 294 if (!VDI_IS_ALLOCATED(bmap[bmap_entry])) {
9aebd98a
SW
295 bmap[bmap_entry] = bmap_entry;
296 } else {
297 fprintf(stderr, "ERROR: block index %" PRIu32
298 " also used by %" PRIu32 "\n", bmap[bmap_entry], bmap_entry);
9ac228e0 299 res->corruptions++;
9aebd98a
SW
300 }
301 } else {
302 fprintf(stderr, "ERROR: block index %" PRIu32
303 " too large, is %" PRIu32 "\n", block, bmap_entry);
9ac228e0 304 res->corruptions++;
9aebd98a
SW
305 }
306 }
307 }
308 if (blocks_allocated != s->header.blocks_allocated) {
309 fprintf(stderr, "ERROR: allocated blocks mismatch, is %" PRIu32
310 ", should be %" PRIu32 "\n",
311 blocks_allocated, s->header.blocks_allocated);
9ac228e0 312 res->corruptions++;
9aebd98a
SW
313 }
314
7267c094 315 g_free(bmap);
9aebd98a 316
9ac228e0 317 return 0;
9aebd98a
SW
318}
319
320static int vdi_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
321{
322 /* TODO: vdi_get_info would be needed for machine snapshots.
323 vm_state_offset is still missing. */
324 BDRVVdiState *s = (BDRVVdiState *)bs->opaque;
325 logout("\n");
326 bdi->cluster_size = s->block_size;
327 bdi->vm_state_offset = 0;
95de6d70 328 bdi->unallocated_blocks_are_zero = true;
9aebd98a
SW
329 return 0;
330}
331
332static int vdi_make_empty(BlockDriverState *bs)
333{
334 /* TODO: missing code. */
335 logout("\n");
336 /* The return value for missing code must be 0, see block.c. */
337 return 0;
338}
339
340static int vdi_probe(const uint8_t *buf, int buf_size, const char *filename)
341{
342 const VdiHeader *header = (const VdiHeader *)buf;
dddc7750 343 int ret = 0;
9aebd98a
SW
344
345 logout("\n");
346
347 if (buf_size < sizeof(*header)) {
348 /* Header too small, no VDI. */
349 } else if (le32_to_cpu(header->signature) == VDI_SIGNATURE) {
dddc7750 350 ret = 100;
9aebd98a
SW
351 }
352
dddc7750 353 if (ret == 0) {
9aebd98a
SW
354 logout("no vdi image\n");
355 } else {
356 logout("%s", header->text);
357 }
358
dddc7750 359 return ret;
9aebd98a
SW
360}
361
015a1036
HR
362static int vdi_open(BlockDriverState *bs, QDict *options, int flags,
363 Error **errp)
9aebd98a
SW
364{
365 BDRVVdiState *s = bs->opaque;
366 VdiHeader header;
367 size_t bmap_size;
8937f822 368 int ret;
fe44dc91 369 Error *local_err = NULL;
9aebd98a 370
4e4bf5c4
KW
371 bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
372 false, errp);
373 if (!bs->file) {
374 return -EINVAL;
375 }
376
9aebd98a
SW
377 logout("\n");
378
fbcbbf4e 379 ret = bdrv_read(bs->file, 0, (uint8_t *)&header, 1);
8937f822 380 if (ret < 0) {
9aebd98a
SW
381 goto fail;
382 }
383
384 vdi_header_to_cpu(&header);
385#if defined(CONFIG_VDI_DEBUG)
386 vdi_header_print(&header);
387#endif
388
63fa06dc
JC
389 if (header.disk_size > VDI_DISK_SIZE_MAX) {
390 error_setg(errp, "Unsupported VDI image size (size is 0x%" PRIx64
391 ", max supported is 0x%" PRIx64 ")",
392 header.disk_size, VDI_DISK_SIZE_MAX);
393 ret = -ENOTSUP;
394 goto fail;
395 }
396
f21dc3a4
SW
397 if (header.disk_size % SECTOR_SIZE != 0) {
398 /* 'VBoxManage convertfromraw' can create images with odd disk sizes.
399 We accept them but round the disk size to the next multiple of
400 SECTOR_SIZE. */
401 logout("odd disk size %" PRIu64 " B, round up\n", header.disk_size);
e9082e47 402 header.disk_size = ROUND_UP(header.disk_size, SECTOR_SIZE);
f21dc3a4
SW
403 }
404
0e87ba2c 405 if (header.signature != VDI_SIGNATURE) {
521b2b5d
HR
406 error_setg(errp, "Image not in VDI format (bad signature %08" PRIx32
407 ")", header.signature);
76abe407 408 ret = -EINVAL;
0e87ba2c
SW
409 goto fail;
410 } else if (header.version != VDI_VERSION_1_1) {
521b2b5d
HR
411 error_setg(errp, "unsupported VDI image (version %" PRIu32 ".%" PRIu32
412 ")", header.version >> 16, header.version & 0xffff);
8937f822 413 ret = -ENOTSUP;
9aebd98a
SW
414 goto fail;
415 } else if (header.offset_bmap % SECTOR_SIZE != 0) {
416 /* We only support block maps which start on a sector boundary. */
5b7aa9b5 417 error_setg(errp, "unsupported VDI image (unaligned block map offset "
521b2b5d 418 "0x%" PRIx32 ")", header.offset_bmap);
8937f822 419 ret = -ENOTSUP;
9aebd98a
SW
420 goto fail;
421 } else if (header.offset_data % SECTOR_SIZE != 0) {
422 /* We only support data blocks which start on a sector boundary. */
521b2b5d
HR
423 error_setg(errp, "unsupported VDI image (unaligned data offset 0x%"
424 PRIx32 ")", header.offset_data);
8937f822 425 ret = -ENOTSUP;
9aebd98a
SW
426 goto fail;
427 } else if (header.sector_size != SECTOR_SIZE) {
521b2b5d
HR
428 error_setg(errp, "unsupported VDI image (sector size %" PRIu32
429 " is not %u)", header.sector_size, SECTOR_SIZE);
8937f822 430 ret = -ENOTSUP;
9aebd98a 431 goto fail;
63fa06dc 432 } else if (header.block_size != DEFAULT_CLUSTER_SIZE) {
521b2b5d
HR
433 error_setg(errp, "unsupported VDI image (block size %" PRIu32
434 " is not %u)", header.block_size, DEFAULT_CLUSTER_SIZE);
8937f822 435 ret = -ENOTSUP;
9aebd98a 436 goto fail;
f21dc3a4
SW
437 } else if (header.disk_size >
438 (uint64_t)header.blocks_in_image * header.block_size) {
5b7aa9b5
PB
439 error_setg(errp, "unsupported VDI image (disk size %" PRIu64 ", "
440 "image bitmap has room for %" PRIu64 ")",
441 header.disk_size,
442 (uint64_t)header.blocks_in_image * header.block_size);
8937f822 443 ret = -ENOTSUP;
9aebd98a 444 goto fail;
7c6f55b6 445 } else if (!qemu_uuid_is_null(&header.uuid_link)) {
5b7aa9b5 446 error_setg(errp, "unsupported VDI image (non-NULL link UUID)");
8937f822 447 ret = -ENOTSUP;
9aebd98a 448 goto fail;
7c6f55b6 449 } else if (!qemu_uuid_is_null(&header.uuid_parent)) {
5b7aa9b5 450 error_setg(errp, "unsupported VDI image (non-NULL parent UUID)");
8937f822 451 ret = -ENOTSUP;
9aebd98a 452 goto fail;
63fa06dc
JC
453 } else if (header.blocks_in_image > VDI_BLOCKS_IN_IMAGE_MAX) {
454 error_setg(errp, "unsupported VDI image "
455 "(too many blocks %u, max is %u)",
456 header.blocks_in_image, VDI_BLOCKS_IN_IMAGE_MAX);
457 ret = -ENOTSUP;
458 goto fail;
9aebd98a
SW
459 }
460
461 bs->total_sectors = header.disk_size / SECTOR_SIZE;
462
463 s->block_size = header.block_size;
9aebd98a
SW
464 s->bmap_sector = header.offset_bmap / SECTOR_SIZE;
465 s->header = header;
466
467 bmap_size = header.blocks_in_image * sizeof(uint32_t);
e9082e47 468 bmap_size = DIV_ROUND_UP(bmap_size, SECTOR_SIZE);
9a4f4c31 469 s->bmap = qemu_try_blockalign(bs->file->bs, bmap_size * SECTOR_SIZE);
17cce735
KW
470 if (s->bmap == NULL) {
471 ret = -ENOMEM;
472 goto fail;
473 }
474
fbcbbf4e 475 ret = bdrv_read(bs->file, s->bmap_sector, (uint8_t *)s->bmap,
9a4f4c31 476 bmap_size);
8937f822 477 if (ret < 0) {
9aebd98a
SW
478 goto fail_free_bmap;
479 }
480
fc9d106c 481 /* Disable migration when vdi images are used */
81e5f78a
AG
482 error_setg(&s->migration_blocker, "The vdi format used by node '%s' "
483 "does not support live migration",
484 bdrv_get_device_or_node_name(bs));
fe44dc91
AA
485 ret = migrate_add_blocker(s->migration_blocker, &local_err);
486 if (local_err) {
487 error_propagate(errp, local_err);
488 error_free(s->migration_blocker);
489 goto fail_free_bmap;
490 }
fc9d106c 491
1e886639 492 qemu_co_rwlock_init(&s->bmap_lock);
f0ab6f10 493
9aebd98a
SW
494 return 0;
495
496 fail_free_bmap:
17cce735 497 qemu_vfree(s->bmap);
9aebd98a
SW
498
499 fail:
8937f822 500 return ret;
9aebd98a
SW
501}
502
ecfe2bba
JC
503static int vdi_reopen_prepare(BDRVReopenState *state,
504 BlockReopenQueue *queue, Error **errp)
505{
506 return 0;
507}
508
67635f6a
EB
509static int coroutine_fn vdi_co_block_status(BlockDriverState *bs,
510 bool want_zero,
511 int64_t offset, int64_t bytes,
512 int64_t *pnum, int64_t *map,
513 BlockDriverState **file)
9aebd98a 514{
9aebd98a 515 BDRVVdiState *s = (BDRVVdiState *)bs->opaque;
67635f6a
EB
516 size_t bmap_index = offset / s->block_size;
517 size_t index_in_block = offset % s->block_size;
9aebd98a 518 uint32_t bmap_entry = le32_to_cpu(s->bmap[bmap_index]);
4bc74be9
PB
519 int result;
520
67635f6a
EB
521 logout("%p, %" PRId64 ", %" PRId64 ", %p\n", bs, offset, bytes, pnum);
522 *pnum = MIN(s->block_size - index_in_block, bytes);
4bc74be9
PB
523 result = VDI_IS_ALLOCATED(bmap_entry);
524 if (!result) {
525 return 0;
526 }
527
67635f6a
EB
528 *map = s->header.offset_data + (uint64_t)bmap_entry * s->block_size +
529 index_in_block;
8bfb1371 530 *file = bs->file->bs;
67635f6a 531 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
9aebd98a
SW
532}
533
0865bb6f
KW
534static int coroutine_fn
535vdi_co_preadv(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
536 QEMUIOVector *qiov, int flags)
9aebd98a 537{
9aebd98a 538 BDRVVdiState *s = bs->opaque;
0865bb6f 539 QEMUIOVector local_qiov;
9aebd98a
SW
540 uint32_t bmap_entry;
541 uint32_t block_index;
0865bb6f
KW
542 uint32_t offset_in_block;
543 uint32_t n_bytes;
544 uint64_t bytes_done = 0;
eb9566d1 545 int ret = 0;
4de659e8
PB
546
547 logout("\n");
9aebd98a 548
0865bb6f 549 qemu_iovec_init(&local_qiov, qiov->niov);
0c7bfc32 550
0865bb6f
KW
551 while (ret >= 0 && bytes > 0) {
552 block_index = offset / s->block_size;
553 offset_in_block = offset % s->block_size;
554 n_bytes = MIN(bytes, s->block_size - offset_in_block);
555
556 logout("will read %u bytes starting at offset %" PRIu64 "\n",
557 n_bytes, offset);
eb9566d1
PB
558
559 /* prepare next AIO request */
1e886639 560 qemu_co_rwlock_rdlock(&s->bmap_lock);
eb9566d1 561 bmap_entry = le32_to_cpu(s->bmap[block_index]);
1e886639 562 qemu_co_rwlock_unlock(&s->bmap_lock);
eb9566d1
PB
563 if (!VDI_IS_ALLOCATED(bmap_entry)) {
564 /* Block not allocated, return zeros, no need to wait. */
0865bb6f 565 qemu_iovec_memset(qiov, bytes_done, 0, n_bytes);
eb9566d1
PB
566 ret = 0;
567 } else {
0865bb6f
KW
568 uint64_t data_offset = s->header.offset_data +
569 (uint64_t)bmap_entry * s->block_size +
570 offset_in_block;
571
572 qemu_iovec_reset(&local_qiov);
573 qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes);
574
a03ef88f 575 ret = bdrv_co_preadv(bs->file, data_offset, n_bytes,
0865bb6f 576 &local_qiov, 0);
eb9566d1 577 }
0865bb6f 578 logout("%u bytes read\n", n_bytes);
0c7bfc32 579
0865bb6f
KW
580 bytes -= n_bytes;
581 offset += n_bytes;
582 bytes_done += n_bytes;
9aebd98a 583 }
3d46a75a 584
0865bb6f
KW
585 qemu_iovec_destroy(&local_qiov);
586
3d46a75a 587 return ret;
9aebd98a
SW
588}
589
fde9d56f
KW
590static int coroutine_fn
591vdi_co_pwritev(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
592 QEMUIOVector *qiov, int flags)
9aebd98a 593{
9aebd98a 594 BDRVVdiState *s = bs->opaque;
fde9d56f 595 QEMUIOVector local_qiov;
9aebd98a
SW
596 uint32_t bmap_entry;
597 uint32_t block_index;
fde9d56f
KW
598 uint32_t offset_in_block;
599 uint32_t n_bytes;
1e886639 600 uint64_t data_offset;
bfc45fc1
PB
601 uint32_t bmap_first = VDI_UNALLOCATED;
602 uint32_t bmap_last = VDI_UNALLOCATED;
bfc45fc1 603 uint8_t *block = NULL;
fde9d56f 604 uint64_t bytes_done = 0;
eb9566d1 605 int ret = 0;
4de659e8
PB
606
607 logout("\n");
9aebd98a 608
fde9d56f 609 qemu_iovec_init(&local_qiov, qiov->niov);
9aebd98a 610
fde9d56f
KW
611 while (ret >= 0 && bytes > 0) {
612 block_index = offset / s->block_size;
613 offset_in_block = offset % s->block_size;
614 n_bytes = MIN(bytes, s->block_size - offset_in_block);
615
616 logout("will write %u bytes starting at offset %" PRIu64 "\n",
617 n_bytes, offset);
eb9566d1
PB
618
619 /* prepare next AIO request */
1e886639 620 qemu_co_rwlock_rdlock(&s->bmap_lock);
eb9566d1
PB
621 bmap_entry = le32_to_cpu(s->bmap[block_index]);
622 if (!VDI_IS_ALLOCATED(bmap_entry)) {
623 /* Allocate new block and write to it. */
fde9d56f 624 uint64_t data_offset;
1e886639
PB
625 qemu_co_rwlock_upgrade(&s->bmap_lock);
626 bmap_entry = le32_to_cpu(s->bmap[block_index]);
627 if (VDI_IS_ALLOCATED(bmap_entry)) {
628 /* A concurrent allocation did the work for us. */
629 qemu_co_rwlock_downgrade(&s->bmap_lock);
630 goto nonallocating_write;
631 }
632
eb9566d1
PB
633 bmap_entry = s->header.blocks_allocated;
634 s->bmap[block_index] = cpu_to_le32(bmap_entry);
635 s->header.blocks_allocated++;
fde9d56f
KW
636 data_offset = s->header.offset_data +
637 (uint64_t)bmap_entry * s->block_size;
eb9566d1
PB
638 if (block == NULL) {
639 block = g_malloc(s->block_size);
640 bmap_first = block_index;
641 }
642 bmap_last = block_index;
643 /* Copy data to be written to new block and zero unused parts. */
fde9d56f
KW
644 memset(block, 0, offset_in_block);
645 qemu_iovec_to_buf(qiov, bytes_done, block + offset_in_block,
646 n_bytes);
647 memset(block + offset_in_block + n_bytes, 0,
648 s->block_size - n_bytes - offset_in_block);
f0ab6f10 649
1e886639
PB
650 /* Write the new block under CoRwLock write-side protection,
651 * so this full-cluster write does not overlap a partial write
652 * of the same cluster, issued from the "else" branch.
653 */
d9ca2ea2 654 ret = bdrv_pwrite(bs->file, data_offset, block, s->block_size);
1e886639 655 qemu_co_rwlock_unlock(&s->bmap_lock);
eb9566d1 656 } else {
1e886639
PB
657nonallocating_write:
658 data_offset = s->header.offset_data +
659 (uint64_t)bmap_entry * s->block_size +
660 offset_in_block;
661 qemu_co_rwlock_unlock(&s->bmap_lock);
fde9d56f
KW
662
663 qemu_iovec_reset(&local_qiov);
664 qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes);
665
a03ef88f 666 ret = bdrv_co_pwritev(bs->file, data_offset, n_bytes,
fde9d56f 667 &local_qiov, 0);
9aebd98a 668 }
0c7bfc32 669
fde9d56f
KW
670 bytes -= n_bytes;
671 offset += n_bytes;
672 bytes_done += n_bytes;
0c7bfc32 673
fde9d56f 674 logout("%u bytes written\n", n_bytes);
9aebd98a 675 }
9aebd98a 676
fde9d56f
KW
677 qemu_iovec_destroy(&local_qiov);
678
0c7bfc32 679 logout("finished data write\n");
4eea78e6
PB
680 if (ret < 0) {
681 return ret;
682 }
683
684 if (block) {
685 /* One or more new blocks were allocated. */
686 VdiHeader *header = (VdiHeader *) block;
687 uint8_t *base;
688 uint64_t offset;
fde9d56f 689 uint32_t n_sectors;
4eea78e6
PB
690
691 logout("now writing modified header\n");
692 assert(VDI_IS_ALLOCATED(bmap_first));
693 *header = s->header;
694 vdi_header_to_le(header);
18d51c4b 695 ret = bdrv_write(bs->file, 0, block, 1);
bfc45fc1
PB
696 g_free(block);
697 block = NULL;
4eea78e6
PB
698
699 if (ret < 0) {
700 return ret;
0c7bfc32 701 }
4eea78e6
PB
702
703 logout("now writing modified block map entry %u...%u\n",
704 bmap_first, bmap_last);
705 /* Write modified sectors from block map. */
706 bmap_first /= (SECTOR_SIZE / sizeof(uint32_t));
707 bmap_last /= (SECTOR_SIZE / sizeof(uint32_t));
708 n_sectors = bmap_last - bmap_first + 1;
709 offset = s->bmap_sector + bmap_first;
710 base = ((uint8_t *)&s->bmap[0]) + bmap_first * SECTOR_SIZE;
711 logout("will write %u block map sectors starting from entry %u\n",
712 n_sectors, bmap_first);
18d51c4b 713 ret = bdrv_write(bs->file, offset, base, n_sectors);
0c7bfc32
PB
714 }
715
3d46a75a 716 return ret;
9aebd98a
SW
717}
718
efc75e2a
SH
719static int coroutine_fn vdi_co_create_opts(const char *filename, QemuOpts *opts,
720 Error **errp)
9aebd98a 721{
dddc7750 722 int ret = 0;
9aebd98a
SW
723 uint64_t bytes = 0;
724 uint32_t blocks;
99cce9fa 725 size_t block_size = DEFAULT_CLUSTER_SIZE;
9aebd98a
SW
726 uint32_t image_type = VDI_TYPE_DYNAMIC;
727 VdiHeader header;
728 size_t i;
729 size_t bmap_size;
70747862
JC
730 int64_t offset = 0;
731 Error *local_err = NULL;
a08f0c3b 732 BlockBackend *blk = NULL;
70747862 733 uint32_t *bmap = NULL;
9aebd98a
SW
734
735 logout("\n");
736
737 /* Read out options. */
c2eb918e
HT
738 bytes = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
739 BDRV_SECTOR_SIZE);
9aebd98a 740#if defined(CONFIG_VDI_BLOCK_SIZE)
004b7f25
CL
741 /* TODO: Additional checks (SECTOR_SIZE * 2^n, ...). */
742 block_size = qemu_opt_get_size_del(opts,
743 BLOCK_OPT_CLUSTER_SIZE,
744 DEFAULT_CLUSTER_SIZE);
9aebd98a
SW
745#endif
746#if defined(CONFIG_VDI_STATIC_IMAGE)
004b7f25
CL
747 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_STATIC, false)) {
748 image_type = VDI_TYPE_STATIC;
9aebd98a 749 }
004b7f25 750#endif
9aebd98a 751
63fa06dc 752 if (bytes > VDI_DISK_SIZE_MAX) {
dddc7750 753 ret = -ENOTSUP;
63fa06dc
JC
754 error_setg(errp, "Unsupported VDI image size (size is 0x%" PRIx64
755 ", max supported is 0x%" PRIx64 ")",
756 bytes, VDI_DISK_SIZE_MAX);
757 goto exit;
758 }
759
dddc7750
JC
760 ret = bdrv_create_file(filename, opts, &local_err);
761 if (ret < 0) {
70747862 762 error_propagate(errp, local_err);
63fa06dc 763 goto exit;
9aebd98a 764 }
a08f0c3b 765
efaa7c4e 766 blk = blk_new_open(filename, NULL, NULL,
55880601
KW
767 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
768 &local_err);
a08f0c3b 769 if (blk == NULL) {
70747862 770 error_propagate(errp, local_err);
a08f0c3b 771 ret = -EIO;
70747862 772 goto exit;
4ab15590
CL
773 }
774
a08f0c3b
KW
775 blk_set_allow_write_beyond_eof(blk, true);
776
f21dc3a4
SW
777 /* We need enough blocks to store the given disk size,
778 so always round up. */
e9082e47 779 blocks = DIV_ROUND_UP(bytes, block_size);
f21dc3a4 780
9aebd98a 781 bmap_size = blocks * sizeof(uint32_t);
e9082e47 782 bmap_size = ROUND_UP(bmap_size, SECTOR_SIZE);
9aebd98a
SW
783
784 memset(&header, 0, sizeof(header));
1786dc15 785 pstrcpy(header.text, sizeof(header.text), VDI_TEXT);
9aebd98a
SW
786 header.signature = VDI_SIGNATURE;
787 header.version = VDI_VERSION_1_1;
788 header.header_size = 0x180;
789 header.image_type = image_type;
790 header.offset_bmap = 0x200;
791 header.offset_data = 0x200 + bmap_size;
792 header.sector_size = SECTOR_SIZE;
793 header.disk_size = bytes;
794 header.block_size = block_size;
795 header.blocks_in_image = blocks;
6eea90eb
SW
796 if (image_type == VDI_TYPE_STATIC) {
797 header.blocks_allocated = blocks;
798 }
7c6f55b6
FZ
799 qemu_uuid_generate(&header.uuid_image);
800 qemu_uuid_generate(&header.uuid_last_snap);
9aebd98a
SW
801 /* There is no need to set header.uuid_link or header.uuid_parent here. */
802#if defined(CONFIG_VDI_DEBUG)
803 vdi_header_print(&header);
804#endif
805 vdi_header_to_le(&header);
8341f00d 806 ret = blk_pwrite(blk, offset, &header, sizeof(header), 0);
dddc7750 807 if (ret < 0) {
70747862
JC
808 error_setg(errp, "Error writing header to %s", filename);
809 goto exit;
9aebd98a 810 }
70747862 811 offset += sizeof(header);
9aebd98a 812
b76b6e95 813 if (bmap_size > 0) {
17cce735
KW
814 bmap = g_try_malloc0(bmap_size);
815 if (bmap == NULL) {
816 ret = -ENOMEM;
817 error_setg(errp, "Could not allocate bmap");
818 goto exit;
819 }
514f21a5
SW
820 for (i = 0; i < blocks; i++) {
821 if (image_type == VDI_TYPE_STATIC) {
822 bmap[i] = i;
823 } else {
824 bmap[i] = VDI_UNALLOCATED;
825 }
9aebd98a 826 }
8341f00d 827 ret = blk_pwrite(blk, offset, bmap, bmap_size, 0);
dddc7750 828 if (ret < 0) {
70747862
JC
829 error_setg(errp, "Error writing bmap to %s", filename);
830 goto exit;
514f21a5 831 }
70747862 832 offset += bmap_size;
9aebd98a 833 }
514f21a5 834
9aebd98a 835 if (image_type == VDI_TYPE_STATIC) {
3a691c50
HR
836 ret = blk_truncate(blk, offset + blocks * block_size,
837 PREALLOC_MODE_OFF, errp);
dddc7750 838 if (ret < 0) {
ed3d2ec9 839 error_prepend(errp, "Failed to statically allocate %s", filename);
70747862 840 goto exit;
9aebd98a
SW
841 }
842 }
843
63fa06dc 844exit:
a08f0c3b 845 blk_unref(blk);
70747862 846 g_free(bmap);
dddc7750 847 return ret;
9aebd98a
SW
848}
849
850static void vdi_close(BlockDriverState *bs)
851{
fc9d106c 852 BDRVVdiState *s = bs->opaque;
6ac5f388 853
17cce735 854 qemu_vfree(s->bmap);
6ac5f388 855
fc9d106c
KW
856 migrate_del_blocker(s->migration_blocker);
857 error_free(s->migration_blocker);
9aebd98a
SW
858}
859
004b7f25
CL
860static QemuOptsList vdi_create_opts = {
861 .name = "vdi-create-opts",
862 .head = QTAILQ_HEAD_INITIALIZER(vdi_create_opts.head),
863 .desc = {
864 {
865 .name = BLOCK_OPT_SIZE,
866 .type = QEMU_OPT_SIZE,
867 .help = "Virtual disk size"
868 },
9aebd98a 869#if defined(CONFIG_VDI_BLOCK_SIZE)
004b7f25
CL
870 {
871 .name = BLOCK_OPT_CLUSTER_SIZE,
872 .type = QEMU_OPT_SIZE,
873 .help = "VDI cluster (block) size",
874 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
875 },
9aebd98a
SW
876#endif
877#if defined(CONFIG_VDI_STATIC_IMAGE)
004b7f25
CL
878 {
879 .name = BLOCK_OPT_STATIC,
880 .type = QEMU_OPT_BOOL,
881 .help = "VDI static (pre-allocated) image",
882 .def_value_str = "off"
883 },
9aebd98a 884#endif
004b7f25
CL
885 /* TODO: An additional option to set UUID values might be useful. */
886 { /* end of list */ }
887 }
9aebd98a
SW
888};
889
890static BlockDriver bdrv_vdi = {
891 .format_name = "vdi",
892 .instance_size = sizeof(BDRVVdiState),
893 .bdrv_probe = vdi_probe,
894 .bdrv_open = vdi_open,
895 .bdrv_close = vdi_close,
ecfe2bba 896 .bdrv_reopen_prepare = vdi_reopen_prepare,
862f215f 897 .bdrv_child_perm = bdrv_format_default_perms,
efc75e2a 898 .bdrv_co_create_opts = vdi_co_create_opts,
3ac21627 899 .bdrv_has_zero_init = bdrv_has_zero_init_1,
67635f6a 900 .bdrv_co_block_status = vdi_co_block_status,
9aebd98a
SW
901 .bdrv_make_empty = vdi_make_empty,
902
0865bb6f 903 .bdrv_co_preadv = vdi_co_preadv,
9aebd98a 904#if defined(CONFIG_VDI_WRITE)
fde9d56f 905 .bdrv_co_pwritev = vdi_co_pwritev,
9aebd98a
SW
906#endif
907
908 .bdrv_get_info = vdi_get_info,
909
004b7f25 910 .create_opts = &vdi_create_opts,
9aebd98a
SW
911 .bdrv_check = vdi_check,
912};
913
914static void bdrv_vdi_init(void)
915{
916 logout("\n");
917 bdrv_register(&bdrv_vdi);
918}
919
920block_init(bdrv_vdi_init);