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