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