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