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