virtio-blk: use aliases instead of duplicate qdev properties
[qemu/cris-port.git] / block / vhdx.c
blobfedcf9f9cacb2b3825112c4ced22b99b4af2e0b7
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 = { .data1 = 0xb04aefb7,
103 .data2 = 0xd19e,
104 .data3 = 0x4a81,
105 .data4 = { 0xb7, 0x89, 0x25, 0xb8,
106 0xe9, 0x44, 0x59, 0x13} };
109 #define META_FILE_PARAMETER_PRESENT 0x01
110 #define META_VIRTUAL_DISK_SIZE_PRESENT 0x02
111 #define META_PAGE_83_PRESENT 0x04
112 #define META_LOGICAL_SECTOR_SIZE_PRESENT 0x08
113 #define META_PHYS_SECTOR_SIZE_PRESENT 0x10
114 #define META_PARENT_LOCATOR_PRESENT 0x20
116 #define META_ALL_PRESENT \
117 (META_FILE_PARAMETER_PRESENT | META_VIRTUAL_DISK_SIZE_PRESENT | \
118 META_PAGE_83_PRESENT | META_LOGICAL_SECTOR_SIZE_PRESENT | \
119 META_PHYS_SECTOR_SIZE_PRESENT)
122 typedef struct VHDXSectorInfo {
123 uint32_t bat_idx; /* BAT entry index */
124 uint32_t sectors_avail; /* sectors available in payload block */
125 uint32_t bytes_left; /* bytes left in the block after data to r/w */
126 uint32_t bytes_avail; /* bytes available in payload block */
127 uint64_t file_offset; /* absolute offset in bytes, in file */
128 uint64_t block_offset; /* block offset, in bytes */
129 } VHDXSectorInfo;
131 /* Calculates new checksum.
133 * Zero is substituted during crc calculation for the original crc field
134 * crc_offset: byte offset in buf of the buffer crc
135 * buf: buffer pointer
136 * size: size of buffer (must be > crc_offset+4)
138 * Note: The resulting checksum is in the CPU endianness, not necessarily
139 * in the file format endianness (LE). Any header export to disk should
140 * make sure that vhdx_header_le_export() is used to convert to the
141 * correct endianness
143 uint32_t vhdx_update_checksum(uint8_t *buf, size_t size, int crc_offset)
145 uint32_t crc;
147 assert(buf != NULL);
148 assert(size > (crc_offset + sizeof(crc)));
150 memset(buf + crc_offset, 0, sizeof(crc));
151 crc = crc32c(0xffffffff, buf, size);
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 memcpy(buffer, hdr, sizeof(VHDXHeader));
325 hdr->checksum = vhdx_update_checksum(buffer, VHDX_HEADER_SIZE,
326 offsetof(VHDXHeader, checksum));
327 vhdx_header_le_export(hdr, &header_le);
328 ret = bdrv_pwrite_sync(bs_file, offset, &header_le, sizeof(VHDXHeader));
330 exit:
331 qemu_vfree(buffer);
332 return ret;
335 /* Update the VHDX headers
337 * This follows the VHDX spec procedures for header updates.
339 * - non-current header is updated with largest sequence number
341 static int vhdx_update_header(BlockDriverState *bs, BDRVVHDXState *s,
342 bool generate_data_write_guid, MSGUID *log_guid)
344 int ret = 0;
345 int hdr_idx = 0;
346 uint64_t header_offset = VHDX_HEADER1_OFFSET;
348 VHDXHeader *active_header;
349 VHDXHeader *inactive_header;
351 /* operate on the non-current header */
352 if (s->curr_header == 0) {
353 hdr_idx = 1;
354 header_offset = VHDX_HEADER2_OFFSET;
357 active_header = s->headers[s->curr_header];
358 inactive_header = s->headers[hdr_idx];
360 inactive_header->sequence_number = active_header->sequence_number + 1;
362 /* a new file guid must be generated before any file write, including
363 * headers */
364 inactive_header->file_write_guid = s->session_guid;
366 /* a new data guid only needs to be generated before any guest-visible
367 * writes (i.e. something observable via virtual disk read) */
368 if (generate_data_write_guid) {
369 vhdx_guid_generate(&inactive_header->data_write_guid);
372 /* update the log guid if present */
373 if (log_guid) {
374 inactive_header->log_guid = *log_guid;
377 ret = vhdx_write_header(bs->file, inactive_header, header_offset, true);
378 if (ret < 0) {
379 goto exit;
381 s->curr_header = hdr_idx;
383 exit:
384 return ret;
388 * The VHDX spec calls for header updates to be performed twice, so that both
389 * the current and non-current header have valid info
391 int vhdx_update_headers(BlockDriverState *bs, BDRVVHDXState *s,
392 bool generate_data_write_guid, MSGUID *log_guid)
394 int ret;
396 ret = vhdx_update_header(bs, s, generate_data_write_guid, log_guid);
397 if (ret < 0) {
398 return ret;
400 ret = vhdx_update_header(bs, s, generate_data_write_guid, log_guid);
401 return ret;
404 /* opens the specified header block from the VHDX file header section */
405 static void vhdx_parse_header(BlockDriverState *bs, BDRVVHDXState *s,
406 Error **errp)
408 int ret;
409 VHDXHeader *header1;
410 VHDXHeader *header2;
411 bool h1_valid = false;
412 bool h2_valid = false;
413 uint64_t h1_seq = 0;
414 uint64_t h2_seq = 0;
415 uint8_t *buffer;
417 /* header1 & header2 are freed in vhdx_close() */
418 header1 = qemu_blockalign(bs, sizeof(VHDXHeader));
419 header2 = qemu_blockalign(bs, sizeof(VHDXHeader));
421 buffer = qemu_blockalign(bs, VHDX_HEADER_SIZE);
423 s->headers[0] = header1;
424 s->headers[1] = header2;
426 /* We have to read the whole VHDX_HEADER_SIZE instead of
427 * sizeof(VHDXHeader), because the checksum is over the whole
428 * region */
429 ret = bdrv_pread(bs->file, VHDX_HEADER1_OFFSET, buffer, VHDX_HEADER_SIZE);
430 if (ret < 0) {
431 goto fail;
433 /* copy over just the relevant portion that we need */
434 memcpy(header1, buffer, sizeof(VHDXHeader));
435 vhdx_header_le_import(header1);
437 if (vhdx_checksum_is_valid(buffer, VHDX_HEADER_SIZE, 4) &&
438 !memcmp(&header1->signature, "head", 4) &&
439 header1->version == 1) {
440 h1_seq = header1->sequence_number;
441 h1_valid = true;
444 ret = bdrv_pread(bs->file, VHDX_HEADER2_OFFSET, buffer, VHDX_HEADER_SIZE);
445 if (ret < 0) {
446 goto fail;
448 /* copy over just the relevant portion that we need */
449 memcpy(header2, buffer, sizeof(VHDXHeader));
450 vhdx_header_le_import(header2);
452 if (vhdx_checksum_is_valid(buffer, VHDX_HEADER_SIZE, 4) &&
453 !memcmp(&header2->signature, "head", 4) &&
454 header2->version == 1) {
455 h2_seq = header2->sequence_number;
456 h2_valid = true;
459 /* If there is only 1 valid header (or no valid headers), we
460 * don't care what the sequence numbers are */
461 if (h1_valid && !h2_valid) {
462 s->curr_header = 0;
463 } else if (!h1_valid && h2_valid) {
464 s->curr_header = 1;
465 } else if (!h1_valid && !h2_valid) {
466 goto fail;
467 } else {
468 /* If both headers are valid, then we choose the active one by the
469 * highest sequence number. If the sequence numbers are equal, that is
470 * invalid */
471 if (h1_seq > h2_seq) {
472 s->curr_header = 0;
473 } else if (h2_seq > h1_seq) {
474 s->curr_header = 1;
475 } else {
476 /* The Microsoft Disk2VHD tool will create 2 identical
477 * headers, with identical sequence numbers. If the headers are
478 * identical, don't consider the file corrupt */
479 if (!memcmp(header1, header2, sizeof(VHDXHeader))) {
480 s->curr_header = 0;
481 } else {
482 goto fail;
487 vhdx_region_register(s, s->headers[s->curr_header]->log_offset,
488 s->headers[s->curr_header]->log_length);
489 goto exit;
491 fail:
492 error_setg_errno(errp, -ret, "No valid VHDX header found");
493 qemu_vfree(header1);
494 qemu_vfree(header2);
495 s->headers[0] = NULL;
496 s->headers[1] = NULL;
497 exit:
498 qemu_vfree(buffer);
502 static int vhdx_open_region_tables(BlockDriverState *bs, BDRVVHDXState *s)
504 int ret = 0;
505 uint8_t *buffer;
506 int offset = 0;
507 VHDXRegionTableEntry rt_entry;
508 uint32_t i;
509 bool bat_rt_found = false;
510 bool metadata_rt_found = false;
512 /* We have to read the whole 64KB block, because the crc32 is over the
513 * whole block */
514 buffer = qemu_blockalign(bs, VHDX_HEADER_BLOCK_SIZE);
516 ret = bdrv_pread(bs->file, VHDX_REGION_TABLE_OFFSET, buffer,
517 VHDX_HEADER_BLOCK_SIZE);
518 if (ret < 0) {
519 goto fail;
521 memcpy(&s->rt, buffer, sizeof(s->rt));
522 vhdx_region_header_le_import(&s->rt);
523 offset += sizeof(s->rt);
525 if (!vhdx_checksum_is_valid(buffer, VHDX_HEADER_BLOCK_SIZE, 4) ||
526 memcmp(&s->rt.signature, "regi", 4)) {
527 ret = -EINVAL;
528 goto fail;
531 /* Per spec, maximum region table entry count is 2047 */
532 if (s->rt.entry_count > 2047) {
533 ret = -EINVAL;
534 goto fail;
537 for (i = 0; i < s->rt.entry_count; i++) {
538 memcpy(&rt_entry, buffer + offset, sizeof(rt_entry));
539 offset += sizeof(rt_entry);
541 vhdx_region_entry_le_import(&rt_entry);
543 /* check for region overlap between these entries, and any
544 * other memory regions in the file */
545 ret = vhdx_region_check(s, rt_entry.file_offset, rt_entry.length);
546 if (ret < 0) {
547 goto fail;
550 vhdx_region_register(s, rt_entry.file_offset, rt_entry.length);
552 /* see if we recognize the entry */
553 if (guid_eq(rt_entry.guid, bat_guid)) {
554 /* must be unique; if we have already found it this is invalid */
555 if (bat_rt_found) {
556 ret = -EINVAL;
557 goto fail;
559 bat_rt_found = true;
560 s->bat_rt = rt_entry;
561 continue;
564 if (guid_eq(rt_entry.guid, metadata_guid)) {
565 /* must be unique; if we have already found it this is invalid */
566 if (metadata_rt_found) {
567 ret = -EINVAL;
568 goto fail;
570 metadata_rt_found = true;
571 s->metadata_rt = rt_entry;
572 continue;
575 if (rt_entry.data_bits & VHDX_REGION_ENTRY_REQUIRED) {
576 /* cannot read vhdx file - required region table entry that
577 * we do not understand. per spec, we must fail to open */
578 ret = -ENOTSUP;
579 goto fail;
583 if (!bat_rt_found || !metadata_rt_found) {
584 ret = -EINVAL;
585 goto fail;
588 ret = 0;
590 fail:
591 qemu_vfree(buffer);
592 return ret;
597 /* Metadata initial parser
599 * This loads all the metadata entry fields. This may cause additional
600 * fields to be processed (e.g. parent locator, etc..).
602 * There are 5 Metadata items that are always required:
603 * - File Parameters (block size, has a parent)
604 * - Virtual Disk Size (size, in bytes, of the virtual drive)
605 * - Page 83 Data (scsi page 83 guid)
606 * - Logical Sector Size (logical sector size in bytes, either 512 or
607 * 4096. We only support 512 currently)
608 * - Physical Sector Size (512 or 4096)
610 * Also, if the File Parameters indicate this is a differencing file,
611 * we must also look for the Parent Locator metadata item.
613 static int vhdx_parse_metadata(BlockDriverState *bs, BDRVVHDXState *s)
615 int ret = 0;
616 uint8_t *buffer;
617 int offset = 0;
618 uint32_t i = 0;
619 VHDXMetadataTableEntry md_entry;
621 buffer = qemu_blockalign(bs, VHDX_METADATA_TABLE_MAX_SIZE);
623 ret = bdrv_pread(bs->file, s->metadata_rt.file_offset, buffer,
624 VHDX_METADATA_TABLE_MAX_SIZE);
625 if (ret < 0) {
626 goto exit;
628 memcpy(&s->metadata_hdr, buffer, sizeof(s->metadata_hdr));
629 offset += sizeof(s->metadata_hdr);
631 vhdx_metadata_header_le_import(&s->metadata_hdr);
633 if (memcmp(&s->metadata_hdr.signature, "metadata", 8)) {
634 ret = -EINVAL;
635 goto exit;
638 s->metadata_entries.present = 0;
640 if ((s->metadata_hdr.entry_count * sizeof(md_entry)) >
641 (VHDX_METADATA_TABLE_MAX_SIZE - offset)) {
642 ret = -EINVAL;
643 goto exit;
646 for (i = 0; i < s->metadata_hdr.entry_count; i++) {
647 memcpy(&md_entry, buffer + offset, sizeof(md_entry));
648 offset += sizeof(md_entry);
650 vhdx_metadata_entry_le_import(&md_entry);
652 if (guid_eq(md_entry.item_id, file_param_guid)) {
653 if (s->metadata_entries.present & META_FILE_PARAMETER_PRESENT) {
654 ret = -EINVAL;
655 goto exit;
657 s->metadata_entries.file_parameters_entry = md_entry;
658 s->metadata_entries.present |= META_FILE_PARAMETER_PRESENT;
659 continue;
662 if (guid_eq(md_entry.item_id, virtual_size_guid)) {
663 if (s->metadata_entries.present & META_VIRTUAL_DISK_SIZE_PRESENT) {
664 ret = -EINVAL;
665 goto exit;
667 s->metadata_entries.virtual_disk_size_entry = md_entry;
668 s->metadata_entries.present |= META_VIRTUAL_DISK_SIZE_PRESENT;
669 continue;
672 if (guid_eq(md_entry.item_id, page83_guid)) {
673 if (s->metadata_entries.present & META_PAGE_83_PRESENT) {
674 ret = -EINVAL;
675 goto exit;
677 s->metadata_entries.page83_data_entry = md_entry;
678 s->metadata_entries.present |= META_PAGE_83_PRESENT;
679 continue;
682 if (guid_eq(md_entry.item_id, logical_sector_guid)) {
683 if (s->metadata_entries.present &
684 META_LOGICAL_SECTOR_SIZE_PRESENT) {
685 ret = -EINVAL;
686 goto exit;
688 s->metadata_entries.logical_sector_size_entry = md_entry;
689 s->metadata_entries.present |= META_LOGICAL_SECTOR_SIZE_PRESENT;
690 continue;
693 if (guid_eq(md_entry.item_id, phys_sector_guid)) {
694 if (s->metadata_entries.present & META_PHYS_SECTOR_SIZE_PRESENT) {
695 ret = -EINVAL;
696 goto exit;
698 s->metadata_entries.phys_sector_size_entry = md_entry;
699 s->metadata_entries.present |= META_PHYS_SECTOR_SIZE_PRESENT;
700 continue;
703 if (guid_eq(md_entry.item_id, parent_locator_guid)) {
704 if (s->metadata_entries.present & META_PARENT_LOCATOR_PRESENT) {
705 ret = -EINVAL;
706 goto exit;
708 s->metadata_entries.parent_locator_entry = md_entry;
709 s->metadata_entries.present |= META_PARENT_LOCATOR_PRESENT;
710 continue;
713 if (md_entry.data_bits & VHDX_META_FLAGS_IS_REQUIRED) {
714 /* cannot read vhdx file - required region table entry that
715 * we do not understand. per spec, we must fail to open */
716 ret = -ENOTSUP;
717 goto exit;
721 if (s->metadata_entries.present != META_ALL_PRESENT) {
722 ret = -ENOTSUP;
723 goto exit;
726 ret = bdrv_pread(bs->file,
727 s->metadata_entries.file_parameters_entry.offset
728 + s->metadata_rt.file_offset,
729 &s->params,
730 sizeof(s->params));
732 if (ret < 0) {
733 goto exit;
736 le32_to_cpus(&s->params.block_size);
737 le32_to_cpus(&s->params.data_bits);
740 /* We now have the file parameters, so we can tell if this is a
741 * differencing file (i.e.. has_parent), is dynamic or fixed
742 * sized (leave_blocks_allocated), and the block size */
744 /* The parent locator required iff the file parameters has_parent set */
745 if (s->params.data_bits & VHDX_PARAMS_HAS_PARENT) {
746 if (s->metadata_entries.present & META_PARENT_LOCATOR_PRESENT) {
747 /* TODO: parse parent locator fields */
748 ret = -ENOTSUP; /* temp, until differencing files are supported */
749 goto exit;
750 } else {
751 /* if has_parent is set, but there is not parent locator present,
752 * then that is an invalid combination */
753 ret = -EINVAL;
754 goto exit;
758 /* determine virtual disk size, logical sector size,
759 * and phys sector size */
761 ret = bdrv_pread(bs->file,
762 s->metadata_entries.virtual_disk_size_entry.offset
763 + s->metadata_rt.file_offset,
764 &s->virtual_disk_size,
765 sizeof(uint64_t));
766 if (ret < 0) {
767 goto exit;
769 ret = bdrv_pread(bs->file,
770 s->metadata_entries.logical_sector_size_entry.offset
771 + s->metadata_rt.file_offset,
772 &s->logical_sector_size,
773 sizeof(uint32_t));
774 if (ret < 0) {
775 goto exit;
777 ret = bdrv_pread(bs->file,
778 s->metadata_entries.phys_sector_size_entry.offset
779 + s->metadata_rt.file_offset,
780 &s->physical_sector_size,
781 sizeof(uint32_t));
782 if (ret < 0) {
783 goto exit;
786 le64_to_cpus(&s->virtual_disk_size);
787 le32_to_cpus(&s->logical_sector_size);
788 le32_to_cpus(&s->physical_sector_size);
790 if (s->params.block_size < VHDX_BLOCK_SIZE_MIN ||
791 s->params.block_size > VHDX_BLOCK_SIZE_MAX) {
792 ret = -EINVAL;
793 goto exit;
796 /* only 2 supported sector sizes */
797 if (s->logical_sector_size != 512 && s->logical_sector_size != 4096) {
798 ret = -EINVAL;
799 goto exit;
802 /* Both block_size and sector_size are guaranteed powers of 2, below.
803 Due to range checks above, s->sectors_per_block can never be < 256 */
804 s->sectors_per_block = s->params.block_size / s->logical_sector_size;
805 s->chunk_ratio = (VHDX_MAX_SECTORS_PER_BLOCK) *
806 (uint64_t)s->logical_sector_size /
807 (uint64_t)s->params.block_size;
809 /* These values are ones we will want to use for division / multiplication
810 * later on, and they are all guaranteed (per the spec) to be powers of 2,
811 * so we can take advantage of that for shift operations during
812 * reads/writes */
813 if (s->logical_sector_size & (s->logical_sector_size - 1)) {
814 ret = -EINVAL;
815 goto exit;
817 if (s->sectors_per_block & (s->sectors_per_block - 1)) {
818 ret = -EINVAL;
819 goto exit;
821 if (s->chunk_ratio & (s->chunk_ratio - 1)) {
822 ret = -EINVAL;
823 goto exit;
825 s->block_size = s->params.block_size;
826 if (s->block_size & (s->block_size - 1)) {
827 ret = -EINVAL;
828 goto exit;
831 vhdx_set_shift_bits(s);
833 ret = 0;
835 exit:
836 qemu_vfree(buffer);
837 return ret;
841 * Calculate the number of BAT entries, including sector
842 * bitmap entries.
844 static void vhdx_calc_bat_entries(BDRVVHDXState *s)
846 uint32_t data_blocks_cnt, bitmap_blocks_cnt;
848 data_blocks_cnt = s->virtual_disk_size >> s->block_size_bits;
849 if (s->virtual_disk_size - (data_blocks_cnt << s->block_size_bits)) {
850 data_blocks_cnt++;
852 bitmap_blocks_cnt = data_blocks_cnt >> s->chunk_ratio_bits;
853 if (data_blocks_cnt - (bitmap_blocks_cnt << s->chunk_ratio_bits)) {
854 bitmap_blocks_cnt++;
857 if (s->parent_entries) {
858 s->bat_entries = bitmap_blocks_cnt * (s->chunk_ratio + 1);
859 } else {
860 s->bat_entries = data_blocks_cnt +
861 ((data_blocks_cnt - 1) >> s->chunk_ratio_bits);
866 static void vhdx_close(BlockDriverState *bs)
868 BDRVVHDXState *s = bs->opaque;
869 qemu_vfree(s->headers[0]);
870 s->headers[0] = NULL;
871 qemu_vfree(s->headers[1]);
872 s->headers[1] = NULL;
873 qemu_vfree(s->bat);
874 s->bat = NULL;
875 qemu_vfree(s->parent_entries);
876 s->parent_entries = NULL;
877 migrate_del_blocker(s->migration_blocker);
878 error_free(s->migration_blocker);
879 qemu_vfree(s->log.hdr);
880 s->log.hdr = NULL;
881 vhdx_region_unregister_all(s);
884 static int vhdx_open(BlockDriverState *bs, QDict *options, int flags,
885 Error **errp)
887 BDRVVHDXState *s = bs->opaque;
888 int ret = 0;
889 uint32_t i;
890 uint64_t signature;
891 Error *local_err = NULL;
893 s->bat = NULL;
894 s->first_visible_write = true;
896 qemu_co_mutex_init(&s->lock);
897 QLIST_INIT(&s->regions);
899 /* validate the file signature */
900 ret = bdrv_pread(bs->file, 0, &signature, sizeof(uint64_t));
901 if (ret < 0) {
902 goto fail;
904 if (memcmp(&signature, "vhdxfile", 8)) {
905 ret = -EINVAL;
906 goto fail;
909 /* This is used for any header updates, for the file_write_guid.
910 * The spec dictates that a new value should be used for the first
911 * header update */
912 vhdx_guid_generate(&s->session_guid);
914 vhdx_parse_header(bs, s, &local_err);
915 if (local_err != NULL) {
916 error_propagate(errp, local_err);
917 ret = -EINVAL;
918 goto fail;
921 ret = vhdx_parse_log(bs, s, &s->log_replayed_on_open, errp);
922 if (ret < 0) {
923 goto fail;
926 ret = vhdx_open_region_tables(bs, s);
927 if (ret < 0) {
928 goto fail;
931 ret = vhdx_parse_metadata(bs, s);
932 if (ret < 0) {
933 goto fail;
936 s->block_size = s->params.block_size;
938 /* the VHDX spec dictates that virtual_disk_size is always a multiple of
939 * logical_sector_size */
940 bs->total_sectors = s->virtual_disk_size >> s->logical_sector_size_bits;
942 vhdx_calc_bat_entries(s);
944 s->bat_offset = s->bat_rt.file_offset;
946 if (s->bat_entries > s->bat_rt.length / sizeof(VHDXBatEntry)) {
947 /* BAT allocation is not large enough for all entries */
948 ret = -EINVAL;
949 goto fail;
952 /* s->bat is freed in vhdx_close() */
953 s->bat = qemu_blockalign(bs, s->bat_rt.length);
955 ret = bdrv_pread(bs->file, s->bat_offset, s->bat, s->bat_rt.length);
956 if (ret < 0) {
957 goto fail;
960 uint64_t payblocks = s->chunk_ratio;
961 /* endian convert, and verify populated BAT field file offsets against
962 * region table and log entries */
963 for (i = 0; i < s->bat_entries; i++) {
964 le64_to_cpus(&s->bat[i]);
965 if (payblocks--) {
966 /* payload bat entries */
967 if ((s->bat[i] & VHDX_BAT_STATE_BIT_MASK) ==
968 PAYLOAD_BLOCK_FULLY_PRESENT) {
969 ret = vhdx_region_check(s, s->bat[i] & VHDX_BAT_FILE_OFF_MASK,
970 s->block_size);
971 if (ret < 0) {
972 goto fail;
975 } else {
976 payblocks = s->chunk_ratio;
977 /* Once differencing files are supported, verify sector bitmap
978 * blocks here */
982 if (flags & BDRV_O_RDWR) {
983 ret = vhdx_update_headers(bs, s, false, NULL);
984 if (ret < 0) {
985 goto fail;
989 /* TODO: differencing files */
991 /* Disable migration when VHDX images are used */
992 error_set(&s->migration_blocker,
993 QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
994 "vhdx", bs->device_name, "live migration");
995 migrate_add_blocker(s->migration_blocker);
997 return 0;
998 fail:
999 vhdx_close(bs);
1000 return ret;
1003 static int vhdx_reopen_prepare(BDRVReopenState *state,
1004 BlockReopenQueue *queue, Error **errp)
1006 return 0;
1011 * Perform sector to block offset translations, to get various
1012 * sector and file offsets into the image. See VHDXSectorInfo
1014 static void vhdx_block_translate(BDRVVHDXState *s, int64_t sector_num,
1015 int nb_sectors, VHDXSectorInfo *sinfo)
1017 uint32_t block_offset;
1019 sinfo->bat_idx = sector_num >> s->sectors_per_block_bits;
1020 /* effectively a modulo - this gives us the offset into the block
1021 * (in sector sizes) for our sector number */
1022 block_offset = sector_num - (sinfo->bat_idx << s->sectors_per_block_bits);
1023 /* the chunk ratio gives us the interleaving of the sector
1024 * bitmaps, so we need to advance our page block index by the
1025 * sector bitmaps entry number */
1026 sinfo->bat_idx += sinfo->bat_idx >> s->chunk_ratio_bits;
1028 /* the number of sectors we can read/write in this cycle */
1029 sinfo->sectors_avail = s->sectors_per_block - block_offset;
1031 sinfo->bytes_left = sinfo->sectors_avail << s->logical_sector_size_bits;
1033 if (sinfo->sectors_avail > nb_sectors) {
1034 sinfo->sectors_avail = nb_sectors;
1037 sinfo->bytes_avail = sinfo->sectors_avail << s->logical_sector_size_bits;
1039 sinfo->file_offset = s->bat[sinfo->bat_idx] & VHDX_BAT_FILE_OFF_MASK;
1041 sinfo->block_offset = block_offset << s->logical_sector_size_bits;
1043 /* The file offset must be past the header section, so must be > 0 */
1044 if (sinfo->file_offset == 0) {
1045 return;
1048 /* block offset is the offset in vhdx logical sectors, in
1049 * the payload data block. Convert that to a byte offset
1050 * in the block, and add in the payload data block offset
1051 * in the file, in bytes, to get the final read address */
1053 sinfo->file_offset += sinfo->block_offset;
1057 static int vhdx_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1059 BDRVVHDXState *s = bs->opaque;
1061 bdi->cluster_size = s->block_size;
1063 bdi->unallocated_blocks_are_zero =
1064 (s->params.data_bits & VHDX_PARAMS_HAS_PARENT) == 0;
1066 return 0;
1070 static coroutine_fn int vhdx_co_readv(BlockDriverState *bs, int64_t sector_num,
1071 int nb_sectors, QEMUIOVector *qiov)
1073 BDRVVHDXState *s = bs->opaque;
1074 int ret = 0;
1075 VHDXSectorInfo sinfo;
1076 uint64_t bytes_done = 0;
1077 QEMUIOVector hd_qiov;
1079 qemu_iovec_init(&hd_qiov, qiov->niov);
1081 qemu_co_mutex_lock(&s->lock);
1083 while (nb_sectors > 0) {
1084 /* We are a differencing file, so we need to inspect the sector bitmap
1085 * to see if we have the data or not */
1086 if (s->params.data_bits & VHDX_PARAMS_HAS_PARENT) {
1087 /* not supported yet */
1088 ret = -ENOTSUP;
1089 goto exit;
1090 } else {
1091 vhdx_block_translate(s, sector_num, nb_sectors, &sinfo);
1093 qemu_iovec_reset(&hd_qiov);
1094 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, sinfo.bytes_avail);
1096 /* check the payload block state */
1097 switch (s->bat[sinfo.bat_idx] & VHDX_BAT_STATE_BIT_MASK) {
1098 case PAYLOAD_BLOCK_NOT_PRESENT: /* fall through */
1099 case PAYLOAD_BLOCK_UNDEFINED: /* fall through */
1100 case PAYLOAD_BLOCK_UNMAPPED: /* fall through */
1101 case PAYLOAD_BLOCK_ZERO:
1102 /* return zero */
1103 qemu_iovec_memset(&hd_qiov, 0, 0, sinfo.bytes_avail);
1104 break;
1105 case PAYLOAD_BLOCK_FULLY_PRESENT:
1106 qemu_co_mutex_unlock(&s->lock);
1107 ret = bdrv_co_readv(bs->file,
1108 sinfo.file_offset >> BDRV_SECTOR_BITS,
1109 sinfo.sectors_avail, &hd_qiov);
1110 qemu_co_mutex_lock(&s->lock);
1111 if (ret < 0) {
1112 goto exit;
1114 break;
1115 case PAYLOAD_BLOCK_PARTIALLY_PRESENT:
1116 /* we don't yet support difference files, fall through
1117 * to error */
1118 default:
1119 ret = -EIO;
1120 goto exit;
1121 break;
1123 nb_sectors -= sinfo.sectors_avail;
1124 sector_num += sinfo.sectors_avail;
1125 bytes_done += sinfo.bytes_avail;
1128 ret = 0;
1129 exit:
1130 qemu_co_mutex_unlock(&s->lock);
1131 qemu_iovec_destroy(&hd_qiov);
1132 return ret;
1136 * Allocate a new payload block at the end of the file.
1138 * Allocation will happen at 1MB alignment inside the file
1140 * Returns the file offset start of the new payload block
1142 static int vhdx_allocate_block(BlockDriverState *bs, BDRVVHDXState *s,
1143 uint64_t *new_offset)
1145 *new_offset = bdrv_getlength(bs->file);
1147 /* per the spec, the address for a block is in units of 1MB */
1148 *new_offset = ROUND_UP(*new_offset, 1024 * 1024);
1150 return bdrv_truncate(bs->file, *new_offset + s->block_size);
1154 * Update the BAT table entry with the new file offset, and the new entry
1155 * state */
1156 static void vhdx_update_bat_table_entry(BlockDriverState *bs, BDRVVHDXState *s,
1157 VHDXSectorInfo *sinfo,
1158 uint64_t *bat_entry_le,
1159 uint64_t *bat_offset, int state)
1161 /* The BAT entry is a uint64, with 44 bits for the file offset in units of
1162 * 1MB, and 3 bits for the block state. */
1163 s->bat[sinfo->bat_idx] = sinfo->file_offset;
1165 s->bat[sinfo->bat_idx] |= state & VHDX_BAT_STATE_BIT_MASK;
1167 *bat_entry_le = cpu_to_le64(s->bat[sinfo->bat_idx]);
1168 *bat_offset = s->bat_offset + sinfo->bat_idx * sizeof(VHDXBatEntry);
1172 /* Per the spec, on the first write of guest-visible data to the file the
1173 * data write guid must be updated in the header */
1174 int vhdx_user_visible_write(BlockDriverState *bs, BDRVVHDXState *s)
1176 int ret = 0;
1177 if (s->first_visible_write) {
1178 s->first_visible_write = false;
1179 ret = vhdx_update_headers(bs, s, true, NULL);
1181 return ret;
1184 static coroutine_fn int vhdx_co_writev(BlockDriverState *bs, int64_t sector_num,
1185 int nb_sectors, QEMUIOVector *qiov)
1187 int ret = -ENOTSUP;
1188 BDRVVHDXState *s = bs->opaque;
1189 VHDXSectorInfo sinfo;
1190 uint64_t bytes_done = 0;
1191 uint64_t bat_entry = 0;
1192 uint64_t bat_entry_offset = 0;
1193 QEMUIOVector hd_qiov;
1194 struct iovec iov1 = { 0 };
1195 struct iovec iov2 = { 0 };
1196 int sectors_to_write;
1197 int bat_state;
1198 uint64_t bat_prior_offset = 0;
1199 bool bat_update = false;
1201 qemu_iovec_init(&hd_qiov, qiov->niov);
1203 qemu_co_mutex_lock(&s->lock);
1205 ret = vhdx_user_visible_write(bs, s);
1206 if (ret < 0) {
1207 goto exit;
1210 while (nb_sectors > 0) {
1211 bool use_zero_buffers = false;
1212 bat_update = false;
1213 if (s->params.data_bits & VHDX_PARAMS_HAS_PARENT) {
1214 /* not supported yet */
1215 ret = -ENOTSUP;
1216 goto exit;
1217 } else {
1218 vhdx_block_translate(s, sector_num, nb_sectors, &sinfo);
1219 sectors_to_write = sinfo.sectors_avail;
1221 qemu_iovec_reset(&hd_qiov);
1222 /* check the payload block state */
1223 bat_state = s->bat[sinfo.bat_idx] & VHDX_BAT_STATE_BIT_MASK;
1224 switch (bat_state) {
1225 case PAYLOAD_BLOCK_ZERO:
1226 /* in this case, we need to preserve zero writes for
1227 * data that is not part of this write, so we must pad
1228 * the rest of the buffer to zeroes */
1230 /* if we are on a posix system with ftruncate() that extends
1231 * a file, then it is zero-filled for us. On Win32, the raw
1232 * layer uses SetFilePointer and SetFileEnd, which does not
1233 * zero fill AFAIK */
1235 /* Queue another write of zero buffers if the underlying file
1236 * does not zero-fill on file extension */
1238 if (bdrv_has_zero_init(bs->file) == 0) {
1239 use_zero_buffers = true;
1241 /* zero fill the front, if any */
1242 if (sinfo.block_offset) {
1243 iov1.iov_len = sinfo.block_offset;
1244 iov1.iov_base = qemu_blockalign(bs, iov1.iov_len);
1245 memset(iov1.iov_base, 0, iov1.iov_len);
1246 qemu_iovec_concat_iov(&hd_qiov, &iov1, 1, 0,
1247 sinfo.block_offset);
1248 sectors_to_write += iov1.iov_len >> BDRV_SECTOR_BITS;
1251 /* our actual data */
1252 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1253 sinfo.bytes_avail);
1255 /* zero fill the back, if any */
1256 if ((sinfo.bytes_avail - sinfo.block_offset) <
1257 s->block_size) {
1258 iov2.iov_len = s->block_size -
1259 (sinfo.bytes_avail + sinfo.block_offset);
1260 iov2.iov_base = qemu_blockalign(bs, iov2.iov_len);
1261 memset(iov2.iov_base, 0, iov2.iov_len);
1262 qemu_iovec_concat_iov(&hd_qiov, &iov2, 1, 0,
1263 sinfo.block_offset);
1264 sectors_to_write += iov2.iov_len >> BDRV_SECTOR_BITS;
1268 /* fall through */
1269 case PAYLOAD_BLOCK_NOT_PRESENT: /* fall through */
1270 case PAYLOAD_BLOCK_UNMAPPED: /* fall through */
1271 case PAYLOAD_BLOCK_UNDEFINED: /* fall through */
1272 bat_prior_offset = sinfo.file_offset;
1273 ret = vhdx_allocate_block(bs, s, &sinfo.file_offset);
1274 if (ret < 0) {
1275 goto exit;
1277 /* once we support differencing files, this may also be
1278 * partially present */
1279 /* update block state to the newly specified state */
1280 vhdx_update_bat_table_entry(bs, s, &sinfo, &bat_entry,
1281 &bat_entry_offset,
1282 PAYLOAD_BLOCK_FULLY_PRESENT);
1283 bat_update = true;
1284 /* since we just allocated a block, file_offset is the
1285 * beginning of the payload block. It needs to be the
1286 * write address, which includes the offset into the block */
1287 if (!use_zero_buffers) {
1288 sinfo.file_offset += sinfo.block_offset;
1290 /* fall through */
1291 case PAYLOAD_BLOCK_FULLY_PRESENT:
1292 /* if the file offset address is in the header zone,
1293 * there is a problem */
1294 if (sinfo.file_offset < (1024 * 1024)) {
1295 ret = -EFAULT;
1296 goto error_bat_restore;
1299 if (!use_zero_buffers) {
1300 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1301 sinfo.bytes_avail);
1303 /* block exists, so we can just overwrite it */
1304 qemu_co_mutex_unlock(&s->lock);
1305 ret = bdrv_co_writev(bs->file,
1306 sinfo.file_offset >> BDRV_SECTOR_BITS,
1307 sectors_to_write, &hd_qiov);
1308 qemu_co_mutex_lock(&s->lock);
1309 if (ret < 0) {
1310 goto error_bat_restore;
1312 break;
1313 case PAYLOAD_BLOCK_PARTIALLY_PRESENT:
1314 /* we don't yet support difference files, fall through
1315 * to error */
1316 default:
1317 ret = -EIO;
1318 goto exit;
1319 break;
1322 if (bat_update) {
1323 /* this will update the BAT entry into the log journal, and
1324 * then flush the log journal out to disk */
1325 ret = vhdx_log_write_and_flush(bs, s, &bat_entry,
1326 sizeof(VHDXBatEntry),
1327 bat_entry_offset);
1328 if (ret < 0) {
1329 goto exit;
1333 nb_sectors -= sinfo.sectors_avail;
1334 sector_num += sinfo.sectors_avail;
1335 bytes_done += sinfo.bytes_avail;
1340 goto exit;
1342 error_bat_restore:
1343 if (bat_update) {
1344 /* keep metadata in sync, and restore the bat entry state
1345 * if error. */
1346 sinfo.file_offset = bat_prior_offset;
1347 vhdx_update_bat_table_entry(bs, s, &sinfo, &bat_entry,
1348 &bat_entry_offset, bat_state);
1350 exit:
1351 qemu_vfree(iov1.iov_base);
1352 qemu_vfree(iov2.iov_base);
1353 qemu_co_mutex_unlock(&s->lock);
1354 qemu_iovec_destroy(&hd_qiov);
1355 return ret;
1361 * Create VHDX Headers
1363 * There are 2 headers, and the highest sequence number will represent
1364 * the active header
1366 static int vhdx_create_new_headers(BlockDriverState *bs, uint64_t image_size,
1367 uint32_t log_size)
1369 int ret = 0;
1370 VHDXHeader *hdr = NULL;
1372 hdr = g_malloc0(sizeof(VHDXHeader));
1374 hdr->signature = VHDX_HEADER_SIGNATURE;
1375 hdr->sequence_number = g_random_int();
1376 hdr->log_version = 0;
1377 hdr->version = 1;
1378 hdr->log_length = log_size;
1379 hdr->log_offset = VHDX_HEADER_SECTION_END;
1380 vhdx_guid_generate(&hdr->file_write_guid);
1381 vhdx_guid_generate(&hdr->data_write_guid);
1383 ret = vhdx_write_header(bs, hdr, VHDX_HEADER1_OFFSET, false);
1384 if (ret < 0) {
1385 goto exit;
1387 hdr->sequence_number++;
1388 ret = vhdx_write_header(bs, hdr, VHDX_HEADER2_OFFSET, false);
1389 if (ret < 0) {
1390 goto exit;
1393 exit:
1394 g_free(hdr);
1395 return ret;
1400 * Create the Metadata entries.
1402 * For more details on the entries, see section 3.5 (pg 29) in the
1403 * VHDX 1.00 specification.
1405 * We support 5 metadata entries (all required by spec):
1406 * File Parameters,
1407 * Virtual Disk Size,
1408 * Page 83 Data,
1409 * Logical Sector Size,
1410 * Physical Sector Size
1412 * The first 64KB of the Metadata section is reserved for the metadata
1413 * header and entries; beyond that, the metadata items themselves reside.
1415 static int vhdx_create_new_metadata(BlockDriverState *bs,
1416 uint64_t image_size,
1417 uint32_t block_size,
1418 uint32_t sector_size,
1419 uint64_t metadata_offset,
1420 VHDXImageType type)
1422 int ret = 0;
1423 uint32_t offset = 0;
1424 void *buffer = NULL;
1425 void *entry_buffer;
1426 VHDXMetadataTableHeader *md_table;;
1427 VHDXMetadataTableEntry *md_table_entry;
1429 /* Metadata entries */
1430 VHDXFileParameters *mt_file_params;
1431 VHDXVirtualDiskSize *mt_virtual_size;
1432 VHDXPage83Data *mt_page83;
1433 VHDXVirtualDiskLogicalSectorSize *mt_log_sector_size;
1434 VHDXVirtualDiskPhysicalSectorSize *mt_phys_sector_size;
1436 entry_buffer = g_malloc0(sizeof(VHDXFileParameters) +
1437 sizeof(VHDXVirtualDiskSize) +
1438 sizeof(VHDXPage83Data) +
1439 sizeof(VHDXVirtualDiskLogicalSectorSize) +
1440 sizeof(VHDXVirtualDiskPhysicalSectorSize));
1442 mt_file_params = entry_buffer;
1443 offset += sizeof(VHDXFileParameters);
1444 mt_virtual_size = entry_buffer + offset;
1445 offset += sizeof(VHDXVirtualDiskSize);
1446 mt_page83 = entry_buffer + offset;
1447 offset += sizeof(VHDXPage83Data);
1448 mt_log_sector_size = entry_buffer + offset;
1449 offset += sizeof(VHDXVirtualDiskLogicalSectorSize);
1450 mt_phys_sector_size = entry_buffer + offset;
1452 mt_file_params->block_size = cpu_to_le32(block_size);
1453 if (type == VHDX_TYPE_FIXED) {
1454 mt_file_params->data_bits |= VHDX_PARAMS_LEAVE_BLOCKS_ALLOCED;
1455 cpu_to_le32s(&mt_file_params->data_bits);
1458 vhdx_guid_generate(&mt_page83->page_83_data);
1459 cpu_to_leguids(&mt_page83->page_83_data);
1460 mt_virtual_size->virtual_disk_size = cpu_to_le64(image_size);
1461 mt_log_sector_size->logical_sector_size = cpu_to_le32(sector_size);
1462 mt_phys_sector_size->physical_sector_size = cpu_to_le32(sector_size);
1464 buffer = g_malloc0(VHDX_HEADER_BLOCK_SIZE);
1465 md_table = buffer;
1467 md_table->signature = VHDX_METADATA_SIGNATURE;
1468 md_table->entry_count = 5;
1469 vhdx_metadata_header_le_export(md_table);
1472 /* This will reference beyond the reserved table portion */
1473 offset = 64 * KiB;
1475 md_table_entry = buffer + sizeof(VHDXMetadataTableHeader);
1477 md_table_entry[0].item_id = file_param_guid;
1478 md_table_entry[0].offset = offset;
1479 md_table_entry[0].length = sizeof(VHDXFileParameters);
1480 md_table_entry[0].data_bits |= VHDX_META_FLAGS_IS_REQUIRED;
1481 offset += md_table_entry[0].length;
1482 vhdx_metadata_entry_le_export(&md_table_entry[0]);
1484 md_table_entry[1].item_id = virtual_size_guid;
1485 md_table_entry[1].offset = offset;
1486 md_table_entry[1].length = sizeof(VHDXVirtualDiskSize);
1487 md_table_entry[1].data_bits |= VHDX_META_FLAGS_IS_REQUIRED |
1488 VHDX_META_FLAGS_IS_VIRTUAL_DISK;
1489 offset += md_table_entry[1].length;
1490 vhdx_metadata_entry_le_export(&md_table_entry[1]);
1492 md_table_entry[2].item_id = page83_guid;
1493 md_table_entry[2].offset = offset;
1494 md_table_entry[2].length = sizeof(VHDXPage83Data);
1495 md_table_entry[2].data_bits |= VHDX_META_FLAGS_IS_REQUIRED |
1496 VHDX_META_FLAGS_IS_VIRTUAL_DISK;
1497 offset += md_table_entry[2].length;
1498 vhdx_metadata_entry_le_export(&md_table_entry[2]);
1500 md_table_entry[3].item_id = logical_sector_guid;
1501 md_table_entry[3].offset = offset;
1502 md_table_entry[3].length = sizeof(VHDXVirtualDiskLogicalSectorSize);
1503 md_table_entry[3].data_bits |= VHDX_META_FLAGS_IS_REQUIRED |
1504 VHDX_META_FLAGS_IS_VIRTUAL_DISK;
1505 offset += md_table_entry[3].length;
1506 vhdx_metadata_entry_le_export(&md_table_entry[3]);
1508 md_table_entry[4].item_id = phys_sector_guid;
1509 md_table_entry[4].offset = offset;
1510 md_table_entry[4].length = sizeof(VHDXVirtualDiskPhysicalSectorSize);
1511 md_table_entry[4].data_bits |= VHDX_META_FLAGS_IS_REQUIRED |
1512 VHDX_META_FLAGS_IS_VIRTUAL_DISK;
1513 vhdx_metadata_entry_le_export(&md_table_entry[4]);
1515 ret = bdrv_pwrite(bs, metadata_offset, buffer, VHDX_HEADER_BLOCK_SIZE);
1516 if (ret < 0) {
1517 goto exit;
1520 ret = bdrv_pwrite(bs, metadata_offset + (64 * KiB), entry_buffer,
1521 VHDX_HEADER_BLOCK_SIZE);
1522 if (ret < 0) {
1523 goto exit;
1527 exit:
1528 g_free(buffer);
1529 g_free(entry_buffer);
1530 return ret;
1533 /* This create the actual BAT itself. We currently only support
1534 * 'Dynamic' and 'Fixed' image types.
1536 * Dynamic images: default state of the BAT is all zeroes.
1538 * Fixed images: default state of the BAT is fully populated, with
1539 * file offsets and state PAYLOAD_BLOCK_FULLY_PRESENT.
1541 static int vhdx_create_bat(BlockDriverState *bs, BDRVVHDXState *s,
1542 uint64_t image_size, VHDXImageType type,
1543 bool use_zero_blocks, VHDXRegionTableEntry *rt_bat)
1545 int ret = 0;
1546 uint64_t data_file_offset;
1547 uint64_t total_sectors = 0;
1548 uint64_t sector_num = 0;
1549 uint64_t unused;
1550 int block_state;
1551 VHDXSectorInfo sinfo;
1553 assert(s->bat == NULL);
1555 /* this gives a data start after BAT/bitmap entries, and well
1556 * past any metadata entries (with a 4 MB buffer for future
1557 * expansion */
1558 data_file_offset = rt_bat->file_offset + rt_bat->length + 5 * MiB;
1559 total_sectors = image_size >> s->logical_sector_size_bits;
1561 if (type == VHDX_TYPE_DYNAMIC) {
1562 /* All zeroes, so we can just extend the file - the end of the BAT
1563 * is the furthest thing we have written yet */
1564 ret = bdrv_truncate(bs, data_file_offset);
1565 if (ret < 0) {
1566 goto exit;
1568 } else if (type == VHDX_TYPE_FIXED) {
1569 ret = bdrv_truncate(bs, data_file_offset + image_size);
1570 if (ret < 0) {
1571 goto exit;
1573 } else {
1574 ret = -ENOTSUP;
1575 goto exit;
1578 if (type == VHDX_TYPE_FIXED ||
1579 use_zero_blocks ||
1580 bdrv_has_zero_init(bs) == 0) {
1581 /* for a fixed file, the default BAT entry is not zero */
1582 s->bat = g_malloc0(rt_bat->length);
1583 block_state = type == VHDX_TYPE_FIXED ? PAYLOAD_BLOCK_FULLY_PRESENT :
1584 PAYLOAD_BLOCK_NOT_PRESENT;
1585 block_state = use_zero_blocks ? PAYLOAD_BLOCK_ZERO : block_state;
1586 /* fill the BAT by emulating sector writes of sectors_per_block size */
1587 while (sector_num < total_sectors) {
1588 vhdx_block_translate(s, sector_num, s->sectors_per_block, &sinfo);
1589 sinfo.file_offset = data_file_offset +
1590 (sector_num << s->logical_sector_size_bits);
1591 sinfo.file_offset = ROUND_UP(sinfo.file_offset, MiB);
1592 vhdx_update_bat_table_entry(bs, s, &sinfo, &unused, &unused,
1593 block_state);
1594 cpu_to_le64s(&s->bat[sinfo.bat_idx]);
1595 sector_num += s->sectors_per_block;
1597 ret = bdrv_pwrite(bs, rt_bat->file_offset, s->bat, rt_bat->length);
1598 if (ret < 0) {
1599 goto exit;
1605 exit:
1606 g_free(s->bat);
1607 return ret;
1610 /* Creates the region table header, and region table entries.
1611 * There are 2 supported region table entries: BAT, and Metadata/
1613 * As the calculations for the BAT region table are also needed
1614 * to create the BAT itself, we will also cause the BAT to be
1615 * created.
1617 static int vhdx_create_new_region_table(BlockDriverState *bs,
1618 uint64_t image_size,
1619 uint32_t block_size,
1620 uint32_t sector_size,
1621 uint32_t log_size,
1622 bool use_zero_blocks,
1623 VHDXImageType type,
1624 uint64_t *metadata_offset)
1626 int ret = 0;
1627 uint32_t offset = 0;
1628 void *buffer = NULL;
1629 BDRVVHDXState *s = NULL;
1630 VHDXRegionTableHeader *region_table;
1631 VHDXRegionTableEntry *rt_bat;
1632 VHDXRegionTableEntry *rt_metadata;
1634 assert(metadata_offset != NULL);
1636 /* Populate enough of the BDRVVHDXState to be able to use the
1637 * pre-existing BAT calculation, translation, and update functions */
1638 s = g_malloc0(sizeof(BDRVVHDXState));
1640 s->chunk_ratio = (VHDX_MAX_SECTORS_PER_BLOCK) *
1641 (uint64_t) sector_size / (uint64_t) block_size;
1643 s->sectors_per_block = block_size / sector_size;
1644 s->virtual_disk_size = image_size;
1645 s->block_size = block_size;
1646 s->logical_sector_size = sector_size;
1648 vhdx_set_shift_bits(s);
1650 vhdx_calc_bat_entries(s);
1652 /* At this point the VHDX state is populated enough for creation */
1654 /* a single buffer is used so we can calculate the checksum over the
1655 * entire 64KB block */
1656 buffer = g_malloc0(VHDX_HEADER_BLOCK_SIZE);
1657 region_table = buffer;
1658 offset += sizeof(VHDXRegionTableHeader);
1659 rt_bat = buffer + offset;
1660 offset += sizeof(VHDXRegionTableEntry);
1661 rt_metadata = buffer + offset;
1663 region_table->signature = VHDX_REGION_SIGNATURE;
1664 region_table->entry_count = 2; /* BAT and Metadata */
1666 rt_bat->guid = bat_guid;
1667 rt_bat->length = ROUND_UP(s->bat_entries * sizeof(VHDXBatEntry), MiB);
1668 rt_bat->file_offset = ROUND_UP(VHDX_HEADER_SECTION_END + log_size, MiB);
1669 s->bat_offset = rt_bat->file_offset;
1671 rt_metadata->guid = metadata_guid;
1672 rt_metadata->file_offset = ROUND_UP(rt_bat->file_offset + rt_bat->length,
1673 MiB);
1674 rt_metadata->length = 1 * MiB; /* min size, and more than enough */
1675 *metadata_offset = rt_metadata->file_offset;
1677 vhdx_update_checksum(buffer, VHDX_HEADER_BLOCK_SIZE,
1678 offsetof(VHDXRegionTableHeader, checksum));
1681 /* The region table gives us the data we need to create the BAT,
1682 * so do that now */
1683 ret = vhdx_create_bat(bs, s, image_size, type, use_zero_blocks, rt_bat);
1685 /* Now write out the region headers to disk */
1686 vhdx_region_header_le_export(region_table);
1687 vhdx_region_entry_le_export(rt_bat);
1688 vhdx_region_entry_le_export(rt_metadata);
1690 ret = bdrv_pwrite(bs, VHDX_REGION_TABLE_OFFSET, buffer,
1691 VHDX_HEADER_BLOCK_SIZE);
1692 if (ret < 0) {
1693 goto exit;
1696 ret = bdrv_pwrite(bs, VHDX_REGION_TABLE2_OFFSET, buffer,
1697 VHDX_HEADER_BLOCK_SIZE);
1698 if (ret < 0) {
1699 goto exit;
1703 exit:
1704 g_free(s);
1705 g_free(buffer);
1706 return ret;
1709 /* We need to create the following elements:
1711 * .-----------------------------------------------------------------.
1712 * | (A) | (B) | (C) | (D) | (E) |
1713 * | File ID | Header1 | Header 2 | Region Tbl 1 | Region Tbl 2 |
1714 * | | | | | |
1715 * .-----------------------------------------------------------------.
1716 * 0 64KB 128KB 192KB 256KB 320KB
1719 * .---- ~ ----------- ~ ------------ ~ ---------------- ~ -----------.
1720 * | (F) | (G) | (H) | |
1721 * | Journal Log | BAT / Bitmap | Metadata | .... data ...... |
1722 * | | | | |
1723 * .---- ~ ----------- ~ ------------ ~ ---------------- ~ -----------.
1724 * 1MB
1726 static int vhdx_create(const char *filename, QemuOpts *opts, Error **errp)
1728 int ret = 0;
1729 uint64_t image_size = (uint64_t) 2 * GiB;
1730 uint32_t log_size = 1 * MiB;
1731 uint32_t block_size = 0;
1732 uint64_t signature;
1733 uint64_t metadata_offset;
1734 bool use_zero_blocks = false;
1736 gunichar2 *creator = NULL;
1737 glong creator_items;
1738 BlockDriverState *bs;
1739 char *type = NULL;
1740 VHDXImageType image_type;
1741 Error *local_err = NULL;
1743 image_size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
1744 log_size = qemu_opt_get_size_del(opts, VHDX_BLOCK_OPT_LOG_SIZE, 0);
1745 block_size = qemu_opt_get_size_del(opts, VHDX_BLOCK_OPT_BLOCK_SIZE, 0);
1746 type = qemu_opt_get_del(opts, BLOCK_OPT_SUBFMT);
1747 use_zero_blocks = qemu_opt_get_bool_del(opts, VHDX_BLOCK_OPT_ZERO, false);
1749 if (image_size > VHDX_MAX_IMAGE_SIZE) {
1750 error_setg_errno(errp, EINVAL, "Image size too large; max of 64TB");
1751 ret = -EINVAL;
1752 goto exit;
1755 if (type == NULL) {
1756 type = g_strdup("dynamic");
1759 if (!strcmp(type, "dynamic")) {
1760 image_type = VHDX_TYPE_DYNAMIC;
1761 } else if (!strcmp(type, "fixed")) {
1762 image_type = VHDX_TYPE_FIXED;
1763 } else if (!strcmp(type, "differencing")) {
1764 error_setg_errno(errp, ENOTSUP,
1765 "Differencing files not yet supported");
1766 ret = -ENOTSUP;
1767 goto exit;
1768 } else {
1769 ret = -EINVAL;
1770 goto exit;
1773 /* These are pretty arbitrary, and mainly designed to keep the BAT
1774 * size reasonable to load into RAM */
1775 if (block_size == 0) {
1776 if (image_size > 32 * TiB) {
1777 block_size = 64 * MiB;
1778 } else if (image_size > (uint64_t) 100 * GiB) {
1779 block_size = 32 * MiB;
1780 } else if (image_size > 1 * GiB) {
1781 block_size = 16 * MiB;
1782 } else {
1783 block_size = 8 * MiB;
1788 /* make the log size close to what was specified, but must be
1789 * min 1MB, and multiple of 1MB */
1790 log_size = ROUND_UP(log_size, MiB);
1792 block_size = ROUND_UP(block_size, MiB);
1793 block_size = block_size > VHDX_BLOCK_SIZE_MAX ? VHDX_BLOCK_SIZE_MAX :
1794 block_size;
1796 ret = bdrv_create_file(filename, opts, &local_err);
1797 if (ret < 0) {
1798 error_propagate(errp, local_err);
1799 goto exit;
1802 bs = NULL;
1803 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1804 NULL, &local_err);
1805 if (ret < 0) {
1806 error_propagate(errp, local_err);
1807 goto exit;
1810 /* Create (A) */
1812 /* The creator field is optional, but may be useful for
1813 * debugging / diagnostics */
1814 creator = g_utf8_to_utf16("QEMU v" QEMU_VERSION, -1, NULL,
1815 &creator_items, NULL);
1816 signature = cpu_to_le64(VHDX_FILE_SIGNATURE);
1817 ret = bdrv_pwrite(bs, VHDX_FILE_ID_OFFSET, &signature, sizeof(signature));
1818 if (ret < 0) {
1819 goto delete_and_exit;
1821 if (creator) {
1822 ret = bdrv_pwrite(bs, VHDX_FILE_ID_OFFSET + sizeof(signature),
1823 creator, creator_items * sizeof(gunichar2));
1824 if (ret < 0) {
1825 goto delete_and_exit;
1830 /* Creates (B),(C) */
1831 ret = vhdx_create_new_headers(bs, image_size, log_size);
1832 if (ret < 0) {
1833 goto delete_and_exit;
1836 /* Creates (D),(E),(G) explicitly. (F) created as by-product */
1837 ret = vhdx_create_new_region_table(bs, image_size, block_size, 512,
1838 log_size, use_zero_blocks, image_type,
1839 &metadata_offset);
1840 if (ret < 0) {
1841 goto delete_and_exit;
1844 /* Creates (H) */
1845 ret = vhdx_create_new_metadata(bs, image_size, block_size, 512,
1846 metadata_offset, image_type);
1847 if (ret < 0) {
1848 goto delete_and_exit;
1853 delete_and_exit:
1854 bdrv_unref(bs);
1855 exit:
1856 g_free(type);
1857 g_free(creator);
1858 return ret;
1861 /* If opened r/w, the VHDX driver will automatically replay the log,
1862 * if one is present, inside the vhdx_open() call.
1864 * If qemu-img check -r all is called, the image is automatically opened
1865 * r/w and any log has already been replayed, so there is nothing (currently)
1866 * for us to do here
1868 static int vhdx_check(BlockDriverState *bs, BdrvCheckResult *result,
1869 BdrvCheckMode fix)
1871 BDRVVHDXState *s = bs->opaque;
1873 if (s->log_replayed_on_open) {
1874 result->corruptions_fixed++;
1876 return 0;
1879 static QemuOptsList vhdx_create_opts = {
1880 .name = "vhdx-create-opts",
1881 .head = QTAILQ_HEAD_INITIALIZER(vhdx_create_opts.head),
1882 .desc = {
1884 .name = BLOCK_OPT_SIZE,
1885 .type = QEMU_OPT_SIZE,
1886 .help = "Virtual disk size; max of 64TB."
1889 .name = VHDX_BLOCK_OPT_LOG_SIZE,
1890 .type = QEMU_OPT_SIZE,
1891 .def_value_str = stringify(DEFAULT_LOG_SIZE),
1892 .help = "Log size; min 1MB."
1895 .name = VHDX_BLOCK_OPT_BLOCK_SIZE,
1896 .type = QEMU_OPT_SIZE,
1897 .def_value_str = stringify(0),
1898 .help = "Block Size; min 1MB, max 256MB. " \
1899 "0 means auto-calculate based on image size."
1902 .name = BLOCK_OPT_SUBFMT,
1903 .type = QEMU_OPT_STRING,
1904 .help = "VHDX format type, can be either 'dynamic' or 'fixed'. "\
1905 "Default is 'dynamic'."
1908 .name = VHDX_BLOCK_OPT_ZERO,
1909 .type = QEMU_OPT_BOOL,
1910 .help = "Force use of payload blocks of type 'ZERO'. Non-standard."
1912 { NULL }
1916 static BlockDriver bdrv_vhdx = {
1917 .format_name = "vhdx",
1918 .instance_size = sizeof(BDRVVHDXState),
1919 .bdrv_probe = vhdx_probe,
1920 .bdrv_open = vhdx_open,
1921 .bdrv_close = vhdx_close,
1922 .bdrv_reopen_prepare = vhdx_reopen_prepare,
1923 .bdrv_co_readv = vhdx_co_readv,
1924 .bdrv_co_writev = vhdx_co_writev,
1925 .bdrv_create = vhdx_create,
1926 .bdrv_get_info = vhdx_get_info,
1927 .bdrv_check = vhdx_check,
1929 .create_opts = &vhdx_create_opts,
1932 static void bdrv_vhdx_init(void)
1934 bdrv_register(&bdrv_vhdx);
1937 block_init(bdrv_vhdx_init);