xref: /openbmc/qemu/block/vpc.c (revision fee5b753)
1 /*
2  * Block driver for Connectix / Microsoft Virtual PC images
3  *
4  * Copyright (c) 2005 Alex Beregszaszi
5  * Copyright (c) 2009 Kevin Wolf <kwolf@suse.de>
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23  * THE SOFTWARE.
24  */
25 #include "qemu/osdep.h"
26 #include "qemu-common.h"
27 #include "block/block_int.h"
28 #include "qemu/module.h"
29 #include "migration/migration.h"
30 #if defined(CONFIG_UUID)
31 #include <uuid/uuid.h>
32 #endif
33 
34 /**************************************************************/
35 
36 #define HEADER_SIZE 512
37 
38 //#define CACHE
39 
40 enum vhd_type {
41     VHD_FIXED           = 2,
42     VHD_DYNAMIC         = 3,
43     VHD_DIFFERENCING    = 4,
44 };
45 
46 // Seconds since Jan 1, 2000 0:00:00 (UTC)
47 #define VHD_TIMESTAMP_BASE 946684800
48 
49 #define VHD_MAX_SECTORS       (65535LL * 255 * 255)
50 #define VHD_MAX_GEOMETRY      (65535LL *  16 * 255)
51 
52 // always big-endian
53 typedef struct vhd_footer {
54     char        creator[8]; // "conectix"
55     uint32_t    features;
56     uint32_t    version;
57 
58     // Offset of next header structure, 0xFFFFFFFF if none
59     uint64_t    data_offset;
60 
61     // Seconds since Jan 1, 2000 0:00:00 (UTC)
62     uint32_t    timestamp;
63 
64     char        creator_app[4]; // "vpc "
65     uint16_t    major;
66     uint16_t    minor;
67     char        creator_os[4]; // "Wi2k"
68 
69     uint64_t    orig_size;
70     uint64_t    current_size;
71 
72     uint16_t    cyls;
73     uint8_t     heads;
74     uint8_t     secs_per_cyl;
75 
76     uint32_t    type;
77 
78     // Checksum of the Hard Disk Footer ("one's complement of the sum of all
79     // the bytes in the footer without the checksum field")
80     uint32_t    checksum;
81 
82     // UUID used to identify a parent hard disk (backing file)
83     uint8_t     uuid[16];
84 
85     uint8_t     in_saved_state;
86 } QEMU_PACKED VHDFooter;
87 
88 typedef struct vhd_dyndisk_header {
89     char        magic[8]; // "cxsparse"
90 
91     // Offset of next header structure, 0xFFFFFFFF if none
92     uint64_t    data_offset;
93 
94     // Offset of the Block Allocation Table (BAT)
95     uint64_t    table_offset;
96 
97     uint32_t    version;
98     uint32_t    max_table_entries; // 32bit/entry
99 
100     // 2 MB by default, must be a power of two
101     uint32_t    block_size;
102 
103     uint32_t    checksum;
104     uint8_t     parent_uuid[16];
105     uint32_t    parent_timestamp;
106     uint32_t    reserved;
107 
108     // Backing file name (in UTF-16)
109     uint8_t     parent_name[512];
110 
111     struct {
112         uint32_t    platform;
113         uint32_t    data_space;
114         uint32_t    data_length;
115         uint32_t    reserved;
116         uint64_t    data_offset;
117     } parent_locator[8];
118 } QEMU_PACKED VHDDynDiskHeader;
119 
120 typedef struct BDRVVPCState {
121     CoMutex lock;
122     uint8_t footer_buf[HEADER_SIZE];
123     uint64_t free_data_block_offset;
124     int max_table_entries;
125     uint32_t *pagetable;
126     uint64_t bat_offset;
127     uint64_t last_bitmap_offset;
128 
129     uint32_t block_size;
130     uint32_t bitmap_size;
131 
132 #ifdef CACHE
133     uint8_t *pageentry_u8;
134     uint32_t *pageentry_u32;
135     uint16_t *pageentry_u16;
136 
137     uint64_t last_bitmap;
138 #endif
139 
140     Error *migration_blocker;
141 } BDRVVPCState;
142 
143 static uint32_t vpc_checksum(uint8_t* buf, size_t size)
144 {
145     uint32_t res = 0;
146     int i;
147 
148     for (i = 0; i < size; i++)
149         res += buf[i];
150 
151     return ~res;
152 }
153 
154 
155 static int vpc_probe(const uint8_t *buf, int buf_size, const char *filename)
156 {
157     if (buf_size >= 8 && !strncmp((char *)buf, "conectix", 8))
158 	return 100;
159     return 0;
160 }
161 
162 static int vpc_open(BlockDriverState *bs, QDict *options, int flags,
163                     Error **errp)
164 {
165     BDRVVPCState *s = bs->opaque;
166     int i;
167     VHDFooter *footer;
168     VHDDynDiskHeader *dyndisk_header;
169     uint8_t buf[HEADER_SIZE];
170     uint32_t checksum;
171     uint64_t computed_size;
172     uint64_t pagetable_size;
173     int disk_type = VHD_DYNAMIC;
174     int ret;
175 
176     ret = bdrv_pread(bs->file->bs, 0, s->footer_buf, HEADER_SIZE);
177     if (ret < 0) {
178         goto fail;
179     }
180 
181     footer = (VHDFooter *) s->footer_buf;
182     if (strncmp(footer->creator, "conectix", 8)) {
183         int64_t offset = bdrv_getlength(bs->file->bs);
184         if (offset < 0) {
185             ret = offset;
186             goto fail;
187         } else if (offset < HEADER_SIZE) {
188             ret = -EINVAL;
189             goto fail;
190         }
191 
192         /* If a fixed disk, the footer is found only at the end of the file */
193         ret = bdrv_pread(bs->file->bs, offset-HEADER_SIZE, s->footer_buf,
194                          HEADER_SIZE);
195         if (ret < 0) {
196             goto fail;
197         }
198         if (strncmp(footer->creator, "conectix", 8)) {
199             error_setg(errp, "invalid VPC image");
200             ret = -EINVAL;
201             goto fail;
202         }
203         disk_type = VHD_FIXED;
204     }
205 
206     checksum = be32_to_cpu(footer->checksum);
207     footer->checksum = 0;
208     if (vpc_checksum(s->footer_buf, HEADER_SIZE) != checksum)
209         fprintf(stderr, "block-vpc: The header checksum of '%s' is "
210             "incorrect.\n", bs->filename);
211 
212     /* Write 'checksum' back to footer, or else will leave it with zero. */
213     footer->checksum = cpu_to_be32(checksum);
214 
215     // The visible size of a image in Virtual PC depends on the geometry
216     // rather than on the size stored in the footer (the size in the footer
217     // is too large usually)
218     bs->total_sectors = (int64_t)
219         be16_to_cpu(footer->cyls) * footer->heads * footer->secs_per_cyl;
220 
221     /* Images that have exactly the maximum geometry are probably bigger and
222      * would be truncated if we adhered to the geometry for them. Rely on
223      * footer->current_size for them. */
224     if (bs->total_sectors == VHD_MAX_GEOMETRY) {
225         bs->total_sectors = be64_to_cpu(footer->current_size) /
226                             BDRV_SECTOR_SIZE;
227     }
228 
229     /* Allow a maximum disk size of approximately 2 TB */
230     if (bs->total_sectors >= VHD_MAX_SECTORS) {
231         ret = -EFBIG;
232         goto fail;
233     }
234 
235     if (disk_type == VHD_DYNAMIC) {
236         ret = bdrv_pread(bs->file->bs, be64_to_cpu(footer->data_offset), buf,
237                          HEADER_SIZE);
238         if (ret < 0) {
239             goto fail;
240         }
241 
242         dyndisk_header = (VHDDynDiskHeader *) buf;
243 
244         if (strncmp(dyndisk_header->magic, "cxsparse", 8)) {
245             ret = -EINVAL;
246             goto fail;
247         }
248 
249         s->block_size = be32_to_cpu(dyndisk_header->block_size);
250         if (!is_power_of_2(s->block_size) || s->block_size < BDRV_SECTOR_SIZE) {
251             error_setg(errp, "Invalid block size %" PRIu32, s->block_size);
252             ret = -EINVAL;
253             goto fail;
254         }
255         s->bitmap_size = ((s->block_size / (8 * 512)) + 511) & ~511;
256 
257         s->max_table_entries = be32_to_cpu(dyndisk_header->max_table_entries);
258 
259         if ((bs->total_sectors * 512) / s->block_size > 0xffffffffU) {
260             ret = -EINVAL;
261             goto fail;
262         }
263         if (s->max_table_entries > (VHD_MAX_SECTORS * 512) / s->block_size) {
264             ret = -EINVAL;
265             goto fail;
266         }
267 
268         computed_size = (uint64_t) s->max_table_entries * s->block_size;
269         if (computed_size < bs->total_sectors * 512) {
270             ret = -EINVAL;
271             goto fail;
272         }
273 
274         if (s->max_table_entries > SIZE_MAX / 4 ||
275             s->max_table_entries > (int) INT_MAX / 4) {
276             error_setg(errp, "Max Table Entries too large (%" PRId32 ")",
277                         s->max_table_entries);
278             ret = -EINVAL;
279             goto fail;
280         }
281 
282         pagetable_size = (uint64_t) s->max_table_entries * 4;
283 
284         s->pagetable = qemu_try_blockalign(bs->file->bs, pagetable_size);
285         if (s->pagetable == NULL) {
286             ret = -ENOMEM;
287             goto fail;
288         }
289 
290         s->bat_offset = be64_to_cpu(dyndisk_header->table_offset);
291 
292         ret = bdrv_pread(bs->file->bs, s->bat_offset, s->pagetable,
293                          pagetable_size);
294         if (ret < 0) {
295             goto fail;
296         }
297 
298         s->free_data_block_offset =
299             ROUND_UP(s->bat_offset + pagetable_size, 512);
300 
301         for (i = 0; i < s->max_table_entries; i++) {
302             be32_to_cpus(&s->pagetable[i]);
303             if (s->pagetable[i] != 0xFFFFFFFF) {
304                 int64_t next = (512 * (int64_t) s->pagetable[i]) +
305                     s->bitmap_size + s->block_size;
306 
307                 if (next > s->free_data_block_offset) {
308                     s->free_data_block_offset = next;
309                 }
310             }
311         }
312 
313         if (s->free_data_block_offset > bdrv_getlength(bs->file->bs)) {
314             error_setg(errp, "block-vpc: free_data_block_offset points after "
315                              "the end of file. The image has been truncated.");
316             ret = -EINVAL;
317             goto fail;
318         }
319 
320         s->last_bitmap_offset = (int64_t) -1;
321 
322 #ifdef CACHE
323         s->pageentry_u8 = g_malloc(512);
324         s->pageentry_u32 = s->pageentry_u8;
325         s->pageentry_u16 = s->pageentry_u8;
326         s->last_pagetable = -1;
327 #endif
328     }
329 
330     qemu_co_mutex_init(&s->lock);
331 
332     /* Disable migration when VHD images are used */
333     error_setg(&s->migration_blocker, "The vpc format used by node '%s' "
334                "does not support live migration",
335                bdrv_get_device_or_node_name(bs));
336     migrate_add_blocker(s->migration_blocker);
337 
338     return 0;
339 
340 fail:
341     qemu_vfree(s->pagetable);
342 #ifdef CACHE
343     g_free(s->pageentry_u8);
344 #endif
345     return ret;
346 }
347 
348 static int vpc_reopen_prepare(BDRVReopenState *state,
349                               BlockReopenQueue *queue, Error **errp)
350 {
351     return 0;
352 }
353 
354 /*
355  * Returns the absolute byte offset of the given sector in the image file.
356  * If the sector is not allocated, -1 is returned instead.
357  *
358  * The parameter write must be 1 if the offset will be used for a write
359  * operation (the block bitmaps is updated then), 0 otherwise.
360  */
361 static inline int64_t get_sector_offset(BlockDriverState *bs,
362     int64_t sector_num, int write)
363 {
364     BDRVVPCState *s = bs->opaque;
365     uint64_t offset = sector_num * 512;
366     uint64_t bitmap_offset, block_offset;
367     uint32_t pagetable_index, pageentry_index;
368 
369     pagetable_index = offset / s->block_size;
370     pageentry_index = (offset % s->block_size) / 512;
371 
372     if (pagetable_index >= s->max_table_entries || s->pagetable[pagetable_index] == 0xffffffff)
373         return -1; // not allocated
374 
375     bitmap_offset = 512 * (uint64_t) s->pagetable[pagetable_index];
376     block_offset = bitmap_offset + s->bitmap_size + (512 * pageentry_index);
377 
378     // We must ensure that we don't write to any sectors which are marked as
379     // unused in the bitmap. We get away with setting all bits in the block
380     // bitmap each time we write to a new block. This might cause Virtual PC to
381     // miss sparse read optimization, but it's not a problem in terms of
382     // correctness.
383     if (write && (s->last_bitmap_offset != bitmap_offset)) {
384         uint8_t bitmap[s->bitmap_size];
385 
386         s->last_bitmap_offset = bitmap_offset;
387         memset(bitmap, 0xff, s->bitmap_size);
388         bdrv_pwrite_sync(bs->file->bs, bitmap_offset, bitmap, s->bitmap_size);
389     }
390 
391     return block_offset;
392 }
393 
394 /*
395  * Writes the footer to the end of the image file. This is needed when the
396  * file grows as it overwrites the old footer
397  *
398  * Returns 0 on success and < 0 on error
399  */
400 static int rewrite_footer(BlockDriverState* bs)
401 {
402     int ret;
403     BDRVVPCState *s = bs->opaque;
404     int64_t offset = s->free_data_block_offset;
405 
406     ret = bdrv_pwrite_sync(bs->file->bs, offset, s->footer_buf, HEADER_SIZE);
407     if (ret < 0)
408         return ret;
409 
410     return 0;
411 }
412 
413 /*
414  * Allocates a new block. This involves writing a new footer and updating
415  * the Block Allocation Table to use the space at the old end of the image
416  * file (overwriting the old footer)
417  *
418  * Returns the sectors' offset in the image file on success and < 0 on error
419  */
420 static int64_t alloc_block(BlockDriverState* bs, int64_t sector_num)
421 {
422     BDRVVPCState *s = bs->opaque;
423     int64_t bat_offset;
424     uint32_t index, bat_value;
425     int ret;
426     uint8_t bitmap[s->bitmap_size];
427 
428     // Check if sector_num is valid
429     if ((sector_num < 0) || (sector_num > bs->total_sectors))
430         return -1;
431 
432     // Write entry into in-memory BAT
433     index = (sector_num * 512) / s->block_size;
434     if (s->pagetable[index] != 0xFFFFFFFF)
435         return -1;
436 
437     s->pagetable[index] = s->free_data_block_offset / 512;
438 
439     // Initialize the block's bitmap
440     memset(bitmap, 0xff, s->bitmap_size);
441     ret = bdrv_pwrite_sync(bs->file->bs, s->free_data_block_offset, bitmap,
442         s->bitmap_size);
443     if (ret < 0) {
444         return ret;
445     }
446 
447     // Write new footer (the old one will be overwritten)
448     s->free_data_block_offset += s->block_size + s->bitmap_size;
449     ret = rewrite_footer(bs);
450     if (ret < 0)
451         goto fail;
452 
453     // Write BAT entry to disk
454     bat_offset = s->bat_offset + (4 * index);
455     bat_value = cpu_to_be32(s->pagetable[index]);
456     ret = bdrv_pwrite_sync(bs->file->bs, bat_offset, &bat_value, 4);
457     if (ret < 0)
458         goto fail;
459 
460     return get_sector_offset(bs, sector_num, 0);
461 
462 fail:
463     s->free_data_block_offset -= (s->block_size + s->bitmap_size);
464     return -1;
465 }
466 
467 static int vpc_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
468 {
469     BDRVVPCState *s = (BDRVVPCState *)bs->opaque;
470     VHDFooter *footer = (VHDFooter *) s->footer_buf;
471 
472     if (be32_to_cpu(footer->type) != VHD_FIXED) {
473         bdi->cluster_size = s->block_size;
474     }
475 
476     bdi->unallocated_blocks_are_zero = true;
477     return 0;
478 }
479 
480 static int vpc_read(BlockDriverState *bs, int64_t sector_num,
481                     uint8_t *buf, int nb_sectors)
482 {
483     BDRVVPCState *s = bs->opaque;
484     int ret;
485     int64_t offset;
486     int64_t sectors, sectors_per_block;
487     VHDFooter *footer = (VHDFooter *) s->footer_buf;
488 
489     if (be32_to_cpu(footer->type) == VHD_FIXED) {
490         return bdrv_read(bs->file->bs, sector_num, buf, nb_sectors);
491     }
492     while (nb_sectors > 0) {
493         offset = get_sector_offset(bs, sector_num, 0);
494 
495         sectors_per_block = s->block_size >> BDRV_SECTOR_BITS;
496         sectors = sectors_per_block - (sector_num % sectors_per_block);
497         if (sectors > nb_sectors) {
498             sectors = nb_sectors;
499         }
500 
501         if (offset == -1) {
502             memset(buf, 0, sectors * BDRV_SECTOR_SIZE);
503         } else {
504             ret = bdrv_pread(bs->file->bs, offset, buf,
505                 sectors * BDRV_SECTOR_SIZE);
506             if (ret != sectors * BDRV_SECTOR_SIZE) {
507                 return -1;
508             }
509         }
510 
511         nb_sectors -= sectors;
512         sector_num += sectors;
513         buf += sectors * BDRV_SECTOR_SIZE;
514     }
515     return 0;
516 }
517 
518 static coroutine_fn int vpc_co_read(BlockDriverState *bs, int64_t sector_num,
519                                     uint8_t *buf, int nb_sectors)
520 {
521     int ret;
522     BDRVVPCState *s = bs->opaque;
523     qemu_co_mutex_lock(&s->lock);
524     ret = vpc_read(bs, sector_num, buf, nb_sectors);
525     qemu_co_mutex_unlock(&s->lock);
526     return ret;
527 }
528 
529 static int vpc_write(BlockDriverState *bs, int64_t sector_num,
530     const uint8_t *buf, int nb_sectors)
531 {
532     BDRVVPCState *s = bs->opaque;
533     int64_t offset;
534     int64_t sectors, sectors_per_block;
535     int ret;
536     VHDFooter *footer =  (VHDFooter *) s->footer_buf;
537 
538     if (be32_to_cpu(footer->type) == VHD_FIXED) {
539         return bdrv_write(bs->file->bs, sector_num, buf, nb_sectors);
540     }
541     while (nb_sectors > 0) {
542         offset = get_sector_offset(bs, sector_num, 1);
543 
544         sectors_per_block = s->block_size >> BDRV_SECTOR_BITS;
545         sectors = sectors_per_block - (sector_num % sectors_per_block);
546         if (sectors > nb_sectors) {
547             sectors = nb_sectors;
548         }
549 
550         if (offset == -1) {
551             offset = alloc_block(bs, sector_num);
552             if (offset < 0)
553                 return -1;
554         }
555 
556         ret = bdrv_pwrite(bs->file->bs, offset, buf,
557                           sectors * BDRV_SECTOR_SIZE);
558         if (ret != sectors * BDRV_SECTOR_SIZE) {
559             return -1;
560         }
561 
562         nb_sectors -= sectors;
563         sector_num += sectors;
564         buf += sectors * BDRV_SECTOR_SIZE;
565     }
566 
567     return 0;
568 }
569 
570 static coroutine_fn int vpc_co_write(BlockDriverState *bs, int64_t sector_num,
571                                      const uint8_t *buf, int nb_sectors)
572 {
573     int ret;
574     BDRVVPCState *s = bs->opaque;
575     qemu_co_mutex_lock(&s->lock);
576     ret = vpc_write(bs, sector_num, buf, nb_sectors);
577     qemu_co_mutex_unlock(&s->lock);
578     return ret;
579 }
580 
581 static int64_t coroutine_fn vpc_co_get_block_status(BlockDriverState *bs,
582         int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file)
583 {
584     BDRVVPCState *s = bs->opaque;
585     VHDFooter *footer = (VHDFooter*) s->footer_buf;
586     int64_t start, offset;
587     bool allocated;
588     int n;
589 
590     if (be32_to_cpu(footer->type) == VHD_FIXED) {
591         *pnum = nb_sectors;
592         *file = bs->file->bs;
593         return BDRV_BLOCK_RAW | BDRV_BLOCK_OFFSET_VALID | BDRV_BLOCK_DATA |
594                (sector_num << BDRV_SECTOR_BITS);
595     }
596 
597     offset = get_sector_offset(bs, sector_num, 0);
598     start = offset;
599     allocated = (offset != -1);
600     *pnum = 0;
601 
602     do {
603         /* All sectors in a block are contiguous (without using the bitmap) */
604         n = ROUND_UP(sector_num + 1, s->block_size / BDRV_SECTOR_SIZE)
605           - sector_num;
606         n = MIN(n, nb_sectors);
607 
608         *pnum += n;
609         sector_num += n;
610         nb_sectors -= n;
611         /* *pnum can't be greater than one block for allocated
612          * sectors since there is always a bitmap in between. */
613         if (allocated) {
614             *file = bs->file->bs;
615             return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | start;
616         }
617         if (nb_sectors == 0) {
618             break;
619         }
620         offset = get_sector_offset(bs, sector_num, 0);
621     } while (offset == -1);
622 
623     return 0;
624 }
625 
626 /*
627  * Calculates the number of cylinders, heads and sectors per cylinder
628  * based on a given number of sectors. This is the algorithm described
629  * in the VHD specification.
630  *
631  * Note that the geometry doesn't always exactly match total_sectors but
632  * may round it down.
633  *
634  * Returns 0 on success, -EFBIG if the size is larger than ~2 TB. Override
635  * the hardware EIDE and ATA-2 limit of 16 heads (max disk size of 127 GB)
636  * and instead allow up to 255 heads.
637  */
638 static int calculate_geometry(int64_t total_sectors, uint16_t* cyls,
639     uint8_t* heads, uint8_t* secs_per_cyl)
640 {
641     uint32_t cyls_times_heads;
642 
643     total_sectors = MIN(total_sectors, VHD_MAX_GEOMETRY);
644 
645     if (total_sectors >= 65535LL * 16 * 63) {
646         *secs_per_cyl = 255;
647         *heads = 16;
648         cyls_times_heads = total_sectors / *secs_per_cyl;
649     } else {
650         *secs_per_cyl = 17;
651         cyls_times_heads = total_sectors / *secs_per_cyl;
652         *heads = (cyls_times_heads + 1023) / 1024;
653 
654         if (*heads < 4) {
655             *heads = 4;
656         }
657 
658         if (cyls_times_heads >= (*heads * 1024) || *heads > 16) {
659             *secs_per_cyl = 31;
660             *heads = 16;
661             cyls_times_heads = total_sectors / *secs_per_cyl;
662         }
663 
664         if (cyls_times_heads >= (*heads * 1024)) {
665             *secs_per_cyl = 63;
666             *heads = 16;
667             cyls_times_heads = total_sectors / *secs_per_cyl;
668         }
669     }
670 
671     *cyls = cyls_times_heads / *heads;
672 
673     return 0;
674 }
675 
676 static int create_dynamic_disk(BlockDriverState *bs, uint8_t *buf,
677                                int64_t total_sectors)
678 {
679     VHDDynDiskHeader *dyndisk_header =
680         (VHDDynDiskHeader *) buf;
681     size_t block_size, num_bat_entries;
682     int i;
683     int ret;
684     int64_t offset = 0;
685 
686     // Write the footer (twice: at the beginning and at the end)
687     block_size = 0x200000;
688     num_bat_entries = (total_sectors + block_size / 512) / (block_size / 512);
689 
690     ret = bdrv_pwrite_sync(bs, offset, buf, HEADER_SIZE);
691     if (ret) {
692         goto fail;
693     }
694 
695     offset = 1536 + ((num_bat_entries * 4 + 511) & ~511);
696     ret = bdrv_pwrite_sync(bs, offset, buf, HEADER_SIZE);
697     if (ret < 0) {
698         goto fail;
699     }
700 
701     // Write the initial BAT
702     offset = 3 * 512;
703 
704     memset(buf, 0xFF, 512);
705     for (i = 0; i < (num_bat_entries * 4 + 511) / 512; i++) {
706         ret = bdrv_pwrite_sync(bs, offset, buf, 512);
707         if (ret < 0) {
708             goto fail;
709         }
710         offset += 512;
711     }
712 
713     // Prepare the Dynamic Disk Header
714     memset(buf, 0, 1024);
715 
716     memcpy(dyndisk_header->magic, "cxsparse", 8);
717 
718     /*
719      * Note: The spec is actually wrong here for data_offset, it says
720      * 0xFFFFFFFF, but MS tools expect all 64 bits to be set.
721      */
722     dyndisk_header->data_offset = cpu_to_be64(0xFFFFFFFFFFFFFFFFULL);
723     dyndisk_header->table_offset = cpu_to_be64(3 * 512);
724     dyndisk_header->version = cpu_to_be32(0x00010000);
725     dyndisk_header->block_size = cpu_to_be32(block_size);
726     dyndisk_header->max_table_entries = cpu_to_be32(num_bat_entries);
727 
728     dyndisk_header->checksum = cpu_to_be32(vpc_checksum(buf, 1024));
729 
730     // Write the header
731     offset = 512;
732 
733     ret = bdrv_pwrite_sync(bs, offset, buf, 1024);
734     if (ret < 0) {
735         goto fail;
736     }
737 
738  fail:
739     return ret;
740 }
741 
742 static int create_fixed_disk(BlockDriverState *bs, uint8_t *buf,
743                              int64_t total_size)
744 {
745     int ret;
746 
747     /* Add footer to total size */
748     total_size += HEADER_SIZE;
749 
750     ret = bdrv_truncate(bs, total_size);
751     if (ret < 0) {
752         return ret;
753     }
754 
755     ret = bdrv_pwrite_sync(bs, total_size - HEADER_SIZE, buf, HEADER_SIZE);
756     if (ret < 0) {
757         return ret;
758     }
759 
760     return ret;
761 }
762 
763 static int vpc_create(const char *filename, QemuOpts *opts, Error **errp)
764 {
765     uint8_t buf[1024];
766     VHDFooter *footer = (VHDFooter *) buf;
767     char *disk_type_param;
768     int i;
769     uint16_t cyls = 0;
770     uint8_t heads = 0;
771     uint8_t secs_per_cyl = 0;
772     int64_t total_sectors;
773     int64_t total_size;
774     int disk_type;
775     int ret = -EIO;
776     Error *local_err = NULL;
777     BlockDriverState *bs = NULL;
778 
779     /* Read out options */
780     total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
781                           BDRV_SECTOR_SIZE);
782     disk_type_param = qemu_opt_get_del(opts, BLOCK_OPT_SUBFMT);
783     if (disk_type_param) {
784         if (!strcmp(disk_type_param, "dynamic")) {
785             disk_type = VHD_DYNAMIC;
786         } else if (!strcmp(disk_type_param, "fixed")) {
787             disk_type = VHD_FIXED;
788         } else {
789             ret = -EINVAL;
790             goto out;
791         }
792     } else {
793         disk_type = VHD_DYNAMIC;
794     }
795 
796     ret = bdrv_create_file(filename, opts, &local_err);
797     if (ret < 0) {
798         error_propagate(errp, local_err);
799         goto out;
800     }
801     ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
802                     &local_err);
803     if (ret < 0) {
804         error_propagate(errp, local_err);
805         goto out;
806     }
807 
808     /*
809      * Calculate matching total_size and geometry. Increase the number of
810      * sectors requested until we get enough (or fail). This ensures that
811      * qemu-img convert doesn't truncate images, but rather rounds up.
812      *
813      * If the image size can't be represented by a spec conform CHS geometry,
814      * we set the geometry to 65535 x 16 x 255 (CxHxS) sectors and use
815      * the image size from the VHD footer to calculate total_sectors.
816      */
817     total_sectors = MIN(VHD_MAX_GEOMETRY, total_size / BDRV_SECTOR_SIZE);
818     for (i = 0; total_sectors > (int64_t)cyls * heads * secs_per_cyl; i++) {
819         calculate_geometry(total_sectors + i, &cyls, &heads, &secs_per_cyl);
820     }
821 
822     if ((int64_t)cyls * heads * secs_per_cyl == VHD_MAX_GEOMETRY) {
823         total_sectors = total_size / BDRV_SECTOR_SIZE;
824         /* Allow a maximum disk size of approximately 2 TB */
825         if (total_sectors > VHD_MAX_SECTORS) {
826             ret = -EFBIG;
827             goto out;
828         }
829     } else {
830         total_sectors = (int64_t)cyls * heads * secs_per_cyl;
831         total_size = total_sectors * BDRV_SECTOR_SIZE;
832     }
833 
834     /* Prepare the Hard Disk Footer */
835     memset(buf, 0, 1024);
836 
837     memcpy(footer->creator, "conectix", 8);
838     /* TODO Check if "qemu" creator_app is ok for VPC */
839     memcpy(footer->creator_app, "qemu", 4);
840     memcpy(footer->creator_os, "Wi2k", 4);
841 
842     footer->features = cpu_to_be32(0x02);
843     footer->version = cpu_to_be32(0x00010000);
844     if (disk_type == VHD_DYNAMIC) {
845         footer->data_offset = cpu_to_be64(HEADER_SIZE);
846     } else {
847         footer->data_offset = cpu_to_be64(0xFFFFFFFFFFFFFFFFULL);
848     }
849     footer->timestamp = cpu_to_be32(time(NULL) - VHD_TIMESTAMP_BASE);
850 
851     /* Version of Virtual PC 2007 */
852     footer->major = cpu_to_be16(0x0005);
853     footer->minor = cpu_to_be16(0x0003);
854     footer->orig_size = cpu_to_be64(total_size);
855     footer->current_size = cpu_to_be64(total_size);
856     footer->cyls = cpu_to_be16(cyls);
857     footer->heads = heads;
858     footer->secs_per_cyl = secs_per_cyl;
859 
860     footer->type = cpu_to_be32(disk_type);
861 
862 #if defined(CONFIG_UUID)
863     uuid_generate(footer->uuid);
864 #endif
865 
866     footer->checksum = cpu_to_be32(vpc_checksum(buf, HEADER_SIZE));
867 
868     if (disk_type == VHD_DYNAMIC) {
869         ret = create_dynamic_disk(bs, buf, total_sectors);
870     } else {
871         ret = create_fixed_disk(bs, buf, total_size);
872     }
873 
874 out:
875     bdrv_unref(bs);
876     g_free(disk_type_param);
877     return ret;
878 }
879 
880 static int vpc_has_zero_init(BlockDriverState *bs)
881 {
882     BDRVVPCState *s = bs->opaque;
883     VHDFooter *footer =  (VHDFooter *) s->footer_buf;
884 
885     if (be32_to_cpu(footer->type) == VHD_FIXED) {
886         return bdrv_has_zero_init(bs->file->bs);
887     } else {
888         return 1;
889     }
890 }
891 
892 static void vpc_close(BlockDriverState *bs)
893 {
894     BDRVVPCState *s = bs->opaque;
895     qemu_vfree(s->pagetable);
896 #ifdef CACHE
897     g_free(s->pageentry_u8);
898 #endif
899 
900     migrate_del_blocker(s->migration_blocker);
901     error_free(s->migration_blocker);
902 }
903 
904 static QemuOptsList vpc_create_opts = {
905     .name = "vpc-create-opts",
906     .head = QTAILQ_HEAD_INITIALIZER(vpc_create_opts.head),
907     .desc = {
908         {
909             .name = BLOCK_OPT_SIZE,
910             .type = QEMU_OPT_SIZE,
911             .help = "Virtual disk size"
912         },
913         {
914             .name = BLOCK_OPT_SUBFMT,
915             .type = QEMU_OPT_STRING,
916             .help =
917                 "Type of virtual hard disk format. Supported formats are "
918                 "{dynamic (default) | fixed} "
919         },
920         { /* end of list */ }
921     }
922 };
923 
924 static BlockDriver bdrv_vpc = {
925     .format_name    = "vpc",
926     .instance_size  = sizeof(BDRVVPCState),
927 
928     .bdrv_probe             = vpc_probe,
929     .bdrv_open              = vpc_open,
930     .bdrv_close             = vpc_close,
931     .bdrv_reopen_prepare    = vpc_reopen_prepare,
932     .bdrv_create            = vpc_create,
933 
934     .bdrv_read                  = vpc_co_read,
935     .bdrv_write                 = vpc_co_write,
936     .bdrv_co_get_block_status   = vpc_co_get_block_status,
937 
938     .bdrv_get_info          = vpc_get_info,
939 
940     .create_opts            = &vpc_create_opts,
941     .bdrv_has_zero_init     = vpc_has_zero_init,
942 };
943 
944 static void bdrv_vpc_init(void)
945 {
946     bdrv_register(&bdrv_vpc);
947 }
948 
949 block_init(bdrv_vpc_init);
950