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