slirp: fix segv when init failed
[qemu.git] / block / vdi.c
blob8a1cf9792889ec39e4597148f55e99dc5d335fcb
1 /*
2 * Block driver for the Virtual Disk Image (VDI) format
4 * Copyright (c) 2009, 2012 Stefan Weil
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.
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.
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/>.
19 * Reference:
20 * http://forums.virtualbox.org/viewtopic.php?t=8046
22 * This driver supports create / read / write operations on VDI images.
24 * Todo (see also TODO in code):
26 * Some features like snapshots are still missing.
28 * Deallocation of zero-filled blocks and shrinking images are missing, too
29 * (might be added to common block layer).
31 * Allocation of blocks could be optimized (less writes to block map and
32 * header).
34 * Read and write of adjacent blocks could be done in one operation
35 * (current code uses one operation per block (1 MiB).
37 * The code is not thread safe (missing locks for changes in header and
38 * block table, no problem with current QEMU).
40 * Hints:
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.
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.
52 #include "qemu/osdep.h"
53 #include "qapi/error.h"
54 #include "block/block_int.h"
55 #include "sysemu/block-backend.h"
56 #include "qemu/module.h"
57 #include "qemu/bswap.h"
58 #include "migration/migration.h"
59 #include "qemu/coroutine.h"
60 #include "qemu/cutils.h"
62 #if defined(CONFIG_UUID)
63 #include <uuid/uuid.h>
64 #else
65 /* TODO: move uuid emulation to some central place in QEMU. */
66 #include "sysemu/sysemu.h" /* UUID_FMT */
67 typedef unsigned char uuid_t[16];
68 #endif
70 /* Code configuration options. */
72 /* Enable debug messages. */
73 //~ #define CONFIG_VDI_DEBUG
75 /* Support write operations on VDI images. */
76 #define CONFIG_VDI_WRITE
78 /* Support non-standard block (cluster) size. This is untested.
79 * Maybe it will be needed for very large images.
81 //~ #define CONFIG_VDI_BLOCK_SIZE
83 /* Support static (fixed, pre-allocated) images. */
84 #define CONFIG_VDI_STATIC_IMAGE
86 /* Command line option for static images. */
87 #define BLOCK_OPT_STATIC "static"
89 #define KiB 1024
90 #define MiB (KiB * KiB)
92 #define SECTOR_SIZE 512
93 #define DEFAULT_CLUSTER_SIZE (1 * MiB)
95 #if defined(CONFIG_VDI_DEBUG)
96 #define logout(fmt, ...) \
97 fprintf(stderr, "vdi\t%-24s" fmt, __func__, ##__VA_ARGS__)
98 #else
99 #define logout(fmt, ...) ((void)0)
100 #endif
102 /* Image signature. */
103 #define VDI_SIGNATURE 0xbeda107f
105 /* Image version. */
106 #define VDI_VERSION_1_1 0x00010001
108 /* Image type. */
109 #define VDI_TYPE_DYNAMIC 1
110 #define VDI_TYPE_STATIC 2
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.
118 #define VDI_TEXT "<<< QEMU VM Virtual Disk Image >>>\n"
120 /* A never-allocated block; semantically arbitrary content. */
121 #define VDI_UNALLOCATED 0xffffffffU
123 /* A discarded (no longer allocated) block; semantically zero-filled. */
124 #define VDI_DISCARDED 0xfffffffeU
126 #define VDI_IS_ALLOCATED(X) ((X) < VDI_DISCARDED)
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)))
140 #define VDI_DISK_SIZE_MAX ((uint64_t)VDI_BLOCKS_IN_IMAGE_MAX * \
141 (uint64_t)DEFAULT_CLUSTER_SIZE)
143 #if !defined(CONFIG_UUID)
144 static inline void uuid_generate(uuid_t out)
146 memset(out, 0, sizeof(uuid_t));
149 static inline int uuid_is_null(const uuid_t uu)
151 uuid_t null_uuid = { 0 };
152 return memcmp(uu, null_uuid, sizeof(uuid_t)) == 0;
155 # if defined(CONFIG_VDI_DEBUG)
156 static inline void uuid_unparse(const uuid_t uu, char *out)
158 snprintf(out, 37, UUID_FMT,
159 uu[0], uu[1], uu[2], uu[3], uu[4], uu[5], uu[6], uu[7],
160 uu[8], uu[9], uu[10], uu[11], uu[12], uu[13], uu[14], uu[15]);
162 # endif
163 #endif
165 typedef struct {
166 char text[0x40];
167 uint32_t signature;
168 uint32_t version;
169 uint32_t header_size;
170 uint32_t image_type;
171 uint32_t image_flags;
172 char description[256];
173 uint32_t offset_bmap;
174 uint32_t offset_data;
175 uint32_t cylinders; /* disk geometry, unused here */
176 uint32_t heads; /* disk geometry, unused here */
177 uint32_t sectors; /* disk geometry, unused here */
178 uint32_t sector_size;
179 uint32_t unused1;
180 uint64_t disk_size;
181 uint32_t block_size;
182 uint32_t block_extra; /* unused here */
183 uint32_t blocks_in_image;
184 uint32_t blocks_allocated;
185 uuid_t uuid_image;
186 uuid_t uuid_last_snap;
187 uuid_t uuid_link;
188 uuid_t uuid_parent;
189 uint64_t unused2[7];
190 } QEMU_PACKED VdiHeader;
192 typedef struct {
193 /* The block map entries are little endian (even in memory). */
194 uint32_t *bmap;
195 /* Size of block (bytes). */
196 uint32_t block_size;
197 /* Size of block (sectors). */
198 uint32_t block_sectors;
199 /* First sector of block map. */
200 uint32_t bmap_sector;
201 /* VDI header (converted to host endianness). */
202 VdiHeader header;
204 CoMutex write_lock;
206 Error *migration_blocker;
207 } BDRVVdiState;
209 /* Change UUID from little endian (IPRT = VirtualBox format) to big endian
210 * format (network byte order, standard, see RFC 4122) and vice versa.
212 static void uuid_convert(uuid_t uuid)
214 bswap32s((uint32_t *)&uuid[0]);
215 bswap16s((uint16_t *)&uuid[4]);
216 bswap16s((uint16_t *)&uuid[6]);
219 static void vdi_header_to_cpu(VdiHeader *header)
221 le32_to_cpus(&header->signature);
222 le32_to_cpus(&header->version);
223 le32_to_cpus(&header->header_size);
224 le32_to_cpus(&header->image_type);
225 le32_to_cpus(&header->image_flags);
226 le32_to_cpus(&header->offset_bmap);
227 le32_to_cpus(&header->offset_data);
228 le32_to_cpus(&header->cylinders);
229 le32_to_cpus(&header->heads);
230 le32_to_cpus(&header->sectors);
231 le32_to_cpus(&header->sector_size);
232 le64_to_cpus(&header->disk_size);
233 le32_to_cpus(&header->block_size);
234 le32_to_cpus(&header->block_extra);
235 le32_to_cpus(&header->blocks_in_image);
236 le32_to_cpus(&header->blocks_allocated);
237 uuid_convert(header->uuid_image);
238 uuid_convert(header->uuid_last_snap);
239 uuid_convert(header->uuid_link);
240 uuid_convert(header->uuid_parent);
243 static void vdi_header_to_le(VdiHeader *header)
245 cpu_to_le32s(&header->signature);
246 cpu_to_le32s(&header->version);
247 cpu_to_le32s(&header->header_size);
248 cpu_to_le32s(&header->image_type);
249 cpu_to_le32s(&header->image_flags);
250 cpu_to_le32s(&header->offset_bmap);
251 cpu_to_le32s(&header->offset_data);
252 cpu_to_le32s(&header->cylinders);
253 cpu_to_le32s(&header->heads);
254 cpu_to_le32s(&header->sectors);
255 cpu_to_le32s(&header->sector_size);
256 cpu_to_le64s(&header->disk_size);
257 cpu_to_le32s(&header->block_size);
258 cpu_to_le32s(&header->block_extra);
259 cpu_to_le32s(&header->blocks_in_image);
260 cpu_to_le32s(&header->blocks_allocated);
261 uuid_convert(header->uuid_image);
262 uuid_convert(header->uuid_last_snap);
263 uuid_convert(header->uuid_link);
264 uuid_convert(header->uuid_parent);
267 #if defined(CONFIG_VDI_DEBUG)
268 static void vdi_header_print(VdiHeader *header)
270 char uuid[37];
271 logout("text %s", header->text);
272 logout("signature 0x%08x\n", header->signature);
273 logout("header size 0x%04x\n", header->header_size);
274 logout("image type 0x%04x\n", header->image_type);
275 logout("image flags 0x%04x\n", header->image_flags);
276 logout("description %s\n", header->description);
277 logout("offset bmap 0x%04x\n", header->offset_bmap);
278 logout("offset data 0x%04x\n", header->offset_data);
279 logout("cylinders 0x%04x\n", header->cylinders);
280 logout("heads 0x%04x\n", header->heads);
281 logout("sectors 0x%04x\n", header->sectors);
282 logout("sector size 0x%04x\n", header->sector_size);
283 logout("image size 0x%" PRIx64 " B (%" PRIu64 " MiB)\n",
284 header->disk_size, header->disk_size / MiB);
285 logout("block size 0x%04x\n", header->block_size);
286 logout("block extra 0x%04x\n", header->block_extra);
287 logout("blocks tot. 0x%04x\n", header->blocks_in_image);
288 logout("blocks all. 0x%04x\n", header->blocks_allocated);
289 uuid_unparse(header->uuid_image, uuid);
290 logout("uuid image %s\n", uuid);
291 uuid_unparse(header->uuid_last_snap, uuid);
292 logout("uuid snap %s\n", uuid);
293 uuid_unparse(header->uuid_link, uuid);
294 logout("uuid link %s\n", uuid);
295 uuid_unparse(header->uuid_parent, uuid);
296 logout("uuid parent %s\n", uuid);
298 #endif
300 static int vdi_check(BlockDriverState *bs, BdrvCheckResult *res,
301 BdrvCheckMode fix)
303 /* TODO: additional checks possible. */
304 BDRVVdiState *s = (BDRVVdiState *)bs->opaque;
305 uint32_t blocks_allocated = 0;
306 uint32_t block;
307 uint32_t *bmap;
308 logout("\n");
310 if (fix) {
311 return -ENOTSUP;
314 bmap = g_try_new(uint32_t, s->header.blocks_in_image);
315 if (s->header.blocks_in_image && bmap == NULL) {
316 res->check_errors++;
317 return -ENOMEM;
320 memset(bmap, 0xff, s->header.blocks_in_image * sizeof(uint32_t));
322 /* Check block map and value of blocks_allocated. */
323 for (block = 0; block < s->header.blocks_in_image; block++) {
324 uint32_t bmap_entry = le32_to_cpu(s->bmap[block]);
325 if (VDI_IS_ALLOCATED(bmap_entry)) {
326 if (bmap_entry < s->header.blocks_in_image) {
327 blocks_allocated++;
328 if (!VDI_IS_ALLOCATED(bmap[bmap_entry])) {
329 bmap[bmap_entry] = bmap_entry;
330 } else {
331 fprintf(stderr, "ERROR: block index %" PRIu32
332 " also used by %" PRIu32 "\n", bmap[bmap_entry], bmap_entry);
333 res->corruptions++;
335 } else {
336 fprintf(stderr, "ERROR: block index %" PRIu32
337 " too large, is %" PRIu32 "\n", block, bmap_entry);
338 res->corruptions++;
342 if (blocks_allocated != s->header.blocks_allocated) {
343 fprintf(stderr, "ERROR: allocated blocks mismatch, is %" PRIu32
344 ", should be %" PRIu32 "\n",
345 blocks_allocated, s->header.blocks_allocated);
346 res->corruptions++;
349 g_free(bmap);
351 return 0;
354 static int vdi_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
356 /* TODO: vdi_get_info would be needed for machine snapshots.
357 vm_state_offset is still missing. */
358 BDRVVdiState *s = (BDRVVdiState *)bs->opaque;
359 logout("\n");
360 bdi->cluster_size = s->block_size;
361 bdi->vm_state_offset = 0;
362 bdi->unallocated_blocks_are_zero = true;
363 return 0;
366 static int vdi_make_empty(BlockDriverState *bs)
368 /* TODO: missing code. */
369 logout("\n");
370 /* The return value for missing code must be 0, see block.c. */
371 return 0;
374 static int vdi_probe(const uint8_t *buf, int buf_size, const char *filename)
376 const VdiHeader *header = (const VdiHeader *)buf;
377 int ret = 0;
379 logout("\n");
381 if (buf_size < sizeof(*header)) {
382 /* Header too small, no VDI. */
383 } else if (le32_to_cpu(header->signature) == VDI_SIGNATURE) {
384 ret = 100;
387 if (ret == 0) {
388 logout("no vdi image\n");
389 } else {
390 logout("%s", header->text);
393 return ret;
396 static int vdi_open(BlockDriverState *bs, QDict *options, int flags,
397 Error **errp)
399 BDRVVdiState *s = bs->opaque;
400 VdiHeader header;
401 size_t bmap_size;
402 int ret;
404 logout("\n");
406 ret = bdrv_read(bs->file, 0, (uint8_t *)&header, 1);
407 if (ret < 0) {
408 goto fail;
411 vdi_header_to_cpu(&header);
412 #if defined(CONFIG_VDI_DEBUG)
413 vdi_header_print(&header);
414 #endif
416 if (header.disk_size > VDI_DISK_SIZE_MAX) {
417 error_setg(errp, "Unsupported VDI image size (size is 0x%" PRIx64
418 ", max supported is 0x%" PRIx64 ")",
419 header.disk_size, VDI_DISK_SIZE_MAX);
420 ret = -ENOTSUP;
421 goto fail;
424 if (header.disk_size % SECTOR_SIZE != 0) {
425 /* 'VBoxManage convertfromraw' can create images with odd disk sizes.
426 We accept them but round the disk size to the next multiple of
427 SECTOR_SIZE. */
428 logout("odd disk size %" PRIu64 " B, round up\n", header.disk_size);
429 header.disk_size = ROUND_UP(header.disk_size, SECTOR_SIZE);
432 if (header.signature != VDI_SIGNATURE) {
433 error_setg(errp, "Image not in VDI format (bad signature %08" PRIx32
434 ")", header.signature);
435 ret = -EINVAL;
436 goto fail;
437 } else if (header.version != VDI_VERSION_1_1) {
438 error_setg(errp, "unsupported VDI image (version %" PRIu32 ".%" PRIu32
439 ")", header.version >> 16, header.version & 0xffff);
440 ret = -ENOTSUP;
441 goto fail;
442 } else if (header.offset_bmap % SECTOR_SIZE != 0) {
443 /* We only support block maps which start on a sector boundary. */
444 error_setg(errp, "unsupported VDI image (unaligned block map offset "
445 "0x%" PRIx32 ")", header.offset_bmap);
446 ret = -ENOTSUP;
447 goto fail;
448 } else if (header.offset_data % SECTOR_SIZE != 0) {
449 /* We only support data blocks which start on a sector boundary. */
450 error_setg(errp, "unsupported VDI image (unaligned data offset 0x%"
451 PRIx32 ")", header.offset_data);
452 ret = -ENOTSUP;
453 goto fail;
454 } else if (header.sector_size != SECTOR_SIZE) {
455 error_setg(errp, "unsupported VDI image (sector size %" PRIu32
456 " is not %u)", header.sector_size, SECTOR_SIZE);
457 ret = -ENOTSUP;
458 goto fail;
459 } else if (header.block_size != DEFAULT_CLUSTER_SIZE) {
460 error_setg(errp, "unsupported VDI image (block size %" PRIu32
461 " is not %u)", header.block_size, DEFAULT_CLUSTER_SIZE);
462 ret = -ENOTSUP;
463 goto fail;
464 } else if (header.disk_size >
465 (uint64_t)header.blocks_in_image * header.block_size) {
466 error_setg(errp, "unsupported VDI image (disk size %" PRIu64 ", "
467 "image bitmap has room for %" PRIu64 ")",
468 header.disk_size,
469 (uint64_t)header.blocks_in_image * header.block_size);
470 ret = -ENOTSUP;
471 goto fail;
472 } else if (!uuid_is_null(header.uuid_link)) {
473 error_setg(errp, "unsupported VDI image (non-NULL link UUID)");
474 ret = -ENOTSUP;
475 goto fail;
476 } else if (!uuid_is_null(header.uuid_parent)) {
477 error_setg(errp, "unsupported VDI image (non-NULL parent UUID)");
478 ret = -ENOTSUP;
479 goto fail;
480 } else if (header.blocks_in_image > VDI_BLOCKS_IN_IMAGE_MAX) {
481 error_setg(errp, "unsupported VDI image "
482 "(too many blocks %u, max is %u)",
483 header.blocks_in_image, VDI_BLOCKS_IN_IMAGE_MAX);
484 ret = -ENOTSUP;
485 goto fail;
488 bs->total_sectors = header.disk_size / SECTOR_SIZE;
490 s->block_size = header.block_size;
491 s->block_sectors = header.block_size / SECTOR_SIZE;
492 s->bmap_sector = header.offset_bmap / SECTOR_SIZE;
493 s->header = header;
495 bmap_size = header.blocks_in_image * sizeof(uint32_t);
496 bmap_size = DIV_ROUND_UP(bmap_size, SECTOR_SIZE);
497 s->bmap = qemu_try_blockalign(bs->file->bs, bmap_size * SECTOR_SIZE);
498 if (s->bmap == NULL) {
499 ret = -ENOMEM;
500 goto fail;
503 ret = bdrv_read(bs->file, s->bmap_sector, (uint8_t *)s->bmap,
504 bmap_size);
505 if (ret < 0) {
506 goto fail_free_bmap;
509 /* Disable migration when vdi images are used */
510 error_setg(&s->migration_blocker, "The vdi format used by node '%s' "
511 "does not support live migration",
512 bdrv_get_device_or_node_name(bs));
513 migrate_add_blocker(s->migration_blocker);
515 qemu_co_mutex_init(&s->write_lock);
517 return 0;
519 fail_free_bmap:
520 qemu_vfree(s->bmap);
522 fail:
523 return ret;
526 static int vdi_reopen_prepare(BDRVReopenState *state,
527 BlockReopenQueue *queue, Error **errp)
529 return 0;
532 static int64_t coroutine_fn vdi_co_get_block_status(BlockDriverState *bs,
533 int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file)
535 /* TODO: Check for too large sector_num (in bdrv_is_allocated or here). */
536 BDRVVdiState *s = (BDRVVdiState *)bs->opaque;
537 size_t bmap_index = sector_num / s->block_sectors;
538 size_t sector_in_block = sector_num % s->block_sectors;
539 int n_sectors = s->block_sectors - sector_in_block;
540 uint32_t bmap_entry = le32_to_cpu(s->bmap[bmap_index]);
541 uint64_t offset;
542 int result;
544 logout("%p, %" PRId64 ", %d, %p\n", bs, sector_num, nb_sectors, pnum);
545 if (n_sectors > nb_sectors) {
546 n_sectors = nb_sectors;
548 *pnum = n_sectors;
549 result = VDI_IS_ALLOCATED(bmap_entry);
550 if (!result) {
551 return 0;
554 offset = s->header.offset_data +
555 (uint64_t)bmap_entry * s->block_size +
556 sector_in_block * SECTOR_SIZE;
557 *file = bs->file->bs;
558 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | offset;
561 static int coroutine_fn
562 vdi_co_preadv(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
563 QEMUIOVector *qiov, int flags)
565 BDRVVdiState *s = bs->opaque;
566 QEMUIOVector local_qiov;
567 uint32_t bmap_entry;
568 uint32_t block_index;
569 uint32_t offset_in_block;
570 uint32_t n_bytes;
571 uint64_t bytes_done = 0;
572 int ret = 0;
574 logout("\n");
576 qemu_iovec_init(&local_qiov, qiov->niov);
578 while (ret >= 0 && bytes > 0) {
579 block_index = offset / s->block_size;
580 offset_in_block = offset % s->block_size;
581 n_bytes = MIN(bytes, s->block_size - offset_in_block);
583 logout("will read %u bytes starting at offset %" PRIu64 "\n",
584 n_bytes, offset);
586 /* prepare next AIO request */
587 bmap_entry = le32_to_cpu(s->bmap[block_index]);
588 if (!VDI_IS_ALLOCATED(bmap_entry)) {
589 /* Block not allocated, return zeros, no need to wait. */
590 qemu_iovec_memset(qiov, bytes_done, 0, n_bytes);
591 ret = 0;
592 } else {
593 uint64_t data_offset = s->header.offset_data +
594 (uint64_t)bmap_entry * s->block_size +
595 offset_in_block;
597 qemu_iovec_reset(&local_qiov);
598 qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes);
600 ret = bdrv_co_preadv(bs->file, data_offset, n_bytes,
601 &local_qiov, 0);
603 logout("%u bytes read\n", n_bytes);
605 bytes -= n_bytes;
606 offset += n_bytes;
607 bytes_done += n_bytes;
610 qemu_iovec_destroy(&local_qiov);
612 return ret;
615 static int coroutine_fn
616 vdi_co_pwritev(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
617 QEMUIOVector *qiov, int flags)
619 BDRVVdiState *s = bs->opaque;
620 QEMUIOVector local_qiov;
621 uint32_t bmap_entry;
622 uint32_t block_index;
623 uint32_t offset_in_block;
624 uint32_t n_bytes;
625 uint32_t bmap_first = VDI_UNALLOCATED;
626 uint32_t bmap_last = VDI_UNALLOCATED;
627 uint8_t *block = NULL;
628 uint64_t bytes_done = 0;
629 int ret = 0;
631 logout("\n");
633 qemu_iovec_init(&local_qiov, qiov->niov);
635 while (ret >= 0 && bytes > 0) {
636 block_index = offset / s->block_size;
637 offset_in_block = offset % s->block_size;
638 n_bytes = MIN(bytes, s->block_size - offset_in_block);
640 logout("will write %u bytes starting at offset %" PRIu64 "\n",
641 n_bytes, offset);
643 /* prepare next AIO request */
644 bmap_entry = le32_to_cpu(s->bmap[block_index]);
645 if (!VDI_IS_ALLOCATED(bmap_entry)) {
646 /* Allocate new block and write to it. */
647 uint64_t data_offset;
648 bmap_entry = s->header.blocks_allocated;
649 s->bmap[block_index] = cpu_to_le32(bmap_entry);
650 s->header.blocks_allocated++;
651 data_offset = s->header.offset_data +
652 (uint64_t)bmap_entry * s->block_size;
653 if (block == NULL) {
654 block = g_malloc(s->block_size);
655 bmap_first = block_index;
657 bmap_last = block_index;
658 /* Copy data to be written to new block and zero unused parts. */
659 memset(block, 0, offset_in_block);
660 qemu_iovec_to_buf(qiov, bytes_done, block + offset_in_block,
661 n_bytes);
662 memset(block + offset_in_block + n_bytes, 0,
663 s->block_size - n_bytes - offset_in_block);
665 /* Note that this coroutine does not yield anywhere from reading the
666 * bmap entry until here, so in regards to all the coroutines trying
667 * to write to this cluster, the one doing the allocation will
668 * always be the first to try to acquire the lock.
669 * Therefore, it is also the first that will actually be able to
670 * acquire the lock and thus the padded cluster is written before
671 * the other coroutines can write to the affected area. */
672 qemu_co_mutex_lock(&s->write_lock);
673 ret = bdrv_pwrite(bs->file, data_offset, block, s->block_size);
674 qemu_co_mutex_unlock(&s->write_lock);
675 } else {
676 uint64_t data_offset = s->header.offset_data +
677 (uint64_t)bmap_entry * s->block_size +
678 offset_in_block;
679 qemu_co_mutex_lock(&s->write_lock);
680 /* This lock is only used to make sure the following write operation
681 * is executed after the write issued by the coroutine allocating
682 * this cluster, therefore we do not need to keep it locked.
683 * As stated above, the allocating coroutine will always try to lock
684 * the mutex before all the other concurrent accesses to that
685 * cluster, therefore at this point we can be absolutely certain
686 * that that write operation has returned (there may be other writes
687 * in flight, but they do not concern this very operation). */
688 qemu_co_mutex_unlock(&s->write_lock);
690 qemu_iovec_reset(&local_qiov);
691 qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes);
693 ret = bdrv_co_pwritev(bs->file, data_offset, n_bytes,
694 &local_qiov, 0);
697 bytes -= n_bytes;
698 offset += n_bytes;
699 bytes_done += n_bytes;
701 logout("%u bytes written\n", n_bytes);
704 qemu_iovec_destroy(&local_qiov);
706 logout("finished data write\n");
707 if (ret < 0) {
708 return ret;
711 if (block) {
712 /* One or more new blocks were allocated. */
713 VdiHeader *header = (VdiHeader *) block;
714 uint8_t *base;
715 uint64_t offset;
716 uint32_t n_sectors;
718 logout("now writing modified header\n");
719 assert(VDI_IS_ALLOCATED(bmap_first));
720 *header = s->header;
721 vdi_header_to_le(header);
722 ret = bdrv_write(bs->file, 0, block, 1);
723 g_free(block);
724 block = NULL;
726 if (ret < 0) {
727 return ret;
730 logout("now writing modified block map entry %u...%u\n",
731 bmap_first, bmap_last);
732 /* Write modified sectors from block map. */
733 bmap_first /= (SECTOR_SIZE / sizeof(uint32_t));
734 bmap_last /= (SECTOR_SIZE / sizeof(uint32_t));
735 n_sectors = bmap_last - bmap_first + 1;
736 offset = s->bmap_sector + bmap_first;
737 base = ((uint8_t *)&s->bmap[0]) + bmap_first * SECTOR_SIZE;
738 logout("will write %u block map sectors starting from entry %u\n",
739 n_sectors, bmap_first);
740 ret = bdrv_write(bs->file, offset, base, n_sectors);
743 return ret;
746 static int vdi_create(const char *filename, QemuOpts *opts, Error **errp)
748 int ret = 0;
749 uint64_t bytes = 0;
750 uint32_t blocks;
751 size_t block_size = DEFAULT_CLUSTER_SIZE;
752 uint32_t image_type = VDI_TYPE_DYNAMIC;
753 VdiHeader header;
754 size_t i;
755 size_t bmap_size;
756 int64_t offset = 0;
757 Error *local_err = NULL;
758 BlockBackend *blk = NULL;
759 uint32_t *bmap = NULL;
761 logout("\n");
763 /* Read out options. */
764 bytes = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
765 BDRV_SECTOR_SIZE);
766 #if defined(CONFIG_VDI_BLOCK_SIZE)
767 /* TODO: Additional checks (SECTOR_SIZE * 2^n, ...). */
768 block_size = qemu_opt_get_size_del(opts,
769 BLOCK_OPT_CLUSTER_SIZE,
770 DEFAULT_CLUSTER_SIZE);
771 #endif
772 #if defined(CONFIG_VDI_STATIC_IMAGE)
773 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_STATIC, false)) {
774 image_type = VDI_TYPE_STATIC;
776 #endif
778 if (bytes > VDI_DISK_SIZE_MAX) {
779 ret = -ENOTSUP;
780 error_setg(errp, "Unsupported VDI image size (size is 0x%" PRIx64
781 ", max supported is 0x%" PRIx64 ")",
782 bytes, VDI_DISK_SIZE_MAX);
783 goto exit;
786 ret = bdrv_create_file(filename, opts, &local_err);
787 if (ret < 0) {
788 error_propagate(errp, local_err);
789 goto exit;
792 blk = blk_new_open(filename, NULL, NULL,
793 BDRV_O_RDWR | BDRV_O_PROTOCOL, &local_err);
794 if (blk == NULL) {
795 error_propagate(errp, local_err);
796 ret = -EIO;
797 goto exit;
800 blk_set_allow_write_beyond_eof(blk, true);
802 /* We need enough blocks to store the given disk size,
803 so always round up. */
804 blocks = DIV_ROUND_UP(bytes, block_size);
806 bmap_size = blocks * sizeof(uint32_t);
807 bmap_size = ROUND_UP(bmap_size, SECTOR_SIZE);
809 memset(&header, 0, sizeof(header));
810 pstrcpy(header.text, sizeof(header.text), VDI_TEXT);
811 header.signature = VDI_SIGNATURE;
812 header.version = VDI_VERSION_1_1;
813 header.header_size = 0x180;
814 header.image_type = image_type;
815 header.offset_bmap = 0x200;
816 header.offset_data = 0x200 + bmap_size;
817 header.sector_size = SECTOR_SIZE;
818 header.disk_size = bytes;
819 header.block_size = block_size;
820 header.blocks_in_image = blocks;
821 if (image_type == VDI_TYPE_STATIC) {
822 header.blocks_allocated = blocks;
824 uuid_generate(header.uuid_image);
825 uuid_generate(header.uuid_last_snap);
826 /* There is no need to set header.uuid_link or header.uuid_parent here. */
827 #if defined(CONFIG_VDI_DEBUG)
828 vdi_header_print(&header);
829 #endif
830 vdi_header_to_le(&header);
831 ret = blk_pwrite(blk, offset, &header, sizeof(header), 0);
832 if (ret < 0) {
833 error_setg(errp, "Error writing header to %s", filename);
834 goto exit;
836 offset += sizeof(header);
838 if (bmap_size > 0) {
839 bmap = g_try_malloc0(bmap_size);
840 if (bmap == NULL) {
841 ret = -ENOMEM;
842 error_setg(errp, "Could not allocate bmap");
843 goto exit;
845 for (i = 0; i < blocks; i++) {
846 if (image_type == VDI_TYPE_STATIC) {
847 bmap[i] = i;
848 } else {
849 bmap[i] = VDI_UNALLOCATED;
852 ret = blk_pwrite(blk, offset, bmap, bmap_size, 0);
853 if (ret < 0) {
854 error_setg(errp, "Error writing bmap to %s", filename);
855 goto exit;
857 offset += bmap_size;
860 if (image_type == VDI_TYPE_STATIC) {
861 ret = blk_truncate(blk, offset + blocks * block_size);
862 if (ret < 0) {
863 error_setg(errp, "Failed to statically allocate %s", filename);
864 goto exit;
868 exit:
869 blk_unref(blk);
870 g_free(bmap);
871 return ret;
874 static void vdi_close(BlockDriverState *bs)
876 BDRVVdiState *s = bs->opaque;
878 qemu_vfree(s->bmap);
880 migrate_del_blocker(s->migration_blocker);
881 error_free(s->migration_blocker);
884 static QemuOptsList vdi_create_opts = {
885 .name = "vdi-create-opts",
886 .head = QTAILQ_HEAD_INITIALIZER(vdi_create_opts.head),
887 .desc = {
889 .name = BLOCK_OPT_SIZE,
890 .type = QEMU_OPT_SIZE,
891 .help = "Virtual disk size"
893 #if defined(CONFIG_VDI_BLOCK_SIZE)
895 .name = BLOCK_OPT_CLUSTER_SIZE,
896 .type = QEMU_OPT_SIZE,
897 .help = "VDI cluster (block) size",
898 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
900 #endif
901 #if defined(CONFIG_VDI_STATIC_IMAGE)
903 .name = BLOCK_OPT_STATIC,
904 .type = QEMU_OPT_BOOL,
905 .help = "VDI static (pre-allocated) image",
906 .def_value_str = "off"
908 #endif
909 /* TODO: An additional option to set UUID values might be useful. */
910 { /* end of list */ }
914 static BlockDriver bdrv_vdi = {
915 .format_name = "vdi",
916 .instance_size = sizeof(BDRVVdiState),
917 .bdrv_probe = vdi_probe,
918 .bdrv_open = vdi_open,
919 .bdrv_close = vdi_close,
920 .bdrv_reopen_prepare = vdi_reopen_prepare,
921 .bdrv_create = vdi_create,
922 .bdrv_has_zero_init = bdrv_has_zero_init_1,
923 .bdrv_co_get_block_status = vdi_co_get_block_status,
924 .bdrv_make_empty = vdi_make_empty,
926 .bdrv_co_preadv = vdi_co_preadv,
927 #if defined(CONFIG_VDI_WRITE)
928 .bdrv_co_pwritev = vdi_co_pwritev,
929 #endif
931 .bdrv_get_info = vdi_get_info,
933 .create_opts = &vdi_create_opts,
934 .bdrv_check = vdi_check,
937 static void bdrv_vdi_init(void)
939 logout("\n");
940 bdrv_register(&bdrv_vdi);
943 block_init(bdrv_vdi_init);