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