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