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