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