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