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