xref: /qemu/block/vhdx.c (revision 65ff757d)
1e8d4e5ffSJeff Cody /*
2e8d4e5ffSJeff Cody  * Block driver for Hyper-V VHDX Images
3e8d4e5ffSJeff Cody  *
4e8d4e5ffSJeff Cody  * Copyright (c) 2013 Red Hat, Inc.,
5e8d4e5ffSJeff Cody  *
6e8d4e5ffSJeff Cody  * Authors:
7e8d4e5ffSJeff Cody  *  Jeff Cody <jcody@redhat.com>
8e8d4e5ffSJeff Cody  *
96e9d290bSJeff Cody  *  This is based on the "VHDX Format Specification v1.00", published 8/25/2012
10e8d4e5ffSJeff Cody  *  by Microsoft:
116e9d290bSJeff Cody  *      https://www.microsoft.com/en-us/download/details.aspx?id=34750
12e8d4e5ffSJeff Cody  *
13e8d4e5ffSJeff Cody  * This work is licensed under the terms of the GNU LGPL, version 2 or later.
14e8d4e5ffSJeff Cody  * See the COPYING.LIB file in the top-level directory.
15e8d4e5ffSJeff Cody  *
16e8d4e5ffSJeff Cody  */
17e8d4e5ffSJeff Cody 
1880c71a24SPeter Maydell #include "qemu/osdep.h"
19da34e65cSMarkus Armbruster #include "qapi/error.h"
20e8d4e5ffSJeff Cody #include "block/block_int.h"
21609f45eaSMax Reitz #include "block/qdict.h"
2210bf03afSKevin Wolf #include "sysemu/block-backend.h"
23e8d4e5ffSJeff Cody #include "qemu/module.h"
24922a01a0SMarkus Armbruster #include "qemu/option.h"
25e8d4e5ffSJeff Cody #include "qemu/crc32c.h"
2658369e22SPaolo Bonzini #include "qemu/bswap.h"
276caaad46SPeter Lieven #include "qemu/error-report.h"
285df022cfSPeter Maydell #include "qemu/memalign.h"
290d8c41daSMichael S. Tsirkin #include "vhdx.h"
30795c40b8SJuan Quintela #include "migration/blocker.h"
31cb6414dfSFam Zheng #include "qemu/uuid.h"
3209b68dabSKevin Wolf #include "qapi/qmp/qdict.h"
3309b68dabSKevin Wolf #include "qapi/qobject-input-visitor.h"
3409b68dabSKevin Wolf #include "qapi/qapi-visit-block-core.h"
353412f7b1SJeff Cody 
363412f7b1SJeff Cody /* Options for VHDX creation */
373412f7b1SJeff Cody 
383412f7b1SJeff Cody #define VHDX_BLOCK_OPT_LOG_SIZE   "log_size"
393412f7b1SJeff Cody #define VHDX_BLOCK_OPT_BLOCK_SIZE "block_size"
403412f7b1SJeff Cody #define VHDX_BLOCK_OPT_ZERO "block_state_zero"
413412f7b1SJeff Cody 
423412f7b1SJeff Cody typedef enum VHDXImageType {
433412f7b1SJeff Cody     VHDX_TYPE_DYNAMIC = 0,
443412f7b1SJeff Cody     VHDX_TYPE_FIXED,
453412f7b1SJeff Cody     VHDX_TYPE_DIFFERENCING,   /* Currently unsupported */
463412f7b1SJeff Cody } VHDXImageType;
47e8d4e5ffSJeff Cody 
4809b68dabSKevin Wolf static QemuOptsList vhdx_create_opts;
4909b68dabSKevin Wolf 
50e8d4e5ffSJeff Cody /* Several metadata and region table data entries are identified by
51e8d4e5ffSJeff Cody  * guids in  a MS-specific GUID format. */
52e8d4e5ffSJeff Cody 
53e8d4e5ffSJeff Cody 
54e8d4e5ffSJeff Cody /* ------- Known Region Table GUIDs ---------------------- */
55e8d4e5ffSJeff Cody static const MSGUID bat_guid =      { .data1 = 0x2dc27766,
56e8d4e5ffSJeff Cody                                       .data2 = 0xf623,
57e8d4e5ffSJeff Cody                                       .data3 = 0x4200,
58e8d4e5ffSJeff Cody                                       .data4 = { 0x9d, 0x64, 0x11, 0x5e,
59e8d4e5ffSJeff Cody                                                  0x9b, 0xfd, 0x4a, 0x08} };
60e8d4e5ffSJeff Cody 
61e8d4e5ffSJeff Cody static const MSGUID metadata_guid = { .data1 = 0x8b7ca206,
62e8d4e5ffSJeff Cody                                       .data2 = 0x4790,
63e8d4e5ffSJeff Cody                                       .data3 = 0x4b9a,
64e8d4e5ffSJeff Cody                                       .data4 = { 0xb8, 0xfe, 0x57, 0x5f,
65e8d4e5ffSJeff Cody                                                  0x05, 0x0f, 0x88, 0x6e} };
66e8d4e5ffSJeff Cody 
67e8d4e5ffSJeff Cody 
68e8d4e5ffSJeff Cody 
69e8d4e5ffSJeff Cody /* ------- Known Metadata Entry GUIDs ---------------------- */
70e8d4e5ffSJeff Cody static const MSGUID file_param_guid =   { .data1 = 0xcaa16737,
71e8d4e5ffSJeff Cody                                           .data2 = 0xfa36,
72e8d4e5ffSJeff Cody                                           .data3 = 0x4d43,
73e8d4e5ffSJeff Cody                                           .data4 = { 0xb3, 0xb6, 0x33, 0xf0,
74e8d4e5ffSJeff Cody                                                      0xaa, 0x44, 0xe7, 0x6b} };
75e8d4e5ffSJeff Cody 
76e8d4e5ffSJeff Cody static const MSGUID virtual_size_guid = { .data1 = 0x2FA54224,
77e8d4e5ffSJeff Cody                                           .data2 = 0xcd1b,
78e8d4e5ffSJeff Cody                                           .data3 = 0x4876,
79e8d4e5ffSJeff Cody                                           .data4 = { 0xb2, 0x11, 0x5d, 0xbe,
80e8d4e5ffSJeff Cody                                                      0xd8, 0x3b, 0xf4, 0xb8} };
81e8d4e5ffSJeff Cody 
82e8d4e5ffSJeff Cody static const MSGUID page83_guid =       { .data1 = 0xbeca12ab,
83e8d4e5ffSJeff Cody                                           .data2 = 0xb2e6,
84e8d4e5ffSJeff Cody                                           .data3 = 0x4523,
85e8d4e5ffSJeff Cody                                           .data4 = { 0x93, 0xef, 0xc3, 0x09,
86e8d4e5ffSJeff Cody                                                      0xe0, 0x00, 0xc7, 0x46} };
87e8d4e5ffSJeff Cody 
88e8d4e5ffSJeff Cody 
89e8d4e5ffSJeff Cody static const MSGUID phys_sector_guid =  { .data1 = 0xcda348c7,
90e8d4e5ffSJeff Cody                                           .data2 = 0x445d,
91e8d4e5ffSJeff Cody                                           .data3 = 0x4471,
92e8d4e5ffSJeff Cody                                           .data4 = { 0x9c, 0xc9, 0xe9, 0x88,
93e8d4e5ffSJeff Cody                                                      0x52, 0x51, 0xc5, 0x56} };
94e8d4e5ffSJeff Cody 
95e8d4e5ffSJeff Cody static const MSGUID parent_locator_guid = { .data1 = 0xa8d35f2d,
96e8d4e5ffSJeff Cody                                             .data2 = 0xb30b,
97e8d4e5ffSJeff Cody                                             .data3 = 0x454d,
98e8d4e5ffSJeff Cody                                             .data4 = { 0xab, 0xf7, 0xd3,
99e8d4e5ffSJeff Cody                                                        0xd8, 0x48, 0x34,
100e8d4e5ffSJeff Cody                                                        0xab, 0x0c} };
101e8d4e5ffSJeff Cody 
102e8d4e5ffSJeff Cody static const MSGUID logical_sector_guid = { .data1 = 0x8141bf1d,
103e8d4e5ffSJeff Cody                                             .data2 = 0xa96f,
104e8d4e5ffSJeff Cody                                             .data3 = 0x4709,
105e8d4e5ffSJeff Cody                                             .data4 = { 0xba, 0x47, 0xf2,
106e8d4e5ffSJeff Cody                                                        0x33, 0xa8, 0xfa,
107e8d4e5ffSJeff Cody                                                        0xab, 0x5f} };
108e8d4e5ffSJeff Cody 
109e8d4e5ffSJeff Cody /* Each parent type must have a valid GUID; this is for parent images
110e8d4e5ffSJeff Cody  * of type 'VHDX'.  If we were to allow e.g. a QCOW2 parent, we would
111e8d4e5ffSJeff Cody  * need to make up our own QCOW2 GUID type */
112c2ebb05eSPeter Maydell static const MSGUID parent_vhdx_guid __attribute__((unused))
113c2ebb05eSPeter Maydell                                      = { .data1 = 0xb04aefb7,
114e8d4e5ffSJeff Cody                                          .data2 = 0xd19e,
115e8d4e5ffSJeff Cody                                          .data3 = 0x4a81,
116e8d4e5ffSJeff Cody                                          .data4 = { 0xb7, 0x89, 0x25, 0xb8,
117e8d4e5ffSJeff Cody                                                     0xe9, 0x44, 0x59, 0x13} };
118e8d4e5ffSJeff Cody 
119e8d4e5ffSJeff Cody 
120e8d4e5ffSJeff Cody #define META_FILE_PARAMETER_PRESENT      0x01
121e8d4e5ffSJeff Cody #define META_VIRTUAL_DISK_SIZE_PRESENT   0x02
122e8d4e5ffSJeff Cody #define META_PAGE_83_PRESENT             0x04
123e8d4e5ffSJeff Cody #define META_LOGICAL_SECTOR_SIZE_PRESENT 0x08
124e8d4e5ffSJeff Cody #define META_PHYS_SECTOR_SIZE_PRESENT    0x10
125e8d4e5ffSJeff Cody #define META_PARENT_LOCATOR_PRESENT      0x20
126e8d4e5ffSJeff Cody 
127e8d4e5ffSJeff Cody #define META_ALL_PRESENT    \
128e8d4e5ffSJeff Cody     (META_FILE_PARAMETER_PRESENT | META_VIRTUAL_DISK_SIZE_PRESENT | \
129e8d4e5ffSJeff Cody      META_PAGE_83_PRESENT | META_LOGICAL_SECTOR_SIZE_PRESENT | \
130e8d4e5ffSJeff Cody      META_PHYS_SECTOR_SIZE_PRESENT)
131e8d4e5ffSJeff Cody 
132e8d4e5ffSJeff Cody 
133059e2fbbSJeff Cody typedef struct VHDXSectorInfo {
134059e2fbbSJeff Cody     uint32_t bat_idx;       /* BAT entry index */
135059e2fbbSJeff Cody     uint32_t sectors_avail; /* sectors available in payload block */
136059e2fbbSJeff Cody     uint32_t bytes_left;    /* bytes left in the block after data to r/w */
137059e2fbbSJeff Cody     uint32_t bytes_avail;   /* bytes available in payload block */
138059e2fbbSJeff Cody     uint64_t file_offset;   /* absolute offset in bytes, in file */
139059e2fbbSJeff Cody     uint64_t block_offset;  /* block offset, in bytes */
140059e2fbbSJeff Cody } VHDXSectorInfo;
141059e2fbbSJeff Cody 
1424f18b782SJeff Cody /* Calculates new checksum.
1434f18b782SJeff Cody  *
1444f18b782SJeff Cody  * Zero is substituted during crc calculation for the original crc field
1454f18b782SJeff Cody  * crc_offset: byte offset in buf of the buffer crc
1464f18b782SJeff Cody  * buf: buffer pointer
1474f18b782SJeff Cody  * size: size of buffer (must be > crc_offset+4)
1484f18b782SJeff Cody  *
1494f75b52aSJeff Cody  * Note: The buffer should have all multi-byte data in little-endian format,
1504f75b52aSJeff Cody  *       and the resulting checksum is in little endian format.
1514f18b782SJeff Cody  */
vhdx_update_checksum(uint8_t * buf,size_t size,int crc_offset)1524f18b782SJeff Cody uint32_t vhdx_update_checksum(uint8_t *buf, size_t size, int crc_offset)
1534f18b782SJeff Cody {
1544f18b782SJeff Cody     uint32_t crc;
1554f18b782SJeff Cody 
1564f18b782SJeff Cody     assert(buf != NULL);
1574f18b782SJeff Cody     assert(size > (crc_offset + sizeof(crc)));
1584f18b782SJeff Cody 
1594f18b782SJeff Cody     memset(buf + crc_offset, 0, sizeof(crc));
1604f18b782SJeff Cody     crc =  crc32c(0xffffffff, buf, size);
1611229e46dSPeter Maydell     crc = cpu_to_le32(crc);
1624f18b782SJeff Cody     memcpy(buf + crc_offset, &crc, sizeof(crc));
1634f18b782SJeff Cody 
1644f18b782SJeff Cody     return crc;
1654f18b782SJeff Cody }
1664f18b782SJeff Cody 
vhdx_checksum_calc(uint32_t crc,uint8_t * buf,size_t size,int crc_offset)167e8d4e5ffSJeff Cody uint32_t vhdx_checksum_calc(uint32_t crc, uint8_t *buf, size_t size,
168e8d4e5ffSJeff Cody                             int crc_offset)
169e8d4e5ffSJeff Cody {
170e8d4e5ffSJeff Cody     uint32_t crc_new;
171e8d4e5ffSJeff Cody     uint32_t crc_orig;
172e8d4e5ffSJeff Cody     assert(buf != NULL);
173e8d4e5ffSJeff Cody 
174e8d4e5ffSJeff Cody     if (crc_offset > 0) {
175e8d4e5ffSJeff Cody         memcpy(&crc_orig, buf + crc_offset, sizeof(crc_orig));
176e8d4e5ffSJeff Cody         memset(buf + crc_offset, 0, sizeof(crc_orig));
177e8d4e5ffSJeff Cody     }
178e8d4e5ffSJeff Cody 
179e8d4e5ffSJeff Cody     crc_new = crc32c(crc, buf, size);
180e8d4e5ffSJeff Cody     if (crc_offset > 0) {
181e8d4e5ffSJeff Cody         memcpy(buf + crc_offset, &crc_orig, sizeof(crc_orig));
182e8d4e5ffSJeff Cody     }
183e8d4e5ffSJeff Cody 
184e8d4e5ffSJeff Cody     return crc_new;
185e8d4e5ffSJeff Cody }
186e8d4e5ffSJeff Cody 
187e8d4e5ffSJeff Cody /* Validates the checksum of the buffer, with an in-place CRC.
188e8d4e5ffSJeff Cody  *
189e8d4e5ffSJeff Cody  * Zero is substituted during crc calculation for the original crc field,
19050d6a8a3SStefan Weil  * and the crc field is restored afterwards.  But the buffer will be modified
191e8d4e5ffSJeff Cody  * during the calculation, so this may not be not suitable for multi-threaded
192e8d4e5ffSJeff Cody  * use.
193e8d4e5ffSJeff Cody  *
194e8d4e5ffSJeff Cody  * crc_offset: byte offset in buf of the buffer crc
195e8d4e5ffSJeff Cody  * buf: buffer pointer
196e8d4e5ffSJeff Cody  * size: size of buffer (must be > crc_offset+4)
197e8d4e5ffSJeff Cody  *
198e8d4e5ffSJeff Cody  * returns true if checksum is valid, false otherwise
199e8d4e5ffSJeff Cody  */
vhdx_checksum_is_valid(uint8_t * buf,size_t size,int crc_offset)200e8d4e5ffSJeff Cody bool vhdx_checksum_is_valid(uint8_t *buf, size_t size, int crc_offset)
201e8d4e5ffSJeff Cody {
202e8d4e5ffSJeff Cody     uint32_t crc_orig;
203e8d4e5ffSJeff Cody     uint32_t crc;
204e8d4e5ffSJeff Cody 
205e8d4e5ffSJeff Cody     assert(buf != NULL);
206e8d4e5ffSJeff Cody     assert(size > (crc_offset + 4));
207e8d4e5ffSJeff Cody 
208e8d4e5ffSJeff Cody     memcpy(&crc_orig, buf + crc_offset, sizeof(crc_orig));
209e8d4e5ffSJeff Cody     crc_orig = le32_to_cpu(crc_orig);
210e8d4e5ffSJeff Cody 
211e8d4e5ffSJeff Cody     crc = vhdx_checksum_calc(0xffffffff, buf, size, crc_offset);
212e8d4e5ffSJeff Cody 
213e8d4e5ffSJeff Cody     return crc == crc_orig;
214e8d4e5ffSJeff Cody }
215e8d4e5ffSJeff Cody 
216e8d4e5ffSJeff Cody 
217e8d4e5ffSJeff Cody /*
2184f18b782SJeff Cody  * This generates a UUID that is compliant with the MS GUIDs used
2194f18b782SJeff Cody  * in the VHDX spec (and elsewhere).
2204f18b782SJeff Cody  */
vhdx_guid_generate(MSGUID * guid)2214f18b782SJeff Cody void vhdx_guid_generate(MSGUID *guid)
2224f18b782SJeff Cody {
223cb6414dfSFam Zheng     QemuUUID uuid;
2244f18b782SJeff Cody     assert(guid != NULL);
2254f18b782SJeff Cody 
226cb6414dfSFam Zheng     qemu_uuid_generate(&uuid);
227cb6414dfSFam Zheng     memcpy(guid, &uuid, sizeof(MSGUID));
2284f18b782SJeff Cody }
2294f18b782SJeff Cody 
2301a848fd4SJeff Cody /* Check for region overlaps inside the VHDX image */
vhdx_region_check(BDRVVHDXState * s,uint64_t start,uint64_t length)2311a848fd4SJeff Cody static int vhdx_region_check(BDRVVHDXState *s, uint64_t start, uint64_t length)
2321a848fd4SJeff Cody {
2331a848fd4SJeff Cody     int ret = 0;
2341a848fd4SJeff Cody     uint64_t end;
2351a848fd4SJeff Cody     VHDXRegionEntry *r;
2361a848fd4SJeff Cody 
2371a848fd4SJeff Cody     end = start + length;
2381a848fd4SJeff Cody     QLIST_FOREACH(r, &s->regions, entries) {
2391a848fd4SJeff Cody         if (!((start >= r->end) || (end <= r->start))) {
2406caaad46SPeter Lieven             error_report("VHDX region %" PRIu64 "-%" PRIu64 " overlaps with "
2416caaad46SPeter Lieven                          "region %" PRIu64 "-%." PRIu64, start, end, r->start,
2426caaad46SPeter Lieven                          r->end);
2431a848fd4SJeff Cody             ret = -EINVAL;
2441a848fd4SJeff Cody             goto exit;
2451a848fd4SJeff Cody         }
2461a848fd4SJeff Cody     }
2471a848fd4SJeff Cody 
2481a848fd4SJeff Cody exit:
2491a848fd4SJeff Cody     return ret;
2501a848fd4SJeff Cody }
2511a848fd4SJeff Cody 
2521a848fd4SJeff Cody /* Register a region for future checks */
vhdx_region_register(BDRVVHDXState * s,uint64_t start,uint64_t length)2531a848fd4SJeff Cody static void vhdx_region_register(BDRVVHDXState *s,
2541a848fd4SJeff Cody                                  uint64_t start, uint64_t length)
2551a848fd4SJeff Cody {
2561a848fd4SJeff Cody     VHDXRegionEntry *r;
2571a848fd4SJeff Cody 
2581a848fd4SJeff Cody     r = g_malloc0(sizeof(*r));
2591a848fd4SJeff Cody 
2601a848fd4SJeff Cody     r->start = start;
2611a848fd4SJeff Cody     r->end = start + length;
2621a848fd4SJeff Cody 
2631a848fd4SJeff Cody     QLIST_INSERT_HEAD(&s->regions, r, entries);
2641a848fd4SJeff Cody }
2651a848fd4SJeff Cody 
2661a848fd4SJeff Cody /* Free all registered regions */
vhdx_region_unregister_all(BDRVVHDXState * s)2671a848fd4SJeff Cody static void vhdx_region_unregister_all(BDRVVHDXState *s)
2681a848fd4SJeff Cody {
2691a848fd4SJeff Cody     VHDXRegionEntry *r, *r_next;
2701a848fd4SJeff Cody 
2711a848fd4SJeff Cody     QLIST_FOREACH_SAFE(r, &s->regions, entries, r_next) {
2721a848fd4SJeff Cody         QLIST_REMOVE(r, entries);
2731a848fd4SJeff Cody         g_free(r);
2741a848fd4SJeff Cody     }
2751a848fd4SJeff Cody }
2761a848fd4SJeff Cody 
vhdx_set_shift_bits(BDRVVHDXState * s)2771e74a971SJeff Cody static void vhdx_set_shift_bits(BDRVVHDXState *s)
2781e74a971SJeff Cody {
27904a36158SMax Reitz     s->logical_sector_size_bits = ctz32(s->logical_sector_size);
28004a36158SMax Reitz     s->sectors_per_block_bits =   ctz32(s->sectors_per_block);
28104a36158SMax Reitz     s->chunk_ratio_bits =         ctz64(s->chunk_ratio);
28204a36158SMax Reitz     s->block_size_bits =          ctz32(s->block_size);
2831e74a971SJeff Cody }
2841e74a971SJeff Cody 
2854f18b782SJeff Cody /*
286e8d4e5ffSJeff Cody  * Per the MS VHDX Specification, for every VHDX file:
287e8d4e5ffSJeff Cody  *      - The header section is fixed size - 1 MB
288e8d4e5ffSJeff Cody  *      - The header section is always the first "object"
289e8d4e5ffSJeff Cody  *      - The first 64KB of the header is the File Identifier
290e8d4e5ffSJeff Cody  *      - The first uint64 (8 bytes) is the VHDX Signature ("vhdxfile")
291e8d4e5ffSJeff Cody  *      - The following 512 bytes constitute a UTF-16 string identifiying the
292e8d4e5ffSJeff Cody  *        software that created the file, and is optional and diagnostic only.
293e8d4e5ffSJeff Cody  *
294e8d4e5ffSJeff Cody  *  Therefore, we probe by looking for the vhdxfile signature "vhdxfile"
295e8d4e5ffSJeff Cody  */
vhdx_probe(const uint8_t * buf,int buf_size,const char * filename)296e8d4e5ffSJeff Cody static int vhdx_probe(const uint8_t *buf, int buf_size, const char *filename)
297e8d4e5ffSJeff Cody {
298e8d4e5ffSJeff Cody     if (buf_size >= 8 && !memcmp(buf, "vhdxfile", 8)) {
299e8d4e5ffSJeff Cody         return 100;
300e8d4e5ffSJeff Cody     }
301e8d4e5ffSJeff Cody     return 0;
302e8d4e5ffSJeff Cody }
303e8d4e5ffSJeff Cody 
3041e74a971SJeff Cody /*
3051e74a971SJeff Cody  * Writes the header to the specified offset.
3061e74a971SJeff Cody  *
3071e74a971SJeff Cody  * This will optionally read in buffer data from disk (otherwise zero-fill),
3081e74a971SJeff Cody  * and then update the header checksum.  Header is converted to proper
3091e74a971SJeff Cody  * endianness before being written to the specified file offset
3101e74a971SJeff Cody  */
vhdx_write_header(BdrvChild * file,VHDXHeader * hdr,uint64_t offset,bool read)311cf2ab8fcSKevin Wolf static int vhdx_write_header(BdrvChild *file, VHDXHeader *hdr,
3121e74a971SJeff Cody                              uint64_t offset, bool read)
3131e74a971SJeff Cody {
314cf2ab8fcSKevin Wolf     BlockDriverState *bs_file = file->bs;
3151e74a971SJeff Cody     uint8_t *buffer = NULL;
3161e74a971SJeff Cody     int ret;
3174f75b52aSJeff Cody     VHDXHeader *header_le;
3181e74a971SJeff Cody 
3191e74a971SJeff Cody     assert(bs_file != NULL);
3201e74a971SJeff Cody     assert(hdr != NULL);
3211e74a971SJeff Cody 
3221e74a971SJeff Cody     /* the header checksum is not over just the packed size of VHDXHeader,
3231e74a971SJeff Cody      * but rather over the entire 'reserved' range for the header, which is
3241e74a971SJeff Cody      * 4KB (VHDX_HEADER_SIZE). */
3251e74a971SJeff Cody 
3261e74a971SJeff Cody     buffer = qemu_blockalign(bs_file, VHDX_HEADER_SIZE);
3271e74a971SJeff Cody     if (read) {
3281e74a971SJeff Cody         /* if true, we can't assume the extra reserved bytes are 0 */
32932cc71deSAlberto Faria         ret = bdrv_pread(file, offset, VHDX_HEADER_SIZE, buffer, 0);
3301e74a971SJeff Cody         if (ret < 0) {
3311e74a971SJeff Cody             goto exit;
3321e74a971SJeff Cody         }
3331e74a971SJeff Cody     } else {
3341e74a971SJeff Cody         memset(buffer, 0, VHDX_HEADER_SIZE);
3351e74a971SJeff Cody     }
3361e74a971SJeff Cody 
3371e74a971SJeff Cody     /* overwrite the actual VHDXHeader portion */
3384f75b52aSJeff Cody     header_le = (VHDXHeader *)buffer;
3394f75b52aSJeff Cody     memcpy(header_le, hdr, sizeof(VHDXHeader));
3404f75b52aSJeff Cody     vhdx_header_le_export(hdr, header_le);
3414f75b52aSJeff Cody     vhdx_update_checksum(buffer, VHDX_HEADER_SIZE,
3421e74a971SJeff Cody                          offsetof(VHDXHeader, checksum));
34332cc71deSAlberto Faria     ret = bdrv_pwrite_sync(file, offset, sizeof(VHDXHeader), header_le, 0);
3441e74a971SJeff Cody 
3451e74a971SJeff Cody exit:
3461e74a971SJeff Cody     qemu_vfree(buffer);
3471e74a971SJeff Cody     return ret;
3481e74a971SJeff Cody }
3491e74a971SJeff Cody 
3504f18b782SJeff Cody /* Update the VHDX headers
3514f18b782SJeff Cody  *
3524f18b782SJeff Cody  * This follows the VHDX spec procedures for header updates.
3534f18b782SJeff Cody  *
3544f18b782SJeff Cody  *  - non-current header is updated with largest sequence number
3554f18b782SJeff Cody  */
35665ff757dSKevin Wolf static int GRAPH_RDLOCK
vhdx_update_header(BlockDriverState * bs,BDRVVHDXState * s,bool generate_data_write_guid,MSGUID * log_guid)35765ff757dSKevin Wolf vhdx_update_header(BlockDriverState *bs, BDRVVHDXState *s,
358c3906c5eSJeff Cody                    bool generate_data_write_guid, MSGUID *log_guid)
3594f18b782SJeff Cody {
3604f18b782SJeff Cody     int ret = 0;
3614f18b782SJeff Cody     int hdr_idx = 0;
3624f18b782SJeff Cody     uint64_t header_offset = VHDX_HEADER1_OFFSET;
3634f18b782SJeff Cody 
3644f18b782SJeff Cody     VHDXHeader *active_header;
3654f18b782SJeff Cody     VHDXHeader *inactive_header;
3664f18b782SJeff Cody 
3674f18b782SJeff Cody     /* operate on the non-current header */
3684f18b782SJeff Cody     if (s->curr_header == 0) {
3694f18b782SJeff Cody         hdr_idx = 1;
3704f18b782SJeff Cody         header_offset = VHDX_HEADER2_OFFSET;
3714f18b782SJeff Cody     }
3724f18b782SJeff Cody 
3734f18b782SJeff Cody     active_header   = s->headers[s->curr_header];
3744f18b782SJeff Cody     inactive_header = s->headers[hdr_idx];
3754f18b782SJeff Cody 
3764f18b782SJeff Cody     inactive_header->sequence_number = active_header->sequence_number + 1;
3774f18b782SJeff Cody 
3784f18b782SJeff Cody     /* a new file guid must be generated before any file write, including
3794f18b782SJeff Cody      * headers */
3804f18b782SJeff Cody     inactive_header->file_write_guid = s->session_guid;
3814f18b782SJeff Cody 
3824f18b782SJeff Cody     /* a new data guid only needs to be generated before any guest-visible
3834f18b782SJeff Cody      * writes (i.e. something observable via virtual disk read) */
3844f18b782SJeff Cody     if (generate_data_write_guid) {
3854f18b782SJeff Cody         vhdx_guid_generate(&inactive_header->data_write_guid);
3864f18b782SJeff Cody     }
3874f18b782SJeff Cody 
388c3906c5eSJeff Cody     /* update the log guid if present */
389c3906c5eSJeff Cody     if (log_guid) {
390c3906c5eSJeff Cody         inactive_header->log_guid = *log_guid;
391c3906c5eSJeff Cody     }
392c3906c5eSJeff Cody 
393cf2ab8fcSKevin Wolf     ret = vhdx_write_header(bs->file, inactive_header, header_offset, true);
3944f18b782SJeff Cody     if (ret < 0) {
3954f18b782SJeff Cody         goto exit;
3964f18b782SJeff Cody     }
3974f18b782SJeff Cody     s->curr_header = hdr_idx;
3984f18b782SJeff Cody 
3994f18b782SJeff Cody exit:
4004f18b782SJeff Cody     return ret;
4014f18b782SJeff Cody }
4024f18b782SJeff Cody 
4034f18b782SJeff Cody /*
4044f18b782SJeff Cody  * The VHDX spec calls for header updates to be performed twice, so that both
4054f18b782SJeff Cody  * the current and non-current header have valid info
4064f18b782SJeff Cody  */
vhdx_update_headers(BlockDriverState * bs,BDRVVHDXState * s,bool generate_data_write_guid,MSGUID * log_guid)407c3906c5eSJeff Cody int vhdx_update_headers(BlockDriverState *bs, BDRVVHDXState *s,
408c3906c5eSJeff Cody                         bool generate_data_write_guid, MSGUID *log_guid)
4094f18b782SJeff Cody {
4104f18b782SJeff Cody     int ret;
4114f18b782SJeff Cody 
412c3906c5eSJeff Cody     ret = vhdx_update_header(bs, s, generate_data_write_guid, log_guid);
4134f18b782SJeff Cody     if (ret < 0) {
4144f18b782SJeff Cody         return ret;
4154f18b782SJeff Cody     }
416b3ac2b94SSimran Singhal     return vhdx_update_header(bs, s, generate_data_write_guid, log_guid);
4174f18b782SJeff Cody }
418e8d4e5ffSJeff Cody 
419e8d4e5ffSJeff Cody /* opens the specified header block from the VHDX file header section */
42065ff757dSKevin Wolf static void GRAPH_RDLOCK
vhdx_parse_header(BlockDriverState * bs,BDRVVHDXState * s,Error ** errp)42165ff757dSKevin Wolf vhdx_parse_header(BlockDriverState *bs, BDRVVHDXState *s, Error **errp)
422e8d4e5ffSJeff Cody {
4236890aad4SPaolo Bonzini     int ret;
424e8d4e5ffSJeff Cody     VHDXHeader *header1;
425e8d4e5ffSJeff Cody     VHDXHeader *header2;
426e8d4e5ffSJeff Cody     bool h1_valid = false;
427e8d4e5ffSJeff Cody     bool h2_valid = false;
428e8d4e5ffSJeff Cody     uint64_t h1_seq = 0;
429e8d4e5ffSJeff Cody     uint64_t h2_seq = 0;
430e8d4e5ffSJeff Cody     uint8_t *buffer;
431e8d4e5ffSJeff Cody 
4326e9d290bSJeff Cody     /* header1 & header2 are freed in vhdx_close() */
433e8d4e5ffSJeff Cody     header1 = qemu_blockalign(bs, sizeof(VHDXHeader));
434e8d4e5ffSJeff Cody     header2 = qemu_blockalign(bs, sizeof(VHDXHeader));
435e8d4e5ffSJeff Cody 
436e8d4e5ffSJeff Cody     buffer = qemu_blockalign(bs, VHDX_HEADER_SIZE);
437e8d4e5ffSJeff Cody 
438e8d4e5ffSJeff Cody     s->headers[0] = header1;
439e8d4e5ffSJeff Cody     s->headers[1] = header2;
440e8d4e5ffSJeff Cody 
441e8d4e5ffSJeff Cody     /* We have to read the whole VHDX_HEADER_SIZE instead of
442e8d4e5ffSJeff Cody      * sizeof(VHDXHeader), because the checksum is over the whole
443e8d4e5ffSJeff Cody      * region */
44432cc71deSAlberto Faria     ret = bdrv_pread(bs->file, VHDX_HEADER1_OFFSET, VHDX_HEADER_SIZE, buffer,
44553fb7844SAlberto Faria                      0);
446e8d4e5ffSJeff Cody     if (ret < 0) {
447e8d4e5ffSJeff Cody         goto fail;
448e8d4e5ffSJeff Cody     }
449e8d4e5ffSJeff Cody     /* copy over just the relevant portion that we need */
450e8d4e5ffSJeff Cody     memcpy(header1, buffer, sizeof(VHDXHeader));
451e8d4e5ffSJeff Cody 
4524f75b52aSJeff Cody     if (vhdx_checksum_is_valid(buffer, VHDX_HEADER_SIZE, 4)) {
4534f75b52aSJeff Cody         vhdx_header_le_import(header1);
4544f75b52aSJeff Cody         if (header1->signature == VHDX_HEADER_SIGNATURE &&
455e8d4e5ffSJeff Cody             header1->version == 1) {
456e8d4e5ffSJeff Cody             h1_seq = header1->sequence_number;
457e8d4e5ffSJeff Cody             h1_valid = true;
458e8d4e5ffSJeff Cody         }
4594f75b52aSJeff Cody     }
460e8d4e5ffSJeff Cody 
46132cc71deSAlberto Faria     ret = bdrv_pread(bs->file, VHDX_HEADER2_OFFSET, VHDX_HEADER_SIZE, buffer,
46253fb7844SAlberto Faria                      0);
463e8d4e5ffSJeff Cody     if (ret < 0) {
464e8d4e5ffSJeff Cody         goto fail;
465e8d4e5ffSJeff Cody     }
466e8d4e5ffSJeff Cody     /* copy over just the relevant portion that we need */
467e8d4e5ffSJeff Cody     memcpy(header2, buffer, sizeof(VHDXHeader));
468e8d4e5ffSJeff Cody 
4694f75b52aSJeff Cody     if (vhdx_checksum_is_valid(buffer, VHDX_HEADER_SIZE, 4)) {
4704f75b52aSJeff Cody         vhdx_header_le_import(header2);
4714f75b52aSJeff Cody         if (header2->signature == VHDX_HEADER_SIGNATURE &&
472e8d4e5ffSJeff Cody             header2->version == 1) {
473e8d4e5ffSJeff Cody             h2_seq = header2->sequence_number;
474e8d4e5ffSJeff Cody             h2_valid = true;
475e8d4e5ffSJeff Cody         }
4764f75b52aSJeff Cody     }
477e8d4e5ffSJeff Cody 
478e8d4e5ffSJeff Cody     /* If there is only 1 valid header (or no valid headers), we
479e8d4e5ffSJeff Cody      * don't care what the sequence numbers are */
480e8d4e5ffSJeff Cody     if (h1_valid && !h2_valid) {
481e8d4e5ffSJeff Cody         s->curr_header = 0;
482e8d4e5ffSJeff Cody     } else if (!h1_valid && h2_valid) {
483e8d4e5ffSJeff Cody         s->curr_header = 1;
484e8d4e5ffSJeff Cody     } else if (!h1_valid && !h2_valid) {
485e8d4e5ffSJeff Cody         goto fail;
486e8d4e5ffSJeff Cody     } else {
487e8d4e5ffSJeff Cody         /* If both headers are valid, then we choose the active one by the
488e8d4e5ffSJeff Cody          * highest sequence number.  If the sequence numbers are equal, that is
489e8d4e5ffSJeff Cody          * invalid */
490e8d4e5ffSJeff Cody         if (h1_seq > h2_seq) {
491e8d4e5ffSJeff Cody             s->curr_header = 0;
492e8d4e5ffSJeff Cody         } else if (h2_seq > h1_seq) {
493e8d4e5ffSJeff Cody             s->curr_header = 1;
494e8d4e5ffSJeff Cody         } else {
49569060461SJeff Cody             /* The Microsoft Disk2VHD tool will create 2 identical
49669060461SJeff Cody              * headers, with identical sequence numbers.  If the headers are
49769060461SJeff Cody              * identical, don't consider the file corrupt */
49869060461SJeff Cody             if (!memcmp(header1, header2, sizeof(VHDXHeader))) {
49969060461SJeff Cody                 s->curr_header = 0;
50069060461SJeff Cody             } else {
501e8d4e5ffSJeff Cody                 goto fail;
502e8d4e5ffSJeff Cody             }
503e8d4e5ffSJeff Cody         }
50469060461SJeff Cody     }
505e8d4e5ffSJeff Cody 
5061a848fd4SJeff Cody     vhdx_region_register(s, s->headers[s->curr_header]->log_offset,
5071a848fd4SJeff Cody                             s->headers[s->curr_header]->log_length);
508e8d4e5ffSJeff Cody     goto exit;
509e8d4e5ffSJeff Cody 
510e8d4e5ffSJeff Cody fail:
5116890aad4SPaolo Bonzini     error_setg_errno(errp, -ret, "No valid VHDX header found");
512e8d4e5ffSJeff Cody     qemu_vfree(header1);
513e8d4e5ffSJeff Cody     qemu_vfree(header2);
514e8d4e5ffSJeff Cody     s->headers[0] = NULL;
515e8d4e5ffSJeff Cody     s->headers[1] = NULL;
516e8d4e5ffSJeff Cody exit:
517e8d4e5ffSJeff Cody     qemu_vfree(buffer);
518e8d4e5ffSJeff Cody }
519e8d4e5ffSJeff Cody 
520e8d4e5ffSJeff Cody 
52165ff757dSKevin Wolf static int GRAPH_RDLOCK
vhdx_open_region_tables(BlockDriverState * bs,BDRVVHDXState * s)52265ff757dSKevin Wolf vhdx_open_region_tables(BlockDriverState *bs, BDRVVHDXState *s)
523e8d4e5ffSJeff Cody {
524e8d4e5ffSJeff Cody     int ret = 0;
525e8d4e5ffSJeff Cody     uint8_t *buffer;
526e8d4e5ffSJeff Cody     int offset = 0;
527e8d4e5ffSJeff Cody     VHDXRegionTableEntry rt_entry;
528e8d4e5ffSJeff Cody     uint32_t i;
529e8d4e5ffSJeff Cody     bool bat_rt_found = false;
530e8d4e5ffSJeff Cody     bool metadata_rt_found = false;
531e8d4e5ffSJeff Cody 
532e8d4e5ffSJeff Cody     /* We have to read the whole 64KB block, because the crc32 is over the
533e8d4e5ffSJeff Cody      * whole block */
534e8d4e5ffSJeff Cody     buffer = qemu_blockalign(bs, VHDX_HEADER_BLOCK_SIZE);
535e8d4e5ffSJeff Cody 
53632cc71deSAlberto Faria     ret = bdrv_pread(bs->file, VHDX_REGION_TABLE_OFFSET,
53732cc71deSAlberto Faria                      VHDX_HEADER_BLOCK_SIZE, buffer, 0);
538e8d4e5ffSJeff Cody     if (ret < 0) {
539e8d4e5ffSJeff Cody         goto fail;
540e8d4e5ffSJeff Cody     }
541e8d4e5ffSJeff Cody     memcpy(&s->rt, buffer, sizeof(s->rt));
542e8d4e5ffSJeff Cody     offset += sizeof(s->rt);
543e8d4e5ffSJeff Cody 
5444f75b52aSJeff Cody     if (!vhdx_checksum_is_valid(buffer, VHDX_HEADER_BLOCK_SIZE, 4)) {
545e8d4e5ffSJeff Cody         ret = -EINVAL;
546e8d4e5ffSJeff Cody         goto fail;
547e8d4e5ffSJeff Cody     }
548e8d4e5ffSJeff Cody 
5494f75b52aSJeff Cody     vhdx_region_header_le_import(&s->rt);
5504f75b52aSJeff Cody 
5514f75b52aSJeff Cody     if (s->rt.signature != VHDX_REGION_SIGNATURE) {
5524f75b52aSJeff Cody         ret = -EINVAL;
5534f75b52aSJeff Cody         goto fail;
5544f75b52aSJeff Cody     }
5554f75b52aSJeff Cody 
5564f75b52aSJeff Cody 
557e8d4e5ffSJeff Cody     /* Per spec, maximum region table entry count is 2047 */
558e8d4e5ffSJeff Cody     if (s->rt.entry_count > 2047) {
559e8d4e5ffSJeff Cody         ret = -EINVAL;
560e8d4e5ffSJeff Cody         goto fail;
561e8d4e5ffSJeff Cody     }
562e8d4e5ffSJeff Cody 
563e8d4e5ffSJeff Cody     for (i = 0; i < s->rt.entry_count; i++) {
564e8d4e5ffSJeff Cody         memcpy(&rt_entry, buffer + offset, sizeof(rt_entry));
565e8d4e5ffSJeff Cody         offset += sizeof(rt_entry);
566e8d4e5ffSJeff Cody 
567c325ee1dSJeff Cody         vhdx_region_entry_le_import(&rt_entry);
568e8d4e5ffSJeff Cody 
5691a848fd4SJeff Cody         /* check for region overlap between these entries, and any
5701a848fd4SJeff Cody          * other memory regions in the file */
5711a848fd4SJeff Cody         ret = vhdx_region_check(s, rt_entry.file_offset, rt_entry.length);
5721a848fd4SJeff Cody         if (ret < 0) {
5731a848fd4SJeff Cody             goto fail;
5741a848fd4SJeff Cody         }
5751a848fd4SJeff Cody 
5761a848fd4SJeff Cody         vhdx_region_register(s, rt_entry.file_offset, rt_entry.length);
5771a848fd4SJeff Cody 
578e8d4e5ffSJeff Cody         /* see if we recognize the entry */
579e8d4e5ffSJeff Cody         if (guid_eq(rt_entry.guid, bat_guid)) {
580e8d4e5ffSJeff Cody             /* must be unique; if we have already found it this is invalid */
581e8d4e5ffSJeff Cody             if (bat_rt_found) {
582e8d4e5ffSJeff Cody                 ret = -EINVAL;
583e8d4e5ffSJeff Cody                 goto fail;
584e8d4e5ffSJeff Cody             }
585e8d4e5ffSJeff Cody             bat_rt_found = true;
586e8d4e5ffSJeff Cody             s->bat_rt = rt_entry;
587e8d4e5ffSJeff Cody             continue;
588e8d4e5ffSJeff Cody         }
589e8d4e5ffSJeff Cody 
590e8d4e5ffSJeff Cody         if (guid_eq(rt_entry.guid, metadata_guid)) {
591e8d4e5ffSJeff Cody             /* must be unique; if we have already found it this is invalid */
592e8d4e5ffSJeff Cody             if (metadata_rt_found) {
593e8d4e5ffSJeff Cody                 ret = -EINVAL;
594e8d4e5ffSJeff Cody                 goto fail;
595e8d4e5ffSJeff Cody             }
596e8d4e5ffSJeff Cody             metadata_rt_found = true;
597e8d4e5ffSJeff Cody             s->metadata_rt = rt_entry;
598e8d4e5ffSJeff Cody             continue;
599e8d4e5ffSJeff Cody         }
600e8d4e5ffSJeff Cody 
601e8d4e5ffSJeff Cody         if (rt_entry.data_bits & VHDX_REGION_ENTRY_REQUIRED) {
602e8d4e5ffSJeff Cody             /* cannot read vhdx file - required region table entry that
603e8d4e5ffSJeff Cody              * we do not understand.  per spec, we must fail to open */
604e8d4e5ffSJeff Cody             ret = -ENOTSUP;
605e8d4e5ffSJeff Cody             goto fail;
606e8d4e5ffSJeff Cody         }
607e8d4e5ffSJeff Cody     }
6081a848fd4SJeff Cody 
6091a848fd4SJeff Cody     if (!bat_rt_found || !metadata_rt_found) {
6101a848fd4SJeff Cody         ret = -EINVAL;
6111a848fd4SJeff Cody         goto fail;
6121a848fd4SJeff Cody     }
6131a848fd4SJeff Cody 
614e8d4e5ffSJeff Cody     ret = 0;
615e8d4e5ffSJeff Cody 
616e8d4e5ffSJeff Cody fail:
617e8d4e5ffSJeff Cody     qemu_vfree(buffer);
618e8d4e5ffSJeff Cody     return ret;
619e8d4e5ffSJeff Cody }
620e8d4e5ffSJeff Cody 
621e8d4e5ffSJeff Cody 
622e8d4e5ffSJeff Cody 
623e8d4e5ffSJeff Cody /* Metadata initial parser
624e8d4e5ffSJeff Cody  *
625e8d4e5ffSJeff Cody  * This loads all the metadata entry fields.  This may cause additional
626e8d4e5ffSJeff Cody  * fields to be processed (e.g. parent locator, etc..).
627e8d4e5ffSJeff Cody  *
628e8d4e5ffSJeff Cody  * There are 5 Metadata items that are always required:
629e8d4e5ffSJeff Cody  *      - File Parameters (block size, has a parent)
630e8d4e5ffSJeff Cody  *      - Virtual Disk Size (size, in bytes, of the virtual drive)
631e8d4e5ffSJeff Cody  *      - Page 83 Data (scsi page 83 guid)
632e8d4e5ffSJeff Cody  *      - Logical Sector Size (logical sector size in bytes, either 512 or
633e8d4e5ffSJeff Cody  *                             4096.  We only support 512 currently)
634e8d4e5ffSJeff Cody  *      - Physical Sector Size (512 or 4096)
635e8d4e5ffSJeff Cody  *
636e8d4e5ffSJeff Cody  * Also, if the File Parameters indicate this is a differencing file,
637e8d4e5ffSJeff Cody  * we must also look for the Parent Locator metadata item.
638e8d4e5ffSJeff Cody  */
63965ff757dSKevin Wolf static int GRAPH_RDLOCK
vhdx_parse_metadata(BlockDriverState * bs,BDRVVHDXState * s)64065ff757dSKevin Wolf vhdx_parse_metadata(BlockDriverState *bs, BDRVVHDXState *s)
641e8d4e5ffSJeff Cody {
642e8d4e5ffSJeff Cody     int ret = 0;
643e8d4e5ffSJeff Cody     uint8_t *buffer;
644e8d4e5ffSJeff Cody     int offset = 0;
645e8d4e5ffSJeff Cody     uint32_t i = 0;
646e8d4e5ffSJeff Cody     VHDXMetadataTableEntry md_entry;
647e8d4e5ffSJeff Cody 
648e8d4e5ffSJeff Cody     buffer = qemu_blockalign(bs, VHDX_METADATA_TABLE_MAX_SIZE);
649e8d4e5ffSJeff Cody 
65032cc71deSAlberto Faria     ret = bdrv_pread(bs->file, s->metadata_rt.file_offset,
65132cc71deSAlberto Faria                      VHDX_METADATA_TABLE_MAX_SIZE, buffer, 0);
652e8d4e5ffSJeff Cody     if (ret < 0) {
653e8d4e5ffSJeff Cody         goto exit;
654e8d4e5ffSJeff Cody     }
655e8d4e5ffSJeff Cody     memcpy(&s->metadata_hdr, buffer, sizeof(s->metadata_hdr));
656e8d4e5ffSJeff Cody     offset += sizeof(s->metadata_hdr);
657e8d4e5ffSJeff Cody 
658c325ee1dSJeff Cody     vhdx_metadata_header_le_import(&s->metadata_hdr);
659e8d4e5ffSJeff Cody 
6604f75b52aSJeff Cody     if (s->metadata_hdr.signature != VHDX_METADATA_SIGNATURE) {
661e8d4e5ffSJeff Cody         ret = -EINVAL;
662e8d4e5ffSJeff Cody         goto exit;
663e8d4e5ffSJeff Cody     }
664e8d4e5ffSJeff Cody 
665e8d4e5ffSJeff Cody     s->metadata_entries.present = 0;
666e8d4e5ffSJeff Cody 
667e8d4e5ffSJeff Cody     if ((s->metadata_hdr.entry_count * sizeof(md_entry)) >
668e8d4e5ffSJeff Cody         (VHDX_METADATA_TABLE_MAX_SIZE - offset)) {
669e8d4e5ffSJeff Cody         ret = -EINVAL;
670e8d4e5ffSJeff Cody         goto exit;
671e8d4e5ffSJeff Cody     }
672e8d4e5ffSJeff Cody 
673e8d4e5ffSJeff Cody     for (i = 0; i < s->metadata_hdr.entry_count; i++) {
674e8d4e5ffSJeff Cody         memcpy(&md_entry, buffer + offset, sizeof(md_entry));
675e8d4e5ffSJeff Cody         offset += sizeof(md_entry);
676e8d4e5ffSJeff Cody 
677c325ee1dSJeff Cody         vhdx_metadata_entry_le_import(&md_entry);
678e8d4e5ffSJeff Cody 
679e8d4e5ffSJeff Cody         if (guid_eq(md_entry.item_id, file_param_guid)) {
680e8d4e5ffSJeff Cody             if (s->metadata_entries.present & META_FILE_PARAMETER_PRESENT) {
681e8d4e5ffSJeff Cody                 ret = -EINVAL;
682e8d4e5ffSJeff Cody                 goto exit;
683e8d4e5ffSJeff Cody             }
684e8d4e5ffSJeff Cody             s->metadata_entries.file_parameters_entry = md_entry;
685e8d4e5ffSJeff Cody             s->metadata_entries.present |= META_FILE_PARAMETER_PRESENT;
686e8d4e5ffSJeff Cody             continue;
687e8d4e5ffSJeff Cody         }
688e8d4e5ffSJeff Cody 
689e8d4e5ffSJeff Cody         if (guid_eq(md_entry.item_id, virtual_size_guid)) {
690e8d4e5ffSJeff Cody             if (s->metadata_entries.present & META_VIRTUAL_DISK_SIZE_PRESENT) {
691e8d4e5ffSJeff Cody                 ret = -EINVAL;
692e8d4e5ffSJeff Cody                 goto exit;
693e8d4e5ffSJeff Cody             }
694e8d4e5ffSJeff Cody             s->metadata_entries.virtual_disk_size_entry = md_entry;
695e8d4e5ffSJeff Cody             s->metadata_entries.present |= META_VIRTUAL_DISK_SIZE_PRESENT;
696e8d4e5ffSJeff Cody             continue;
697e8d4e5ffSJeff Cody         }
698e8d4e5ffSJeff Cody 
699e8d4e5ffSJeff Cody         if (guid_eq(md_entry.item_id, page83_guid)) {
700e8d4e5ffSJeff Cody             if (s->metadata_entries.present & META_PAGE_83_PRESENT) {
701e8d4e5ffSJeff Cody                 ret = -EINVAL;
702e8d4e5ffSJeff Cody                 goto exit;
703e8d4e5ffSJeff Cody             }
704e8d4e5ffSJeff Cody             s->metadata_entries.page83_data_entry = md_entry;
705e8d4e5ffSJeff Cody             s->metadata_entries.present |= META_PAGE_83_PRESENT;
706e8d4e5ffSJeff Cody             continue;
707e8d4e5ffSJeff Cody         }
708e8d4e5ffSJeff Cody 
709e8d4e5ffSJeff Cody         if (guid_eq(md_entry.item_id, logical_sector_guid)) {
710e8d4e5ffSJeff Cody             if (s->metadata_entries.present &
711e8d4e5ffSJeff Cody                 META_LOGICAL_SECTOR_SIZE_PRESENT) {
712e8d4e5ffSJeff Cody                 ret = -EINVAL;
713e8d4e5ffSJeff Cody                 goto exit;
714e8d4e5ffSJeff Cody             }
715e8d4e5ffSJeff Cody             s->metadata_entries.logical_sector_size_entry = md_entry;
716e8d4e5ffSJeff Cody             s->metadata_entries.present |= META_LOGICAL_SECTOR_SIZE_PRESENT;
717e8d4e5ffSJeff Cody             continue;
718e8d4e5ffSJeff Cody         }
719e8d4e5ffSJeff Cody 
720e8d4e5ffSJeff Cody         if (guid_eq(md_entry.item_id, phys_sector_guid)) {
721e8d4e5ffSJeff Cody             if (s->metadata_entries.present & META_PHYS_SECTOR_SIZE_PRESENT) {
722e8d4e5ffSJeff Cody                 ret = -EINVAL;
723e8d4e5ffSJeff Cody                 goto exit;
724e8d4e5ffSJeff Cody             }
725e8d4e5ffSJeff Cody             s->metadata_entries.phys_sector_size_entry = md_entry;
726e8d4e5ffSJeff Cody             s->metadata_entries.present |= META_PHYS_SECTOR_SIZE_PRESENT;
727e8d4e5ffSJeff Cody             continue;
728e8d4e5ffSJeff Cody         }
729e8d4e5ffSJeff Cody 
730e8d4e5ffSJeff Cody         if (guid_eq(md_entry.item_id, parent_locator_guid)) {
731e8d4e5ffSJeff Cody             if (s->metadata_entries.present & META_PARENT_LOCATOR_PRESENT) {
732e8d4e5ffSJeff Cody                 ret = -EINVAL;
733e8d4e5ffSJeff Cody                 goto exit;
734e8d4e5ffSJeff Cody             }
735e8d4e5ffSJeff Cody             s->metadata_entries.parent_locator_entry = md_entry;
736e8d4e5ffSJeff Cody             s->metadata_entries.present |= META_PARENT_LOCATOR_PRESENT;
737e8d4e5ffSJeff Cody             continue;
738e8d4e5ffSJeff Cody         }
739e8d4e5ffSJeff Cody 
740e8d4e5ffSJeff Cody         if (md_entry.data_bits & VHDX_META_FLAGS_IS_REQUIRED) {
741e8d4e5ffSJeff Cody             /* cannot read vhdx file - required region table entry that
742e8d4e5ffSJeff Cody              * we do not understand.  per spec, we must fail to open */
743e8d4e5ffSJeff Cody             ret = -ENOTSUP;
744e8d4e5ffSJeff Cody             goto exit;
745e8d4e5ffSJeff Cody         }
746e8d4e5ffSJeff Cody     }
747e8d4e5ffSJeff Cody 
748e8d4e5ffSJeff Cody     if (s->metadata_entries.present != META_ALL_PRESENT) {
749e8d4e5ffSJeff Cody         ret = -ENOTSUP;
750e8d4e5ffSJeff Cody         goto exit;
751e8d4e5ffSJeff Cody     }
752e8d4e5ffSJeff Cody 
753cf2ab8fcSKevin Wolf     ret = bdrv_pread(bs->file,
754e8d4e5ffSJeff Cody                      s->metadata_entries.file_parameters_entry.offset
755e8d4e5ffSJeff Cody                                          + s->metadata_rt.file_offset,
75653fb7844SAlberto Faria                      sizeof(s->params),
75732cc71deSAlberto Faria                      &s->params,
75853fb7844SAlberto Faria                      0);
759e8d4e5ffSJeff Cody 
760e8d4e5ffSJeff Cody     if (ret < 0) {
761e8d4e5ffSJeff Cody         goto exit;
762e8d4e5ffSJeff Cody     }
763e8d4e5ffSJeff Cody 
7641229e46dSPeter Maydell     s->params.block_size = le32_to_cpu(s->params.block_size);
7651229e46dSPeter Maydell     s->params.data_bits = le32_to_cpu(s->params.data_bits);
766e8d4e5ffSJeff Cody 
767e8d4e5ffSJeff Cody 
768e8d4e5ffSJeff Cody     /* We now have the file parameters, so we can tell if this is a
769e8d4e5ffSJeff Cody      * differencing file (i.e.. has_parent), is dynamic or fixed
770e8d4e5ffSJeff Cody      * sized (leave_blocks_allocated), and the block size */
771e8d4e5ffSJeff Cody 
772e8d4e5ffSJeff Cody     /* The parent locator required iff the file parameters has_parent set */
773e8d4e5ffSJeff Cody     if (s->params.data_bits & VHDX_PARAMS_HAS_PARENT) {
774e8d4e5ffSJeff Cody         if (s->metadata_entries.present & META_PARENT_LOCATOR_PRESENT) {
775e8d4e5ffSJeff Cody             /* TODO: parse  parent locator fields */
776e8d4e5ffSJeff Cody             ret = -ENOTSUP; /* temp, until differencing files are supported */
777e8d4e5ffSJeff Cody             goto exit;
778e8d4e5ffSJeff Cody         } else {
779e8d4e5ffSJeff Cody             /* if has_parent is set, but there is not parent locator present,
780e8d4e5ffSJeff Cody              * then that is an invalid combination */
781e8d4e5ffSJeff Cody             ret = -EINVAL;
782e8d4e5ffSJeff Cody             goto exit;
783e8d4e5ffSJeff Cody         }
784e8d4e5ffSJeff Cody     }
785e8d4e5ffSJeff Cody 
786e8d4e5ffSJeff Cody     /* determine virtual disk size, logical sector size,
787e8d4e5ffSJeff Cody      * and phys sector size */
788e8d4e5ffSJeff Cody 
789cf2ab8fcSKevin Wolf     ret = bdrv_pread(bs->file,
790e8d4e5ffSJeff Cody                      s->metadata_entries.virtual_disk_size_entry.offset
791e8d4e5ffSJeff Cody                                            + s->metadata_rt.file_offset,
79253fb7844SAlberto Faria                      sizeof(uint64_t),
79332cc71deSAlberto Faria                      &s->virtual_disk_size,
79453fb7844SAlberto Faria                      0);
795e8d4e5ffSJeff Cody     if (ret < 0) {
796e8d4e5ffSJeff Cody         goto exit;
797e8d4e5ffSJeff Cody     }
798cf2ab8fcSKevin Wolf     ret = bdrv_pread(bs->file,
799e8d4e5ffSJeff Cody                      s->metadata_entries.logical_sector_size_entry.offset
800e8d4e5ffSJeff Cody                                              + s->metadata_rt.file_offset,
80153fb7844SAlberto Faria                      sizeof(uint32_t),
80232cc71deSAlberto Faria                      &s->logical_sector_size,
80353fb7844SAlberto Faria                      0);
804e8d4e5ffSJeff Cody     if (ret < 0) {
805e8d4e5ffSJeff Cody         goto exit;
806e8d4e5ffSJeff Cody     }
807cf2ab8fcSKevin Wolf     ret = bdrv_pread(bs->file,
808e8d4e5ffSJeff Cody                      s->metadata_entries.phys_sector_size_entry.offset
809e8d4e5ffSJeff Cody                                           + s->metadata_rt.file_offset,
81053fb7844SAlberto Faria                      sizeof(uint32_t),
81132cc71deSAlberto Faria                      &s->physical_sector_size,
81253fb7844SAlberto Faria                      0);
813e8d4e5ffSJeff Cody     if (ret < 0) {
814e8d4e5ffSJeff Cody         goto exit;
815e8d4e5ffSJeff Cody     }
816e8d4e5ffSJeff Cody 
8171229e46dSPeter Maydell     s->virtual_disk_size = le64_to_cpu(s->virtual_disk_size);
8181229e46dSPeter Maydell     s->logical_sector_size = le32_to_cpu(s->logical_sector_size);
8191229e46dSPeter Maydell     s->physical_sector_size = le32_to_cpu(s->physical_sector_size);
820e8d4e5ffSJeff Cody 
8211d7678deSJeff Cody     if (s->params.block_size < VHDX_BLOCK_SIZE_MIN ||
8221d7678deSJeff Cody         s->params.block_size > VHDX_BLOCK_SIZE_MAX) {
823e8d4e5ffSJeff Cody         ret = -EINVAL;
824e8d4e5ffSJeff Cody         goto exit;
825e8d4e5ffSJeff Cody     }
826e8d4e5ffSJeff Cody 
82783a6a900SSwapnil Ingle     /* Currently we only support 512 */
82883a6a900SSwapnil Ingle     if (s->logical_sector_size != 512) {
82983a6a900SSwapnil Ingle         ret = -ENOTSUP;
8301d7678deSJeff Cody         goto exit;
8311d7678deSJeff Cody     }
8321d7678deSJeff Cody 
8331d7678deSJeff Cody     /* Both block_size and sector_size are guaranteed powers of 2, below.
8341d7678deSJeff Cody        Due to range checks above, s->sectors_per_block can never be < 256 */
835e8d4e5ffSJeff Cody     s->sectors_per_block = s->params.block_size / s->logical_sector_size;
836e8d4e5ffSJeff Cody     s->chunk_ratio = (VHDX_MAX_SECTORS_PER_BLOCK) *
837e8d4e5ffSJeff Cody                      (uint64_t)s->logical_sector_size /
838e8d4e5ffSJeff Cody                      (uint64_t)s->params.block_size;
839e8d4e5ffSJeff Cody 
840e8d4e5ffSJeff Cody     /* These values are ones we will want to use for division / multiplication
841e8d4e5ffSJeff Cody      * later on, and they are all guaranteed (per the spec) to be powers of 2,
842e8d4e5ffSJeff Cody      * so we can take advantage of that for shift operations during
843e8d4e5ffSJeff Cody      * reads/writes */
844e8d4e5ffSJeff Cody     if (s->logical_sector_size & (s->logical_sector_size - 1)) {
845e8d4e5ffSJeff Cody         ret = -EINVAL;
846e8d4e5ffSJeff Cody         goto exit;
847e8d4e5ffSJeff Cody     }
848e8d4e5ffSJeff Cody     if (s->sectors_per_block & (s->sectors_per_block - 1)) {
849e8d4e5ffSJeff Cody         ret = -EINVAL;
850e8d4e5ffSJeff Cody         goto exit;
851e8d4e5ffSJeff Cody     }
852e8d4e5ffSJeff Cody     if (s->chunk_ratio & (s->chunk_ratio - 1)) {
853e8d4e5ffSJeff Cody         ret = -EINVAL;
854e8d4e5ffSJeff Cody         goto exit;
855e8d4e5ffSJeff Cody     }
856e8d4e5ffSJeff Cody     s->block_size = s->params.block_size;
857e8d4e5ffSJeff Cody     if (s->block_size & (s->block_size - 1)) {
858e8d4e5ffSJeff Cody         ret = -EINVAL;
859e8d4e5ffSJeff Cody         goto exit;
860e8d4e5ffSJeff Cody     }
861e8d4e5ffSJeff Cody 
8621e74a971SJeff Cody     vhdx_set_shift_bits(s);
863e8d4e5ffSJeff Cody 
864e8d4e5ffSJeff Cody     ret = 0;
865e8d4e5ffSJeff Cody 
866e8d4e5ffSJeff Cody exit:
867e8d4e5ffSJeff Cody     qemu_vfree(buffer);
868e8d4e5ffSJeff Cody     return ret;
869e8d4e5ffSJeff Cody }
870e8d4e5ffSJeff Cody 
8711e74a971SJeff Cody /*
8721e74a971SJeff Cody  * Calculate the number of BAT entries, including sector
8731e74a971SJeff Cody  * bitmap entries.
8741e74a971SJeff Cody  */
vhdx_calc_bat_entries(BDRVVHDXState * s)8751e74a971SJeff Cody static void vhdx_calc_bat_entries(BDRVVHDXState *s)
8761e74a971SJeff Cody {
8771e74a971SJeff Cody     uint32_t data_blocks_cnt, bitmap_blocks_cnt;
8781e74a971SJeff Cody 
879939901dcSMax Reitz     data_blocks_cnt = DIV_ROUND_UP(s->virtual_disk_size, s->block_size);
880939901dcSMax Reitz     bitmap_blocks_cnt = DIV_ROUND_UP(data_blocks_cnt, s->chunk_ratio);
8811e74a971SJeff Cody 
8821e74a971SJeff Cody     if (s->parent_entries) {
8831e74a971SJeff Cody         s->bat_entries = bitmap_blocks_cnt * (s->chunk_ratio + 1);
8841e74a971SJeff Cody     } else {
8851e74a971SJeff Cody         s->bat_entries = data_blocks_cnt +
8861e74a971SJeff Cody                          ((data_blocks_cnt - 1) >> s->chunk_ratio_bits);
8871e74a971SJeff Cody     }
8881e74a971SJeff Cody 
8891e74a971SJeff Cody }
890e8d4e5ffSJeff Cody 
89165ff757dSKevin Wolf static int coroutine_mixed_fn GRAPH_RDLOCK
vhdx_check_bat_entries(BlockDriverState * bs,int * errcnt)89265ff757dSKevin Wolf vhdx_check_bat_entries(BlockDriverState *bs, int *errcnt)
8936caaad46SPeter Lieven {
8946caaad46SPeter Lieven     BDRVVHDXState *s = bs->opaque;
8956caaad46SPeter Lieven     int64_t image_file_size = bdrv_getlength(bs->file->bs);
8966caaad46SPeter Lieven     uint64_t payblocks = s->chunk_ratio;
8976caaad46SPeter Lieven     uint64_t i;
8986caaad46SPeter Lieven     int ret = 0;
8996caaad46SPeter Lieven 
9006caaad46SPeter Lieven     if (image_file_size < 0) {
9016caaad46SPeter Lieven         error_report("Could not determinate VHDX image file size.");
9026caaad46SPeter Lieven         return image_file_size;
9036caaad46SPeter Lieven     }
9046caaad46SPeter Lieven 
9056caaad46SPeter Lieven     for (i = 0; i < s->bat_entries; i++) {
9066caaad46SPeter Lieven         if ((s->bat[i] & VHDX_BAT_STATE_BIT_MASK) ==
9076caaad46SPeter Lieven             PAYLOAD_BLOCK_FULLY_PRESENT) {
9086caaad46SPeter Lieven             uint64_t offset = s->bat[i] & VHDX_BAT_FILE_OFF_MASK;
9096caaad46SPeter Lieven             /*
9106caaad46SPeter Lieven              * Allow that the last block exists only partially. The VHDX spec
9116caaad46SPeter Lieven              * states that the image file can only grow in blocksize increments,
9126caaad46SPeter Lieven              * but QEMU created images with partial last blocks in the past.
9136caaad46SPeter Lieven              */
9146caaad46SPeter Lieven             uint32_t block_length = MIN(s->block_size,
9156caaad46SPeter Lieven                 bs->total_sectors * BDRV_SECTOR_SIZE - i * s->block_size);
9166caaad46SPeter Lieven             /*
9176caaad46SPeter Lieven              * Check for BAT entry overflow.
9186caaad46SPeter Lieven              */
9196caaad46SPeter Lieven             if (offset > INT64_MAX - s->block_size) {
9206caaad46SPeter Lieven                 error_report("VHDX BAT entry %" PRIu64 " offset overflow.", i);
9216caaad46SPeter Lieven                 ret = -EINVAL;
9226caaad46SPeter Lieven                 if (!errcnt) {
9236caaad46SPeter Lieven                     break;
9246caaad46SPeter Lieven                 }
9256caaad46SPeter Lieven                 (*errcnt)++;
9266caaad46SPeter Lieven             }
9276caaad46SPeter Lieven             /*
9286caaad46SPeter Lieven              * Check if fully allocated BAT entries do not reside after
9296caaad46SPeter Lieven              * end of the image file.
9306caaad46SPeter Lieven              */
9316caaad46SPeter Lieven             if (offset >= image_file_size) {
9326caaad46SPeter Lieven                 error_report("VHDX BAT entry %" PRIu64 " start offset %" PRIu64
9336caaad46SPeter Lieven                              " points after end of file (%" PRIi64 "). Image"
9346caaad46SPeter Lieven                              " has probably been truncated.",
9356caaad46SPeter Lieven                              i, offset, image_file_size);
9366caaad46SPeter Lieven                 ret = -EINVAL;
9376caaad46SPeter Lieven                 if (!errcnt) {
9386caaad46SPeter Lieven                     break;
9396caaad46SPeter Lieven                 }
9406caaad46SPeter Lieven                 (*errcnt)++;
9416caaad46SPeter Lieven             } else if (offset + block_length > image_file_size) {
9426caaad46SPeter Lieven                 error_report("VHDX BAT entry %" PRIu64 " end offset %" PRIu64
9436caaad46SPeter Lieven                              " points after end of file (%" PRIi64 "). Image"
9446caaad46SPeter Lieven                              " has probably been truncated.",
9456caaad46SPeter Lieven                              i, offset + block_length - 1, image_file_size);
9466caaad46SPeter Lieven                 ret = -EINVAL;
9476caaad46SPeter Lieven                 if (!errcnt) {
9486caaad46SPeter Lieven                     break;
9496caaad46SPeter Lieven                 }
9506caaad46SPeter Lieven                 (*errcnt)++;
9516caaad46SPeter Lieven             }
9526caaad46SPeter Lieven 
9536caaad46SPeter Lieven             /*
9546caaad46SPeter Lieven              * verify populated BAT field file offsets against
9556caaad46SPeter Lieven              * region table and log entries
9566caaad46SPeter Lieven              */
9576caaad46SPeter Lieven             if (payblocks--) {
9586caaad46SPeter Lieven                 /* payload bat entries */
9596caaad46SPeter Lieven                 int ret2;
9606caaad46SPeter Lieven                 ret2 = vhdx_region_check(s, offset, s->block_size);
9616caaad46SPeter Lieven                 if (ret2 < 0) {
9626caaad46SPeter Lieven                     ret = -EINVAL;
9636caaad46SPeter Lieven                     if (!errcnt) {
9646caaad46SPeter Lieven                         break;
9656caaad46SPeter Lieven                     }
9666caaad46SPeter Lieven                     (*errcnt)++;
9676caaad46SPeter Lieven                 }
9686caaad46SPeter Lieven             } else {
9696caaad46SPeter Lieven                 payblocks = s->chunk_ratio;
9706caaad46SPeter Lieven                 /*
9716caaad46SPeter Lieven                  * Once differencing files are supported, verify sector bitmap
9726caaad46SPeter Lieven                  * blocks here
9736caaad46SPeter Lieven                  */
9746caaad46SPeter Lieven             }
9756caaad46SPeter Lieven         }
9766caaad46SPeter Lieven     }
9776caaad46SPeter Lieven 
9786caaad46SPeter Lieven     return ret;
9796caaad46SPeter Lieven }
9806caaad46SPeter Lieven 
vhdx_close(BlockDriverState * bs)981c46415afSJeff Cody static void vhdx_close(BlockDriverState *bs)
982c46415afSJeff Cody {
983c46415afSJeff Cody     BDRVVHDXState *s = bs->opaque;
984c46415afSJeff Cody     qemu_vfree(s->headers[0]);
9850a43a1b5SJeff Cody     s->headers[0] = NULL;
986c46415afSJeff Cody     qemu_vfree(s->headers[1]);
9870a43a1b5SJeff Cody     s->headers[1] = NULL;
988c46415afSJeff Cody     qemu_vfree(s->bat);
9890a43a1b5SJeff Cody     s->bat = NULL;
990c46415afSJeff Cody     qemu_vfree(s->parent_entries);
9910a43a1b5SJeff Cody     s->parent_entries = NULL;
992c8a7fc51SSteve Sistare     migrate_del_blocker(&s->migration_blocker);
9930a43a1b5SJeff Cody     qemu_vfree(s->log.hdr);
9940a43a1b5SJeff Cody     s->log.hdr = NULL;
9951a848fd4SJeff Cody     vhdx_region_unregister_all(s);
996c46415afSJeff Cody }
997c46415afSJeff Cody 
vhdx_open(BlockDriverState * bs,QDict * options,int flags,Error ** errp)998015a1036SMax Reitz static int vhdx_open(BlockDriverState *bs, QDict *options, int flags,
999015a1036SMax Reitz                      Error **errp)
1000e8d4e5ffSJeff Cody {
1001e8d4e5ffSJeff Cody     BDRVVHDXState *s = bs->opaque;
1002e8d4e5ffSJeff Cody     int ret = 0;
1003e8d4e5ffSJeff Cody     uint32_t i;
1004e8d4e5ffSJeff Cody     uint64_t signature;
10056890aad4SPaolo Bonzini     Error *local_err = NULL;
1006e8d4e5ffSJeff Cody 
1007b7cfc7d5SKevin Wolf     GLOBAL_STATE_CODE();
1008b7cfc7d5SKevin Wolf 
100983930780SVladimir Sementsov-Ogievskiy     ret = bdrv_open_file_child(NULL, options, "file", bs, errp);
101083930780SVladimir Sementsov-Ogievskiy     if (ret < 0) {
101183930780SVladimir Sementsov-Ogievskiy         return ret;
10124e4bf5c4SKevin Wolf     }
10134e4bf5c4SKevin Wolf 
1014b7cfc7d5SKevin Wolf     GRAPH_RDLOCK_GUARD_MAINLOOP();
1015b7cfc7d5SKevin Wolf 
1016e8d4e5ffSJeff Cody     s->bat = NULL;
1017c3906c5eSJeff Cody     s->first_visible_write = true;
1018e8d4e5ffSJeff Cody 
1019e8d4e5ffSJeff Cody     qemu_co_mutex_init(&s->lock);
10201a848fd4SJeff Cody     QLIST_INIT(&s->regions);
1021e8d4e5ffSJeff Cody 
1022e8d4e5ffSJeff Cody     /* validate the file signature */
102332cc71deSAlberto Faria     ret = bdrv_pread(bs->file, 0, sizeof(uint64_t), &signature, 0);
1024e8d4e5ffSJeff Cody     if (ret < 0) {
1025e8d4e5ffSJeff Cody         goto fail;
1026e8d4e5ffSJeff Cody     }
1027e8d4e5ffSJeff Cody     if (memcmp(&signature, "vhdxfile", 8)) {
1028e8d4e5ffSJeff Cody         ret = -EINVAL;
1029e8d4e5ffSJeff Cody         goto fail;
1030e8d4e5ffSJeff Cody     }
1031e8d4e5ffSJeff Cody 
10324f18b782SJeff Cody     /* This is used for any header updates, for the file_write_guid.
10334f18b782SJeff Cody      * The spec dictates that a new value should be used for the first
10344f18b782SJeff Cody      * header update */
10354f18b782SJeff Cody     vhdx_guid_generate(&s->session_guid);
10364f18b782SJeff Cody 
10376890aad4SPaolo Bonzini     vhdx_parse_header(bs, s, &local_err);
10386890aad4SPaolo Bonzini     if (local_err != NULL) {
10396890aad4SPaolo Bonzini         error_propagate(errp, local_err);
10406890aad4SPaolo Bonzini         ret = -EINVAL;
1041e8d4e5ffSJeff Cody         goto fail;
1042e8d4e5ffSJeff Cody     }
1043e8d4e5ffSJeff Cody 
10447e30e6a6SJeff Cody     ret = vhdx_parse_log(bs, s, &s->log_replayed_on_open, errp);
10450a43a1b5SJeff Cody     if (ret < 0) {
1046e8d4e5ffSJeff Cody         goto fail;
1047e8d4e5ffSJeff Cody     }
1048e8d4e5ffSJeff Cody 
1049e8d4e5ffSJeff Cody     ret = vhdx_open_region_tables(bs, s);
10500a43a1b5SJeff Cody     if (ret < 0) {
1051e8d4e5ffSJeff Cody         goto fail;
1052e8d4e5ffSJeff Cody     }
1053e8d4e5ffSJeff Cody 
1054e8d4e5ffSJeff Cody     ret = vhdx_parse_metadata(bs, s);
10550a43a1b5SJeff Cody     if (ret < 0) {
1056e8d4e5ffSJeff Cody         goto fail;
1057e8d4e5ffSJeff Cody     }
10580a43a1b5SJeff Cody 
1059e8d4e5ffSJeff Cody     s->block_size = s->params.block_size;
1060e8d4e5ffSJeff Cody 
1061e8d4e5ffSJeff Cody     /* the VHDX spec dictates that virtual_disk_size is always a multiple of
1062e8d4e5ffSJeff Cody      * logical_sector_size */
1063e8d4e5ffSJeff Cody     bs->total_sectors = s->virtual_disk_size >> s->logical_sector_size_bits;
1064e8d4e5ffSJeff Cody 
10651e74a971SJeff Cody     vhdx_calc_bat_entries(s);
1066e8d4e5ffSJeff Cody 
1067e8d4e5ffSJeff Cody     s->bat_offset = s->bat_rt.file_offset;
1068e8d4e5ffSJeff Cody 
1069e8d4e5ffSJeff Cody     if (s->bat_entries > s->bat_rt.length / sizeof(VHDXBatEntry)) {
1070e8d4e5ffSJeff Cody         /* BAT allocation is not large enough for all entries */
1071e8d4e5ffSJeff Cody         ret = -EINVAL;
1072e8d4e5ffSJeff Cody         goto fail;
1073e8d4e5ffSJeff Cody     }
1074e8d4e5ffSJeff Cody 
10756e9d290bSJeff Cody     /* s->bat is freed in vhdx_close() */
10769a4f4c31SKevin Wolf     s->bat = qemu_try_blockalign(bs->file->bs, s->bat_rt.length);
1077a67e128aSKevin Wolf     if (s->bat == NULL) {
1078a67e128aSKevin Wolf         ret = -ENOMEM;
1079a67e128aSKevin Wolf         goto fail;
1080a67e128aSKevin Wolf     }
1081a67e128aSKevin Wolf 
108232cc71deSAlberto Faria     ret = bdrv_pread(bs->file, s->bat_offset, s->bat_rt.length, s->bat, 0);
1083e8d4e5ffSJeff Cody     if (ret < 0) {
1084e8d4e5ffSJeff Cody         goto fail;
1085e8d4e5ffSJeff Cody     }
1086e8d4e5ffSJeff Cody 
10873202d8e4SMichael Tokarev     /* endian convert populated BAT field entries */
1088e8d4e5ffSJeff Cody     for (i = 0; i < s->bat_entries; i++) {
10891229e46dSPeter Maydell         s->bat[i] = le64_to_cpu(s->bat[i]);
10906caaad46SPeter Lieven     }
10916caaad46SPeter Lieven 
10926caaad46SPeter Lieven     if (!(flags & BDRV_O_CHECK)) {
10936caaad46SPeter Lieven         ret = vhdx_check_bat_entries(bs, NULL);
10941a848fd4SJeff Cody         if (ret < 0) {
10951a848fd4SJeff Cody             goto fail;
10961a848fd4SJeff Cody         }
10971a848fd4SJeff Cody     }
1098e8d4e5ffSJeff Cody 
1099fe44dc91SAshijeet Acharya     /* Disable migration when VHDX images are used */
1100fe44dc91SAshijeet Acharya     error_setg(&s->migration_blocker, "The vhdx format used by node '%s' "
1101fe44dc91SAshijeet Acharya                "does not support live migration",
1102fe44dc91SAshijeet Acharya                bdrv_get_device_or_node_name(bs));
1103e0ee3a8fSSteve Sistare     ret = migrate_add_blocker_normal(&s->migration_blocker, errp);
1104386f6c07SMarkus Armbruster     if (ret < 0) {
1105fe44dc91SAshijeet Acharya         goto fail;
1106fe44dc91SAshijeet Acharya     }
1107fe44dc91SAshijeet Acharya 
1108d92aa883SJeff Cody     /* TODO: differencing files */
1109e8d4e5ffSJeff Cody 
1110e8d4e5ffSJeff Cody     return 0;
1111e8d4e5ffSJeff Cody fail:
11120a43a1b5SJeff Cody     vhdx_close(bs);
1113e8d4e5ffSJeff Cody     return ret;
1114e8d4e5ffSJeff Cody }
1115e8d4e5ffSJeff Cody 
vhdx_reopen_prepare(BDRVReopenState * state,BlockReopenQueue * queue,Error ** errp)1116e8d4e5ffSJeff Cody static int vhdx_reopen_prepare(BDRVReopenState *state,
1117e8d4e5ffSJeff Cody                                BlockReopenQueue *queue, Error **errp)
1118e8d4e5ffSJeff Cody {
1119e8d4e5ffSJeff Cody     return 0;
1120e8d4e5ffSJeff Cody }
1121e8d4e5ffSJeff Cody 
1122e8d4e5ffSJeff Cody 
1123059e2fbbSJeff Cody /*
1124059e2fbbSJeff Cody  * Perform sector to block offset translations, to get various
1125059e2fbbSJeff Cody  * sector and file offsets into the image.  See VHDXSectorInfo
1126059e2fbbSJeff Cody  */
vhdx_block_translate(BDRVVHDXState * s,int64_t sector_num,int nb_sectors,VHDXSectorInfo * sinfo)1127059e2fbbSJeff Cody static void vhdx_block_translate(BDRVVHDXState *s, int64_t sector_num,
1128059e2fbbSJeff Cody                                  int nb_sectors, VHDXSectorInfo *sinfo)
1129059e2fbbSJeff Cody {
1130059e2fbbSJeff Cody     uint32_t block_offset;
1131059e2fbbSJeff Cody 
1132059e2fbbSJeff Cody     sinfo->bat_idx = sector_num >> s->sectors_per_block_bits;
1133059e2fbbSJeff Cody     /* effectively a modulo - this gives us the offset into the block
1134059e2fbbSJeff Cody      * (in sector sizes) for our sector number */
1135059e2fbbSJeff Cody     block_offset = sector_num - (sinfo->bat_idx << s->sectors_per_block_bits);
1136059e2fbbSJeff Cody     /* the chunk ratio gives us the interleaving of the sector
1137059e2fbbSJeff Cody      * bitmaps, so we need to advance our page block index by the
1138059e2fbbSJeff Cody      * sector bitmaps entry number */
1139059e2fbbSJeff Cody     sinfo->bat_idx += sinfo->bat_idx >> s->chunk_ratio_bits;
1140059e2fbbSJeff Cody 
1141059e2fbbSJeff Cody     /* the number of sectors we can read/write in this cycle */
1142059e2fbbSJeff Cody     sinfo->sectors_avail = s->sectors_per_block - block_offset;
1143059e2fbbSJeff Cody 
1144059e2fbbSJeff Cody     sinfo->bytes_left = sinfo->sectors_avail << s->logical_sector_size_bits;
1145059e2fbbSJeff Cody 
1146059e2fbbSJeff Cody     if (sinfo->sectors_avail > nb_sectors) {
1147059e2fbbSJeff Cody         sinfo->sectors_avail = nb_sectors;
1148059e2fbbSJeff Cody     }
1149059e2fbbSJeff Cody 
1150059e2fbbSJeff Cody     sinfo->bytes_avail = sinfo->sectors_avail << s->logical_sector_size_bits;
1151059e2fbbSJeff Cody 
11520b7da092SJeff Cody     sinfo->file_offset = s->bat[sinfo->bat_idx] & VHDX_BAT_FILE_OFF_MASK;
1153059e2fbbSJeff Cody 
1154059e2fbbSJeff Cody     sinfo->block_offset = block_offset << s->logical_sector_size_bits;
1155059e2fbbSJeff Cody 
1156059e2fbbSJeff Cody     /* The file offset must be past the header section, so must be > 0 */
1157059e2fbbSJeff Cody     if (sinfo->file_offset == 0) {
1158059e2fbbSJeff Cody         return;
1159059e2fbbSJeff Cody     }
1160059e2fbbSJeff Cody 
1161059e2fbbSJeff Cody     /* block offset is the offset in vhdx logical sectors, in
1162059e2fbbSJeff Cody      * the payload data block. Convert that to a byte offset
1163059e2fbbSJeff Cody      * in the block, and add in the payload data block offset
1164059e2fbbSJeff Cody      * in the file, in bytes, to get the final read address */
1165059e2fbbSJeff Cody 
1166059e2fbbSJeff Cody     sinfo->file_offset += sinfo->block_offset;
1167059e2fbbSJeff Cody }
1168059e2fbbSJeff Cody 
1169059e2fbbSJeff Cody 
11703d47eb0aSEmanuele Giuseppe Esposito static int coroutine_fn
vhdx_co_get_info(BlockDriverState * bs,BlockDriverInfo * bdi)11713d47eb0aSEmanuele Giuseppe Esposito vhdx_co_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
117297b00e28SPaolo Bonzini {
117397b00e28SPaolo Bonzini     BDRVVHDXState *s = bs->opaque;
117497b00e28SPaolo Bonzini 
117597b00e28SPaolo Bonzini     bdi->cluster_size = s->block_size;
117697b00e28SPaolo Bonzini 
117797b00e28SPaolo Bonzini     return 0;
117897b00e28SPaolo Bonzini }
117997b00e28SPaolo Bonzini 
1180059e2fbbSJeff Cody 
1181b9b10c35SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
vhdx_co_readv(BlockDriverState * bs,int64_t sector_num,int nb_sectors,QEMUIOVector * qiov)1182b9b10c35SKevin Wolf vhdx_co_readv(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1183b9b10c35SKevin Wolf               QEMUIOVector *qiov)
1184e8d4e5ffSJeff Cody {
1185059e2fbbSJeff Cody     BDRVVHDXState *s = bs->opaque;
1186059e2fbbSJeff Cody     int ret = 0;
1187059e2fbbSJeff Cody     VHDXSectorInfo sinfo;
1188059e2fbbSJeff Cody     uint64_t bytes_done = 0;
1189059e2fbbSJeff Cody     QEMUIOVector hd_qiov;
1190059e2fbbSJeff Cody 
1191059e2fbbSJeff Cody     qemu_iovec_init(&hd_qiov, qiov->niov);
1192059e2fbbSJeff Cody 
1193059e2fbbSJeff Cody     qemu_co_mutex_lock(&s->lock);
1194059e2fbbSJeff Cody 
1195059e2fbbSJeff Cody     while (nb_sectors > 0) {
1196059e2fbbSJeff Cody         /* We are a differencing file, so we need to inspect the sector bitmap
1197059e2fbbSJeff Cody          * to see if we have the data or not */
1198059e2fbbSJeff Cody         if (s->params.data_bits & VHDX_PARAMS_HAS_PARENT) {
1199059e2fbbSJeff Cody             /* not supported yet */
1200059e2fbbSJeff Cody             ret = -ENOTSUP;
1201059e2fbbSJeff Cody             goto exit;
1202059e2fbbSJeff Cody         } else {
1203059e2fbbSJeff Cody             vhdx_block_translate(s, sector_num, nb_sectors, &sinfo);
1204059e2fbbSJeff Cody 
1205059e2fbbSJeff Cody             qemu_iovec_reset(&hd_qiov);
1206059e2fbbSJeff Cody             qemu_iovec_concat(&hd_qiov, qiov,  bytes_done, sinfo.bytes_avail);
1207059e2fbbSJeff Cody 
1208059e2fbbSJeff Cody             /* check the payload block state */
1209059e2fbbSJeff Cody             switch (s->bat[sinfo.bat_idx] & VHDX_BAT_STATE_BIT_MASK) {
1210059e2fbbSJeff Cody             case PAYLOAD_BLOCK_NOT_PRESENT: /* fall through */
12110571df44SJeff Cody             case PAYLOAD_BLOCK_UNDEFINED:
12120571df44SJeff Cody             case PAYLOAD_BLOCK_UNMAPPED:
1213a9d1e9daSJeff Cody             case PAYLOAD_BLOCK_UNMAPPED_v095:
1214059e2fbbSJeff Cody             case PAYLOAD_BLOCK_ZERO:
1215059e2fbbSJeff Cody                 /* return zero */
1216059e2fbbSJeff Cody                 qemu_iovec_memset(&hd_qiov, 0, 0, sinfo.bytes_avail);
1217059e2fbbSJeff Cody                 break;
1218d92aa883SJeff Cody             case PAYLOAD_BLOCK_FULLY_PRESENT:
1219059e2fbbSJeff Cody                 qemu_co_mutex_unlock(&s->lock);
12203a7404b3SEric Blake                 ret = bdrv_co_preadv(bs->file, sinfo.file_offset,
12213a7404b3SEric Blake                                      sinfo.sectors_avail * BDRV_SECTOR_SIZE,
12223a7404b3SEric Blake                                      &hd_qiov, 0);
1223059e2fbbSJeff Cody                 qemu_co_mutex_lock(&s->lock);
1224059e2fbbSJeff Cody                 if (ret < 0) {
1225059e2fbbSJeff Cody                     goto exit;
1226059e2fbbSJeff Cody                 }
1227059e2fbbSJeff Cody                 break;
1228059e2fbbSJeff Cody             case PAYLOAD_BLOCK_PARTIALLY_PRESENT:
1229059e2fbbSJeff Cody                 /* we don't yet support difference files, fall through
1230059e2fbbSJeff Cody                  * to error */
1231059e2fbbSJeff Cody             default:
1232059e2fbbSJeff Cody                 ret = -EIO;
1233059e2fbbSJeff Cody                 goto exit;
1234059e2fbbSJeff Cody                 break;
1235059e2fbbSJeff Cody             }
1236059e2fbbSJeff Cody             nb_sectors -= sinfo.sectors_avail;
1237059e2fbbSJeff Cody             sector_num += sinfo.sectors_avail;
1238059e2fbbSJeff Cody             bytes_done += sinfo.bytes_avail;
1239059e2fbbSJeff Cody         }
1240059e2fbbSJeff Cody     }
1241059e2fbbSJeff Cody     ret = 0;
1242059e2fbbSJeff Cody exit:
1243059e2fbbSJeff Cody     qemu_co_mutex_unlock(&s->lock);
1244059e2fbbSJeff Cody     qemu_iovec_destroy(&hd_qiov);
1245059e2fbbSJeff Cody     return ret;
1246e8d4e5ffSJeff Cody }
1247e8d4e5ffSJeff Cody 
1248d92aa883SJeff Cody /*
1249d92aa883SJeff Cody  * Allocate a new payload block at the end of the file.
1250d92aa883SJeff Cody  *
1251dbc636e7SEric Blake  * Allocation will happen at 1MB alignment inside the file.
1252dbc636e7SEric Blake  *
1253dbc636e7SEric Blake  * If @need_zero is set on entry but not cleared on return, then truncation
1254dbc636e7SEric Blake  * could not guarantee that the new portion reads as zero, and the caller
1255dbc636e7SEric Blake  * will take care of it instead.
1256d92aa883SJeff Cody  *
1257d92aa883SJeff Cody  * Returns the file offset start of the new payload block
1258d92aa883SJeff Cody  */
1259f6b08994SPaolo Bonzini static int coroutine_fn GRAPH_RDLOCK
vhdx_allocate_block(BlockDriverState * bs,BDRVVHDXState * s,uint64_t * new_offset,bool * need_zero)1260f6b08994SPaolo Bonzini vhdx_allocate_block(BlockDriverState *bs, BDRVVHDXState *s,
1261dbc636e7SEric Blake                     uint64_t *new_offset, bool *need_zero)
1262d92aa883SJeff Cody {
12633f910692SJeff Cody     int64_t current_len;
12643f910692SJeff Cody 
1265f6b08994SPaolo Bonzini     current_len = bdrv_co_getlength(bs->file->bs);
12663f910692SJeff Cody     if (current_len < 0) {
12673f910692SJeff Cody         return current_len;
12683f910692SJeff Cody     }
12693f910692SJeff Cody 
12703f910692SJeff Cody     *new_offset = current_len;
1271e8d4e5ffSJeff Cody 
1272d92aa883SJeff Cody     /* per the spec, the address for a block is in units of 1MB */
12730cb98af2SStefano Garzarella     *new_offset = ROUND_UP(*new_offset, 1 * MiB);
127427539ac5SJeff Cody     if (*new_offset > INT64_MAX) {
127527539ac5SJeff Cody         return -EINVAL;
127627539ac5SJeff Cody     }
1277d92aa883SJeff Cody 
1278dbc636e7SEric Blake     if (*need_zero) {
1279dbc636e7SEric Blake         int ret;
1280dbc636e7SEric Blake 
1281f6b08994SPaolo Bonzini         ret = bdrv_co_truncate(bs->file, *new_offset + s->block_size, false,
1282dbc636e7SEric Blake                                PREALLOC_MODE_OFF, BDRV_REQ_ZERO_WRITE, NULL);
1283dbc636e7SEric Blake         if (ret != -ENOTSUP) {
1284dbc636e7SEric Blake             *need_zero = false;
1285dbc636e7SEric Blake             return ret;
1286dbc636e7SEric Blake         }
1287dbc636e7SEric Blake     }
1288dbc636e7SEric Blake 
1289f6b08994SPaolo Bonzini     return bdrv_co_truncate(bs->file, *new_offset + s->block_size, false,
12907b8e4857SKevin Wolf                             PREALLOC_MODE_OFF, 0, NULL);
1291d92aa883SJeff Cody }
1292d92aa883SJeff Cody 
1293d92aa883SJeff Cody /*
1294d92aa883SJeff Cody  * Update the BAT table entry with the new file offset, and the new entry
1295d92aa883SJeff Cody  * state */
vhdx_update_bat_table_entry(BlockDriverState * bs,BDRVVHDXState * s,VHDXSectorInfo * sinfo,uint64_t * bat_entry_le,uint64_t * bat_offset,int state)1296d92aa883SJeff Cody static void vhdx_update_bat_table_entry(BlockDriverState *bs, BDRVVHDXState *s,
1297d92aa883SJeff Cody                                        VHDXSectorInfo *sinfo,
1298d92aa883SJeff Cody                                        uint64_t *bat_entry_le,
1299d92aa883SJeff Cody                                        uint64_t *bat_offset, int state)
1300d92aa883SJeff Cody {
1301d92aa883SJeff Cody     /* The BAT entry is a uint64, with 44 bits for the file offset in units of
1302d92aa883SJeff Cody      * 1MB, and 3 bits for the block state. */
1303cdf9634bSJeff Cody     if ((state == PAYLOAD_BLOCK_ZERO)        ||
1304cdf9634bSJeff Cody         (state == PAYLOAD_BLOCK_UNDEFINED)   ||
1305cdf9634bSJeff Cody         (state == PAYLOAD_BLOCK_NOT_PRESENT) ||
1306cdf9634bSJeff Cody         (state == PAYLOAD_BLOCK_UNMAPPED)) {
1307cdf9634bSJeff Cody         s->bat[sinfo->bat_idx]  = 0;  /* For PAYLOAD_BLOCK_ZERO, the
1308cdf9634bSJeff Cody                                          FileOffsetMB field is denoted as
1309cdf9634bSJeff Cody                                          'reserved' in the v1.0 spec.  If it is
1310cdf9634bSJeff Cody                                          non-zero, MS Hyper-V will fail to read
1311cdf9634bSJeff Cody                                          the disk image */
1312cdf9634bSJeff Cody     } else {
13130b7da092SJeff Cody         s->bat[sinfo->bat_idx]  = sinfo->file_offset;
1314cdf9634bSJeff Cody     }
1315d92aa883SJeff Cody 
1316d92aa883SJeff Cody     s->bat[sinfo->bat_idx] |= state & VHDX_BAT_STATE_BIT_MASK;
1317d92aa883SJeff Cody 
1318d92aa883SJeff Cody     *bat_entry_le = cpu_to_le64(s->bat[sinfo->bat_idx]);
1319d92aa883SJeff Cody     *bat_offset = s->bat_offset + sinfo->bat_idx * sizeof(VHDXBatEntry);
1320d92aa883SJeff Cody 
1321d92aa883SJeff Cody }
1322e8d4e5ffSJeff Cody 
1323c3906c5eSJeff Cody /* Per the spec, on the first write of guest-visible data to the file the
1324c3906c5eSJeff Cody  * data write guid must be updated in the header */
vhdx_user_visible_write(BlockDriverState * bs,BDRVVHDXState * s)1325c3906c5eSJeff Cody int vhdx_user_visible_write(BlockDriverState *bs, BDRVVHDXState *s)
1326c3906c5eSJeff Cody {
1327c3906c5eSJeff Cody     int ret = 0;
1328c3906c5eSJeff Cody     if (s->first_visible_write) {
1329c3906c5eSJeff Cody         s->first_visible_write = false;
1330c3906c5eSJeff Cody         ret = vhdx_update_headers(bs, s, true, NULL);
1331c3906c5eSJeff Cody     }
1332c3906c5eSJeff Cody     return ret;
1333c3906c5eSJeff Cody }
1334c3906c5eSJeff Cody 
1335b9b10c35SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
vhdx_co_writev(BlockDriverState * bs,int64_t sector_num,int nb_sectors,QEMUIOVector * qiov,int flags)1336b9b10c35SKevin Wolf vhdx_co_writev(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1337b9b10c35SKevin Wolf                QEMUIOVector *qiov, int flags)
1338e8d4e5ffSJeff Cody {
1339d92aa883SJeff Cody     int ret = -ENOTSUP;
1340d92aa883SJeff Cody     BDRVVHDXState *s = bs->opaque;
1341d92aa883SJeff Cody     VHDXSectorInfo sinfo;
1342d92aa883SJeff Cody     uint64_t bytes_done = 0;
1343d92aa883SJeff Cody     uint64_t bat_entry = 0;
1344d92aa883SJeff Cody     uint64_t bat_entry_offset = 0;
1345d92aa883SJeff Cody     QEMUIOVector hd_qiov;
1346d92aa883SJeff Cody     struct iovec iov1 = { 0 };
1347d92aa883SJeff Cody     struct iovec iov2 = { 0 };
1348d92aa883SJeff Cody     int sectors_to_write;
1349d92aa883SJeff Cody     int bat_state;
1350d92aa883SJeff Cody     uint64_t bat_prior_offset = 0;
1351d92aa883SJeff Cody     bool bat_update = false;
1352d92aa883SJeff Cody 
1353d92aa883SJeff Cody     qemu_iovec_init(&hd_qiov, qiov->niov);
1354d92aa883SJeff Cody 
1355d92aa883SJeff Cody     qemu_co_mutex_lock(&s->lock);
1356d92aa883SJeff Cody 
1357d92aa883SJeff Cody     ret = vhdx_user_visible_write(bs, s);
1358d92aa883SJeff Cody     if (ret < 0) {
1359d92aa883SJeff Cody         goto exit;
1360d92aa883SJeff Cody     }
1361d92aa883SJeff Cody 
1362d92aa883SJeff Cody     while (nb_sectors > 0) {
1363d92aa883SJeff Cody         bool use_zero_buffers = false;
1364d92aa883SJeff Cody         bat_update = false;
1365d92aa883SJeff Cody         if (s->params.data_bits & VHDX_PARAMS_HAS_PARENT) {
1366d92aa883SJeff Cody             /* not supported yet */
1367d92aa883SJeff Cody             ret = -ENOTSUP;
1368d92aa883SJeff Cody             goto exit;
1369d92aa883SJeff Cody         } else {
1370d92aa883SJeff Cody             vhdx_block_translate(s, sector_num, nb_sectors, &sinfo);
1371d92aa883SJeff Cody             sectors_to_write = sinfo.sectors_avail;
1372d92aa883SJeff Cody 
1373d92aa883SJeff Cody             qemu_iovec_reset(&hd_qiov);
1374d92aa883SJeff Cody             /* check the payload block state */
1375d92aa883SJeff Cody             bat_state = s->bat[sinfo.bat_idx] & VHDX_BAT_STATE_BIT_MASK;
1376d92aa883SJeff Cody             switch (bat_state) {
1377d92aa883SJeff Cody             case PAYLOAD_BLOCK_ZERO:
1378d92aa883SJeff Cody                 /* in this case, we need to preserve zero writes for
1379d92aa883SJeff Cody                  * data that is not part of this write, so we must pad
1380d92aa883SJeff Cody                  * the rest of the buffer to zeroes */
1381d92aa883SJeff Cody                 use_zero_buffers = true;
1382dbc636e7SEric Blake                 /* fall through */
1383dbc636e7SEric Blake             case PAYLOAD_BLOCK_NOT_PRESENT: /* fall through */
1384dbc636e7SEric Blake             case PAYLOAD_BLOCK_UNMAPPED:
1385dbc636e7SEric Blake             case PAYLOAD_BLOCK_UNMAPPED_v095:
1386dbc636e7SEric Blake             case PAYLOAD_BLOCK_UNDEFINED:
1387dbc636e7SEric Blake                 bat_prior_offset = sinfo.file_offset;
1388dbc636e7SEric Blake                 ret = vhdx_allocate_block(bs, s, &sinfo.file_offset,
1389dbc636e7SEric Blake                                           &use_zero_buffers);
1390dbc636e7SEric Blake                 if (ret < 0) {
1391dbc636e7SEric Blake                     goto exit;
1392dbc636e7SEric Blake                 }
1393dbc636e7SEric Blake                 /*
1394dbc636e7SEric Blake                  * once we support differencing files, this may also be
1395dbc636e7SEric Blake                  * partially present
1396dbc636e7SEric Blake                  */
1397dbc636e7SEric Blake                 /* update block state to the newly specified state */
1398dbc636e7SEric Blake                 vhdx_update_bat_table_entry(bs, s, &sinfo, &bat_entry,
1399dbc636e7SEric Blake                                             &bat_entry_offset,
1400dbc636e7SEric Blake                                             PAYLOAD_BLOCK_FULLY_PRESENT);
1401dbc636e7SEric Blake                 bat_update = true;
1402dbc636e7SEric Blake                 /*
1403dbc636e7SEric Blake                  * Since we just allocated a block, file_offset is the
1404dbc636e7SEric Blake                  * beginning of the payload block. It needs to be the
1405dbc636e7SEric Blake                  * write address, which includes the offset into the
1406dbc636e7SEric Blake                  * block, unless the entire block needs to read as
1407dbc636e7SEric Blake                  * zeroes but truncation was not able to provide them,
1408dbc636e7SEric Blake                  * in which case we need to fill in the rest.
1409dbc636e7SEric Blake                  */
1410dbc636e7SEric Blake                 if (!use_zero_buffers) {
1411dbc636e7SEric Blake                     sinfo.file_offset += sinfo.block_offset;
1412dbc636e7SEric Blake                 } else {
1413d92aa883SJeff Cody                     /* zero fill the front, if any */
1414d92aa883SJeff Cody                     if (sinfo.block_offset) {
1415d92aa883SJeff Cody                         iov1.iov_len = sinfo.block_offset;
1416d92aa883SJeff Cody                         iov1.iov_base = qemu_blockalign(bs, iov1.iov_len);
1417d92aa883SJeff Cody                         memset(iov1.iov_base, 0, iov1.iov_len);
1418d92aa883SJeff Cody                         qemu_iovec_concat_iov(&hd_qiov, &iov1, 1, 0,
1419d1a126c5SKevin Wolf                                               iov1.iov_len);
1420d92aa883SJeff Cody                         sectors_to_write += iov1.iov_len >> BDRV_SECTOR_BITS;
1421d92aa883SJeff Cody                     }
1422d92aa883SJeff Cody 
1423d92aa883SJeff Cody                     /* our actual data */
1424d92aa883SJeff Cody                     qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1425d92aa883SJeff Cody                                       sinfo.bytes_avail);
1426d92aa883SJeff Cody 
1427d92aa883SJeff Cody                     /* zero fill the back, if any */
1428d92aa883SJeff Cody                     if ((sinfo.bytes_avail - sinfo.block_offset) <
1429d92aa883SJeff Cody                          s->block_size) {
1430d92aa883SJeff Cody                         iov2.iov_len = s->block_size -
1431d92aa883SJeff Cody                                       (sinfo.bytes_avail + sinfo.block_offset);
1432d92aa883SJeff Cody                         iov2.iov_base = qemu_blockalign(bs, iov2.iov_len);
1433d92aa883SJeff Cody                         memset(iov2.iov_base, 0, iov2.iov_len);
1434d92aa883SJeff Cody                         qemu_iovec_concat_iov(&hd_qiov, &iov2, 1, 0,
1435d1a126c5SKevin Wolf                                               iov2.iov_len);
1436d92aa883SJeff Cody                         sectors_to_write += iov2.iov_len >> BDRV_SECTOR_BITS;
1437d92aa883SJeff Cody                     }
1438d92aa883SJeff Cody                 }
1439dbc636e7SEric Blake 
1440d92aa883SJeff Cody                 /* fall through */
1441d92aa883SJeff Cody             case PAYLOAD_BLOCK_FULLY_PRESENT:
1442d92aa883SJeff Cody                 /* if the file offset address is in the header zone,
1443d92aa883SJeff Cody                  * there is a problem */
14440cb98af2SStefano Garzarella                 if (sinfo.file_offset < (1 * MiB)) {
1445d92aa883SJeff Cody                     ret = -EFAULT;
1446d92aa883SJeff Cody                     goto error_bat_restore;
1447d92aa883SJeff Cody                 }
1448d92aa883SJeff Cody 
1449d92aa883SJeff Cody                 if (!use_zero_buffers) {
1450d92aa883SJeff Cody                     qemu_iovec_concat(&hd_qiov, qiov,  bytes_done,
1451d92aa883SJeff Cody                                       sinfo.bytes_avail);
1452d92aa883SJeff Cody                 }
1453d92aa883SJeff Cody                 /* block exists, so we can just overwrite it */
1454d92aa883SJeff Cody                 qemu_co_mutex_unlock(&s->lock);
14553a7404b3SEric Blake                 ret = bdrv_co_pwritev(bs->file, sinfo.file_offset,
14563a7404b3SEric Blake                                       sectors_to_write * BDRV_SECTOR_SIZE,
14573a7404b3SEric Blake                                       &hd_qiov, 0);
1458d92aa883SJeff Cody                 qemu_co_mutex_lock(&s->lock);
1459d92aa883SJeff Cody                 if (ret < 0) {
1460d92aa883SJeff Cody                     goto error_bat_restore;
1461d92aa883SJeff Cody                 }
1462d92aa883SJeff Cody                 break;
1463d92aa883SJeff Cody             case PAYLOAD_BLOCK_PARTIALLY_PRESENT:
1464d92aa883SJeff Cody                 /* we don't yet support difference files, fall through
1465d92aa883SJeff Cody                  * to error */
1466d92aa883SJeff Cody             default:
1467d92aa883SJeff Cody                 ret = -EIO;
1468d92aa883SJeff Cody                 goto exit;
1469d92aa883SJeff Cody                 break;
1470d92aa883SJeff Cody             }
1471d92aa883SJeff Cody 
1472d92aa883SJeff Cody             if (bat_update) {
1473d92aa883SJeff Cody                 /* this will update the BAT entry into the log journal, and
1474d92aa883SJeff Cody                  * then flush the log journal out to disk */
1475d92aa883SJeff Cody                 ret =  vhdx_log_write_and_flush(bs, s, &bat_entry,
1476d92aa883SJeff Cody                                                 sizeof(VHDXBatEntry),
1477d92aa883SJeff Cody                                                 bat_entry_offset);
1478d92aa883SJeff Cody                 if (ret < 0) {
1479d92aa883SJeff Cody                     goto exit;
1480d92aa883SJeff Cody                 }
1481d92aa883SJeff Cody             }
1482d92aa883SJeff Cody 
1483d92aa883SJeff Cody             nb_sectors -= sinfo.sectors_avail;
1484d92aa883SJeff Cody             sector_num += sinfo.sectors_avail;
1485d92aa883SJeff Cody             bytes_done += sinfo.bytes_avail;
1486d92aa883SJeff Cody 
1487d92aa883SJeff Cody         }
1488d92aa883SJeff Cody     }
1489d92aa883SJeff Cody 
1490d92aa883SJeff Cody     goto exit;
1491d92aa883SJeff Cody 
1492d92aa883SJeff Cody error_bat_restore:
1493d92aa883SJeff Cody     if (bat_update) {
1494d92aa883SJeff Cody         /* keep metadata in sync, and restore the bat entry state
1495d92aa883SJeff Cody          * if error. */
1496d92aa883SJeff Cody         sinfo.file_offset = bat_prior_offset;
1497d92aa883SJeff Cody         vhdx_update_bat_table_entry(bs, s, &sinfo, &bat_entry,
1498d92aa883SJeff Cody                                     &bat_entry_offset, bat_state);
1499d92aa883SJeff Cody     }
1500d92aa883SJeff Cody exit:
1501d92aa883SJeff Cody     qemu_vfree(iov1.iov_base);
1502d92aa883SJeff Cody     qemu_vfree(iov2.iov_base);
1503d92aa883SJeff Cody     qemu_co_mutex_unlock(&s->lock);
1504d92aa883SJeff Cody     qemu_iovec_destroy(&hd_qiov);
1505d92aa883SJeff Cody     return ret;
1506e8d4e5ffSJeff Cody }
1507e8d4e5ffSJeff Cody 
1508e8d4e5ffSJeff Cody 
15093412f7b1SJeff Cody 
15103412f7b1SJeff Cody /*
15113412f7b1SJeff Cody  * Create VHDX Headers
15123412f7b1SJeff Cody  *
15133412f7b1SJeff Cody  * There are 2 headers, and the highest sequence number will represent
15143412f7b1SJeff Cody  * the active header
15153412f7b1SJeff Cody  */
15164db7ba3bSKevin Wolf static int coroutine_fn GRAPH_UNLOCKED
vhdx_create_new_headers(BlockBackend * blk,uint64_t image_size,uint32_t log_size)1517622d30afSKevin Wolf vhdx_create_new_headers(BlockBackend *blk, uint64_t image_size,
15183412f7b1SJeff Cody                         uint32_t log_size)
15193412f7b1SJeff Cody {
1520db1e80eeSKevin Wolf     BlockDriverState *bs = blk_bs(blk);
1521cf2ab8fcSKevin Wolf     BdrvChild *child;
15223412f7b1SJeff Cody     int ret = 0;
15233412f7b1SJeff Cody     VHDXHeader *hdr = NULL;
15243412f7b1SJeff Cody 
15254db7ba3bSKevin Wolf     GRAPH_RDLOCK_GUARD();
15264db7ba3bSKevin Wolf 
15275839e53bSMarkus Armbruster     hdr = g_new0(VHDXHeader, 1);
15283412f7b1SJeff Cody 
15293412f7b1SJeff Cody     hdr->signature       = VHDX_HEADER_SIGNATURE;
15303412f7b1SJeff Cody     hdr->sequence_number = g_random_int();
15313412f7b1SJeff Cody     hdr->log_version     = 0;
15323412f7b1SJeff Cody     hdr->version         = 1;
15333412f7b1SJeff Cody     hdr->log_length      = log_size;
15343412f7b1SJeff Cody     hdr->log_offset      = VHDX_HEADER_SECTION_END;
15353412f7b1SJeff Cody     vhdx_guid_generate(&hdr->file_write_guid);
15363412f7b1SJeff Cody     vhdx_guid_generate(&hdr->data_write_guid);
15373412f7b1SJeff Cody 
1538cf2ab8fcSKevin Wolf     /* XXX Ugly way to get blk->root, but that's a feature, not a bug. This
1539cf2ab8fcSKevin Wolf      * hack makes it obvious that vhdx_write_header() bypasses the BlockBackend
1540cf2ab8fcSKevin Wolf      * here, which it really shouldn't be doing. */
1541cf2ab8fcSKevin Wolf     child = QLIST_FIRST(&bs->parents);
1542cf2ab8fcSKevin Wolf     assert(!QLIST_NEXT(child, next_parent));
1543cf2ab8fcSKevin Wolf 
1544cf2ab8fcSKevin Wolf     ret = vhdx_write_header(child, hdr, VHDX_HEADER1_OFFSET, false);
15453412f7b1SJeff Cody     if (ret < 0) {
15463412f7b1SJeff Cody         goto exit;
15473412f7b1SJeff Cody     }
15483412f7b1SJeff Cody     hdr->sequence_number++;
1549cf2ab8fcSKevin Wolf     ret = vhdx_write_header(child, hdr, VHDX_HEADER2_OFFSET, false);
15503412f7b1SJeff Cody     if (ret < 0) {
15513412f7b1SJeff Cody         goto exit;
15523412f7b1SJeff Cody     }
15533412f7b1SJeff Cody 
15543412f7b1SJeff Cody exit:
15553412f7b1SJeff Cody     g_free(hdr);
15563412f7b1SJeff Cody     return ret;
15573412f7b1SJeff Cody }
15583412f7b1SJeff Cody 
1559e91a8b2fSJeff Cody #define VHDX_METADATA_ENTRY_BUFFER_SIZE \
1560e91a8b2fSJeff Cody                                     (sizeof(VHDXFileParameters)               +\
1561e91a8b2fSJeff Cody                                      sizeof(VHDXVirtualDiskSize)              +\
1562e91a8b2fSJeff Cody                                      sizeof(VHDXPage83Data)                   +\
1563e91a8b2fSJeff Cody                                      sizeof(VHDXVirtualDiskLogicalSectorSize) +\
1564e91a8b2fSJeff Cody                                      sizeof(VHDXVirtualDiskPhysicalSectorSize))
15653412f7b1SJeff Cody 
15663412f7b1SJeff Cody /*
15673412f7b1SJeff Cody  * Create the Metadata entries.
15683412f7b1SJeff Cody  *
15693412f7b1SJeff Cody  * For more details on the entries, see section 3.5 (pg 29) in the
15703412f7b1SJeff Cody  * VHDX 1.00 specification.
15713412f7b1SJeff Cody  *
15723412f7b1SJeff Cody  * We support 5 metadata entries (all required by spec):
15733412f7b1SJeff Cody  *          File Parameters,
15743412f7b1SJeff Cody  *          Virtual Disk Size,
15753412f7b1SJeff Cody  *          Page 83 Data,
15763412f7b1SJeff Cody  *          Logical Sector Size,
15773412f7b1SJeff Cody  *          Physical Sector Size
15783412f7b1SJeff Cody  *
15793412f7b1SJeff Cody  * The first 64KB of the Metadata section is reserved for the metadata
15803412f7b1SJeff Cody  * header and entries; beyond that, the metadata items themselves reside.
15813412f7b1SJeff Cody  */
1582f6b08994SPaolo Bonzini static int coroutine_fn
vhdx_create_new_metadata(BlockBackend * blk,uint64_t image_size,uint32_t block_size,uint32_t sector_size,uint64_t metadata_offset,VHDXImageType type)1583f6b08994SPaolo Bonzini vhdx_create_new_metadata(BlockBackend *blk, uint64_t image_size,
1584f6b08994SPaolo Bonzini                          uint32_t block_size, uint32_t sector_size,
1585f6b08994SPaolo Bonzini                          uint64_t metadata_offset, VHDXImageType type)
15863412f7b1SJeff Cody {
15873412f7b1SJeff Cody     int ret = 0;
15883412f7b1SJeff Cody     uint32_t offset = 0;
15893412f7b1SJeff Cody     void *buffer = NULL;
15903412f7b1SJeff Cody     void *entry_buffer;
1591a8f15a27SDaniel P. Berrange     VHDXMetadataTableHeader *md_table;
15923412f7b1SJeff Cody     VHDXMetadataTableEntry  *md_table_entry;
15933412f7b1SJeff Cody 
15943412f7b1SJeff Cody     /* Metadata entries */
15953412f7b1SJeff Cody     VHDXFileParameters     *mt_file_params;
15963412f7b1SJeff Cody     VHDXVirtualDiskSize    *mt_virtual_size;
15973412f7b1SJeff Cody     VHDXPage83Data         *mt_page83;
15983412f7b1SJeff Cody     VHDXVirtualDiskLogicalSectorSize  *mt_log_sector_size;
15993412f7b1SJeff Cody     VHDXVirtualDiskPhysicalSectorSize *mt_phys_sector_size;
16003412f7b1SJeff Cody 
1601e91a8b2fSJeff Cody     entry_buffer = g_malloc0(VHDX_METADATA_ENTRY_BUFFER_SIZE);
16023412f7b1SJeff Cody 
16033412f7b1SJeff Cody     mt_file_params = entry_buffer;
16043412f7b1SJeff Cody     offset += sizeof(VHDXFileParameters);
16053412f7b1SJeff Cody     mt_virtual_size = entry_buffer + offset;
16063412f7b1SJeff Cody     offset += sizeof(VHDXVirtualDiskSize);
16073412f7b1SJeff Cody     mt_page83 = entry_buffer + offset;
16083412f7b1SJeff Cody     offset += sizeof(VHDXPage83Data);
16093412f7b1SJeff Cody     mt_log_sector_size = entry_buffer + offset;
16103412f7b1SJeff Cody     offset += sizeof(VHDXVirtualDiskLogicalSectorSize);
16113412f7b1SJeff Cody     mt_phys_sector_size = entry_buffer + offset;
16123412f7b1SJeff Cody 
16133412f7b1SJeff Cody     mt_file_params->block_size = cpu_to_le32(block_size);
16143412f7b1SJeff Cody     if (type == VHDX_TYPE_FIXED) {
16153412f7b1SJeff Cody         mt_file_params->data_bits |= VHDX_PARAMS_LEAVE_BLOCKS_ALLOCED;
16161229e46dSPeter Maydell         mt_file_params->data_bits = cpu_to_le32(mt_file_params->data_bits);
16173412f7b1SJeff Cody     }
16183412f7b1SJeff Cody 
16193412f7b1SJeff Cody     vhdx_guid_generate(&mt_page83->page_83_data);
16203412f7b1SJeff Cody     cpu_to_leguids(&mt_page83->page_83_data);
16213412f7b1SJeff Cody     mt_virtual_size->virtual_disk_size        = cpu_to_le64(image_size);
16223412f7b1SJeff Cody     mt_log_sector_size->logical_sector_size   = cpu_to_le32(sector_size);
16233412f7b1SJeff Cody     mt_phys_sector_size->physical_sector_size = cpu_to_le32(sector_size);
16243412f7b1SJeff Cody 
16253412f7b1SJeff Cody     buffer = g_malloc0(VHDX_HEADER_BLOCK_SIZE);
16263412f7b1SJeff Cody     md_table = buffer;
16273412f7b1SJeff Cody 
16283412f7b1SJeff Cody     md_table->signature   = VHDX_METADATA_SIGNATURE;
16293412f7b1SJeff Cody     md_table->entry_count = 5;
16303412f7b1SJeff Cody     vhdx_metadata_header_le_export(md_table);
16313412f7b1SJeff Cody 
16323412f7b1SJeff Cody 
16333412f7b1SJeff Cody     /* This will reference beyond the reserved table portion */
16343412f7b1SJeff Cody     offset = 64 * KiB;
16353412f7b1SJeff Cody 
16363412f7b1SJeff Cody     md_table_entry = buffer + sizeof(VHDXMetadataTableHeader);
16373412f7b1SJeff Cody 
16383412f7b1SJeff Cody     md_table_entry[0].item_id = file_param_guid;
16393412f7b1SJeff Cody     md_table_entry[0].offset  = offset;
16403412f7b1SJeff Cody     md_table_entry[0].length  = sizeof(VHDXFileParameters);
16413412f7b1SJeff Cody     md_table_entry[0].data_bits |= VHDX_META_FLAGS_IS_REQUIRED;
16423412f7b1SJeff Cody     offset += md_table_entry[0].length;
16433412f7b1SJeff Cody     vhdx_metadata_entry_le_export(&md_table_entry[0]);
16443412f7b1SJeff Cody 
16453412f7b1SJeff Cody     md_table_entry[1].item_id = virtual_size_guid;
16463412f7b1SJeff Cody     md_table_entry[1].offset  = offset;
16473412f7b1SJeff Cody     md_table_entry[1].length  = sizeof(VHDXVirtualDiskSize);
16483412f7b1SJeff Cody     md_table_entry[1].data_bits |= VHDX_META_FLAGS_IS_REQUIRED |
16493412f7b1SJeff Cody                                    VHDX_META_FLAGS_IS_VIRTUAL_DISK;
16503412f7b1SJeff Cody     offset += md_table_entry[1].length;
16513412f7b1SJeff Cody     vhdx_metadata_entry_le_export(&md_table_entry[1]);
16523412f7b1SJeff Cody 
16533412f7b1SJeff Cody     md_table_entry[2].item_id = page83_guid;
16543412f7b1SJeff Cody     md_table_entry[2].offset  = offset;
16553412f7b1SJeff Cody     md_table_entry[2].length  = sizeof(VHDXPage83Data);
16563412f7b1SJeff Cody     md_table_entry[2].data_bits |= VHDX_META_FLAGS_IS_REQUIRED |
16573412f7b1SJeff Cody                                    VHDX_META_FLAGS_IS_VIRTUAL_DISK;
16583412f7b1SJeff Cody     offset += md_table_entry[2].length;
16593412f7b1SJeff Cody     vhdx_metadata_entry_le_export(&md_table_entry[2]);
16603412f7b1SJeff Cody 
16613412f7b1SJeff Cody     md_table_entry[3].item_id = logical_sector_guid;
16623412f7b1SJeff Cody     md_table_entry[3].offset  = offset;
16633412f7b1SJeff Cody     md_table_entry[3].length  = sizeof(VHDXVirtualDiskLogicalSectorSize);
16643412f7b1SJeff Cody     md_table_entry[3].data_bits |= VHDX_META_FLAGS_IS_REQUIRED |
16653412f7b1SJeff Cody                                    VHDX_META_FLAGS_IS_VIRTUAL_DISK;
16663412f7b1SJeff Cody     offset += md_table_entry[3].length;
16673412f7b1SJeff Cody     vhdx_metadata_entry_le_export(&md_table_entry[3]);
16683412f7b1SJeff Cody 
16693412f7b1SJeff Cody     md_table_entry[4].item_id = phys_sector_guid;
16703412f7b1SJeff Cody     md_table_entry[4].offset  = offset;
16713412f7b1SJeff Cody     md_table_entry[4].length  = sizeof(VHDXVirtualDiskPhysicalSectorSize);
16723412f7b1SJeff Cody     md_table_entry[4].data_bits |= VHDX_META_FLAGS_IS_REQUIRED |
16733412f7b1SJeff Cody                                    VHDX_META_FLAGS_IS_VIRTUAL_DISK;
16743412f7b1SJeff Cody     vhdx_metadata_entry_le_export(&md_table_entry[4]);
16753412f7b1SJeff Cody 
1676f6b08994SPaolo Bonzini     ret = blk_co_pwrite(blk, metadata_offset, VHDX_HEADER_BLOCK_SIZE, buffer, 0);
16773412f7b1SJeff Cody     if (ret < 0) {
16783412f7b1SJeff Cody         goto exit;
16793412f7b1SJeff Cody     }
16803412f7b1SJeff Cody 
1681f6b08994SPaolo Bonzini     ret = blk_co_pwrite(blk, metadata_offset + (64 * KiB),
1682a9262f55SAlberto Faria                         VHDX_METADATA_ENTRY_BUFFER_SIZE, entry_buffer, 0);
16833412f7b1SJeff Cody     if (ret < 0) {
16843412f7b1SJeff Cody         goto exit;
16853412f7b1SJeff Cody     }
16863412f7b1SJeff Cody 
16873412f7b1SJeff Cody 
16883412f7b1SJeff Cody exit:
16893412f7b1SJeff Cody     g_free(buffer);
16903412f7b1SJeff Cody     g_free(entry_buffer);
16913412f7b1SJeff Cody     return ret;
16923412f7b1SJeff Cody }
16933412f7b1SJeff Cody 
16943412f7b1SJeff Cody /* This create the actual BAT itself.  We currently only support
16953412f7b1SJeff Cody  * 'Dynamic' and 'Fixed' image types.
16963412f7b1SJeff Cody  *
16973412f7b1SJeff Cody  *  Dynamic images: default state of the BAT is all zeroes.
16983412f7b1SJeff Cody  *
16993412f7b1SJeff Cody  *  Fixed images: default state of the BAT is fully populated, with
17003412f7b1SJeff Cody  *                file offsets and state PAYLOAD_BLOCK_FULLY_PRESENT.
17013412f7b1SJeff Cody  */
170206717986SKevin Wolf static int coroutine_fn GRAPH_UNLOCKED
vhdx_create_bat(BlockBackend * blk,BDRVVHDXState * s,uint64_t image_size,VHDXImageType type,bool use_zero_blocks,uint64_t file_offset,uint32_t length,Error ** errp)1703f6b08994SPaolo Bonzini vhdx_create_bat(BlockBackend *blk, BDRVVHDXState *s,
17043412f7b1SJeff Cody                 uint64_t image_size, VHDXImageType type,
17054f75b52aSJeff Cody                 bool use_zero_blocks, uint64_t file_offset,
170655b9392bSMax Reitz                 uint32_t length, Error **errp)
17073412f7b1SJeff Cody {
17083412f7b1SJeff Cody     int ret = 0;
17093412f7b1SJeff Cody     uint64_t data_file_offset;
17103412f7b1SJeff Cody     uint64_t total_sectors = 0;
17113412f7b1SJeff Cody     uint64_t sector_num = 0;
17123412f7b1SJeff Cody     uint64_t unused;
17133412f7b1SJeff Cody     int block_state;
17143412f7b1SJeff Cody     VHDXSectorInfo sinfo;
171506717986SKevin Wolf     bool has_zero_init;
17163412f7b1SJeff Cody 
17173412f7b1SJeff Cody     assert(s->bat == NULL);
17183412f7b1SJeff Cody 
17193412f7b1SJeff Cody     /* this gives a data start after BAT/bitmap entries, and well
17203412f7b1SJeff Cody      * past any metadata entries (with a 4 MB buffer for future
17213412f7b1SJeff Cody      * expansion */
17224f75b52aSJeff Cody     data_file_offset = file_offset + length + 5 * MiB;
17233412f7b1SJeff Cody     total_sectors = image_size >> s->logical_sector_size_bits;
17243412f7b1SJeff Cody 
17253412f7b1SJeff Cody     if (type == VHDX_TYPE_DYNAMIC) {
17263412f7b1SJeff Cody         /* All zeroes, so we can just extend the file - the end of the BAT
17273412f7b1SJeff Cody          * is the furthest thing we have written yet */
1728f6b08994SPaolo Bonzini         ret = blk_co_truncate(blk, data_file_offset, false, PREALLOC_MODE_OFF,
17298c6242b6SKevin Wolf                               0, errp);
17303412f7b1SJeff Cody         if (ret < 0) {
17313412f7b1SJeff Cody             goto exit;
17323412f7b1SJeff Cody         }
17333412f7b1SJeff Cody     } else if (type == VHDX_TYPE_FIXED) {
1734f6b08994SPaolo Bonzini         ret = blk_co_truncate(blk, data_file_offset + image_size, false,
17358c6242b6SKevin Wolf                               PREALLOC_MODE_OFF, 0, errp);
17363412f7b1SJeff Cody         if (ret < 0) {
17373412f7b1SJeff Cody             goto exit;
17383412f7b1SJeff Cody         }
17393412f7b1SJeff Cody     } else {
174055b9392bSMax Reitz         error_setg(errp, "Unsupported image type");
17413412f7b1SJeff Cody         ret = -ENOTSUP;
17423412f7b1SJeff Cody         goto exit;
17433412f7b1SJeff Cody     }
17443412f7b1SJeff Cody 
174506717986SKevin Wolf     bdrv_graph_co_rdlock();
174606717986SKevin Wolf     has_zero_init = bdrv_has_zero_init(blk_bs(blk));
174706717986SKevin Wolf     bdrv_graph_co_rdunlock();
174806717986SKevin Wolf 
17493412f7b1SJeff Cody     if (type == VHDX_TYPE_FIXED ||
17503412f7b1SJeff Cody                 use_zero_blocks ||
175106717986SKevin Wolf                 has_zero_init == 0) {
17523412f7b1SJeff Cody         /* for a fixed file, the default BAT entry is not zero */
1753a67e128aSKevin Wolf         s->bat = g_try_malloc0(length);
1754a011898dSAdelina Tuvenie         if (length && s->bat == NULL) {
175555b9392bSMax Reitz             error_setg(errp, "Failed to allocate memory for the BAT");
1756a67e128aSKevin Wolf             ret = -ENOMEM;
1757a67e128aSKevin Wolf             goto exit;
1758a67e128aSKevin Wolf         }
17593412f7b1SJeff Cody         block_state = type == VHDX_TYPE_FIXED ? PAYLOAD_BLOCK_FULLY_PRESENT :
17603412f7b1SJeff Cody                                                 PAYLOAD_BLOCK_NOT_PRESENT;
17613412f7b1SJeff Cody         block_state = use_zero_blocks ? PAYLOAD_BLOCK_ZERO : block_state;
17623412f7b1SJeff Cody         /* fill the BAT by emulating sector writes of sectors_per_block size */
17633412f7b1SJeff Cody         while (sector_num < total_sectors) {
17643412f7b1SJeff Cody             vhdx_block_translate(s, sector_num, s->sectors_per_block, &sinfo);
17653412f7b1SJeff Cody             sinfo.file_offset = data_file_offset +
17663412f7b1SJeff Cody                                 (sector_num << s->logical_sector_size_bits);
17673412f7b1SJeff Cody             sinfo.file_offset = ROUND_UP(sinfo.file_offset, MiB);
1768db1e80eeSKevin Wolf             vhdx_update_bat_table_entry(blk_bs(blk), s, &sinfo, &unused, &unused,
17693412f7b1SJeff Cody                                         block_state);
17701229e46dSPeter Maydell             s->bat[sinfo.bat_idx] = cpu_to_le64(s->bat[sinfo.bat_idx]);
17713412f7b1SJeff Cody             sector_num += s->sectors_per_block;
17723412f7b1SJeff Cody         }
1773f6b08994SPaolo Bonzini         ret = blk_co_pwrite(blk, file_offset, length, s->bat, 0);
17743412f7b1SJeff Cody         if (ret < 0) {
177555b9392bSMax Reitz             error_setg_errno(errp, -ret, "Failed to write the BAT");
17763412f7b1SJeff Cody             goto exit;
17773412f7b1SJeff Cody         }
17783412f7b1SJeff Cody     }
17793412f7b1SJeff Cody 
17803412f7b1SJeff Cody 
17813412f7b1SJeff Cody 
17823412f7b1SJeff Cody exit:
17833412f7b1SJeff Cody     g_free(s->bat);
17843412f7b1SJeff Cody     return ret;
17853412f7b1SJeff Cody }
17863412f7b1SJeff Cody 
17873412f7b1SJeff Cody /* Creates the region table header, and region table entries.
17883412f7b1SJeff Cody  * There are 2 supported region table entries: BAT, and Metadata/
17893412f7b1SJeff Cody  *
17903412f7b1SJeff Cody  * As the calculations for the BAT region table are also needed
17913412f7b1SJeff Cody  * to create the BAT itself, we will also cause the BAT to be
17923412f7b1SJeff Cody  * created.
17933412f7b1SJeff Cody  */
179406717986SKevin Wolf static int coroutine_fn GRAPH_UNLOCKED
vhdx_create_new_region_table(BlockBackend * blk,uint64_t image_size,uint32_t block_size,uint32_t sector_size,uint32_t log_size,bool use_zero_blocks,VHDXImageType type,uint64_t * metadata_offset,Error ** errp)1795f6b08994SPaolo Bonzini vhdx_create_new_region_table(BlockBackend *blk, uint64_t image_size,
1796f6b08994SPaolo Bonzini                              uint32_t block_size, uint32_t sector_size,
1797f6b08994SPaolo Bonzini                              uint32_t log_size, bool use_zero_blocks,
1798f6b08994SPaolo Bonzini                              VHDXImageType type, uint64_t *metadata_offset,
179955b9392bSMax Reitz                              Error **errp)
18003412f7b1SJeff Cody {
18013412f7b1SJeff Cody     int ret = 0;
18023412f7b1SJeff Cody     uint32_t offset = 0;
18033412f7b1SJeff Cody     void *buffer = NULL;
18044f75b52aSJeff Cody     uint64_t bat_file_offset;
18054f75b52aSJeff Cody     uint32_t bat_length;
18063412f7b1SJeff Cody     BDRVVHDXState *s = NULL;
18073412f7b1SJeff Cody     VHDXRegionTableHeader *region_table;
18083412f7b1SJeff Cody     VHDXRegionTableEntry *rt_bat;
18093412f7b1SJeff Cody     VHDXRegionTableEntry *rt_metadata;
18103412f7b1SJeff Cody 
18113412f7b1SJeff Cody     assert(metadata_offset != NULL);
18123412f7b1SJeff Cody 
18133412f7b1SJeff Cody     /* Populate enough of the BDRVVHDXState to be able to use the
18143412f7b1SJeff Cody      * pre-existing BAT calculation, translation, and update functions */
18155839e53bSMarkus Armbruster     s = g_new0(BDRVVHDXState, 1);
18163412f7b1SJeff Cody 
18173412f7b1SJeff Cody     s->chunk_ratio = (VHDX_MAX_SECTORS_PER_BLOCK) *
18183412f7b1SJeff Cody                      (uint64_t) sector_size / (uint64_t) block_size;
18193412f7b1SJeff Cody 
18203412f7b1SJeff Cody     s->sectors_per_block = block_size / sector_size;
18213412f7b1SJeff Cody     s->virtual_disk_size = image_size;
18223412f7b1SJeff Cody     s->block_size = block_size;
18233412f7b1SJeff Cody     s->logical_sector_size = sector_size;
18243412f7b1SJeff Cody 
18253412f7b1SJeff Cody     vhdx_set_shift_bits(s);
18263412f7b1SJeff Cody 
18273412f7b1SJeff Cody     vhdx_calc_bat_entries(s);
18283412f7b1SJeff Cody 
18293412f7b1SJeff Cody     /* At this point the VHDX state is populated enough for creation */
18303412f7b1SJeff Cody 
18313412f7b1SJeff Cody     /* a single buffer is used so we can calculate the checksum over the
18323412f7b1SJeff Cody      * entire 64KB block */
18333412f7b1SJeff Cody     buffer = g_malloc0(VHDX_HEADER_BLOCK_SIZE);
18343412f7b1SJeff Cody     region_table = buffer;
18353412f7b1SJeff Cody     offset += sizeof(VHDXRegionTableHeader);
18363412f7b1SJeff Cody     rt_bat = buffer + offset;
18373412f7b1SJeff Cody     offset += sizeof(VHDXRegionTableEntry);
18383412f7b1SJeff Cody     rt_metadata  = buffer + offset;
18393412f7b1SJeff Cody 
18403412f7b1SJeff Cody     region_table->signature = VHDX_REGION_SIGNATURE;
18413412f7b1SJeff Cody     region_table->entry_count = 2;   /* BAT and Metadata */
18423412f7b1SJeff Cody 
18433412f7b1SJeff Cody     rt_bat->guid        = bat_guid;
18443412f7b1SJeff Cody     rt_bat->length      = ROUND_UP(s->bat_entries * sizeof(VHDXBatEntry), MiB);
18453412f7b1SJeff Cody     rt_bat->file_offset = ROUND_UP(VHDX_HEADER_SECTION_END + log_size, MiB);
18463412f7b1SJeff Cody     s->bat_offset = rt_bat->file_offset;
18473412f7b1SJeff Cody 
18483412f7b1SJeff Cody     rt_metadata->guid        = metadata_guid;
18493412f7b1SJeff Cody     rt_metadata->file_offset = ROUND_UP(rt_bat->file_offset + rt_bat->length,
18503412f7b1SJeff Cody                                         MiB);
18513412f7b1SJeff Cody     rt_metadata->length      = 1 * MiB; /* min size, and more than enough */
18523412f7b1SJeff Cody     *metadata_offset = rt_metadata->file_offset;
18533412f7b1SJeff Cody 
18544f75b52aSJeff Cody     bat_file_offset = rt_bat->file_offset;
18554f75b52aSJeff Cody     bat_length = rt_bat->length;
18564f75b52aSJeff Cody 
18574f75b52aSJeff Cody     vhdx_region_header_le_export(region_table);
18584f75b52aSJeff Cody     vhdx_region_entry_le_export(rt_bat);
18594f75b52aSJeff Cody     vhdx_region_entry_le_export(rt_metadata);
18604f75b52aSJeff Cody 
18613412f7b1SJeff Cody     vhdx_update_checksum(buffer, VHDX_HEADER_BLOCK_SIZE,
18623412f7b1SJeff Cody                          offsetof(VHDXRegionTableHeader, checksum));
18633412f7b1SJeff Cody 
18643412f7b1SJeff Cody 
18653412f7b1SJeff Cody     /* The region table gives us the data we need to create the BAT,
18663412f7b1SJeff Cody      * so do that now */
1867db1e80eeSKevin Wolf     ret = vhdx_create_bat(blk, s, image_size, type, use_zero_blocks,
186855b9392bSMax Reitz                           bat_file_offset, bat_length, errp);
18694f75b52aSJeff Cody     if (ret < 0) {
18704f75b52aSJeff Cody         goto exit;
18714f75b52aSJeff Cody     }
18723412f7b1SJeff Cody 
18733412f7b1SJeff Cody     /* Now write out the region headers to disk */
1874f6b08994SPaolo Bonzini     ret = blk_co_pwrite(blk, VHDX_REGION_TABLE_OFFSET, VHDX_HEADER_BLOCK_SIZE,
1875a9262f55SAlberto Faria                         buffer, 0);
18763412f7b1SJeff Cody     if (ret < 0) {
187755b9392bSMax Reitz         error_setg_errno(errp, -ret, "Failed to write first region table");
18783412f7b1SJeff Cody         goto exit;
18793412f7b1SJeff Cody     }
18803412f7b1SJeff Cody 
1881f6b08994SPaolo Bonzini     ret = blk_co_pwrite(blk, VHDX_REGION_TABLE2_OFFSET, VHDX_HEADER_BLOCK_SIZE,
1882a9262f55SAlberto Faria                         buffer, 0);
18833412f7b1SJeff Cody     if (ret < 0) {
188455b9392bSMax Reitz         error_setg_errno(errp, -ret, "Failed to write second region table");
18853412f7b1SJeff Cody         goto exit;
18863412f7b1SJeff Cody     }
18873412f7b1SJeff Cody 
18883412f7b1SJeff Cody exit:
18893412f7b1SJeff Cody     g_free(s);
18903412f7b1SJeff Cody     g_free(buffer);
18913412f7b1SJeff Cody     return ret;
18923412f7b1SJeff Cody }
18933412f7b1SJeff Cody 
18943412f7b1SJeff Cody /* We need to create the following elements:
18953412f7b1SJeff Cody  *
18963412f7b1SJeff Cody  *    .-----------------------------------------------------------------.
18973412f7b1SJeff Cody  *    |   (A)    |   (B)    |    (C)    |     (D)       |     (E)       |
18983412f7b1SJeff Cody  *    |  File ID |  Header1 |  Header 2 |  Region Tbl 1 |  Region Tbl 2 |
18993412f7b1SJeff Cody  *    |          |          |           |               |               |
19003412f7b1SJeff Cody  *    .-----------------------------------------------------------------.
19013412f7b1SJeff Cody  *    0         64KB      128KB       192KB           256KB           320KB
19023412f7b1SJeff Cody  *
19033412f7b1SJeff Cody  *
19043412f7b1SJeff Cody  *    .---- ~ ----------- ~ ------------ ~ ---------------- ~ -----------.
19053412f7b1SJeff Cody  *    |     (F)     |     (G)       |    (H)    |                        |
19063412f7b1SJeff Cody  *    | Journal Log |  BAT / Bitmap |  Metadata |  .... data ......      |
19073412f7b1SJeff Cody  *    |             |               |           |                        |
19083412f7b1SJeff Cody  *    .---- ~ ----------- ~ ------------ ~ ---------------- ~ -----------.
19093412f7b1SJeff Cody  *   1MB
19103412f7b1SJeff Cody  */
19114db7ba3bSKevin Wolf static int coroutine_fn GRAPH_UNLOCKED
vhdx_co_create(BlockdevCreateOptions * opts,Error ** errp)1912622d30afSKevin Wolf vhdx_co_create(BlockdevCreateOptions *opts, Error **errp)
19133412f7b1SJeff Cody {
191409b68dabSKevin Wolf     BlockdevCreateOptionsVhdx *vhdx_opts;
191509b68dabSKevin Wolf     BlockBackend *blk = NULL;
191609b68dabSKevin Wolf     BlockDriverState *bs = NULL;
191709b68dabSKevin Wolf 
19183412f7b1SJeff Cody     int ret = 0;
191909b68dabSKevin Wolf     uint64_t image_size;
192009b68dabSKevin Wolf     uint32_t log_size;
192109b68dabSKevin Wolf     uint32_t block_size;
19223412f7b1SJeff Cody     uint64_t signature;
19233412f7b1SJeff Cody     uint64_t metadata_offset;
19243412f7b1SJeff Cody     bool use_zero_blocks = false;
19253412f7b1SJeff Cody 
19263412f7b1SJeff Cody     gunichar2 *creator = NULL;
19273412f7b1SJeff Cody     glong creator_items;
19283412f7b1SJeff Cody     VHDXImageType image_type;
19293412f7b1SJeff Cody 
193009b68dabSKevin Wolf     assert(opts->driver == BLOCKDEV_DRIVER_VHDX);
193109b68dabSKevin Wolf     vhdx_opts = &opts->u.vhdx;
19323412f7b1SJeff Cody 
193309b68dabSKevin Wolf     /* Validate options and set default values */
193409b68dabSKevin Wolf     image_size = vhdx_opts->size;
19353412f7b1SJeff Cody     if (image_size > VHDX_MAX_IMAGE_SIZE) {
19360fcc38e7SKevin Wolf         error_setg(errp, "Image size too large; max of 64TB");
193709b68dabSKevin Wolf         return -EINVAL;
19383412f7b1SJeff Cody     }
19393412f7b1SJeff Cody 
194009b68dabSKevin Wolf     if (!vhdx_opts->has_log_size) {
194109b68dabSKevin Wolf         log_size = DEFAULT_LOG_SIZE;
19423412f7b1SJeff Cody     } else {
19436f16f7c5SKevin Wolf         if (vhdx_opts->log_size > UINT32_MAX) {
19446f16f7c5SKevin Wolf             error_setg(errp, "Log size must be smaller than 4 GB");
19456f16f7c5SKevin Wolf             return -EINVAL;
19466f16f7c5SKevin Wolf         }
194709b68dabSKevin Wolf         log_size = vhdx_opts->log_size;
194809b68dabSKevin Wolf     }
194909b68dabSKevin Wolf     if (log_size < MiB || (log_size % MiB) != 0) {
19500fcc38e7SKevin Wolf         error_setg(errp, "Log size must be a multiple of 1 MB");
195109b68dabSKevin Wolf         return -EINVAL;
195209b68dabSKevin Wolf     }
195309b68dabSKevin Wolf 
195409b68dabSKevin Wolf     if (!vhdx_opts->has_block_state_zero) {
195509b68dabSKevin Wolf         use_zero_blocks = true;
195609b68dabSKevin Wolf     } else {
195709b68dabSKevin Wolf         use_zero_blocks = vhdx_opts->block_state_zero;
195809b68dabSKevin Wolf     }
195909b68dabSKevin Wolf 
196009b68dabSKevin Wolf     if (!vhdx_opts->has_subformat) {
196109b68dabSKevin Wolf         vhdx_opts->subformat = BLOCKDEV_VHDX_SUBFORMAT_DYNAMIC;
196209b68dabSKevin Wolf     }
196309b68dabSKevin Wolf 
196409b68dabSKevin Wolf     switch (vhdx_opts->subformat) {
196509b68dabSKevin Wolf     case BLOCKDEV_VHDX_SUBFORMAT_DYNAMIC:
196609b68dabSKevin Wolf         image_type = VHDX_TYPE_DYNAMIC;
196709b68dabSKevin Wolf         break;
196809b68dabSKevin Wolf     case BLOCKDEV_VHDX_SUBFORMAT_FIXED:
196909b68dabSKevin Wolf         image_type = VHDX_TYPE_FIXED;
197009b68dabSKevin Wolf         break;
197109b68dabSKevin Wolf     default:
197209b68dabSKevin Wolf         g_assert_not_reached();
19733412f7b1SJeff Cody     }
19743412f7b1SJeff Cody 
19753412f7b1SJeff Cody     /* These are pretty arbitrary, and mainly designed to keep the BAT
19763412f7b1SJeff Cody      * size reasonable to load into RAM */
197709b68dabSKevin Wolf     if (vhdx_opts->has_block_size) {
197809b68dabSKevin Wolf         block_size = vhdx_opts->block_size;
197909b68dabSKevin Wolf     } else {
19803412f7b1SJeff Cody         if (image_size > 32 * TiB) {
19813412f7b1SJeff Cody             block_size = 64 * MiB;
19823412f7b1SJeff Cody         } else if (image_size > (uint64_t) 100 * GiB) {
19833412f7b1SJeff Cody             block_size = 32 * MiB;
19843412f7b1SJeff Cody         } else if (image_size > 1 * GiB) {
19853412f7b1SJeff Cody             block_size = 16 * MiB;
19863412f7b1SJeff Cody         } else {
19873412f7b1SJeff Cody             block_size = 8 * MiB;
19883412f7b1SJeff Cody         }
19893412f7b1SJeff Cody     }
19903412f7b1SJeff Cody 
199109b68dabSKevin Wolf     if (block_size < MiB || (block_size % MiB) != 0) {
19920fcc38e7SKevin Wolf         error_setg(errp, "Block size must be a multiple of 1 MB");
199309b68dabSKevin Wolf         return -EINVAL;
199409b68dabSKevin Wolf     }
1995b412f494SKevin Wolf     if (!is_power_of_2(block_size)) {
1996b412f494SKevin Wolf         error_setg(errp, "Block size must be a power of two");
1997b412f494SKevin Wolf         return -EINVAL;
1998b412f494SKevin Wolf     }
199909b68dabSKevin Wolf     if (block_size > VHDX_BLOCK_SIZE_MAX) {
2000e9991e29SStefano Garzarella         error_setg(errp, "Block size must not exceed %" PRId64,
2001e9991e29SStefano Garzarella                    VHDX_BLOCK_SIZE_MAX);
200209b68dabSKevin Wolf         return -EINVAL;
200309b68dabSKevin Wolf     }
20043412f7b1SJeff Cody 
200509b68dabSKevin Wolf     /* Create BlockBackend to write to the image */
200641e089cbSKevin Wolf     bs = bdrv_co_open_blockdev_ref(vhdx_opts->file, errp);
200709b68dabSKevin Wolf     if (bs == NULL) {
200809b68dabSKevin Wolf         return -EIO;
200909b68dabSKevin Wolf     }
20103412f7b1SJeff Cody 
201141e089cbSKevin Wolf     blk = blk_co_new_with_bs(bs, BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL,
2012a3aeeab5SEric Blake                              errp);
2013a3aeeab5SEric Blake     if (!blk) {
2014a3aeeab5SEric Blake         ret = -EPERM;
201509b68dabSKevin Wolf         goto delete_and_exit;
20163412f7b1SJeff Cody     }
201710bf03afSKevin Wolf     blk_set_allow_write_beyond_eof(blk, true);
201810bf03afSKevin Wolf 
20193412f7b1SJeff Cody     /* Create (A) */
20203412f7b1SJeff Cody 
20213412f7b1SJeff Cody     /* The creator field is optional, but may be useful for
20223412f7b1SJeff Cody      * debugging / diagnostics */
20233412f7b1SJeff Cody     creator = g_utf8_to_utf16("QEMU v" QEMU_VERSION, -1, NULL,
20243412f7b1SJeff Cody                               &creator_items, NULL);
20253412f7b1SJeff Cody     signature = cpu_to_le64(VHDX_FILE_SIGNATURE);
2026eb342749SAlberto Faria     ret = blk_co_pwrite(blk, VHDX_FILE_ID_OFFSET, sizeof(signature), &signature,
20278341f00dSEric Blake                         0);
20283412f7b1SJeff Cody     if (ret < 0) {
202955b9392bSMax Reitz         error_setg_errno(errp, -ret, "Failed to write file signature");
20303412f7b1SJeff Cody         goto delete_and_exit;
20313412f7b1SJeff Cody     }
20323412f7b1SJeff Cody     if (creator) {
2033eb342749SAlberto Faria         ret = blk_co_pwrite(blk, VHDX_FILE_ID_OFFSET + sizeof(signature),
2034a9262f55SAlberto Faria                             creator_items * sizeof(gunichar2), creator, 0);
20353412f7b1SJeff Cody         if (ret < 0) {
203655b9392bSMax Reitz             error_setg_errno(errp, -ret, "Failed to write creator field");
20373412f7b1SJeff Cody             goto delete_and_exit;
20383412f7b1SJeff Cody         }
20393412f7b1SJeff Cody     }
20403412f7b1SJeff Cody 
20413412f7b1SJeff Cody 
20423412f7b1SJeff Cody     /* Creates (B),(C) */
2043db1e80eeSKevin Wolf     ret = vhdx_create_new_headers(blk, image_size, log_size);
20443412f7b1SJeff Cody     if (ret < 0) {
204555b9392bSMax Reitz         error_setg_errno(errp, -ret, "Failed to write image headers");
20463412f7b1SJeff Cody         goto delete_and_exit;
20473412f7b1SJeff Cody     }
20483412f7b1SJeff Cody 
20493412f7b1SJeff Cody     /* Creates (D),(E),(G) explicitly. (F) created as by-product */
2050db1e80eeSKevin Wolf     ret = vhdx_create_new_region_table(blk, image_size, block_size, 512,
20513412f7b1SJeff Cody                                        log_size, use_zero_blocks, image_type,
205255b9392bSMax Reitz                                        &metadata_offset, errp);
20533412f7b1SJeff Cody     if (ret < 0) {
20543412f7b1SJeff Cody         goto delete_and_exit;
20553412f7b1SJeff Cody     }
20563412f7b1SJeff Cody 
20573412f7b1SJeff Cody     /* Creates (H) */
2058db1e80eeSKevin Wolf     ret = vhdx_create_new_metadata(blk, image_size, block_size, 512,
20593412f7b1SJeff Cody                                    metadata_offset, image_type);
20603412f7b1SJeff Cody     if (ret < 0) {
206155b9392bSMax Reitz         error_setg_errno(errp, -ret, "Failed to initialize metadata");
20623412f7b1SJeff Cody         goto delete_and_exit;
20633412f7b1SJeff Cody     }
20643412f7b1SJeff Cody 
20654a5f2779SKevin Wolf     ret = 0;
20663412f7b1SJeff Cody delete_and_exit:
2067b2ab5f54SKevin Wolf     blk_co_unref(blk);
2068b2ab5f54SKevin Wolf     bdrv_co_unref(bs);
20693412f7b1SJeff Cody     g_free(creator);
20703412f7b1SJeff Cody     return ret;
20713412f7b1SJeff Cody }
20723412f7b1SJeff Cody 
20734db7ba3bSKevin Wolf static int coroutine_fn GRAPH_UNLOCKED
vhdx_co_create_opts(BlockDriver * drv,const char * filename,QemuOpts * opts,Error ** errp)20744ec8df01SKevin Wolf vhdx_co_create_opts(BlockDriver *drv, const char *filename,
20754ec8df01SKevin Wolf                     QemuOpts *opts, Error **errp)
207609b68dabSKevin Wolf {
207709b68dabSKevin Wolf     BlockdevCreateOptions *create_options = NULL;
207892adf9dbSMarkus Armbruster     QDict *qdict;
207909b68dabSKevin Wolf     Visitor *v;
208009b68dabSKevin Wolf     BlockDriverState *bs = NULL;
208109b68dabSKevin Wolf     int ret;
208209b68dabSKevin Wolf 
208309b68dabSKevin Wolf     static const QDictRenames opt_renames[] = {
208409b68dabSKevin Wolf         { VHDX_BLOCK_OPT_LOG_SIZE,      "log-size" },
208509b68dabSKevin Wolf         { VHDX_BLOCK_OPT_BLOCK_SIZE,    "block-size" },
208609b68dabSKevin Wolf         { VHDX_BLOCK_OPT_ZERO,          "block-state-zero" },
208709b68dabSKevin Wolf         { NULL, NULL },
208809b68dabSKevin Wolf     };
208909b68dabSKevin Wolf 
209009b68dabSKevin Wolf     /* Parse options and convert legacy syntax */
209109b68dabSKevin Wolf     qdict = qemu_opts_to_qdict_filtered(opts, NULL, &vhdx_create_opts, true);
209209b68dabSKevin Wolf 
209309b68dabSKevin Wolf     if (!qdict_rename_keys(qdict, opt_renames, errp)) {
209409b68dabSKevin Wolf         ret = -EINVAL;
209509b68dabSKevin Wolf         goto fail;
209609b68dabSKevin Wolf     }
209709b68dabSKevin Wolf 
209809b68dabSKevin Wolf     /* Create and open the file (protocol layer) */
20992475a0d0SEmanuele Giuseppe Esposito     ret = bdrv_co_create_file(filename, opts, errp);
210009b68dabSKevin Wolf     if (ret < 0) {
210109b68dabSKevin Wolf         goto fail;
210209b68dabSKevin Wolf     }
210309b68dabSKevin Wolf 
210441e089cbSKevin Wolf     bs = bdrv_co_open(filename, NULL, NULL,
210509b68dabSKevin Wolf                       BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
210609b68dabSKevin Wolf     if (bs == NULL) {
210709b68dabSKevin Wolf         ret = -EIO;
210809b68dabSKevin Wolf         goto fail;
210909b68dabSKevin Wolf     }
211009b68dabSKevin Wolf 
211109b68dabSKevin Wolf     /* Now get the QAPI type BlockdevCreateOptions */
211209b68dabSKevin Wolf     qdict_put_str(qdict, "driver", "vhdx");
211309b68dabSKevin Wolf     qdict_put_str(qdict, "file", bs->node_name);
211409b68dabSKevin Wolf 
2115af91062eSMarkus Armbruster     v = qobject_input_visitor_new_flat_confused(qdict, errp);
2116af91062eSMarkus Armbruster     if (!v) {
211709b68dabSKevin Wolf         ret = -EINVAL;
211809b68dabSKevin Wolf         goto fail;
211909b68dabSKevin Wolf     }
212009b68dabSKevin Wolf 
2121b11a093cSMarkus Armbruster     visit_type_BlockdevCreateOptions(v, NULL, &create_options, errp);
212209b68dabSKevin Wolf     visit_free(v);
2123b11a093cSMarkus Armbruster     if (!create_options) {
212409b68dabSKevin Wolf         ret = -EINVAL;
212509b68dabSKevin Wolf         goto fail;
212609b68dabSKevin Wolf     }
212709b68dabSKevin Wolf 
212809b68dabSKevin Wolf     /* Silently round up sizes:
212909b68dabSKevin Wolf      * The image size is rounded to 512 bytes. Make the block and log size
213009b68dabSKevin Wolf      * close to what was specified, but must be at least 1MB, and a multiple of
213109b68dabSKevin Wolf      * 1 MB. Also respect VHDX_BLOCK_SIZE_MAX for block sizes. block_size = 0
213209b68dabSKevin Wolf      * means auto, which is represented by a missing key in QAPI. */
213309b68dabSKevin Wolf     assert(create_options->driver == BLOCKDEV_DRIVER_VHDX);
213409b68dabSKevin Wolf     create_options->u.vhdx.size =
213509b68dabSKevin Wolf         ROUND_UP(create_options->u.vhdx.size, BDRV_SECTOR_SIZE);
213609b68dabSKevin Wolf 
213709b68dabSKevin Wolf     if (create_options->u.vhdx.has_log_size) {
213809b68dabSKevin Wolf         create_options->u.vhdx.log_size =
213909b68dabSKevin Wolf             ROUND_UP(create_options->u.vhdx.log_size, MiB);
214009b68dabSKevin Wolf     }
214109b68dabSKevin Wolf     if (create_options->u.vhdx.has_block_size) {
214209b68dabSKevin Wolf         create_options->u.vhdx.block_size =
214309b68dabSKevin Wolf             ROUND_UP(create_options->u.vhdx.block_size, MiB);
214409b68dabSKevin Wolf 
214509b68dabSKevin Wolf         if (create_options->u.vhdx.block_size == 0) {
214609b68dabSKevin Wolf             create_options->u.vhdx.has_block_size = false;
214709b68dabSKevin Wolf         }
214809b68dabSKevin Wolf         if (create_options->u.vhdx.block_size > VHDX_BLOCK_SIZE_MAX) {
214909b68dabSKevin Wolf             create_options->u.vhdx.block_size = VHDX_BLOCK_SIZE_MAX;
215009b68dabSKevin Wolf         }
215109b68dabSKevin Wolf     }
215209b68dabSKevin Wolf 
215309b68dabSKevin Wolf     /* Create the vhdx image (format layer) */
215409b68dabSKevin Wolf     ret = vhdx_co_create(create_options, errp);
215509b68dabSKevin Wolf 
215609b68dabSKevin Wolf fail:
2157cb3e7f08SMarc-André Lureau     qobject_unref(qdict);
2158b2ab5f54SKevin Wolf     bdrv_co_unref(bs);
215909b68dabSKevin Wolf     qapi_free_BlockdevCreateOptions(create_options);
216009b68dabSKevin Wolf     return ret;
216109b68dabSKevin Wolf }
216209b68dabSKevin Wolf 
21637e30e6a6SJeff Cody /* If opened r/w, the VHDX driver will automatically replay the log,
21647e30e6a6SJeff Cody  * if one is present, inside the vhdx_open() call.
21657e30e6a6SJeff Cody  *
21667e30e6a6SJeff Cody  * If qemu-img check -r all is called, the image is automatically opened
21677e30e6a6SJeff Cody  * r/w and any log has already been replayed, so there is nothing (currently)
21687e30e6a6SJeff Cody  * for us to do here
21697e30e6a6SJeff Cody  */
217079a55866SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
vhdx_co_check(BlockDriverState * bs,BdrvCheckResult * result,BdrvCheckMode fix)217179a55866SKevin Wolf vhdx_co_check(BlockDriverState *bs, BdrvCheckResult *result,
21727e30e6a6SJeff Cody               BdrvCheckMode fix)
21737e30e6a6SJeff Cody {
21747e30e6a6SJeff Cody     BDRVVHDXState *s = bs->opaque;
21757e30e6a6SJeff Cody 
21767e30e6a6SJeff Cody     if (s->log_replayed_on_open) {
21777e30e6a6SJeff Cody         result->corruptions_fixed++;
21787e30e6a6SJeff Cody     }
21796caaad46SPeter Lieven 
21806caaad46SPeter Lieven     vhdx_check_bat_entries(bs, &result->corruptions);
21816caaad46SPeter Lieven 
21827e30e6a6SJeff Cody     return 0;
21837e30e6a6SJeff Cody }
21847e30e6a6SJeff Cody 
vhdx_has_zero_init(BlockDriverState * bs)218506717986SKevin Wolf static int GRAPH_RDLOCK vhdx_has_zero_init(BlockDriverState *bs)
21869956688aSMax Reitz {
21879956688aSMax Reitz     BDRVVHDXState *s = bs->opaque;
21889956688aSMax Reitz     int state;
21899956688aSMax Reitz 
21909956688aSMax Reitz     /*
21919956688aSMax Reitz      * Check the subformat: Fixed images have all BAT entries present,
21929956688aSMax Reitz      * dynamic images have none (right after creation).  It is
21939956688aSMax Reitz      * therefore enough to check the first BAT entry.
21949956688aSMax Reitz      */
21959956688aSMax Reitz     if (!s->bat_entries) {
21969956688aSMax Reitz         return 1;
21979956688aSMax Reitz     }
21989956688aSMax Reitz 
21999956688aSMax Reitz     state = s->bat[0] & VHDX_BAT_STATE_BIT_MASK;
22009956688aSMax Reitz     if (state == PAYLOAD_BLOCK_FULLY_PRESENT) {
22019956688aSMax Reitz         /* Fixed subformat */
22029956688aSMax Reitz         return bdrv_has_zero_init(bs->file->bs);
22039956688aSMax Reitz     }
22049956688aSMax Reitz 
22059956688aSMax Reitz     /* Dynamic subformat */
22069956688aSMax Reitz     return 1;
22079956688aSMax Reitz }
22089956688aSMax Reitz 
22095366092cSChunyan Liu static QemuOptsList vhdx_create_opts = {
22105366092cSChunyan Liu     .name = "vhdx-create-opts",
22115366092cSChunyan Liu     .head = QTAILQ_HEAD_INITIALIZER(vhdx_create_opts.head),
22125366092cSChunyan Liu     .desc = {
22133412f7b1SJeff Cody         {
22143412f7b1SJeff Cody            .name = BLOCK_OPT_SIZE,
22155366092cSChunyan Liu            .type = QEMU_OPT_SIZE,
22163412f7b1SJeff Cody            .help = "Virtual disk size; max of 64TB."
22173412f7b1SJeff Cody        },
22183412f7b1SJeff Cody        {
22193412f7b1SJeff Cody            .name = VHDX_BLOCK_OPT_LOG_SIZE,
22205366092cSChunyan Liu            .type = QEMU_OPT_SIZE,
22215366092cSChunyan Liu            .def_value_str = stringify(DEFAULT_LOG_SIZE),
22223412f7b1SJeff Cody            .help = "Log size; min 1MB."
22233412f7b1SJeff Cody        },
22243412f7b1SJeff Cody        {
22253412f7b1SJeff Cody            .name = VHDX_BLOCK_OPT_BLOCK_SIZE,
22265366092cSChunyan Liu            .type = QEMU_OPT_SIZE,
22275366092cSChunyan Liu            .def_value_str = stringify(0),
222878ee6bd0SPhilippe Mathieu-Daudé            .help = "Block Size; min 1MB, max 256MB. "
22293412f7b1SJeff Cody                    "0 means auto-calculate based on image size."
22303412f7b1SJeff Cody        },
22313412f7b1SJeff Cody        {
22323412f7b1SJeff Cody            .name = BLOCK_OPT_SUBFMT,
22335366092cSChunyan Liu            .type = QEMU_OPT_STRING,
223478ee6bd0SPhilippe Mathieu-Daudé            .help = "VHDX format type, can be either 'dynamic' or 'fixed'. "
22353412f7b1SJeff Cody                    "Default is 'dynamic'."
22363412f7b1SJeff Cody        },
22373412f7b1SJeff Cody        {
22383412f7b1SJeff Cody            .name = VHDX_BLOCK_OPT_ZERO,
22395366092cSChunyan Liu            .type = QEMU_OPT_BOOL,
224078ee6bd0SPhilippe Mathieu-Daudé            .help = "Force use of payload blocks of type 'ZERO'. "
224178ee6bd0SPhilippe Mathieu-Daudé                    "Non-standard, but default.  Do not set to 'off' when "
224230af51ceSJeff Cody                    "using 'qemu-img convert' with subformat=dynamic."
22433412f7b1SJeff Cody        },
22443412f7b1SJeff Cody        { NULL }
22455366092cSChunyan Liu     }
22463412f7b1SJeff Cody };
22473412f7b1SJeff Cody 
2248e8d4e5ffSJeff Cody static BlockDriver bdrv_vhdx = {
2249e8d4e5ffSJeff Cody     .format_name            = "vhdx",
2250e8d4e5ffSJeff Cody     .instance_size          = sizeof(BDRVVHDXState),
2251e8d4e5ffSJeff Cody     .bdrv_probe             = vhdx_probe,
2252e8d4e5ffSJeff Cody     .bdrv_open              = vhdx_open,
2253e8d4e5ffSJeff Cody     .bdrv_close             = vhdx_close,
2254e8d4e5ffSJeff Cody     .bdrv_reopen_prepare    = vhdx_reopen_prepare,
225569dca43dSMax Reitz     .bdrv_child_perm        = bdrv_default_perms,
2256e8d4e5ffSJeff Cody     .bdrv_co_readv          = vhdx_co_readv,
2257e8d4e5ffSJeff Cody     .bdrv_co_writev         = vhdx_co_writev,
225809b68dabSKevin Wolf     .bdrv_co_create         = vhdx_co_create,
2259efc75e2aSStefan Hajnoczi     .bdrv_co_create_opts    = vhdx_co_create_opts,
22603d47eb0aSEmanuele Giuseppe Esposito     .bdrv_co_get_info       = vhdx_co_get_info,
22612fd61638SPaolo Bonzini     .bdrv_co_check          = vhdx_co_check,
22629956688aSMax Reitz     .bdrv_has_zero_init     = vhdx_has_zero_init,
22633412f7b1SJeff Cody 
2264d67066d8SMax Reitz     .is_format              = true,
22655366092cSChunyan Liu     .create_opts            = &vhdx_create_opts,
2266e8d4e5ffSJeff Cody };
2267e8d4e5ffSJeff Cody 
bdrv_vhdx_init(void)2268e8d4e5ffSJeff Cody static void bdrv_vhdx_init(void)
2269e8d4e5ffSJeff Cody {
2270e8d4e5ffSJeff Cody     bdrv_register(&bdrv_vhdx);
2271e8d4e5ffSJeff Cody }
2272e8d4e5ffSJeff Cody 
2273e8d4e5ffSJeff Cody block_init(bdrv_vhdx_init);
2274