]> git.proxmox.com Git - mirror_qemu.git/blame - block/vdi.c
iotests: use python logging for iotests.log()
[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"
f043568f 53#include "qemu/units.h"
da34e65c 54#include "qapi/error.h"
49858b50
HR
55#include "qapi/qobject-input-visitor.h"
56#include "qapi/qapi-visit-block-core.h"
737e150e 57#include "block/block_int.h"
f853465a 58#include "block/qdict.h"
a08f0c3b 59#include "sysemu/block-backend.h"
1de7afc9 60#include "qemu/module.h"
922a01a0 61#include "qemu/option.h"
58369e22 62#include "qemu/bswap.h"
795c40b8 63#include "migration/blocker.h"
10817bf0 64#include "qemu/coroutine.h"
f348b6d1 65#include "qemu/cutils.h"
7c6f55b6 66#include "qemu/uuid.h"
9aebd98a
SW
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
9aebd98a 87#define SECTOR_SIZE 512
14632122
MA
88#define DEFAULT_CLUSTER_SIZE 1048576
89/* Note: can't use 1 * MiB, because it's passed to stringify() */
9aebd98a
SW
90
91#if defined(CONFIG_VDI_DEBUG)
b80666bf 92#define VDI_DEBUG 1
9aebd98a 93#else
b80666bf 94#define VDI_DEBUG 0
9aebd98a
SW
95#endif
96
b80666bf
EB
97#define logout(fmt, ...) \
98 do { \
99 if (VDI_DEBUG) { \
100 fprintf(stderr, "vdi\t%-24s" fmt, __func__, ##__VA_ARGS__); \
101 } \
102 } while (0)
103
9aebd98a
SW
104/* Image signature. */
105#define VDI_SIGNATURE 0xbeda107f
106
107/* Image version. */
108#define VDI_VERSION_1_1 0x00010001
109
110/* Image type. */
111#define VDI_TYPE_DYNAMIC 1
112#define VDI_TYPE_STATIC 2
113
114/* Innotek / SUN images use these strings in header.text:
115 * "<<< innotek VirtualBox Disk Image >>>\n"
116 * "<<< Sun xVM VirtualBox Disk Image >>>\n"
117 * "<<< Sun VirtualBox Disk Image >>>\n"
118 * The value does not matter, so QEMU created images use a different text.
119 */
120#define VDI_TEXT "<<< QEMU VM Virtual Disk Image >>>\n"
121
c794b4e0
ES
122/* A never-allocated block; semantically arbitrary content. */
123#define VDI_UNALLOCATED 0xffffffffU
124
125/* A discarded (no longer allocated) block; semantically zero-filled. */
126#define VDI_DISCARDED 0xfffffffeU
127
128#define VDI_IS_ALLOCATED(X) ((X) < VDI_DISCARDED)
9aebd98a 129
d20418ee
HR
130/* The bmap will take up VDI_BLOCKS_IN_IMAGE_MAX * sizeof(uint32_t) bytes; since
131 * the bmap is read and written in a single operation, its size needs to be
132 * limited to INT_MAX; furthermore, when opening an image, the bmap size is
133 * rounded up to be aligned on BDRV_SECTOR_SIZE.
134 * Therefore this should satisfy the following:
135 * VDI_BLOCKS_IN_IMAGE_MAX * sizeof(uint32_t) + BDRV_SECTOR_SIZE == INT_MAX + 1
136 * (INT_MAX + 1 is the first value not representable as an int)
137 * This guarantees that any value below or equal to the constant will, when
138 * multiplied by sizeof(uint32_t) and rounded up to a BDRV_SECTOR_SIZE boundary,
139 * still be below or equal to INT_MAX. */
140#define VDI_BLOCKS_IN_IMAGE_MAX \
141 ((unsigned)((INT_MAX + 1u - BDRV_SECTOR_SIZE) / sizeof(uint32_t)))
63fa06dc
JC
142#define VDI_DISK_SIZE_MAX ((uint64_t)VDI_BLOCKS_IN_IMAGE_MAX * \
143 (uint64_t)DEFAULT_CLUSTER_SIZE)
144
49858b50
HR
145static QemuOptsList vdi_create_opts;
146
9aebd98a
SW
147typedef struct {
148 char text[0x40];
149 uint32_t signature;
150 uint32_t version;
151 uint32_t header_size;
152 uint32_t image_type;
153 uint32_t image_flags;
154 char description[256];
155 uint32_t offset_bmap;
156 uint32_t offset_data;
157 uint32_t cylinders; /* disk geometry, unused here */
158 uint32_t heads; /* disk geometry, unused here */
159 uint32_t sectors; /* disk geometry, unused here */
160 uint32_t sector_size;
161 uint32_t unused1;
162 uint64_t disk_size;
163 uint32_t block_size;
164 uint32_t block_extra; /* unused here */
165 uint32_t blocks_in_image;
166 uint32_t blocks_allocated;
7c6f55b6
FZ
167 QemuUUID uuid_image;
168 QemuUUID uuid_last_snap;
169 QemuUUID uuid_link;
170 QemuUUID uuid_parent;
9aebd98a 171 uint64_t unused2[7];
8368febd 172} QEMU_PACKED VdiHeader;
9aebd98a 173
d4f18971
AG
174QEMU_BUILD_BUG_ON(sizeof(VdiHeader) != 512);
175
9aebd98a 176typedef struct {
9aebd98a
SW
177 /* The block map entries are little endian (even in memory). */
178 uint32_t *bmap;
179 /* Size of block (bytes). */
180 uint32_t block_size;
9aebd98a
SW
181 /* First sector of block map. */
182 uint32_t bmap_sector;
4ff9786c 183 /* VDI header (converted to host endianness). */
9aebd98a 184 VdiHeader header;
fc9d106c 185
1e886639 186 CoRwlock bmap_lock;
f0ab6f10 187
fc9d106c 188 Error *migration_blocker;
9aebd98a
SW
189} BDRVVdiState;
190
9aebd98a
SW
191static void vdi_header_to_cpu(VdiHeader *header)
192{
09190184
PM
193 header->signature = le32_to_cpu(header->signature);
194 header->version = le32_to_cpu(header->version);
195 header->header_size = le32_to_cpu(header->header_size);
196 header->image_type = le32_to_cpu(header->image_type);
197 header->image_flags = le32_to_cpu(header->image_flags);
198 header->offset_bmap = le32_to_cpu(header->offset_bmap);
199 header->offset_data = le32_to_cpu(header->offset_data);
200 header->cylinders = le32_to_cpu(header->cylinders);
201 header->heads = le32_to_cpu(header->heads);
202 header->sectors = le32_to_cpu(header->sectors);
203 header->sector_size = le32_to_cpu(header->sector_size);
204 header->disk_size = le64_to_cpu(header->disk_size);
205 header->block_size = le32_to_cpu(header->block_size);
206 header->block_extra = le32_to_cpu(header->block_extra);
207 header->blocks_in_image = le32_to_cpu(header->blocks_in_image);
208 header->blocks_allocated = le32_to_cpu(header->blocks_allocated);
1324f063
PM
209 header->uuid_image = qemu_uuid_bswap(header->uuid_image);
210 header->uuid_last_snap = qemu_uuid_bswap(header->uuid_last_snap);
211 header->uuid_link = qemu_uuid_bswap(header->uuid_link);
212 header->uuid_parent = qemu_uuid_bswap(header->uuid_parent);
9aebd98a
SW
213}
214
215static void vdi_header_to_le(VdiHeader *header)
216{
09190184
PM
217 header->signature = cpu_to_le32(header->signature);
218 header->version = cpu_to_le32(header->version);
219 header->header_size = cpu_to_le32(header->header_size);
220 header->image_type = cpu_to_le32(header->image_type);
221 header->image_flags = cpu_to_le32(header->image_flags);
222 header->offset_bmap = cpu_to_le32(header->offset_bmap);
223 header->offset_data = cpu_to_le32(header->offset_data);
224 header->cylinders = cpu_to_le32(header->cylinders);
225 header->heads = cpu_to_le32(header->heads);
226 header->sectors = cpu_to_le32(header->sectors);
227 header->sector_size = cpu_to_le32(header->sector_size);
228 header->disk_size = cpu_to_le64(header->disk_size);
229 header->block_size = cpu_to_le32(header->block_size);
230 header->block_extra = cpu_to_le32(header->block_extra);
231 header->blocks_in_image = cpu_to_le32(header->blocks_in_image);
232 header->blocks_allocated = cpu_to_le32(header->blocks_allocated);
1324f063
PM
233 header->uuid_image = qemu_uuid_bswap(header->uuid_image);
234 header->uuid_last_snap = qemu_uuid_bswap(header->uuid_last_snap);
235 header->uuid_link = qemu_uuid_bswap(header->uuid_link);
236 header->uuid_parent = qemu_uuid_bswap(header->uuid_parent);
9aebd98a
SW
237}
238
9aebd98a
SW
239static void vdi_header_print(VdiHeader *header)
240{
ac928b8e
PM
241 char uuidstr[37];
242 QemuUUID uuid;
9aebd98a 243 logout("text %s", header->text);
9f0470bb 244 logout("signature 0x%08x\n", header->signature);
9aebd98a
SW
245 logout("header size 0x%04x\n", header->header_size);
246 logout("image type 0x%04x\n", header->image_type);
247 logout("image flags 0x%04x\n", header->image_flags);
248 logout("description %s\n", header->description);
249 logout("offset bmap 0x%04x\n", header->offset_bmap);
250 logout("offset data 0x%04x\n", header->offset_data);
251 logout("cylinders 0x%04x\n", header->cylinders);
252 logout("heads 0x%04x\n", header->heads);
253 logout("sectors 0x%04x\n", header->sectors);
254 logout("sector size 0x%04x\n", header->sector_size);
255 logout("image size 0x%" PRIx64 " B (%" PRIu64 " MiB)\n",
256 header->disk_size, header->disk_size / MiB);
257 logout("block size 0x%04x\n", header->block_size);
258 logout("block extra 0x%04x\n", header->block_extra);
259 logout("blocks tot. 0x%04x\n", header->blocks_in_image);
260 logout("blocks all. 0x%04x\n", header->blocks_allocated);
ac928b8e
PM
261 uuid = header->uuid_image;
262 qemu_uuid_unparse(&uuid, uuidstr);
263 logout("uuid image %s\n", uuidstr);
264 uuid = header->uuid_last_snap;
265 qemu_uuid_unparse(&uuid, uuidstr);
266 logout("uuid snap %s\n", uuidstr);
267 uuid = header->uuid_link;
268 qemu_uuid_unparse(&uuid, uuidstr);
269 logout("uuid link %s\n", uuidstr);
270 uuid = header->uuid_parent;
271 qemu_uuid_unparse(&uuid, uuidstr);
272 logout("uuid parent %s\n", uuidstr);
9aebd98a 273}
9aebd98a 274
2fd61638
PB
275static int coroutine_fn vdi_co_check(BlockDriverState *bs, BdrvCheckResult *res,
276 BdrvCheckMode fix)
9aebd98a
SW
277{
278 /* TODO: additional checks possible. */
279 BDRVVdiState *s = (BDRVVdiState *)bs->opaque;
9aebd98a
SW
280 uint32_t blocks_allocated = 0;
281 uint32_t block;
282 uint32_t *bmap;
283 logout("\n");
284
4534ff54
KW
285 if (fix) {
286 return -ENOTSUP;
287 }
288
5839e53b 289 bmap = g_try_new(uint32_t, s->header.blocks_in_image);
17cce735
KW
290 if (s->header.blocks_in_image && bmap == NULL) {
291 res->check_errors++;
292 return -ENOMEM;
293 }
294
9aebd98a
SW
295 memset(bmap, 0xff, s->header.blocks_in_image * sizeof(uint32_t));
296
297 /* Check block map and value of blocks_allocated. */
298 for (block = 0; block < s->header.blocks_in_image; block++) {
299 uint32_t bmap_entry = le32_to_cpu(s->bmap[block]);
c794b4e0 300 if (VDI_IS_ALLOCATED(bmap_entry)) {
9aebd98a
SW
301 if (bmap_entry < s->header.blocks_in_image) {
302 blocks_allocated++;
c794b4e0 303 if (!VDI_IS_ALLOCATED(bmap[bmap_entry])) {
9aebd98a
SW
304 bmap[bmap_entry] = bmap_entry;
305 } else {
306 fprintf(stderr, "ERROR: block index %" PRIu32
307 " also used by %" PRIu32 "\n", bmap[bmap_entry], bmap_entry);
9ac228e0 308 res->corruptions++;
9aebd98a
SW
309 }
310 } else {
311 fprintf(stderr, "ERROR: block index %" PRIu32
312 " too large, is %" PRIu32 "\n", block, bmap_entry);
9ac228e0 313 res->corruptions++;
9aebd98a
SW
314 }
315 }
316 }
317 if (blocks_allocated != s->header.blocks_allocated) {
318 fprintf(stderr, "ERROR: allocated blocks mismatch, is %" PRIu32
319 ", should be %" PRIu32 "\n",
320 blocks_allocated, s->header.blocks_allocated);
9ac228e0 321 res->corruptions++;
9aebd98a
SW
322 }
323
7267c094 324 g_free(bmap);
9aebd98a 325
9ac228e0 326 return 0;
9aebd98a
SW
327}
328
329static int vdi_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
330{
331 /* TODO: vdi_get_info would be needed for machine snapshots.
332 vm_state_offset is still missing. */
333 BDRVVdiState *s = (BDRVVdiState *)bs->opaque;
334 logout("\n");
335 bdi->cluster_size = s->block_size;
336 bdi->vm_state_offset = 0;
95de6d70 337 bdi->unallocated_blocks_are_zero = true;
9aebd98a
SW
338 return 0;
339}
340
341static int vdi_make_empty(BlockDriverState *bs)
342{
343 /* TODO: missing code. */
344 logout("\n");
345 /* The return value for missing code must be 0, see block.c. */
346 return 0;
347}
348
349static int vdi_probe(const uint8_t *buf, int buf_size, const char *filename)
350{
351 const VdiHeader *header = (const VdiHeader *)buf;
dddc7750 352 int ret = 0;
9aebd98a
SW
353
354 logout("\n");
355
356 if (buf_size < sizeof(*header)) {
357 /* Header too small, no VDI. */
358 } else if (le32_to_cpu(header->signature) == VDI_SIGNATURE) {
dddc7750 359 ret = 100;
9aebd98a
SW
360 }
361
dddc7750 362 if (ret == 0) {
9aebd98a
SW
363 logout("no vdi image\n");
364 } else {
365 logout("%s", header->text);
366 }
367
dddc7750 368 return ret;
9aebd98a
SW
369}
370
015a1036
HR
371static int vdi_open(BlockDriverState *bs, QDict *options, int flags,
372 Error **errp)
9aebd98a
SW
373{
374 BDRVVdiState *s = bs->opaque;
375 VdiHeader header;
376 size_t bmap_size;
8937f822 377 int ret;
fe44dc91 378 Error *local_err = NULL;
ac928b8e 379 QemuUUID uuid_link, uuid_parent;
9aebd98a 380
4e4bf5c4
KW
381 bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
382 false, errp);
383 if (!bs->file) {
384 return -EINVAL;
385 }
386
9aebd98a
SW
387 logout("\n");
388
d4f18971 389 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
8937f822 390 if (ret < 0) {
9aebd98a
SW
391 goto fail;
392 }
393
394 vdi_header_to_cpu(&header);
95a14d51
KW
395 if (VDI_DEBUG) {
396 vdi_header_print(&header);
397 }
9aebd98a 398
63fa06dc
JC
399 if (header.disk_size > VDI_DISK_SIZE_MAX) {
400 error_setg(errp, "Unsupported VDI image size (size is 0x%" PRIx64
401 ", max supported is 0x%" PRIx64 ")",
402 header.disk_size, VDI_DISK_SIZE_MAX);
403 ret = -ENOTSUP;
404 goto fail;
405 }
406
ac928b8e
PM
407 uuid_link = header.uuid_link;
408 uuid_parent = header.uuid_parent;
409
f21dc3a4
SW
410 if (header.disk_size % SECTOR_SIZE != 0) {
411 /* 'VBoxManage convertfromraw' can create images with odd disk sizes.
412 We accept them but round the disk size to the next multiple of
413 SECTOR_SIZE. */
414 logout("odd disk size %" PRIu64 " B, round up\n", header.disk_size);
e9082e47 415 header.disk_size = ROUND_UP(header.disk_size, SECTOR_SIZE);
f21dc3a4
SW
416 }
417
0e87ba2c 418 if (header.signature != VDI_SIGNATURE) {
521b2b5d
HR
419 error_setg(errp, "Image not in VDI format (bad signature %08" PRIx32
420 ")", header.signature);
76abe407 421 ret = -EINVAL;
0e87ba2c
SW
422 goto fail;
423 } else if (header.version != VDI_VERSION_1_1) {
521b2b5d
HR
424 error_setg(errp, "unsupported VDI image (version %" PRIu32 ".%" PRIu32
425 ")", header.version >> 16, header.version & 0xffff);
8937f822 426 ret = -ENOTSUP;
9aebd98a
SW
427 goto fail;
428 } else if (header.offset_bmap % SECTOR_SIZE != 0) {
429 /* We only support block maps which start on a sector boundary. */
5b7aa9b5 430 error_setg(errp, "unsupported VDI image (unaligned block map offset "
521b2b5d 431 "0x%" PRIx32 ")", header.offset_bmap);
8937f822 432 ret = -ENOTSUP;
9aebd98a
SW
433 goto fail;
434 } else if (header.offset_data % SECTOR_SIZE != 0) {
435 /* We only support data blocks which start on a sector boundary. */
521b2b5d
HR
436 error_setg(errp, "unsupported VDI image (unaligned data offset 0x%"
437 PRIx32 ")", header.offset_data);
8937f822 438 ret = -ENOTSUP;
9aebd98a
SW
439 goto fail;
440 } else if (header.sector_size != SECTOR_SIZE) {
521b2b5d
HR
441 error_setg(errp, "unsupported VDI image (sector size %" PRIu32
442 " is not %u)", header.sector_size, SECTOR_SIZE);
8937f822 443 ret = -ENOTSUP;
9aebd98a 444 goto fail;
63fa06dc 445 } else if (header.block_size != DEFAULT_CLUSTER_SIZE) {
521b2b5d 446 error_setg(errp, "unsupported VDI image (block size %" PRIu32
3dd5b8f4 447 " is not %" PRIu32 ")",
f043568f 448 header.block_size, DEFAULT_CLUSTER_SIZE);
8937f822 449 ret = -ENOTSUP;
9aebd98a 450 goto fail;
f21dc3a4
SW
451 } else if (header.disk_size >
452 (uint64_t)header.blocks_in_image * header.block_size) {
5b7aa9b5
PB
453 error_setg(errp, "unsupported VDI image (disk size %" PRIu64 ", "
454 "image bitmap has room for %" PRIu64 ")",
455 header.disk_size,
456 (uint64_t)header.blocks_in_image * header.block_size);
8937f822 457 ret = -ENOTSUP;
9aebd98a 458 goto fail;
ac928b8e 459 } else if (!qemu_uuid_is_null(&uuid_link)) {
5b7aa9b5 460 error_setg(errp, "unsupported VDI image (non-NULL link UUID)");
8937f822 461 ret = -ENOTSUP;
9aebd98a 462 goto fail;
ac928b8e 463 } else if (!qemu_uuid_is_null(&uuid_parent)) {
5b7aa9b5 464 error_setg(errp, "unsupported VDI image (non-NULL parent UUID)");
8937f822 465 ret = -ENOTSUP;
9aebd98a 466 goto fail;
63fa06dc
JC
467 } else if (header.blocks_in_image > VDI_BLOCKS_IN_IMAGE_MAX) {
468 error_setg(errp, "unsupported VDI image "
469 "(too many blocks %u, max is %u)",
470 header.blocks_in_image, VDI_BLOCKS_IN_IMAGE_MAX);
471 ret = -ENOTSUP;
472 goto fail;
9aebd98a
SW
473 }
474
475 bs->total_sectors = header.disk_size / SECTOR_SIZE;
476
477 s->block_size = header.block_size;
9aebd98a
SW
478 s->bmap_sector = header.offset_bmap / SECTOR_SIZE;
479 s->header = header;
480
481 bmap_size = header.blocks_in_image * sizeof(uint32_t);
e9082e47 482 bmap_size = DIV_ROUND_UP(bmap_size, SECTOR_SIZE);
9a4f4c31 483 s->bmap = qemu_try_blockalign(bs->file->bs, bmap_size * SECTOR_SIZE);
17cce735
KW
484 if (s->bmap == NULL) {
485 ret = -ENOMEM;
486 goto fail;
487 }
488
d4f18971
AG
489 ret = bdrv_pread(bs->file, header.offset_bmap, s->bmap,
490 bmap_size * SECTOR_SIZE);
8937f822 491 if (ret < 0) {
9aebd98a
SW
492 goto fail_free_bmap;
493 }
494
fc9d106c 495 /* Disable migration when vdi images are used */
81e5f78a
AG
496 error_setg(&s->migration_blocker, "The vdi format used by node '%s' "
497 "does not support live migration",
498 bdrv_get_device_or_node_name(bs));
fe44dc91
AA
499 ret = migrate_add_blocker(s->migration_blocker, &local_err);
500 if (local_err) {
501 error_propagate(errp, local_err);
502 error_free(s->migration_blocker);
503 goto fail_free_bmap;
504 }
fc9d106c 505
1e886639 506 qemu_co_rwlock_init(&s->bmap_lock);
f0ab6f10 507
9aebd98a
SW
508 return 0;
509
510 fail_free_bmap:
17cce735 511 qemu_vfree(s->bmap);
9aebd98a
SW
512
513 fail:
8937f822 514 return ret;
9aebd98a
SW
515}
516
ecfe2bba
JC
517static int vdi_reopen_prepare(BDRVReopenState *state,
518 BlockReopenQueue *queue, Error **errp)
519{
520 return 0;
521}
522
67635f6a
EB
523static int coroutine_fn vdi_co_block_status(BlockDriverState *bs,
524 bool want_zero,
525 int64_t offset, int64_t bytes,
526 int64_t *pnum, int64_t *map,
527 BlockDriverState **file)
9aebd98a 528{
9aebd98a 529 BDRVVdiState *s = (BDRVVdiState *)bs->opaque;
67635f6a
EB
530 size_t bmap_index = offset / s->block_size;
531 size_t index_in_block = offset % s->block_size;
9aebd98a 532 uint32_t bmap_entry = le32_to_cpu(s->bmap[bmap_index]);
4bc74be9
PB
533 int result;
534
67635f6a
EB
535 logout("%p, %" PRId64 ", %" PRId64 ", %p\n", bs, offset, bytes, pnum);
536 *pnum = MIN(s->block_size - index_in_block, bytes);
4bc74be9
PB
537 result = VDI_IS_ALLOCATED(bmap_entry);
538 if (!result) {
539 return 0;
540 }
541
67635f6a
EB
542 *map = s->header.offset_data + (uint64_t)bmap_entry * s->block_size +
543 index_in_block;
8bfb1371 544 *file = bs->file->bs;
ad6434dc
HR
545 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID |
546 (s->header.image_type == VDI_TYPE_STATIC ? BDRV_BLOCK_RECURSE : 0);
9aebd98a
SW
547}
548
0865bb6f
KW
549static int coroutine_fn
550vdi_co_preadv(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
551 QEMUIOVector *qiov, int flags)
9aebd98a 552{
9aebd98a 553 BDRVVdiState *s = bs->opaque;
0865bb6f 554 QEMUIOVector local_qiov;
9aebd98a
SW
555 uint32_t bmap_entry;
556 uint32_t block_index;
0865bb6f
KW
557 uint32_t offset_in_block;
558 uint32_t n_bytes;
559 uint64_t bytes_done = 0;
eb9566d1 560 int ret = 0;
4de659e8
PB
561
562 logout("\n");
9aebd98a 563
0865bb6f 564 qemu_iovec_init(&local_qiov, qiov->niov);
0c7bfc32 565
0865bb6f
KW
566 while (ret >= 0 && bytes > 0) {
567 block_index = offset / s->block_size;
568 offset_in_block = offset % s->block_size;
569 n_bytes = MIN(bytes, s->block_size - offset_in_block);
570
571 logout("will read %u bytes starting at offset %" PRIu64 "\n",
572 n_bytes, offset);
eb9566d1
PB
573
574 /* prepare next AIO request */
1e886639 575 qemu_co_rwlock_rdlock(&s->bmap_lock);
eb9566d1 576 bmap_entry = le32_to_cpu(s->bmap[block_index]);
1e886639 577 qemu_co_rwlock_unlock(&s->bmap_lock);
eb9566d1
PB
578 if (!VDI_IS_ALLOCATED(bmap_entry)) {
579 /* Block not allocated, return zeros, no need to wait. */
0865bb6f 580 qemu_iovec_memset(qiov, bytes_done, 0, n_bytes);
eb9566d1
PB
581 ret = 0;
582 } else {
0865bb6f
KW
583 uint64_t data_offset = s->header.offset_data +
584 (uint64_t)bmap_entry * s->block_size +
585 offset_in_block;
586
587 qemu_iovec_reset(&local_qiov);
588 qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes);
589
a03ef88f 590 ret = bdrv_co_preadv(bs->file, data_offset, n_bytes,
0865bb6f 591 &local_qiov, 0);
eb9566d1 592 }
0865bb6f 593 logout("%u bytes read\n", n_bytes);
0c7bfc32 594
0865bb6f
KW
595 bytes -= n_bytes;
596 offset += n_bytes;
597 bytes_done += n_bytes;
9aebd98a 598 }
3d46a75a 599
0865bb6f
KW
600 qemu_iovec_destroy(&local_qiov);
601
3d46a75a 602 return ret;
9aebd98a
SW
603}
604
fde9d56f
KW
605static int coroutine_fn
606vdi_co_pwritev(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
607 QEMUIOVector *qiov, int flags)
9aebd98a 608{
9aebd98a 609 BDRVVdiState *s = bs->opaque;
fde9d56f 610 QEMUIOVector local_qiov;
9aebd98a
SW
611 uint32_t bmap_entry;
612 uint32_t block_index;
fde9d56f
KW
613 uint32_t offset_in_block;
614 uint32_t n_bytes;
1e886639 615 uint64_t data_offset;
bfc45fc1
PB
616 uint32_t bmap_first = VDI_UNALLOCATED;
617 uint32_t bmap_last = VDI_UNALLOCATED;
bfc45fc1 618 uint8_t *block = NULL;
fde9d56f 619 uint64_t bytes_done = 0;
eb9566d1 620 int ret = 0;
4de659e8
PB
621
622 logout("\n");
9aebd98a 623
fde9d56f 624 qemu_iovec_init(&local_qiov, qiov->niov);
9aebd98a 625
fde9d56f
KW
626 while (ret >= 0 && bytes > 0) {
627 block_index = offset / s->block_size;
628 offset_in_block = offset % s->block_size;
629 n_bytes = MIN(bytes, s->block_size - offset_in_block);
630
631 logout("will write %u bytes starting at offset %" PRIu64 "\n",
632 n_bytes, offset);
eb9566d1
PB
633
634 /* prepare next AIO request */
1e886639 635 qemu_co_rwlock_rdlock(&s->bmap_lock);
eb9566d1
PB
636 bmap_entry = le32_to_cpu(s->bmap[block_index]);
637 if (!VDI_IS_ALLOCATED(bmap_entry)) {
638 /* Allocate new block and write to it. */
fde9d56f 639 uint64_t data_offset;
1e886639
PB
640 qemu_co_rwlock_upgrade(&s->bmap_lock);
641 bmap_entry = le32_to_cpu(s->bmap[block_index]);
642 if (VDI_IS_ALLOCATED(bmap_entry)) {
643 /* A concurrent allocation did the work for us. */
644 qemu_co_rwlock_downgrade(&s->bmap_lock);
645 goto nonallocating_write;
646 }
647
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 664
1e886639
PB
665 /* Write the new block under CoRwLock write-side protection,
666 * so this full-cluster write does not overlap a partial write
667 * of the same cluster, issued from the "else" branch.
668 */
d9ca2ea2 669 ret = bdrv_pwrite(bs->file, data_offset, block, s->block_size);
1e886639 670 qemu_co_rwlock_unlock(&s->bmap_lock);
eb9566d1 671 } else {
1e886639
PB
672nonallocating_write:
673 data_offset = s->header.offset_data +
674 (uint64_t)bmap_entry * s->block_size +
675 offset_in_block;
676 qemu_co_rwlock_unlock(&s->bmap_lock);
fde9d56f
KW
677
678 qemu_iovec_reset(&local_qiov);
679 qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes);
680
a03ef88f 681 ret = bdrv_co_pwritev(bs->file, data_offset, n_bytes,
fde9d56f 682 &local_qiov, 0);
9aebd98a 683 }
0c7bfc32 684
fde9d56f
KW
685 bytes -= n_bytes;
686 offset += n_bytes;
687 bytes_done += n_bytes;
0c7bfc32 688
fde9d56f 689 logout("%u bytes written\n", n_bytes);
9aebd98a 690 }
9aebd98a 691
fde9d56f
KW
692 qemu_iovec_destroy(&local_qiov);
693
0c7bfc32 694 logout("finished data write\n");
4eea78e6
PB
695 if (ret < 0) {
696 return ret;
697 }
698
699 if (block) {
700 /* One or more new blocks were allocated. */
701 VdiHeader *header = (VdiHeader *) block;
702 uint8_t *base;
703 uint64_t offset;
fde9d56f 704 uint32_t n_sectors;
4eea78e6
PB
705
706 logout("now writing modified header\n");
707 assert(VDI_IS_ALLOCATED(bmap_first));
708 *header = s->header;
709 vdi_header_to_le(header);
d4f18971 710 ret = bdrv_pwrite(bs->file, 0, block, sizeof(VdiHeader));
bfc45fc1
PB
711 g_free(block);
712 block = NULL;
4eea78e6
PB
713
714 if (ret < 0) {
715 return ret;
0c7bfc32 716 }
4eea78e6
PB
717
718 logout("now writing modified block map entry %u...%u\n",
719 bmap_first, bmap_last);
720 /* Write modified sectors from block map. */
721 bmap_first /= (SECTOR_SIZE / sizeof(uint32_t));
722 bmap_last /= (SECTOR_SIZE / sizeof(uint32_t));
723 n_sectors = bmap_last - bmap_first + 1;
724 offset = s->bmap_sector + bmap_first;
725 base = ((uint8_t *)&s->bmap[0]) + bmap_first * SECTOR_SIZE;
726 logout("will write %u block map sectors starting from entry %u\n",
727 n_sectors, bmap_first);
d4f18971
AG
728 ret = bdrv_pwrite(bs->file, offset * SECTOR_SIZE, base,
729 n_sectors * SECTOR_SIZE);
0c7bfc32
PB
730 }
731
d4f18971 732 return ret < 0 ? ret : 0;
9aebd98a
SW
733}
734
e3810574 735static int coroutine_fn vdi_co_do_create(BlockdevCreateOptions *create_options,
49858b50 736 size_t block_size, Error **errp)
9aebd98a 737{
e3810574 738 BlockdevCreateOptionsVdi *vdi_opts;
dddc7750 739 int ret = 0;
9aebd98a
SW
740 uint64_t bytes = 0;
741 uint32_t blocks;
61fa6487 742 uint32_t image_type;
9aebd98a
SW
743 VdiHeader header;
744 size_t i;
745 size_t bmap_size;
70747862 746 int64_t offset = 0;
ec73f060 747 BlockDriverState *bs_file = NULL;
a08f0c3b 748 BlockBackend *blk = NULL;
70747862 749 uint32_t *bmap = NULL;
ac928b8e 750 QemuUUID uuid;
9aebd98a 751
e3810574
HR
752 assert(create_options->driver == BLOCKDEV_DRIVER_VDI);
753 vdi_opts = &create_options->u.vdi;
754
9aebd98a
SW
755 logout("\n");
756
da23248f 757 /* Validate options and set default values */
49858b50 758 bytes = vdi_opts->size;
61fa6487
KW
759
760 if (!vdi_opts->has_preallocation) {
761 vdi_opts->preallocation = PREALLOC_MODE_OFF;
762 }
763 switch (vdi_opts->preallocation) {
764 case PREALLOC_MODE_OFF:
765 image_type = VDI_TYPE_DYNAMIC;
766 break;
767 case PREALLOC_MODE_METADATA:
004b7f25 768 image_type = VDI_TYPE_STATIC;
61fa6487
KW
769 break;
770 default:
771 error_setg(errp, "Preallocation mode not supported for vdi");
772 return -EINVAL;
9aebd98a 773 }
61fa6487 774
49858b50
HR
775#ifndef CONFIG_VDI_STATIC_IMAGE
776 if (image_type == VDI_TYPE_STATIC) {
777 ret = -ENOTSUP;
778 error_setg(errp, "Statically allocated images cannot be created in "
779 "this build");
780 goto exit;
781 }
782#endif
783#ifndef CONFIG_VDI_BLOCK_SIZE
784 if (block_size != DEFAULT_CLUSTER_SIZE) {
785 ret = -ENOTSUP;
786 error_setg(errp,
787 "A non-default cluster size is not supported in this build");
788 goto exit;
789 }
004b7f25 790#endif
9aebd98a 791
63fa06dc 792 if (bytes > VDI_DISK_SIZE_MAX) {
dddc7750 793 ret = -ENOTSUP;
63fa06dc
JC
794 error_setg(errp, "Unsupported VDI image size (size is 0x%" PRIx64
795 ", max supported is 0x%" PRIx64 ")",
796 bytes, VDI_DISK_SIZE_MAX);
797 goto exit;
798 }
799
da23248f 800 /* Create BlockBackend to write to the image */
ec73f060
HR
801 bs_file = bdrv_open_blockdev_ref(vdi_opts->file, errp);
802 if (!bs_file) {
803 ret = -EIO;
63fa06dc 804 goto exit;
9aebd98a 805 }
a08f0c3b 806
d861ab3a
KW
807 blk = blk_new(bdrv_get_aio_context(bs_file),
808 BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL);
ec73f060
HR
809 ret = blk_insert_bs(blk, bs_file, errp);
810 if (ret < 0) {
70747862 811 goto exit;
4ab15590
CL
812 }
813
a08f0c3b
KW
814 blk_set_allow_write_beyond_eof(blk, true);
815
f21dc3a4
SW
816 /* We need enough blocks to store the given disk size,
817 so always round up. */
e9082e47 818 blocks = DIV_ROUND_UP(bytes, block_size);
f21dc3a4 819
9aebd98a 820 bmap_size = blocks * sizeof(uint32_t);
e9082e47 821 bmap_size = ROUND_UP(bmap_size, SECTOR_SIZE);
9aebd98a
SW
822
823 memset(&header, 0, sizeof(header));
1786dc15 824 pstrcpy(header.text, sizeof(header.text), VDI_TEXT);
9aebd98a
SW
825 header.signature = VDI_SIGNATURE;
826 header.version = VDI_VERSION_1_1;
827 header.header_size = 0x180;
828 header.image_type = image_type;
829 header.offset_bmap = 0x200;
830 header.offset_data = 0x200 + bmap_size;
831 header.sector_size = SECTOR_SIZE;
832 header.disk_size = bytes;
833 header.block_size = block_size;
834 header.blocks_in_image = blocks;
6eea90eb
SW
835 if (image_type == VDI_TYPE_STATIC) {
836 header.blocks_allocated = blocks;
837 }
ac928b8e
PM
838 qemu_uuid_generate(&uuid);
839 header.uuid_image = uuid;
840 qemu_uuid_generate(&uuid);
841 header.uuid_last_snap = uuid;
9aebd98a 842 /* There is no need to set header.uuid_link or header.uuid_parent here. */
95a14d51
KW
843 if (VDI_DEBUG) {
844 vdi_header_print(&header);
845 }
9aebd98a 846 vdi_header_to_le(&header);
8341f00d 847 ret = blk_pwrite(blk, offset, &header, sizeof(header), 0);
dddc7750 848 if (ret < 0) {
ec73f060 849 error_setg(errp, "Error writing header");
70747862 850 goto exit;
9aebd98a 851 }
70747862 852 offset += sizeof(header);
9aebd98a 853
b76b6e95 854 if (bmap_size > 0) {
17cce735
KW
855 bmap = g_try_malloc0(bmap_size);
856 if (bmap == NULL) {
857 ret = -ENOMEM;
858 error_setg(errp, "Could not allocate bmap");
859 goto exit;
860 }
514f21a5
SW
861 for (i = 0; i < blocks; i++) {
862 if (image_type == VDI_TYPE_STATIC) {
863 bmap[i] = i;
864 } else {
865 bmap[i] = VDI_UNALLOCATED;
866 }
9aebd98a 867 }
8341f00d 868 ret = blk_pwrite(blk, offset, bmap, bmap_size, 0);
dddc7750 869 if (ret < 0) {
ec73f060 870 error_setg(errp, "Error writing bmap");
70747862 871 goto exit;
514f21a5 872 }
70747862 873 offset += bmap_size;
9aebd98a 874 }
514f21a5 875
9aebd98a 876 if (image_type == VDI_TYPE_STATIC) {
c80d8b06 877 ret = blk_truncate(blk, offset + blocks * block_size, false,
8c6242b6 878 PREALLOC_MODE_OFF, 0, errp);
dddc7750 879 if (ret < 0) {
ec73f060 880 error_prepend(errp, "Failed to statically allocate file");
70747862 881 goto exit;
9aebd98a
SW
882 }
883 }
884
53618dd8 885 ret = 0;
63fa06dc 886exit:
a08f0c3b 887 blk_unref(blk);
ec73f060 888 bdrv_unref(bs_file);
70747862 889 g_free(bmap);
dddc7750 890 return ret;
9aebd98a
SW
891}
892
e3810574
HR
893static int coroutine_fn vdi_co_create(BlockdevCreateOptions *create_options,
894 Error **errp)
895{
896 return vdi_co_do_create(create_options, DEFAULT_CLUSTER_SIZE, errp);
897}
898
b92902df
ML
899static int coroutine_fn vdi_co_create_opts(BlockDriver *drv,
900 const char *filename,
901 QemuOpts *opts,
49858b50
HR
902 Error **errp)
903{
904 QDict *qdict = NULL;
e3810574 905 BlockdevCreateOptions *create_options = NULL;
ec73f060 906 BlockDriverState *bs_file = NULL;
49858b50 907 uint64_t block_size = DEFAULT_CLUSTER_SIZE;
61fa6487 908 bool is_static = false;
49858b50
HR
909 Visitor *v;
910 Error *local_err = NULL;
911 int ret;
912
da23248f
KW
913 /* Parse options and convert legacy syntax.
914 *
915 * Since CONFIG_VDI_BLOCK_SIZE is disabled by default,
49858b50
HR
916 * cluster-size is not part of the QAPI schema; therefore we have
917 * to parse it before creating the QAPI object. */
918#if defined(CONFIG_VDI_BLOCK_SIZE)
919 block_size = qemu_opt_get_size_del(opts,
920 BLOCK_OPT_CLUSTER_SIZE,
921 DEFAULT_CLUSTER_SIZE);
922 if (block_size < BDRV_SECTOR_SIZE || block_size > UINT32_MAX ||
923 !is_power_of_2(block_size))
924 {
925 error_setg(errp, "Invalid cluster size");
926 ret = -EINVAL;
927 goto done;
928 }
929#endif
61fa6487
KW
930 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_STATIC, false)) {
931 is_static = true;
932 }
49858b50
HR
933
934 qdict = qemu_opts_to_qdict_filtered(opts, NULL, &vdi_create_opts, true);
935
da23248f 936 /* Create and open the file (protocol layer) */
ec73f060
HR
937 ret = bdrv_create_file(filename, opts, errp);
938 if (ret < 0) {
939 goto done;
940 }
941
942 bs_file = bdrv_open(filename, NULL, NULL,
943 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
944 if (!bs_file) {
945 ret = -EIO;
946 goto done;
947 }
948
e3810574 949 qdict_put_str(qdict, "driver", "vdi");
ec73f060 950 qdict_put_str(qdict, "file", bs_file->node_name);
61fa6487
KW
951 if (is_static) {
952 qdict_put_str(qdict, "preallocation", "metadata");
953 }
49858b50
HR
954
955 /* Get the QAPI object */
f853465a
MA
956 v = qobject_input_visitor_new_flat_confused(qdict, errp);
957 if (!v) {
958 ret = -EINVAL;
959 goto done;
960 }
e3810574 961 visit_type_BlockdevCreateOptions(v, NULL, &create_options, &local_err);
49858b50
HR
962 visit_free(v);
963
964 if (local_err) {
965 error_propagate(errp, local_err);
966 ret = -EINVAL;
967 goto done;
968 }
969
da23248f 970 /* Silently round up size */
e3810574
HR
971 assert(create_options->driver == BLOCKDEV_DRIVER_VDI);
972 create_options->u.vdi.size = ROUND_UP(create_options->u.vdi.size,
973 BDRV_SECTOR_SIZE);
49858b50 974
da23248f 975 /* Create the vdi image (format layer) */
ec73f060 976 ret = vdi_co_do_create(create_options, block_size, errp);
49858b50 977done:
cb3e7f08 978 qobject_unref(qdict);
e3810574 979 qapi_free_BlockdevCreateOptions(create_options);
ec73f060 980 bdrv_unref(bs_file);
49858b50
HR
981 return ret;
982}
983
9aebd98a
SW
984static void vdi_close(BlockDriverState *bs)
985{
fc9d106c 986 BDRVVdiState *s = bs->opaque;
6ac5f388 987
17cce735 988 qemu_vfree(s->bmap);
6ac5f388 989
fc9d106c
KW
990 migrate_del_blocker(s->migration_blocker);
991 error_free(s->migration_blocker);
9aebd98a
SW
992}
993
0a28bf28
HR
994static int vdi_has_zero_init(BlockDriverState *bs)
995{
996 BDRVVdiState *s = bs->opaque;
997
998 if (s->header.image_type == VDI_TYPE_STATIC) {
999 return bdrv_has_zero_init(bs->file->bs);
1000 } else {
1001 return 1;
1002 }
1003}
1004
004b7f25
CL
1005static QemuOptsList vdi_create_opts = {
1006 .name = "vdi-create-opts",
1007 .head = QTAILQ_HEAD_INITIALIZER(vdi_create_opts.head),
1008 .desc = {
1009 {
1010 .name = BLOCK_OPT_SIZE,
1011 .type = QEMU_OPT_SIZE,
1012 .help = "Virtual disk size"
1013 },
9aebd98a 1014#if defined(CONFIG_VDI_BLOCK_SIZE)
004b7f25
CL
1015 {
1016 .name = BLOCK_OPT_CLUSTER_SIZE,
1017 .type = QEMU_OPT_SIZE,
1018 .help = "VDI cluster (block) size",
1019 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
1020 },
9aebd98a
SW
1021#endif
1022#if defined(CONFIG_VDI_STATIC_IMAGE)
004b7f25
CL
1023 {
1024 .name = BLOCK_OPT_STATIC,
1025 .type = QEMU_OPT_BOOL,
1026 .help = "VDI static (pre-allocated) image",
1027 .def_value_str = "off"
1028 },
9aebd98a 1029#endif
004b7f25
CL
1030 /* TODO: An additional option to set UUID values might be useful. */
1031 { /* end of list */ }
1032 }
9aebd98a
SW
1033};
1034
1035static BlockDriver bdrv_vdi = {
1036 .format_name = "vdi",
1037 .instance_size = sizeof(BDRVVdiState),
1038 .bdrv_probe = vdi_probe,
1039 .bdrv_open = vdi_open,
1040 .bdrv_close = vdi_close,
ecfe2bba 1041 .bdrv_reopen_prepare = vdi_reopen_prepare,
862f215f 1042 .bdrv_child_perm = bdrv_format_default_perms,
e3810574 1043 .bdrv_co_create = vdi_co_create,
da23248f 1044 .bdrv_co_create_opts = vdi_co_create_opts,
0a28bf28 1045 .bdrv_has_zero_init = vdi_has_zero_init,
67635f6a 1046 .bdrv_co_block_status = vdi_co_block_status,
9aebd98a
SW
1047 .bdrv_make_empty = vdi_make_empty,
1048
0865bb6f 1049 .bdrv_co_preadv = vdi_co_preadv,
9aebd98a 1050#if defined(CONFIG_VDI_WRITE)
fde9d56f 1051 .bdrv_co_pwritev = vdi_co_pwritev,
9aebd98a
SW
1052#endif
1053
1054 .bdrv_get_info = vdi_get_info,
1055
004b7f25 1056 .create_opts = &vdi_create_opts,
2fd61638 1057 .bdrv_co_check = vdi_co_check,
9aebd98a
SW
1058};
1059
1060static void bdrv_vdi_init(void)
1061{
1062 logout("\n");
1063 bdrv_register(&bdrv_vdi);
1064}
1065
1066block_init(bdrv_vdi_init);