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