block: vhdx - change .vhdx_create default block state to ZERO
[qemu/ar7.git] / block / vhdx.c
blob46d504c96c1cb62f40eebf4468bcb7cacd36a566
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-common.h"
19 #include "block/block_int.h"
20 #include "qemu/module.h"
21 #include "qemu/crc32c.h"
22 #include "block/vhdx.h"
23 #include "migration/migration.h"
25 #include <uuid/uuid.h>
26 #include <glib.h>
28 /* Options for VHDX creation */
30 #define VHDX_BLOCK_OPT_LOG_SIZE "log_size"
31 #define VHDX_BLOCK_OPT_BLOCK_SIZE "block_size"
32 #define VHDX_BLOCK_OPT_ZERO "block_state_zero"
34 typedef enum VHDXImageType {
35 VHDX_TYPE_DYNAMIC = 0,
36 VHDX_TYPE_FIXED,
37 VHDX_TYPE_DIFFERENCING, /* Currently unsupported */
38 } VHDXImageType;
40 /* Several metadata and region table data entries are identified by
41 * guids in a MS-specific GUID format. */
44 /* ------- Known Region Table GUIDs ---------------------- */
45 static const MSGUID bat_guid = { .data1 = 0x2dc27766,
46 .data2 = 0xf623,
47 .data3 = 0x4200,
48 .data4 = { 0x9d, 0x64, 0x11, 0x5e,
49 0x9b, 0xfd, 0x4a, 0x08} };
51 static const MSGUID metadata_guid = { .data1 = 0x8b7ca206,
52 .data2 = 0x4790,
53 .data3 = 0x4b9a,
54 .data4 = { 0xb8, 0xfe, 0x57, 0x5f,
55 0x05, 0x0f, 0x88, 0x6e} };
59 /* ------- Known Metadata Entry GUIDs ---------------------- */
60 static const MSGUID file_param_guid = { .data1 = 0xcaa16737,
61 .data2 = 0xfa36,
62 .data3 = 0x4d43,
63 .data4 = { 0xb3, 0xb6, 0x33, 0xf0,
64 0xaa, 0x44, 0xe7, 0x6b} };
66 static const MSGUID virtual_size_guid = { .data1 = 0x2FA54224,
67 .data2 = 0xcd1b,
68 .data3 = 0x4876,
69 .data4 = { 0xb2, 0x11, 0x5d, 0xbe,
70 0xd8, 0x3b, 0xf4, 0xb8} };
72 static const MSGUID page83_guid = { .data1 = 0xbeca12ab,
73 .data2 = 0xb2e6,
74 .data3 = 0x4523,
75 .data4 = { 0x93, 0xef, 0xc3, 0x09,
76 0xe0, 0x00, 0xc7, 0x46} };
79 static const MSGUID phys_sector_guid = { .data1 = 0xcda348c7,
80 .data2 = 0x445d,
81 .data3 = 0x4471,
82 .data4 = { 0x9c, 0xc9, 0xe9, 0x88,
83 0x52, 0x51, 0xc5, 0x56} };
85 static const MSGUID parent_locator_guid = { .data1 = 0xa8d35f2d,
86 .data2 = 0xb30b,
87 .data3 = 0x454d,
88 .data4 = { 0xab, 0xf7, 0xd3,
89 0xd8, 0x48, 0x34,
90 0xab, 0x0c} };
92 static const MSGUID logical_sector_guid = { .data1 = 0x8141bf1d,
93 .data2 = 0xa96f,
94 .data3 = 0x4709,
95 .data4 = { 0xba, 0x47, 0xf2,
96 0x33, 0xa8, 0xfa,
97 0xab, 0x5f} };
99 /* Each parent type must have a valid GUID; this is for parent images
100 * of type 'VHDX'. If we were to allow e.g. a QCOW2 parent, we would
101 * need to make up our own QCOW2 GUID type */
102 static const MSGUID parent_vhdx_guid __attribute__((unused))
103 = { .data1 = 0xb04aefb7,
104 .data2 = 0xd19e,
105 .data3 = 0x4a81,
106 .data4 = { 0xb7, 0x89, 0x25, 0xb8,
107 0xe9, 0x44, 0x59, 0x13} };
110 #define META_FILE_PARAMETER_PRESENT 0x01
111 #define META_VIRTUAL_DISK_SIZE_PRESENT 0x02
112 #define META_PAGE_83_PRESENT 0x04
113 #define META_LOGICAL_SECTOR_SIZE_PRESENT 0x08
114 #define META_PHYS_SECTOR_SIZE_PRESENT 0x10
115 #define META_PARENT_LOCATOR_PRESENT 0x20
117 #define META_ALL_PRESENT \
118 (META_FILE_PARAMETER_PRESENT | META_VIRTUAL_DISK_SIZE_PRESENT | \
119 META_PAGE_83_PRESENT | META_LOGICAL_SECTOR_SIZE_PRESENT | \
120 META_PHYS_SECTOR_SIZE_PRESENT)
123 typedef struct VHDXSectorInfo {
124 uint32_t bat_idx; /* BAT entry index */
125 uint32_t sectors_avail; /* sectors available in payload block */
126 uint32_t bytes_left; /* bytes left in the block after data to r/w */
127 uint32_t bytes_avail; /* bytes available in payload block */
128 uint64_t file_offset; /* absolute offset in bytes, in file */
129 uint64_t block_offset; /* block offset, in bytes */
130 } VHDXSectorInfo;
132 /* Calculates new checksum.
134 * Zero is substituted during crc calculation for the original crc field
135 * crc_offset: byte offset in buf of the buffer crc
136 * buf: buffer pointer
137 * size: size of buffer (must be > crc_offset+4)
139 * Note: The buffer should have all multi-byte data in little-endian format,
140 * and the resulting checksum is in little endian format.
142 uint32_t vhdx_update_checksum(uint8_t *buf, size_t size, int crc_offset)
144 uint32_t crc;
146 assert(buf != NULL);
147 assert(size > (crc_offset + sizeof(crc)));
149 memset(buf + crc_offset, 0, sizeof(crc));
150 crc = crc32c(0xffffffff, buf, size);
151 cpu_to_le32s(&crc);
152 memcpy(buf + crc_offset, &crc, sizeof(crc));
154 return crc;
157 uint32_t vhdx_checksum_calc(uint32_t crc, uint8_t *buf, size_t size,
158 int crc_offset)
160 uint32_t crc_new;
161 uint32_t crc_orig;
162 assert(buf != NULL);
164 if (crc_offset > 0) {
165 memcpy(&crc_orig, buf + crc_offset, sizeof(crc_orig));
166 memset(buf + crc_offset, 0, sizeof(crc_orig));
169 crc_new = crc32c(crc, buf, size);
170 if (crc_offset > 0) {
171 memcpy(buf + crc_offset, &crc_orig, sizeof(crc_orig));
174 return crc_new;
177 /* Validates the checksum of the buffer, with an in-place CRC.
179 * Zero is substituted during crc calculation for the original crc field,
180 * and the crc field is restored afterwards. But the buffer will be modifed
181 * during the calculation, so this may not be not suitable for multi-threaded
182 * use.
184 * crc_offset: byte offset in buf of the buffer crc
185 * buf: buffer pointer
186 * size: size of buffer (must be > crc_offset+4)
188 * returns true if checksum is valid, false otherwise
190 bool vhdx_checksum_is_valid(uint8_t *buf, size_t size, int crc_offset)
192 uint32_t crc_orig;
193 uint32_t crc;
195 assert(buf != NULL);
196 assert(size > (crc_offset + 4));
198 memcpy(&crc_orig, buf + crc_offset, sizeof(crc_orig));
199 crc_orig = le32_to_cpu(crc_orig);
201 crc = vhdx_checksum_calc(0xffffffff, buf, size, crc_offset);
203 return crc == crc_orig;
208 * This generates a UUID that is compliant with the MS GUIDs used
209 * in the VHDX spec (and elsewhere).
211 void vhdx_guid_generate(MSGUID *guid)
213 uuid_t uuid;
214 assert(guid != NULL);
216 uuid_generate(uuid);
217 memcpy(guid, uuid, sizeof(MSGUID));
220 /* Check for region overlaps inside the VHDX image */
221 static int vhdx_region_check(BDRVVHDXState *s, uint64_t start, uint64_t length)
223 int ret = 0;
224 uint64_t end;
225 VHDXRegionEntry *r;
227 end = start + length;
228 QLIST_FOREACH(r, &s->regions, entries) {
229 if (!((start >= r->end) || (end <= r->start))) {
230 ret = -EINVAL;
231 goto exit;
235 exit:
236 return ret;
239 /* Register a region for future checks */
240 static void vhdx_region_register(BDRVVHDXState *s,
241 uint64_t start, uint64_t length)
243 VHDXRegionEntry *r;
245 r = g_malloc0(sizeof(*r));
247 r->start = start;
248 r->end = start + length;
250 QLIST_INSERT_HEAD(&s->regions, r, entries);
253 /* Free all registered regions */
254 static void vhdx_region_unregister_all(BDRVVHDXState *s)
256 VHDXRegionEntry *r, *r_next;
258 QLIST_FOREACH_SAFE(r, &s->regions, entries, r_next) {
259 QLIST_REMOVE(r, entries);
260 g_free(r);
264 static void vhdx_set_shift_bits(BDRVVHDXState *s)
266 s->logical_sector_size_bits = 31 - clz32(s->logical_sector_size);
267 s->sectors_per_block_bits = 31 - clz32(s->sectors_per_block);
268 s->chunk_ratio_bits = 63 - clz64(s->chunk_ratio);
269 s->block_size_bits = 31 - clz32(s->block_size);
273 * Per the MS VHDX Specification, for every VHDX file:
274 * - The header section is fixed size - 1 MB
275 * - The header section is always the first "object"
276 * - The first 64KB of the header is the File Identifier
277 * - The first uint64 (8 bytes) is the VHDX Signature ("vhdxfile")
278 * - The following 512 bytes constitute a UTF-16 string identifiying the
279 * software that created the file, and is optional and diagnostic only.
281 * Therefore, we probe by looking for the vhdxfile signature "vhdxfile"
283 static int vhdx_probe(const uint8_t *buf, int buf_size, const char *filename)
285 if (buf_size >= 8 && !memcmp(buf, "vhdxfile", 8)) {
286 return 100;
288 return 0;
292 * Writes the header to the specified offset.
294 * This will optionally read in buffer data from disk (otherwise zero-fill),
295 * and then update the header checksum. Header is converted to proper
296 * endianness before being written to the specified file offset
298 static int vhdx_write_header(BlockDriverState *bs_file, VHDXHeader *hdr,
299 uint64_t offset, bool read)
301 uint8_t *buffer = NULL;
302 int ret;
303 VHDXHeader *header_le;
305 assert(bs_file != NULL);
306 assert(hdr != NULL);
308 /* the header checksum is not over just the packed size of VHDXHeader,
309 * but rather over the entire 'reserved' range for the header, which is
310 * 4KB (VHDX_HEADER_SIZE). */
312 buffer = qemu_blockalign(bs_file, VHDX_HEADER_SIZE);
313 if (read) {
314 /* if true, we can't assume the extra reserved bytes are 0 */
315 ret = bdrv_pread(bs_file, offset, buffer, VHDX_HEADER_SIZE);
316 if (ret < 0) {
317 goto exit;
319 } else {
320 memset(buffer, 0, VHDX_HEADER_SIZE);
323 /* overwrite the actual VHDXHeader portion */
324 header_le = (VHDXHeader *)buffer;
325 memcpy(header_le, hdr, sizeof(VHDXHeader));
326 vhdx_header_le_export(hdr, header_le);
327 vhdx_update_checksum(buffer, VHDX_HEADER_SIZE,
328 offsetof(VHDXHeader, checksum));
329 ret = bdrv_pwrite_sync(bs_file, offset, header_le, sizeof(VHDXHeader));
331 exit:
332 qemu_vfree(buffer);
333 return ret;
336 /* Update the VHDX headers
338 * This follows the VHDX spec procedures for header updates.
340 * - non-current header is updated with largest sequence number
342 static int vhdx_update_header(BlockDriverState *bs, BDRVVHDXState *s,
343 bool generate_data_write_guid, MSGUID *log_guid)
345 int ret = 0;
346 int hdr_idx = 0;
347 uint64_t header_offset = VHDX_HEADER1_OFFSET;
349 VHDXHeader *active_header;
350 VHDXHeader *inactive_header;
352 /* operate on the non-current header */
353 if (s->curr_header == 0) {
354 hdr_idx = 1;
355 header_offset = VHDX_HEADER2_OFFSET;
358 active_header = s->headers[s->curr_header];
359 inactive_header = s->headers[hdr_idx];
361 inactive_header->sequence_number = active_header->sequence_number + 1;
363 /* a new file guid must be generated before any file write, including
364 * headers */
365 inactive_header->file_write_guid = s->session_guid;
367 /* a new data guid only needs to be generated before any guest-visible
368 * writes (i.e. something observable via virtual disk read) */
369 if (generate_data_write_guid) {
370 vhdx_guid_generate(&inactive_header->data_write_guid);
373 /* update the log guid if present */
374 if (log_guid) {
375 inactive_header->log_guid = *log_guid;
378 ret = vhdx_write_header(bs->file, inactive_header, header_offset, true);
379 if (ret < 0) {
380 goto exit;
382 s->curr_header = hdr_idx;
384 exit:
385 return ret;
389 * The VHDX spec calls for header updates to be performed twice, so that both
390 * the current and non-current header have valid info
392 int vhdx_update_headers(BlockDriverState *bs, BDRVVHDXState *s,
393 bool generate_data_write_guid, MSGUID *log_guid)
395 int ret;
397 ret = vhdx_update_header(bs, s, generate_data_write_guid, log_guid);
398 if (ret < 0) {
399 return ret;
401 ret = vhdx_update_header(bs, s, generate_data_write_guid, log_guid);
402 return ret;
405 /* opens the specified header block from the VHDX file header section */
406 static void vhdx_parse_header(BlockDriverState *bs, BDRVVHDXState *s,
407 Error **errp)
409 int ret;
410 VHDXHeader *header1;
411 VHDXHeader *header2;
412 bool h1_valid = false;
413 bool h2_valid = false;
414 uint64_t h1_seq = 0;
415 uint64_t h2_seq = 0;
416 uint8_t *buffer;
418 /* header1 & header2 are freed in vhdx_close() */
419 header1 = qemu_blockalign(bs, sizeof(VHDXHeader));
420 header2 = qemu_blockalign(bs, sizeof(VHDXHeader));
422 buffer = qemu_blockalign(bs, VHDX_HEADER_SIZE);
424 s->headers[0] = header1;
425 s->headers[1] = header2;
427 /* We have to read the whole VHDX_HEADER_SIZE instead of
428 * sizeof(VHDXHeader), because the checksum is over the whole
429 * region */
430 ret = bdrv_pread(bs->file, VHDX_HEADER1_OFFSET, buffer, VHDX_HEADER_SIZE);
431 if (ret < 0) {
432 goto fail;
434 /* copy over just the relevant portion that we need */
435 memcpy(header1, buffer, sizeof(VHDXHeader));
437 if (vhdx_checksum_is_valid(buffer, VHDX_HEADER_SIZE, 4)) {
438 vhdx_header_le_import(header1);
439 if (header1->signature == VHDX_HEADER_SIGNATURE &&
440 header1->version == 1) {
441 h1_seq = header1->sequence_number;
442 h1_valid = true;
446 ret = bdrv_pread(bs->file, VHDX_HEADER2_OFFSET, buffer, VHDX_HEADER_SIZE);
447 if (ret < 0) {
448 goto fail;
450 /* copy over just the relevant portion that we need */
451 memcpy(header2, buffer, sizeof(VHDXHeader));
453 if (vhdx_checksum_is_valid(buffer, VHDX_HEADER_SIZE, 4)) {
454 vhdx_header_le_import(header2);
455 if (header2->signature == VHDX_HEADER_SIGNATURE &&
456 header2->version == 1) {
457 h2_seq = header2->sequence_number;
458 h2_valid = true;
462 /* If there is only 1 valid header (or no valid headers), we
463 * don't care what the sequence numbers are */
464 if (h1_valid && !h2_valid) {
465 s->curr_header = 0;
466 } else if (!h1_valid && h2_valid) {
467 s->curr_header = 1;
468 } else if (!h1_valid && !h2_valid) {
469 goto fail;
470 } else {
471 /* If both headers are valid, then we choose the active one by the
472 * highest sequence number. If the sequence numbers are equal, that is
473 * invalid */
474 if (h1_seq > h2_seq) {
475 s->curr_header = 0;
476 } else if (h2_seq > h1_seq) {
477 s->curr_header = 1;
478 } else {
479 /* The Microsoft Disk2VHD tool will create 2 identical
480 * headers, with identical sequence numbers. If the headers are
481 * identical, don't consider the file corrupt */
482 if (!memcmp(header1, header2, sizeof(VHDXHeader))) {
483 s->curr_header = 0;
484 } else {
485 goto fail;
490 vhdx_region_register(s, s->headers[s->curr_header]->log_offset,
491 s->headers[s->curr_header]->log_length);
492 goto exit;
494 fail:
495 error_setg_errno(errp, -ret, "No valid VHDX header found");
496 qemu_vfree(header1);
497 qemu_vfree(header2);
498 s->headers[0] = NULL;
499 s->headers[1] = NULL;
500 exit:
501 qemu_vfree(buffer);
505 static int vhdx_open_region_tables(BlockDriverState *bs, BDRVVHDXState *s)
507 int ret = 0;
508 uint8_t *buffer;
509 int offset = 0;
510 VHDXRegionTableEntry rt_entry;
511 uint32_t i;
512 bool bat_rt_found = false;
513 bool metadata_rt_found = false;
515 /* We have to read the whole 64KB block, because the crc32 is over the
516 * whole block */
517 buffer = qemu_blockalign(bs, VHDX_HEADER_BLOCK_SIZE);
519 ret = bdrv_pread(bs->file, VHDX_REGION_TABLE_OFFSET, buffer,
520 VHDX_HEADER_BLOCK_SIZE);
521 if (ret < 0) {
522 goto fail;
524 memcpy(&s->rt, buffer, sizeof(s->rt));
525 offset += sizeof(s->rt);
527 if (!vhdx_checksum_is_valid(buffer, VHDX_HEADER_BLOCK_SIZE, 4)) {
528 ret = -EINVAL;
529 goto fail;
532 vhdx_region_header_le_import(&s->rt);
534 if (s->rt.signature != VHDX_REGION_SIGNATURE) {
535 ret = -EINVAL;
536 goto fail;
540 /* Per spec, maximum region table entry count is 2047 */
541 if (s->rt.entry_count > 2047) {
542 ret = -EINVAL;
543 goto fail;
546 for (i = 0; i < s->rt.entry_count; i++) {
547 memcpy(&rt_entry, buffer + offset, sizeof(rt_entry));
548 offset += sizeof(rt_entry);
550 vhdx_region_entry_le_import(&rt_entry);
552 /* check for region overlap between these entries, and any
553 * other memory regions in the file */
554 ret = vhdx_region_check(s, rt_entry.file_offset, rt_entry.length);
555 if (ret < 0) {
556 goto fail;
559 vhdx_region_register(s, rt_entry.file_offset, rt_entry.length);
561 /* see if we recognize the entry */
562 if (guid_eq(rt_entry.guid, bat_guid)) {
563 /* must be unique; if we have already found it this is invalid */
564 if (bat_rt_found) {
565 ret = -EINVAL;
566 goto fail;
568 bat_rt_found = true;
569 s->bat_rt = rt_entry;
570 continue;
573 if (guid_eq(rt_entry.guid, metadata_guid)) {
574 /* must be unique; if we have already found it this is invalid */
575 if (metadata_rt_found) {
576 ret = -EINVAL;
577 goto fail;
579 metadata_rt_found = true;
580 s->metadata_rt = rt_entry;
581 continue;
584 if (rt_entry.data_bits & VHDX_REGION_ENTRY_REQUIRED) {
585 /* cannot read vhdx file - required region table entry that
586 * we do not understand. per spec, we must fail to open */
587 ret = -ENOTSUP;
588 goto fail;
592 if (!bat_rt_found || !metadata_rt_found) {
593 ret = -EINVAL;
594 goto fail;
597 ret = 0;
599 fail:
600 qemu_vfree(buffer);
601 return ret;
606 /* Metadata initial parser
608 * This loads all the metadata entry fields. This may cause additional
609 * fields to be processed (e.g. parent locator, etc..).
611 * There are 5 Metadata items that are always required:
612 * - File Parameters (block size, has a parent)
613 * - Virtual Disk Size (size, in bytes, of the virtual drive)
614 * - Page 83 Data (scsi page 83 guid)
615 * - Logical Sector Size (logical sector size in bytes, either 512 or
616 * 4096. We only support 512 currently)
617 * - Physical Sector Size (512 or 4096)
619 * Also, if the File Parameters indicate this is a differencing file,
620 * we must also look for the Parent Locator metadata item.
622 static int vhdx_parse_metadata(BlockDriverState *bs, BDRVVHDXState *s)
624 int ret = 0;
625 uint8_t *buffer;
626 int offset = 0;
627 uint32_t i = 0;
628 VHDXMetadataTableEntry md_entry;
630 buffer = qemu_blockalign(bs, VHDX_METADATA_TABLE_MAX_SIZE);
632 ret = bdrv_pread(bs->file, s->metadata_rt.file_offset, buffer,
633 VHDX_METADATA_TABLE_MAX_SIZE);
634 if (ret < 0) {
635 goto exit;
637 memcpy(&s->metadata_hdr, buffer, sizeof(s->metadata_hdr));
638 offset += sizeof(s->metadata_hdr);
640 vhdx_metadata_header_le_import(&s->metadata_hdr);
642 if (s->metadata_hdr.signature != VHDX_METADATA_SIGNATURE) {
643 ret = -EINVAL;
644 goto exit;
647 s->metadata_entries.present = 0;
649 if ((s->metadata_hdr.entry_count * sizeof(md_entry)) >
650 (VHDX_METADATA_TABLE_MAX_SIZE - offset)) {
651 ret = -EINVAL;
652 goto exit;
655 for (i = 0; i < s->metadata_hdr.entry_count; i++) {
656 memcpy(&md_entry, buffer + offset, sizeof(md_entry));
657 offset += sizeof(md_entry);
659 vhdx_metadata_entry_le_import(&md_entry);
661 if (guid_eq(md_entry.item_id, file_param_guid)) {
662 if (s->metadata_entries.present & META_FILE_PARAMETER_PRESENT) {
663 ret = -EINVAL;
664 goto exit;
666 s->metadata_entries.file_parameters_entry = md_entry;
667 s->metadata_entries.present |= META_FILE_PARAMETER_PRESENT;
668 continue;
671 if (guid_eq(md_entry.item_id, virtual_size_guid)) {
672 if (s->metadata_entries.present & META_VIRTUAL_DISK_SIZE_PRESENT) {
673 ret = -EINVAL;
674 goto exit;
676 s->metadata_entries.virtual_disk_size_entry = md_entry;
677 s->metadata_entries.present |= META_VIRTUAL_DISK_SIZE_PRESENT;
678 continue;
681 if (guid_eq(md_entry.item_id, page83_guid)) {
682 if (s->metadata_entries.present & META_PAGE_83_PRESENT) {
683 ret = -EINVAL;
684 goto exit;
686 s->metadata_entries.page83_data_entry = md_entry;
687 s->metadata_entries.present |= META_PAGE_83_PRESENT;
688 continue;
691 if (guid_eq(md_entry.item_id, logical_sector_guid)) {
692 if (s->metadata_entries.present &
693 META_LOGICAL_SECTOR_SIZE_PRESENT) {
694 ret = -EINVAL;
695 goto exit;
697 s->metadata_entries.logical_sector_size_entry = md_entry;
698 s->metadata_entries.present |= META_LOGICAL_SECTOR_SIZE_PRESENT;
699 continue;
702 if (guid_eq(md_entry.item_id, phys_sector_guid)) {
703 if (s->metadata_entries.present & META_PHYS_SECTOR_SIZE_PRESENT) {
704 ret = -EINVAL;
705 goto exit;
707 s->metadata_entries.phys_sector_size_entry = md_entry;
708 s->metadata_entries.present |= META_PHYS_SECTOR_SIZE_PRESENT;
709 continue;
712 if (guid_eq(md_entry.item_id, parent_locator_guid)) {
713 if (s->metadata_entries.present & META_PARENT_LOCATOR_PRESENT) {
714 ret = -EINVAL;
715 goto exit;
717 s->metadata_entries.parent_locator_entry = md_entry;
718 s->metadata_entries.present |= META_PARENT_LOCATOR_PRESENT;
719 continue;
722 if (md_entry.data_bits & VHDX_META_FLAGS_IS_REQUIRED) {
723 /* cannot read vhdx file - required region table entry that
724 * we do not understand. per spec, we must fail to open */
725 ret = -ENOTSUP;
726 goto exit;
730 if (s->metadata_entries.present != META_ALL_PRESENT) {
731 ret = -ENOTSUP;
732 goto exit;
735 ret = bdrv_pread(bs->file,
736 s->metadata_entries.file_parameters_entry.offset
737 + s->metadata_rt.file_offset,
738 &s->params,
739 sizeof(s->params));
741 if (ret < 0) {
742 goto exit;
745 le32_to_cpus(&s->params.block_size);
746 le32_to_cpus(&s->params.data_bits);
749 /* We now have the file parameters, so we can tell if this is a
750 * differencing file (i.e.. has_parent), is dynamic or fixed
751 * sized (leave_blocks_allocated), and the block size */
753 /* The parent locator required iff the file parameters has_parent set */
754 if (s->params.data_bits & VHDX_PARAMS_HAS_PARENT) {
755 if (s->metadata_entries.present & META_PARENT_LOCATOR_PRESENT) {
756 /* TODO: parse parent locator fields */
757 ret = -ENOTSUP; /* temp, until differencing files are supported */
758 goto exit;
759 } else {
760 /* if has_parent is set, but there is not parent locator present,
761 * then that is an invalid combination */
762 ret = -EINVAL;
763 goto exit;
767 /* determine virtual disk size, logical sector size,
768 * and phys sector size */
770 ret = bdrv_pread(bs->file,
771 s->metadata_entries.virtual_disk_size_entry.offset
772 + s->metadata_rt.file_offset,
773 &s->virtual_disk_size,
774 sizeof(uint64_t));
775 if (ret < 0) {
776 goto exit;
778 ret = bdrv_pread(bs->file,
779 s->metadata_entries.logical_sector_size_entry.offset
780 + s->metadata_rt.file_offset,
781 &s->logical_sector_size,
782 sizeof(uint32_t));
783 if (ret < 0) {
784 goto exit;
786 ret = bdrv_pread(bs->file,
787 s->metadata_entries.phys_sector_size_entry.offset
788 + s->metadata_rt.file_offset,
789 &s->physical_sector_size,
790 sizeof(uint32_t));
791 if (ret < 0) {
792 goto exit;
795 le64_to_cpus(&s->virtual_disk_size);
796 le32_to_cpus(&s->logical_sector_size);
797 le32_to_cpus(&s->physical_sector_size);
799 if (s->params.block_size < VHDX_BLOCK_SIZE_MIN ||
800 s->params.block_size > VHDX_BLOCK_SIZE_MAX) {
801 ret = -EINVAL;
802 goto exit;
805 /* only 2 supported sector sizes */
806 if (s->logical_sector_size != 512 && s->logical_sector_size != 4096) {
807 ret = -EINVAL;
808 goto exit;
811 /* Both block_size and sector_size are guaranteed powers of 2, below.
812 Due to range checks above, s->sectors_per_block can never be < 256 */
813 s->sectors_per_block = s->params.block_size / s->logical_sector_size;
814 s->chunk_ratio = (VHDX_MAX_SECTORS_PER_BLOCK) *
815 (uint64_t)s->logical_sector_size /
816 (uint64_t)s->params.block_size;
818 /* These values are ones we will want to use for division / multiplication
819 * later on, and they are all guaranteed (per the spec) to be powers of 2,
820 * so we can take advantage of that for shift operations during
821 * reads/writes */
822 if (s->logical_sector_size & (s->logical_sector_size - 1)) {
823 ret = -EINVAL;
824 goto exit;
826 if (s->sectors_per_block & (s->sectors_per_block - 1)) {
827 ret = -EINVAL;
828 goto exit;
830 if (s->chunk_ratio & (s->chunk_ratio - 1)) {
831 ret = -EINVAL;
832 goto exit;
834 s->block_size = s->params.block_size;
835 if (s->block_size & (s->block_size - 1)) {
836 ret = -EINVAL;
837 goto exit;
840 vhdx_set_shift_bits(s);
842 ret = 0;
844 exit:
845 qemu_vfree(buffer);
846 return ret;
850 * Calculate the number of BAT entries, including sector
851 * bitmap entries.
853 static void vhdx_calc_bat_entries(BDRVVHDXState *s)
855 uint32_t data_blocks_cnt, bitmap_blocks_cnt;
857 data_blocks_cnt = s->virtual_disk_size >> s->block_size_bits;
858 if (s->virtual_disk_size - (data_blocks_cnt << s->block_size_bits)) {
859 data_blocks_cnt++;
861 bitmap_blocks_cnt = data_blocks_cnt >> s->chunk_ratio_bits;
862 if (data_blocks_cnt - (bitmap_blocks_cnt << s->chunk_ratio_bits)) {
863 bitmap_blocks_cnt++;
866 if (s->parent_entries) {
867 s->bat_entries = bitmap_blocks_cnt * (s->chunk_ratio + 1);
868 } else {
869 s->bat_entries = data_blocks_cnt +
870 ((data_blocks_cnt - 1) >> s->chunk_ratio_bits);
875 static void vhdx_close(BlockDriverState *bs)
877 BDRVVHDXState *s = bs->opaque;
878 qemu_vfree(s->headers[0]);
879 s->headers[0] = NULL;
880 qemu_vfree(s->headers[1]);
881 s->headers[1] = NULL;
882 qemu_vfree(s->bat);
883 s->bat = NULL;
884 qemu_vfree(s->parent_entries);
885 s->parent_entries = NULL;
886 migrate_del_blocker(s->migration_blocker);
887 error_free(s->migration_blocker);
888 qemu_vfree(s->log.hdr);
889 s->log.hdr = NULL;
890 vhdx_region_unregister_all(s);
893 static int vhdx_open(BlockDriverState *bs, QDict *options, int flags,
894 Error **errp)
896 BDRVVHDXState *s = bs->opaque;
897 int ret = 0;
898 uint32_t i;
899 uint64_t signature;
900 Error *local_err = NULL;
902 s->bat = NULL;
903 s->first_visible_write = true;
905 qemu_co_mutex_init(&s->lock);
906 QLIST_INIT(&s->regions);
908 /* validate the file signature */
909 ret = bdrv_pread(bs->file, 0, &signature, sizeof(uint64_t));
910 if (ret < 0) {
911 goto fail;
913 if (memcmp(&signature, "vhdxfile", 8)) {
914 ret = -EINVAL;
915 goto fail;
918 /* This is used for any header updates, for the file_write_guid.
919 * The spec dictates that a new value should be used for the first
920 * header update */
921 vhdx_guid_generate(&s->session_guid);
923 vhdx_parse_header(bs, s, &local_err);
924 if (local_err != NULL) {
925 error_propagate(errp, local_err);
926 ret = -EINVAL;
927 goto fail;
930 ret = vhdx_parse_log(bs, s, &s->log_replayed_on_open, errp);
931 if (ret < 0) {
932 goto fail;
935 ret = vhdx_open_region_tables(bs, s);
936 if (ret < 0) {
937 goto fail;
940 ret = vhdx_parse_metadata(bs, s);
941 if (ret < 0) {
942 goto fail;
945 s->block_size = s->params.block_size;
947 /* the VHDX spec dictates that virtual_disk_size is always a multiple of
948 * logical_sector_size */
949 bs->total_sectors = s->virtual_disk_size >> s->logical_sector_size_bits;
951 vhdx_calc_bat_entries(s);
953 s->bat_offset = s->bat_rt.file_offset;
955 if (s->bat_entries > s->bat_rt.length / sizeof(VHDXBatEntry)) {
956 /* BAT allocation is not large enough for all entries */
957 ret = -EINVAL;
958 goto fail;
961 /* s->bat is freed in vhdx_close() */
962 s->bat = qemu_try_blockalign(bs->file, s->bat_rt.length);
963 if (s->bat == NULL) {
964 ret = -ENOMEM;
965 goto fail;
968 ret = bdrv_pread(bs->file, s->bat_offset, s->bat, s->bat_rt.length);
969 if (ret < 0) {
970 goto fail;
973 uint64_t payblocks = s->chunk_ratio;
974 /* endian convert, and verify populated BAT field file offsets against
975 * region table and log entries */
976 for (i = 0; i < s->bat_entries; i++) {
977 le64_to_cpus(&s->bat[i]);
978 if (payblocks--) {
979 /* payload bat entries */
980 if ((s->bat[i] & VHDX_BAT_STATE_BIT_MASK) ==
981 PAYLOAD_BLOCK_FULLY_PRESENT) {
982 ret = vhdx_region_check(s, s->bat[i] & VHDX_BAT_FILE_OFF_MASK,
983 s->block_size);
984 if (ret < 0) {
985 goto fail;
988 } else {
989 payblocks = s->chunk_ratio;
990 /* Once differencing files are supported, verify sector bitmap
991 * blocks here */
995 if (flags & BDRV_O_RDWR) {
996 ret = vhdx_update_headers(bs, s, false, NULL);
997 if (ret < 0) {
998 goto fail;
1002 /* TODO: differencing files */
1004 /* Disable migration when VHDX images are used */
1005 error_set(&s->migration_blocker,
1006 QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1007 "vhdx", bdrv_get_device_name(bs), "live migration");
1008 migrate_add_blocker(s->migration_blocker);
1010 return 0;
1011 fail:
1012 vhdx_close(bs);
1013 return ret;
1016 static int vhdx_reopen_prepare(BDRVReopenState *state,
1017 BlockReopenQueue *queue, Error **errp)
1019 return 0;
1024 * Perform sector to block offset translations, to get various
1025 * sector and file offsets into the image. See VHDXSectorInfo
1027 static void vhdx_block_translate(BDRVVHDXState *s, int64_t sector_num,
1028 int nb_sectors, VHDXSectorInfo *sinfo)
1030 uint32_t block_offset;
1032 sinfo->bat_idx = sector_num >> s->sectors_per_block_bits;
1033 /* effectively a modulo - this gives us the offset into the block
1034 * (in sector sizes) for our sector number */
1035 block_offset = sector_num - (sinfo->bat_idx << s->sectors_per_block_bits);
1036 /* the chunk ratio gives us the interleaving of the sector
1037 * bitmaps, so we need to advance our page block index by the
1038 * sector bitmaps entry number */
1039 sinfo->bat_idx += sinfo->bat_idx >> s->chunk_ratio_bits;
1041 /* the number of sectors we can read/write in this cycle */
1042 sinfo->sectors_avail = s->sectors_per_block - block_offset;
1044 sinfo->bytes_left = sinfo->sectors_avail << s->logical_sector_size_bits;
1046 if (sinfo->sectors_avail > nb_sectors) {
1047 sinfo->sectors_avail = nb_sectors;
1050 sinfo->bytes_avail = sinfo->sectors_avail << s->logical_sector_size_bits;
1052 sinfo->file_offset = s->bat[sinfo->bat_idx] & VHDX_BAT_FILE_OFF_MASK;
1054 sinfo->block_offset = block_offset << s->logical_sector_size_bits;
1056 /* The file offset must be past the header section, so must be > 0 */
1057 if (sinfo->file_offset == 0) {
1058 return;
1061 /* block offset is the offset in vhdx logical sectors, in
1062 * the payload data block. Convert that to a byte offset
1063 * in the block, and add in the payload data block offset
1064 * in the file, in bytes, to get the final read address */
1066 sinfo->file_offset += sinfo->block_offset;
1070 static int vhdx_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1072 BDRVVHDXState *s = bs->opaque;
1074 bdi->cluster_size = s->block_size;
1076 bdi->unallocated_blocks_are_zero =
1077 (s->params.data_bits & VHDX_PARAMS_HAS_PARENT) == 0;
1079 return 0;
1083 static coroutine_fn int vhdx_co_readv(BlockDriverState *bs, int64_t sector_num,
1084 int nb_sectors, QEMUIOVector *qiov)
1086 BDRVVHDXState *s = bs->opaque;
1087 int ret = 0;
1088 VHDXSectorInfo sinfo;
1089 uint64_t bytes_done = 0;
1090 QEMUIOVector hd_qiov;
1092 qemu_iovec_init(&hd_qiov, qiov->niov);
1094 qemu_co_mutex_lock(&s->lock);
1096 while (nb_sectors > 0) {
1097 /* We are a differencing file, so we need to inspect the sector bitmap
1098 * to see if we have the data or not */
1099 if (s->params.data_bits & VHDX_PARAMS_HAS_PARENT) {
1100 /* not supported yet */
1101 ret = -ENOTSUP;
1102 goto exit;
1103 } else {
1104 vhdx_block_translate(s, sector_num, nb_sectors, &sinfo);
1106 qemu_iovec_reset(&hd_qiov);
1107 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, sinfo.bytes_avail);
1109 /* check the payload block state */
1110 switch (s->bat[sinfo.bat_idx] & VHDX_BAT_STATE_BIT_MASK) {
1111 case PAYLOAD_BLOCK_NOT_PRESENT: /* fall through */
1112 case PAYLOAD_BLOCK_UNDEFINED:
1113 case PAYLOAD_BLOCK_UNMAPPED:
1114 case PAYLOAD_BLOCK_UNMAPPED_v095:
1115 case PAYLOAD_BLOCK_ZERO:
1116 /* return zero */
1117 qemu_iovec_memset(&hd_qiov, 0, 0, sinfo.bytes_avail);
1118 break;
1119 case PAYLOAD_BLOCK_FULLY_PRESENT:
1120 qemu_co_mutex_unlock(&s->lock);
1121 ret = bdrv_co_readv(bs->file,
1122 sinfo.file_offset >> BDRV_SECTOR_BITS,
1123 sinfo.sectors_avail, &hd_qiov);
1124 qemu_co_mutex_lock(&s->lock);
1125 if (ret < 0) {
1126 goto exit;
1128 break;
1129 case PAYLOAD_BLOCK_PARTIALLY_PRESENT:
1130 /* we don't yet support difference files, fall through
1131 * to error */
1132 default:
1133 ret = -EIO;
1134 goto exit;
1135 break;
1137 nb_sectors -= sinfo.sectors_avail;
1138 sector_num += sinfo.sectors_avail;
1139 bytes_done += sinfo.bytes_avail;
1142 ret = 0;
1143 exit:
1144 qemu_co_mutex_unlock(&s->lock);
1145 qemu_iovec_destroy(&hd_qiov);
1146 return ret;
1150 * Allocate a new payload block at the end of the file.
1152 * Allocation will happen at 1MB alignment inside the file
1154 * Returns the file offset start of the new payload block
1156 static int vhdx_allocate_block(BlockDriverState *bs, BDRVVHDXState *s,
1157 uint64_t *new_offset)
1159 *new_offset = bdrv_getlength(bs->file);
1161 /* per the spec, the address for a block is in units of 1MB */
1162 *new_offset = ROUND_UP(*new_offset, 1024 * 1024);
1164 return bdrv_truncate(bs->file, *new_offset + s->block_size);
1168 * Update the BAT table entry with the new file offset, and the new entry
1169 * state */
1170 static void vhdx_update_bat_table_entry(BlockDriverState *bs, BDRVVHDXState *s,
1171 VHDXSectorInfo *sinfo,
1172 uint64_t *bat_entry_le,
1173 uint64_t *bat_offset, int state)
1175 /* The BAT entry is a uint64, with 44 bits for the file offset in units of
1176 * 1MB, and 3 bits for the block state. */
1177 s->bat[sinfo->bat_idx] = sinfo->file_offset;
1179 s->bat[sinfo->bat_idx] |= state & VHDX_BAT_STATE_BIT_MASK;
1181 *bat_entry_le = cpu_to_le64(s->bat[sinfo->bat_idx]);
1182 *bat_offset = s->bat_offset + sinfo->bat_idx * sizeof(VHDXBatEntry);
1186 /* Per the spec, on the first write of guest-visible data to the file the
1187 * data write guid must be updated in the header */
1188 int vhdx_user_visible_write(BlockDriverState *bs, BDRVVHDXState *s)
1190 int ret = 0;
1191 if (s->first_visible_write) {
1192 s->first_visible_write = false;
1193 ret = vhdx_update_headers(bs, s, true, NULL);
1195 return ret;
1198 static coroutine_fn int vhdx_co_writev(BlockDriverState *bs, int64_t sector_num,
1199 int nb_sectors, QEMUIOVector *qiov)
1201 int ret = -ENOTSUP;
1202 BDRVVHDXState *s = bs->opaque;
1203 VHDXSectorInfo sinfo;
1204 uint64_t bytes_done = 0;
1205 uint64_t bat_entry = 0;
1206 uint64_t bat_entry_offset = 0;
1207 QEMUIOVector hd_qiov;
1208 struct iovec iov1 = { 0 };
1209 struct iovec iov2 = { 0 };
1210 int sectors_to_write;
1211 int bat_state;
1212 uint64_t bat_prior_offset = 0;
1213 bool bat_update = false;
1215 qemu_iovec_init(&hd_qiov, qiov->niov);
1217 qemu_co_mutex_lock(&s->lock);
1219 ret = vhdx_user_visible_write(bs, s);
1220 if (ret < 0) {
1221 goto exit;
1224 while (nb_sectors > 0) {
1225 bool use_zero_buffers = false;
1226 bat_update = false;
1227 if (s->params.data_bits & VHDX_PARAMS_HAS_PARENT) {
1228 /* not supported yet */
1229 ret = -ENOTSUP;
1230 goto exit;
1231 } else {
1232 vhdx_block_translate(s, sector_num, nb_sectors, &sinfo);
1233 sectors_to_write = sinfo.sectors_avail;
1235 qemu_iovec_reset(&hd_qiov);
1236 /* check the payload block state */
1237 bat_state = s->bat[sinfo.bat_idx] & VHDX_BAT_STATE_BIT_MASK;
1238 switch (bat_state) {
1239 case PAYLOAD_BLOCK_ZERO:
1240 /* in this case, we need to preserve zero writes for
1241 * data that is not part of this write, so we must pad
1242 * the rest of the buffer to zeroes */
1244 /* if we are on a posix system with ftruncate() that extends
1245 * a file, then it is zero-filled for us. On Win32, the raw
1246 * layer uses SetFilePointer and SetFileEnd, which does not
1247 * zero fill AFAIK */
1249 /* Queue another write of zero buffers if the underlying file
1250 * does not zero-fill on file extension */
1252 if (bdrv_has_zero_init(bs->file) == 0) {
1253 use_zero_buffers = true;
1255 /* zero fill the front, if any */
1256 if (sinfo.block_offset) {
1257 iov1.iov_len = sinfo.block_offset;
1258 iov1.iov_base = qemu_blockalign(bs, iov1.iov_len);
1259 memset(iov1.iov_base, 0, iov1.iov_len);
1260 qemu_iovec_concat_iov(&hd_qiov, &iov1, 1, 0,
1261 sinfo.block_offset);
1262 sectors_to_write += iov1.iov_len >> BDRV_SECTOR_BITS;
1265 /* our actual data */
1266 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1267 sinfo.bytes_avail);
1269 /* zero fill the back, if any */
1270 if ((sinfo.bytes_avail - sinfo.block_offset) <
1271 s->block_size) {
1272 iov2.iov_len = s->block_size -
1273 (sinfo.bytes_avail + sinfo.block_offset);
1274 iov2.iov_base = qemu_blockalign(bs, iov2.iov_len);
1275 memset(iov2.iov_base, 0, iov2.iov_len);
1276 qemu_iovec_concat_iov(&hd_qiov, &iov2, 1, 0,
1277 sinfo.block_offset);
1278 sectors_to_write += iov2.iov_len >> BDRV_SECTOR_BITS;
1281 /* fall through */
1282 case PAYLOAD_BLOCK_NOT_PRESENT: /* fall through */
1283 case PAYLOAD_BLOCK_UNMAPPED:
1284 case PAYLOAD_BLOCK_UNMAPPED_v095:
1285 case PAYLOAD_BLOCK_UNDEFINED:
1286 bat_prior_offset = sinfo.file_offset;
1287 ret = vhdx_allocate_block(bs, s, &sinfo.file_offset);
1288 if (ret < 0) {
1289 goto exit;
1291 /* once we support differencing files, this may also be
1292 * partially present */
1293 /* update block state to the newly specified state */
1294 vhdx_update_bat_table_entry(bs, s, &sinfo, &bat_entry,
1295 &bat_entry_offset,
1296 PAYLOAD_BLOCK_FULLY_PRESENT);
1297 bat_update = true;
1298 /* since we just allocated a block, file_offset is the
1299 * beginning of the payload block. It needs to be the
1300 * write address, which includes the offset into the block */
1301 if (!use_zero_buffers) {
1302 sinfo.file_offset += sinfo.block_offset;
1304 /* fall through */
1305 case PAYLOAD_BLOCK_FULLY_PRESENT:
1306 /* if the file offset address is in the header zone,
1307 * there is a problem */
1308 if (sinfo.file_offset < (1024 * 1024)) {
1309 ret = -EFAULT;
1310 goto error_bat_restore;
1313 if (!use_zero_buffers) {
1314 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1315 sinfo.bytes_avail);
1317 /* block exists, so we can just overwrite it */
1318 qemu_co_mutex_unlock(&s->lock);
1319 ret = bdrv_co_writev(bs->file,
1320 sinfo.file_offset >> BDRV_SECTOR_BITS,
1321 sectors_to_write, &hd_qiov);
1322 qemu_co_mutex_lock(&s->lock);
1323 if (ret < 0) {
1324 goto error_bat_restore;
1326 break;
1327 case PAYLOAD_BLOCK_PARTIALLY_PRESENT:
1328 /* we don't yet support difference files, fall through
1329 * to error */
1330 default:
1331 ret = -EIO;
1332 goto exit;
1333 break;
1336 if (bat_update) {
1337 /* this will update the BAT entry into the log journal, and
1338 * then flush the log journal out to disk */
1339 ret = vhdx_log_write_and_flush(bs, s, &bat_entry,
1340 sizeof(VHDXBatEntry),
1341 bat_entry_offset);
1342 if (ret < 0) {
1343 goto exit;
1347 nb_sectors -= sinfo.sectors_avail;
1348 sector_num += sinfo.sectors_avail;
1349 bytes_done += sinfo.bytes_avail;
1354 goto exit;
1356 error_bat_restore:
1357 if (bat_update) {
1358 /* keep metadata in sync, and restore the bat entry state
1359 * if error. */
1360 sinfo.file_offset = bat_prior_offset;
1361 vhdx_update_bat_table_entry(bs, s, &sinfo, &bat_entry,
1362 &bat_entry_offset, bat_state);
1364 exit:
1365 qemu_vfree(iov1.iov_base);
1366 qemu_vfree(iov2.iov_base);
1367 qemu_co_mutex_unlock(&s->lock);
1368 qemu_iovec_destroy(&hd_qiov);
1369 return ret;
1375 * Create VHDX Headers
1377 * There are 2 headers, and the highest sequence number will represent
1378 * the active header
1380 static int vhdx_create_new_headers(BlockDriverState *bs, uint64_t image_size,
1381 uint32_t log_size)
1383 int ret = 0;
1384 VHDXHeader *hdr = NULL;
1386 hdr = g_new0(VHDXHeader, 1);
1388 hdr->signature = VHDX_HEADER_SIGNATURE;
1389 hdr->sequence_number = g_random_int();
1390 hdr->log_version = 0;
1391 hdr->version = 1;
1392 hdr->log_length = log_size;
1393 hdr->log_offset = VHDX_HEADER_SECTION_END;
1394 vhdx_guid_generate(&hdr->file_write_guid);
1395 vhdx_guid_generate(&hdr->data_write_guid);
1397 ret = vhdx_write_header(bs, hdr, VHDX_HEADER1_OFFSET, false);
1398 if (ret < 0) {
1399 goto exit;
1401 hdr->sequence_number++;
1402 ret = vhdx_write_header(bs, hdr, VHDX_HEADER2_OFFSET, false);
1403 if (ret < 0) {
1404 goto exit;
1407 exit:
1408 g_free(hdr);
1409 return ret;
1412 #define VHDX_METADATA_ENTRY_BUFFER_SIZE \
1413 (sizeof(VHDXFileParameters) +\
1414 sizeof(VHDXVirtualDiskSize) +\
1415 sizeof(VHDXPage83Data) +\
1416 sizeof(VHDXVirtualDiskLogicalSectorSize) +\
1417 sizeof(VHDXVirtualDiskPhysicalSectorSize))
1420 * Create the Metadata entries.
1422 * For more details on the entries, see section 3.5 (pg 29) in the
1423 * VHDX 1.00 specification.
1425 * We support 5 metadata entries (all required by spec):
1426 * File Parameters,
1427 * Virtual Disk Size,
1428 * Page 83 Data,
1429 * Logical Sector Size,
1430 * Physical Sector Size
1432 * The first 64KB of the Metadata section is reserved for the metadata
1433 * header and entries; beyond that, the metadata items themselves reside.
1435 static int vhdx_create_new_metadata(BlockDriverState *bs,
1436 uint64_t image_size,
1437 uint32_t block_size,
1438 uint32_t sector_size,
1439 uint64_t metadata_offset,
1440 VHDXImageType type)
1442 int ret = 0;
1443 uint32_t offset = 0;
1444 void *buffer = NULL;
1445 void *entry_buffer;
1446 VHDXMetadataTableHeader *md_table;;
1447 VHDXMetadataTableEntry *md_table_entry;
1449 /* Metadata entries */
1450 VHDXFileParameters *mt_file_params;
1451 VHDXVirtualDiskSize *mt_virtual_size;
1452 VHDXPage83Data *mt_page83;
1453 VHDXVirtualDiskLogicalSectorSize *mt_log_sector_size;
1454 VHDXVirtualDiskPhysicalSectorSize *mt_phys_sector_size;
1456 entry_buffer = g_malloc0(VHDX_METADATA_ENTRY_BUFFER_SIZE);
1458 mt_file_params = entry_buffer;
1459 offset += sizeof(VHDXFileParameters);
1460 mt_virtual_size = entry_buffer + offset;
1461 offset += sizeof(VHDXVirtualDiskSize);
1462 mt_page83 = entry_buffer + offset;
1463 offset += sizeof(VHDXPage83Data);
1464 mt_log_sector_size = entry_buffer + offset;
1465 offset += sizeof(VHDXVirtualDiskLogicalSectorSize);
1466 mt_phys_sector_size = entry_buffer + offset;
1468 mt_file_params->block_size = cpu_to_le32(block_size);
1469 if (type == VHDX_TYPE_FIXED) {
1470 mt_file_params->data_bits |= VHDX_PARAMS_LEAVE_BLOCKS_ALLOCED;
1471 cpu_to_le32s(&mt_file_params->data_bits);
1474 vhdx_guid_generate(&mt_page83->page_83_data);
1475 cpu_to_leguids(&mt_page83->page_83_data);
1476 mt_virtual_size->virtual_disk_size = cpu_to_le64(image_size);
1477 mt_log_sector_size->logical_sector_size = cpu_to_le32(sector_size);
1478 mt_phys_sector_size->physical_sector_size = cpu_to_le32(sector_size);
1480 buffer = g_malloc0(VHDX_HEADER_BLOCK_SIZE);
1481 md_table = buffer;
1483 md_table->signature = VHDX_METADATA_SIGNATURE;
1484 md_table->entry_count = 5;
1485 vhdx_metadata_header_le_export(md_table);
1488 /* This will reference beyond the reserved table portion */
1489 offset = 64 * KiB;
1491 md_table_entry = buffer + sizeof(VHDXMetadataTableHeader);
1493 md_table_entry[0].item_id = file_param_guid;
1494 md_table_entry[0].offset = offset;
1495 md_table_entry[0].length = sizeof(VHDXFileParameters);
1496 md_table_entry[0].data_bits |= VHDX_META_FLAGS_IS_REQUIRED;
1497 offset += md_table_entry[0].length;
1498 vhdx_metadata_entry_le_export(&md_table_entry[0]);
1500 md_table_entry[1].item_id = virtual_size_guid;
1501 md_table_entry[1].offset = offset;
1502 md_table_entry[1].length = sizeof(VHDXVirtualDiskSize);
1503 md_table_entry[1].data_bits |= VHDX_META_FLAGS_IS_REQUIRED |
1504 VHDX_META_FLAGS_IS_VIRTUAL_DISK;
1505 offset += md_table_entry[1].length;
1506 vhdx_metadata_entry_le_export(&md_table_entry[1]);
1508 md_table_entry[2].item_id = page83_guid;
1509 md_table_entry[2].offset = offset;
1510 md_table_entry[2].length = sizeof(VHDXPage83Data);
1511 md_table_entry[2].data_bits |= VHDX_META_FLAGS_IS_REQUIRED |
1512 VHDX_META_FLAGS_IS_VIRTUAL_DISK;
1513 offset += md_table_entry[2].length;
1514 vhdx_metadata_entry_le_export(&md_table_entry[2]);
1516 md_table_entry[3].item_id = logical_sector_guid;
1517 md_table_entry[3].offset = offset;
1518 md_table_entry[3].length = sizeof(VHDXVirtualDiskLogicalSectorSize);
1519 md_table_entry[3].data_bits |= VHDX_META_FLAGS_IS_REQUIRED |
1520 VHDX_META_FLAGS_IS_VIRTUAL_DISK;
1521 offset += md_table_entry[3].length;
1522 vhdx_metadata_entry_le_export(&md_table_entry[3]);
1524 md_table_entry[4].item_id = phys_sector_guid;
1525 md_table_entry[4].offset = offset;
1526 md_table_entry[4].length = sizeof(VHDXVirtualDiskPhysicalSectorSize);
1527 md_table_entry[4].data_bits |= VHDX_META_FLAGS_IS_REQUIRED |
1528 VHDX_META_FLAGS_IS_VIRTUAL_DISK;
1529 vhdx_metadata_entry_le_export(&md_table_entry[4]);
1531 ret = bdrv_pwrite(bs, metadata_offset, buffer, VHDX_HEADER_BLOCK_SIZE);
1532 if (ret < 0) {
1533 goto exit;
1536 ret = bdrv_pwrite(bs, metadata_offset + (64 * KiB), entry_buffer,
1537 VHDX_METADATA_ENTRY_BUFFER_SIZE);
1538 if (ret < 0) {
1539 goto exit;
1543 exit:
1544 g_free(buffer);
1545 g_free(entry_buffer);
1546 return ret;
1549 /* This create the actual BAT itself. We currently only support
1550 * 'Dynamic' and 'Fixed' image types.
1552 * Dynamic images: default state of the BAT is all zeroes.
1554 * Fixed images: default state of the BAT is fully populated, with
1555 * file offsets and state PAYLOAD_BLOCK_FULLY_PRESENT.
1557 static int vhdx_create_bat(BlockDriverState *bs, BDRVVHDXState *s,
1558 uint64_t image_size, VHDXImageType type,
1559 bool use_zero_blocks, uint64_t file_offset,
1560 uint32_t length)
1562 int ret = 0;
1563 uint64_t data_file_offset;
1564 uint64_t total_sectors = 0;
1565 uint64_t sector_num = 0;
1566 uint64_t unused;
1567 int block_state;
1568 VHDXSectorInfo sinfo;
1570 assert(s->bat == NULL);
1572 /* this gives a data start after BAT/bitmap entries, and well
1573 * past any metadata entries (with a 4 MB buffer for future
1574 * expansion */
1575 data_file_offset = file_offset + length + 5 * MiB;
1576 total_sectors = image_size >> s->logical_sector_size_bits;
1578 if (type == VHDX_TYPE_DYNAMIC) {
1579 /* All zeroes, so we can just extend the file - the end of the BAT
1580 * is the furthest thing we have written yet */
1581 ret = bdrv_truncate(bs, data_file_offset);
1582 if (ret < 0) {
1583 goto exit;
1585 } else if (type == VHDX_TYPE_FIXED) {
1586 ret = bdrv_truncate(bs, data_file_offset + image_size);
1587 if (ret < 0) {
1588 goto exit;
1590 } else {
1591 ret = -ENOTSUP;
1592 goto exit;
1595 if (type == VHDX_TYPE_FIXED ||
1596 use_zero_blocks ||
1597 bdrv_has_zero_init(bs) == 0) {
1598 /* for a fixed file, the default BAT entry is not zero */
1599 s->bat = g_try_malloc0(length);
1600 if (length && s->bat == NULL) {
1601 ret = -ENOMEM;
1602 goto exit;
1604 block_state = type == VHDX_TYPE_FIXED ? PAYLOAD_BLOCK_FULLY_PRESENT :
1605 PAYLOAD_BLOCK_NOT_PRESENT;
1606 block_state = use_zero_blocks ? PAYLOAD_BLOCK_ZERO : block_state;
1607 /* fill the BAT by emulating sector writes of sectors_per_block size */
1608 while (sector_num < total_sectors) {
1609 vhdx_block_translate(s, sector_num, s->sectors_per_block, &sinfo);
1610 sinfo.file_offset = data_file_offset +
1611 (sector_num << s->logical_sector_size_bits);
1612 sinfo.file_offset = ROUND_UP(sinfo.file_offset, MiB);
1613 vhdx_update_bat_table_entry(bs, s, &sinfo, &unused, &unused,
1614 block_state);
1615 cpu_to_le64s(&s->bat[sinfo.bat_idx]);
1616 sector_num += s->sectors_per_block;
1618 ret = bdrv_pwrite(bs, file_offset, s->bat, length);
1619 if (ret < 0) {
1620 goto exit;
1626 exit:
1627 g_free(s->bat);
1628 return ret;
1631 /* Creates the region table header, and region table entries.
1632 * There are 2 supported region table entries: BAT, and Metadata/
1634 * As the calculations for the BAT region table are also needed
1635 * to create the BAT itself, we will also cause the BAT to be
1636 * created.
1638 static int vhdx_create_new_region_table(BlockDriverState *bs,
1639 uint64_t image_size,
1640 uint32_t block_size,
1641 uint32_t sector_size,
1642 uint32_t log_size,
1643 bool use_zero_blocks,
1644 VHDXImageType type,
1645 uint64_t *metadata_offset)
1647 int ret = 0;
1648 uint32_t offset = 0;
1649 void *buffer = NULL;
1650 uint64_t bat_file_offset;
1651 uint32_t bat_length;
1652 BDRVVHDXState *s = NULL;
1653 VHDXRegionTableHeader *region_table;
1654 VHDXRegionTableEntry *rt_bat;
1655 VHDXRegionTableEntry *rt_metadata;
1657 assert(metadata_offset != NULL);
1659 /* Populate enough of the BDRVVHDXState to be able to use the
1660 * pre-existing BAT calculation, translation, and update functions */
1661 s = g_new0(BDRVVHDXState, 1);
1663 s->chunk_ratio = (VHDX_MAX_SECTORS_PER_BLOCK) *
1664 (uint64_t) sector_size / (uint64_t) block_size;
1666 s->sectors_per_block = block_size / sector_size;
1667 s->virtual_disk_size = image_size;
1668 s->block_size = block_size;
1669 s->logical_sector_size = sector_size;
1671 vhdx_set_shift_bits(s);
1673 vhdx_calc_bat_entries(s);
1675 /* At this point the VHDX state is populated enough for creation */
1677 /* a single buffer is used so we can calculate the checksum over the
1678 * entire 64KB block */
1679 buffer = g_malloc0(VHDX_HEADER_BLOCK_SIZE);
1680 region_table = buffer;
1681 offset += sizeof(VHDXRegionTableHeader);
1682 rt_bat = buffer + offset;
1683 offset += sizeof(VHDXRegionTableEntry);
1684 rt_metadata = buffer + offset;
1686 region_table->signature = VHDX_REGION_SIGNATURE;
1687 region_table->entry_count = 2; /* BAT and Metadata */
1689 rt_bat->guid = bat_guid;
1690 rt_bat->length = ROUND_UP(s->bat_entries * sizeof(VHDXBatEntry), MiB);
1691 rt_bat->file_offset = ROUND_UP(VHDX_HEADER_SECTION_END + log_size, MiB);
1692 s->bat_offset = rt_bat->file_offset;
1694 rt_metadata->guid = metadata_guid;
1695 rt_metadata->file_offset = ROUND_UP(rt_bat->file_offset + rt_bat->length,
1696 MiB);
1697 rt_metadata->length = 1 * MiB; /* min size, and more than enough */
1698 *metadata_offset = rt_metadata->file_offset;
1700 bat_file_offset = rt_bat->file_offset;
1701 bat_length = rt_bat->length;
1703 vhdx_region_header_le_export(region_table);
1704 vhdx_region_entry_le_export(rt_bat);
1705 vhdx_region_entry_le_export(rt_metadata);
1707 vhdx_update_checksum(buffer, VHDX_HEADER_BLOCK_SIZE,
1708 offsetof(VHDXRegionTableHeader, checksum));
1711 /* The region table gives us the data we need to create the BAT,
1712 * so do that now */
1713 ret = vhdx_create_bat(bs, s, image_size, type, use_zero_blocks,
1714 bat_file_offset, bat_length);
1715 if (ret < 0) {
1716 goto exit;
1719 /* Now write out the region headers to disk */
1720 ret = bdrv_pwrite(bs, VHDX_REGION_TABLE_OFFSET, buffer,
1721 VHDX_HEADER_BLOCK_SIZE);
1722 if (ret < 0) {
1723 goto exit;
1726 ret = bdrv_pwrite(bs, VHDX_REGION_TABLE2_OFFSET, buffer,
1727 VHDX_HEADER_BLOCK_SIZE);
1728 if (ret < 0) {
1729 goto exit;
1732 exit:
1733 g_free(s);
1734 g_free(buffer);
1735 return ret;
1738 /* We need to create the following elements:
1740 * .-----------------------------------------------------------------.
1741 * | (A) | (B) | (C) | (D) | (E) |
1742 * | File ID | Header1 | Header 2 | Region Tbl 1 | Region Tbl 2 |
1743 * | | | | | |
1744 * .-----------------------------------------------------------------.
1745 * 0 64KB 128KB 192KB 256KB 320KB
1748 * .---- ~ ----------- ~ ------------ ~ ---------------- ~ -----------.
1749 * | (F) | (G) | (H) | |
1750 * | Journal Log | BAT / Bitmap | Metadata | .... data ...... |
1751 * | | | | |
1752 * .---- ~ ----------- ~ ------------ ~ ---------------- ~ -----------.
1753 * 1MB
1755 static int vhdx_create(const char *filename, QemuOpts *opts, Error **errp)
1757 int ret = 0;
1758 uint64_t image_size = (uint64_t) 2 * GiB;
1759 uint32_t log_size = 1 * MiB;
1760 uint32_t block_size = 0;
1761 uint64_t signature;
1762 uint64_t metadata_offset;
1763 bool use_zero_blocks = false;
1765 gunichar2 *creator = NULL;
1766 glong creator_items;
1767 BlockDriverState *bs;
1768 char *type = NULL;
1769 VHDXImageType image_type;
1770 Error *local_err = NULL;
1772 image_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1773 BDRV_SECTOR_SIZE);
1774 log_size = qemu_opt_get_size_del(opts, VHDX_BLOCK_OPT_LOG_SIZE, 0);
1775 block_size = qemu_opt_get_size_del(opts, VHDX_BLOCK_OPT_BLOCK_SIZE, 0);
1776 type = qemu_opt_get_del(opts, BLOCK_OPT_SUBFMT);
1777 use_zero_blocks = qemu_opt_get_bool_del(opts, VHDX_BLOCK_OPT_ZERO, true);
1779 if (image_size > VHDX_MAX_IMAGE_SIZE) {
1780 error_setg_errno(errp, EINVAL, "Image size too large; max of 64TB");
1781 ret = -EINVAL;
1782 goto exit;
1785 if (type == NULL) {
1786 type = g_strdup("dynamic");
1789 if (!strcmp(type, "dynamic")) {
1790 image_type = VHDX_TYPE_DYNAMIC;
1791 } else if (!strcmp(type, "fixed")) {
1792 image_type = VHDX_TYPE_FIXED;
1793 } else if (!strcmp(type, "differencing")) {
1794 error_setg_errno(errp, ENOTSUP,
1795 "Differencing files not yet supported");
1796 ret = -ENOTSUP;
1797 goto exit;
1798 } else {
1799 ret = -EINVAL;
1800 goto exit;
1803 /* These are pretty arbitrary, and mainly designed to keep the BAT
1804 * size reasonable to load into RAM */
1805 if (block_size == 0) {
1806 if (image_size > 32 * TiB) {
1807 block_size = 64 * MiB;
1808 } else if (image_size > (uint64_t) 100 * GiB) {
1809 block_size = 32 * MiB;
1810 } else if (image_size > 1 * GiB) {
1811 block_size = 16 * MiB;
1812 } else {
1813 block_size = 8 * MiB;
1818 /* make the log size close to what was specified, but must be
1819 * min 1MB, and multiple of 1MB */
1820 log_size = ROUND_UP(log_size, MiB);
1822 block_size = ROUND_UP(block_size, MiB);
1823 block_size = block_size > VHDX_BLOCK_SIZE_MAX ? VHDX_BLOCK_SIZE_MAX :
1824 block_size;
1826 ret = bdrv_create_file(filename, opts, &local_err);
1827 if (ret < 0) {
1828 error_propagate(errp, local_err);
1829 goto exit;
1832 bs = NULL;
1833 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1834 NULL, &local_err);
1835 if (ret < 0) {
1836 error_propagate(errp, local_err);
1837 goto exit;
1840 /* Create (A) */
1842 /* The creator field is optional, but may be useful for
1843 * debugging / diagnostics */
1844 creator = g_utf8_to_utf16("QEMU v" QEMU_VERSION, -1, NULL,
1845 &creator_items, NULL);
1846 signature = cpu_to_le64(VHDX_FILE_SIGNATURE);
1847 ret = bdrv_pwrite(bs, VHDX_FILE_ID_OFFSET, &signature, sizeof(signature));
1848 if (ret < 0) {
1849 goto delete_and_exit;
1851 if (creator) {
1852 ret = bdrv_pwrite(bs, VHDX_FILE_ID_OFFSET + sizeof(signature),
1853 creator, creator_items * sizeof(gunichar2));
1854 if (ret < 0) {
1855 goto delete_and_exit;
1860 /* Creates (B),(C) */
1861 ret = vhdx_create_new_headers(bs, image_size, log_size);
1862 if (ret < 0) {
1863 goto delete_and_exit;
1866 /* Creates (D),(E),(G) explicitly. (F) created as by-product */
1867 ret = vhdx_create_new_region_table(bs, image_size, block_size, 512,
1868 log_size, use_zero_blocks, image_type,
1869 &metadata_offset);
1870 if (ret < 0) {
1871 goto delete_and_exit;
1874 /* Creates (H) */
1875 ret = vhdx_create_new_metadata(bs, image_size, block_size, 512,
1876 metadata_offset, image_type);
1877 if (ret < 0) {
1878 goto delete_and_exit;
1882 delete_and_exit:
1883 bdrv_unref(bs);
1884 exit:
1885 g_free(type);
1886 g_free(creator);
1887 return ret;
1890 /* If opened r/w, the VHDX driver will automatically replay the log,
1891 * if one is present, inside the vhdx_open() call.
1893 * If qemu-img check -r all is called, the image is automatically opened
1894 * r/w and any log has already been replayed, so there is nothing (currently)
1895 * for us to do here
1897 static int vhdx_check(BlockDriverState *bs, BdrvCheckResult *result,
1898 BdrvCheckMode fix)
1900 BDRVVHDXState *s = bs->opaque;
1902 if (s->log_replayed_on_open) {
1903 result->corruptions_fixed++;
1905 return 0;
1908 static QemuOptsList vhdx_create_opts = {
1909 .name = "vhdx-create-opts",
1910 .head = QTAILQ_HEAD_INITIALIZER(vhdx_create_opts.head),
1911 .desc = {
1913 .name = BLOCK_OPT_SIZE,
1914 .type = QEMU_OPT_SIZE,
1915 .help = "Virtual disk size; max of 64TB."
1918 .name = VHDX_BLOCK_OPT_LOG_SIZE,
1919 .type = QEMU_OPT_SIZE,
1920 .def_value_str = stringify(DEFAULT_LOG_SIZE),
1921 .help = "Log size; min 1MB."
1924 .name = VHDX_BLOCK_OPT_BLOCK_SIZE,
1925 .type = QEMU_OPT_SIZE,
1926 .def_value_str = stringify(0),
1927 .help = "Block Size; min 1MB, max 256MB. " \
1928 "0 means auto-calculate based on image size."
1931 .name = BLOCK_OPT_SUBFMT,
1932 .type = QEMU_OPT_STRING,
1933 .help = "VHDX format type, can be either 'dynamic' or 'fixed'. "\
1934 "Default is 'dynamic'."
1937 .name = VHDX_BLOCK_OPT_ZERO,
1938 .type = QEMU_OPT_BOOL,
1939 .help = "Force use of payload blocks of type 'ZERO'. "\
1940 "Non-standard, but default. Do not set to 'off' when "\
1941 "using 'qemu-img convert' with subformat=dynamic."
1943 { NULL }
1947 static BlockDriver bdrv_vhdx = {
1948 .format_name = "vhdx",
1949 .instance_size = sizeof(BDRVVHDXState),
1950 .bdrv_probe = vhdx_probe,
1951 .bdrv_open = vhdx_open,
1952 .bdrv_close = vhdx_close,
1953 .bdrv_reopen_prepare = vhdx_reopen_prepare,
1954 .bdrv_co_readv = vhdx_co_readv,
1955 .bdrv_co_writev = vhdx_co_writev,
1956 .bdrv_create = vhdx_create,
1957 .bdrv_get_info = vhdx_get_info,
1958 .bdrv_check = vhdx_check,
1960 .create_opts = &vhdx_create_opts,
1963 static void bdrv_vhdx_init(void)
1965 bdrv_register(&bdrv_vhdx);
1968 block_init(bdrv_vhdx_init);