net: simplify net_init_tap_one logic
[qemu/ar7.git] / block / vhdx.c
blob9a51428317ab24562e2d03b6b4e357d977b0be86
1 /*
2 * Block driver for Hyper-V VHDX Images
4 * Copyright (c) 2013 Red Hat, Inc.,
6 * Authors:
7 * Jeff Cody <jcody@redhat.com>
9 * This is based on the "VHDX Format Specification v1.00", published 8/25/2012
10 * by Microsoft:
11 * https://www.microsoft.com/en-us/download/details.aspx?id=34750
13 * This work is licensed under the terms of the GNU LGPL, version 2 or later.
14 * See the COPYING.LIB file in the top-level directory.
18 #include "qemu/osdep.h"
19 #include "qemu-common.h"
20 #include "block/block_int.h"
21 #include "qemu/module.h"
22 #include "qemu/crc32c.h"
23 #include "block/vhdx.h"
24 #include "migration/migration.h"
26 #include <uuid/uuid.h>
27 #include <glib.h>
29 /* Options for VHDX creation */
31 #define VHDX_BLOCK_OPT_LOG_SIZE "log_size"
32 #define VHDX_BLOCK_OPT_BLOCK_SIZE "block_size"
33 #define VHDX_BLOCK_OPT_ZERO "block_state_zero"
35 typedef enum VHDXImageType {
36 VHDX_TYPE_DYNAMIC = 0,
37 VHDX_TYPE_FIXED,
38 VHDX_TYPE_DIFFERENCING, /* Currently unsupported */
39 } VHDXImageType;
41 /* Several metadata and region table data entries are identified by
42 * guids in a MS-specific GUID format. */
45 /* ------- Known Region Table GUIDs ---------------------- */
46 static const MSGUID bat_guid = { .data1 = 0x2dc27766,
47 .data2 = 0xf623,
48 .data3 = 0x4200,
49 .data4 = { 0x9d, 0x64, 0x11, 0x5e,
50 0x9b, 0xfd, 0x4a, 0x08} };
52 static const MSGUID metadata_guid = { .data1 = 0x8b7ca206,
53 .data2 = 0x4790,
54 .data3 = 0x4b9a,
55 .data4 = { 0xb8, 0xfe, 0x57, 0x5f,
56 0x05, 0x0f, 0x88, 0x6e} };
60 /* ------- Known Metadata Entry GUIDs ---------------------- */
61 static const MSGUID file_param_guid = { .data1 = 0xcaa16737,
62 .data2 = 0xfa36,
63 .data3 = 0x4d43,
64 .data4 = { 0xb3, 0xb6, 0x33, 0xf0,
65 0xaa, 0x44, 0xe7, 0x6b} };
67 static const MSGUID virtual_size_guid = { .data1 = 0x2FA54224,
68 .data2 = 0xcd1b,
69 .data3 = 0x4876,
70 .data4 = { 0xb2, 0x11, 0x5d, 0xbe,
71 0xd8, 0x3b, 0xf4, 0xb8} };
73 static const MSGUID page83_guid = { .data1 = 0xbeca12ab,
74 .data2 = 0xb2e6,
75 .data3 = 0x4523,
76 .data4 = { 0x93, 0xef, 0xc3, 0x09,
77 0xe0, 0x00, 0xc7, 0x46} };
80 static const MSGUID phys_sector_guid = { .data1 = 0xcda348c7,
81 .data2 = 0x445d,
82 .data3 = 0x4471,
83 .data4 = { 0x9c, 0xc9, 0xe9, 0x88,
84 0x52, 0x51, 0xc5, 0x56} };
86 static const MSGUID parent_locator_guid = { .data1 = 0xa8d35f2d,
87 .data2 = 0xb30b,
88 .data3 = 0x454d,
89 .data4 = { 0xab, 0xf7, 0xd3,
90 0xd8, 0x48, 0x34,
91 0xab, 0x0c} };
93 static const MSGUID logical_sector_guid = { .data1 = 0x8141bf1d,
94 .data2 = 0xa96f,
95 .data3 = 0x4709,
96 .data4 = { 0xba, 0x47, 0xf2,
97 0x33, 0xa8, 0xfa,
98 0xab, 0x5f} };
100 /* Each parent type must have a valid GUID; this is for parent images
101 * of type 'VHDX'. If we were to allow e.g. a QCOW2 parent, we would
102 * need to make up our own QCOW2 GUID type */
103 static const MSGUID parent_vhdx_guid __attribute__((unused))
104 = { .data1 = 0xb04aefb7,
105 .data2 = 0xd19e,
106 .data3 = 0x4a81,
107 .data4 = { 0xb7, 0x89, 0x25, 0xb8,
108 0xe9, 0x44, 0x59, 0x13} };
111 #define META_FILE_PARAMETER_PRESENT 0x01
112 #define META_VIRTUAL_DISK_SIZE_PRESENT 0x02
113 #define META_PAGE_83_PRESENT 0x04
114 #define META_LOGICAL_SECTOR_SIZE_PRESENT 0x08
115 #define META_PHYS_SECTOR_SIZE_PRESENT 0x10
116 #define META_PARENT_LOCATOR_PRESENT 0x20
118 #define META_ALL_PRESENT \
119 (META_FILE_PARAMETER_PRESENT | META_VIRTUAL_DISK_SIZE_PRESENT | \
120 META_PAGE_83_PRESENT | META_LOGICAL_SECTOR_SIZE_PRESENT | \
121 META_PHYS_SECTOR_SIZE_PRESENT)
124 typedef struct VHDXSectorInfo {
125 uint32_t bat_idx; /* BAT entry index */
126 uint32_t sectors_avail; /* sectors available in payload block */
127 uint32_t bytes_left; /* bytes left in the block after data to r/w */
128 uint32_t bytes_avail; /* bytes available in payload block */
129 uint64_t file_offset; /* absolute offset in bytes, in file */
130 uint64_t block_offset; /* block offset, in bytes */
131 } VHDXSectorInfo;
133 /* Calculates new checksum.
135 * Zero is substituted during crc calculation for the original crc field
136 * crc_offset: byte offset in buf of the buffer crc
137 * buf: buffer pointer
138 * size: size of buffer (must be > crc_offset+4)
140 * Note: The buffer should have all multi-byte data in little-endian format,
141 * and the resulting checksum is in little endian format.
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 cpu_to_le32s(&crc);
153 memcpy(buf + crc_offset, &crc, sizeof(crc));
155 return crc;
158 uint32_t vhdx_checksum_calc(uint32_t crc, uint8_t *buf, size_t size,
159 int crc_offset)
161 uint32_t crc_new;
162 uint32_t crc_orig;
163 assert(buf != NULL);
165 if (crc_offset > 0) {
166 memcpy(&crc_orig, buf + crc_offset, sizeof(crc_orig));
167 memset(buf + crc_offset, 0, sizeof(crc_orig));
170 crc_new = crc32c(crc, buf, size);
171 if (crc_offset > 0) {
172 memcpy(buf + crc_offset, &crc_orig, sizeof(crc_orig));
175 return crc_new;
178 /* Validates the checksum of the buffer, with an in-place CRC.
180 * Zero is substituted during crc calculation for the original crc field,
181 * and the crc field is restored afterwards. But the buffer will be modifed
182 * during the calculation, so this may not be not suitable for multi-threaded
183 * use.
185 * crc_offset: byte offset in buf of the buffer crc
186 * buf: buffer pointer
187 * size: size of buffer (must be > crc_offset+4)
189 * returns true if checksum is valid, false otherwise
191 bool vhdx_checksum_is_valid(uint8_t *buf, size_t size, int crc_offset)
193 uint32_t crc_orig;
194 uint32_t crc;
196 assert(buf != NULL);
197 assert(size > (crc_offset + 4));
199 memcpy(&crc_orig, buf + crc_offset, sizeof(crc_orig));
200 crc_orig = le32_to_cpu(crc_orig);
202 crc = vhdx_checksum_calc(0xffffffff, buf, size, crc_offset);
204 return crc == crc_orig;
209 * This generates a UUID that is compliant with the MS GUIDs used
210 * in the VHDX spec (and elsewhere).
212 void vhdx_guid_generate(MSGUID *guid)
214 uuid_t uuid;
215 assert(guid != NULL);
217 uuid_generate(uuid);
218 memcpy(guid, uuid, sizeof(MSGUID));
221 /* Check for region overlaps inside the VHDX image */
222 static int vhdx_region_check(BDRVVHDXState *s, uint64_t start, uint64_t length)
224 int ret = 0;
225 uint64_t end;
226 VHDXRegionEntry *r;
228 end = start + length;
229 QLIST_FOREACH(r, &s->regions, entries) {
230 if (!((start >= r->end) || (end <= r->start))) {
231 ret = -EINVAL;
232 goto exit;
236 exit:
237 return ret;
240 /* Register a region for future checks */
241 static void vhdx_region_register(BDRVVHDXState *s,
242 uint64_t start, uint64_t length)
244 VHDXRegionEntry *r;
246 r = g_malloc0(sizeof(*r));
248 r->start = start;
249 r->end = start + length;
251 QLIST_INSERT_HEAD(&s->regions, r, entries);
254 /* Free all registered regions */
255 static void vhdx_region_unregister_all(BDRVVHDXState *s)
257 VHDXRegionEntry *r, *r_next;
259 QLIST_FOREACH_SAFE(r, &s->regions, entries, r_next) {
260 QLIST_REMOVE(r, entries);
261 g_free(r);
265 static void vhdx_set_shift_bits(BDRVVHDXState *s)
267 s->logical_sector_size_bits = ctz32(s->logical_sector_size);
268 s->sectors_per_block_bits = ctz32(s->sectors_per_block);
269 s->chunk_ratio_bits = ctz64(s->chunk_ratio);
270 s->block_size_bits = ctz32(s->block_size);
274 * Per the MS VHDX Specification, for every VHDX file:
275 * - The header section is fixed size - 1 MB
276 * - The header section is always the first "object"
277 * - The first 64KB of the header is the File Identifier
278 * - The first uint64 (8 bytes) is the VHDX Signature ("vhdxfile")
279 * - The following 512 bytes constitute a UTF-16 string identifiying the
280 * software that created the file, and is optional and diagnostic only.
282 * Therefore, we probe by looking for the vhdxfile signature "vhdxfile"
284 static int vhdx_probe(const uint8_t *buf, int buf_size, const char *filename)
286 if (buf_size >= 8 && !memcmp(buf, "vhdxfile", 8)) {
287 return 100;
289 return 0;
293 * Writes the header to the specified offset.
295 * This will optionally read in buffer data from disk (otherwise zero-fill),
296 * and then update the header checksum. Header is converted to proper
297 * endianness before being written to the specified file offset
299 static int vhdx_write_header(BlockDriverState *bs_file, VHDXHeader *hdr,
300 uint64_t offset, bool read)
302 uint8_t *buffer = NULL;
303 int ret;
304 VHDXHeader *header_le;
306 assert(bs_file != NULL);
307 assert(hdr != NULL);
309 /* the header checksum is not over just the packed size of VHDXHeader,
310 * but rather over the entire 'reserved' range for the header, which is
311 * 4KB (VHDX_HEADER_SIZE). */
313 buffer = qemu_blockalign(bs_file, VHDX_HEADER_SIZE);
314 if (read) {
315 /* if true, we can't assume the extra reserved bytes are 0 */
316 ret = bdrv_pread(bs_file, offset, buffer, VHDX_HEADER_SIZE);
317 if (ret < 0) {
318 goto exit;
320 } else {
321 memset(buffer, 0, VHDX_HEADER_SIZE);
324 /* overwrite the actual VHDXHeader portion */
325 header_le = (VHDXHeader *)buffer;
326 memcpy(header_le, hdr, sizeof(VHDXHeader));
327 vhdx_header_le_export(hdr, header_le);
328 vhdx_update_checksum(buffer, VHDX_HEADER_SIZE,
329 offsetof(VHDXHeader, checksum));
330 ret = bdrv_pwrite_sync(bs_file, offset, header_le, sizeof(VHDXHeader));
332 exit:
333 qemu_vfree(buffer);
334 return ret;
337 /* Update the VHDX headers
339 * This follows the VHDX spec procedures for header updates.
341 * - non-current header is updated with largest sequence number
343 static int vhdx_update_header(BlockDriverState *bs, BDRVVHDXState *s,
344 bool generate_data_write_guid, MSGUID *log_guid)
346 int ret = 0;
347 int hdr_idx = 0;
348 uint64_t header_offset = VHDX_HEADER1_OFFSET;
350 VHDXHeader *active_header;
351 VHDXHeader *inactive_header;
353 /* operate on the non-current header */
354 if (s->curr_header == 0) {
355 hdr_idx = 1;
356 header_offset = VHDX_HEADER2_OFFSET;
359 active_header = s->headers[s->curr_header];
360 inactive_header = s->headers[hdr_idx];
362 inactive_header->sequence_number = active_header->sequence_number + 1;
364 /* a new file guid must be generated before any file write, including
365 * headers */
366 inactive_header->file_write_guid = s->session_guid;
368 /* a new data guid only needs to be generated before any guest-visible
369 * writes (i.e. something observable via virtual disk read) */
370 if (generate_data_write_guid) {
371 vhdx_guid_generate(&inactive_header->data_write_guid);
374 /* update the log guid if present */
375 if (log_guid) {
376 inactive_header->log_guid = *log_guid;
379 ret = vhdx_write_header(bs->file->bs, inactive_header, header_offset, true);
380 if (ret < 0) {
381 goto exit;
383 s->curr_header = hdr_idx;
385 exit:
386 return ret;
390 * The VHDX spec calls for header updates to be performed twice, so that both
391 * the current and non-current header have valid info
393 int vhdx_update_headers(BlockDriverState *bs, BDRVVHDXState *s,
394 bool generate_data_write_guid, MSGUID *log_guid)
396 int ret;
398 ret = vhdx_update_header(bs, s, generate_data_write_guid, log_guid);
399 if (ret < 0) {
400 return ret;
402 ret = vhdx_update_header(bs, s, generate_data_write_guid, log_guid);
403 return ret;
406 /* opens the specified header block from the VHDX file header section */
407 static void vhdx_parse_header(BlockDriverState *bs, BDRVVHDXState *s,
408 Error **errp)
410 int ret;
411 VHDXHeader *header1;
412 VHDXHeader *header2;
413 bool h1_valid = false;
414 bool h2_valid = false;
415 uint64_t h1_seq = 0;
416 uint64_t h2_seq = 0;
417 uint8_t *buffer;
419 /* header1 & header2 are freed in vhdx_close() */
420 header1 = qemu_blockalign(bs, sizeof(VHDXHeader));
421 header2 = qemu_blockalign(bs, sizeof(VHDXHeader));
423 buffer = qemu_blockalign(bs, VHDX_HEADER_SIZE);
425 s->headers[0] = header1;
426 s->headers[1] = header2;
428 /* We have to read the whole VHDX_HEADER_SIZE instead of
429 * sizeof(VHDXHeader), because the checksum is over the whole
430 * region */
431 ret = bdrv_pread(bs->file->bs, VHDX_HEADER1_OFFSET, buffer,
432 VHDX_HEADER_SIZE);
433 if (ret < 0) {
434 goto fail;
436 /* copy over just the relevant portion that we need */
437 memcpy(header1, buffer, sizeof(VHDXHeader));
439 if (vhdx_checksum_is_valid(buffer, VHDX_HEADER_SIZE, 4)) {
440 vhdx_header_le_import(header1);
441 if (header1->signature == VHDX_HEADER_SIGNATURE &&
442 header1->version == 1) {
443 h1_seq = header1->sequence_number;
444 h1_valid = true;
448 ret = bdrv_pread(bs->file->bs, VHDX_HEADER2_OFFSET, buffer,
449 VHDX_HEADER_SIZE);
450 if (ret < 0) {
451 goto fail;
453 /* copy over just the relevant portion that we need */
454 memcpy(header2, buffer, sizeof(VHDXHeader));
456 if (vhdx_checksum_is_valid(buffer, VHDX_HEADER_SIZE, 4)) {
457 vhdx_header_le_import(header2);
458 if (header2->signature == VHDX_HEADER_SIGNATURE &&
459 header2->version == 1) {
460 h2_seq = header2->sequence_number;
461 h2_valid = true;
465 /* If there is only 1 valid header (or no valid headers), we
466 * don't care what the sequence numbers are */
467 if (h1_valid && !h2_valid) {
468 s->curr_header = 0;
469 } else if (!h1_valid && h2_valid) {
470 s->curr_header = 1;
471 } else if (!h1_valid && !h2_valid) {
472 goto fail;
473 } else {
474 /* If both headers are valid, then we choose the active one by the
475 * highest sequence number. If the sequence numbers are equal, that is
476 * invalid */
477 if (h1_seq > h2_seq) {
478 s->curr_header = 0;
479 } else if (h2_seq > h1_seq) {
480 s->curr_header = 1;
481 } else {
482 /* The Microsoft Disk2VHD tool will create 2 identical
483 * headers, with identical sequence numbers. If the headers are
484 * identical, don't consider the file corrupt */
485 if (!memcmp(header1, header2, sizeof(VHDXHeader))) {
486 s->curr_header = 0;
487 } else {
488 goto fail;
493 vhdx_region_register(s, s->headers[s->curr_header]->log_offset,
494 s->headers[s->curr_header]->log_length);
495 goto exit;
497 fail:
498 error_setg_errno(errp, -ret, "No valid VHDX header found");
499 qemu_vfree(header1);
500 qemu_vfree(header2);
501 s->headers[0] = NULL;
502 s->headers[1] = NULL;
503 exit:
504 qemu_vfree(buffer);
508 static int vhdx_open_region_tables(BlockDriverState *bs, BDRVVHDXState *s)
510 int ret = 0;
511 uint8_t *buffer;
512 int offset = 0;
513 VHDXRegionTableEntry rt_entry;
514 uint32_t i;
515 bool bat_rt_found = false;
516 bool metadata_rt_found = false;
518 /* We have to read the whole 64KB block, because the crc32 is over the
519 * whole block */
520 buffer = qemu_blockalign(bs, VHDX_HEADER_BLOCK_SIZE);
522 ret = bdrv_pread(bs->file->bs, VHDX_REGION_TABLE_OFFSET, buffer,
523 VHDX_HEADER_BLOCK_SIZE);
524 if (ret < 0) {
525 goto fail;
527 memcpy(&s->rt, buffer, sizeof(s->rt));
528 offset += sizeof(s->rt);
530 if (!vhdx_checksum_is_valid(buffer, VHDX_HEADER_BLOCK_SIZE, 4)) {
531 ret = -EINVAL;
532 goto fail;
535 vhdx_region_header_le_import(&s->rt);
537 if (s->rt.signature != VHDX_REGION_SIGNATURE) {
538 ret = -EINVAL;
539 goto fail;
543 /* Per spec, maximum region table entry count is 2047 */
544 if (s->rt.entry_count > 2047) {
545 ret = -EINVAL;
546 goto fail;
549 for (i = 0; i < s->rt.entry_count; i++) {
550 memcpy(&rt_entry, buffer + offset, sizeof(rt_entry));
551 offset += sizeof(rt_entry);
553 vhdx_region_entry_le_import(&rt_entry);
555 /* check for region overlap between these entries, and any
556 * other memory regions in the file */
557 ret = vhdx_region_check(s, rt_entry.file_offset, rt_entry.length);
558 if (ret < 0) {
559 goto fail;
562 vhdx_region_register(s, rt_entry.file_offset, rt_entry.length);
564 /* see if we recognize the entry */
565 if (guid_eq(rt_entry.guid, bat_guid)) {
566 /* must be unique; if we have already found it this is invalid */
567 if (bat_rt_found) {
568 ret = -EINVAL;
569 goto fail;
571 bat_rt_found = true;
572 s->bat_rt = rt_entry;
573 continue;
576 if (guid_eq(rt_entry.guid, metadata_guid)) {
577 /* must be unique; if we have already found it this is invalid */
578 if (metadata_rt_found) {
579 ret = -EINVAL;
580 goto fail;
582 metadata_rt_found = true;
583 s->metadata_rt = rt_entry;
584 continue;
587 if (rt_entry.data_bits & VHDX_REGION_ENTRY_REQUIRED) {
588 /* cannot read vhdx file - required region table entry that
589 * we do not understand. per spec, we must fail to open */
590 ret = -ENOTSUP;
591 goto fail;
595 if (!bat_rt_found || !metadata_rt_found) {
596 ret = -EINVAL;
597 goto fail;
600 ret = 0;
602 fail:
603 qemu_vfree(buffer);
604 return ret;
609 /* Metadata initial parser
611 * This loads all the metadata entry fields. This may cause additional
612 * fields to be processed (e.g. parent locator, etc..).
614 * There are 5 Metadata items that are always required:
615 * - File Parameters (block size, has a parent)
616 * - Virtual Disk Size (size, in bytes, of the virtual drive)
617 * - Page 83 Data (scsi page 83 guid)
618 * - Logical Sector Size (logical sector size in bytes, either 512 or
619 * 4096. We only support 512 currently)
620 * - Physical Sector Size (512 or 4096)
622 * Also, if the File Parameters indicate this is a differencing file,
623 * we must also look for the Parent Locator metadata item.
625 static int vhdx_parse_metadata(BlockDriverState *bs, BDRVVHDXState *s)
627 int ret = 0;
628 uint8_t *buffer;
629 int offset = 0;
630 uint32_t i = 0;
631 VHDXMetadataTableEntry md_entry;
633 buffer = qemu_blockalign(bs, VHDX_METADATA_TABLE_MAX_SIZE);
635 ret = bdrv_pread(bs->file->bs, s->metadata_rt.file_offset, buffer,
636 VHDX_METADATA_TABLE_MAX_SIZE);
637 if (ret < 0) {
638 goto exit;
640 memcpy(&s->metadata_hdr, buffer, sizeof(s->metadata_hdr));
641 offset += sizeof(s->metadata_hdr);
643 vhdx_metadata_header_le_import(&s->metadata_hdr);
645 if (s->metadata_hdr.signature != VHDX_METADATA_SIGNATURE) {
646 ret = -EINVAL;
647 goto exit;
650 s->metadata_entries.present = 0;
652 if ((s->metadata_hdr.entry_count * sizeof(md_entry)) >
653 (VHDX_METADATA_TABLE_MAX_SIZE - offset)) {
654 ret = -EINVAL;
655 goto exit;
658 for (i = 0; i < s->metadata_hdr.entry_count; i++) {
659 memcpy(&md_entry, buffer + offset, sizeof(md_entry));
660 offset += sizeof(md_entry);
662 vhdx_metadata_entry_le_import(&md_entry);
664 if (guid_eq(md_entry.item_id, file_param_guid)) {
665 if (s->metadata_entries.present & META_FILE_PARAMETER_PRESENT) {
666 ret = -EINVAL;
667 goto exit;
669 s->metadata_entries.file_parameters_entry = md_entry;
670 s->metadata_entries.present |= META_FILE_PARAMETER_PRESENT;
671 continue;
674 if (guid_eq(md_entry.item_id, virtual_size_guid)) {
675 if (s->metadata_entries.present & META_VIRTUAL_DISK_SIZE_PRESENT) {
676 ret = -EINVAL;
677 goto exit;
679 s->metadata_entries.virtual_disk_size_entry = md_entry;
680 s->metadata_entries.present |= META_VIRTUAL_DISK_SIZE_PRESENT;
681 continue;
684 if (guid_eq(md_entry.item_id, page83_guid)) {
685 if (s->metadata_entries.present & META_PAGE_83_PRESENT) {
686 ret = -EINVAL;
687 goto exit;
689 s->metadata_entries.page83_data_entry = md_entry;
690 s->metadata_entries.present |= META_PAGE_83_PRESENT;
691 continue;
694 if (guid_eq(md_entry.item_id, logical_sector_guid)) {
695 if (s->metadata_entries.present &
696 META_LOGICAL_SECTOR_SIZE_PRESENT) {
697 ret = -EINVAL;
698 goto exit;
700 s->metadata_entries.logical_sector_size_entry = md_entry;
701 s->metadata_entries.present |= META_LOGICAL_SECTOR_SIZE_PRESENT;
702 continue;
705 if (guid_eq(md_entry.item_id, phys_sector_guid)) {
706 if (s->metadata_entries.present & META_PHYS_SECTOR_SIZE_PRESENT) {
707 ret = -EINVAL;
708 goto exit;
710 s->metadata_entries.phys_sector_size_entry = md_entry;
711 s->metadata_entries.present |= META_PHYS_SECTOR_SIZE_PRESENT;
712 continue;
715 if (guid_eq(md_entry.item_id, parent_locator_guid)) {
716 if (s->metadata_entries.present & META_PARENT_LOCATOR_PRESENT) {
717 ret = -EINVAL;
718 goto exit;
720 s->metadata_entries.parent_locator_entry = md_entry;
721 s->metadata_entries.present |= META_PARENT_LOCATOR_PRESENT;
722 continue;
725 if (md_entry.data_bits & VHDX_META_FLAGS_IS_REQUIRED) {
726 /* cannot read vhdx file - required region table entry that
727 * we do not understand. per spec, we must fail to open */
728 ret = -ENOTSUP;
729 goto exit;
733 if (s->metadata_entries.present != META_ALL_PRESENT) {
734 ret = -ENOTSUP;
735 goto exit;
738 ret = bdrv_pread(bs->file->bs,
739 s->metadata_entries.file_parameters_entry.offset
740 + s->metadata_rt.file_offset,
741 &s->params,
742 sizeof(s->params));
744 if (ret < 0) {
745 goto exit;
748 le32_to_cpus(&s->params.block_size);
749 le32_to_cpus(&s->params.data_bits);
752 /* We now have the file parameters, so we can tell if this is a
753 * differencing file (i.e.. has_parent), is dynamic or fixed
754 * sized (leave_blocks_allocated), and the block size */
756 /* The parent locator required iff the file parameters has_parent set */
757 if (s->params.data_bits & VHDX_PARAMS_HAS_PARENT) {
758 if (s->metadata_entries.present & META_PARENT_LOCATOR_PRESENT) {
759 /* TODO: parse parent locator fields */
760 ret = -ENOTSUP; /* temp, until differencing files are supported */
761 goto exit;
762 } else {
763 /* if has_parent is set, but there is not parent locator present,
764 * then that is an invalid combination */
765 ret = -EINVAL;
766 goto exit;
770 /* determine virtual disk size, logical sector size,
771 * and phys sector size */
773 ret = bdrv_pread(bs->file->bs,
774 s->metadata_entries.virtual_disk_size_entry.offset
775 + s->metadata_rt.file_offset,
776 &s->virtual_disk_size,
777 sizeof(uint64_t));
778 if (ret < 0) {
779 goto exit;
781 ret = bdrv_pread(bs->file->bs,
782 s->metadata_entries.logical_sector_size_entry.offset
783 + s->metadata_rt.file_offset,
784 &s->logical_sector_size,
785 sizeof(uint32_t));
786 if (ret < 0) {
787 goto exit;
789 ret = bdrv_pread(bs->file->bs,
790 s->metadata_entries.phys_sector_size_entry.offset
791 + s->metadata_rt.file_offset,
792 &s->physical_sector_size,
793 sizeof(uint32_t));
794 if (ret < 0) {
795 goto exit;
798 le64_to_cpus(&s->virtual_disk_size);
799 le32_to_cpus(&s->logical_sector_size);
800 le32_to_cpus(&s->physical_sector_size);
802 if (s->params.block_size < VHDX_BLOCK_SIZE_MIN ||
803 s->params.block_size > VHDX_BLOCK_SIZE_MAX) {
804 ret = -EINVAL;
805 goto exit;
808 /* only 2 supported sector sizes */
809 if (s->logical_sector_size != 512 && s->logical_sector_size != 4096) {
810 ret = -EINVAL;
811 goto exit;
814 /* Both block_size and sector_size are guaranteed powers of 2, below.
815 Due to range checks above, s->sectors_per_block can never be < 256 */
816 s->sectors_per_block = s->params.block_size / s->logical_sector_size;
817 s->chunk_ratio = (VHDX_MAX_SECTORS_PER_BLOCK) *
818 (uint64_t)s->logical_sector_size /
819 (uint64_t)s->params.block_size;
821 /* These values are ones we will want to use for division / multiplication
822 * later on, and they are all guaranteed (per the spec) to be powers of 2,
823 * so we can take advantage of that for shift operations during
824 * reads/writes */
825 if (s->logical_sector_size & (s->logical_sector_size - 1)) {
826 ret = -EINVAL;
827 goto exit;
829 if (s->sectors_per_block & (s->sectors_per_block - 1)) {
830 ret = -EINVAL;
831 goto exit;
833 if (s->chunk_ratio & (s->chunk_ratio - 1)) {
834 ret = -EINVAL;
835 goto exit;
837 s->block_size = s->params.block_size;
838 if (s->block_size & (s->block_size - 1)) {
839 ret = -EINVAL;
840 goto exit;
843 vhdx_set_shift_bits(s);
845 ret = 0;
847 exit:
848 qemu_vfree(buffer);
849 return ret;
853 * Calculate the number of BAT entries, including sector
854 * bitmap entries.
856 static void vhdx_calc_bat_entries(BDRVVHDXState *s)
858 uint32_t data_blocks_cnt, bitmap_blocks_cnt;
860 data_blocks_cnt = DIV_ROUND_UP(s->virtual_disk_size, s->block_size);
861 bitmap_blocks_cnt = DIV_ROUND_UP(data_blocks_cnt, s->chunk_ratio);
863 if (s->parent_entries) {
864 s->bat_entries = bitmap_blocks_cnt * (s->chunk_ratio + 1);
865 } else {
866 s->bat_entries = data_blocks_cnt +
867 ((data_blocks_cnt - 1) >> s->chunk_ratio_bits);
872 static void vhdx_close(BlockDriverState *bs)
874 BDRVVHDXState *s = bs->opaque;
875 qemu_vfree(s->headers[0]);
876 s->headers[0] = NULL;
877 qemu_vfree(s->headers[1]);
878 s->headers[1] = NULL;
879 qemu_vfree(s->bat);
880 s->bat = NULL;
881 qemu_vfree(s->parent_entries);
882 s->parent_entries = NULL;
883 migrate_del_blocker(s->migration_blocker);
884 error_free(s->migration_blocker);
885 qemu_vfree(s->log.hdr);
886 s->log.hdr = NULL;
887 vhdx_region_unregister_all(s);
890 static int vhdx_open(BlockDriverState *bs, QDict *options, int flags,
891 Error **errp)
893 BDRVVHDXState *s = bs->opaque;
894 int ret = 0;
895 uint32_t i;
896 uint64_t signature;
897 Error *local_err = NULL;
899 s->bat = NULL;
900 s->first_visible_write = true;
902 qemu_co_mutex_init(&s->lock);
903 QLIST_INIT(&s->regions);
905 /* validate the file signature */
906 ret = bdrv_pread(bs->file->bs, 0, &signature, sizeof(uint64_t));
907 if (ret < 0) {
908 goto fail;
910 if (memcmp(&signature, "vhdxfile", 8)) {
911 ret = -EINVAL;
912 goto fail;
915 /* This is used for any header updates, for the file_write_guid.
916 * The spec dictates that a new value should be used for the first
917 * header update */
918 vhdx_guid_generate(&s->session_guid);
920 vhdx_parse_header(bs, s, &local_err);
921 if (local_err != NULL) {
922 error_propagate(errp, local_err);
923 ret = -EINVAL;
924 goto fail;
927 ret = vhdx_parse_log(bs, s, &s->log_replayed_on_open, errp);
928 if (ret < 0) {
929 goto fail;
932 ret = vhdx_open_region_tables(bs, s);
933 if (ret < 0) {
934 goto fail;
937 ret = vhdx_parse_metadata(bs, s);
938 if (ret < 0) {
939 goto fail;
942 s->block_size = s->params.block_size;
944 /* the VHDX spec dictates that virtual_disk_size is always a multiple of
945 * logical_sector_size */
946 bs->total_sectors = s->virtual_disk_size >> s->logical_sector_size_bits;
948 vhdx_calc_bat_entries(s);
950 s->bat_offset = s->bat_rt.file_offset;
952 if (s->bat_entries > s->bat_rt.length / sizeof(VHDXBatEntry)) {
953 /* BAT allocation is not large enough for all entries */
954 ret = -EINVAL;
955 goto fail;
958 /* s->bat is freed in vhdx_close() */
959 s->bat = qemu_try_blockalign(bs->file->bs, s->bat_rt.length);
960 if (s->bat == NULL) {
961 ret = -ENOMEM;
962 goto fail;
965 ret = bdrv_pread(bs->file->bs, s->bat_offset, s->bat, s->bat_rt.length);
966 if (ret < 0) {
967 goto fail;
970 uint64_t payblocks = s->chunk_ratio;
971 /* endian convert, and verify populated BAT field file offsets against
972 * region table and log entries */
973 for (i = 0; i < s->bat_entries; i++) {
974 le64_to_cpus(&s->bat[i]);
975 if (payblocks--) {
976 /* payload bat entries */
977 if ((s->bat[i] & VHDX_BAT_STATE_BIT_MASK) ==
978 PAYLOAD_BLOCK_FULLY_PRESENT) {
979 ret = vhdx_region_check(s, s->bat[i] & VHDX_BAT_FILE_OFF_MASK,
980 s->block_size);
981 if (ret < 0) {
982 goto fail;
985 } else {
986 payblocks = s->chunk_ratio;
987 /* Once differencing files are supported, verify sector bitmap
988 * blocks here */
992 if (flags & BDRV_O_RDWR) {
993 ret = vhdx_update_headers(bs, s, false, NULL);
994 if (ret < 0) {
995 goto fail;
999 /* TODO: differencing files */
1001 /* Disable migration when VHDX images are used */
1002 error_setg(&s->migration_blocker, "The vhdx format used by node '%s' "
1003 "does not support live migration",
1004 bdrv_get_device_or_node_name(bs));
1005 migrate_add_blocker(s->migration_blocker);
1007 return 0;
1008 fail:
1009 vhdx_close(bs);
1010 return ret;
1013 static int vhdx_reopen_prepare(BDRVReopenState *state,
1014 BlockReopenQueue *queue, Error **errp)
1016 return 0;
1021 * Perform sector to block offset translations, to get various
1022 * sector and file offsets into the image. See VHDXSectorInfo
1024 static void vhdx_block_translate(BDRVVHDXState *s, int64_t sector_num,
1025 int nb_sectors, VHDXSectorInfo *sinfo)
1027 uint32_t block_offset;
1029 sinfo->bat_idx = sector_num >> s->sectors_per_block_bits;
1030 /* effectively a modulo - this gives us the offset into the block
1031 * (in sector sizes) for our sector number */
1032 block_offset = sector_num - (sinfo->bat_idx << s->sectors_per_block_bits);
1033 /* the chunk ratio gives us the interleaving of the sector
1034 * bitmaps, so we need to advance our page block index by the
1035 * sector bitmaps entry number */
1036 sinfo->bat_idx += sinfo->bat_idx >> s->chunk_ratio_bits;
1038 /* the number of sectors we can read/write in this cycle */
1039 sinfo->sectors_avail = s->sectors_per_block - block_offset;
1041 sinfo->bytes_left = sinfo->sectors_avail << s->logical_sector_size_bits;
1043 if (sinfo->sectors_avail > nb_sectors) {
1044 sinfo->sectors_avail = nb_sectors;
1047 sinfo->bytes_avail = sinfo->sectors_avail << s->logical_sector_size_bits;
1049 sinfo->file_offset = s->bat[sinfo->bat_idx] & VHDX_BAT_FILE_OFF_MASK;
1051 sinfo->block_offset = block_offset << s->logical_sector_size_bits;
1053 /* The file offset must be past the header section, so must be > 0 */
1054 if (sinfo->file_offset == 0) {
1055 return;
1058 /* block offset is the offset in vhdx logical sectors, in
1059 * the payload data block. Convert that to a byte offset
1060 * in the block, and add in the payload data block offset
1061 * in the file, in bytes, to get the final read address */
1063 sinfo->file_offset += sinfo->block_offset;
1067 static int vhdx_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1069 BDRVVHDXState *s = bs->opaque;
1071 bdi->cluster_size = s->block_size;
1073 bdi->unallocated_blocks_are_zero =
1074 (s->params.data_bits & VHDX_PARAMS_HAS_PARENT) == 0;
1076 return 0;
1080 static coroutine_fn int vhdx_co_readv(BlockDriverState *bs, int64_t sector_num,
1081 int nb_sectors, QEMUIOVector *qiov)
1083 BDRVVHDXState *s = bs->opaque;
1084 int ret = 0;
1085 VHDXSectorInfo sinfo;
1086 uint64_t bytes_done = 0;
1087 QEMUIOVector hd_qiov;
1089 qemu_iovec_init(&hd_qiov, qiov->niov);
1091 qemu_co_mutex_lock(&s->lock);
1093 while (nb_sectors > 0) {
1094 /* We are a differencing file, so we need to inspect the sector bitmap
1095 * to see if we have the data or not */
1096 if (s->params.data_bits & VHDX_PARAMS_HAS_PARENT) {
1097 /* not supported yet */
1098 ret = -ENOTSUP;
1099 goto exit;
1100 } else {
1101 vhdx_block_translate(s, sector_num, nb_sectors, &sinfo);
1103 qemu_iovec_reset(&hd_qiov);
1104 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, sinfo.bytes_avail);
1106 /* check the payload block state */
1107 switch (s->bat[sinfo.bat_idx] & VHDX_BAT_STATE_BIT_MASK) {
1108 case PAYLOAD_BLOCK_NOT_PRESENT: /* fall through */
1109 case PAYLOAD_BLOCK_UNDEFINED:
1110 case PAYLOAD_BLOCK_UNMAPPED:
1111 case PAYLOAD_BLOCK_UNMAPPED_v095:
1112 case PAYLOAD_BLOCK_ZERO:
1113 /* return zero */
1114 qemu_iovec_memset(&hd_qiov, 0, 0, sinfo.bytes_avail);
1115 break;
1116 case PAYLOAD_BLOCK_FULLY_PRESENT:
1117 qemu_co_mutex_unlock(&s->lock);
1118 ret = bdrv_co_readv(bs->file->bs,
1119 sinfo.file_offset >> BDRV_SECTOR_BITS,
1120 sinfo.sectors_avail, &hd_qiov);
1121 qemu_co_mutex_lock(&s->lock);
1122 if (ret < 0) {
1123 goto exit;
1125 break;
1126 case PAYLOAD_BLOCK_PARTIALLY_PRESENT:
1127 /* we don't yet support difference files, fall through
1128 * to error */
1129 default:
1130 ret = -EIO;
1131 goto exit;
1132 break;
1134 nb_sectors -= sinfo.sectors_avail;
1135 sector_num += sinfo.sectors_avail;
1136 bytes_done += sinfo.bytes_avail;
1139 ret = 0;
1140 exit:
1141 qemu_co_mutex_unlock(&s->lock);
1142 qemu_iovec_destroy(&hd_qiov);
1143 return ret;
1147 * Allocate a new payload block at the end of the file.
1149 * Allocation will happen at 1MB alignment inside the file
1151 * Returns the file offset start of the new payload block
1153 static int vhdx_allocate_block(BlockDriverState *bs, BDRVVHDXState *s,
1154 uint64_t *new_offset)
1156 *new_offset = bdrv_getlength(bs->file->bs);
1158 /* per the spec, the address for a block is in units of 1MB */
1159 *new_offset = ROUND_UP(*new_offset, 1024 * 1024);
1161 return bdrv_truncate(bs->file->bs, *new_offset + s->block_size);
1165 * Update the BAT table entry with the new file offset, and the new entry
1166 * state */
1167 static void vhdx_update_bat_table_entry(BlockDriverState *bs, BDRVVHDXState *s,
1168 VHDXSectorInfo *sinfo,
1169 uint64_t *bat_entry_le,
1170 uint64_t *bat_offset, int state)
1172 /* The BAT entry is a uint64, with 44 bits for the file offset in units of
1173 * 1MB, and 3 bits for the block state. */
1174 if ((state == PAYLOAD_BLOCK_ZERO) ||
1175 (state == PAYLOAD_BLOCK_UNDEFINED) ||
1176 (state == PAYLOAD_BLOCK_NOT_PRESENT) ||
1177 (state == PAYLOAD_BLOCK_UNMAPPED)) {
1178 s->bat[sinfo->bat_idx] = 0; /* For PAYLOAD_BLOCK_ZERO, the
1179 FileOffsetMB field is denoted as
1180 'reserved' in the v1.0 spec. If it is
1181 non-zero, MS Hyper-V will fail to read
1182 the disk image */
1183 } else {
1184 s->bat[sinfo->bat_idx] = sinfo->file_offset;
1187 s->bat[sinfo->bat_idx] |= state & VHDX_BAT_STATE_BIT_MASK;
1189 *bat_entry_le = cpu_to_le64(s->bat[sinfo->bat_idx]);
1190 *bat_offset = s->bat_offset + sinfo->bat_idx * sizeof(VHDXBatEntry);
1194 /* Per the spec, on the first write of guest-visible data to the file the
1195 * data write guid must be updated in the header */
1196 int vhdx_user_visible_write(BlockDriverState *bs, BDRVVHDXState *s)
1198 int ret = 0;
1199 if (s->first_visible_write) {
1200 s->first_visible_write = false;
1201 ret = vhdx_update_headers(bs, s, true, NULL);
1203 return ret;
1206 static coroutine_fn int vhdx_co_writev(BlockDriverState *bs, int64_t sector_num,
1207 int nb_sectors, QEMUIOVector *qiov)
1209 int ret = -ENOTSUP;
1210 BDRVVHDXState *s = bs->opaque;
1211 VHDXSectorInfo sinfo;
1212 uint64_t bytes_done = 0;
1213 uint64_t bat_entry = 0;
1214 uint64_t bat_entry_offset = 0;
1215 QEMUIOVector hd_qiov;
1216 struct iovec iov1 = { 0 };
1217 struct iovec iov2 = { 0 };
1218 int sectors_to_write;
1219 int bat_state;
1220 uint64_t bat_prior_offset = 0;
1221 bool bat_update = false;
1223 qemu_iovec_init(&hd_qiov, qiov->niov);
1225 qemu_co_mutex_lock(&s->lock);
1227 ret = vhdx_user_visible_write(bs, s);
1228 if (ret < 0) {
1229 goto exit;
1232 while (nb_sectors > 0) {
1233 bool use_zero_buffers = false;
1234 bat_update = false;
1235 if (s->params.data_bits & VHDX_PARAMS_HAS_PARENT) {
1236 /* not supported yet */
1237 ret = -ENOTSUP;
1238 goto exit;
1239 } else {
1240 vhdx_block_translate(s, sector_num, nb_sectors, &sinfo);
1241 sectors_to_write = sinfo.sectors_avail;
1243 qemu_iovec_reset(&hd_qiov);
1244 /* check the payload block state */
1245 bat_state = s->bat[sinfo.bat_idx] & VHDX_BAT_STATE_BIT_MASK;
1246 switch (bat_state) {
1247 case PAYLOAD_BLOCK_ZERO:
1248 /* in this case, we need to preserve zero writes for
1249 * data that is not part of this write, so we must pad
1250 * the rest of the buffer to zeroes */
1252 /* if we are on a posix system with ftruncate() that extends
1253 * a file, then it is zero-filled for us. On Win32, the raw
1254 * layer uses SetFilePointer and SetFileEnd, which does not
1255 * zero fill AFAIK */
1257 /* Queue another write of zero buffers if the underlying file
1258 * does not zero-fill on file extension */
1260 if (bdrv_has_zero_init(bs->file->bs) == 0) {
1261 use_zero_buffers = true;
1263 /* zero fill the front, if any */
1264 if (sinfo.block_offset) {
1265 iov1.iov_len = sinfo.block_offset;
1266 iov1.iov_base = qemu_blockalign(bs, iov1.iov_len);
1267 memset(iov1.iov_base, 0, iov1.iov_len);
1268 qemu_iovec_concat_iov(&hd_qiov, &iov1, 1, 0,
1269 iov1.iov_len);
1270 sectors_to_write += iov1.iov_len >> BDRV_SECTOR_BITS;
1273 /* our actual data */
1274 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1275 sinfo.bytes_avail);
1277 /* zero fill the back, if any */
1278 if ((sinfo.bytes_avail - sinfo.block_offset) <
1279 s->block_size) {
1280 iov2.iov_len = s->block_size -
1281 (sinfo.bytes_avail + sinfo.block_offset);
1282 iov2.iov_base = qemu_blockalign(bs, iov2.iov_len);
1283 memset(iov2.iov_base, 0, iov2.iov_len);
1284 qemu_iovec_concat_iov(&hd_qiov, &iov2, 1, 0,
1285 iov2.iov_len);
1286 sectors_to_write += iov2.iov_len >> BDRV_SECTOR_BITS;
1289 /* fall through */
1290 case PAYLOAD_BLOCK_NOT_PRESENT: /* fall through */
1291 case PAYLOAD_BLOCK_UNMAPPED:
1292 case PAYLOAD_BLOCK_UNMAPPED_v095:
1293 case PAYLOAD_BLOCK_UNDEFINED:
1294 bat_prior_offset = sinfo.file_offset;
1295 ret = vhdx_allocate_block(bs, s, &sinfo.file_offset);
1296 if (ret < 0) {
1297 goto exit;
1299 /* once we support differencing files, this may also be
1300 * partially present */
1301 /* update block state to the newly specified state */
1302 vhdx_update_bat_table_entry(bs, s, &sinfo, &bat_entry,
1303 &bat_entry_offset,
1304 PAYLOAD_BLOCK_FULLY_PRESENT);
1305 bat_update = true;
1306 /* since we just allocated a block, file_offset is the
1307 * beginning of the payload block. It needs to be the
1308 * write address, which includes the offset into the block */
1309 if (!use_zero_buffers) {
1310 sinfo.file_offset += sinfo.block_offset;
1312 /* fall through */
1313 case PAYLOAD_BLOCK_FULLY_PRESENT:
1314 /* if the file offset address is in the header zone,
1315 * there is a problem */
1316 if (sinfo.file_offset < (1024 * 1024)) {
1317 ret = -EFAULT;
1318 goto error_bat_restore;
1321 if (!use_zero_buffers) {
1322 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1323 sinfo.bytes_avail);
1325 /* block exists, so we can just overwrite it */
1326 qemu_co_mutex_unlock(&s->lock);
1327 ret = bdrv_co_writev(bs->file->bs,
1328 sinfo.file_offset >> BDRV_SECTOR_BITS,
1329 sectors_to_write, &hd_qiov);
1330 qemu_co_mutex_lock(&s->lock);
1331 if (ret < 0) {
1332 goto error_bat_restore;
1334 break;
1335 case PAYLOAD_BLOCK_PARTIALLY_PRESENT:
1336 /* we don't yet support difference files, fall through
1337 * to error */
1338 default:
1339 ret = -EIO;
1340 goto exit;
1341 break;
1344 if (bat_update) {
1345 /* this will update the BAT entry into the log journal, and
1346 * then flush the log journal out to disk */
1347 ret = vhdx_log_write_and_flush(bs, s, &bat_entry,
1348 sizeof(VHDXBatEntry),
1349 bat_entry_offset);
1350 if (ret < 0) {
1351 goto exit;
1355 nb_sectors -= sinfo.sectors_avail;
1356 sector_num += sinfo.sectors_avail;
1357 bytes_done += sinfo.bytes_avail;
1362 goto exit;
1364 error_bat_restore:
1365 if (bat_update) {
1366 /* keep metadata in sync, and restore the bat entry state
1367 * if error. */
1368 sinfo.file_offset = bat_prior_offset;
1369 vhdx_update_bat_table_entry(bs, s, &sinfo, &bat_entry,
1370 &bat_entry_offset, bat_state);
1372 exit:
1373 qemu_vfree(iov1.iov_base);
1374 qemu_vfree(iov2.iov_base);
1375 qemu_co_mutex_unlock(&s->lock);
1376 qemu_iovec_destroy(&hd_qiov);
1377 return ret;
1383 * Create VHDX Headers
1385 * There are 2 headers, and the highest sequence number will represent
1386 * the active header
1388 static int vhdx_create_new_headers(BlockDriverState *bs, uint64_t image_size,
1389 uint32_t log_size)
1391 int ret = 0;
1392 VHDXHeader *hdr = NULL;
1394 hdr = g_new0(VHDXHeader, 1);
1396 hdr->signature = VHDX_HEADER_SIGNATURE;
1397 hdr->sequence_number = g_random_int();
1398 hdr->log_version = 0;
1399 hdr->version = 1;
1400 hdr->log_length = log_size;
1401 hdr->log_offset = VHDX_HEADER_SECTION_END;
1402 vhdx_guid_generate(&hdr->file_write_guid);
1403 vhdx_guid_generate(&hdr->data_write_guid);
1405 ret = vhdx_write_header(bs, hdr, VHDX_HEADER1_OFFSET, false);
1406 if (ret < 0) {
1407 goto exit;
1409 hdr->sequence_number++;
1410 ret = vhdx_write_header(bs, hdr, VHDX_HEADER2_OFFSET, false);
1411 if (ret < 0) {
1412 goto exit;
1415 exit:
1416 g_free(hdr);
1417 return ret;
1420 #define VHDX_METADATA_ENTRY_BUFFER_SIZE \
1421 (sizeof(VHDXFileParameters) +\
1422 sizeof(VHDXVirtualDiskSize) +\
1423 sizeof(VHDXPage83Data) +\
1424 sizeof(VHDXVirtualDiskLogicalSectorSize) +\
1425 sizeof(VHDXVirtualDiskPhysicalSectorSize))
1428 * Create the Metadata entries.
1430 * For more details on the entries, see section 3.5 (pg 29) in the
1431 * VHDX 1.00 specification.
1433 * We support 5 metadata entries (all required by spec):
1434 * File Parameters,
1435 * Virtual Disk Size,
1436 * Page 83 Data,
1437 * Logical Sector Size,
1438 * Physical Sector Size
1440 * The first 64KB of the Metadata section is reserved for the metadata
1441 * header and entries; beyond that, the metadata items themselves reside.
1443 static int vhdx_create_new_metadata(BlockDriverState *bs,
1444 uint64_t image_size,
1445 uint32_t block_size,
1446 uint32_t sector_size,
1447 uint64_t metadata_offset,
1448 VHDXImageType type)
1450 int ret = 0;
1451 uint32_t offset = 0;
1452 void *buffer = NULL;
1453 void *entry_buffer;
1454 VHDXMetadataTableHeader *md_table;
1455 VHDXMetadataTableEntry *md_table_entry;
1457 /* Metadata entries */
1458 VHDXFileParameters *mt_file_params;
1459 VHDXVirtualDiskSize *mt_virtual_size;
1460 VHDXPage83Data *mt_page83;
1461 VHDXVirtualDiskLogicalSectorSize *mt_log_sector_size;
1462 VHDXVirtualDiskPhysicalSectorSize *mt_phys_sector_size;
1464 entry_buffer = g_malloc0(VHDX_METADATA_ENTRY_BUFFER_SIZE);
1466 mt_file_params = entry_buffer;
1467 offset += sizeof(VHDXFileParameters);
1468 mt_virtual_size = entry_buffer + offset;
1469 offset += sizeof(VHDXVirtualDiskSize);
1470 mt_page83 = entry_buffer + offset;
1471 offset += sizeof(VHDXPage83Data);
1472 mt_log_sector_size = entry_buffer + offset;
1473 offset += sizeof(VHDXVirtualDiskLogicalSectorSize);
1474 mt_phys_sector_size = entry_buffer + offset;
1476 mt_file_params->block_size = cpu_to_le32(block_size);
1477 if (type == VHDX_TYPE_FIXED) {
1478 mt_file_params->data_bits |= VHDX_PARAMS_LEAVE_BLOCKS_ALLOCED;
1479 cpu_to_le32s(&mt_file_params->data_bits);
1482 vhdx_guid_generate(&mt_page83->page_83_data);
1483 cpu_to_leguids(&mt_page83->page_83_data);
1484 mt_virtual_size->virtual_disk_size = cpu_to_le64(image_size);
1485 mt_log_sector_size->logical_sector_size = cpu_to_le32(sector_size);
1486 mt_phys_sector_size->physical_sector_size = cpu_to_le32(sector_size);
1488 buffer = g_malloc0(VHDX_HEADER_BLOCK_SIZE);
1489 md_table = buffer;
1491 md_table->signature = VHDX_METADATA_SIGNATURE;
1492 md_table->entry_count = 5;
1493 vhdx_metadata_header_le_export(md_table);
1496 /* This will reference beyond the reserved table portion */
1497 offset = 64 * KiB;
1499 md_table_entry = buffer + sizeof(VHDXMetadataTableHeader);
1501 md_table_entry[0].item_id = file_param_guid;
1502 md_table_entry[0].offset = offset;
1503 md_table_entry[0].length = sizeof(VHDXFileParameters);
1504 md_table_entry[0].data_bits |= VHDX_META_FLAGS_IS_REQUIRED;
1505 offset += md_table_entry[0].length;
1506 vhdx_metadata_entry_le_export(&md_table_entry[0]);
1508 md_table_entry[1].item_id = virtual_size_guid;
1509 md_table_entry[1].offset = offset;
1510 md_table_entry[1].length = sizeof(VHDXVirtualDiskSize);
1511 md_table_entry[1].data_bits |= VHDX_META_FLAGS_IS_REQUIRED |
1512 VHDX_META_FLAGS_IS_VIRTUAL_DISK;
1513 offset += md_table_entry[1].length;
1514 vhdx_metadata_entry_le_export(&md_table_entry[1]);
1516 md_table_entry[2].item_id = page83_guid;
1517 md_table_entry[2].offset = offset;
1518 md_table_entry[2].length = sizeof(VHDXPage83Data);
1519 md_table_entry[2].data_bits |= VHDX_META_FLAGS_IS_REQUIRED |
1520 VHDX_META_FLAGS_IS_VIRTUAL_DISK;
1521 offset += md_table_entry[2].length;
1522 vhdx_metadata_entry_le_export(&md_table_entry[2]);
1524 md_table_entry[3].item_id = logical_sector_guid;
1525 md_table_entry[3].offset = offset;
1526 md_table_entry[3].length = sizeof(VHDXVirtualDiskLogicalSectorSize);
1527 md_table_entry[3].data_bits |= VHDX_META_FLAGS_IS_REQUIRED |
1528 VHDX_META_FLAGS_IS_VIRTUAL_DISK;
1529 offset += md_table_entry[3].length;
1530 vhdx_metadata_entry_le_export(&md_table_entry[3]);
1532 md_table_entry[4].item_id = phys_sector_guid;
1533 md_table_entry[4].offset = offset;
1534 md_table_entry[4].length = sizeof(VHDXVirtualDiskPhysicalSectorSize);
1535 md_table_entry[4].data_bits |= VHDX_META_FLAGS_IS_REQUIRED |
1536 VHDX_META_FLAGS_IS_VIRTUAL_DISK;
1537 vhdx_metadata_entry_le_export(&md_table_entry[4]);
1539 ret = bdrv_pwrite(bs, metadata_offset, buffer, VHDX_HEADER_BLOCK_SIZE);
1540 if (ret < 0) {
1541 goto exit;
1544 ret = bdrv_pwrite(bs, metadata_offset + (64 * KiB), entry_buffer,
1545 VHDX_METADATA_ENTRY_BUFFER_SIZE);
1546 if (ret < 0) {
1547 goto exit;
1551 exit:
1552 g_free(buffer);
1553 g_free(entry_buffer);
1554 return ret;
1557 /* This create the actual BAT itself. We currently only support
1558 * 'Dynamic' and 'Fixed' image types.
1560 * Dynamic images: default state of the BAT is all zeroes.
1562 * Fixed images: default state of the BAT is fully populated, with
1563 * file offsets and state PAYLOAD_BLOCK_FULLY_PRESENT.
1565 static int vhdx_create_bat(BlockDriverState *bs, BDRVVHDXState *s,
1566 uint64_t image_size, VHDXImageType type,
1567 bool use_zero_blocks, uint64_t file_offset,
1568 uint32_t length)
1570 int ret = 0;
1571 uint64_t data_file_offset;
1572 uint64_t total_sectors = 0;
1573 uint64_t sector_num = 0;
1574 uint64_t unused;
1575 int block_state;
1576 VHDXSectorInfo sinfo;
1578 assert(s->bat == NULL);
1580 /* this gives a data start after BAT/bitmap entries, and well
1581 * past any metadata entries (with a 4 MB buffer for future
1582 * expansion */
1583 data_file_offset = file_offset + length + 5 * MiB;
1584 total_sectors = image_size >> s->logical_sector_size_bits;
1586 if (type == VHDX_TYPE_DYNAMIC) {
1587 /* All zeroes, so we can just extend the file - the end of the BAT
1588 * is the furthest thing we have written yet */
1589 ret = bdrv_truncate(bs, data_file_offset);
1590 if (ret < 0) {
1591 goto exit;
1593 } else if (type == VHDX_TYPE_FIXED) {
1594 ret = bdrv_truncate(bs, data_file_offset + image_size);
1595 if (ret < 0) {
1596 goto exit;
1598 } else {
1599 ret = -ENOTSUP;
1600 goto exit;
1603 if (type == VHDX_TYPE_FIXED ||
1604 use_zero_blocks ||
1605 bdrv_has_zero_init(bs) == 0) {
1606 /* for a fixed file, the default BAT entry is not zero */
1607 s->bat = g_try_malloc0(length);
1608 if (length && s->bat == NULL) {
1609 ret = -ENOMEM;
1610 goto exit;
1612 block_state = type == VHDX_TYPE_FIXED ? PAYLOAD_BLOCK_FULLY_PRESENT :
1613 PAYLOAD_BLOCK_NOT_PRESENT;
1614 block_state = use_zero_blocks ? PAYLOAD_BLOCK_ZERO : block_state;
1615 /* fill the BAT by emulating sector writes of sectors_per_block size */
1616 while (sector_num < total_sectors) {
1617 vhdx_block_translate(s, sector_num, s->sectors_per_block, &sinfo);
1618 sinfo.file_offset = data_file_offset +
1619 (sector_num << s->logical_sector_size_bits);
1620 sinfo.file_offset = ROUND_UP(sinfo.file_offset, MiB);
1621 vhdx_update_bat_table_entry(bs, s, &sinfo, &unused, &unused,
1622 block_state);
1623 cpu_to_le64s(&s->bat[sinfo.bat_idx]);
1624 sector_num += s->sectors_per_block;
1626 ret = bdrv_pwrite(bs, file_offset, s->bat, length);
1627 if (ret < 0) {
1628 goto exit;
1634 exit:
1635 g_free(s->bat);
1636 return ret;
1639 /* Creates the region table header, and region table entries.
1640 * There are 2 supported region table entries: BAT, and Metadata/
1642 * As the calculations for the BAT region table are also needed
1643 * to create the BAT itself, we will also cause the BAT to be
1644 * created.
1646 static int vhdx_create_new_region_table(BlockDriverState *bs,
1647 uint64_t image_size,
1648 uint32_t block_size,
1649 uint32_t sector_size,
1650 uint32_t log_size,
1651 bool use_zero_blocks,
1652 VHDXImageType type,
1653 uint64_t *metadata_offset)
1655 int ret = 0;
1656 uint32_t offset = 0;
1657 void *buffer = NULL;
1658 uint64_t bat_file_offset;
1659 uint32_t bat_length;
1660 BDRVVHDXState *s = NULL;
1661 VHDXRegionTableHeader *region_table;
1662 VHDXRegionTableEntry *rt_bat;
1663 VHDXRegionTableEntry *rt_metadata;
1665 assert(metadata_offset != NULL);
1667 /* Populate enough of the BDRVVHDXState to be able to use the
1668 * pre-existing BAT calculation, translation, and update functions */
1669 s = g_new0(BDRVVHDXState, 1);
1671 s->chunk_ratio = (VHDX_MAX_SECTORS_PER_BLOCK) *
1672 (uint64_t) sector_size / (uint64_t) block_size;
1674 s->sectors_per_block = block_size / sector_size;
1675 s->virtual_disk_size = image_size;
1676 s->block_size = block_size;
1677 s->logical_sector_size = sector_size;
1679 vhdx_set_shift_bits(s);
1681 vhdx_calc_bat_entries(s);
1683 /* At this point the VHDX state is populated enough for creation */
1685 /* a single buffer is used so we can calculate the checksum over the
1686 * entire 64KB block */
1687 buffer = g_malloc0(VHDX_HEADER_BLOCK_SIZE);
1688 region_table = buffer;
1689 offset += sizeof(VHDXRegionTableHeader);
1690 rt_bat = buffer + offset;
1691 offset += sizeof(VHDXRegionTableEntry);
1692 rt_metadata = buffer + offset;
1694 region_table->signature = VHDX_REGION_SIGNATURE;
1695 region_table->entry_count = 2; /* BAT and Metadata */
1697 rt_bat->guid = bat_guid;
1698 rt_bat->length = ROUND_UP(s->bat_entries * sizeof(VHDXBatEntry), MiB);
1699 rt_bat->file_offset = ROUND_UP(VHDX_HEADER_SECTION_END + log_size, MiB);
1700 s->bat_offset = rt_bat->file_offset;
1702 rt_metadata->guid = metadata_guid;
1703 rt_metadata->file_offset = ROUND_UP(rt_bat->file_offset + rt_bat->length,
1704 MiB);
1705 rt_metadata->length = 1 * MiB; /* min size, and more than enough */
1706 *metadata_offset = rt_metadata->file_offset;
1708 bat_file_offset = rt_bat->file_offset;
1709 bat_length = rt_bat->length;
1711 vhdx_region_header_le_export(region_table);
1712 vhdx_region_entry_le_export(rt_bat);
1713 vhdx_region_entry_le_export(rt_metadata);
1715 vhdx_update_checksum(buffer, VHDX_HEADER_BLOCK_SIZE,
1716 offsetof(VHDXRegionTableHeader, checksum));
1719 /* The region table gives us the data we need to create the BAT,
1720 * so do that now */
1721 ret = vhdx_create_bat(bs, s, image_size, type, use_zero_blocks,
1722 bat_file_offset, bat_length);
1723 if (ret < 0) {
1724 goto exit;
1727 /* Now write out the region headers to disk */
1728 ret = bdrv_pwrite(bs, VHDX_REGION_TABLE_OFFSET, buffer,
1729 VHDX_HEADER_BLOCK_SIZE);
1730 if (ret < 0) {
1731 goto exit;
1734 ret = bdrv_pwrite(bs, VHDX_REGION_TABLE2_OFFSET, buffer,
1735 VHDX_HEADER_BLOCK_SIZE);
1736 if (ret < 0) {
1737 goto exit;
1740 exit:
1741 g_free(s);
1742 g_free(buffer);
1743 return ret;
1746 /* We need to create the following elements:
1748 * .-----------------------------------------------------------------.
1749 * | (A) | (B) | (C) | (D) | (E) |
1750 * | File ID | Header1 | Header 2 | Region Tbl 1 | Region Tbl 2 |
1751 * | | | | | |
1752 * .-----------------------------------------------------------------.
1753 * 0 64KB 128KB 192KB 256KB 320KB
1756 * .---- ~ ----------- ~ ------------ ~ ---------------- ~ -----------.
1757 * | (F) | (G) | (H) | |
1758 * | Journal Log | BAT / Bitmap | Metadata | .... data ...... |
1759 * | | | | |
1760 * .---- ~ ----------- ~ ------------ ~ ---------------- ~ -----------.
1761 * 1MB
1763 static int vhdx_create(const char *filename, QemuOpts *opts, Error **errp)
1765 int ret = 0;
1766 uint64_t image_size = (uint64_t) 2 * GiB;
1767 uint32_t log_size = 1 * MiB;
1768 uint32_t block_size = 0;
1769 uint64_t signature;
1770 uint64_t metadata_offset;
1771 bool use_zero_blocks = false;
1773 gunichar2 *creator = NULL;
1774 glong creator_items;
1775 BlockDriverState *bs;
1776 char *type = NULL;
1777 VHDXImageType image_type;
1778 Error *local_err = NULL;
1780 image_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1781 BDRV_SECTOR_SIZE);
1782 log_size = qemu_opt_get_size_del(opts, VHDX_BLOCK_OPT_LOG_SIZE, 0);
1783 block_size = qemu_opt_get_size_del(opts, VHDX_BLOCK_OPT_BLOCK_SIZE, 0);
1784 type = qemu_opt_get_del(opts, BLOCK_OPT_SUBFMT);
1785 use_zero_blocks = qemu_opt_get_bool_del(opts, VHDX_BLOCK_OPT_ZERO, true);
1787 if (image_size > VHDX_MAX_IMAGE_SIZE) {
1788 error_setg_errno(errp, EINVAL, "Image size too large; max of 64TB");
1789 ret = -EINVAL;
1790 goto exit;
1793 if (type == NULL) {
1794 type = g_strdup("dynamic");
1797 if (!strcmp(type, "dynamic")) {
1798 image_type = VHDX_TYPE_DYNAMIC;
1799 } else if (!strcmp(type, "fixed")) {
1800 image_type = VHDX_TYPE_FIXED;
1801 } else if (!strcmp(type, "differencing")) {
1802 error_setg_errno(errp, ENOTSUP,
1803 "Differencing files not yet supported");
1804 ret = -ENOTSUP;
1805 goto exit;
1806 } else {
1807 ret = -EINVAL;
1808 goto exit;
1811 /* These are pretty arbitrary, and mainly designed to keep the BAT
1812 * size reasonable to load into RAM */
1813 if (block_size == 0) {
1814 if (image_size > 32 * TiB) {
1815 block_size = 64 * MiB;
1816 } else if (image_size > (uint64_t) 100 * GiB) {
1817 block_size = 32 * MiB;
1818 } else if (image_size > 1 * GiB) {
1819 block_size = 16 * MiB;
1820 } else {
1821 block_size = 8 * MiB;
1826 /* make the log size close to what was specified, but must be
1827 * min 1MB, and multiple of 1MB */
1828 log_size = ROUND_UP(log_size, MiB);
1830 block_size = ROUND_UP(block_size, MiB);
1831 block_size = block_size > VHDX_BLOCK_SIZE_MAX ? VHDX_BLOCK_SIZE_MAX :
1832 block_size;
1834 ret = bdrv_create_file(filename, opts, &local_err);
1835 if (ret < 0) {
1836 error_propagate(errp, local_err);
1837 goto exit;
1840 bs = NULL;
1841 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1842 &local_err);
1843 if (ret < 0) {
1844 error_propagate(errp, local_err);
1845 goto exit;
1848 /* Create (A) */
1850 /* The creator field is optional, but may be useful for
1851 * debugging / diagnostics */
1852 creator = g_utf8_to_utf16("QEMU v" QEMU_VERSION, -1, NULL,
1853 &creator_items, NULL);
1854 signature = cpu_to_le64(VHDX_FILE_SIGNATURE);
1855 ret = bdrv_pwrite(bs, VHDX_FILE_ID_OFFSET, &signature, sizeof(signature));
1856 if (ret < 0) {
1857 goto delete_and_exit;
1859 if (creator) {
1860 ret = bdrv_pwrite(bs, VHDX_FILE_ID_OFFSET + sizeof(signature),
1861 creator, creator_items * sizeof(gunichar2));
1862 if (ret < 0) {
1863 goto delete_and_exit;
1868 /* Creates (B),(C) */
1869 ret = vhdx_create_new_headers(bs, image_size, log_size);
1870 if (ret < 0) {
1871 goto delete_and_exit;
1874 /* Creates (D),(E),(G) explicitly. (F) created as by-product */
1875 ret = vhdx_create_new_region_table(bs, image_size, block_size, 512,
1876 log_size, use_zero_blocks, image_type,
1877 &metadata_offset);
1878 if (ret < 0) {
1879 goto delete_and_exit;
1882 /* Creates (H) */
1883 ret = vhdx_create_new_metadata(bs, image_size, block_size, 512,
1884 metadata_offset, image_type);
1885 if (ret < 0) {
1886 goto delete_and_exit;
1890 delete_and_exit:
1891 bdrv_unref(bs);
1892 exit:
1893 g_free(type);
1894 g_free(creator);
1895 return ret;
1898 /* If opened r/w, the VHDX driver will automatically replay the log,
1899 * if one is present, inside the vhdx_open() call.
1901 * If qemu-img check -r all is called, the image is automatically opened
1902 * r/w and any log has already been replayed, so there is nothing (currently)
1903 * for us to do here
1905 static int vhdx_check(BlockDriverState *bs, BdrvCheckResult *result,
1906 BdrvCheckMode fix)
1908 BDRVVHDXState *s = bs->opaque;
1910 if (s->log_replayed_on_open) {
1911 result->corruptions_fixed++;
1913 return 0;
1916 static QemuOptsList vhdx_create_opts = {
1917 .name = "vhdx-create-opts",
1918 .head = QTAILQ_HEAD_INITIALIZER(vhdx_create_opts.head),
1919 .desc = {
1921 .name = BLOCK_OPT_SIZE,
1922 .type = QEMU_OPT_SIZE,
1923 .help = "Virtual disk size; max of 64TB."
1926 .name = VHDX_BLOCK_OPT_LOG_SIZE,
1927 .type = QEMU_OPT_SIZE,
1928 .def_value_str = stringify(DEFAULT_LOG_SIZE),
1929 .help = "Log size; min 1MB."
1932 .name = VHDX_BLOCK_OPT_BLOCK_SIZE,
1933 .type = QEMU_OPT_SIZE,
1934 .def_value_str = stringify(0),
1935 .help = "Block Size; min 1MB, max 256MB. " \
1936 "0 means auto-calculate based on image size."
1939 .name = BLOCK_OPT_SUBFMT,
1940 .type = QEMU_OPT_STRING,
1941 .help = "VHDX format type, can be either 'dynamic' or 'fixed'. "\
1942 "Default is 'dynamic'."
1945 .name = VHDX_BLOCK_OPT_ZERO,
1946 .type = QEMU_OPT_BOOL,
1947 .help = "Force use of payload blocks of type 'ZERO'. "\
1948 "Non-standard, but default. Do not set to 'off' when "\
1949 "using 'qemu-img convert' with subformat=dynamic."
1951 { NULL }
1955 static BlockDriver bdrv_vhdx = {
1956 .format_name = "vhdx",
1957 .instance_size = sizeof(BDRVVHDXState),
1958 .bdrv_probe = vhdx_probe,
1959 .bdrv_open = vhdx_open,
1960 .bdrv_close = vhdx_close,
1961 .bdrv_reopen_prepare = vhdx_reopen_prepare,
1962 .bdrv_co_readv = vhdx_co_readv,
1963 .bdrv_co_writev = vhdx_co_writev,
1964 .bdrv_create = vhdx_create,
1965 .bdrv_get_info = vhdx_get_info,
1966 .bdrv_check = vhdx_check,
1967 .bdrv_has_zero_init = bdrv_has_zero_init_1,
1969 .create_opts = &vhdx_create_opts,
1972 static void bdrv_vhdx_init(void)
1974 bdrv_register(&bdrv_vhdx);
1977 block_init(bdrv_vhdx_init);