xref: /openbmc/qemu/block/vhdx.c (revision a9ded601)
1 /*
2  * Block driver for Hyper-V VHDX Images
3  *
4  * Copyright (c) 2013 Red Hat, Inc.,
5  *
6  * Authors:
7  *  Jeff Cody <jcody@redhat.com>
8  *
9  *  This is based on the "VHDX Format Specification v1.00", published 8/25/2012
10  *  by Microsoft:
11  *      https://www.microsoft.com/en-us/download/details.aspx?id=34750
12  *
13  * This work is licensed under the terms of the GNU LGPL, version 2 or later.
14  * See the COPYING.LIB file in the top-level directory.
15  *
16  */
17 
18 #include "qemu/osdep.h"
19 #include "qapi/error.h"
20 #include "qemu-common.h"
21 #include "block/block_int.h"
22 #include "sysemu/block-backend.h"
23 #include "qemu/module.h"
24 #include "qemu/crc32c.h"
25 #include "qemu/bswap.h"
26 #include "block/vhdx.h"
27 #include "migration/blocker.h"
28 #include "qemu/uuid.h"
29 
30 /* Options for VHDX creation */
31 
32 #define VHDX_BLOCK_OPT_LOG_SIZE   "log_size"
33 #define VHDX_BLOCK_OPT_BLOCK_SIZE "block_size"
34 #define VHDX_BLOCK_OPT_ZERO "block_state_zero"
35 
36 typedef enum VHDXImageType {
37     VHDX_TYPE_DYNAMIC = 0,
38     VHDX_TYPE_FIXED,
39     VHDX_TYPE_DIFFERENCING,   /* Currently unsupported */
40 } VHDXImageType;
41 
42 /* Several metadata and region table data entries are identified by
43  * guids in  a MS-specific GUID format. */
44 
45 
46 /* ------- Known Region Table GUIDs ---------------------- */
47 static const MSGUID bat_guid =      { .data1 = 0x2dc27766,
48                                       .data2 = 0xf623,
49                                       .data3 = 0x4200,
50                                       .data4 = { 0x9d, 0x64, 0x11, 0x5e,
51                                                  0x9b, 0xfd, 0x4a, 0x08} };
52 
53 static const MSGUID metadata_guid = { .data1 = 0x8b7ca206,
54                                       .data2 = 0x4790,
55                                       .data3 = 0x4b9a,
56                                       .data4 = { 0xb8, 0xfe, 0x57, 0x5f,
57                                                  0x05, 0x0f, 0x88, 0x6e} };
58 
59 
60 
61 /* ------- Known Metadata Entry GUIDs ---------------------- */
62 static const MSGUID file_param_guid =   { .data1 = 0xcaa16737,
63                                           .data2 = 0xfa36,
64                                           .data3 = 0x4d43,
65                                           .data4 = { 0xb3, 0xb6, 0x33, 0xf0,
66                                                      0xaa, 0x44, 0xe7, 0x6b} };
67 
68 static const MSGUID virtual_size_guid = { .data1 = 0x2FA54224,
69                                           .data2 = 0xcd1b,
70                                           .data3 = 0x4876,
71                                           .data4 = { 0xb2, 0x11, 0x5d, 0xbe,
72                                                      0xd8, 0x3b, 0xf4, 0xb8} };
73 
74 static const MSGUID page83_guid =       { .data1 = 0xbeca12ab,
75                                           .data2 = 0xb2e6,
76                                           .data3 = 0x4523,
77                                           .data4 = { 0x93, 0xef, 0xc3, 0x09,
78                                                      0xe0, 0x00, 0xc7, 0x46} };
79 
80 
81 static const MSGUID phys_sector_guid =  { .data1 = 0xcda348c7,
82                                           .data2 = 0x445d,
83                                           .data3 = 0x4471,
84                                           .data4 = { 0x9c, 0xc9, 0xe9, 0x88,
85                                                      0x52, 0x51, 0xc5, 0x56} };
86 
87 static const MSGUID parent_locator_guid = { .data1 = 0xa8d35f2d,
88                                             .data2 = 0xb30b,
89                                             .data3 = 0x454d,
90                                             .data4 = { 0xab, 0xf7, 0xd3,
91                                                        0xd8, 0x48, 0x34,
92                                                        0xab, 0x0c} };
93 
94 static const MSGUID logical_sector_guid = { .data1 = 0x8141bf1d,
95                                             .data2 = 0xa96f,
96                                             .data3 = 0x4709,
97                                             .data4 = { 0xba, 0x47, 0xf2,
98                                                        0x33, 0xa8, 0xfa,
99                                                        0xab, 0x5f} };
100 
101 /* Each parent type must have a valid GUID; this is for parent images
102  * of type 'VHDX'.  If we were to allow e.g. a QCOW2 parent, we would
103  * need to make up our own QCOW2 GUID type */
104 static const MSGUID parent_vhdx_guid __attribute__((unused))
105                                      = { .data1 = 0xb04aefb7,
106                                          .data2 = 0xd19e,
107                                          .data3 = 0x4a81,
108                                          .data4 = { 0xb7, 0x89, 0x25, 0xb8,
109                                                     0xe9, 0x44, 0x59, 0x13} };
110 
111 
112 #define META_FILE_PARAMETER_PRESENT      0x01
113 #define META_VIRTUAL_DISK_SIZE_PRESENT   0x02
114 #define META_PAGE_83_PRESENT             0x04
115 #define META_LOGICAL_SECTOR_SIZE_PRESENT 0x08
116 #define META_PHYS_SECTOR_SIZE_PRESENT    0x10
117 #define META_PARENT_LOCATOR_PRESENT      0x20
118 
119 #define META_ALL_PRESENT    \
120     (META_FILE_PARAMETER_PRESENT | META_VIRTUAL_DISK_SIZE_PRESENT | \
121      META_PAGE_83_PRESENT | META_LOGICAL_SECTOR_SIZE_PRESENT | \
122      META_PHYS_SECTOR_SIZE_PRESENT)
123 
124 
125 typedef struct VHDXSectorInfo {
126     uint32_t bat_idx;       /* BAT entry index */
127     uint32_t sectors_avail; /* sectors available in payload block */
128     uint32_t bytes_left;    /* bytes left in the block after data to r/w */
129     uint32_t bytes_avail;   /* bytes available in payload block */
130     uint64_t file_offset;   /* absolute offset in bytes, in file */
131     uint64_t block_offset;  /* block offset, in bytes */
132 } VHDXSectorInfo;
133 
134 /* Calculates new checksum.
135  *
136  * Zero is substituted during crc calculation for the original crc field
137  * crc_offset: byte offset in buf of the buffer crc
138  * buf: buffer pointer
139  * size: size of buffer (must be > crc_offset+4)
140  *
141  * Note: The buffer should have all multi-byte data in little-endian format,
142  *       and the resulting checksum is in little endian format.
143  */
144 uint32_t vhdx_update_checksum(uint8_t *buf, size_t size, int crc_offset)
145 {
146     uint32_t crc;
147 
148     assert(buf != NULL);
149     assert(size > (crc_offset + sizeof(crc)));
150 
151     memset(buf + crc_offset, 0, sizeof(crc));
152     crc =  crc32c(0xffffffff, buf, size);
153     cpu_to_le32s(&crc);
154     memcpy(buf + crc_offset, &crc, sizeof(crc));
155 
156     return crc;
157 }
158 
159 uint32_t vhdx_checksum_calc(uint32_t crc, uint8_t *buf, size_t size,
160                             int crc_offset)
161 {
162     uint32_t crc_new;
163     uint32_t crc_orig;
164     assert(buf != NULL);
165 
166     if (crc_offset > 0) {
167         memcpy(&crc_orig, buf + crc_offset, sizeof(crc_orig));
168         memset(buf + crc_offset, 0, sizeof(crc_orig));
169     }
170 
171     crc_new = crc32c(crc, buf, size);
172     if (crc_offset > 0) {
173         memcpy(buf + crc_offset, &crc_orig, sizeof(crc_orig));
174     }
175 
176     return crc_new;
177 }
178 
179 /* Validates the checksum of the buffer, with an in-place CRC.
180  *
181  * Zero is substituted during crc calculation for the original crc field,
182  * and the crc field is restored afterwards.  But the buffer will be modifed
183  * during the calculation, so this may not be not suitable for multi-threaded
184  * use.
185  *
186  * crc_offset: byte offset in buf of the buffer crc
187  * buf: buffer pointer
188  * size: size of buffer (must be > crc_offset+4)
189  *
190  * returns true if checksum is valid, false otherwise
191  */
192 bool vhdx_checksum_is_valid(uint8_t *buf, size_t size, int crc_offset)
193 {
194     uint32_t crc_orig;
195     uint32_t crc;
196 
197     assert(buf != NULL);
198     assert(size > (crc_offset + 4));
199 
200     memcpy(&crc_orig, buf + crc_offset, sizeof(crc_orig));
201     crc_orig = le32_to_cpu(crc_orig);
202 
203     crc = vhdx_checksum_calc(0xffffffff, buf, size, crc_offset);
204 
205     return crc == crc_orig;
206 }
207 
208 
209 /*
210  * This generates a UUID that is compliant with the MS GUIDs used
211  * in the VHDX spec (and elsewhere).
212  */
213 void vhdx_guid_generate(MSGUID *guid)
214 {
215     QemuUUID uuid;
216     assert(guid != NULL);
217 
218     qemu_uuid_generate(&uuid);
219     memcpy(guid, &uuid, sizeof(MSGUID));
220 }
221 
222 /* Check for region overlaps inside the VHDX image */
223 static int vhdx_region_check(BDRVVHDXState *s, uint64_t start, uint64_t length)
224 {
225     int ret = 0;
226     uint64_t end;
227     VHDXRegionEntry *r;
228 
229     end = start + length;
230     QLIST_FOREACH(r, &s->regions, entries) {
231         if (!((start >= r->end) || (end <= r->start))) {
232             ret = -EINVAL;
233             goto exit;
234         }
235     }
236 
237 exit:
238     return ret;
239 }
240 
241 /* Register a region for future checks */
242 static void vhdx_region_register(BDRVVHDXState *s,
243                                  uint64_t start, uint64_t length)
244 {
245     VHDXRegionEntry *r;
246 
247     r = g_malloc0(sizeof(*r));
248 
249     r->start = start;
250     r->end = start + length;
251 
252     QLIST_INSERT_HEAD(&s->regions, r, entries);
253 }
254 
255 /* Free all registered regions */
256 static void vhdx_region_unregister_all(BDRVVHDXState *s)
257 {
258     VHDXRegionEntry *r, *r_next;
259 
260     QLIST_FOREACH_SAFE(r, &s->regions, entries, r_next) {
261         QLIST_REMOVE(r, entries);
262         g_free(r);
263     }
264 }
265 
266 static void vhdx_set_shift_bits(BDRVVHDXState *s)
267 {
268     s->logical_sector_size_bits = ctz32(s->logical_sector_size);
269     s->sectors_per_block_bits =   ctz32(s->sectors_per_block);
270     s->chunk_ratio_bits =         ctz64(s->chunk_ratio);
271     s->block_size_bits =          ctz32(s->block_size);
272 }
273 
274 /*
275  * Per the MS VHDX Specification, for every VHDX file:
276  *      - The header section is fixed size - 1 MB
277  *      - The header section is always the first "object"
278  *      - The first 64KB of the header is the File Identifier
279  *      - The first uint64 (8 bytes) is the VHDX Signature ("vhdxfile")
280  *      - The following 512 bytes constitute a UTF-16 string identifiying the
281  *        software that created the file, and is optional and diagnostic only.
282  *
283  *  Therefore, we probe by looking for the vhdxfile signature "vhdxfile"
284  */
285 static int vhdx_probe(const uint8_t *buf, int buf_size, const char *filename)
286 {
287     if (buf_size >= 8 && !memcmp(buf, "vhdxfile", 8)) {
288         return 100;
289     }
290     return 0;
291 }
292 
293 /*
294  * Writes the header to the specified offset.
295  *
296  * This will optionally read in buffer data from disk (otherwise zero-fill),
297  * and then update the header checksum.  Header is converted to proper
298  * endianness before being written to the specified file offset
299  */
300 static int vhdx_write_header(BdrvChild *file, VHDXHeader *hdr,
301                              uint64_t offset, bool read)
302 {
303     BlockDriverState *bs_file = file->bs;
304     uint8_t *buffer = NULL;
305     int ret;
306     VHDXHeader *header_le;
307 
308     assert(bs_file != NULL);
309     assert(hdr != NULL);
310 
311     /* the header checksum is not over just the packed size of VHDXHeader,
312      * but rather over the entire 'reserved' range for the header, which is
313      * 4KB (VHDX_HEADER_SIZE). */
314 
315     buffer = qemu_blockalign(bs_file, VHDX_HEADER_SIZE);
316     if (read) {
317         /* if true, we can't assume the extra reserved bytes are 0 */
318         ret = bdrv_pread(file, offset, buffer, VHDX_HEADER_SIZE);
319         if (ret < 0) {
320             goto exit;
321         }
322     } else {
323         memset(buffer, 0, VHDX_HEADER_SIZE);
324     }
325 
326     /* overwrite the actual VHDXHeader portion */
327     header_le = (VHDXHeader *)buffer;
328     memcpy(header_le, hdr, sizeof(VHDXHeader));
329     vhdx_header_le_export(hdr, header_le);
330     vhdx_update_checksum(buffer, VHDX_HEADER_SIZE,
331                          offsetof(VHDXHeader, checksum));
332     ret = bdrv_pwrite_sync(file, offset, header_le, sizeof(VHDXHeader));
333 
334 exit:
335     qemu_vfree(buffer);
336     return ret;
337 }
338 
339 /* Update the VHDX headers
340  *
341  * This follows the VHDX spec procedures for header updates.
342  *
343  *  - non-current header is updated with largest sequence number
344  */
345 static int vhdx_update_header(BlockDriverState *bs, BDRVVHDXState *s,
346                               bool generate_data_write_guid, MSGUID *log_guid)
347 {
348     int ret = 0;
349     int hdr_idx = 0;
350     uint64_t header_offset = VHDX_HEADER1_OFFSET;
351 
352     VHDXHeader *active_header;
353     VHDXHeader *inactive_header;
354 
355     /* operate on the non-current header */
356     if (s->curr_header == 0) {
357         hdr_idx = 1;
358         header_offset = VHDX_HEADER2_OFFSET;
359     }
360 
361     active_header   = s->headers[s->curr_header];
362     inactive_header = s->headers[hdr_idx];
363 
364     inactive_header->sequence_number = active_header->sequence_number + 1;
365 
366     /* a new file guid must be generated before any file write, including
367      * headers */
368     inactive_header->file_write_guid = s->session_guid;
369 
370     /* a new data guid only needs to be generated before any guest-visible
371      * writes (i.e. something observable via virtual disk read) */
372     if (generate_data_write_guid) {
373         vhdx_guid_generate(&inactive_header->data_write_guid);
374     }
375 
376     /* update the log guid if present */
377     if (log_guid) {
378         inactive_header->log_guid = *log_guid;
379     }
380 
381     ret = vhdx_write_header(bs->file, inactive_header, header_offset, true);
382     if (ret < 0) {
383         goto exit;
384     }
385     s->curr_header = hdr_idx;
386 
387 exit:
388     return ret;
389 }
390 
391 /*
392  * The VHDX spec calls for header updates to be performed twice, so that both
393  * the current and non-current header have valid info
394  */
395 int vhdx_update_headers(BlockDriverState *bs, BDRVVHDXState *s,
396                         bool generate_data_write_guid, MSGUID *log_guid)
397 {
398     int ret;
399 
400     ret = vhdx_update_header(bs, s, generate_data_write_guid, log_guid);
401     if (ret < 0) {
402         return ret;
403     }
404     ret = vhdx_update_header(bs, s, generate_data_write_guid, log_guid);
405     return ret;
406 }
407 
408 /* opens the specified header block from the VHDX file header section */
409 static void vhdx_parse_header(BlockDriverState *bs, BDRVVHDXState *s,
410                               Error **errp)
411 {
412     int ret;
413     VHDXHeader *header1;
414     VHDXHeader *header2;
415     bool h1_valid = false;
416     bool h2_valid = false;
417     uint64_t h1_seq = 0;
418     uint64_t h2_seq = 0;
419     uint8_t *buffer;
420 
421     /* header1 & header2 are freed in vhdx_close() */
422     header1 = qemu_blockalign(bs, sizeof(VHDXHeader));
423     header2 = qemu_blockalign(bs, sizeof(VHDXHeader));
424 
425     buffer = qemu_blockalign(bs, VHDX_HEADER_SIZE);
426 
427     s->headers[0] = header1;
428     s->headers[1] = header2;
429 
430     /* We have to read the whole VHDX_HEADER_SIZE instead of
431      * sizeof(VHDXHeader), because the checksum is over the whole
432      * region */
433     ret = bdrv_pread(bs->file, VHDX_HEADER1_OFFSET, buffer,
434                      VHDX_HEADER_SIZE);
435     if (ret < 0) {
436         goto fail;
437     }
438     /* copy over just the relevant portion that we need */
439     memcpy(header1, buffer, sizeof(VHDXHeader));
440 
441     if (vhdx_checksum_is_valid(buffer, VHDX_HEADER_SIZE, 4)) {
442         vhdx_header_le_import(header1);
443         if (header1->signature == VHDX_HEADER_SIGNATURE &&
444             header1->version == 1) {
445             h1_seq = header1->sequence_number;
446             h1_valid = true;
447         }
448     }
449 
450     ret = bdrv_pread(bs->file, VHDX_HEADER2_OFFSET, buffer,
451                      VHDX_HEADER_SIZE);
452     if (ret < 0) {
453         goto fail;
454     }
455     /* copy over just the relevant portion that we need */
456     memcpy(header2, buffer, sizeof(VHDXHeader));
457 
458     if (vhdx_checksum_is_valid(buffer, VHDX_HEADER_SIZE, 4)) {
459         vhdx_header_le_import(header2);
460         if (header2->signature == VHDX_HEADER_SIGNATURE &&
461             header2->version == 1) {
462             h2_seq = header2->sequence_number;
463             h2_valid = true;
464         }
465     }
466 
467     /* If there is only 1 valid header (or no valid headers), we
468      * don't care what the sequence numbers are */
469     if (h1_valid && !h2_valid) {
470         s->curr_header = 0;
471     } else if (!h1_valid && h2_valid) {
472         s->curr_header = 1;
473     } else if (!h1_valid && !h2_valid) {
474         goto fail;
475     } else {
476         /* If both headers are valid, then we choose the active one by the
477          * highest sequence number.  If the sequence numbers are equal, that is
478          * invalid */
479         if (h1_seq > h2_seq) {
480             s->curr_header = 0;
481         } else if (h2_seq > h1_seq) {
482             s->curr_header = 1;
483         } else {
484             /* The Microsoft Disk2VHD tool will create 2 identical
485              * headers, with identical sequence numbers.  If the headers are
486              * identical, don't consider the file corrupt */
487             if (!memcmp(header1, header2, sizeof(VHDXHeader))) {
488                 s->curr_header = 0;
489             } else {
490                 goto fail;
491             }
492         }
493     }
494 
495     vhdx_region_register(s, s->headers[s->curr_header]->log_offset,
496                             s->headers[s->curr_header]->log_length);
497     goto exit;
498 
499 fail:
500     error_setg_errno(errp, -ret, "No valid VHDX header found");
501     qemu_vfree(header1);
502     qemu_vfree(header2);
503     s->headers[0] = NULL;
504     s->headers[1] = NULL;
505 exit:
506     qemu_vfree(buffer);
507 }
508 
509 
510 static int vhdx_open_region_tables(BlockDriverState *bs, BDRVVHDXState *s)
511 {
512     int ret = 0;
513     uint8_t *buffer;
514     int offset = 0;
515     VHDXRegionTableEntry rt_entry;
516     uint32_t i;
517     bool bat_rt_found = false;
518     bool metadata_rt_found = false;
519 
520     /* We have to read the whole 64KB block, because the crc32 is over the
521      * whole block */
522     buffer = qemu_blockalign(bs, VHDX_HEADER_BLOCK_SIZE);
523 
524     ret = bdrv_pread(bs->file, VHDX_REGION_TABLE_OFFSET, buffer,
525                      VHDX_HEADER_BLOCK_SIZE);
526     if (ret < 0) {
527         goto fail;
528     }
529     memcpy(&s->rt, buffer, sizeof(s->rt));
530     offset += sizeof(s->rt);
531 
532     if (!vhdx_checksum_is_valid(buffer, VHDX_HEADER_BLOCK_SIZE, 4)) {
533         ret = -EINVAL;
534         goto fail;
535     }
536 
537     vhdx_region_header_le_import(&s->rt);
538 
539     if (s->rt.signature != VHDX_REGION_SIGNATURE) {
540         ret = -EINVAL;
541         goto fail;
542     }
543 
544 
545     /* Per spec, maximum region table entry count is 2047 */
546     if (s->rt.entry_count > 2047) {
547         ret = -EINVAL;
548         goto fail;
549     }
550 
551     for (i = 0; i < s->rt.entry_count; i++) {
552         memcpy(&rt_entry, buffer + offset, sizeof(rt_entry));
553         offset += sizeof(rt_entry);
554 
555         vhdx_region_entry_le_import(&rt_entry);
556 
557         /* check for region overlap between these entries, and any
558          * other memory regions in the file */
559         ret = vhdx_region_check(s, rt_entry.file_offset, rt_entry.length);
560         if (ret < 0) {
561             goto fail;
562         }
563 
564         vhdx_region_register(s, rt_entry.file_offset, rt_entry.length);
565 
566         /* see if we recognize the entry */
567         if (guid_eq(rt_entry.guid, bat_guid)) {
568             /* must be unique; if we have already found it this is invalid */
569             if (bat_rt_found) {
570                 ret = -EINVAL;
571                 goto fail;
572             }
573             bat_rt_found = true;
574             s->bat_rt = rt_entry;
575             continue;
576         }
577 
578         if (guid_eq(rt_entry.guid, metadata_guid)) {
579             /* must be unique; if we have already found it this is invalid */
580             if (metadata_rt_found) {
581                 ret = -EINVAL;
582                 goto fail;
583             }
584             metadata_rt_found = true;
585             s->metadata_rt = rt_entry;
586             continue;
587         }
588 
589         if (rt_entry.data_bits & VHDX_REGION_ENTRY_REQUIRED) {
590             /* cannot read vhdx file - required region table entry that
591              * we do not understand.  per spec, we must fail to open */
592             ret = -ENOTSUP;
593             goto fail;
594         }
595     }
596 
597     if (!bat_rt_found || !metadata_rt_found) {
598         ret = -EINVAL;
599         goto fail;
600     }
601 
602     ret = 0;
603 
604 fail:
605     qemu_vfree(buffer);
606     return ret;
607 }
608 
609 
610 
611 /* Metadata initial parser
612  *
613  * This loads all the metadata entry fields.  This may cause additional
614  * fields to be processed (e.g. parent locator, etc..).
615  *
616  * There are 5 Metadata items that are always required:
617  *      - File Parameters (block size, has a parent)
618  *      - Virtual Disk Size (size, in bytes, of the virtual drive)
619  *      - Page 83 Data (scsi page 83 guid)
620  *      - Logical Sector Size (logical sector size in bytes, either 512 or
621  *                             4096.  We only support 512 currently)
622  *      - Physical Sector Size (512 or 4096)
623  *
624  * Also, if the File Parameters indicate this is a differencing file,
625  * we must also look for the Parent Locator metadata item.
626  */
627 static int vhdx_parse_metadata(BlockDriverState *bs, BDRVVHDXState *s)
628 {
629     int ret = 0;
630     uint8_t *buffer;
631     int offset = 0;
632     uint32_t i = 0;
633     VHDXMetadataTableEntry md_entry;
634 
635     buffer = qemu_blockalign(bs, VHDX_METADATA_TABLE_MAX_SIZE);
636 
637     ret = bdrv_pread(bs->file, s->metadata_rt.file_offset, buffer,
638                      VHDX_METADATA_TABLE_MAX_SIZE);
639     if (ret < 0) {
640         goto exit;
641     }
642     memcpy(&s->metadata_hdr, buffer, sizeof(s->metadata_hdr));
643     offset += sizeof(s->metadata_hdr);
644 
645     vhdx_metadata_header_le_import(&s->metadata_hdr);
646 
647     if (s->metadata_hdr.signature != VHDX_METADATA_SIGNATURE) {
648         ret = -EINVAL;
649         goto exit;
650     }
651 
652     s->metadata_entries.present = 0;
653 
654     if ((s->metadata_hdr.entry_count * sizeof(md_entry)) >
655         (VHDX_METADATA_TABLE_MAX_SIZE - offset)) {
656         ret = -EINVAL;
657         goto exit;
658     }
659 
660     for (i = 0; i < s->metadata_hdr.entry_count; i++) {
661         memcpy(&md_entry, buffer + offset, sizeof(md_entry));
662         offset += sizeof(md_entry);
663 
664         vhdx_metadata_entry_le_import(&md_entry);
665 
666         if (guid_eq(md_entry.item_id, file_param_guid)) {
667             if (s->metadata_entries.present & META_FILE_PARAMETER_PRESENT) {
668                 ret = -EINVAL;
669                 goto exit;
670             }
671             s->metadata_entries.file_parameters_entry = md_entry;
672             s->metadata_entries.present |= META_FILE_PARAMETER_PRESENT;
673             continue;
674         }
675 
676         if (guid_eq(md_entry.item_id, virtual_size_guid)) {
677             if (s->metadata_entries.present & META_VIRTUAL_DISK_SIZE_PRESENT) {
678                 ret = -EINVAL;
679                 goto exit;
680             }
681             s->metadata_entries.virtual_disk_size_entry = md_entry;
682             s->metadata_entries.present |= META_VIRTUAL_DISK_SIZE_PRESENT;
683             continue;
684         }
685 
686         if (guid_eq(md_entry.item_id, page83_guid)) {
687             if (s->metadata_entries.present & META_PAGE_83_PRESENT) {
688                 ret = -EINVAL;
689                 goto exit;
690             }
691             s->metadata_entries.page83_data_entry = md_entry;
692             s->metadata_entries.present |= META_PAGE_83_PRESENT;
693             continue;
694         }
695 
696         if (guid_eq(md_entry.item_id, logical_sector_guid)) {
697             if (s->metadata_entries.present &
698                 META_LOGICAL_SECTOR_SIZE_PRESENT) {
699                 ret = -EINVAL;
700                 goto exit;
701             }
702             s->metadata_entries.logical_sector_size_entry = md_entry;
703             s->metadata_entries.present |= META_LOGICAL_SECTOR_SIZE_PRESENT;
704             continue;
705         }
706 
707         if (guid_eq(md_entry.item_id, phys_sector_guid)) {
708             if (s->metadata_entries.present & META_PHYS_SECTOR_SIZE_PRESENT) {
709                 ret = -EINVAL;
710                 goto exit;
711             }
712             s->metadata_entries.phys_sector_size_entry = md_entry;
713             s->metadata_entries.present |= META_PHYS_SECTOR_SIZE_PRESENT;
714             continue;
715         }
716 
717         if (guid_eq(md_entry.item_id, parent_locator_guid)) {
718             if (s->metadata_entries.present & META_PARENT_LOCATOR_PRESENT) {
719                 ret = -EINVAL;
720                 goto exit;
721             }
722             s->metadata_entries.parent_locator_entry = md_entry;
723             s->metadata_entries.present |= META_PARENT_LOCATOR_PRESENT;
724             continue;
725         }
726 
727         if (md_entry.data_bits & VHDX_META_FLAGS_IS_REQUIRED) {
728             /* cannot read vhdx file - required region table entry that
729              * we do not understand.  per spec, we must fail to open */
730             ret = -ENOTSUP;
731             goto exit;
732         }
733     }
734 
735     if (s->metadata_entries.present != META_ALL_PRESENT) {
736         ret = -ENOTSUP;
737         goto exit;
738     }
739 
740     ret = bdrv_pread(bs->file,
741                      s->metadata_entries.file_parameters_entry.offset
742                                          + s->metadata_rt.file_offset,
743                      &s->params,
744                      sizeof(s->params));
745 
746     if (ret < 0) {
747         goto exit;
748     }
749 
750     le32_to_cpus(&s->params.block_size);
751     le32_to_cpus(&s->params.data_bits);
752 
753 
754     /* We now have the file parameters, so we can tell if this is a
755      * differencing file (i.e.. has_parent), is dynamic or fixed
756      * sized (leave_blocks_allocated), and the block size */
757 
758     /* The parent locator required iff the file parameters has_parent set */
759     if (s->params.data_bits & VHDX_PARAMS_HAS_PARENT) {
760         if (s->metadata_entries.present & META_PARENT_LOCATOR_PRESENT) {
761             /* TODO: parse  parent locator fields */
762             ret = -ENOTSUP; /* temp, until differencing files are supported */
763             goto exit;
764         } else {
765             /* if has_parent is set, but there is not parent locator present,
766              * then that is an invalid combination */
767             ret = -EINVAL;
768             goto exit;
769         }
770     }
771 
772     /* determine virtual disk size, logical sector size,
773      * and phys sector size */
774 
775     ret = bdrv_pread(bs->file,
776                      s->metadata_entries.virtual_disk_size_entry.offset
777                                            + s->metadata_rt.file_offset,
778                      &s->virtual_disk_size,
779                      sizeof(uint64_t));
780     if (ret < 0) {
781         goto exit;
782     }
783     ret = bdrv_pread(bs->file,
784                      s->metadata_entries.logical_sector_size_entry.offset
785                                              + s->metadata_rt.file_offset,
786                      &s->logical_sector_size,
787                      sizeof(uint32_t));
788     if (ret < 0) {
789         goto exit;
790     }
791     ret = bdrv_pread(bs->file,
792                      s->metadata_entries.phys_sector_size_entry.offset
793                                           + s->metadata_rt.file_offset,
794                      &s->physical_sector_size,
795                      sizeof(uint32_t));
796     if (ret < 0) {
797         goto exit;
798     }
799 
800     le64_to_cpus(&s->virtual_disk_size);
801     le32_to_cpus(&s->logical_sector_size);
802     le32_to_cpus(&s->physical_sector_size);
803 
804     if (s->params.block_size < VHDX_BLOCK_SIZE_MIN ||
805         s->params.block_size > VHDX_BLOCK_SIZE_MAX) {
806         ret = -EINVAL;
807         goto exit;
808     }
809 
810     /* only 2 supported sector sizes */
811     if (s->logical_sector_size != 512 && s->logical_sector_size != 4096) {
812         ret = -EINVAL;
813         goto exit;
814     }
815 
816     /* Both block_size and sector_size are guaranteed powers of 2, below.
817        Due to range checks above, s->sectors_per_block can never be < 256 */
818     s->sectors_per_block = s->params.block_size / s->logical_sector_size;
819     s->chunk_ratio = (VHDX_MAX_SECTORS_PER_BLOCK) *
820                      (uint64_t)s->logical_sector_size /
821                      (uint64_t)s->params.block_size;
822 
823     /* These values are ones we will want to use for division / multiplication
824      * later on, and they are all guaranteed (per the spec) to be powers of 2,
825      * so we can take advantage of that for shift operations during
826      * reads/writes */
827     if (s->logical_sector_size & (s->logical_sector_size - 1)) {
828         ret = -EINVAL;
829         goto exit;
830     }
831     if (s->sectors_per_block & (s->sectors_per_block - 1)) {
832         ret = -EINVAL;
833         goto exit;
834     }
835     if (s->chunk_ratio & (s->chunk_ratio - 1)) {
836         ret = -EINVAL;
837         goto exit;
838     }
839     s->block_size = s->params.block_size;
840     if (s->block_size & (s->block_size - 1)) {
841         ret = -EINVAL;
842         goto exit;
843     }
844 
845     vhdx_set_shift_bits(s);
846 
847     ret = 0;
848 
849 exit:
850     qemu_vfree(buffer);
851     return ret;
852 }
853 
854 /*
855  * Calculate the number of BAT entries, including sector
856  * bitmap entries.
857  */
858 static void vhdx_calc_bat_entries(BDRVVHDXState *s)
859 {
860     uint32_t data_blocks_cnt, bitmap_blocks_cnt;
861 
862     data_blocks_cnt = DIV_ROUND_UP(s->virtual_disk_size, s->block_size);
863     bitmap_blocks_cnt = DIV_ROUND_UP(data_blocks_cnt, s->chunk_ratio);
864 
865     if (s->parent_entries) {
866         s->bat_entries = bitmap_blocks_cnt * (s->chunk_ratio + 1);
867     } else {
868         s->bat_entries = data_blocks_cnt +
869                          ((data_blocks_cnt - 1) >> s->chunk_ratio_bits);
870     }
871 
872 }
873 
874 static void vhdx_close(BlockDriverState *bs)
875 {
876     BDRVVHDXState *s = bs->opaque;
877     qemu_vfree(s->headers[0]);
878     s->headers[0] = NULL;
879     qemu_vfree(s->headers[1]);
880     s->headers[1] = NULL;
881     qemu_vfree(s->bat);
882     s->bat = NULL;
883     qemu_vfree(s->parent_entries);
884     s->parent_entries = NULL;
885     migrate_del_blocker(s->migration_blocker);
886     error_free(s->migration_blocker);
887     qemu_vfree(s->log.hdr);
888     s->log.hdr = NULL;
889     vhdx_region_unregister_all(s);
890 }
891 
892 static int vhdx_open(BlockDriverState *bs, QDict *options, int flags,
893                      Error **errp)
894 {
895     BDRVVHDXState *s = bs->opaque;
896     int ret = 0;
897     uint32_t i;
898     uint64_t signature;
899     Error *local_err = NULL;
900 
901     bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
902                                false, errp);
903     if (!bs->file) {
904         return -EINVAL;
905     }
906 
907     s->bat = NULL;
908     s->first_visible_write = true;
909 
910     qemu_co_mutex_init(&s->lock);
911     QLIST_INIT(&s->regions);
912 
913     /* validate the file signature */
914     ret = bdrv_pread(bs->file, 0, &signature, sizeof(uint64_t));
915     if (ret < 0) {
916         goto fail;
917     }
918     if (memcmp(&signature, "vhdxfile", 8)) {
919         ret = -EINVAL;
920         goto fail;
921     }
922 
923     /* This is used for any header updates, for the file_write_guid.
924      * The spec dictates that a new value should be used for the first
925      * header update */
926     vhdx_guid_generate(&s->session_guid);
927 
928     vhdx_parse_header(bs, s, &local_err);
929     if (local_err != NULL) {
930         error_propagate(errp, local_err);
931         ret = -EINVAL;
932         goto fail;
933     }
934 
935     ret = vhdx_parse_log(bs, s, &s->log_replayed_on_open, errp);
936     if (ret < 0) {
937         goto fail;
938     }
939 
940     ret = vhdx_open_region_tables(bs, s);
941     if (ret < 0) {
942         goto fail;
943     }
944 
945     ret = vhdx_parse_metadata(bs, s);
946     if (ret < 0) {
947         goto fail;
948     }
949 
950     s->block_size = s->params.block_size;
951 
952     /* the VHDX spec dictates that virtual_disk_size is always a multiple of
953      * logical_sector_size */
954     bs->total_sectors = s->virtual_disk_size >> s->logical_sector_size_bits;
955 
956     vhdx_calc_bat_entries(s);
957 
958     s->bat_offset = s->bat_rt.file_offset;
959 
960     if (s->bat_entries > s->bat_rt.length / sizeof(VHDXBatEntry)) {
961         /* BAT allocation is not large enough for all entries */
962         ret = -EINVAL;
963         goto fail;
964     }
965 
966     /* s->bat is freed in vhdx_close() */
967     s->bat = qemu_try_blockalign(bs->file->bs, s->bat_rt.length);
968     if (s->bat == NULL) {
969         ret = -ENOMEM;
970         goto fail;
971     }
972 
973     ret = bdrv_pread(bs->file, s->bat_offset, s->bat, s->bat_rt.length);
974     if (ret < 0) {
975         goto fail;
976     }
977 
978     uint64_t payblocks = s->chunk_ratio;
979     /* endian convert, and verify populated BAT field file offsets against
980      * region table and log entries */
981     for (i = 0; i < s->bat_entries; i++) {
982         le64_to_cpus(&s->bat[i]);
983         if (payblocks--) {
984             /* payload bat entries */
985             if ((s->bat[i] & VHDX_BAT_STATE_BIT_MASK) ==
986                     PAYLOAD_BLOCK_FULLY_PRESENT) {
987                 ret = vhdx_region_check(s, s->bat[i] & VHDX_BAT_FILE_OFF_MASK,
988                                         s->block_size);
989                 if (ret < 0) {
990                     goto fail;
991                 }
992             }
993         } else {
994             payblocks = s->chunk_ratio;
995             /* Once differencing files are supported, verify sector bitmap
996              * blocks here */
997         }
998     }
999 
1000     /* Disable migration when VHDX images are used */
1001     error_setg(&s->migration_blocker, "The vhdx format used by node '%s' "
1002                "does not support live migration",
1003                bdrv_get_device_or_node_name(bs));
1004     ret = migrate_add_blocker(s->migration_blocker, &local_err);
1005     if (local_err) {
1006         error_propagate(errp, local_err);
1007         error_free(s->migration_blocker);
1008         goto fail;
1009     }
1010 
1011     if (flags & BDRV_O_RDWR) {
1012         ret = vhdx_update_headers(bs, s, false, NULL);
1013         if (ret < 0) {
1014             goto fail;
1015         }
1016     }
1017 
1018     /* TODO: differencing files */
1019 
1020     return 0;
1021 fail:
1022     vhdx_close(bs);
1023     return ret;
1024 }
1025 
1026 static int vhdx_reopen_prepare(BDRVReopenState *state,
1027                                BlockReopenQueue *queue, Error **errp)
1028 {
1029     return 0;
1030 }
1031 
1032 
1033 /*
1034  * Perform sector to block offset translations, to get various
1035  * sector and file offsets into the image.  See VHDXSectorInfo
1036  */
1037 static void vhdx_block_translate(BDRVVHDXState *s, int64_t sector_num,
1038                                  int nb_sectors, VHDXSectorInfo *sinfo)
1039 {
1040     uint32_t block_offset;
1041 
1042     sinfo->bat_idx = sector_num >> s->sectors_per_block_bits;
1043     /* effectively a modulo - this gives us the offset into the block
1044      * (in sector sizes) for our sector number */
1045     block_offset = sector_num - (sinfo->bat_idx << s->sectors_per_block_bits);
1046     /* the chunk ratio gives us the interleaving of the sector
1047      * bitmaps, so we need to advance our page block index by the
1048      * sector bitmaps entry number */
1049     sinfo->bat_idx += sinfo->bat_idx >> s->chunk_ratio_bits;
1050 
1051     /* the number of sectors we can read/write in this cycle */
1052     sinfo->sectors_avail = s->sectors_per_block - block_offset;
1053 
1054     sinfo->bytes_left = sinfo->sectors_avail << s->logical_sector_size_bits;
1055 
1056     if (sinfo->sectors_avail > nb_sectors) {
1057         sinfo->sectors_avail = nb_sectors;
1058     }
1059 
1060     sinfo->bytes_avail = sinfo->sectors_avail << s->logical_sector_size_bits;
1061 
1062     sinfo->file_offset = s->bat[sinfo->bat_idx] & VHDX_BAT_FILE_OFF_MASK;
1063 
1064     sinfo->block_offset = block_offset << s->logical_sector_size_bits;
1065 
1066     /* The file offset must be past the header section, so must be > 0 */
1067     if (sinfo->file_offset == 0) {
1068         return;
1069     }
1070 
1071     /* block offset is the offset in vhdx logical sectors, in
1072      * the payload data block. Convert that to a byte offset
1073      * in the block, and add in the payload data block offset
1074      * in the file, in bytes, to get the final read address */
1075 
1076     sinfo->file_offset += sinfo->block_offset;
1077 }
1078 
1079 
1080 static int vhdx_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1081 {
1082     BDRVVHDXState *s = bs->opaque;
1083 
1084     bdi->cluster_size = s->block_size;
1085 
1086     bdi->unallocated_blocks_are_zero =
1087         (s->params.data_bits & VHDX_PARAMS_HAS_PARENT) == 0;
1088 
1089     return 0;
1090 }
1091 
1092 
1093 static coroutine_fn int vhdx_co_readv(BlockDriverState *bs, int64_t sector_num,
1094                                       int nb_sectors, QEMUIOVector *qiov)
1095 {
1096     BDRVVHDXState *s = bs->opaque;
1097     int ret = 0;
1098     VHDXSectorInfo sinfo;
1099     uint64_t bytes_done = 0;
1100     QEMUIOVector hd_qiov;
1101 
1102     qemu_iovec_init(&hd_qiov, qiov->niov);
1103 
1104     qemu_co_mutex_lock(&s->lock);
1105 
1106     while (nb_sectors > 0) {
1107         /* We are a differencing file, so we need to inspect the sector bitmap
1108          * to see if we have the data or not */
1109         if (s->params.data_bits & VHDX_PARAMS_HAS_PARENT) {
1110             /* not supported yet */
1111             ret = -ENOTSUP;
1112             goto exit;
1113         } else {
1114             vhdx_block_translate(s, sector_num, nb_sectors, &sinfo);
1115 
1116             qemu_iovec_reset(&hd_qiov);
1117             qemu_iovec_concat(&hd_qiov, qiov,  bytes_done, sinfo.bytes_avail);
1118 
1119             /* check the payload block state */
1120             switch (s->bat[sinfo.bat_idx] & VHDX_BAT_STATE_BIT_MASK) {
1121             case PAYLOAD_BLOCK_NOT_PRESENT: /* fall through */
1122             case PAYLOAD_BLOCK_UNDEFINED:
1123             case PAYLOAD_BLOCK_UNMAPPED:
1124             case PAYLOAD_BLOCK_UNMAPPED_v095:
1125             case PAYLOAD_BLOCK_ZERO:
1126                 /* return zero */
1127                 qemu_iovec_memset(&hd_qiov, 0, 0, sinfo.bytes_avail);
1128                 break;
1129             case PAYLOAD_BLOCK_FULLY_PRESENT:
1130                 qemu_co_mutex_unlock(&s->lock);
1131                 ret = bdrv_co_readv(bs->file,
1132                                     sinfo.file_offset >> BDRV_SECTOR_BITS,
1133                                     sinfo.sectors_avail, &hd_qiov);
1134                 qemu_co_mutex_lock(&s->lock);
1135                 if (ret < 0) {
1136                     goto exit;
1137                 }
1138                 break;
1139             case PAYLOAD_BLOCK_PARTIALLY_PRESENT:
1140                 /* we don't yet support difference files, fall through
1141                  * to error */
1142             default:
1143                 ret = -EIO;
1144                 goto exit;
1145                 break;
1146             }
1147             nb_sectors -= sinfo.sectors_avail;
1148             sector_num += sinfo.sectors_avail;
1149             bytes_done += sinfo.bytes_avail;
1150         }
1151     }
1152     ret = 0;
1153 exit:
1154     qemu_co_mutex_unlock(&s->lock);
1155     qemu_iovec_destroy(&hd_qiov);
1156     return ret;
1157 }
1158 
1159 /*
1160  * Allocate a new payload block at the end of the file.
1161  *
1162  * Allocation will happen at 1MB alignment inside the file
1163  *
1164  * Returns the file offset start of the new payload block
1165  */
1166 static int vhdx_allocate_block(BlockDriverState *bs, BDRVVHDXState *s,
1167                                     uint64_t *new_offset)
1168 {
1169     *new_offset = bdrv_getlength(bs->file->bs);
1170 
1171     /* per the spec, the address for a block is in units of 1MB */
1172     *new_offset = ROUND_UP(*new_offset, 1024 * 1024);
1173 
1174     return bdrv_truncate(bs->file, *new_offset + s->block_size, NULL);
1175 }
1176 
1177 /*
1178  * Update the BAT table entry with the new file offset, and the new entry
1179  * state */
1180 static void vhdx_update_bat_table_entry(BlockDriverState *bs, BDRVVHDXState *s,
1181                                        VHDXSectorInfo *sinfo,
1182                                        uint64_t *bat_entry_le,
1183                                        uint64_t *bat_offset, int state)
1184 {
1185     /* The BAT entry is a uint64, with 44 bits for the file offset in units of
1186      * 1MB, and 3 bits for the block state. */
1187     if ((state == PAYLOAD_BLOCK_ZERO)        ||
1188         (state == PAYLOAD_BLOCK_UNDEFINED)   ||
1189         (state == PAYLOAD_BLOCK_NOT_PRESENT) ||
1190         (state == PAYLOAD_BLOCK_UNMAPPED)) {
1191         s->bat[sinfo->bat_idx]  = 0;  /* For PAYLOAD_BLOCK_ZERO, the
1192                                          FileOffsetMB field is denoted as
1193                                          'reserved' in the v1.0 spec.  If it is
1194                                          non-zero, MS Hyper-V will fail to read
1195                                          the disk image */
1196     } else {
1197         s->bat[sinfo->bat_idx]  = sinfo->file_offset;
1198     }
1199 
1200     s->bat[sinfo->bat_idx] |= state & VHDX_BAT_STATE_BIT_MASK;
1201 
1202     *bat_entry_le = cpu_to_le64(s->bat[sinfo->bat_idx]);
1203     *bat_offset = s->bat_offset + sinfo->bat_idx * sizeof(VHDXBatEntry);
1204 
1205 }
1206 
1207 /* Per the spec, on the first write of guest-visible data to the file the
1208  * data write guid must be updated in the header */
1209 int vhdx_user_visible_write(BlockDriverState *bs, BDRVVHDXState *s)
1210 {
1211     int ret = 0;
1212     if (s->first_visible_write) {
1213         s->first_visible_write = false;
1214         ret = vhdx_update_headers(bs, s, true, NULL);
1215     }
1216     return ret;
1217 }
1218 
1219 static coroutine_fn int vhdx_co_writev(BlockDriverState *bs, int64_t sector_num,
1220                                       int nb_sectors, QEMUIOVector *qiov)
1221 {
1222     int ret = -ENOTSUP;
1223     BDRVVHDXState *s = bs->opaque;
1224     VHDXSectorInfo sinfo;
1225     uint64_t bytes_done = 0;
1226     uint64_t bat_entry = 0;
1227     uint64_t bat_entry_offset = 0;
1228     QEMUIOVector hd_qiov;
1229     struct iovec iov1 = { 0 };
1230     struct iovec iov2 = { 0 };
1231     int sectors_to_write;
1232     int bat_state;
1233     uint64_t bat_prior_offset = 0;
1234     bool bat_update = false;
1235 
1236     qemu_iovec_init(&hd_qiov, qiov->niov);
1237 
1238     qemu_co_mutex_lock(&s->lock);
1239 
1240     ret = vhdx_user_visible_write(bs, s);
1241     if (ret < 0) {
1242         goto exit;
1243     }
1244 
1245     while (nb_sectors > 0) {
1246         bool use_zero_buffers = false;
1247         bat_update = false;
1248         if (s->params.data_bits & VHDX_PARAMS_HAS_PARENT) {
1249             /* not supported yet */
1250             ret = -ENOTSUP;
1251             goto exit;
1252         } else {
1253             vhdx_block_translate(s, sector_num, nb_sectors, &sinfo);
1254             sectors_to_write = sinfo.sectors_avail;
1255 
1256             qemu_iovec_reset(&hd_qiov);
1257             /* check the payload block state */
1258             bat_state = s->bat[sinfo.bat_idx] & VHDX_BAT_STATE_BIT_MASK;
1259             switch (bat_state) {
1260             case PAYLOAD_BLOCK_ZERO:
1261                 /* in this case, we need to preserve zero writes for
1262                  * data that is not part of this write, so we must pad
1263                  * the rest of the buffer to zeroes */
1264 
1265                 /* if we are on a posix system with ftruncate() that extends
1266                  * a file, then it is zero-filled for us.  On Win32, the raw
1267                  * layer uses SetFilePointer and SetFileEnd, which does not
1268                  * zero fill AFAIK */
1269 
1270                 /* Queue another write of zero buffers if the underlying file
1271                  * does not zero-fill on file extension */
1272 
1273                 if (bdrv_has_zero_init(bs->file->bs) == 0) {
1274                     use_zero_buffers = true;
1275 
1276                     /* zero fill the front, if any */
1277                     if (sinfo.block_offset) {
1278                         iov1.iov_len = sinfo.block_offset;
1279                         iov1.iov_base = qemu_blockalign(bs, iov1.iov_len);
1280                         memset(iov1.iov_base, 0, iov1.iov_len);
1281                         qemu_iovec_concat_iov(&hd_qiov, &iov1, 1, 0,
1282                                               iov1.iov_len);
1283                         sectors_to_write += iov1.iov_len >> BDRV_SECTOR_BITS;
1284                     }
1285 
1286                     /* our actual data */
1287                     qemu_iovec_concat(&hd_qiov, qiov,  bytes_done,
1288                                       sinfo.bytes_avail);
1289 
1290                     /* zero fill the back, if any */
1291                     if ((sinfo.bytes_avail - sinfo.block_offset) <
1292                          s->block_size) {
1293                         iov2.iov_len = s->block_size -
1294                                       (sinfo.bytes_avail + sinfo.block_offset);
1295                         iov2.iov_base = qemu_blockalign(bs, iov2.iov_len);
1296                         memset(iov2.iov_base, 0, iov2.iov_len);
1297                         qemu_iovec_concat_iov(&hd_qiov, &iov2, 1, 0,
1298                                               iov2.iov_len);
1299                         sectors_to_write += iov2.iov_len >> BDRV_SECTOR_BITS;
1300                     }
1301                 }
1302                 /* fall through */
1303             case PAYLOAD_BLOCK_NOT_PRESENT: /* fall through */
1304             case PAYLOAD_BLOCK_UNMAPPED:
1305             case PAYLOAD_BLOCK_UNMAPPED_v095:
1306             case PAYLOAD_BLOCK_UNDEFINED:
1307                 bat_prior_offset = sinfo.file_offset;
1308                 ret = vhdx_allocate_block(bs, s, &sinfo.file_offset);
1309                 if (ret < 0) {
1310                     goto exit;
1311                 }
1312                 /* once we support differencing files, this may also be
1313                  * partially present */
1314                 /* update block state to the newly specified state */
1315                 vhdx_update_bat_table_entry(bs, s, &sinfo, &bat_entry,
1316                                             &bat_entry_offset,
1317                                             PAYLOAD_BLOCK_FULLY_PRESENT);
1318                 bat_update = true;
1319                 /* since we just allocated a block, file_offset is the
1320                  * beginning of the payload block. It needs to be the
1321                  * write address, which includes the offset into the block */
1322                 if (!use_zero_buffers) {
1323                     sinfo.file_offset += sinfo.block_offset;
1324                 }
1325                 /* fall through */
1326             case PAYLOAD_BLOCK_FULLY_PRESENT:
1327                 /* if the file offset address is in the header zone,
1328                  * there is a problem */
1329                 if (sinfo.file_offset < (1024 * 1024)) {
1330                     ret = -EFAULT;
1331                     goto error_bat_restore;
1332                 }
1333 
1334                 if (!use_zero_buffers) {
1335                     qemu_iovec_concat(&hd_qiov, qiov,  bytes_done,
1336                                       sinfo.bytes_avail);
1337                 }
1338                 /* block exists, so we can just overwrite it */
1339                 qemu_co_mutex_unlock(&s->lock);
1340                 ret = bdrv_co_writev(bs->file,
1341                                     sinfo.file_offset >> BDRV_SECTOR_BITS,
1342                                     sectors_to_write, &hd_qiov);
1343                 qemu_co_mutex_lock(&s->lock);
1344                 if (ret < 0) {
1345                     goto error_bat_restore;
1346                 }
1347                 break;
1348             case PAYLOAD_BLOCK_PARTIALLY_PRESENT:
1349                 /* we don't yet support difference files, fall through
1350                  * to error */
1351             default:
1352                 ret = -EIO;
1353                 goto exit;
1354                 break;
1355             }
1356 
1357             if (bat_update) {
1358                 /* this will update the BAT entry into the log journal, and
1359                  * then flush the log journal out to disk */
1360                 ret =  vhdx_log_write_and_flush(bs, s, &bat_entry,
1361                                                 sizeof(VHDXBatEntry),
1362                                                 bat_entry_offset);
1363                 if (ret < 0) {
1364                     goto exit;
1365                 }
1366             }
1367 
1368             nb_sectors -= sinfo.sectors_avail;
1369             sector_num += sinfo.sectors_avail;
1370             bytes_done += sinfo.bytes_avail;
1371 
1372         }
1373     }
1374 
1375     goto exit;
1376 
1377 error_bat_restore:
1378     if (bat_update) {
1379         /* keep metadata in sync, and restore the bat entry state
1380          * if error. */
1381         sinfo.file_offset = bat_prior_offset;
1382         vhdx_update_bat_table_entry(bs, s, &sinfo, &bat_entry,
1383                                     &bat_entry_offset, bat_state);
1384     }
1385 exit:
1386     qemu_vfree(iov1.iov_base);
1387     qemu_vfree(iov2.iov_base);
1388     qemu_co_mutex_unlock(&s->lock);
1389     qemu_iovec_destroy(&hd_qiov);
1390     return ret;
1391 }
1392 
1393 
1394 
1395 /*
1396  * Create VHDX Headers
1397  *
1398  * There are 2 headers, and the highest sequence number will represent
1399  * the active header
1400  */
1401 static int vhdx_create_new_headers(BlockBackend *blk, uint64_t image_size,
1402                                    uint32_t log_size)
1403 {
1404     BlockDriverState *bs = blk_bs(blk);
1405     BdrvChild *child;
1406     int ret = 0;
1407     VHDXHeader *hdr = NULL;
1408 
1409     hdr = g_new0(VHDXHeader, 1);
1410 
1411     hdr->signature       = VHDX_HEADER_SIGNATURE;
1412     hdr->sequence_number = g_random_int();
1413     hdr->log_version     = 0;
1414     hdr->version         = 1;
1415     hdr->log_length      = log_size;
1416     hdr->log_offset      = VHDX_HEADER_SECTION_END;
1417     vhdx_guid_generate(&hdr->file_write_guid);
1418     vhdx_guid_generate(&hdr->data_write_guid);
1419 
1420     /* XXX Ugly way to get blk->root, but that's a feature, not a bug. This
1421      * hack makes it obvious that vhdx_write_header() bypasses the BlockBackend
1422      * here, which it really shouldn't be doing. */
1423     child = QLIST_FIRST(&bs->parents);
1424     assert(!QLIST_NEXT(child, next_parent));
1425 
1426     ret = vhdx_write_header(child, hdr, VHDX_HEADER1_OFFSET, false);
1427     if (ret < 0) {
1428         goto exit;
1429     }
1430     hdr->sequence_number++;
1431     ret = vhdx_write_header(child, hdr, VHDX_HEADER2_OFFSET, false);
1432     if (ret < 0) {
1433         goto exit;
1434     }
1435 
1436 exit:
1437     g_free(hdr);
1438     return ret;
1439 }
1440 
1441 #define VHDX_METADATA_ENTRY_BUFFER_SIZE \
1442                                     (sizeof(VHDXFileParameters)               +\
1443                                      sizeof(VHDXVirtualDiskSize)              +\
1444                                      sizeof(VHDXPage83Data)                   +\
1445                                      sizeof(VHDXVirtualDiskLogicalSectorSize) +\
1446                                      sizeof(VHDXVirtualDiskPhysicalSectorSize))
1447 
1448 /*
1449  * Create the Metadata entries.
1450  *
1451  * For more details on the entries, see section 3.5 (pg 29) in the
1452  * VHDX 1.00 specification.
1453  *
1454  * We support 5 metadata entries (all required by spec):
1455  *          File Parameters,
1456  *          Virtual Disk Size,
1457  *          Page 83 Data,
1458  *          Logical Sector Size,
1459  *          Physical Sector Size
1460  *
1461  * The first 64KB of the Metadata section is reserved for the metadata
1462  * header and entries; beyond that, the metadata items themselves reside.
1463  */
1464 static int vhdx_create_new_metadata(BlockBackend *blk,
1465                                     uint64_t image_size,
1466                                     uint32_t block_size,
1467                                     uint32_t sector_size,
1468                                     uint64_t metadata_offset,
1469                                     VHDXImageType type)
1470 {
1471     int ret = 0;
1472     uint32_t offset = 0;
1473     void *buffer = NULL;
1474     void *entry_buffer;
1475     VHDXMetadataTableHeader *md_table;
1476     VHDXMetadataTableEntry  *md_table_entry;
1477 
1478     /* Metadata entries */
1479     VHDXFileParameters     *mt_file_params;
1480     VHDXVirtualDiskSize    *mt_virtual_size;
1481     VHDXPage83Data         *mt_page83;
1482     VHDXVirtualDiskLogicalSectorSize  *mt_log_sector_size;
1483     VHDXVirtualDiskPhysicalSectorSize *mt_phys_sector_size;
1484 
1485     entry_buffer = g_malloc0(VHDX_METADATA_ENTRY_BUFFER_SIZE);
1486 
1487     mt_file_params = entry_buffer;
1488     offset += sizeof(VHDXFileParameters);
1489     mt_virtual_size = entry_buffer + offset;
1490     offset += sizeof(VHDXVirtualDiskSize);
1491     mt_page83 = entry_buffer + offset;
1492     offset += sizeof(VHDXPage83Data);
1493     mt_log_sector_size = entry_buffer + offset;
1494     offset += sizeof(VHDXVirtualDiskLogicalSectorSize);
1495     mt_phys_sector_size = entry_buffer + offset;
1496 
1497     mt_file_params->block_size = cpu_to_le32(block_size);
1498     if (type == VHDX_TYPE_FIXED) {
1499         mt_file_params->data_bits |= VHDX_PARAMS_LEAVE_BLOCKS_ALLOCED;
1500         cpu_to_le32s(&mt_file_params->data_bits);
1501     }
1502 
1503     vhdx_guid_generate(&mt_page83->page_83_data);
1504     cpu_to_leguids(&mt_page83->page_83_data);
1505     mt_virtual_size->virtual_disk_size        = cpu_to_le64(image_size);
1506     mt_log_sector_size->logical_sector_size   = cpu_to_le32(sector_size);
1507     mt_phys_sector_size->physical_sector_size = cpu_to_le32(sector_size);
1508 
1509     buffer = g_malloc0(VHDX_HEADER_BLOCK_SIZE);
1510     md_table = buffer;
1511 
1512     md_table->signature   = VHDX_METADATA_SIGNATURE;
1513     md_table->entry_count = 5;
1514     vhdx_metadata_header_le_export(md_table);
1515 
1516 
1517     /* This will reference beyond the reserved table portion */
1518     offset = 64 * KiB;
1519 
1520     md_table_entry = buffer + sizeof(VHDXMetadataTableHeader);
1521 
1522     md_table_entry[0].item_id = file_param_guid;
1523     md_table_entry[0].offset  = offset;
1524     md_table_entry[0].length  = sizeof(VHDXFileParameters);
1525     md_table_entry[0].data_bits |= VHDX_META_FLAGS_IS_REQUIRED;
1526     offset += md_table_entry[0].length;
1527     vhdx_metadata_entry_le_export(&md_table_entry[0]);
1528 
1529     md_table_entry[1].item_id = virtual_size_guid;
1530     md_table_entry[1].offset  = offset;
1531     md_table_entry[1].length  = sizeof(VHDXVirtualDiskSize);
1532     md_table_entry[1].data_bits |= VHDX_META_FLAGS_IS_REQUIRED |
1533                                    VHDX_META_FLAGS_IS_VIRTUAL_DISK;
1534     offset += md_table_entry[1].length;
1535     vhdx_metadata_entry_le_export(&md_table_entry[1]);
1536 
1537     md_table_entry[2].item_id = page83_guid;
1538     md_table_entry[2].offset  = offset;
1539     md_table_entry[2].length  = sizeof(VHDXPage83Data);
1540     md_table_entry[2].data_bits |= VHDX_META_FLAGS_IS_REQUIRED |
1541                                    VHDX_META_FLAGS_IS_VIRTUAL_DISK;
1542     offset += md_table_entry[2].length;
1543     vhdx_metadata_entry_le_export(&md_table_entry[2]);
1544 
1545     md_table_entry[3].item_id = logical_sector_guid;
1546     md_table_entry[3].offset  = offset;
1547     md_table_entry[3].length  = sizeof(VHDXVirtualDiskLogicalSectorSize);
1548     md_table_entry[3].data_bits |= VHDX_META_FLAGS_IS_REQUIRED |
1549                                    VHDX_META_FLAGS_IS_VIRTUAL_DISK;
1550     offset += md_table_entry[3].length;
1551     vhdx_metadata_entry_le_export(&md_table_entry[3]);
1552 
1553     md_table_entry[4].item_id = phys_sector_guid;
1554     md_table_entry[4].offset  = offset;
1555     md_table_entry[4].length  = sizeof(VHDXVirtualDiskPhysicalSectorSize);
1556     md_table_entry[4].data_bits |= VHDX_META_FLAGS_IS_REQUIRED |
1557                                    VHDX_META_FLAGS_IS_VIRTUAL_DISK;
1558     vhdx_metadata_entry_le_export(&md_table_entry[4]);
1559 
1560     ret = blk_pwrite(blk, metadata_offset, buffer, VHDX_HEADER_BLOCK_SIZE, 0);
1561     if (ret < 0) {
1562         goto exit;
1563     }
1564 
1565     ret = blk_pwrite(blk, metadata_offset + (64 * KiB), entry_buffer,
1566                      VHDX_METADATA_ENTRY_BUFFER_SIZE, 0);
1567     if (ret < 0) {
1568         goto exit;
1569     }
1570 
1571 
1572 exit:
1573     g_free(buffer);
1574     g_free(entry_buffer);
1575     return ret;
1576 }
1577 
1578 /* This create the actual BAT itself.  We currently only support
1579  * 'Dynamic' and 'Fixed' image types.
1580  *
1581  *  Dynamic images: default state of the BAT is all zeroes.
1582  *
1583  *  Fixed images: default state of the BAT is fully populated, with
1584  *                file offsets and state PAYLOAD_BLOCK_FULLY_PRESENT.
1585  */
1586 static int vhdx_create_bat(BlockBackend *blk, BDRVVHDXState *s,
1587                            uint64_t image_size, VHDXImageType type,
1588                            bool use_zero_blocks, uint64_t file_offset,
1589                            uint32_t length, Error **errp)
1590 {
1591     int ret = 0;
1592     uint64_t data_file_offset;
1593     uint64_t total_sectors = 0;
1594     uint64_t sector_num = 0;
1595     uint64_t unused;
1596     int block_state;
1597     VHDXSectorInfo sinfo;
1598 
1599     assert(s->bat == NULL);
1600 
1601     /* this gives a data start after BAT/bitmap entries, and well
1602      * past any metadata entries (with a 4 MB buffer for future
1603      * expansion */
1604     data_file_offset = file_offset + length + 5 * MiB;
1605     total_sectors = image_size >> s->logical_sector_size_bits;
1606 
1607     if (type == VHDX_TYPE_DYNAMIC) {
1608         /* All zeroes, so we can just extend the file - the end of the BAT
1609          * is the furthest thing we have written yet */
1610         ret = blk_truncate(blk, data_file_offset, errp);
1611         if (ret < 0) {
1612             goto exit;
1613         }
1614     } else if (type == VHDX_TYPE_FIXED) {
1615         ret = blk_truncate(blk, data_file_offset + image_size, errp);
1616         if (ret < 0) {
1617             goto exit;
1618         }
1619     } else {
1620         error_setg(errp, "Unsupported image type");
1621         ret = -ENOTSUP;
1622         goto exit;
1623     }
1624 
1625     if (type == VHDX_TYPE_FIXED ||
1626                 use_zero_blocks ||
1627                 bdrv_has_zero_init(blk_bs(blk)) == 0) {
1628         /* for a fixed file, the default BAT entry is not zero */
1629         s->bat = g_try_malloc0(length);
1630         if (length && s->bat == NULL) {
1631             error_setg(errp, "Failed to allocate memory for the BAT");
1632             ret = -ENOMEM;
1633             goto exit;
1634         }
1635         block_state = type == VHDX_TYPE_FIXED ? PAYLOAD_BLOCK_FULLY_PRESENT :
1636                                                 PAYLOAD_BLOCK_NOT_PRESENT;
1637         block_state = use_zero_blocks ? PAYLOAD_BLOCK_ZERO : block_state;
1638         /* fill the BAT by emulating sector writes of sectors_per_block size */
1639         while (sector_num < total_sectors) {
1640             vhdx_block_translate(s, sector_num, s->sectors_per_block, &sinfo);
1641             sinfo.file_offset = data_file_offset +
1642                                 (sector_num << s->logical_sector_size_bits);
1643             sinfo.file_offset = ROUND_UP(sinfo.file_offset, MiB);
1644             vhdx_update_bat_table_entry(blk_bs(blk), s, &sinfo, &unused, &unused,
1645                                         block_state);
1646             cpu_to_le64s(&s->bat[sinfo.bat_idx]);
1647             sector_num += s->sectors_per_block;
1648         }
1649         ret = blk_pwrite(blk, file_offset, s->bat, length, 0);
1650         if (ret < 0) {
1651             error_setg_errno(errp, -ret, "Failed to write the BAT");
1652             goto exit;
1653         }
1654     }
1655 
1656 
1657 
1658 exit:
1659     g_free(s->bat);
1660     return ret;
1661 }
1662 
1663 /* Creates the region table header, and region table entries.
1664  * There are 2 supported region table entries: BAT, and Metadata/
1665  *
1666  * As the calculations for the BAT region table are also needed
1667  * to create the BAT itself, we will also cause the BAT to be
1668  * created.
1669  */
1670 static int vhdx_create_new_region_table(BlockBackend *blk,
1671                                         uint64_t image_size,
1672                                         uint32_t block_size,
1673                                         uint32_t sector_size,
1674                                         uint32_t log_size,
1675                                         bool use_zero_blocks,
1676                                         VHDXImageType type,
1677                                         uint64_t *metadata_offset,
1678                                         Error **errp)
1679 {
1680     int ret = 0;
1681     uint32_t offset = 0;
1682     void *buffer = NULL;
1683     uint64_t bat_file_offset;
1684     uint32_t bat_length;
1685     BDRVVHDXState *s = NULL;
1686     VHDXRegionTableHeader *region_table;
1687     VHDXRegionTableEntry *rt_bat;
1688     VHDXRegionTableEntry *rt_metadata;
1689 
1690     assert(metadata_offset != NULL);
1691 
1692     /* Populate enough of the BDRVVHDXState to be able to use the
1693      * pre-existing BAT calculation, translation, and update functions */
1694     s = g_new0(BDRVVHDXState, 1);
1695 
1696     s->chunk_ratio = (VHDX_MAX_SECTORS_PER_BLOCK) *
1697                      (uint64_t) sector_size / (uint64_t) block_size;
1698 
1699     s->sectors_per_block = block_size / sector_size;
1700     s->virtual_disk_size = image_size;
1701     s->block_size = block_size;
1702     s->logical_sector_size = sector_size;
1703 
1704     vhdx_set_shift_bits(s);
1705 
1706     vhdx_calc_bat_entries(s);
1707 
1708     /* At this point the VHDX state is populated enough for creation */
1709 
1710     /* a single buffer is used so we can calculate the checksum over the
1711      * entire 64KB block */
1712     buffer = g_malloc0(VHDX_HEADER_BLOCK_SIZE);
1713     region_table = buffer;
1714     offset += sizeof(VHDXRegionTableHeader);
1715     rt_bat = buffer + offset;
1716     offset += sizeof(VHDXRegionTableEntry);
1717     rt_metadata  = buffer + offset;
1718 
1719     region_table->signature = VHDX_REGION_SIGNATURE;
1720     region_table->entry_count = 2;   /* BAT and Metadata */
1721 
1722     rt_bat->guid        = bat_guid;
1723     rt_bat->length      = ROUND_UP(s->bat_entries * sizeof(VHDXBatEntry), MiB);
1724     rt_bat->file_offset = ROUND_UP(VHDX_HEADER_SECTION_END + log_size, MiB);
1725     s->bat_offset = rt_bat->file_offset;
1726 
1727     rt_metadata->guid        = metadata_guid;
1728     rt_metadata->file_offset = ROUND_UP(rt_bat->file_offset + rt_bat->length,
1729                                         MiB);
1730     rt_metadata->length      = 1 * MiB; /* min size, and more than enough */
1731     *metadata_offset = rt_metadata->file_offset;
1732 
1733     bat_file_offset = rt_bat->file_offset;
1734     bat_length = rt_bat->length;
1735 
1736     vhdx_region_header_le_export(region_table);
1737     vhdx_region_entry_le_export(rt_bat);
1738     vhdx_region_entry_le_export(rt_metadata);
1739 
1740     vhdx_update_checksum(buffer, VHDX_HEADER_BLOCK_SIZE,
1741                          offsetof(VHDXRegionTableHeader, checksum));
1742 
1743 
1744     /* The region table gives us the data we need to create the BAT,
1745      * so do that now */
1746     ret = vhdx_create_bat(blk, s, image_size, type, use_zero_blocks,
1747                           bat_file_offset, bat_length, errp);
1748     if (ret < 0) {
1749         goto exit;
1750     }
1751 
1752     /* Now write out the region headers to disk */
1753     ret = blk_pwrite(blk, VHDX_REGION_TABLE_OFFSET, buffer,
1754                      VHDX_HEADER_BLOCK_SIZE, 0);
1755     if (ret < 0) {
1756         error_setg_errno(errp, -ret, "Failed to write first region table");
1757         goto exit;
1758     }
1759 
1760     ret = blk_pwrite(blk, VHDX_REGION_TABLE2_OFFSET, buffer,
1761                      VHDX_HEADER_BLOCK_SIZE, 0);
1762     if (ret < 0) {
1763         error_setg_errno(errp, -ret, "Failed to write second region table");
1764         goto exit;
1765     }
1766 
1767 exit:
1768     g_free(s);
1769     g_free(buffer);
1770     return ret;
1771 }
1772 
1773 /* We need to create the following elements:
1774  *
1775  *    .-----------------------------------------------------------------.
1776  *    |   (A)    |   (B)    |    (C)    |     (D)       |     (E)       |
1777  *    |  File ID |  Header1 |  Header 2 |  Region Tbl 1 |  Region Tbl 2 |
1778  *    |          |          |           |               |               |
1779  *    .-----------------------------------------------------------------.
1780  *    0         64KB      128KB       192KB           256KB           320KB
1781  *
1782  *
1783  *    .---- ~ ----------- ~ ------------ ~ ---------------- ~ -----------.
1784  *    |     (F)     |     (G)       |    (H)    |                        |
1785  *    | Journal Log |  BAT / Bitmap |  Metadata |  .... data ......      |
1786  *    |             |               |           |                        |
1787  *    .---- ~ ----------- ~ ------------ ~ ---------------- ~ -----------.
1788  *   1MB
1789  */
1790 static int vhdx_create(const char *filename, QemuOpts *opts, Error **errp)
1791 {
1792     int ret = 0;
1793     uint64_t image_size = (uint64_t) 2 * GiB;
1794     uint32_t log_size   = 1 * MiB;
1795     uint32_t block_size = 0;
1796     uint64_t signature;
1797     uint64_t metadata_offset;
1798     bool use_zero_blocks = false;
1799 
1800     gunichar2 *creator = NULL;
1801     glong creator_items;
1802     BlockBackend *blk;
1803     char *type = NULL;
1804     VHDXImageType image_type;
1805     Error *local_err = NULL;
1806 
1807     image_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1808                           BDRV_SECTOR_SIZE);
1809     log_size = qemu_opt_get_size_del(opts, VHDX_BLOCK_OPT_LOG_SIZE, 0);
1810     block_size = qemu_opt_get_size_del(opts, VHDX_BLOCK_OPT_BLOCK_SIZE, 0);
1811     type = qemu_opt_get_del(opts, BLOCK_OPT_SUBFMT);
1812     use_zero_blocks = qemu_opt_get_bool_del(opts, VHDX_BLOCK_OPT_ZERO, true);
1813 
1814     if (image_size > VHDX_MAX_IMAGE_SIZE) {
1815         error_setg_errno(errp, EINVAL, "Image size too large; max of 64TB");
1816         ret = -EINVAL;
1817         goto exit;
1818     }
1819 
1820     if (type == NULL) {
1821         type = g_strdup("dynamic");
1822     }
1823 
1824     if (!strcmp(type, "dynamic")) {
1825         image_type = VHDX_TYPE_DYNAMIC;
1826     } else if (!strcmp(type, "fixed")) {
1827         image_type = VHDX_TYPE_FIXED;
1828     } else if (!strcmp(type, "differencing")) {
1829         error_setg_errno(errp, ENOTSUP,
1830                          "Differencing files not yet supported");
1831         ret = -ENOTSUP;
1832         goto exit;
1833     } else {
1834         error_setg(errp, "Invalid subformat '%s'", type);
1835         ret = -EINVAL;
1836         goto exit;
1837     }
1838 
1839     /* These are pretty arbitrary, and mainly designed to keep the BAT
1840      * size reasonable to load into RAM */
1841     if (block_size == 0) {
1842         if (image_size > 32 * TiB) {
1843             block_size = 64 * MiB;
1844         } else if (image_size > (uint64_t) 100 * GiB) {
1845             block_size = 32 * MiB;
1846         } else if (image_size > 1 * GiB) {
1847             block_size = 16 * MiB;
1848         } else {
1849             block_size = 8 * MiB;
1850         }
1851     }
1852 
1853 
1854     /* make the log size close to what was specified, but must be
1855      * min 1MB, and multiple of 1MB */
1856     log_size = ROUND_UP(log_size, MiB);
1857 
1858     block_size = ROUND_UP(block_size, MiB);
1859     block_size = block_size > VHDX_BLOCK_SIZE_MAX ? VHDX_BLOCK_SIZE_MAX :
1860                                                     block_size;
1861 
1862     ret = bdrv_create_file(filename, opts, &local_err);
1863     if (ret < 0) {
1864         error_propagate(errp, local_err);
1865         goto exit;
1866     }
1867 
1868     blk = blk_new_open(filename, NULL, NULL,
1869                        BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
1870                        &local_err);
1871     if (blk == NULL) {
1872         error_propagate(errp, local_err);
1873         ret = -EIO;
1874         goto exit;
1875     }
1876 
1877     blk_set_allow_write_beyond_eof(blk, true);
1878 
1879     /* Create (A) */
1880 
1881     /* The creator field is optional, but may be useful for
1882      * debugging / diagnostics */
1883     creator = g_utf8_to_utf16("QEMU v" QEMU_VERSION, -1, NULL,
1884                               &creator_items, NULL);
1885     signature = cpu_to_le64(VHDX_FILE_SIGNATURE);
1886     ret = blk_pwrite(blk, VHDX_FILE_ID_OFFSET, &signature, sizeof(signature),
1887                      0);
1888     if (ret < 0) {
1889         error_setg_errno(errp, -ret, "Failed to write file signature");
1890         goto delete_and_exit;
1891     }
1892     if (creator) {
1893         ret = blk_pwrite(blk, VHDX_FILE_ID_OFFSET + sizeof(signature),
1894                          creator, creator_items * sizeof(gunichar2), 0);
1895         if (ret < 0) {
1896             error_setg_errno(errp, -ret, "Failed to write creator field");
1897             goto delete_and_exit;
1898         }
1899     }
1900 
1901 
1902     /* Creates (B),(C) */
1903     ret = vhdx_create_new_headers(blk, image_size, log_size);
1904     if (ret < 0) {
1905         error_setg_errno(errp, -ret, "Failed to write image headers");
1906         goto delete_and_exit;
1907     }
1908 
1909     /* Creates (D),(E),(G) explicitly. (F) created as by-product */
1910     ret = vhdx_create_new_region_table(blk, image_size, block_size, 512,
1911                                        log_size, use_zero_blocks, image_type,
1912                                        &metadata_offset, errp);
1913     if (ret < 0) {
1914         goto delete_and_exit;
1915     }
1916 
1917     /* Creates (H) */
1918     ret = vhdx_create_new_metadata(blk, image_size, block_size, 512,
1919                                    metadata_offset, image_type);
1920     if (ret < 0) {
1921         error_setg_errno(errp, -ret, "Failed to initialize metadata");
1922         goto delete_and_exit;
1923     }
1924 
1925 
1926 delete_and_exit:
1927     blk_unref(blk);
1928 exit:
1929     g_free(type);
1930     g_free(creator);
1931     return ret;
1932 }
1933 
1934 /* If opened r/w, the VHDX driver will automatically replay the log,
1935  * if one is present, inside the vhdx_open() call.
1936  *
1937  * If qemu-img check -r all is called, the image is automatically opened
1938  * r/w and any log has already been replayed, so there is nothing (currently)
1939  * for us to do here
1940  */
1941 static int vhdx_check(BlockDriverState *bs, BdrvCheckResult *result,
1942                        BdrvCheckMode fix)
1943 {
1944     BDRVVHDXState *s = bs->opaque;
1945 
1946     if (s->log_replayed_on_open) {
1947         result->corruptions_fixed++;
1948     }
1949     return 0;
1950 }
1951 
1952 static QemuOptsList vhdx_create_opts = {
1953     .name = "vhdx-create-opts",
1954     .head = QTAILQ_HEAD_INITIALIZER(vhdx_create_opts.head),
1955     .desc = {
1956         {
1957            .name = BLOCK_OPT_SIZE,
1958            .type = QEMU_OPT_SIZE,
1959            .help = "Virtual disk size; max of 64TB."
1960        },
1961        {
1962            .name = VHDX_BLOCK_OPT_LOG_SIZE,
1963            .type = QEMU_OPT_SIZE,
1964            .def_value_str = stringify(DEFAULT_LOG_SIZE),
1965            .help = "Log size; min 1MB."
1966        },
1967        {
1968            .name = VHDX_BLOCK_OPT_BLOCK_SIZE,
1969            .type = QEMU_OPT_SIZE,
1970            .def_value_str = stringify(0),
1971            .help = "Block Size; min 1MB, max 256MB. " \
1972                    "0 means auto-calculate based on image size."
1973        },
1974        {
1975            .name = BLOCK_OPT_SUBFMT,
1976            .type = QEMU_OPT_STRING,
1977            .help = "VHDX format type, can be either 'dynamic' or 'fixed'. "\
1978                    "Default is 'dynamic'."
1979        },
1980        {
1981            .name = VHDX_BLOCK_OPT_ZERO,
1982            .type = QEMU_OPT_BOOL,
1983            .help = "Force use of payload blocks of type 'ZERO'. "\
1984                    "Non-standard, but default.  Do not set to 'off' when "\
1985                    "using 'qemu-img convert' with subformat=dynamic."
1986        },
1987        { NULL }
1988     }
1989 };
1990 
1991 static BlockDriver bdrv_vhdx = {
1992     .format_name            = "vhdx",
1993     .instance_size          = sizeof(BDRVVHDXState),
1994     .bdrv_probe             = vhdx_probe,
1995     .bdrv_open              = vhdx_open,
1996     .bdrv_close             = vhdx_close,
1997     .bdrv_reopen_prepare    = vhdx_reopen_prepare,
1998     .bdrv_child_perm        = bdrv_format_default_perms,
1999     .bdrv_co_readv          = vhdx_co_readv,
2000     .bdrv_co_writev         = vhdx_co_writev,
2001     .bdrv_create            = vhdx_create,
2002     .bdrv_get_info          = vhdx_get_info,
2003     .bdrv_check             = vhdx_check,
2004     .bdrv_has_zero_init     = bdrv_has_zero_init_1,
2005 
2006     .create_opts            = &vhdx_create_opts,
2007 };
2008 
2009 static void bdrv_vhdx_init(void)
2010 {
2011     bdrv_register(&bdrv_vhdx);
2012 }
2013 
2014 block_init(bdrv_vhdx_init);
2015