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