2 * Block driver for Parallels disk image format
4 * Copyright (c) 2007 Alex Beregszaszi
5 * Copyright (c) 2015 Denis V. Lunev <den@openvz.org>
7 * This code was originally based on comparing different disk images created
8 * by Parallels. Currently it is based on opened OpenVZ sources
10 * http://git.openvz.org/?p=ploop;a=summary
12 * Permission is hereby granted, free of charge, to any person obtaining a copy
13 * of this software and associated documentation files (the "Software"), to deal
14 * in the Software without restriction, including without limitation the rights
15 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 * copies of the Software, and to permit persons to whom the Software is
17 * furnished to do so, subject to the following conditions:
19 * The above copyright notice and this permission notice shall be included in
20 * all copies or substantial portions of the Software.
22 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
25 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
31 #include "qemu/osdep.h"
32 #include "qemu/error-report.h"
33 #include "qapi/error.h"
34 #include "block/block_int.h"
35 #include "block/qdict.h"
36 #include "sysemu/block-backend.h"
37 #include "qemu/module.h"
38 #include "qemu/option.h"
39 #include "qapi/qmp/qdict.h"
40 #include "qapi/qobject-input-visitor.h"
41 #include "qapi/qapi-visit-block-core.h"
42 #include "qemu/bswap.h"
43 #include "qemu/bitmap.h"
44 #include "qemu/memalign.h"
45 #include "migration/blocker.h"
46 #include "parallels.h"
48 /**************************************************************/
50 #define HEADER_MAGIC "WithoutFreeSpace"
51 #define HEADER_MAGIC2 "WithouFreSpacExt"
52 #define HEADER_VERSION 2
53 #define HEADER_INUSE_MAGIC (0x746F6E59)
54 #define MAX_PARALLELS_IMAGE_FACTOR (1ull << 32)
56 static QEnumLookup prealloc_mode_lookup = {
57 .array = (const char *const[]) {
61 .size = PRL_PREALLOC_MODE__MAX
64 #define PARALLELS_OPT_PREALLOC_MODE "prealloc-mode"
65 #define PARALLELS_OPT_PREALLOC_SIZE "prealloc-size"
67 static QemuOptsList parallels_runtime_opts = {
69 .head = QTAILQ_HEAD_INITIALIZER(parallels_runtime_opts.head),
72 .name = PARALLELS_OPT_PREALLOC_SIZE,
73 .type = QEMU_OPT_SIZE,
74 .help = "Preallocation size on image expansion",
75 .def_value_str = "128M",
78 .name = PARALLELS_OPT_PREALLOC_MODE,
79 .type = QEMU_OPT_STRING,
80 .help = "Preallocation mode on image expansion "
81 "(allowed values: falloc, truncate)",
82 .def_value_str = "falloc",
84 { /* end of list */ },
88 static QemuOptsList parallels_create_opts = {
89 .name = "parallels-create-opts",
90 .head = QTAILQ_HEAD_INITIALIZER(parallels_create_opts.head),
93 .name = BLOCK_OPT_SIZE,
94 .type = QEMU_OPT_SIZE,
95 .help = "Virtual disk size",
98 .name = BLOCK_OPT_CLUSTER_SIZE,
99 .type = QEMU_OPT_SIZE,
100 .help = "Parallels image cluster size",
101 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE),
103 { /* end of list */ }
108 static int64_t bat2sect(BDRVParallelsState *s, uint32_t idx)
110 return (uint64_t)le32_to_cpu(s->bat_bitmap[idx]) * s->off_multiplier;
113 static uint32_t bat_entry_off(uint32_t idx)
115 return sizeof(ParallelsHeader) + sizeof(uint32_t) * idx;
118 static int64_t seek_to_sector(BDRVParallelsState *s, int64_t sector_num)
120 uint32_t index, offset;
122 index = sector_num / s->tracks;
123 offset = sector_num % s->tracks;
126 if ((index >= s->bat_size) || (s->bat_bitmap[index] == 0)) {
129 return bat2sect(s, index) + offset;
132 static int cluster_remainder(BDRVParallelsState *s, int64_t sector_num,
135 int ret = s->tracks - sector_num % s->tracks;
136 return MIN(nb_sectors, ret);
139 static uint32_t host_cluster_index(BDRVParallelsState *s, int64_t off)
141 off -= s->data_start << BDRV_SECTOR_BITS;
142 return off / s->cluster_size;
145 static int64_t block_status(BDRVParallelsState *s, int64_t sector_num,
146 int nb_sectors, int *pnum)
148 int64_t start_off = -2, prev_end_off = -2;
151 while (nb_sectors > 0 || start_off == -2) {
152 int64_t offset = seek_to_sector(s, sector_num);
155 if (start_off == -2) {
157 prev_end_off = offset;
158 } else if (offset != prev_end_off) {
162 to_end = cluster_remainder(s, sector_num, nb_sectors);
163 nb_sectors -= to_end;
164 sector_num += to_end;
168 prev_end_off += to_end;
174 static void parallels_set_bat_entry(BDRVParallelsState *s,
175 uint32_t index, uint32_t offset)
177 s->bat_bitmap[index] = cpu_to_le32(offset);
178 bitmap_set(s->bat_dirty_bmap, bat_entry_off(index) / s->bat_dirty_block, 1);
181 static int mark_used(BlockDriverState *bs, unsigned long *bitmap,
182 uint32_t bitmap_size, int64_t off, uint32_t count)
184 BDRVParallelsState *s = bs->opaque;
185 uint32_t cluster_index = host_cluster_index(s, off);
186 unsigned long next_used;
187 if (cluster_index + count > bitmap_size) {
190 next_used = find_next_bit(bitmap, bitmap_size, cluster_index);
191 if (next_used < cluster_index + count) {
194 bitmap_set(bitmap, cluster_index, count);
199 * Collect used bitmap. The image can contain errors, we should fill the
200 * bitmap anyway, as much as we can. This information will be used for
203 static int parallels_fill_used_bitmap(BlockDriverState *bs)
205 BDRVParallelsState *s = bs->opaque;
206 int64_t payload_bytes;
210 payload_bytes = bdrv_getlength(bs->file->bs);
211 if (payload_bytes < 0) {
212 return payload_bytes;
214 payload_bytes -= s->data_start * BDRV_SECTOR_SIZE;
215 if (payload_bytes < 0) {
219 s->used_bmap_size = DIV_ROUND_UP(payload_bytes, s->cluster_size);
220 if (s->used_bmap_size == 0) {
223 s->used_bmap = bitmap_try_new(s->used_bmap_size);
224 if (s->used_bmap == NULL) {
228 for (i = 0; i < s->bat_size; i++) {
230 int64_t host_off = bat2sect(s, i) << BDRV_SECTOR_BITS;
235 err2 = mark_used(bs, s->used_bmap, s->used_bmap_size, host_off, 1);
236 if (err2 < 0 && err == 0) {
243 static void parallels_free_used_bitmap(BlockDriverState *bs)
245 BDRVParallelsState *s = bs->opaque;
246 s->used_bmap_size = 0;
247 g_free(s->used_bmap);
250 static int64_t coroutine_fn GRAPH_RDLOCK
251 allocate_clusters(BlockDriverState *bs, int64_t sector_num,
252 int nb_sectors, int *pnum)
255 BDRVParallelsState *s = bs->opaque;
256 int64_t i, pos, idx, to_allocate, first_free, host_off;
258 pos = block_status(s, sector_num, nb_sectors, pnum);
263 idx = sector_num / s->tracks;
264 to_allocate = DIV_ROUND_UP(sector_num + *pnum, s->tracks) - idx;
267 * This function is called only by parallels_co_writev(), which will never
268 * pass a sector_num at or beyond the end of the image (because the block
269 * layer never passes such a sector_num to that function). Therefore, idx
270 * is always below s->bat_size.
271 * block_status() will limit *pnum so that sector_num + *pnum will not
272 * exceed the image end. Therefore, idx + to_allocate cannot exceed
274 * Note that s->bat_size is an unsigned int, therefore idx + to_allocate
275 * will always fit into a uint32_t.
277 assert(idx < s->bat_size && idx + to_allocate <= s->bat_size);
279 first_free = find_first_zero_bit(s->used_bmap, s->used_bmap_size);
280 if (first_free == s->used_bmap_size) {
281 uint32_t new_usedsize;
282 int64_t bytes = to_allocate * s->cluster_size;
283 bytes += s->prealloc_size * BDRV_SECTOR_SIZE;
285 host_off = s->data_end * BDRV_SECTOR_SIZE;
288 * We require the expanded size to read back as zero. If the
289 * user permitted truncation, we try that; but if it fails, we
290 * force the safer-but-slower fallocate.
292 if (s->prealloc_mode == PRL_PREALLOC_MODE_TRUNCATE) {
293 ret = bdrv_co_truncate(bs->file, host_off + bytes,
294 false, PREALLOC_MODE_OFF,
295 BDRV_REQ_ZERO_WRITE, NULL);
296 if (ret == -ENOTSUP) {
297 s->prealloc_mode = PRL_PREALLOC_MODE_FALLOCATE;
300 if (s->prealloc_mode == PRL_PREALLOC_MODE_FALLOCATE) {
301 ret = bdrv_co_pwrite_zeroes(bs->file, host_off, bytes, 0);
307 new_usedsize = s->used_bmap_size + bytes / s->cluster_size;
308 s->used_bmap = bitmap_zero_extend(s->used_bmap, s->used_bmap_size,
310 s->used_bmap_size = new_usedsize;
313 next_used = find_next_bit(s->used_bmap, s->used_bmap_size, first_free);
315 /* Not enough continuous clusters in the middle, adjust the size */
316 if (next_used - first_free < to_allocate) {
317 to_allocate = next_used - first_free;
318 *pnum = (idx + to_allocate) * s->tracks - sector_num;
321 host_off = s->data_start * BDRV_SECTOR_SIZE;
322 host_off += first_free * s->cluster_size;
325 * No need to preallocate if we are using tail area from the above
326 * branch. In the other case we are likely re-using hole. Preallocate
327 * the space if required by the prealloc_mode.
329 if (s->prealloc_mode == PRL_PREALLOC_MODE_FALLOCATE &&
330 host_off < s->data_end * BDRV_SECTOR_SIZE) {
331 ret = bdrv_co_pwrite_zeroes(bs->file, host_off,
332 s->cluster_size * to_allocate, 0);
340 * Try to read from backing to fill empty clusters
341 * FIXME: 1. previous write_zeroes may be redundant
342 * 2. most of data we read from backing will be rewritten by
343 * parallels_co_writev. On aligned-to-cluster write we do not need
345 * 3. it would be good to combine write of data from backing and new
346 * data into one write call.
349 int64_t nb_cow_sectors = to_allocate * s->tracks;
350 int64_t nb_cow_bytes = nb_cow_sectors << BDRV_SECTOR_BITS;
351 void *buf = qemu_blockalign(bs, nb_cow_bytes);
353 ret = bdrv_co_pread(bs->backing, idx * s->tracks * BDRV_SECTOR_SIZE,
354 nb_cow_bytes, buf, 0);
360 ret = bdrv_co_pwrite(bs->file, s->data_end * BDRV_SECTOR_SIZE,
361 nb_cow_bytes, buf, 0);
368 ret = mark_used(bs, s->used_bmap, s->used_bmap_size, host_off, to_allocate);
370 /* Image consistency is broken. Alarm! */
373 for (i = 0; i < to_allocate; i++) {
374 parallels_set_bat_entry(s, idx + i,
375 host_off / BDRV_SECTOR_SIZE / s->off_multiplier);
376 host_off += s->cluster_size;
378 if (host_off > s->data_end * BDRV_SECTOR_SIZE) {
379 s->data_end = host_off / BDRV_SECTOR_SIZE;
382 return bat2sect(s, idx) + sector_num % s->tracks;
386 static int coroutine_fn GRAPH_RDLOCK
387 parallels_co_flush_to_os(BlockDriverState *bs)
389 BDRVParallelsState *s = bs->opaque;
390 unsigned long size = DIV_ROUND_UP(s->header_size, s->bat_dirty_block);
393 qemu_co_mutex_lock(&s->lock);
395 bit = find_first_bit(s->bat_dirty_bmap, size);
397 uint32_t off = bit * s->bat_dirty_block;
398 uint32_t to_write = s->bat_dirty_block;
401 if (off + to_write > s->header_size) {
402 to_write = s->header_size - off;
404 ret = bdrv_co_pwrite(bs->file, off, to_write,
405 (uint8_t *)s->header + off, 0);
407 qemu_co_mutex_unlock(&s->lock);
410 bit = find_next_bit(s->bat_dirty_bmap, size, bit + 1);
412 bitmap_zero(s->bat_dirty_bmap, size);
414 qemu_co_mutex_unlock(&s->lock);
419 static int coroutine_fn parallels_co_block_status(BlockDriverState *bs,
425 BlockDriverState **file)
427 BDRVParallelsState *s = bs->opaque;
430 assert(QEMU_IS_ALIGNED(offset | bytes, BDRV_SECTOR_SIZE));
431 qemu_co_mutex_lock(&s->lock);
432 offset = block_status(s, offset >> BDRV_SECTOR_BITS,
433 bytes >> BDRV_SECTOR_BITS, &count);
434 qemu_co_mutex_unlock(&s->lock);
436 *pnum = count * BDRV_SECTOR_SIZE;
441 *map = offset * BDRV_SECTOR_SIZE;
442 *file = bs->file->bs;
443 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
446 static int coroutine_fn GRAPH_RDLOCK
447 parallels_co_writev(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
448 QEMUIOVector *qiov, int flags)
450 BDRVParallelsState *s = bs->opaque;
451 uint64_t bytes_done = 0;
452 QEMUIOVector hd_qiov;
455 qemu_iovec_init(&hd_qiov, qiov->niov);
457 while (nb_sectors > 0) {
461 qemu_co_mutex_lock(&s->lock);
462 position = allocate_clusters(bs, sector_num, nb_sectors, &n);
463 qemu_co_mutex_unlock(&s->lock);
469 nbytes = n << BDRV_SECTOR_BITS;
471 qemu_iovec_reset(&hd_qiov);
472 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, nbytes);
474 ret = bdrv_co_pwritev(bs->file, position * BDRV_SECTOR_SIZE, nbytes,
482 bytes_done += nbytes;
485 qemu_iovec_destroy(&hd_qiov);
489 static int coroutine_fn GRAPH_RDLOCK
490 parallels_co_readv(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
493 BDRVParallelsState *s = bs->opaque;
494 uint64_t bytes_done = 0;
495 QEMUIOVector hd_qiov;
498 qemu_iovec_init(&hd_qiov, qiov->niov);
500 while (nb_sectors > 0) {
504 qemu_co_mutex_lock(&s->lock);
505 position = block_status(s, sector_num, nb_sectors, &n);
506 qemu_co_mutex_unlock(&s->lock);
508 nbytes = n << BDRV_SECTOR_BITS;
510 qemu_iovec_reset(&hd_qiov);
511 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, nbytes);
515 ret = bdrv_co_preadv(bs->backing, sector_num * BDRV_SECTOR_SIZE,
516 nbytes, &hd_qiov, 0);
521 qemu_iovec_memset(&hd_qiov, 0, 0, nbytes);
524 ret = bdrv_co_preadv(bs->file, position * BDRV_SECTOR_SIZE, nbytes,
533 bytes_done += nbytes;
536 qemu_iovec_destroy(&hd_qiov);
541 static int coroutine_fn GRAPH_RDLOCK
542 parallels_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes)
545 uint32_t cluster, count;
546 BDRVParallelsState *s = bs->opaque;
549 * The image does not support ZERO mark inside the BAT, which means that
550 * stale data could be exposed from the backing file.
556 if (!QEMU_IS_ALIGNED(offset, s->cluster_size)) {
558 } else if (!QEMU_IS_ALIGNED(bytes, s->cluster_size)) {
562 cluster = offset / s->cluster_size;
563 count = bytes / s->cluster_size;
565 qemu_co_mutex_lock(&s->lock);
566 for (; count > 0; cluster++, count--) {
567 int64_t host_off = bat2sect(s, cluster) << BDRV_SECTOR_BITS;
572 ret = bdrv_co_pdiscard(bs->file, host_off, s->cluster_size);
577 parallels_set_bat_entry(s, cluster, 0);
578 bitmap_clear(s->used_bmap, host_cluster_index(s, host_off), 1);
581 qemu_co_mutex_unlock(&s->lock);
585 static void parallels_check_unclean(BlockDriverState *bs,
586 BdrvCheckResult *res,
589 BDRVParallelsState *s = bs->opaque;
591 if (!s->header_unclean) {
595 fprintf(stderr, "%s image was not closed correctly\n",
596 fix & BDRV_FIX_ERRORS ? "Repairing" : "ERROR");
598 if (fix & BDRV_FIX_ERRORS) {
599 /* parallels_close will do the job right */
600 res->corruptions_fixed++;
601 s->header_unclean = false;
606 * Returns true if data_off is correct, otherwise false. In both cases
607 * correct_offset is set to the proper value.
609 static bool parallels_test_data_off(BDRVParallelsState *s,
610 int64_t file_nb_sectors,
611 uint32_t *correct_offset)
613 uint32_t data_off, min_off;
617 * There are two slightly different image formats: with "WithoutFreeSpace"
618 * or "WithouFreSpacExt" magic words. Call the first one as "old magic".
619 * In such images data_off field can be zero. In this case the offset is
620 * calculated as the end of BAT table plus some padding to ensure sector
623 old_magic = !memcmp(s->header->magic, HEADER_MAGIC, 16);
625 min_off = DIV_ROUND_UP(bat_entry_off(s->bat_size), BDRV_SECTOR_SIZE);
627 min_off = ROUND_UP(min_off, s->cluster_size / BDRV_SECTOR_SIZE);
630 if (correct_offset) {
631 *correct_offset = min_off;
634 data_off = le32_to_cpu(s->header->data_off);
635 if (data_off == 0 && old_magic) {
639 if (data_off < min_off || data_off > file_nb_sectors) {
643 if (correct_offset) {
644 *correct_offset = data_off;
650 static int coroutine_fn GRAPH_RDLOCK
651 parallels_check_data_off(BlockDriverState *bs, BdrvCheckResult *res,
654 BDRVParallelsState *s = bs->opaque;
658 file_size = bdrv_co_nb_sectors(bs->file->bs);
664 if (parallels_test_data_off(s, file_size, &data_off)) {
669 if (fix & BDRV_FIX_ERRORS) {
671 s->header->data_off = cpu_to_le32(data_off);
672 s->data_start = data_off;
674 parallels_free_used_bitmap(bs);
675 err = parallels_fill_used_bitmap(bs);
676 if (err == -ENOMEM) {
681 res->corruptions_fixed++;
684 fprintf(stderr, "%s data_off field has incorrect value\n",
685 fix & BDRV_FIX_ERRORS ? "Repairing" : "ERROR");
690 static int coroutine_fn GRAPH_RDLOCK
691 parallels_check_outside_image(BlockDriverState *bs, BdrvCheckResult *res,
694 BDRVParallelsState *s = bs->opaque;
696 int64_t off, high_off, size;
698 size = bdrv_co_getlength(bs->file->bs);
705 for (i = 0; i < s->bat_size; i++) {
706 off = bat2sect(s, i) << BDRV_SECTOR_BITS;
707 if (off + s->cluster_size > size) {
708 fprintf(stderr, "%s cluster %u is outside image\n",
709 fix & BDRV_FIX_ERRORS ? "Repairing" : "ERROR", i);
711 if (fix & BDRV_FIX_ERRORS) {
712 parallels_set_bat_entry(s, i, 0);
713 res->corruptions_fixed++;
717 if (high_off < off) {
723 res->image_end_offset = s->data_end << BDRV_SECTOR_BITS;
725 res->image_end_offset = high_off + s->cluster_size;
726 s->data_end = res->image_end_offset >> BDRV_SECTOR_BITS;
732 static int coroutine_fn GRAPH_RDLOCK
733 parallels_check_leak(BlockDriverState *bs, BdrvCheckResult *res,
734 BdrvCheckMode fix, bool explicit)
736 BDRVParallelsState *s = bs->opaque;
740 size = bdrv_co_getlength(bs->file->bs);
746 if (size > res->image_end_offset) {
748 count = DIV_ROUND_UP(size - res->image_end_offset, s->cluster_size);
751 "%s space leaked at the end of the image %" PRId64 "\n",
752 fix & BDRV_FIX_LEAKS ? "Repairing" : "ERROR",
753 size - res->image_end_offset);
756 if (fix & BDRV_FIX_LEAKS) {
757 Error *local_err = NULL;
760 * In order to really repair the image, we must shrink it.
761 * That means we have to pass exact=true.
763 ret = bdrv_co_truncate(bs->file, res->image_end_offset, true,
764 PREALLOC_MODE_OFF, 0, &local_err);
766 error_report_err(local_err);
771 res->leaks_fixed += count;
779 static int coroutine_fn GRAPH_RDLOCK
780 parallels_check_duplicate(BlockDriverState *bs, BdrvCheckResult *res,
783 BDRVParallelsState *s = bs->opaque;
784 int64_t host_off, host_sector, guest_sector;
785 unsigned long *bitmap;
786 uint32_t i, bitmap_size, bat_entry;
788 uint64_t *buf = NULL;
792 * Create a bitmap of used clusters.
793 * If a bit is set, there is a BAT entry pointing to this cluster.
794 * Loop through the BAT entries, check bits relevant to an entry offset.
795 * If bit is set, this entry is duplicated. Otherwise set the bit.
797 * We shouldn't worry about newly allocated clusters outside the image
798 * because they are created higher then any existing cluster pointed by
801 bitmap_size = host_cluster_index(s, res->image_end_offset);
802 if (bitmap_size == 0) {
805 if (res->image_end_offset % s->cluster_size) {
806 /* A not aligned image end leads to a bitmap shorter by 1 */
810 bitmap = bitmap_new(bitmap_size);
812 buf = qemu_blockalign(bs, s->cluster_size);
814 for (i = 0; i < s->bat_size; i++) {
815 host_off = bat2sect(s, i) << BDRV_SECTOR_BITS;
820 ret = mark_used(bs, bitmap, bitmap_size, host_off, 1);
821 assert(ret != -E2BIG);
826 /* this cluster duplicates another one */
827 fprintf(stderr, "%s duplicate offset in BAT entry %u\n",
828 fix & BDRV_FIX_ERRORS ? "Repairing" : "ERROR", i);
832 if (!(fix & BDRV_FIX_ERRORS)) {
837 * Reset the entry and allocate a new cluster
838 * for the relevant guest offset. In this way we let
839 * the lower layer to place the new cluster properly.
840 * Copy the original cluster to the allocated one.
841 * But before save the old offset value for repairing
842 * if we have an error.
844 bat_entry = s->bat_bitmap[i];
845 parallels_set_bat_entry(s, i, 0);
847 ret = bdrv_co_pread(bs->file, host_off, s->cluster_size, buf, 0);
853 guest_sector = (i * (int64_t)s->cluster_size) >> BDRV_SECTOR_BITS;
854 host_sector = allocate_clusters(bs, guest_sector, s->tracks, &n);
855 if (host_sector < 0) {
859 host_off = host_sector << BDRV_SECTOR_BITS;
861 ret = bdrv_co_pwrite(bs->file, host_off, s->cluster_size, buf, 0);
867 if (host_off + s->cluster_size > res->image_end_offset) {
868 res->image_end_offset = host_off + s->cluster_size;
872 * In the future allocate_cluster() will reuse holed offsets
873 * inside the image. Keep the used clusters bitmap content
874 * consistent for the new allocated clusters too.
876 * Note, clusters allocated outside the current image are not
877 * considered, and the bitmap size doesn't change. This specifically
878 * means that -E2BIG is OK.
880 ret = mark_used(bs, bitmap, bitmap_size, host_off, 1);
887 res->corruptions_fixed++;
893 * When new clusters are allocated, the file size increases by
894 * 128 Mb. We need to truncate the file to the right size. Let
895 * the leak fix code make its job without res changing.
897 ret = parallels_check_leak(bs, res, fix, false);
905 * We can get here only from places where index and old_offset have
909 s->bat_bitmap[i] = bat_entry;
913 static void parallels_collect_statistics(BlockDriverState *bs,
914 BdrvCheckResult *res,
917 BDRVParallelsState *s = bs->opaque;
918 int64_t off, prev_off;
921 res->bfi.total_clusters = s->bat_size;
922 res->bfi.compressed_clusters = 0; /* compression is not supported */
925 for (i = 0; i < s->bat_size; i++) {
926 off = bat2sect(s, i) << BDRV_SECTOR_BITS;
928 * If BDRV_FIX_ERRORS is not set, out-of-image BAT entries were not
929 * fixed. Skip not allocated and out-of-image BAT entries.
931 if (off == 0 || off + s->cluster_size > res->image_end_offset) {
936 if (prev_off != 0 && (prev_off + s->cluster_size) != off) {
937 res->bfi.fragmented_clusters++;
940 res->bfi.allocated_clusters++;
944 static int coroutine_fn GRAPH_RDLOCK
945 parallels_co_check(BlockDriverState *bs, BdrvCheckResult *res,
948 BDRVParallelsState *s = bs->opaque;
951 WITH_QEMU_LOCK_GUARD(&s->lock) {
952 parallels_check_unclean(bs, res, fix);
954 ret = parallels_check_data_off(bs, res, fix);
959 ret = parallels_check_outside_image(bs, res, fix);
964 ret = parallels_check_leak(bs, res, fix, true);
969 ret = parallels_check_duplicate(bs, res, fix);
974 parallels_collect_statistics(bs, res, fix);
977 ret = bdrv_co_flush(bs);
986 static int coroutine_fn GRAPH_UNLOCKED
987 parallels_co_create(BlockdevCreateOptions* opts, Error **errp)
989 BlockdevCreateOptionsParallels *parallels_opts;
990 BlockDriverState *bs;
992 int64_t total_size, cl_size;
993 uint32_t bat_entries, bat_sectors;
994 ParallelsHeader header;
995 uint8_t tmp[BDRV_SECTOR_SIZE];
998 assert(opts->driver == BLOCKDEV_DRIVER_PARALLELS);
999 parallels_opts = &opts->u.parallels;
1002 total_size = parallels_opts->size;
1004 if (parallels_opts->has_cluster_size) {
1005 cl_size = parallels_opts->cluster_size;
1007 cl_size = DEFAULT_CLUSTER_SIZE;
1010 /* XXX What is the real limit here? This is an insanely large maximum. */
1011 if (cl_size >= INT64_MAX / MAX_PARALLELS_IMAGE_FACTOR) {
1012 error_setg(errp, "Cluster size is too large");
1015 if (total_size >= MAX_PARALLELS_IMAGE_FACTOR * cl_size) {
1016 error_setg(errp, "Image size is too large for this cluster size");
1020 if (!QEMU_IS_ALIGNED(total_size, BDRV_SECTOR_SIZE)) {
1021 error_setg(errp, "Image size must be a multiple of 512 bytes");
1025 if (!QEMU_IS_ALIGNED(cl_size, BDRV_SECTOR_SIZE)) {
1026 error_setg(errp, "Cluster size must be a multiple of 512 bytes");
1030 /* Create BlockBackend to write to the image */
1031 bs = bdrv_co_open_blockdev_ref(parallels_opts->file, errp);
1036 blk = blk_co_new_with_bs(bs, BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL,
1042 blk_set_allow_write_beyond_eof(blk, true);
1044 /* Create image format */
1045 bat_entries = DIV_ROUND_UP(total_size, cl_size);
1046 bat_sectors = DIV_ROUND_UP(bat_entry_off(bat_entries), cl_size);
1047 bat_sectors = (bat_sectors * cl_size) >> BDRV_SECTOR_BITS;
1049 memset(&header, 0, sizeof(header));
1050 memcpy(header.magic, HEADER_MAGIC2, sizeof(header.magic));
1051 header.version = cpu_to_le32(HEADER_VERSION);
1052 /* don't care much about geometry, it is not used on image level */
1053 header.heads = cpu_to_le32(HEADS_NUMBER);
1054 header.cylinders = cpu_to_le32(total_size / BDRV_SECTOR_SIZE
1055 / HEADS_NUMBER / SEC_IN_CYL);
1056 header.tracks = cpu_to_le32(cl_size >> BDRV_SECTOR_BITS);
1057 header.bat_entries = cpu_to_le32(bat_entries);
1058 header.nb_sectors = cpu_to_le64(DIV_ROUND_UP(total_size, BDRV_SECTOR_SIZE));
1059 header.data_off = cpu_to_le32(bat_sectors);
1061 /* write all the data */
1062 memset(tmp, 0, sizeof(tmp));
1063 memcpy(tmp, &header, sizeof(header));
1065 ret = blk_co_pwrite(blk, 0, BDRV_SECTOR_SIZE, tmp, 0);
1069 ret = blk_co_pwrite_zeroes(blk, BDRV_SECTOR_SIZE,
1070 (bat_sectors - 1) << BDRV_SECTOR_BITS, 0);
1082 error_setg_errno(errp, -ret, "Failed to create Parallels image");
1086 static int coroutine_fn GRAPH_UNLOCKED
1087 parallels_co_create_opts(BlockDriver *drv, const char *filename,
1088 QemuOpts *opts, Error **errp)
1090 BlockdevCreateOptions *create_options = NULL;
1091 BlockDriverState *bs = NULL;
1096 static const QDictRenames opt_renames[] = {
1097 { BLOCK_OPT_CLUSTER_SIZE, "cluster-size" },
1101 /* Parse options and convert legacy syntax */
1102 qdict = qemu_opts_to_qdict_filtered(opts, NULL, ¶llels_create_opts,
1105 if (!qdict_rename_keys(qdict, opt_renames, errp)) {
1110 /* Create and open the file (protocol layer) */
1111 ret = bdrv_co_create_file(filename, opts, errp);
1116 bs = bdrv_co_open(filename, NULL, NULL,
1117 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
1123 /* Now get the QAPI type BlockdevCreateOptions */
1124 qdict_put_str(qdict, "driver", "parallels");
1125 qdict_put_str(qdict, "file", bs->node_name);
1127 v = qobject_input_visitor_new_flat_confused(qdict, errp);
1133 visit_type_BlockdevCreateOptions(v, NULL, &create_options, errp);
1135 if (!create_options) {
1140 /* Silently round up sizes */
1141 create_options->u.parallels.size =
1142 ROUND_UP(create_options->u.parallels.size, BDRV_SECTOR_SIZE);
1143 create_options->u.parallels.cluster_size =
1144 ROUND_UP(create_options->u.parallels.cluster_size, BDRV_SECTOR_SIZE);
1146 /* Create the Parallels image (format layer) */
1147 ret = parallels_co_create(create_options, errp);
1154 qobject_unref(qdict);
1156 qapi_free_BlockdevCreateOptions(create_options);
1161 static int parallels_probe(const uint8_t *buf, int buf_size,
1162 const char *filename)
1164 const ParallelsHeader *ph = (const void *)buf;
1166 if (buf_size < sizeof(ParallelsHeader)) {
1170 if ((!memcmp(ph->magic, HEADER_MAGIC, 16) ||
1171 !memcmp(ph->magic, HEADER_MAGIC2, 16)) &&
1172 (le32_to_cpu(ph->version) == HEADER_VERSION)) {
1179 static int parallels_update_header(BlockDriverState *bs)
1181 BDRVParallelsState *s = bs->opaque;
1182 unsigned size = MAX(bdrv_opt_mem_align(bs->file->bs),
1183 sizeof(ParallelsHeader));
1185 if (size > s->header_size) {
1186 size = s->header_size;
1188 return bdrv_pwrite_sync(bs->file, 0, size, s->header, 0);
1192 static int parallels_opts_prealloc(BlockDriverState *bs, QDict *options,
1198 BDRVParallelsState *s = bs->opaque;
1199 Error *local_err = NULL;
1200 QemuOpts *opts = qemu_opts_create(¶llels_runtime_opts, NULL, 0, errp);
1206 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
1210 bytes = qemu_opt_get_size_del(opts, PARALLELS_OPT_PREALLOC_SIZE, 0);
1211 s->prealloc_size = bytes >> BDRV_SECTOR_BITS;
1212 buf = qemu_opt_get_del(opts, PARALLELS_OPT_PREALLOC_MODE);
1213 /* prealloc_mode can be downgraded later during allocate_clusters */
1214 s->prealloc_mode = qapi_enum_parse(&prealloc_mode_lookup, buf,
1215 PRL_PREALLOC_MODE_FALLOCATE,
1218 if (local_err != NULL) {
1219 error_propagate(errp, local_err);
1225 qemu_opts_del(opts);
1229 static int parallels_open(BlockDriverState *bs, QDict *options, int flags,
1232 BDRVParallelsState *s = bs->opaque;
1235 int64_t file_nb_sectors, sector;
1236 uint32_t data_start;
1237 bool need_check = false;
1239 ret = parallels_opts_prealloc(bs, options, errp);
1244 ret = bdrv_open_file_child(NULL, options, "file", bs, errp);
1249 file_nb_sectors = bdrv_nb_sectors(bs->file->bs);
1250 if (file_nb_sectors < 0) {
1254 ret = bdrv_pread(bs->file, 0, sizeof(ph), &ph, 0);
1259 bs->total_sectors = le64_to_cpu(ph.nb_sectors);
1261 if (le32_to_cpu(ph.version) != HEADER_VERSION) {
1264 if (!memcmp(ph.magic, HEADER_MAGIC, 16)) {
1265 s->off_multiplier = 1;
1266 bs->total_sectors = 0xffffffff & bs->total_sectors;
1267 } else if (!memcmp(ph.magic, HEADER_MAGIC2, 16)) {
1268 s->off_multiplier = le32_to_cpu(ph.tracks);
1273 s->tracks = le32_to_cpu(ph.tracks);
1274 if (s->tracks == 0) {
1275 error_setg(errp, "Invalid image: Zero sectors per track");
1278 if (s->tracks > INT32_MAX/513) {
1279 error_setg(errp, "Invalid image: Too big cluster");
1282 s->prealloc_size = MAX(s->tracks, s->prealloc_size);
1283 s->cluster_size = s->tracks << BDRV_SECTOR_BITS;
1285 s->bat_size = le32_to_cpu(ph.bat_entries);
1286 if (s->bat_size > INT_MAX / sizeof(uint32_t)) {
1287 error_setg(errp, "Catalog too large");
1291 size = bat_entry_off(s->bat_size);
1292 s->header_size = ROUND_UP(size, bdrv_opt_mem_align(bs->file->bs));
1293 s->header = qemu_try_blockalign(bs->file->bs, s->header_size);
1294 if (s->header == NULL) {
1298 ret = bdrv_pread(bs->file, 0, s->header_size, s->header, 0);
1302 s->bat_bitmap = (uint32_t *)(s->header + 1);
1304 if (le32_to_cpu(ph.inuse) == HEADER_INUSE_MAGIC) {
1305 need_check = s->header_unclean = true;
1309 bool ok = parallels_test_data_off(s, file_nb_sectors, &data_start);
1310 need_check = need_check || !ok;
1313 s->data_start = data_start;
1314 s->data_end = s->data_start;
1315 if (s->data_end < (s->header_size >> BDRV_SECTOR_BITS)) {
1317 * There is not enough unused space to fit to block align between BAT
1318 * and actual data. We can't avoid read-modify-write...
1320 s->header_size = size;
1324 if (flags & BDRV_O_RDWR) {
1326 * It's unsafe to open image RW if there is an extension (as we
1327 * don't support it). But parallels driver in QEMU historically
1328 * ignores the extension, so print warning and don't care.
1330 warn_report("Format Extension ignored in RW mode");
1332 ret = parallels_read_format_extension(
1333 bs, le64_to_cpu(ph.ext_off) << BDRV_SECTOR_BITS, errp);
1340 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_INACTIVE)) {
1341 s->header->inuse = cpu_to_le32(HEADER_INUSE_MAGIC);
1342 ret = parallels_update_header(bs);
1348 s->bat_dirty_block = 4 * qemu_real_host_page_size();
1350 bitmap_new(DIV_ROUND_UP(s->header_size, s->bat_dirty_block));
1352 /* Disable migration until bdrv_activate method is added */
1353 error_setg(&s->migration_blocker, "The Parallels format used by node '%s' "
1354 "does not support live migration",
1355 bdrv_get_device_or_node_name(bs));
1356 ret = migrate_add_blocker(s->migration_blocker, errp);
1358 error_setg(errp, "Migration blocker error");
1361 qemu_co_mutex_init(&s->lock);
1363 for (i = 0; i < s->bat_size; i++) {
1364 sector = bat2sect(s, i);
1365 if (sector + s->tracks > s->data_end) {
1366 s->data_end = sector + s->tracks;
1369 need_check = need_check || s->data_end > file_nb_sectors;
1372 ret = parallels_fill_used_bitmap(bs);
1373 if (ret == -ENOMEM) {
1376 need_check = need_check || ret < 0; /* These are correctable errors */
1380 * We don't repair the image here if it's opened for checks. Also we don't
1381 * want to change inactive images and can't change readonly images.
1383 if ((flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) || !(flags & BDRV_O_RDWR)) {
1387 /* Repair the image if corruption was detected. */
1389 BdrvCheckResult res;
1390 ret = bdrv_check(bs, &res, BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1392 error_setg_errno(errp, -ret, "Could not repair corrupted image");
1393 migrate_del_blocker(s->migration_blocker);
1400 error_setg(errp, "Image not in Parallels format");
1405 * "s" object was allocated by g_malloc0 so we can safely
1406 * try to free its fields even they were not allocated.
1408 parallels_free_used_bitmap(bs);
1410 error_free(s->migration_blocker);
1411 g_free(s->bat_dirty_bmap);
1412 qemu_vfree(s->header);
1417 static void parallels_close(BlockDriverState *bs)
1419 BDRVParallelsState *s = bs->opaque;
1421 if ((bs->open_flags & BDRV_O_RDWR) && !(bs->open_flags & BDRV_O_INACTIVE)) {
1422 s->header->inuse = 0;
1423 parallels_update_header(bs);
1425 /* errors are ignored, so we might as well pass exact=true */
1426 bdrv_truncate(bs->file, s->data_end << BDRV_SECTOR_BITS, true,
1427 PREALLOC_MODE_OFF, 0, NULL);
1430 parallels_free_used_bitmap(bs);
1432 g_free(s->bat_dirty_bmap);
1433 qemu_vfree(s->header);
1435 migrate_del_blocker(s->migration_blocker);
1436 error_free(s->migration_blocker);
1439 static bool parallels_is_support_dirty_bitmaps(BlockDriverState *bs)
1444 static BlockDriver bdrv_parallels = {
1445 .format_name = "parallels",
1446 .instance_size = sizeof(BDRVParallelsState),
1447 .create_opts = ¶llels_create_opts,
1449 .supports_backing = true,
1451 .bdrv_has_zero_init = bdrv_has_zero_init_1,
1452 .bdrv_supports_persistent_dirty_bitmap = parallels_is_support_dirty_bitmaps,
1454 .bdrv_probe = parallels_probe,
1455 .bdrv_open = parallels_open,
1456 .bdrv_close = parallels_close,
1457 .bdrv_child_perm = bdrv_default_perms,
1458 .bdrv_co_block_status = parallels_co_block_status,
1459 .bdrv_co_flush_to_os = parallels_co_flush_to_os,
1460 .bdrv_co_readv = parallels_co_readv,
1461 .bdrv_co_writev = parallels_co_writev,
1462 .bdrv_co_create = parallels_co_create,
1463 .bdrv_co_create_opts = parallels_co_create_opts,
1464 .bdrv_co_check = parallels_co_check,
1465 .bdrv_co_pdiscard = parallels_co_pdiscard,
1468 static void bdrv_parallels_init(void)
1470 bdrv_register(&bdrv_parallels);
1473 block_init(bdrv_parallels_init);