xref: /openbmc/qemu/block/vpc.c (revision d341d9f3)
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)
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         return BDRV_BLOCK_RAW | BDRV_BLOCK_OFFSET_VALID | BDRV_BLOCK_DATA |
593                (sector_num << BDRV_SECTOR_BITS);
594     }
595 
596     offset = get_sector_offset(bs, sector_num, 0);
597     start = offset;
598     allocated = (offset != -1);
599     *pnum = 0;
600 
601     do {
602         /* All sectors in a block are contiguous (without using the bitmap) */
603         n = ROUND_UP(sector_num + 1, s->block_size / BDRV_SECTOR_SIZE)
604           - sector_num;
605         n = MIN(n, nb_sectors);
606 
607         *pnum += n;
608         sector_num += n;
609         nb_sectors -= n;
610         /* *pnum can't be greater than one block for allocated
611          * sectors since there is always a bitmap in between. */
612         if (allocated) {
613             return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | start;
614         }
615         if (nb_sectors == 0) {
616             break;
617         }
618         offset = get_sector_offset(bs, sector_num, 0);
619     } while (offset == -1);
620 
621     return 0;
622 }
623 
624 /*
625  * Calculates the number of cylinders, heads and sectors per cylinder
626  * based on a given number of sectors. This is the algorithm described
627  * in the VHD specification.
628  *
629  * Note that the geometry doesn't always exactly match total_sectors but
630  * may round it down.
631  *
632  * Returns 0 on success, -EFBIG if the size is larger than ~2 TB. Override
633  * the hardware EIDE and ATA-2 limit of 16 heads (max disk size of 127 GB)
634  * and instead allow up to 255 heads.
635  */
636 static int calculate_geometry(int64_t total_sectors, uint16_t* cyls,
637     uint8_t* heads, uint8_t* secs_per_cyl)
638 {
639     uint32_t cyls_times_heads;
640 
641     total_sectors = MIN(total_sectors, VHD_MAX_GEOMETRY);
642 
643     if (total_sectors >= 65535LL * 16 * 63) {
644         *secs_per_cyl = 255;
645         *heads = 16;
646         cyls_times_heads = total_sectors / *secs_per_cyl;
647     } else {
648         *secs_per_cyl = 17;
649         cyls_times_heads = total_sectors / *secs_per_cyl;
650         *heads = (cyls_times_heads + 1023) / 1024;
651 
652         if (*heads < 4) {
653             *heads = 4;
654         }
655 
656         if (cyls_times_heads >= (*heads * 1024) || *heads > 16) {
657             *secs_per_cyl = 31;
658             *heads = 16;
659             cyls_times_heads = total_sectors / *secs_per_cyl;
660         }
661 
662         if (cyls_times_heads >= (*heads * 1024)) {
663             *secs_per_cyl = 63;
664             *heads = 16;
665             cyls_times_heads = total_sectors / *secs_per_cyl;
666         }
667     }
668 
669     *cyls = cyls_times_heads / *heads;
670 
671     return 0;
672 }
673 
674 static int create_dynamic_disk(BlockDriverState *bs, uint8_t *buf,
675                                int64_t total_sectors)
676 {
677     VHDDynDiskHeader *dyndisk_header =
678         (VHDDynDiskHeader *) buf;
679     size_t block_size, num_bat_entries;
680     int i;
681     int ret;
682     int64_t offset = 0;
683 
684     // Write the footer (twice: at the beginning and at the end)
685     block_size = 0x200000;
686     num_bat_entries = (total_sectors + block_size / 512) / (block_size / 512);
687 
688     ret = bdrv_pwrite_sync(bs, offset, buf, HEADER_SIZE);
689     if (ret) {
690         goto fail;
691     }
692 
693     offset = 1536 + ((num_bat_entries * 4 + 511) & ~511);
694     ret = bdrv_pwrite_sync(bs, offset, buf, HEADER_SIZE);
695     if (ret < 0) {
696         goto fail;
697     }
698 
699     // Write the initial BAT
700     offset = 3 * 512;
701 
702     memset(buf, 0xFF, 512);
703     for (i = 0; i < (num_bat_entries * 4 + 511) / 512; i++) {
704         ret = bdrv_pwrite_sync(bs, offset, buf, 512);
705         if (ret < 0) {
706             goto fail;
707         }
708         offset += 512;
709     }
710 
711     // Prepare the Dynamic Disk Header
712     memset(buf, 0, 1024);
713 
714     memcpy(dyndisk_header->magic, "cxsparse", 8);
715 
716     /*
717      * Note: The spec is actually wrong here for data_offset, it says
718      * 0xFFFFFFFF, but MS tools expect all 64 bits to be set.
719      */
720     dyndisk_header->data_offset = cpu_to_be64(0xFFFFFFFFFFFFFFFFULL);
721     dyndisk_header->table_offset = cpu_to_be64(3 * 512);
722     dyndisk_header->version = cpu_to_be32(0x00010000);
723     dyndisk_header->block_size = cpu_to_be32(block_size);
724     dyndisk_header->max_table_entries = cpu_to_be32(num_bat_entries);
725 
726     dyndisk_header->checksum = cpu_to_be32(vpc_checksum(buf, 1024));
727 
728     // Write the header
729     offset = 512;
730 
731     ret = bdrv_pwrite_sync(bs, offset, buf, 1024);
732     if (ret < 0) {
733         goto fail;
734     }
735 
736  fail:
737     return ret;
738 }
739 
740 static int create_fixed_disk(BlockDriverState *bs, uint8_t *buf,
741                              int64_t total_size)
742 {
743     int ret;
744 
745     /* Add footer to total size */
746     total_size += HEADER_SIZE;
747 
748     ret = bdrv_truncate(bs, total_size);
749     if (ret < 0) {
750         return ret;
751     }
752 
753     ret = bdrv_pwrite_sync(bs, total_size - HEADER_SIZE, buf, HEADER_SIZE);
754     if (ret < 0) {
755         return ret;
756     }
757 
758     return ret;
759 }
760 
761 static int vpc_create(const char *filename, QemuOpts *opts, Error **errp)
762 {
763     uint8_t buf[1024];
764     VHDFooter *footer = (VHDFooter *) buf;
765     char *disk_type_param;
766     int i;
767     uint16_t cyls = 0;
768     uint8_t heads = 0;
769     uint8_t secs_per_cyl = 0;
770     int64_t total_sectors;
771     int64_t total_size;
772     int disk_type;
773     int ret = -EIO;
774     Error *local_err = NULL;
775     BlockDriverState *bs = NULL;
776 
777     /* Read out options */
778     total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
779                           BDRV_SECTOR_SIZE);
780     disk_type_param = qemu_opt_get_del(opts, BLOCK_OPT_SUBFMT);
781     if (disk_type_param) {
782         if (!strcmp(disk_type_param, "dynamic")) {
783             disk_type = VHD_DYNAMIC;
784         } else if (!strcmp(disk_type_param, "fixed")) {
785             disk_type = VHD_FIXED;
786         } else {
787             ret = -EINVAL;
788             goto out;
789         }
790     } else {
791         disk_type = VHD_DYNAMIC;
792     }
793 
794     ret = bdrv_create_file(filename, opts, &local_err);
795     if (ret < 0) {
796         error_propagate(errp, local_err);
797         goto out;
798     }
799     ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
800                     &local_err);
801     if (ret < 0) {
802         error_propagate(errp, local_err);
803         goto out;
804     }
805 
806     /*
807      * Calculate matching total_size and geometry. Increase the number of
808      * sectors requested until we get enough (or fail). This ensures that
809      * qemu-img convert doesn't truncate images, but rather rounds up.
810      *
811      * If the image size can't be represented by a spec conform CHS geometry,
812      * we set the geometry to 65535 x 16 x 255 (CxHxS) sectors and use
813      * the image size from the VHD footer to calculate total_sectors.
814      */
815     total_sectors = MIN(VHD_MAX_GEOMETRY, total_size / BDRV_SECTOR_SIZE);
816     for (i = 0; total_sectors > (int64_t)cyls * heads * secs_per_cyl; i++) {
817         calculate_geometry(total_sectors + i, &cyls, &heads, &secs_per_cyl);
818     }
819 
820     if ((int64_t)cyls * heads * secs_per_cyl == VHD_MAX_GEOMETRY) {
821         total_sectors = total_size / BDRV_SECTOR_SIZE;
822         /* Allow a maximum disk size of approximately 2 TB */
823         if (total_sectors > VHD_MAX_SECTORS) {
824             ret = -EFBIG;
825             goto out;
826         }
827     } else {
828         total_sectors = (int64_t)cyls * heads * secs_per_cyl;
829         total_size = total_sectors * BDRV_SECTOR_SIZE;
830     }
831 
832     /* Prepare the Hard Disk Footer */
833     memset(buf, 0, 1024);
834 
835     memcpy(footer->creator, "conectix", 8);
836     /* TODO Check if "qemu" creator_app is ok for VPC */
837     memcpy(footer->creator_app, "qemu", 4);
838     memcpy(footer->creator_os, "Wi2k", 4);
839 
840     footer->features = cpu_to_be32(0x02);
841     footer->version = cpu_to_be32(0x00010000);
842     if (disk_type == VHD_DYNAMIC) {
843         footer->data_offset = cpu_to_be64(HEADER_SIZE);
844     } else {
845         footer->data_offset = cpu_to_be64(0xFFFFFFFFFFFFFFFFULL);
846     }
847     footer->timestamp = cpu_to_be32(time(NULL) - VHD_TIMESTAMP_BASE);
848 
849     /* Version of Virtual PC 2007 */
850     footer->major = cpu_to_be16(0x0005);
851     footer->minor = cpu_to_be16(0x0003);
852     footer->orig_size = cpu_to_be64(total_size);
853     footer->current_size = cpu_to_be64(total_size);
854     footer->cyls = cpu_to_be16(cyls);
855     footer->heads = heads;
856     footer->secs_per_cyl = secs_per_cyl;
857 
858     footer->type = cpu_to_be32(disk_type);
859 
860 #if defined(CONFIG_UUID)
861     uuid_generate(footer->uuid);
862 #endif
863 
864     footer->checksum = cpu_to_be32(vpc_checksum(buf, HEADER_SIZE));
865 
866     if (disk_type == VHD_DYNAMIC) {
867         ret = create_dynamic_disk(bs, buf, total_sectors);
868     } else {
869         ret = create_fixed_disk(bs, buf, total_size);
870     }
871 
872 out:
873     bdrv_unref(bs);
874     g_free(disk_type_param);
875     return ret;
876 }
877 
878 static int vpc_has_zero_init(BlockDriverState *bs)
879 {
880     BDRVVPCState *s = bs->opaque;
881     VHDFooter *footer =  (VHDFooter *) s->footer_buf;
882 
883     if (be32_to_cpu(footer->type) == VHD_FIXED) {
884         return bdrv_has_zero_init(bs->file->bs);
885     } else {
886         return 1;
887     }
888 }
889 
890 static void vpc_close(BlockDriverState *bs)
891 {
892     BDRVVPCState *s = bs->opaque;
893     qemu_vfree(s->pagetable);
894 #ifdef CACHE
895     g_free(s->pageentry_u8);
896 #endif
897 
898     migrate_del_blocker(s->migration_blocker);
899     error_free(s->migration_blocker);
900 }
901 
902 static QemuOptsList vpc_create_opts = {
903     .name = "vpc-create-opts",
904     .head = QTAILQ_HEAD_INITIALIZER(vpc_create_opts.head),
905     .desc = {
906         {
907             .name = BLOCK_OPT_SIZE,
908             .type = QEMU_OPT_SIZE,
909             .help = "Virtual disk size"
910         },
911         {
912             .name = BLOCK_OPT_SUBFMT,
913             .type = QEMU_OPT_STRING,
914             .help =
915                 "Type of virtual hard disk format. Supported formats are "
916                 "{dynamic (default) | fixed} "
917         },
918         { /* end of list */ }
919     }
920 };
921 
922 static BlockDriver bdrv_vpc = {
923     .format_name    = "vpc",
924     .instance_size  = sizeof(BDRVVPCState),
925 
926     .bdrv_probe             = vpc_probe,
927     .bdrv_open              = vpc_open,
928     .bdrv_close             = vpc_close,
929     .bdrv_reopen_prepare    = vpc_reopen_prepare,
930     .bdrv_create            = vpc_create,
931 
932     .bdrv_read                  = vpc_co_read,
933     .bdrv_write                 = vpc_co_write,
934     .bdrv_co_get_block_status   = vpc_co_get_block_status,
935 
936     .bdrv_get_info          = vpc_get_info,
937 
938     .create_opts            = &vpc_create_opts,
939     .bdrv_has_zero_init     = vpc_has_zero_init,
940 };
941 
942 static void bdrv_vpc_init(void)
943 {
944     bdrv_register(&bdrv_vpc);
945 }
946 
947 block_init(bdrv_vpc_init);
948