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