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