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