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