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