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