hw/arm/allwinner-h3: add EMAC ethernet device
[qemu/ar7.git] / block / vhdx.c
blobf02d2611bef85d885c36fc0e097c13bff78f656d
1 /*
2 * Block driver for Hyper-V VHDX Images
4 * Copyright (c) 2013 Red Hat, Inc.,
6 * Authors:
7 * Jeff Cody <jcody@redhat.com>
9 * This is based on the "VHDX Format Specification v1.00", published 8/25/2012
10 * by Microsoft:
11 * https://www.microsoft.com/en-us/download/details.aspx?id=34750
13 * This work is licensed under the terms of the GNU LGPL, version 2 or later.
14 * See the COPYING.LIB file in the top-level directory.
18 #include "qemu/osdep.h"
19 #include "qapi/error.h"
20 #include "block/block_int.h"
21 #include "block/qdict.h"
22 #include "sysemu/block-backend.h"
23 #include "qemu/module.h"
24 #include "qemu/option.h"
25 #include "qemu/crc32c.h"
26 #include "qemu/bswap.h"
27 #include "qemu/error-report.h"
28 #include "vhdx.h"
29 #include "migration/blocker.h"
30 #include "qemu/uuid.h"
31 #include "qapi/qmp/qdict.h"
32 #include "qapi/qobject-input-visitor.h"
33 #include "qapi/qapi-visit-block-core.h"
35 /* Options for VHDX creation */
37 #define VHDX_BLOCK_OPT_LOG_SIZE "log_size"
38 #define VHDX_BLOCK_OPT_BLOCK_SIZE "block_size"
39 #define VHDX_BLOCK_OPT_ZERO "block_state_zero"
41 typedef enum VHDXImageType {
42 VHDX_TYPE_DYNAMIC = 0,
43 VHDX_TYPE_FIXED,
44 VHDX_TYPE_DIFFERENCING, /* Currently unsupported */
45 } VHDXImageType;
47 static QemuOptsList vhdx_create_opts;
49 /* Several metadata and region table data entries are identified by
50 * guids in a MS-specific GUID format. */
53 /* ------- Known Region Table GUIDs ---------------------- */
54 static const MSGUID bat_guid = { .data1 = 0x2dc27766,
55 .data2 = 0xf623,
56 .data3 = 0x4200,
57 .data4 = { 0x9d, 0x64, 0x11, 0x5e,
58 0x9b, 0xfd, 0x4a, 0x08} };
60 static const MSGUID metadata_guid = { .data1 = 0x8b7ca206,
61 .data2 = 0x4790,
62 .data3 = 0x4b9a,
63 .data4 = { 0xb8, 0xfe, 0x57, 0x5f,
64 0x05, 0x0f, 0x88, 0x6e} };
68 /* ------- Known Metadata Entry GUIDs ---------------------- */
69 static const MSGUID file_param_guid = { .data1 = 0xcaa16737,
70 .data2 = 0xfa36,
71 .data3 = 0x4d43,
72 .data4 = { 0xb3, 0xb6, 0x33, 0xf0,
73 0xaa, 0x44, 0xe7, 0x6b} };
75 static const MSGUID virtual_size_guid = { .data1 = 0x2FA54224,
76 .data2 = 0xcd1b,
77 .data3 = 0x4876,
78 .data4 = { 0xb2, 0x11, 0x5d, 0xbe,
79 0xd8, 0x3b, 0xf4, 0xb8} };
81 static const MSGUID page83_guid = { .data1 = 0xbeca12ab,
82 .data2 = 0xb2e6,
83 .data3 = 0x4523,
84 .data4 = { 0x93, 0xef, 0xc3, 0x09,
85 0xe0, 0x00, 0xc7, 0x46} };
88 static const MSGUID phys_sector_guid = { .data1 = 0xcda348c7,
89 .data2 = 0x445d,
90 .data3 = 0x4471,
91 .data4 = { 0x9c, 0xc9, 0xe9, 0x88,
92 0x52, 0x51, 0xc5, 0x56} };
94 static const MSGUID parent_locator_guid = { .data1 = 0xa8d35f2d,
95 .data2 = 0xb30b,
96 .data3 = 0x454d,
97 .data4 = { 0xab, 0xf7, 0xd3,
98 0xd8, 0x48, 0x34,
99 0xab, 0x0c} };
101 static const MSGUID logical_sector_guid = { .data1 = 0x8141bf1d,
102 .data2 = 0xa96f,
103 .data3 = 0x4709,
104 .data4 = { 0xba, 0x47, 0xf2,
105 0x33, 0xa8, 0xfa,
106 0xab, 0x5f} };
108 /* Each parent type must have a valid GUID; this is for parent images
109 * of type 'VHDX'. If we were to allow e.g. a QCOW2 parent, we would
110 * need to make up our own QCOW2 GUID type */
111 static const MSGUID parent_vhdx_guid __attribute__((unused))
112 = { .data1 = 0xb04aefb7,
113 .data2 = 0xd19e,
114 .data3 = 0x4a81,
115 .data4 = { 0xb7, 0x89, 0x25, 0xb8,
116 0xe9, 0x44, 0x59, 0x13} };
119 #define META_FILE_PARAMETER_PRESENT 0x01
120 #define META_VIRTUAL_DISK_SIZE_PRESENT 0x02
121 #define META_PAGE_83_PRESENT 0x04
122 #define META_LOGICAL_SECTOR_SIZE_PRESENT 0x08
123 #define META_PHYS_SECTOR_SIZE_PRESENT 0x10
124 #define META_PARENT_LOCATOR_PRESENT 0x20
126 #define META_ALL_PRESENT \
127 (META_FILE_PARAMETER_PRESENT | META_VIRTUAL_DISK_SIZE_PRESENT | \
128 META_PAGE_83_PRESENT | META_LOGICAL_SECTOR_SIZE_PRESENT | \
129 META_PHYS_SECTOR_SIZE_PRESENT)
132 typedef struct VHDXSectorInfo {
133 uint32_t bat_idx; /* BAT entry index */
134 uint32_t sectors_avail; /* sectors available in payload block */
135 uint32_t bytes_left; /* bytes left in the block after data to r/w */
136 uint32_t bytes_avail; /* bytes available in payload block */
137 uint64_t file_offset; /* absolute offset in bytes, in file */
138 uint64_t block_offset; /* block offset, in bytes */
139 } VHDXSectorInfo;
141 /* Calculates new checksum.
143 * Zero is substituted during crc calculation for the original crc field
144 * crc_offset: byte offset in buf of the buffer crc
145 * buf: buffer pointer
146 * size: size of buffer (must be > crc_offset+4)
148 * Note: The buffer should have all multi-byte data in little-endian format,
149 * and the resulting checksum is in little endian format.
151 uint32_t vhdx_update_checksum(uint8_t *buf, size_t size, int crc_offset)
153 uint32_t crc;
155 assert(buf != NULL);
156 assert(size > (crc_offset + sizeof(crc)));
158 memset(buf + crc_offset, 0, sizeof(crc));
159 crc = crc32c(0xffffffff, buf, size);
160 crc = cpu_to_le32(crc);
161 memcpy(buf + crc_offset, &crc, sizeof(crc));
163 return crc;
166 uint32_t vhdx_checksum_calc(uint32_t crc, uint8_t *buf, size_t size,
167 int crc_offset)
169 uint32_t crc_new;
170 uint32_t crc_orig;
171 assert(buf != NULL);
173 if (crc_offset > 0) {
174 memcpy(&crc_orig, buf + crc_offset, sizeof(crc_orig));
175 memset(buf + crc_offset, 0, sizeof(crc_orig));
178 crc_new = crc32c(crc, buf, size);
179 if (crc_offset > 0) {
180 memcpy(buf + crc_offset, &crc_orig, sizeof(crc_orig));
183 return crc_new;
186 /* Validates the checksum of the buffer, with an in-place CRC.
188 * Zero is substituted during crc calculation for the original crc field,
189 * and the crc field is restored afterwards. But the buffer will be modified
190 * during the calculation, so this may not be not suitable for multi-threaded
191 * use.
193 * crc_offset: byte offset in buf of the buffer crc
194 * buf: buffer pointer
195 * size: size of buffer (must be > crc_offset+4)
197 * returns true if checksum is valid, false otherwise
199 bool vhdx_checksum_is_valid(uint8_t *buf, size_t size, int crc_offset)
201 uint32_t crc_orig;
202 uint32_t crc;
204 assert(buf != NULL);
205 assert(size > (crc_offset + 4));
207 memcpy(&crc_orig, buf + crc_offset, sizeof(crc_orig));
208 crc_orig = le32_to_cpu(crc_orig);
210 crc = vhdx_checksum_calc(0xffffffff, buf, size, crc_offset);
212 return crc == crc_orig;
217 * This generates a UUID that is compliant with the MS GUIDs used
218 * in the VHDX spec (and elsewhere).
220 void vhdx_guid_generate(MSGUID *guid)
222 QemuUUID uuid;
223 assert(guid != NULL);
225 qemu_uuid_generate(&uuid);
226 memcpy(guid, &uuid, sizeof(MSGUID));
229 /* Check for region overlaps inside the VHDX image */
230 static int vhdx_region_check(BDRVVHDXState *s, uint64_t start, uint64_t length)
232 int ret = 0;
233 uint64_t end;
234 VHDXRegionEntry *r;
236 end = start + length;
237 QLIST_FOREACH(r, &s->regions, entries) {
238 if (!((start >= r->end) || (end <= r->start))) {
239 error_report("VHDX region %" PRIu64 "-%" PRIu64 " overlaps with "
240 "region %" PRIu64 "-%." PRIu64, start, end, r->start,
241 r->end);
242 ret = -EINVAL;
243 goto exit;
247 exit:
248 return ret;
251 /* Register a region for future checks */
252 static void vhdx_region_register(BDRVVHDXState *s,
253 uint64_t start, uint64_t length)
255 VHDXRegionEntry *r;
257 r = g_malloc0(sizeof(*r));
259 r->start = start;
260 r->end = start + length;
262 QLIST_INSERT_HEAD(&s->regions, r, entries);
265 /* Free all registered regions */
266 static void vhdx_region_unregister_all(BDRVVHDXState *s)
268 VHDXRegionEntry *r, *r_next;
270 QLIST_FOREACH_SAFE(r, &s->regions, entries, r_next) {
271 QLIST_REMOVE(r, entries);
272 g_free(r);
276 static void vhdx_set_shift_bits(BDRVVHDXState *s)
278 s->logical_sector_size_bits = ctz32(s->logical_sector_size);
279 s->sectors_per_block_bits = ctz32(s->sectors_per_block);
280 s->chunk_ratio_bits = ctz64(s->chunk_ratio);
281 s->block_size_bits = ctz32(s->block_size);
285 * Per the MS VHDX Specification, for every VHDX file:
286 * - The header section is fixed size - 1 MB
287 * - The header section is always the first "object"
288 * - The first 64KB of the header is the File Identifier
289 * - The first uint64 (8 bytes) is the VHDX Signature ("vhdxfile")
290 * - The following 512 bytes constitute a UTF-16 string identifiying the
291 * software that created the file, and is optional and diagnostic only.
293 * Therefore, we probe by looking for the vhdxfile signature "vhdxfile"
295 static int vhdx_probe(const uint8_t *buf, int buf_size, const char *filename)
297 if (buf_size >= 8 && !memcmp(buf, "vhdxfile", 8)) {
298 return 100;
300 return 0;
304 * Writes the header to the specified offset.
306 * This will optionally read in buffer data from disk (otherwise zero-fill),
307 * and then update the header checksum. Header is converted to proper
308 * endianness before being written to the specified file offset
310 static int vhdx_write_header(BdrvChild *file, VHDXHeader *hdr,
311 uint64_t offset, bool read)
313 BlockDriverState *bs_file = file->bs;
314 uint8_t *buffer = NULL;
315 int ret;
316 VHDXHeader *header_le;
318 assert(bs_file != NULL);
319 assert(hdr != NULL);
321 /* the header checksum is not over just the packed size of VHDXHeader,
322 * but rather over the entire 'reserved' range for the header, which is
323 * 4KB (VHDX_HEADER_SIZE). */
325 buffer = qemu_blockalign(bs_file, VHDX_HEADER_SIZE);
326 if (read) {
327 /* if true, we can't assume the extra reserved bytes are 0 */
328 ret = bdrv_pread(file, offset, buffer, VHDX_HEADER_SIZE);
329 if (ret < 0) {
330 goto exit;
332 } else {
333 memset(buffer, 0, VHDX_HEADER_SIZE);
336 /* overwrite the actual VHDXHeader portion */
337 header_le = (VHDXHeader *)buffer;
338 memcpy(header_le, hdr, sizeof(VHDXHeader));
339 vhdx_header_le_export(hdr, header_le);
340 vhdx_update_checksum(buffer, VHDX_HEADER_SIZE,
341 offsetof(VHDXHeader, checksum));
342 ret = bdrv_pwrite_sync(file, offset, header_le, sizeof(VHDXHeader));
344 exit:
345 qemu_vfree(buffer);
346 return ret;
349 /* Update the VHDX headers
351 * This follows the VHDX spec procedures for header updates.
353 * - non-current header is updated with largest sequence number
355 static int vhdx_update_header(BlockDriverState *bs, BDRVVHDXState *s,
356 bool generate_data_write_guid, MSGUID *log_guid)
358 int ret = 0;
359 int hdr_idx = 0;
360 uint64_t header_offset = VHDX_HEADER1_OFFSET;
362 VHDXHeader *active_header;
363 VHDXHeader *inactive_header;
365 /* operate on the non-current header */
366 if (s->curr_header == 0) {
367 hdr_idx = 1;
368 header_offset = VHDX_HEADER2_OFFSET;
371 active_header = s->headers[s->curr_header];
372 inactive_header = s->headers[hdr_idx];
374 inactive_header->sequence_number = active_header->sequence_number + 1;
376 /* a new file guid must be generated before any file write, including
377 * headers */
378 inactive_header->file_write_guid = s->session_guid;
380 /* a new data guid only needs to be generated before any guest-visible
381 * writes (i.e. something observable via virtual disk read) */
382 if (generate_data_write_guid) {
383 vhdx_guid_generate(&inactive_header->data_write_guid);
386 /* update the log guid if present */
387 if (log_guid) {
388 inactive_header->log_guid = *log_guid;
391 ret = vhdx_write_header(bs->file, inactive_header, header_offset, true);
392 if (ret < 0) {
393 goto exit;
395 s->curr_header = hdr_idx;
397 exit:
398 return ret;
402 * The VHDX spec calls for header updates to be performed twice, so that both
403 * the current and non-current header have valid info
405 int vhdx_update_headers(BlockDriverState *bs, BDRVVHDXState *s,
406 bool generate_data_write_guid, MSGUID *log_guid)
408 int ret;
410 ret = vhdx_update_header(bs, s, generate_data_write_guid, log_guid);
411 if (ret < 0) {
412 return ret;
414 ret = vhdx_update_header(bs, s, generate_data_write_guid, log_guid);
415 return ret;
418 /* opens the specified header block from the VHDX file header section */
419 static void vhdx_parse_header(BlockDriverState *bs, BDRVVHDXState *s,
420 Error **errp)
422 int ret;
423 VHDXHeader *header1;
424 VHDXHeader *header2;
425 bool h1_valid = false;
426 bool h2_valid = false;
427 uint64_t h1_seq = 0;
428 uint64_t h2_seq = 0;
429 uint8_t *buffer;
431 /* header1 & header2 are freed in vhdx_close() */
432 header1 = qemu_blockalign(bs, sizeof(VHDXHeader));
433 header2 = qemu_blockalign(bs, sizeof(VHDXHeader));
435 buffer = qemu_blockalign(bs, VHDX_HEADER_SIZE);
437 s->headers[0] = header1;
438 s->headers[1] = header2;
440 /* We have to read the whole VHDX_HEADER_SIZE instead of
441 * sizeof(VHDXHeader), because the checksum is over the whole
442 * region */
443 ret = bdrv_pread(bs->file, VHDX_HEADER1_OFFSET, buffer,
444 VHDX_HEADER_SIZE);
445 if (ret < 0) {
446 goto fail;
448 /* copy over just the relevant portion that we need */
449 memcpy(header1, buffer, sizeof(VHDXHeader));
451 if (vhdx_checksum_is_valid(buffer, VHDX_HEADER_SIZE, 4)) {
452 vhdx_header_le_import(header1);
453 if (header1->signature == VHDX_HEADER_SIGNATURE &&
454 header1->version == 1) {
455 h1_seq = header1->sequence_number;
456 h1_valid = true;
460 ret = bdrv_pread(bs->file, VHDX_HEADER2_OFFSET, buffer,
461 VHDX_HEADER_SIZE);
462 if (ret < 0) {
463 goto fail;
465 /* copy over just the relevant portion that we need */
466 memcpy(header2, buffer, sizeof(VHDXHeader));
468 if (vhdx_checksum_is_valid(buffer, VHDX_HEADER_SIZE, 4)) {
469 vhdx_header_le_import(header2);
470 if (header2->signature == VHDX_HEADER_SIGNATURE &&
471 header2->version == 1) {
472 h2_seq = header2->sequence_number;
473 h2_valid = true;
477 /* If there is only 1 valid header (or no valid headers), we
478 * don't care what the sequence numbers are */
479 if (h1_valid && !h2_valid) {
480 s->curr_header = 0;
481 } else if (!h1_valid && h2_valid) {
482 s->curr_header = 1;
483 } else if (!h1_valid && !h2_valid) {
484 goto fail;
485 } else {
486 /* If both headers are valid, then we choose the active one by the
487 * highest sequence number. If the sequence numbers are equal, that is
488 * invalid */
489 if (h1_seq > h2_seq) {
490 s->curr_header = 0;
491 } else if (h2_seq > h1_seq) {
492 s->curr_header = 1;
493 } else {
494 /* The Microsoft Disk2VHD tool will create 2 identical
495 * headers, with identical sequence numbers. If the headers are
496 * identical, don't consider the file corrupt */
497 if (!memcmp(header1, header2, sizeof(VHDXHeader))) {
498 s->curr_header = 0;
499 } else {
500 goto fail;
505 vhdx_region_register(s, s->headers[s->curr_header]->log_offset,
506 s->headers[s->curr_header]->log_length);
507 goto exit;
509 fail:
510 error_setg_errno(errp, -ret, "No valid VHDX header found");
511 qemu_vfree(header1);
512 qemu_vfree(header2);
513 s->headers[0] = NULL;
514 s->headers[1] = NULL;
515 exit:
516 qemu_vfree(buffer);
520 static int vhdx_open_region_tables(BlockDriverState *bs, BDRVVHDXState *s)
522 int ret = 0;
523 uint8_t *buffer;
524 int offset = 0;
525 VHDXRegionTableEntry rt_entry;
526 uint32_t i;
527 bool bat_rt_found = false;
528 bool metadata_rt_found = false;
530 /* We have to read the whole 64KB block, because the crc32 is over the
531 * whole block */
532 buffer = qemu_blockalign(bs, VHDX_HEADER_BLOCK_SIZE);
534 ret = bdrv_pread(bs->file, VHDX_REGION_TABLE_OFFSET, buffer,
535 VHDX_HEADER_BLOCK_SIZE);
536 if (ret < 0) {
537 goto fail;
539 memcpy(&s->rt, buffer, sizeof(s->rt));
540 offset += sizeof(s->rt);
542 if (!vhdx_checksum_is_valid(buffer, VHDX_HEADER_BLOCK_SIZE, 4)) {
543 ret = -EINVAL;
544 goto fail;
547 vhdx_region_header_le_import(&s->rt);
549 if (s->rt.signature != VHDX_REGION_SIGNATURE) {
550 ret = -EINVAL;
551 goto fail;
555 /* Per spec, maximum region table entry count is 2047 */
556 if (s->rt.entry_count > 2047) {
557 ret = -EINVAL;
558 goto fail;
561 for (i = 0; i < s->rt.entry_count; i++) {
562 memcpy(&rt_entry, buffer + offset, sizeof(rt_entry));
563 offset += sizeof(rt_entry);
565 vhdx_region_entry_le_import(&rt_entry);
567 /* check for region overlap between these entries, and any
568 * other memory regions in the file */
569 ret = vhdx_region_check(s, rt_entry.file_offset, rt_entry.length);
570 if (ret < 0) {
571 goto fail;
574 vhdx_region_register(s, rt_entry.file_offset, rt_entry.length);
576 /* see if we recognize the entry */
577 if (guid_eq(rt_entry.guid, bat_guid)) {
578 /* must be unique; if we have already found it this is invalid */
579 if (bat_rt_found) {
580 ret = -EINVAL;
581 goto fail;
583 bat_rt_found = true;
584 s->bat_rt = rt_entry;
585 continue;
588 if (guid_eq(rt_entry.guid, metadata_guid)) {
589 /* must be unique; if we have already found it this is invalid */
590 if (metadata_rt_found) {
591 ret = -EINVAL;
592 goto fail;
594 metadata_rt_found = true;
595 s->metadata_rt = rt_entry;
596 continue;
599 if (rt_entry.data_bits & VHDX_REGION_ENTRY_REQUIRED) {
600 /* cannot read vhdx file - required region table entry that
601 * we do not understand. per spec, we must fail to open */
602 ret = -ENOTSUP;
603 goto fail;
607 if (!bat_rt_found || !metadata_rt_found) {
608 ret = -EINVAL;
609 goto fail;
612 ret = 0;
614 fail:
615 qemu_vfree(buffer);
616 return ret;
621 /* Metadata initial parser
623 * This loads all the metadata entry fields. This may cause additional
624 * fields to be processed (e.g. parent locator, etc..).
626 * There are 5 Metadata items that are always required:
627 * - File Parameters (block size, has a parent)
628 * - Virtual Disk Size (size, in bytes, of the virtual drive)
629 * - Page 83 Data (scsi page 83 guid)
630 * - Logical Sector Size (logical sector size in bytes, either 512 or
631 * 4096. We only support 512 currently)
632 * - Physical Sector Size (512 or 4096)
634 * Also, if the File Parameters indicate this is a differencing file,
635 * we must also look for the Parent Locator metadata item.
637 static int vhdx_parse_metadata(BlockDriverState *bs, BDRVVHDXState *s)
639 int ret = 0;
640 uint8_t *buffer;
641 int offset = 0;
642 uint32_t i = 0;
643 VHDXMetadataTableEntry md_entry;
645 buffer = qemu_blockalign(bs, VHDX_METADATA_TABLE_MAX_SIZE);
647 ret = bdrv_pread(bs->file, s->metadata_rt.file_offset, buffer,
648 VHDX_METADATA_TABLE_MAX_SIZE);
649 if (ret < 0) {
650 goto exit;
652 memcpy(&s->metadata_hdr, buffer, sizeof(s->metadata_hdr));
653 offset += sizeof(s->metadata_hdr);
655 vhdx_metadata_header_le_import(&s->metadata_hdr);
657 if (s->metadata_hdr.signature != VHDX_METADATA_SIGNATURE) {
658 ret = -EINVAL;
659 goto exit;
662 s->metadata_entries.present = 0;
664 if ((s->metadata_hdr.entry_count * sizeof(md_entry)) >
665 (VHDX_METADATA_TABLE_MAX_SIZE - offset)) {
666 ret = -EINVAL;
667 goto exit;
670 for (i = 0; i < s->metadata_hdr.entry_count; i++) {
671 memcpy(&md_entry, buffer + offset, sizeof(md_entry));
672 offset += sizeof(md_entry);
674 vhdx_metadata_entry_le_import(&md_entry);
676 if (guid_eq(md_entry.item_id, file_param_guid)) {
677 if (s->metadata_entries.present & META_FILE_PARAMETER_PRESENT) {
678 ret = -EINVAL;
679 goto exit;
681 s->metadata_entries.file_parameters_entry = md_entry;
682 s->metadata_entries.present |= META_FILE_PARAMETER_PRESENT;
683 continue;
686 if (guid_eq(md_entry.item_id, virtual_size_guid)) {
687 if (s->metadata_entries.present & META_VIRTUAL_DISK_SIZE_PRESENT) {
688 ret = -EINVAL;
689 goto exit;
691 s->metadata_entries.virtual_disk_size_entry = md_entry;
692 s->metadata_entries.present |= META_VIRTUAL_DISK_SIZE_PRESENT;
693 continue;
696 if (guid_eq(md_entry.item_id, page83_guid)) {
697 if (s->metadata_entries.present & META_PAGE_83_PRESENT) {
698 ret = -EINVAL;
699 goto exit;
701 s->metadata_entries.page83_data_entry = md_entry;
702 s->metadata_entries.present |= META_PAGE_83_PRESENT;
703 continue;
706 if (guid_eq(md_entry.item_id, logical_sector_guid)) {
707 if (s->metadata_entries.present &
708 META_LOGICAL_SECTOR_SIZE_PRESENT) {
709 ret = -EINVAL;
710 goto exit;
712 s->metadata_entries.logical_sector_size_entry = md_entry;
713 s->metadata_entries.present |= META_LOGICAL_SECTOR_SIZE_PRESENT;
714 continue;
717 if (guid_eq(md_entry.item_id, phys_sector_guid)) {
718 if (s->metadata_entries.present & META_PHYS_SECTOR_SIZE_PRESENT) {
719 ret = -EINVAL;
720 goto exit;
722 s->metadata_entries.phys_sector_size_entry = md_entry;
723 s->metadata_entries.present |= META_PHYS_SECTOR_SIZE_PRESENT;
724 continue;
727 if (guid_eq(md_entry.item_id, parent_locator_guid)) {
728 if (s->metadata_entries.present & META_PARENT_LOCATOR_PRESENT) {
729 ret = -EINVAL;
730 goto exit;
732 s->metadata_entries.parent_locator_entry = md_entry;
733 s->metadata_entries.present |= META_PARENT_LOCATOR_PRESENT;
734 continue;
737 if (md_entry.data_bits & VHDX_META_FLAGS_IS_REQUIRED) {
738 /* cannot read vhdx file - required region table entry that
739 * we do not understand. per spec, we must fail to open */
740 ret = -ENOTSUP;
741 goto exit;
745 if (s->metadata_entries.present != META_ALL_PRESENT) {
746 ret = -ENOTSUP;
747 goto exit;
750 ret = bdrv_pread(bs->file,
751 s->metadata_entries.file_parameters_entry.offset
752 + s->metadata_rt.file_offset,
753 &s->params,
754 sizeof(s->params));
756 if (ret < 0) {
757 goto exit;
760 s->params.block_size = le32_to_cpu(s->params.block_size);
761 s->params.data_bits = le32_to_cpu(s->params.data_bits);
764 /* We now have the file parameters, so we can tell if this is a
765 * differencing file (i.e.. has_parent), is dynamic or fixed
766 * sized (leave_blocks_allocated), and the block size */
768 /* The parent locator required iff the file parameters has_parent set */
769 if (s->params.data_bits & VHDX_PARAMS_HAS_PARENT) {
770 if (s->metadata_entries.present & META_PARENT_LOCATOR_PRESENT) {
771 /* TODO: parse parent locator fields */
772 ret = -ENOTSUP; /* temp, until differencing files are supported */
773 goto exit;
774 } else {
775 /* if has_parent is set, but there is not parent locator present,
776 * then that is an invalid combination */
777 ret = -EINVAL;
778 goto exit;
782 /* determine virtual disk size, logical sector size,
783 * and phys sector size */
785 ret = bdrv_pread(bs->file,
786 s->metadata_entries.virtual_disk_size_entry.offset
787 + s->metadata_rt.file_offset,
788 &s->virtual_disk_size,
789 sizeof(uint64_t));
790 if (ret < 0) {
791 goto exit;
793 ret = bdrv_pread(bs->file,
794 s->metadata_entries.logical_sector_size_entry.offset
795 + s->metadata_rt.file_offset,
796 &s->logical_sector_size,
797 sizeof(uint32_t));
798 if (ret < 0) {
799 goto exit;
801 ret = bdrv_pread(bs->file,
802 s->metadata_entries.phys_sector_size_entry.offset
803 + s->metadata_rt.file_offset,
804 &s->physical_sector_size,
805 sizeof(uint32_t));
806 if (ret < 0) {
807 goto exit;
810 s->virtual_disk_size = le64_to_cpu(s->virtual_disk_size);
811 s->logical_sector_size = le32_to_cpu(s->logical_sector_size);
812 s->physical_sector_size = le32_to_cpu(s->physical_sector_size);
814 if (s->params.block_size < VHDX_BLOCK_SIZE_MIN ||
815 s->params.block_size > VHDX_BLOCK_SIZE_MAX) {
816 ret = -EINVAL;
817 goto exit;
820 /* only 2 supported sector sizes */
821 if (s->logical_sector_size != 512 && s->logical_sector_size != 4096) {
822 ret = -EINVAL;
823 goto exit;
826 /* Both block_size and sector_size are guaranteed powers of 2, below.
827 Due to range checks above, s->sectors_per_block can never be < 256 */
828 s->sectors_per_block = s->params.block_size / s->logical_sector_size;
829 s->chunk_ratio = (VHDX_MAX_SECTORS_PER_BLOCK) *
830 (uint64_t)s->logical_sector_size /
831 (uint64_t)s->params.block_size;
833 /* These values are ones we will want to use for division / multiplication
834 * later on, and they are all guaranteed (per the spec) to be powers of 2,
835 * so we can take advantage of that for shift operations during
836 * reads/writes */
837 if (s->logical_sector_size & (s->logical_sector_size - 1)) {
838 ret = -EINVAL;
839 goto exit;
841 if (s->sectors_per_block & (s->sectors_per_block - 1)) {
842 ret = -EINVAL;
843 goto exit;
845 if (s->chunk_ratio & (s->chunk_ratio - 1)) {
846 ret = -EINVAL;
847 goto exit;
849 s->block_size = s->params.block_size;
850 if (s->block_size & (s->block_size - 1)) {
851 ret = -EINVAL;
852 goto exit;
855 vhdx_set_shift_bits(s);
857 ret = 0;
859 exit:
860 qemu_vfree(buffer);
861 return ret;
865 * Calculate the number of BAT entries, including sector
866 * bitmap entries.
868 static void vhdx_calc_bat_entries(BDRVVHDXState *s)
870 uint32_t data_blocks_cnt, bitmap_blocks_cnt;
872 data_blocks_cnt = DIV_ROUND_UP(s->virtual_disk_size, s->block_size);
873 bitmap_blocks_cnt = DIV_ROUND_UP(data_blocks_cnt, s->chunk_ratio);
875 if (s->parent_entries) {
876 s->bat_entries = bitmap_blocks_cnt * (s->chunk_ratio + 1);
877 } else {
878 s->bat_entries = data_blocks_cnt +
879 ((data_blocks_cnt - 1) >> s->chunk_ratio_bits);
884 static int vhdx_check_bat_entries(BlockDriverState *bs, int *errcnt)
886 BDRVVHDXState *s = bs->opaque;
887 int64_t image_file_size = bdrv_getlength(bs->file->bs);
888 uint64_t payblocks = s->chunk_ratio;
889 uint64_t i;
890 int ret = 0;
892 if (image_file_size < 0) {
893 error_report("Could not determinate VHDX image file size.");
894 return image_file_size;
897 for (i = 0; i < s->bat_entries; i++) {
898 if ((s->bat[i] & VHDX_BAT_STATE_BIT_MASK) ==
899 PAYLOAD_BLOCK_FULLY_PRESENT) {
900 uint64_t offset = s->bat[i] & VHDX_BAT_FILE_OFF_MASK;
902 * Allow that the last block exists only partially. The VHDX spec
903 * states that the image file can only grow in blocksize increments,
904 * but QEMU created images with partial last blocks in the past.
906 uint32_t block_length = MIN(s->block_size,
907 bs->total_sectors * BDRV_SECTOR_SIZE - i * s->block_size);
909 * Check for BAT entry overflow.
911 if (offset > INT64_MAX - s->block_size) {
912 error_report("VHDX BAT entry %" PRIu64 " offset overflow.", i);
913 ret = -EINVAL;
914 if (!errcnt) {
915 break;
917 (*errcnt)++;
920 * Check if fully allocated BAT entries do not reside after
921 * end of the image file.
923 if (offset >= image_file_size) {
924 error_report("VHDX BAT entry %" PRIu64 " start offset %" PRIu64
925 " points after end of file (%" PRIi64 "). Image"
926 " has probably been truncated.",
927 i, offset, image_file_size);
928 ret = -EINVAL;
929 if (!errcnt) {
930 break;
932 (*errcnt)++;
933 } else if (offset + block_length > image_file_size) {
934 error_report("VHDX BAT entry %" PRIu64 " end offset %" PRIu64
935 " points after end of file (%" PRIi64 "). Image"
936 " has probably been truncated.",
937 i, offset + block_length - 1, image_file_size);
938 ret = -EINVAL;
939 if (!errcnt) {
940 break;
942 (*errcnt)++;
946 * verify populated BAT field file offsets against
947 * region table and log entries
949 if (payblocks--) {
950 /* payload bat entries */
951 int ret2;
952 ret2 = vhdx_region_check(s, offset, s->block_size);
953 if (ret2 < 0) {
954 ret = -EINVAL;
955 if (!errcnt) {
956 break;
958 (*errcnt)++;
960 } else {
961 payblocks = s->chunk_ratio;
963 * Once differencing files are supported, verify sector bitmap
964 * blocks here
970 return ret;
973 static void vhdx_close(BlockDriverState *bs)
975 BDRVVHDXState *s = bs->opaque;
976 qemu_vfree(s->headers[0]);
977 s->headers[0] = NULL;
978 qemu_vfree(s->headers[1]);
979 s->headers[1] = NULL;
980 qemu_vfree(s->bat);
981 s->bat = NULL;
982 qemu_vfree(s->parent_entries);
983 s->parent_entries = NULL;
984 migrate_del_blocker(s->migration_blocker);
985 error_free(s->migration_blocker);
986 qemu_vfree(s->log.hdr);
987 s->log.hdr = NULL;
988 vhdx_region_unregister_all(s);
991 static int vhdx_open(BlockDriverState *bs, QDict *options, int flags,
992 Error **errp)
994 BDRVVHDXState *s = bs->opaque;
995 int ret = 0;
996 uint32_t i;
997 uint64_t signature;
998 Error *local_err = NULL;
1000 bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
1001 false, errp);
1002 if (!bs->file) {
1003 return -EINVAL;
1006 s->bat = NULL;
1007 s->first_visible_write = true;
1009 qemu_co_mutex_init(&s->lock);
1010 QLIST_INIT(&s->regions);
1012 /* validate the file signature */
1013 ret = bdrv_pread(bs->file, 0, &signature, sizeof(uint64_t));
1014 if (ret < 0) {
1015 goto fail;
1017 if (memcmp(&signature, "vhdxfile", 8)) {
1018 ret = -EINVAL;
1019 goto fail;
1022 /* This is used for any header updates, for the file_write_guid.
1023 * The spec dictates that a new value should be used for the first
1024 * header update */
1025 vhdx_guid_generate(&s->session_guid);
1027 vhdx_parse_header(bs, s, &local_err);
1028 if (local_err != NULL) {
1029 error_propagate(errp, local_err);
1030 ret = -EINVAL;
1031 goto fail;
1034 ret = vhdx_parse_log(bs, s, &s->log_replayed_on_open, errp);
1035 if (ret < 0) {
1036 goto fail;
1039 ret = vhdx_open_region_tables(bs, s);
1040 if (ret < 0) {
1041 goto fail;
1044 ret = vhdx_parse_metadata(bs, s);
1045 if (ret < 0) {
1046 goto fail;
1049 s->block_size = s->params.block_size;
1051 /* the VHDX spec dictates that virtual_disk_size is always a multiple of
1052 * logical_sector_size */
1053 bs->total_sectors = s->virtual_disk_size >> s->logical_sector_size_bits;
1055 vhdx_calc_bat_entries(s);
1057 s->bat_offset = s->bat_rt.file_offset;
1059 if (s->bat_entries > s->bat_rt.length / sizeof(VHDXBatEntry)) {
1060 /* BAT allocation is not large enough for all entries */
1061 ret = -EINVAL;
1062 goto fail;
1065 /* s->bat is freed in vhdx_close() */
1066 s->bat = qemu_try_blockalign(bs->file->bs, s->bat_rt.length);
1067 if (s->bat == NULL) {
1068 ret = -ENOMEM;
1069 goto fail;
1072 ret = bdrv_pread(bs->file, s->bat_offset, s->bat, s->bat_rt.length);
1073 if (ret < 0) {
1074 goto fail;
1077 /* endian convert populated BAT field entires */
1078 for (i = 0; i < s->bat_entries; i++) {
1079 s->bat[i] = le64_to_cpu(s->bat[i]);
1082 if (!(flags & BDRV_O_CHECK)) {
1083 ret = vhdx_check_bat_entries(bs, NULL);
1084 if (ret < 0) {
1085 goto fail;
1089 /* Disable migration when VHDX images are used */
1090 error_setg(&s->migration_blocker, "The vhdx format used by node '%s' "
1091 "does not support live migration",
1092 bdrv_get_device_or_node_name(bs));
1093 ret = migrate_add_blocker(s->migration_blocker, &local_err);
1094 if (local_err) {
1095 error_propagate(errp, local_err);
1096 error_free(s->migration_blocker);
1097 goto fail;
1100 /* TODO: differencing files */
1102 return 0;
1103 fail:
1104 vhdx_close(bs);
1105 return ret;
1108 static int vhdx_reopen_prepare(BDRVReopenState *state,
1109 BlockReopenQueue *queue, Error **errp)
1111 return 0;
1116 * Perform sector to block offset translations, to get various
1117 * sector and file offsets into the image. See VHDXSectorInfo
1119 static void vhdx_block_translate(BDRVVHDXState *s, int64_t sector_num,
1120 int nb_sectors, VHDXSectorInfo *sinfo)
1122 uint32_t block_offset;
1124 sinfo->bat_idx = sector_num >> s->sectors_per_block_bits;
1125 /* effectively a modulo - this gives us the offset into the block
1126 * (in sector sizes) for our sector number */
1127 block_offset = sector_num - (sinfo->bat_idx << s->sectors_per_block_bits);
1128 /* the chunk ratio gives us the interleaving of the sector
1129 * bitmaps, so we need to advance our page block index by the
1130 * sector bitmaps entry number */
1131 sinfo->bat_idx += sinfo->bat_idx >> s->chunk_ratio_bits;
1133 /* the number of sectors we can read/write in this cycle */
1134 sinfo->sectors_avail = s->sectors_per_block - block_offset;
1136 sinfo->bytes_left = sinfo->sectors_avail << s->logical_sector_size_bits;
1138 if (sinfo->sectors_avail > nb_sectors) {
1139 sinfo->sectors_avail = nb_sectors;
1142 sinfo->bytes_avail = sinfo->sectors_avail << s->logical_sector_size_bits;
1144 sinfo->file_offset = s->bat[sinfo->bat_idx] & VHDX_BAT_FILE_OFF_MASK;
1146 sinfo->block_offset = block_offset << s->logical_sector_size_bits;
1148 /* The file offset must be past the header section, so must be > 0 */
1149 if (sinfo->file_offset == 0) {
1150 return;
1153 /* block offset is the offset in vhdx logical sectors, in
1154 * the payload data block. Convert that to a byte offset
1155 * in the block, and add in the payload data block offset
1156 * in the file, in bytes, to get the final read address */
1158 sinfo->file_offset += sinfo->block_offset;
1162 static int vhdx_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1164 BDRVVHDXState *s = bs->opaque;
1166 bdi->cluster_size = s->block_size;
1168 bdi->unallocated_blocks_are_zero =
1169 (s->params.data_bits & VHDX_PARAMS_HAS_PARENT) == 0;
1171 return 0;
1175 static coroutine_fn int vhdx_co_readv(BlockDriverState *bs, int64_t sector_num,
1176 int nb_sectors, QEMUIOVector *qiov)
1178 BDRVVHDXState *s = bs->opaque;
1179 int ret = 0;
1180 VHDXSectorInfo sinfo;
1181 uint64_t bytes_done = 0;
1182 QEMUIOVector hd_qiov;
1184 qemu_iovec_init(&hd_qiov, qiov->niov);
1186 qemu_co_mutex_lock(&s->lock);
1188 while (nb_sectors > 0) {
1189 /* We are a differencing file, so we need to inspect the sector bitmap
1190 * to see if we have the data or not */
1191 if (s->params.data_bits & VHDX_PARAMS_HAS_PARENT) {
1192 /* not supported yet */
1193 ret = -ENOTSUP;
1194 goto exit;
1195 } else {
1196 vhdx_block_translate(s, sector_num, nb_sectors, &sinfo);
1198 qemu_iovec_reset(&hd_qiov);
1199 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, sinfo.bytes_avail);
1201 /* check the payload block state */
1202 switch (s->bat[sinfo.bat_idx] & VHDX_BAT_STATE_BIT_MASK) {
1203 case PAYLOAD_BLOCK_NOT_PRESENT: /* fall through */
1204 case PAYLOAD_BLOCK_UNDEFINED:
1205 case PAYLOAD_BLOCK_UNMAPPED:
1206 case PAYLOAD_BLOCK_UNMAPPED_v095:
1207 case PAYLOAD_BLOCK_ZERO:
1208 /* return zero */
1209 qemu_iovec_memset(&hd_qiov, 0, 0, sinfo.bytes_avail);
1210 break;
1211 case PAYLOAD_BLOCK_FULLY_PRESENT:
1212 qemu_co_mutex_unlock(&s->lock);
1213 ret = bdrv_co_preadv(bs->file, sinfo.file_offset,
1214 sinfo.sectors_avail * BDRV_SECTOR_SIZE,
1215 &hd_qiov, 0);
1216 qemu_co_mutex_lock(&s->lock);
1217 if (ret < 0) {
1218 goto exit;
1220 break;
1221 case PAYLOAD_BLOCK_PARTIALLY_PRESENT:
1222 /* we don't yet support difference files, fall through
1223 * to error */
1224 default:
1225 ret = -EIO;
1226 goto exit;
1227 break;
1229 nb_sectors -= sinfo.sectors_avail;
1230 sector_num += sinfo.sectors_avail;
1231 bytes_done += sinfo.bytes_avail;
1234 ret = 0;
1235 exit:
1236 qemu_co_mutex_unlock(&s->lock);
1237 qemu_iovec_destroy(&hd_qiov);
1238 return ret;
1242 * Allocate a new payload block at the end of the file.
1244 * Allocation will happen at 1MB alignment inside the file
1246 * Returns the file offset start of the new payload block
1248 static int vhdx_allocate_block(BlockDriverState *bs, BDRVVHDXState *s,
1249 uint64_t *new_offset)
1251 int64_t current_len;
1253 current_len = bdrv_getlength(bs->file->bs);
1254 if (current_len < 0) {
1255 return current_len;
1258 *new_offset = current_len;
1260 /* per the spec, the address for a block is in units of 1MB */
1261 *new_offset = ROUND_UP(*new_offset, 1 * MiB);
1262 if (*new_offset > INT64_MAX) {
1263 return -EINVAL;
1266 return bdrv_truncate(bs->file, *new_offset + s->block_size, false,
1267 PREALLOC_MODE_OFF, NULL);
1271 * Update the BAT table entry with the new file offset, and the new entry
1272 * state */
1273 static void vhdx_update_bat_table_entry(BlockDriverState *bs, BDRVVHDXState *s,
1274 VHDXSectorInfo *sinfo,
1275 uint64_t *bat_entry_le,
1276 uint64_t *bat_offset, int state)
1278 /* The BAT entry is a uint64, with 44 bits for the file offset in units of
1279 * 1MB, and 3 bits for the block state. */
1280 if ((state == PAYLOAD_BLOCK_ZERO) ||
1281 (state == PAYLOAD_BLOCK_UNDEFINED) ||
1282 (state == PAYLOAD_BLOCK_NOT_PRESENT) ||
1283 (state == PAYLOAD_BLOCK_UNMAPPED)) {
1284 s->bat[sinfo->bat_idx] = 0; /* For PAYLOAD_BLOCK_ZERO, the
1285 FileOffsetMB field is denoted as
1286 'reserved' in the v1.0 spec. If it is
1287 non-zero, MS Hyper-V will fail to read
1288 the disk image */
1289 } else {
1290 s->bat[sinfo->bat_idx] = sinfo->file_offset;
1293 s->bat[sinfo->bat_idx] |= state & VHDX_BAT_STATE_BIT_MASK;
1295 *bat_entry_le = cpu_to_le64(s->bat[sinfo->bat_idx]);
1296 *bat_offset = s->bat_offset + sinfo->bat_idx * sizeof(VHDXBatEntry);
1300 /* Per the spec, on the first write of guest-visible data to the file the
1301 * data write guid must be updated in the header */
1302 int vhdx_user_visible_write(BlockDriverState *bs, BDRVVHDXState *s)
1304 int ret = 0;
1305 if (s->first_visible_write) {
1306 s->first_visible_write = false;
1307 ret = vhdx_update_headers(bs, s, true, NULL);
1309 return ret;
1312 static coroutine_fn int vhdx_co_writev(BlockDriverState *bs, int64_t sector_num,
1313 int nb_sectors, QEMUIOVector *qiov,
1314 int flags)
1316 int ret = -ENOTSUP;
1317 BDRVVHDXState *s = bs->opaque;
1318 VHDXSectorInfo sinfo;
1319 uint64_t bytes_done = 0;
1320 uint64_t bat_entry = 0;
1321 uint64_t bat_entry_offset = 0;
1322 QEMUIOVector hd_qiov;
1323 struct iovec iov1 = { 0 };
1324 struct iovec iov2 = { 0 };
1325 int sectors_to_write;
1326 int bat_state;
1327 uint64_t bat_prior_offset = 0;
1328 bool bat_update = false;
1330 assert(!flags);
1331 qemu_iovec_init(&hd_qiov, qiov->niov);
1333 qemu_co_mutex_lock(&s->lock);
1335 ret = vhdx_user_visible_write(bs, s);
1336 if (ret < 0) {
1337 goto exit;
1340 while (nb_sectors > 0) {
1341 bool use_zero_buffers = false;
1342 bat_update = false;
1343 if (s->params.data_bits & VHDX_PARAMS_HAS_PARENT) {
1344 /* not supported yet */
1345 ret = -ENOTSUP;
1346 goto exit;
1347 } else {
1348 vhdx_block_translate(s, sector_num, nb_sectors, &sinfo);
1349 sectors_to_write = sinfo.sectors_avail;
1351 qemu_iovec_reset(&hd_qiov);
1352 /* check the payload block state */
1353 bat_state = s->bat[sinfo.bat_idx] & VHDX_BAT_STATE_BIT_MASK;
1354 switch (bat_state) {
1355 case PAYLOAD_BLOCK_ZERO:
1356 /* in this case, we need to preserve zero writes for
1357 * data that is not part of this write, so we must pad
1358 * the rest of the buffer to zeroes */
1360 /* if we are on a posix system with ftruncate() that extends
1361 * a file, then it is zero-filled for us. On Win32, the raw
1362 * layer uses SetFilePointer and SetFileEnd, which does not
1363 * zero fill AFAIK */
1365 /* Queue another write of zero buffers if the underlying file
1366 * does not zero-fill on file extension */
1368 if (bdrv_has_zero_init_truncate(bs->file->bs) == 0) {
1369 use_zero_buffers = true;
1371 /* zero fill the front, if any */
1372 if (sinfo.block_offset) {
1373 iov1.iov_len = sinfo.block_offset;
1374 iov1.iov_base = qemu_blockalign(bs, iov1.iov_len);
1375 memset(iov1.iov_base, 0, iov1.iov_len);
1376 qemu_iovec_concat_iov(&hd_qiov, &iov1, 1, 0,
1377 iov1.iov_len);
1378 sectors_to_write += iov1.iov_len >> BDRV_SECTOR_BITS;
1381 /* our actual data */
1382 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1383 sinfo.bytes_avail);
1385 /* zero fill the back, if any */
1386 if ((sinfo.bytes_avail - sinfo.block_offset) <
1387 s->block_size) {
1388 iov2.iov_len = s->block_size -
1389 (sinfo.bytes_avail + sinfo.block_offset);
1390 iov2.iov_base = qemu_blockalign(bs, iov2.iov_len);
1391 memset(iov2.iov_base, 0, iov2.iov_len);
1392 qemu_iovec_concat_iov(&hd_qiov, &iov2, 1, 0,
1393 iov2.iov_len);
1394 sectors_to_write += iov2.iov_len >> BDRV_SECTOR_BITS;
1397 /* fall through */
1398 case PAYLOAD_BLOCK_NOT_PRESENT: /* fall through */
1399 case PAYLOAD_BLOCK_UNMAPPED:
1400 case PAYLOAD_BLOCK_UNMAPPED_v095:
1401 case PAYLOAD_BLOCK_UNDEFINED:
1402 bat_prior_offset = sinfo.file_offset;
1403 ret = vhdx_allocate_block(bs, s, &sinfo.file_offset);
1404 if (ret < 0) {
1405 goto exit;
1407 /* once we support differencing files, this may also be
1408 * partially present */
1409 /* update block state to the newly specified state */
1410 vhdx_update_bat_table_entry(bs, s, &sinfo, &bat_entry,
1411 &bat_entry_offset,
1412 PAYLOAD_BLOCK_FULLY_PRESENT);
1413 bat_update = true;
1414 /* since we just allocated a block, file_offset is the
1415 * beginning of the payload block. It needs to be the
1416 * write address, which includes the offset into the block */
1417 if (!use_zero_buffers) {
1418 sinfo.file_offset += sinfo.block_offset;
1420 /* fall through */
1421 case PAYLOAD_BLOCK_FULLY_PRESENT:
1422 /* if the file offset address is in the header zone,
1423 * there is a problem */
1424 if (sinfo.file_offset < (1 * MiB)) {
1425 ret = -EFAULT;
1426 goto error_bat_restore;
1429 if (!use_zero_buffers) {
1430 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1431 sinfo.bytes_avail);
1433 /* block exists, so we can just overwrite it */
1434 qemu_co_mutex_unlock(&s->lock);
1435 ret = bdrv_co_pwritev(bs->file, sinfo.file_offset,
1436 sectors_to_write * BDRV_SECTOR_SIZE,
1437 &hd_qiov, 0);
1438 qemu_co_mutex_lock(&s->lock);
1439 if (ret < 0) {
1440 goto error_bat_restore;
1442 break;
1443 case PAYLOAD_BLOCK_PARTIALLY_PRESENT:
1444 /* we don't yet support difference files, fall through
1445 * to error */
1446 default:
1447 ret = -EIO;
1448 goto exit;
1449 break;
1452 if (bat_update) {
1453 /* this will update the BAT entry into the log journal, and
1454 * then flush the log journal out to disk */
1455 ret = vhdx_log_write_and_flush(bs, s, &bat_entry,
1456 sizeof(VHDXBatEntry),
1457 bat_entry_offset);
1458 if (ret < 0) {
1459 goto exit;
1463 nb_sectors -= sinfo.sectors_avail;
1464 sector_num += sinfo.sectors_avail;
1465 bytes_done += sinfo.bytes_avail;
1470 goto exit;
1472 error_bat_restore:
1473 if (bat_update) {
1474 /* keep metadata in sync, and restore the bat entry state
1475 * if error. */
1476 sinfo.file_offset = bat_prior_offset;
1477 vhdx_update_bat_table_entry(bs, s, &sinfo, &bat_entry,
1478 &bat_entry_offset, bat_state);
1480 exit:
1481 qemu_vfree(iov1.iov_base);
1482 qemu_vfree(iov2.iov_base);
1483 qemu_co_mutex_unlock(&s->lock);
1484 qemu_iovec_destroy(&hd_qiov);
1485 return ret;
1491 * Create VHDX Headers
1493 * There are 2 headers, and the highest sequence number will represent
1494 * the active header
1496 static int vhdx_create_new_headers(BlockBackend *blk, uint64_t image_size,
1497 uint32_t log_size)
1499 BlockDriverState *bs = blk_bs(blk);
1500 BdrvChild *child;
1501 int ret = 0;
1502 VHDXHeader *hdr = NULL;
1504 hdr = g_new0(VHDXHeader, 1);
1506 hdr->signature = VHDX_HEADER_SIGNATURE;
1507 hdr->sequence_number = g_random_int();
1508 hdr->log_version = 0;
1509 hdr->version = 1;
1510 hdr->log_length = log_size;
1511 hdr->log_offset = VHDX_HEADER_SECTION_END;
1512 vhdx_guid_generate(&hdr->file_write_guid);
1513 vhdx_guid_generate(&hdr->data_write_guid);
1515 /* XXX Ugly way to get blk->root, but that's a feature, not a bug. This
1516 * hack makes it obvious that vhdx_write_header() bypasses the BlockBackend
1517 * here, which it really shouldn't be doing. */
1518 child = QLIST_FIRST(&bs->parents);
1519 assert(!QLIST_NEXT(child, next_parent));
1521 ret = vhdx_write_header(child, hdr, VHDX_HEADER1_OFFSET, false);
1522 if (ret < 0) {
1523 goto exit;
1525 hdr->sequence_number++;
1526 ret = vhdx_write_header(child, hdr, VHDX_HEADER2_OFFSET, false);
1527 if (ret < 0) {
1528 goto exit;
1531 exit:
1532 g_free(hdr);
1533 return ret;
1536 #define VHDX_METADATA_ENTRY_BUFFER_SIZE \
1537 (sizeof(VHDXFileParameters) +\
1538 sizeof(VHDXVirtualDiskSize) +\
1539 sizeof(VHDXPage83Data) +\
1540 sizeof(VHDXVirtualDiskLogicalSectorSize) +\
1541 sizeof(VHDXVirtualDiskPhysicalSectorSize))
1544 * Create the Metadata entries.
1546 * For more details on the entries, see section 3.5 (pg 29) in the
1547 * VHDX 1.00 specification.
1549 * We support 5 metadata entries (all required by spec):
1550 * File Parameters,
1551 * Virtual Disk Size,
1552 * Page 83 Data,
1553 * Logical Sector Size,
1554 * Physical Sector Size
1556 * The first 64KB of the Metadata section is reserved for the metadata
1557 * header and entries; beyond that, the metadata items themselves reside.
1559 static int vhdx_create_new_metadata(BlockBackend *blk,
1560 uint64_t image_size,
1561 uint32_t block_size,
1562 uint32_t sector_size,
1563 uint64_t metadata_offset,
1564 VHDXImageType type)
1566 int ret = 0;
1567 uint32_t offset = 0;
1568 void *buffer = NULL;
1569 void *entry_buffer;
1570 VHDXMetadataTableHeader *md_table;
1571 VHDXMetadataTableEntry *md_table_entry;
1573 /* Metadata entries */
1574 VHDXFileParameters *mt_file_params;
1575 VHDXVirtualDiskSize *mt_virtual_size;
1576 VHDXPage83Data *mt_page83;
1577 VHDXVirtualDiskLogicalSectorSize *mt_log_sector_size;
1578 VHDXVirtualDiskPhysicalSectorSize *mt_phys_sector_size;
1580 entry_buffer = g_malloc0(VHDX_METADATA_ENTRY_BUFFER_SIZE);
1582 mt_file_params = entry_buffer;
1583 offset += sizeof(VHDXFileParameters);
1584 mt_virtual_size = entry_buffer + offset;
1585 offset += sizeof(VHDXVirtualDiskSize);
1586 mt_page83 = entry_buffer + offset;
1587 offset += sizeof(VHDXPage83Data);
1588 mt_log_sector_size = entry_buffer + offset;
1589 offset += sizeof(VHDXVirtualDiskLogicalSectorSize);
1590 mt_phys_sector_size = entry_buffer + offset;
1592 mt_file_params->block_size = cpu_to_le32(block_size);
1593 if (type == VHDX_TYPE_FIXED) {
1594 mt_file_params->data_bits |= VHDX_PARAMS_LEAVE_BLOCKS_ALLOCED;
1595 mt_file_params->data_bits = cpu_to_le32(mt_file_params->data_bits);
1598 vhdx_guid_generate(&mt_page83->page_83_data);
1599 cpu_to_leguids(&mt_page83->page_83_data);
1600 mt_virtual_size->virtual_disk_size = cpu_to_le64(image_size);
1601 mt_log_sector_size->logical_sector_size = cpu_to_le32(sector_size);
1602 mt_phys_sector_size->physical_sector_size = cpu_to_le32(sector_size);
1604 buffer = g_malloc0(VHDX_HEADER_BLOCK_SIZE);
1605 md_table = buffer;
1607 md_table->signature = VHDX_METADATA_SIGNATURE;
1608 md_table->entry_count = 5;
1609 vhdx_metadata_header_le_export(md_table);
1612 /* This will reference beyond the reserved table portion */
1613 offset = 64 * KiB;
1615 md_table_entry = buffer + sizeof(VHDXMetadataTableHeader);
1617 md_table_entry[0].item_id = file_param_guid;
1618 md_table_entry[0].offset = offset;
1619 md_table_entry[0].length = sizeof(VHDXFileParameters);
1620 md_table_entry[0].data_bits |= VHDX_META_FLAGS_IS_REQUIRED;
1621 offset += md_table_entry[0].length;
1622 vhdx_metadata_entry_le_export(&md_table_entry[0]);
1624 md_table_entry[1].item_id = virtual_size_guid;
1625 md_table_entry[1].offset = offset;
1626 md_table_entry[1].length = sizeof(VHDXVirtualDiskSize);
1627 md_table_entry[1].data_bits |= VHDX_META_FLAGS_IS_REQUIRED |
1628 VHDX_META_FLAGS_IS_VIRTUAL_DISK;
1629 offset += md_table_entry[1].length;
1630 vhdx_metadata_entry_le_export(&md_table_entry[1]);
1632 md_table_entry[2].item_id = page83_guid;
1633 md_table_entry[2].offset = offset;
1634 md_table_entry[2].length = sizeof(VHDXPage83Data);
1635 md_table_entry[2].data_bits |= VHDX_META_FLAGS_IS_REQUIRED |
1636 VHDX_META_FLAGS_IS_VIRTUAL_DISK;
1637 offset += md_table_entry[2].length;
1638 vhdx_metadata_entry_le_export(&md_table_entry[2]);
1640 md_table_entry[3].item_id = logical_sector_guid;
1641 md_table_entry[3].offset = offset;
1642 md_table_entry[3].length = sizeof(VHDXVirtualDiskLogicalSectorSize);
1643 md_table_entry[3].data_bits |= VHDX_META_FLAGS_IS_REQUIRED |
1644 VHDX_META_FLAGS_IS_VIRTUAL_DISK;
1645 offset += md_table_entry[3].length;
1646 vhdx_metadata_entry_le_export(&md_table_entry[3]);
1648 md_table_entry[4].item_id = phys_sector_guid;
1649 md_table_entry[4].offset = offset;
1650 md_table_entry[4].length = sizeof(VHDXVirtualDiskPhysicalSectorSize);
1651 md_table_entry[4].data_bits |= VHDX_META_FLAGS_IS_REQUIRED |
1652 VHDX_META_FLAGS_IS_VIRTUAL_DISK;
1653 vhdx_metadata_entry_le_export(&md_table_entry[4]);
1655 ret = blk_pwrite(blk, metadata_offset, buffer, VHDX_HEADER_BLOCK_SIZE, 0);
1656 if (ret < 0) {
1657 goto exit;
1660 ret = blk_pwrite(blk, metadata_offset + (64 * KiB), entry_buffer,
1661 VHDX_METADATA_ENTRY_BUFFER_SIZE, 0);
1662 if (ret < 0) {
1663 goto exit;
1667 exit:
1668 g_free(buffer);
1669 g_free(entry_buffer);
1670 return ret;
1673 /* This create the actual BAT itself. We currently only support
1674 * 'Dynamic' and 'Fixed' image types.
1676 * Dynamic images: default state of the BAT is all zeroes.
1678 * Fixed images: default state of the BAT is fully populated, with
1679 * file offsets and state PAYLOAD_BLOCK_FULLY_PRESENT.
1681 static int vhdx_create_bat(BlockBackend *blk, BDRVVHDXState *s,
1682 uint64_t image_size, VHDXImageType type,
1683 bool use_zero_blocks, uint64_t file_offset,
1684 uint32_t length, Error **errp)
1686 int ret = 0;
1687 uint64_t data_file_offset;
1688 uint64_t total_sectors = 0;
1689 uint64_t sector_num = 0;
1690 uint64_t unused;
1691 int block_state;
1692 VHDXSectorInfo sinfo;
1694 assert(s->bat == NULL);
1696 /* this gives a data start after BAT/bitmap entries, and well
1697 * past any metadata entries (with a 4 MB buffer for future
1698 * expansion */
1699 data_file_offset = file_offset + length + 5 * MiB;
1700 total_sectors = image_size >> s->logical_sector_size_bits;
1702 if (type == VHDX_TYPE_DYNAMIC) {
1703 /* All zeroes, so we can just extend the file - the end of the BAT
1704 * is the furthest thing we have written yet */
1705 ret = blk_truncate(blk, data_file_offset, false, PREALLOC_MODE_OFF,
1706 errp);
1707 if (ret < 0) {
1708 goto exit;
1710 } else if (type == VHDX_TYPE_FIXED) {
1711 ret = blk_truncate(blk, data_file_offset + image_size, false,
1712 PREALLOC_MODE_OFF, errp);
1713 if (ret < 0) {
1714 goto exit;
1716 } else {
1717 error_setg(errp, "Unsupported image type");
1718 ret = -ENOTSUP;
1719 goto exit;
1722 if (type == VHDX_TYPE_FIXED ||
1723 use_zero_blocks ||
1724 bdrv_has_zero_init(blk_bs(blk)) == 0) {
1725 /* for a fixed file, the default BAT entry is not zero */
1726 s->bat = g_try_malloc0(length);
1727 if (length && s->bat == NULL) {
1728 error_setg(errp, "Failed to allocate memory for the BAT");
1729 ret = -ENOMEM;
1730 goto exit;
1732 block_state = type == VHDX_TYPE_FIXED ? PAYLOAD_BLOCK_FULLY_PRESENT :
1733 PAYLOAD_BLOCK_NOT_PRESENT;
1734 block_state = use_zero_blocks ? PAYLOAD_BLOCK_ZERO : block_state;
1735 /* fill the BAT by emulating sector writes of sectors_per_block size */
1736 while (sector_num < total_sectors) {
1737 vhdx_block_translate(s, sector_num, s->sectors_per_block, &sinfo);
1738 sinfo.file_offset = data_file_offset +
1739 (sector_num << s->logical_sector_size_bits);
1740 sinfo.file_offset = ROUND_UP(sinfo.file_offset, MiB);
1741 vhdx_update_bat_table_entry(blk_bs(blk), s, &sinfo, &unused, &unused,
1742 block_state);
1743 s->bat[sinfo.bat_idx] = cpu_to_le64(s->bat[sinfo.bat_idx]);
1744 sector_num += s->sectors_per_block;
1746 ret = blk_pwrite(blk, file_offset, s->bat, length, 0);
1747 if (ret < 0) {
1748 error_setg_errno(errp, -ret, "Failed to write the BAT");
1749 goto exit;
1755 exit:
1756 g_free(s->bat);
1757 return ret;
1760 /* Creates the region table header, and region table entries.
1761 * There are 2 supported region table entries: BAT, and Metadata/
1763 * As the calculations for the BAT region table are also needed
1764 * to create the BAT itself, we will also cause the BAT to be
1765 * created.
1767 static int vhdx_create_new_region_table(BlockBackend *blk,
1768 uint64_t image_size,
1769 uint32_t block_size,
1770 uint32_t sector_size,
1771 uint32_t log_size,
1772 bool use_zero_blocks,
1773 VHDXImageType type,
1774 uint64_t *metadata_offset,
1775 Error **errp)
1777 int ret = 0;
1778 uint32_t offset = 0;
1779 void *buffer = NULL;
1780 uint64_t bat_file_offset;
1781 uint32_t bat_length;
1782 BDRVVHDXState *s = NULL;
1783 VHDXRegionTableHeader *region_table;
1784 VHDXRegionTableEntry *rt_bat;
1785 VHDXRegionTableEntry *rt_metadata;
1787 assert(metadata_offset != NULL);
1789 /* Populate enough of the BDRVVHDXState to be able to use the
1790 * pre-existing BAT calculation, translation, and update functions */
1791 s = g_new0(BDRVVHDXState, 1);
1793 s->chunk_ratio = (VHDX_MAX_SECTORS_PER_BLOCK) *
1794 (uint64_t) sector_size / (uint64_t) block_size;
1796 s->sectors_per_block = block_size / sector_size;
1797 s->virtual_disk_size = image_size;
1798 s->block_size = block_size;
1799 s->logical_sector_size = sector_size;
1801 vhdx_set_shift_bits(s);
1803 vhdx_calc_bat_entries(s);
1805 /* At this point the VHDX state is populated enough for creation */
1807 /* a single buffer is used so we can calculate the checksum over the
1808 * entire 64KB block */
1809 buffer = g_malloc0(VHDX_HEADER_BLOCK_SIZE);
1810 region_table = buffer;
1811 offset += sizeof(VHDXRegionTableHeader);
1812 rt_bat = buffer + offset;
1813 offset += sizeof(VHDXRegionTableEntry);
1814 rt_metadata = buffer + offset;
1816 region_table->signature = VHDX_REGION_SIGNATURE;
1817 region_table->entry_count = 2; /* BAT and Metadata */
1819 rt_bat->guid = bat_guid;
1820 rt_bat->length = ROUND_UP(s->bat_entries * sizeof(VHDXBatEntry), MiB);
1821 rt_bat->file_offset = ROUND_UP(VHDX_HEADER_SECTION_END + log_size, MiB);
1822 s->bat_offset = rt_bat->file_offset;
1824 rt_metadata->guid = metadata_guid;
1825 rt_metadata->file_offset = ROUND_UP(rt_bat->file_offset + rt_bat->length,
1826 MiB);
1827 rt_metadata->length = 1 * MiB; /* min size, and more than enough */
1828 *metadata_offset = rt_metadata->file_offset;
1830 bat_file_offset = rt_bat->file_offset;
1831 bat_length = rt_bat->length;
1833 vhdx_region_header_le_export(region_table);
1834 vhdx_region_entry_le_export(rt_bat);
1835 vhdx_region_entry_le_export(rt_metadata);
1837 vhdx_update_checksum(buffer, VHDX_HEADER_BLOCK_SIZE,
1838 offsetof(VHDXRegionTableHeader, checksum));
1841 /* The region table gives us the data we need to create the BAT,
1842 * so do that now */
1843 ret = vhdx_create_bat(blk, s, image_size, type, use_zero_blocks,
1844 bat_file_offset, bat_length, errp);
1845 if (ret < 0) {
1846 goto exit;
1849 /* Now write out the region headers to disk */
1850 ret = blk_pwrite(blk, VHDX_REGION_TABLE_OFFSET, buffer,
1851 VHDX_HEADER_BLOCK_SIZE, 0);
1852 if (ret < 0) {
1853 error_setg_errno(errp, -ret, "Failed to write first region table");
1854 goto exit;
1857 ret = blk_pwrite(blk, VHDX_REGION_TABLE2_OFFSET, buffer,
1858 VHDX_HEADER_BLOCK_SIZE, 0);
1859 if (ret < 0) {
1860 error_setg_errno(errp, -ret, "Failed to write second region table");
1861 goto exit;
1864 exit:
1865 g_free(s);
1866 g_free(buffer);
1867 return ret;
1870 /* We need to create the following elements:
1872 * .-----------------------------------------------------------------.
1873 * | (A) | (B) | (C) | (D) | (E) |
1874 * | File ID | Header1 | Header 2 | Region Tbl 1 | Region Tbl 2 |
1875 * | | | | | |
1876 * .-----------------------------------------------------------------.
1877 * 0 64KB 128KB 192KB 256KB 320KB
1880 * .---- ~ ----------- ~ ------------ ~ ---------------- ~ -----------.
1881 * | (F) | (G) | (H) | |
1882 * | Journal Log | BAT / Bitmap | Metadata | .... data ...... |
1883 * | | | | |
1884 * .---- ~ ----------- ~ ------------ ~ ---------------- ~ -----------.
1885 * 1MB
1887 static int coroutine_fn vhdx_co_create(BlockdevCreateOptions *opts,
1888 Error **errp)
1890 BlockdevCreateOptionsVhdx *vhdx_opts;
1891 BlockBackend *blk = NULL;
1892 BlockDriverState *bs = NULL;
1894 int ret = 0;
1895 uint64_t image_size;
1896 uint32_t log_size;
1897 uint32_t block_size;
1898 uint64_t signature;
1899 uint64_t metadata_offset;
1900 bool use_zero_blocks = false;
1902 gunichar2 *creator = NULL;
1903 glong creator_items;
1904 VHDXImageType image_type;
1906 assert(opts->driver == BLOCKDEV_DRIVER_VHDX);
1907 vhdx_opts = &opts->u.vhdx;
1909 /* Validate options and set default values */
1910 image_size = vhdx_opts->size;
1911 if (image_size > VHDX_MAX_IMAGE_SIZE) {
1912 error_setg(errp, "Image size too large; max of 64TB");
1913 return -EINVAL;
1916 if (!vhdx_opts->has_log_size) {
1917 log_size = DEFAULT_LOG_SIZE;
1918 } else {
1919 if (vhdx_opts->log_size > UINT32_MAX) {
1920 error_setg(errp, "Log size must be smaller than 4 GB");
1921 return -EINVAL;
1923 log_size = vhdx_opts->log_size;
1925 if (log_size < MiB || (log_size % MiB) != 0) {
1926 error_setg(errp, "Log size must be a multiple of 1 MB");
1927 return -EINVAL;
1930 if (!vhdx_opts->has_block_state_zero) {
1931 use_zero_blocks = true;
1932 } else {
1933 use_zero_blocks = vhdx_opts->block_state_zero;
1936 if (!vhdx_opts->has_subformat) {
1937 vhdx_opts->subformat = BLOCKDEV_VHDX_SUBFORMAT_DYNAMIC;
1940 switch (vhdx_opts->subformat) {
1941 case BLOCKDEV_VHDX_SUBFORMAT_DYNAMIC:
1942 image_type = VHDX_TYPE_DYNAMIC;
1943 break;
1944 case BLOCKDEV_VHDX_SUBFORMAT_FIXED:
1945 image_type = VHDX_TYPE_FIXED;
1946 break;
1947 default:
1948 g_assert_not_reached();
1951 /* These are pretty arbitrary, and mainly designed to keep the BAT
1952 * size reasonable to load into RAM */
1953 if (vhdx_opts->has_block_size) {
1954 block_size = vhdx_opts->block_size;
1955 } else {
1956 if (image_size > 32 * TiB) {
1957 block_size = 64 * MiB;
1958 } else if (image_size > (uint64_t) 100 * GiB) {
1959 block_size = 32 * MiB;
1960 } else if (image_size > 1 * GiB) {
1961 block_size = 16 * MiB;
1962 } else {
1963 block_size = 8 * MiB;
1967 if (block_size < MiB || (block_size % MiB) != 0) {
1968 error_setg(errp, "Block size must be a multiple of 1 MB");
1969 return -EINVAL;
1971 if (!is_power_of_2(block_size)) {
1972 error_setg(errp, "Block size must be a power of two");
1973 return -EINVAL;
1975 if (block_size > VHDX_BLOCK_SIZE_MAX) {
1976 error_setg(errp, "Block size must not exceed %" PRId64,
1977 VHDX_BLOCK_SIZE_MAX);
1978 return -EINVAL;
1981 /* Create BlockBackend to write to the image */
1982 bs = bdrv_open_blockdev_ref(vhdx_opts->file, errp);
1983 if (bs == NULL) {
1984 return -EIO;
1987 blk = blk_new(bdrv_get_aio_context(bs),
1988 BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL);
1989 ret = blk_insert_bs(blk, bs, errp);
1990 if (ret < 0) {
1991 goto delete_and_exit;
1993 blk_set_allow_write_beyond_eof(blk, true);
1995 /* Create (A) */
1997 /* The creator field is optional, but may be useful for
1998 * debugging / diagnostics */
1999 creator = g_utf8_to_utf16("QEMU v" QEMU_VERSION, -1, NULL,
2000 &creator_items, NULL);
2001 signature = cpu_to_le64(VHDX_FILE_SIGNATURE);
2002 ret = blk_pwrite(blk, VHDX_FILE_ID_OFFSET, &signature, sizeof(signature),
2004 if (ret < 0) {
2005 error_setg_errno(errp, -ret, "Failed to write file signature");
2006 goto delete_and_exit;
2008 if (creator) {
2009 ret = blk_pwrite(blk, VHDX_FILE_ID_OFFSET + sizeof(signature),
2010 creator, creator_items * sizeof(gunichar2), 0);
2011 if (ret < 0) {
2012 error_setg_errno(errp, -ret, "Failed to write creator field");
2013 goto delete_and_exit;
2018 /* Creates (B),(C) */
2019 ret = vhdx_create_new_headers(blk, image_size, log_size);
2020 if (ret < 0) {
2021 error_setg_errno(errp, -ret, "Failed to write image headers");
2022 goto delete_and_exit;
2025 /* Creates (D),(E),(G) explicitly. (F) created as by-product */
2026 ret = vhdx_create_new_region_table(blk, image_size, block_size, 512,
2027 log_size, use_zero_blocks, image_type,
2028 &metadata_offset, errp);
2029 if (ret < 0) {
2030 goto delete_and_exit;
2033 /* Creates (H) */
2034 ret = vhdx_create_new_metadata(blk, image_size, block_size, 512,
2035 metadata_offset, image_type);
2036 if (ret < 0) {
2037 error_setg_errno(errp, -ret, "Failed to initialize metadata");
2038 goto delete_and_exit;
2041 ret = 0;
2042 delete_and_exit:
2043 blk_unref(blk);
2044 bdrv_unref(bs);
2045 g_free(creator);
2046 return ret;
2049 static int coroutine_fn vhdx_co_create_opts(const char *filename,
2050 QemuOpts *opts,
2051 Error **errp)
2053 BlockdevCreateOptions *create_options = NULL;
2054 QDict *qdict;
2055 Visitor *v;
2056 BlockDriverState *bs = NULL;
2057 Error *local_err = NULL;
2058 int ret;
2060 static const QDictRenames opt_renames[] = {
2061 { VHDX_BLOCK_OPT_LOG_SIZE, "log-size" },
2062 { VHDX_BLOCK_OPT_BLOCK_SIZE, "block-size" },
2063 { VHDX_BLOCK_OPT_ZERO, "block-state-zero" },
2064 { NULL, NULL },
2067 /* Parse options and convert legacy syntax */
2068 qdict = qemu_opts_to_qdict_filtered(opts, NULL, &vhdx_create_opts, true);
2070 if (!qdict_rename_keys(qdict, opt_renames, errp)) {
2071 ret = -EINVAL;
2072 goto fail;
2075 /* Create and open the file (protocol layer) */
2076 ret = bdrv_create_file(filename, opts, &local_err);
2077 if (ret < 0) {
2078 error_propagate(errp, local_err);
2079 goto fail;
2082 bs = bdrv_open(filename, NULL, NULL,
2083 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
2084 if (bs == NULL) {
2085 ret = -EIO;
2086 goto fail;
2089 /* Now get the QAPI type BlockdevCreateOptions */
2090 qdict_put_str(qdict, "driver", "vhdx");
2091 qdict_put_str(qdict, "file", bs->node_name);
2093 v = qobject_input_visitor_new_flat_confused(qdict, errp);
2094 if (!v) {
2095 ret = -EINVAL;
2096 goto fail;
2099 visit_type_BlockdevCreateOptions(v, NULL, &create_options, &local_err);
2100 visit_free(v);
2102 if (local_err) {
2103 error_propagate(errp, local_err);
2104 ret = -EINVAL;
2105 goto fail;
2108 /* Silently round up sizes:
2109 * The image size is rounded to 512 bytes. Make the block and log size
2110 * close to what was specified, but must be at least 1MB, and a multiple of
2111 * 1 MB. Also respect VHDX_BLOCK_SIZE_MAX for block sizes. block_size = 0
2112 * means auto, which is represented by a missing key in QAPI. */
2113 assert(create_options->driver == BLOCKDEV_DRIVER_VHDX);
2114 create_options->u.vhdx.size =
2115 ROUND_UP(create_options->u.vhdx.size, BDRV_SECTOR_SIZE);
2117 if (create_options->u.vhdx.has_log_size) {
2118 create_options->u.vhdx.log_size =
2119 ROUND_UP(create_options->u.vhdx.log_size, MiB);
2121 if (create_options->u.vhdx.has_block_size) {
2122 create_options->u.vhdx.block_size =
2123 ROUND_UP(create_options->u.vhdx.block_size, MiB);
2125 if (create_options->u.vhdx.block_size == 0) {
2126 create_options->u.vhdx.has_block_size = false;
2128 if (create_options->u.vhdx.block_size > VHDX_BLOCK_SIZE_MAX) {
2129 create_options->u.vhdx.block_size = VHDX_BLOCK_SIZE_MAX;
2133 /* Create the vhdx image (format layer) */
2134 ret = vhdx_co_create(create_options, errp);
2136 fail:
2137 qobject_unref(qdict);
2138 bdrv_unref(bs);
2139 qapi_free_BlockdevCreateOptions(create_options);
2140 return ret;
2143 /* If opened r/w, the VHDX driver will automatically replay the log,
2144 * if one is present, inside the vhdx_open() call.
2146 * If qemu-img check -r all is called, the image is automatically opened
2147 * r/w and any log has already been replayed, so there is nothing (currently)
2148 * for us to do here
2150 static int coroutine_fn vhdx_co_check(BlockDriverState *bs,
2151 BdrvCheckResult *result,
2152 BdrvCheckMode fix)
2154 BDRVVHDXState *s = bs->opaque;
2156 if (s->log_replayed_on_open) {
2157 result->corruptions_fixed++;
2160 vhdx_check_bat_entries(bs, &result->corruptions);
2162 return 0;
2165 static int vhdx_has_zero_init(BlockDriverState *bs)
2167 BDRVVHDXState *s = bs->opaque;
2168 int state;
2171 * Check the subformat: Fixed images have all BAT entries present,
2172 * dynamic images have none (right after creation). It is
2173 * therefore enough to check the first BAT entry.
2175 if (!s->bat_entries) {
2176 return 1;
2179 state = s->bat[0] & VHDX_BAT_STATE_BIT_MASK;
2180 if (state == PAYLOAD_BLOCK_FULLY_PRESENT) {
2181 /* Fixed subformat */
2182 return bdrv_has_zero_init(bs->file->bs);
2185 /* Dynamic subformat */
2186 return 1;
2189 static QemuOptsList vhdx_create_opts = {
2190 .name = "vhdx-create-opts",
2191 .head = QTAILQ_HEAD_INITIALIZER(vhdx_create_opts.head),
2192 .desc = {
2194 .name = BLOCK_OPT_SIZE,
2195 .type = QEMU_OPT_SIZE,
2196 .help = "Virtual disk size; max of 64TB."
2199 .name = VHDX_BLOCK_OPT_LOG_SIZE,
2200 .type = QEMU_OPT_SIZE,
2201 .def_value_str = stringify(DEFAULT_LOG_SIZE),
2202 .help = "Log size; min 1MB."
2205 .name = VHDX_BLOCK_OPT_BLOCK_SIZE,
2206 .type = QEMU_OPT_SIZE,
2207 .def_value_str = stringify(0),
2208 .help = "Block Size; min 1MB, max 256MB. " \
2209 "0 means auto-calculate based on image size."
2212 .name = BLOCK_OPT_SUBFMT,
2213 .type = QEMU_OPT_STRING,
2214 .help = "VHDX format type, can be either 'dynamic' or 'fixed'. "\
2215 "Default is 'dynamic'."
2218 .name = VHDX_BLOCK_OPT_ZERO,
2219 .type = QEMU_OPT_BOOL,
2220 .help = "Force use of payload blocks of type 'ZERO'. "\
2221 "Non-standard, but default. Do not set to 'off' when "\
2222 "using 'qemu-img convert' with subformat=dynamic."
2224 { NULL }
2228 static BlockDriver bdrv_vhdx = {
2229 .format_name = "vhdx",
2230 .instance_size = sizeof(BDRVVHDXState),
2231 .bdrv_probe = vhdx_probe,
2232 .bdrv_open = vhdx_open,
2233 .bdrv_close = vhdx_close,
2234 .bdrv_reopen_prepare = vhdx_reopen_prepare,
2235 .bdrv_child_perm = bdrv_format_default_perms,
2236 .bdrv_co_readv = vhdx_co_readv,
2237 .bdrv_co_writev = vhdx_co_writev,
2238 .bdrv_co_create = vhdx_co_create,
2239 .bdrv_co_create_opts = vhdx_co_create_opts,
2240 .bdrv_get_info = vhdx_get_info,
2241 .bdrv_co_check = vhdx_co_check,
2242 .bdrv_has_zero_init = vhdx_has_zero_init,
2244 .create_opts = &vhdx_create_opts,
2247 static void bdrv_vhdx_init(void)
2249 bdrv_register(&bdrv_vhdx);
2252 block_init(bdrv_vhdx_init);