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