]> git.proxmox.com Git - mirror_qemu.git/blame - block/vdi.c
virtio: decrement vq->inuse in virtqueue_discard()
[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"
58369e22 57#include "qemu/bswap.h"
caf71f86 58#include "migration/migration.h"
10817bf0 59#include "qemu/coroutine.h"
f348b6d1 60#include "qemu/cutils.h"
9aebd98a 61
ee682d27 62#if defined(CONFIG_UUID)
9aebd98a
SW
63#include <uuid/uuid.h>
64#else
65/* TODO: move uuid emulation to some central place in QEMU. */
9c17d615 66#include "sysemu/sysemu.h" /* UUID_FMT */
9aebd98a 67typedef unsigned char uuid_t[16];
9aebd98a
SW
68#endif
69
70/* Code configuration options. */
71
72/* Enable debug messages. */
73//~ #define CONFIG_VDI_DEBUG
74
75/* Support write operations on VDI images. */
76#define CONFIG_VDI_WRITE
77
78/* Support non-standard block (cluster) size. This is untested.
79 * Maybe it will be needed for very large images.
80 */
81//~ #define CONFIG_VDI_BLOCK_SIZE
82
83/* Support static (fixed, pre-allocated) images. */
84#define CONFIG_VDI_STATIC_IMAGE
85
86/* Command line option for static images. */
87#define BLOCK_OPT_STATIC "static"
88
89#define KiB 1024
90#define MiB (KiB * KiB)
91
92#define SECTOR_SIZE 512
99cce9fa 93#define DEFAULT_CLUSTER_SIZE (1 * MiB)
9aebd98a
SW
94
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
101
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
ee682d27 143#if !defined(CONFIG_UUID)
8ba2aae3 144static inline void uuid_generate(uuid_t out)
9aebd98a 145{
4f3669ea 146 memset(out, 0, sizeof(uuid_t));
9aebd98a
SW
147}
148
8ba2aae3 149static inline int uuid_is_null(const uuid_t uu)
9aebd98a
SW
150{
151 uuid_t null_uuid = { 0 };
4f3669ea 152 return memcmp(uu, null_uuid, sizeof(uuid_t)) == 0;
9aebd98a
SW
153}
154
f18a768e 155# if defined(CONFIG_VDI_DEBUG)
8ba2aae3 156static inline void uuid_unparse(const uuid_t uu, char *out)
9aebd98a
SW
157{
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]);
161}
f18a768e 162# endif
9aebd98a
SW
163#endif
164
9aebd98a
SW
165typedef 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];
8368febd 190} QEMU_PACKED VdiHeader;
9aebd98a
SW
191
192typedef struct {
9aebd98a
SW
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;
4ff9786c 201 /* VDI header (converted to host endianness). */
9aebd98a 202 VdiHeader header;
fc9d106c 203
f0ab6f10
HR
204 CoMutex write_lock;
205
fc9d106c 206 Error *migration_blocker;
9aebd98a
SW
207} BDRVVdiState;
208
209/* Change UUID from little endian (IPRT = VirtualBox format) to big endian
210 * format (network byte order, standard, see RFC 4122) and vice versa.
211 */
212static void uuid_convert(uuid_t uuid)
213{
214 bswap32s((uint32_t *)&uuid[0]);
215 bswap16s((uint16_t *)&uuid[4]);
216 bswap16s((uint16_t *)&uuid[6]);
217}
218
219static void vdi_header_to_cpu(VdiHeader *header)
220{
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);
241}
242
243static void vdi_header_to_le(VdiHeader *header)
244{
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);
9aebd98a
SW
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);
265}
266
267#if defined(CONFIG_VDI_DEBUG)
268static void vdi_header_print(VdiHeader *header)
269{
270 char uuid[37];
271 logout("text %s", header->text);
9f0470bb 272 logout("signature 0x%08x\n", header->signature);
9aebd98a
SW
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);
297}
298#endif
299
4534ff54
KW
300static int vdi_check(BlockDriverState *bs, BdrvCheckResult *res,
301 BdrvCheckMode fix)
9aebd98a
SW
302{
303 /* TODO: additional checks possible. */
304 BDRVVdiState *s = (BDRVVdiState *)bs->opaque;
9aebd98a
SW
305 uint32_t blocks_allocated = 0;
306 uint32_t block;
307 uint32_t *bmap;
308 logout("\n");
309
4534ff54
KW
310 if (fix) {
311 return -ENOTSUP;
312 }
313
5839e53b 314 bmap = g_try_new(uint32_t, s->header.blocks_in_image);
17cce735
KW
315 if (s->header.blocks_in_image && bmap == NULL) {
316 res->check_errors++;
317 return -ENOMEM;
318 }
319
9aebd98a
SW
320 memset(bmap, 0xff, s->header.blocks_in_image * sizeof(uint32_t));
321
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]);
c794b4e0 325 if (VDI_IS_ALLOCATED(bmap_entry)) {
9aebd98a
SW
326 if (bmap_entry < s->header.blocks_in_image) {
327 blocks_allocated++;
c794b4e0 328 if (!VDI_IS_ALLOCATED(bmap[bmap_entry])) {
9aebd98a
SW
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);
9ac228e0 333 res->corruptions++;
9aebd98a
SW
334 }
335 } else {
336 fprintf(stderr, "ERROR: block index %" PRIu32
337 " too large, is %" PRIu32 "\n", block, bmap_entry);
9ac228e0 338 res->corruptions++;
9aebd98a
SW
339 }
340 }
341 }
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);
9ac228e0 346 res->corruptions++;
9aebd98a
SW
347 }
348
7267c094 349 g_free(bmap);
9aebd98a 350
9ac228e0 351 return 0;
9aebd98a
SW
352}
353
354static int vdi_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
355{
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;
95de6d70 362 bdi->unallocated_blocks_are_zero = true;
9aebd98a
SW
363 return 0;
364}
365
366static int vdi_make_empty(BlockDriverState *bs)
367{
368 /* TODO: missing code. */
369 logout("\n");
370 /* The return value for missing code must be 0, see block.c. */
371 return 0;
372}
373
374static int vdi_probe(const uint8_t *buf, int buf_size, const char *filename)
375{
376 const VdiHeader *header = (const VdiHeader *)buf;
dddc7750 377 int ret = 0;
9aebd98a
SW
378
379 logout("\n");
380
381 if (buf_size < sizeof(*header)) {
382 /* Header too small, no VDI. */
383 } else if (le32_to_cpu(header->signature) == VDI_SIGNATURE) {
dddc7750 384 ret = 100;
9aebd98a
SW
385 }
386
dddc7750 387 if (ret == 0) {
9aebd98a
SW
388 logout("no vdi image\n");
389 } else {
390 logout("%s", header->text);
391 }
392
dddc7750 393 return ret;
9aebd98a
SW
394}
395
015a1036
HR
396static int vdi_open(BlockDriverState *bs, QDict *options, int flags,
397 Error **errp)
9aebd98a
SW
398{
399 BDRVVdiState *s = bs->opaque;
400 VdiHeader header;
401 size_t bmap_size;
8937f822 402 int ret;
9aebd98a
SW
403
404 logout("\n");
405
fbcbbf4e 406 ret = bdrv_read(bs->file, 0, (uint8_t *)&header, 1);
8937f822 407 if (ret < 0) {
9aebd98a
SW
408 goto fail;
409 }
410
411 vdi_header_to_cpu(&header);
412#if defined(CONFIG_VDI_DEBUG)
413 vdi_header_print(&header);
414#endif
415
63fa06dc
JC
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;
422 }
423
f21dc3a4
SW
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);
e9082e47 429 header.disk_size = ROUND_UP(header.disk_size, SECTOR_SIZE);
f21dc3a4
SW
430 }
431
0e87ba2c 432 if (header.signature != VDI_SIGNATURE) {
521b2b5d
HR
433 error_setg(errp, "Image not in VDI format (bad signature %08" PRIx32
434 ")", header.signature);
76abe407 435 ret = -EINVAL;
0e87ba2c
SW
436 goto fail;
437 } else if (header.version != VDI_VERSION_1_1) {
521b2b5d
HR
438 error_setg(errp, "unsupported VDI image (version %" PRIu32 ".%" PRIu32
439 ")", header.version >> 16, header.version & 0xffff);
8937f822 440 ret = -ENOTSUP;
9aebd98a
SW
441 goto fail;
442 } else if (header.offset_bmap % SECTOR_SIZE != 0) {
443 /* We only support block maps which start on a sector boundary. */
5b7aa9b5 444 error_setg(errp, "unsupported VDI image (unaligned block map offset "
521b2b5d 445 "0x%" PRIx32 ")", header.offset_bmap);
8937f822 446 ret = -ENOTSUP;
9aebd98a
SW
447 goto fail;
448 } else if (header.offset_data % SECTOR_SIZE != 0) {
449 /* We only support data blocks which start on a sector boundary. */
521b2b5d
HR
450 error_setg(errp, "unsupported VDI image (unaligned data offset 0x%"
451 PRIx32 ")", header.offset_data);
8937f822 452 ret = -ENOTSUP;
9aebd98a
SW
453 goto fail;
454 } else if (header.sector_size != SECTOR_SIZE) {
521b2b5d
HR
455 error_setg(errp, "unsupported VDI image (sector size %" PRIu32
456 " is not %u)", header.sector_size, SECTOR_SIZE);
8937f822 457 ret = -ENOTSUP;
9aebd98a 458 goto fail;
63fa06dc 459 } else if (header.block_size != DEFAULT_CLUSTER_SIZE) {
521b2b5d
HR
460 error_setg(errp, "unsupported VDI image (block size %" PRIu32
461 " is not %u)", header.block_size, DEFAULT_CLUSTER_SIZE);
8937f822 462 ret = -ENOTSUP;
9aebd98a 463 goto fail;
f21dc3a4
SW
464 } else if (header.disk_size >
465 (uint64_t)header.blocks_in_image * header.block_size) {
5b7aa9b5
PB
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);
8937f822 470 ret = -ENOTSUP;
9aebd98a
SW
471 goto fail;
472 } else if (!uuid_is_null(header.uuid_link)) {
5b7aa9b5 473 error_setg(errp, "unsupported VDI image (non-NULL link UUID)");
8937f822 474 ret = -ENOTSUP;
9aebd98a
SW
475 goto fail;
476 } else if (!uuid_is_null(header.uuid_parent)) {
5b7aa9b5 477 error_setg(errp, "unsupported VDI image (non-NULL parent UUID)");
8937f822 478 ret = -ENOTSUP;
9aebd98a 479 goto fail;
63fa06dc
JC
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;
9aebd98a
SW
486 }
487
488 bs->total_sectors = header.disk_size / SECTOR_SIZE;
489
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;
494
495 bmap_size = header.blocks_in_image * sizeof(uint32_t);
e9082e47 496 bmap_size = DIV_ROUND_UP(bmap_size, SECTOR_SIZE);
9a4f4c31 497 s->bmap = qemu_try_blockalign(bs->file->bs, bmap_size * SECTOR_SIZE);
17cce735
KW
498 if (s->bmap == NULL) {
499 ret = -ENOMEM;
500 goto fail;
501 }
502
fbcbbf4e 503 ret = bdrv_read(bs->file, s->bmap_sector, (uint8_t *)s->bmap,
9a4f4c31 504 bmap_size);
8937f822 505 if (ret < 0) {
9aebd98a
SW
506 goto fail_free_bmap;
507 }
508
fc9d106c 509 /* Disable migration when vdi images are used */
81e5f78a
AG
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));
fc9d106c
KW
513 migrate_add_blocker(s->migration_blocker);
514
f0ab6f10
HR
515 qemu_co_mutex_init(&s->write_lock);
516
9aebd98a
SW
517 return 0;
518
519 fail_free_bmap:
17cce735 520 qemu_vfree(s->bmap);
9aebd98a
SW
521
522 fail:
8937f822 523 return ret;
9aebd98a
SW
524}
525
ecfe2bba
JC
526static int vdi_reopen_prepare(BDRVReopenState *state,
527 BlockReopenQueue *queue, Error **errp)
528{
529 return 0;
530}
531
b6b8a333 532static int64_t coroutine_fn vdi_co_get_block_status(BlockDriverState *bs,
67a0fd2a 533 int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file)
9aebd98a
SW
534{
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]);
4bc74be9
PB
541 uint64_t offset;
542 int result;
543
9aebd98a
SW
544 logout("%p, %" PRId64 ", %d, %p\n", bs, sector_num, nb_sectors, pnum);
545 if (n_sectors > nb_sectors) {
546 n_sectors = nb_sectors;
547 }
548 *pnum = n_sectors;
4bc74be9
PB
549 result = VDI_IS_ALLOCATED(bmap_entry);
550 if (!result) {
551 return 0;
552 }
553
554 offset = s->header.offset_data +
555 (uint64_t)bmap_entry * s->block_size +
556 sector_in_block * SECTOR_SIZE;
8bfb1371 557 *file = bs->file->bs;
4bc74be9 558 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | offset;
9aebd98a
SW
559}
560
0865bb6f
KW
561static int coroutine_fn
562vdi_co_preadv(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
563 QEMUIOVector *qiov, int flags)
9aebd98a 564{
9aebd98a 565 BDRVVdiState *s = bs->opaque;
0865bb6f 566 QEMUIOVector local_qiov;
9aebd98a
SW
567 uint32_t bmap_entry;
568 uint32_t block_index;
0865bb6f
KW
569 uint32_t offset_in_block;
570 uint32_t n_bytes;
571 uint64_t bytes_done = 0;
eb9566d1 572 int ret = 0;
4de659e8
PB
573
574 logout("\n");
9aebd98a 575
0865bb6f 576 qemu_iovec_init(&local_qiov, qiov->niov);
0c7bfc32 577
0865bb6f
KW
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);
582
583 logout("will read %u bytes starting at offset %" PRIu64 "\n",
584 n_bytes, offset);
eb9566d1
PB
585
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. */
0865bb6f 590 qemu_iovec_memset(qiov, bytes_done, 0, n_bytes);
eb9566d1
PB
591 ret = 0;
592 } else {
0865bb6f
KW
593 uint64_t data_offset = s->header.offset_data +
594 (uint64_t)bmap_entry * s->block_size +
595 offset_in_block;
596
597 qemu_iovec_reset(&local_qiov);
598 qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes);
599
a03ef88f 600 ret = bdrv_co_preadv(bs->file, data_offset, n_bytes,
0865bb6f 601 &local_qiov, 0);
eb9566d1 602 }
0865bb6f 603 logout("%u bytes read\n", n_bytes);
0c7bfc32 604
0865bb6f
KW
605 bytes -= n_bytes;
606 offset += n_bytes;
607 bytes_done += n_bytes;
9aebd98a 608 }
3d46a75a 609
0865bb6f
KW
610 qemu_iovec_destroy(&local_qiov);
611
3d46a75a 612 return ret;
9aebd98a
SW
613}
614
fde9d56f
KW
615static int coroutine_fn
616vdi_co_pwritev(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
617 QEMUIOVector *qiov, int flags)
9aebd98a 618{
9aebd98a 619 BDRVVdiState *s = bs->opaque;
fde9d56f 620 QEMUIOVector local_qiov;
9aebd98a
SW
621 uint32_t bmap_entry;
622 uint32_t block_index;
fde9d56f
KW
623 uint32_t offset_in_block;
624 uint32_t n_bytes;
bfc45fc1
PB
625 uint32_t bmap_first = VDI_UNALLOCATED;
626 uint32_t bmap_last = VDI_UNALLOCATED;
bfc45fc1 627 uint8_t *block = NULL;
fde9d56f 628 uint64_t bytes_done = 0;
eb9566d1 629 int ret = 0;
4de659e8
PB
630
631 logout("\n");
9aebd98a 632
fde9d56f 633 qemu_iovec_init(&local_qiov, qiov->niov);
9aebd98a 634
fde9d56f
KW
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);
639
640 logout("will write %u bytes starting at offset %" PRIu64 "\n",
641 n_bytes, offset);
eb9566d1
PB
642
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. */
fde9d56f 647 uint64_t data_offset;
eb9566d1
PB
648 bmap_entry = s->header.blocks_allocated;
649 s->bmap[block_index] = cpu_to_le32(bmap_entry);
650 s->header.blocks_allocated++;
fde9d56f
KW
651 data_offset = s->header.offset_data +
652 (uint64_t)bmap_entry * s->block_size;
eb9566d1
PB
653 if (block == NULL) {
654 block = g_malloc(s->block_size);
655 bmap_first = block_index;
656 }
657 bmap_last = block_index;
658 /* Copy data to be written to new block and zero unused parts. */
fde9d56f
KW
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);
f0ab6f10
HR
664
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);
d9ca2ea2 673 ret = bdrv_pwrite(bs->file, data_offset, block, s->block_size);
f0ab6f10 674 qemu_co_mutex_unlock(&s->write_lock);
eb9566d1 675 } else {
fde9d56f
KW
676 uint64_t data_offset = s->header.offset_data +
677 (uint64_t)bmap_entry * s->block_size +
678 offset_in_block;
f0ab6f10
HR
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);
fde9d56f
KW
689
690 qemu_iovec_reset(&local_qiov);
691 qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes);
692
a03ef88f 693 ret = bdrv_co_pwritev(bs->file, data_offset, n_bytes,
fde9d56f 694 &local_qiov, 0);
9aebd98a 695 }
0c7bfc32 696
fde9d56f
KW
697 bytes -= n_bytes;
698 offset += n_bytes;
699 bytes_done += n_bytes;
0c7bfc32 700
fde9d56f 701 logout("%u bytes written\n", n_bytes);
9aebd98a 702 }
9aebd98a 703
fde9d56f
KW
704 qemu_iovec_destroy(&local_qiov);
705
0c7bfc32 706 logout("finished data write\n");
4eea78e6
PB
707 if (ret < 0) {
708 return ret;
709 }
710
711 if (block) {
712 /* One or more new blocks were allocated. */
713 VdiHeader *header = (VdiHeader *) block;
714 uint8_t *base;
715 uint64_t offset;
fde9d56f 716 uint32_t n_sectors;
4eea78e6
PB
717
718 logout("now writing modified header\n");
719 assert(VDI_IS_ALLOCATED(bmap_first));
720 *header = s->header;
721 vdi_header_to_le(header);
18d51c4b 722 ret = bdrv_write(bs->file, 0, block, 1);
bfc45fc1
PB
723 g_free(block);
724 block = NULL;
4eea78e6
PB
725
726 if (ret < 0) {
727 return ret;
0c7bfc32 728 }
4eea78e6
PB
729
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);
18d51c4b 740 ret = bdrv_write(bs->file, offset, base, n_sectors);
0c7bfc32
PB
741 }
742
3d46a75a 743 return ret;
9aebd98a
SW
744}
745
004b7f25 746static int vdi_create(const char *filename, QemuOpts *opts, Error **errp)
9aebd98a 747{
dddc7750 748 int ret = 0;
9aebd98a
SW
749 uint64_t bytes = 0;
750 uint32_t blocks;
99cce9fa 751 size_t block_size = DEFAULT_CLUSTER_SIZE;
9aebd98a
SW
752 uint32_t image_type = VDI_TYPE_DYNAMIC;
753 VdiHeader header;
754 size_t i;
755 size_t bmap_size;
70747862
JC
756 int64_t offset = 0;
757 Error *local_err = NULL;
a08f0c3b 758 BlockBackend *blk = NULL;
70747862 759 uint32_t *bmap = NULL;
9aebd98a
SW
760
761 logout("\n");
762
763 /* Read out options. */
c2eb918e
HT
764 bytes = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
765 BDRV_SECTOR_SIZE);
9aebd98a 766#if defined(CONFIG_VDI_BLOCK_SIZE)
004b7f25
CL
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);
9aebd98a
SW
771#endif
772#if defined(CONFIG_VDI_STATIC_IMAGE)
004b7f25
CL
773 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_STATIC, false)) {
774 image_type = VDI_TYPE_STATIC;
9aebd98a 775 }
004b7f25 776#endif
9aebd98a 777
63fa06dc 778 if (bytes > VDI_DISK_SIZE_MAX) {
dddc7750 779 ret = -ENOTSUP;
63fa06dc
JC
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;
784 }
785
dddc7750
JC
786 ret = bdrv_create_file(filename, opts, &local_err);
787 if (ret < 0) {
70747862 788 error_propagate(errp, local_err);
63fa06dc 789 goto exit;
9aebd98a 790 }
a08f0c3b 791
efaa7c4e 792 blk = blk_new_open(filename, NULL, NULL,
72e775c7 793 BDRV_O_RDWR | BDRV_O_PROTOCOL, &local_err);
a08f0c3b 794 if (blk == NULL) {
70747862 795 error_propagate(errp, local_err);
a08f0c3b 796 ret = -EIO;
70747862 797 goto exit;
4ab15590
CL
798 }
799
a08f0c3b
KW
800 blk_set_allow_write_beyond_eof(blk, true);
801
f21dc3a4
SW
802 /* We need enough blocks to store the given disk size,
803 so always round up. */
e9082e47 804 blocks = DIV_ROUND_UP(bytes, block_size);
f21dc3a4 805
9aebd98a 806 bmap_size = blocks * sizeof(uint32_t);
e9082e47 807 bmap_size = ROUND_UP(bmap_size, SECTOR_SIZE);
9aebd98a
SW
808
809 memset(&header, 0, sizeof(header));
1786dc15 810 pstrcpy(header.text, sizeof(header.text), VDI_TEXT);
9aebd98a
SW
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;
6eea90eb
SW
821 if (image_type == VDI_TYPE_STATIC) {
822 header.blocks_allocated = blocks;
823 }
9aebd98a
SW
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);
8341f00d 831 ret = blk_pwrite(blk, offset, &header, sizeof(header), 0);
dddc7750 832 if (ret < 0) {
70747862
JC
833 error_setg(errp, "Error writing header to %s", filename);
834 goto exit;
9aebd98a 835 }
70747862 836 offset += sizeof(header);
9aebd98a 837
b76b6e95 838 if (bmap_size > 0) {
17cce735
KW
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;
844 }
514f21a5
SW
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;
850 }
9aebd98a 851 }
8341f00d 852 ret = blk_pwrite(blk, offset, bmap, bmap_size, 0);
dddc7750 853 if (ret < 0) {
70747862
JC
854 error_setg(errp, "Error writing bmap to %s", filename);
855 goto exit;
514f21a5 856 }
70747862 857 offset += bmap_size;
9aebd98a 858 }
514f21a5 859
9aebd98a 860 if (image_type == VDI_TYPE_STATIC) {
a08f0c3b 861 ret = blk_truncate(blk, offset + blocks * block_size);
dddc7750 862 if (ret < 0) {
70747862
JC
863 error_setg(errp, "Failed to statically allocate %s", filename);
864 goto exit;
9aebd98a
SW
865 }
866 }
867
63fa06dc 868exit:
a08f0c3b 869 blk_unref(blk);
70747862 870 g_free(bmap);
dddc7750 871 return ret;
9aebd98a
SW
872}
873
874static void vdi_close(BlockDriverState *bs)
875{
fc9d106c 876 BDRVVdiState *s = bs->opaque;
6ac5f388 877
17cce735 878 qemu_vfree(s->bmap);
6ac5f388 879
fc9d106c
KW
880 migrate_del_blocker(s->migration_blocker);
881 error_free(s->migration_blocker);
9aebd98a
SW
882}
883
004b7f25
CL
884static QemuOptsList vdi_create_opts = {
885 .name = "vdi-create-opts",
886 .head = QTAILQ_HEAD_INITIALIZER(vdi_create_opts.head),
887 .desc = {
888 {
889 .name = BLOCK_OPT_SIZE,
890 .type = QEMU_OPT_SIZE,
891 .help = "Virtual disk size"
892 },
9aebd98a 893#if defined(CONFIG_VDI_BLOCK_SIZE)
004b7f25
CL
894 {
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)
899 },
9aebd98a
SW
900#endif
901#if defined(CONFIG_VDI_STATIC_IMAGE)
004b7f25
CL
902 {
903 .name = BLOCK_OPT_STATIC,
904 .type = QEMU_OPT_BOOL,
905 .help = "VDI static (pre-allocated) image",
906 .def_value_str = "off"
907 },
9aebd98a 908#endif
004b7f25
CL
909 /* TODO: An additional option to set UUID values might be useful. */
910 { /* end of list */ }
911 }
9aebd98a
SW
912};
913
914static 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,
ecfe2bba 920 .bdrv_reopen_prepare = vdi_reopen_prepare,
c282e1fd 921 .bdrv_create = vdi_create,
3ac21627 922 .bdrv_has_zero_init = bdrv_has_zero_init_1,
b6b8a333 923 .bdrv_co_get_block_status = vdi_co_get_block_status,
9aebd98a
SW
924 .bdrv_make_empty = vdi_make_empty,
925
0865bb6f 926 .bdrv_co_preadv = vdi_co_preadv,
9aebd98a 927#if defined(CONFIG_VDI_WRITE)
fde9d56f 928 .bdrv_co_pwritev = vdi_co_pwritev,
9aebd98a
SW
929#endif
930
931 .bdrv_get_info = vdi_get_info,
932
004b7f25 933 .create_opts = &vdi_create_opts,
9aebd98a
SW
934 .bdrv_check = vdi_check,
935};
936
937static void bdrv_vdi_init(void)
938{
939 logout("\n");
940 bdrv_register(&bdrv_vdi);
941}
942
943block_init(bdrv_vdi_init);