1 From 9cb2f2d61ebf1c28b19bc2df78879431b735f460 Mon Sep 17 00:00:00 2001
2 From: Dietmar Maurer <dietmar@proxmox.com>
3 Date: Tue, 13 Nov 2012 11:11:38 +0100
4 Subject: [PATCH 11/41] introduce new vma archive format
6 This is a very simple archive format, see docs/specs/vma_spec.txt
8 Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
12 vma-reader.c | 797 +++++++++++++++++++++++++++++++++++++++++++++++++++++
13 vma-writer.c | 870 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
14 vma.c | 585 +++++++++++++++++++++++++++++++++++++++
15 vma.h | 146 ++++++++++
16 6 files changed, 2401 insertions(+), 1 deletion(-)
17 create mode 100644 vma-reader.c
18 create mode 100644 vma-writer.c
19 create mode 100644 vma.c
20 create mode 100644 vma.h
22 diff --git a/Makefile b/Makefile
23 index 50b4b3a..d92d905 100644
26 @@ -165,7 +165,7 @@ ifneq ($(wildcard config-host.mak),)
27 include $(SRC_PATH)/tests/Makefile.include
30 -all: $(DOCS) $(TOOLS) $(HELPERS-y) recurse-all modules
31 +all: $(DOCS) $(TOOLS) vma$(EXESUF) $(HELPERS-y) recurse-all modules
34 $(call quiet-command, \
35 @@ -256,6 +256,7 @@ qemu-img.o: qemu-img-cmds.h
36 qemu-img$(EXESUF): qemu-img.o $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) libqemuutil.a libqemustub.a
37 qemu-nbd$(EXESUF): qemu-nbd.o $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) libqemuutil.a libqemustub.a
38 qemu-io$(EXESUF): qemu-io.o $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) libqemuutil.a libqemustub.a
39 +vma$(EXESUF): vma.o vma-reader.o $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) libqemuutil.a libqemustub.a
41 qemu-bridge-helper$(EXESUF): qemu-bridge-helper.o libqemuutil.a libqemustub.a
43 diff --git a/Makefile.objs b/Makefile.objs
44 index 6d5ddcf..845edd0 100644
47 @@ -15,6 +15,7 @@ block-obj-$(CONFIG_POSIX) += aio-posix.o
48 block-obj-$(CONFIG_WIN32) += aio-win32.o
50 block-obj-y += qemu-io-cmds.o
51 +block-obj-y += vma-writer.o
55 diff --git a/vma-reader.c b/vma-reader.c
57 index 0000000..51dd8fe
62 + * VMA: Virtual Machine Archive
64 + * Copyright (C) 2012 Proxmox Server Solutions
67 + * Dietmar Maurer (dietmar@proxmox.com)
69 + * This work is licensed under the terms of the GNU GPL, version 2 or later.
70 + * See the COPYING file in the top-level directory.
74 +#include "qemu/osdep.h"
76 +#include <uuid/uuid.h>
78 +#include "qemu-common.h"
79 +#include "qemu/timer.h"
80 +#include "qemu/ratelimit.h"
82 +#include "block/block.h"
83 +#include "sysemu/block-backend.h"
85 +static unsigned char zero_vma_block[VMA_BLOCK_SIZE];
87 +typedef struct VmaRestoreState {
88 + BlockDriverState *bs;
90 + unsigned long *bitmap;
97 + GHashTable *blob_hash;
98 + unsigned char *head_data;
99 + VmaDeviceInfo devinfo[256];
100 + VmaRestoreState rstate[256];
102 + guint8 vmstate_stream;
103 + uint32_t vmstate_clusters;
104 + /* to show restore percentage if run with -v */
106 + int64_t cluster_count;
107 + int64_t clusters_read;
108 + int clusters_read_per;
112 +g_int32_hash(gconstpointer v)
114 + return *(const uint32_t *)v;
118 +g_int32_equal(gconstpointer v1, gconstpointer v2)
120 + return *((const uint32_t *)v1) == *((const uint32_t *)v2);
123 +static int vma_reader_get_bitmap(VmaRestoreState *rstate, int64_t cluster_num)
126 + assert(rstate->bitmap);
128 + unsigned long val, idx, bit;
130 + idx = cluster_num / BITS_PER_LONG;
132 + assert(rstate->bitmap_size > idx);
134 + bit = cluster_num % BITS_PER_LONG;
135 + val = rstate->bitmap[idx];
137 + return !!(val & (1UL << bit));
140 +static void vma_reader_set_bitmap(VmaRestoreState *rstate, int64_t cluster_num,
144 + assert(rstate->bitmap);
146 + unsigned long val, idx, bit;
148 + idx = cluster_num / BITS_PER_LONG;
150 + assert(rstate->bitmap_size > idx);
152 + bit = cluster_num % BITS_PER_LONG;
153 + val = rstate->bitmap[idx];
155 + if (!(val & (1UL << bit))) {
159 + if (val & (1UL << bit)) {
160 + val &= ~(1UL << bit);
163 + rstate->bitmap[idx] = val;
166 +typedef struct VmaBlob {
172 +static const VmaBlob *get_header_blob(VmaReader *vmar, uint32_t pos)
175 + assert(vmar->blob_hash);
177 + return g_hash_table_lookup(vmar->blob_hash, &pos);
180 +static const char *get_header_str(VmaReader *vmar, uint32_t pos)
182 + const VmaBlob *blob = get_header_blob(vmar, pos);
186 + const char *res = (char *)blob->data;
187 + if (res[blob->len-1] != '\0') {
194 +safe_read(int fd, unsigned char *buf, size_t count)
199 + n = read(fd, buf, count);
200 + } while (n < 0 && errno == EINTR);
206 +full_read(int fd, unsigned char *buf, size_t len)
214 + n = safe_read(fd, buf, len);
236 +void vma_reader_destroy(VmaReader *vmar)
240 + if (vmar->fd >= 0) {
244 + if (vmar->cdata_list) {
245 + g_list_free(vmar->cdata_list);
249 + for (i = 1; i < 256; i++) {
250 + if (vmar->rstate[i].bitmap) {
251 + g_free(vmar->rstate[i].bitmap);
255 + if (vmar->md5csum) {
256 + g_checksum_free(vmar->md5csum);
259 + if (vmar->blob_hash) {
260 + g_hash_table_destroy(vmar->blob_hash);
263 + if (vmar->head_data) {
264 + g_free(vmar->head_data);
271 +static int vma_reader_read_head(VmaReader *vmar, Error **errp)
275 + assert(*errp == NULL);
277 + unsigned char md5sum[16];
281 + vmar->head_data = g_malloc(sizeof(VmaHeader));
283 + if (full_read(vmar->fd, vmar->head_data, sizeof(VmaHeader)) !=
284 + sizeof(VmaHeader)) {
285 + error_setg(errp, "can't read vma header - %s",
286 + errno ? g_strerror(errno) : "got EOF");
290 + VmaHeader *h = (VmaHeader *)vmar->head_data;
292 + if (h->magic != VMA_MAGIC) {
293 + error_setg(errp, "not a vma file - wrong magic number");
297 + uint32_t header_size = GUINT32_FROM_BE(h->header_size);
298 + int need = header_size - sizeof(VmaHeader);
300 + error_setg(errp, "wrong vma header size %d", header_size);
304 + vmar->head_data = g_realloc(vmar->head_data, header_size);
305 + h = (VmaHeader *)vmar->head_data;
307 + if (full_read(vmar->fd, vmar->head_data + sizeof(VmaHeader), need) !=
309 + error_setg(errp, "can't read vma header data - %s",
310 + errno ? g_strerror(errno) : "got EOF");
314 + memcpy(md5sum, h->md5sum, 16);
315 + memset(h->md5sum, 0, 16);
317 + g_checksum_reset(vmar->md5csum);
318 + g_checksum_update(vmar->md5csum, vmar->head_data, header_size);
320 + g_checksum_get_digest(vmar->md5csum, (guint8 *)(h->md5sum), &csize);
322 + if (memcmp(md5sum, h->md5sum, 16) != 0) {
323 + error_setg(errp, "wrong vma header chechsum");
327 + /* we can modify header data after checksum verify */
328 + h->header_size = header_size;
330 + h->version = GUINT32_FROM_BE(h->version);
331 + if (h->version != 1) {
332 + error_setg(errp, "wrong vma version %d", h->version);
336 + h->ctime = GUINT64_FROM_BE(h->ctime);
337 + h->blob_buffer_offset = GUINT32_FROM_BE(h->blob_buffer_offset);
338 + h->blob_buffer_size = GUINT32_FROM_BE(h->blob_buffer_size);
340 + uint32_t bstart = h->blob_buffer_offset + 1;
341 + uint32_t bend = h->blob_buffer_offset + h->blob_buffer_size;
343 + if (bstart <= sizeof(VmaHeader)) {
344 + error_setg(errp, "wrong vma blob buffer offset %d",
345 + h->blob_buffer_offset);
349 + if (bend > header_size) {
350 + error_setg(errp, "wrong vma blob buffer size %d/%d",
351 + h->blob_buffer_offset, h->blob_buffer_size);
355 + while ((bstart + 2) <= bend) {
356 + uint32_t size = vmar->head_data[bstart] +
357 + (vmar->head_data[bstart+1] << 8);
358 + if ((bstart + size + 2) <= bend) {
359 + VmaBlob *blob = g_new0(VmaBlob, 1);
360 + blob->start = bstart - h->blob_buffer_offset;
362 + blob->data = vmar->head_data + bstart + 2;
363 + g_hash_table_insert(vmar->blob_hash, &blob->start, blob);
365 + bstart += size + 2;
370 + for (i = 1; i < 256; i++) {
371 + VmaDeviceInfoHeader *dih = &h->dev_info[i];
372 + uint32_t devname_ptr = GUINT32_FROM_BE(dih->devname_ptr);
373 + uint64_t size = GUINT64_FROM_BE(dih->size);
374 + const char *devname = get_header_str(vmar, devname_ptr);
376 + if (size && devname) {
378 + vmar->devinfo[i].size = size;
379 + vmar->devinfo[i].devname = devname;
381 + if (strcmp(devname, "vmstate") == 0) {
382 + vmar->vmstate_stream = i;
388 + error_setg(errp, "vma does not contain data");
392 + for (i = 0; i < VMA_MAX_CONFIGS; i++) {
393 + uint32_t name_ptr = GUINT32_FROM_BE(h->config_names[i]);
394 + uint32_t data_ptr = GUINT32_FROM_BE(h->config_data[i]);
396 + if (!(name_ptr && data_ptr)) {
399 + const char *name = get_header_str(vmar, name_ptr);
400 + const VmaBlob *blob = get_header_blob(vmar, data_ptr);
402 + if (!(name && blob)) {
403 + error_setg(errp, "vma contains invalid data pointers");
407 + VmaConfigData *cdata = g_new0(VmaConfigData, 1);
408 + cdata->name = name;
409 + cdata->data = blob->data;
410 + cdata->len = blob->len;
412 + vmar->cdata_list = g_list_append(vmar->cdata_list, cdata);
418 +VmaReader *vma_reader_create(const char *filename, Error **errp)
423 + VmaReader *vmar = g_new0(VmaReader, 1);
425 + if (strcmp(filename, "-") == 0) {
428 + vmar->fd = open(filename, O_RDONLY);
431 + if (vmar->fd < 0) {
432 + error_setg(errp, "can't open file %s - %s\n", filename,
433 + g_strerror(errno));
437 + vmar->md5csum = g_checksum_new(G_CHECKSUM_MD5);
438 + if (!vmar->md5csum) {
439 + error_setg(errp, "can't allocate cmsum\n");
443 + vmar->blob_hash = g_hash_table_new_full(g_int32_hash, g_int32_equal,
446 + if (vma_reader_read_head(vmar, errp) < 0) {
454 + vma_reader_destroy(vmar);
460 +VmaHeader *vma_reader_get_header(VmaReader *vmar)
463 + assert(vmar->head_data);
465 + return (VmaHeader *)(vmar->head_data);
468 +GList *vma_reader_get_config_data(VmaReader *vmar)
471 + assert(vmar->head_data);
473 + return vmar->cdata_list;
476 +VmaDeviceInfo *vma_reader_get_device_info(VmaReader *vmar, guint8 dev_id)
481 + if (vmar->devinfo[dev_id].size && vmar->devinfo[dev_id].devname) {
482 + return &vmar->devinfo[dev_id];
488 +int vma_reader_register_bs(VmaReader *vmar, guint8 dev_id, BlockDriverState *bs,
489 + bool write_zeroes, Error **errp)
492 + assert(bs != NULL);
494 + assert(vmar->rstate[dev_id].bs == NULL);
496 + int64_t size = bdrv_getlength(bs);
497 + int64_t size_diff = size - vmar->devinfo[dev_id].size;
499 + /* storage types can have different size restrictions, so it
500 + * is not always possible to create an image with exact size.
501 + * So we tolerate a size difference up to 4MB.
503 + if ((size_diff < 0) || (size_diff > 4*1024*1024)) {
504 + error_setg(errp, "vma_reader_register_bs for stream %s failed - "
505 + "unexpected size %zd != %zd", vmar->devinfo[dev_id].devname,
506 + size, vmar->devinfo[dev_id].size);
510 + vmar->rstate[dev_id].bs = bs;
511 + vmar->rstate[dev_id].write_zeroes = write_zeroes;
513 + int64_t bitmap_size = (size/BDRV_SECTOR_SIZE) +
514 + (VMA_CLUSTER_SIZE/BDRV_SECTOR_SIZE) * BITS_PER_LONG - 1;
515 + bitmap_size /= (VMA_CLUSTER_SIZE/BDRV_SECTOR_SIZE) * BITS_PER_LONG;
517 + vmar->rstate[dev_id].bitmap_size = bitmap_size;
518 + vmar->rstate[dev_id].bitmap = g_new0(unsigned long, bitmap_size);
520 + vmar->cluster_count += size/VMA_CLUSTER_SIZE;
525 +static ssize_t safe_write(int fd, void *buf, size_t count)
530 + n = write(fd, buf, count);
531 + } while (n < 0 && errno == EINTR);
536 +static size_t full_write(int fd, void *buf, size_t len)
544 + n = safe_write(fd, buf, len);
554 + /* incomplete write ? */
561 +static int restore_write_data(VmaReader *vmar, guint8 dev_id,
562 + BlockDriverState *bs, int vmstate_fd,
563 + unsigned char *buf, int64_t sector_num,
564 + int nb_sectors, Error **errp)
568 + if (dev_id == vmar->vmstate_stream) {
569 + if (vmstate_fd >= 0) {
570 + int len = nb_sectors * BDRV_SECTOR_SIZE;
571 + int res = full_write(vmstate_fd, buf, len);
573 + error_setg(errp, "write vmstate failed %d", res);
578 + int res = bdrv_write(bs, sector_num, buf, nb_sectors);
580 + error_setg(errp, "bdrv_write to %s failed (%d)",
581 + bdrv_get_device_name(bs), res);
587 +static int restore_extent(VmaReader *vmar, unsigned char *buf,
588 + int extent_size, int vmstate_fd,
589 + bool verbose, Error **errp)
594 + VmaExtentHeader *ehead = (VmaExtentHeader *)buf;
595 + int start = VMA_EXTENT_HEADER_SIZE;
598 + for (i = 0; i < VMA_BLOCKS_PER_EXTENT; i++) {
599 + uint64_t block_info = GUINT64_FROM_BE(ehead->blockinfo[i]);
600 + uint64_t cluster_num = block_info & 0xffffffff;
601 + uint8_t dev_id = (block_info >> 32) & 0xff;
602 + uint16_t mask = block_info >> (32+16);
603 + int64_t max_sector;
609 + VmaRestoreState *rstate = &vmar->rstate[dev_id];
610 + BlockDriverState *bs = NULL;
612 + if (dev_id != vmar->vmstate_stream) {
615 + error_setg(errp, "got wrong dev id %d", dev_id);
619 + if (vma_reader_get_bitmap(rstate, cluster_num)) {
620 + error_setg(errp, "found duplicated cluster %zd for stream %s",
621 + cluster_num, vmar->devinfo[dev_id].devname);
624 + vma_reader_set_bitmap(rstate, cluster_num, 1);
626 + max_sector = vmar->devinfo[dev_id].size/BDRV_SECTOR_SIZE;
628 + max_sector = G_MAXINT64;
629 + if (cluster_num != vmar->vmstate_clusters) {
630 + error_setg(errp, "found out of order vmstate data");
633 + vmar->vmstate_clusters++;
636 + vmar->clusters_read++;
639 + time_t duration = time(NULL) - vmar->start_time;
640 + int percent = (vmar->clusters_read*100)/vmar->cluster_count;
641 + if (percent != vmar->clusters_read_per) {
642 + printf("progress %d%% (read %zd bytes, duration %zd sec)\n",
643 + percent, vmar->clusters_read*VMA_CLUSTER_SIZE,
646 + vmar->clusters_read_per = percent;
650 + /* try to write whole clusters to speedup restore */
651 + if (mask == 0xffff) {
652 + if ((start + VMA_CLUSTER_SIZE) > extent_size) {
653 + error_setg(errp, "short vma extent - too many blocks");
656 + int64_t sector_num = (cluster_num * VMA_CLUSTER_SIZE) /
658 + int64_t end_sector = sector_num +
659 + VMA_CLUSTER_SIZE/BDRV_SECTOR_SIZE;
661 + if (end_sector > max_sector) {
662 + end_sector = max_sector;
665 + if (end_sector <= sector_num) {
666 + error_setg(errp, "got wrong block address - write bejond end");
670 + int nb_sectors = end_sector - sector_num;
671 + if (restore_write_data(vmar, dev_id, bs, vmstate_fd, buf + start,
672 + sector_num, nb_sectors, errp) < 0) {
676 + start += VMA_CLUSTER_SIZE;
681 + for (j = 0; j < 16; j++) {
682 + int64_t sector_num = (cluster_num*VMA_CLUSTER_SIZE +
683 + j*VMA_BLOCK_SIZE)/BDRV_SECTOR_SIZE;
685 + int64_t end_sector = sector_num +
686 + VMA_BLOCK_SIZE/BDRV_SECTOR_SIZE;
687 + if (end_sector > max_sector) {
688 + end_sector = max_sector;
692 + if ((start + VMA_BLOCK_SIZE) > extent_size) {
693 + error_setg(errp, "short vma extent - too many blocks");
697 + if (end_sector <= sector_num) {
698 + error_setg(errp, "got wrong block address - "
699 + "write bejond end");
703 + int nb_sectors = end_sector - sector_num;
704 + if (restore_write_data(vmar, dev_id, bs, vmstate_fd,
705 + buf + start, sector_num,
706 + nb_sectors, errp) < 0) {
710 + start += VMA_BLOCK_SIZE;
714 + if (rstate->write_zeroes && (end_sector > sector_num)) {
715 + /* Todo: use bdrv_co_write_zeroes (but that need to
716 + * be run inside coroutine?)
718 + int nb_sectors = end_sector - sector_num;
719 + if (restore_write_data(vmar, dev_id, bs, vmstate_fd,
720 + zero_vma_block, sector_num,
721 + nb_sectors, errp) < 0) {
732 + if (start != extent_size) {
733 + error_setg(errp, "vma extent error - missing blocks");
740 +int vma_reader_restore(VmaReader *vmar, int vmstate_fd, bool verbose,
744 + assert(vmar->head_data);
747 + unsigned char buf[VMA_MAX_EXTENT_SIZE];
749 + unsigned char md5sum[16];
750 + VmaHeader *h = (VmaHeader *)vmar->head_data;
752 + vmar->start_time = time(NULL);
755 + int bytes = full_read(vmar->fd, buf + buf_pos, sizeof(buf) - buf_pos);
757 + error_setg(errp, "read failed - %s", g_strerror(errno));
767 + if (buf_pos < VMA_EXTENT_HEADER_SIZE) {
768 + error_setg(errp, "read short extent (%d bytes)", buf_pos);
772 + VmaExtentHeader *ehead = (VmaExtentHeader *)buf;
774 + /* extract md5sum */
775 + memcpy(md5sum, ehead->md5sum, sizeof(ehead->md5sum));
776 + memset(ehead->md5sum, 0, sizeof(ehead->md5sum));
778 + g_checksum_reset(vmar->md5csum);
779 + g_checksum_update(vmar->md5csum, buf, VMA_EXTENT_HEADER_SIZE);
781 + g_checksum_get_digest(vmar->md5csum, ehead->md5sum, &csize);
783 + if (memcmp(md5sum, ehead->md5sum, 16) != 0) {
784 + error_setg(errp, "wrong vma extent header chechsum");
788 + if (memcmp(h->uuid, ehead->uuid, sizeof(ehead->uuid)) != 0) {
789 + error_setg(errp, "wrong vma extent uuid");
793 + if (ehead->magic != VMA_EXTENT_MAGIC || ehead->reserved1 != 0) {
794 + error_setg(errp, "wrong vma extent header magic");
798 + int block_count = GUINT16_FROM_BE(ehead->block_count);
799 + int extent_size = VMA_EXTENT_HEADER_SIZE + block_count*VMA_BLOCK_SIZE;
801 + if (buf_pos < extent_size) {
802 + error_setg(errp, "short vma extent (%d < %d)", buf_pos,
807 + if (restore_extent(vmar, buf, extent_size, vmstate_fd, verbose,
812 + if (buf_pos > extent_size) {
813 + memmove(buf, buf + extent_size, buf_pos - extent_size);
814 + buf_pos = buf_pos - extent_size;
823 + for (i = 1; i < 256; i++) {
824 + VmaRestoreState *rstate = &vmar->rstate[i];
829 + if (bdrv_flush(rstate->bs) < 0) {
830 + error_setg(errp, "vma bdrv_flush %s failed",
831 + vmar->devinfo[i].devname);
835 + if (vmar->devinfo[i].size &&
836 + (strcmp(vmar->devinfo[i].devname, "vmstate") != 0)) {
837 + assert(rstate->bitmap);
839 + int64_t cluster_num, end;
841 + end = (vmar->devinfo[i].size + VMA_CLUSTER_SIZE - 1) /
844 + for (cluster_num = 0; cluster_num < end; cluster_num++) {
845 + if (!vma_reader_get_bitmap(rstate, cluster_num)) {
846 + error_setg(errp, "detected missing cluster %zd "
847 + "for stream %s", cluster_num,
848 + vmar->devinfo[i].devname);
858 diff --git a/vma-writer.c b/vma-writer.c
860 index 0000000..b0cf529
865 + * VMA: Virtual Machine Archive
867 + * Copyright (C) 2012 Proxmox Server Solutions
870 + * Dietmar Maurer (dietmar@proxmox.com)
872 + * This work is licensed under the terms of the GNU GPL, version 2 or later.
873 + * See the COPYING file in the top-level directory.
877 +#include "qemu/osdep.h"
879 +#include <uuid/uuid.h>
882 +#include "block/block.h"
883 +#include "monitor/monitor.h"
884 +#include "qemu/main-loop.h"
885 +#include "qemu/coroutine.h"
886 +#include "qemu/cutils.h"
890 +#define DPRINTF(fmt, ...)\
891 + do { if (DEBUG_VMA) { printf("vma: " fmt, ## __VA_ARGS__); } } while (0)
893 +#define WRITE_BUFFERS 5
895 +typedef struct VmaAIOCB VmaAIOCB;
897 + unsigned char buffer[VMA_MAX_EXTENT_SIZE];
909 + bool header_written;
912 + /* we always write extents */
913 + unsigned char outbuf[VMA_MAX_EXTENT_SIZE];
914 + int outbuf_pos; /* in bytes */
915 + int outbuf_count; /* in VMA_BLOCKS */
916 + uint64_t outbuf_block_info[VMA_BLOCKS_PER_EXTENT];
918 + VmaAIOCB *aiocbs[WRITE_BUFFERS];
921 + GChecksum *md5csum;
922 + CoMutex writer_lock;
923 + CoMutex flush_lock;
924 + Coroutine *co_writer;
926 + /* drive informations */
927 + VmaStreamInfo stream_info[256];
928 + guint stream_count;
930 + guint8 vmstate_stream;
931 + uint32_t vmstate_clusters;
933 + /* header blob table */
934 + char *header_blob_table;
935 + uint32_t header_blob_table_size;
936 + uint32_t header_blob_table_pos;
938 + /* store for config blobs */
939 + uint32_t config_names[VMA_MAX_CONFIGS]; /* offset into blob_buffer table */
940 + uint32_t config_data[VMA_MAX_CONFIGS]; /* offset into blob_buffer table */
941 + uint32_t config_count;
944 +void vma_writer_set_error(VmaWriter *vmaw, const char *fmt, ...)
948 + if (vmaw->status < 0) {
955 + g_vsnprintf(vmaw->errmsg, sizeof(vmaw->errmsg), fmt, ap);
958 + DPRINTF("vma_writer_set_error: %s\n", vmaw->errmsg);
961 +static uint32_t allocate_header_blob(VmaWriter *vmaw, const char *data,
968 + if (!vmaw->header_blob_table ||
969 + (vmaw->header_blob_table_size <
970 + (vmaw->header_blob_table_pos + len + 2))) {
971 + int newsize = vmaw->header_blob_table_size + ((len + 2 + 511)/512)*512;
973 + vmaw->header_blob_table = g_realloc(vmaw->header_blob_table, newsize);
974 + memset(vmaw->header_blob_table + vmaw->header_blob_table_size,
975 + 0, newsize - vmaw->header_blob_table_size);
976 + vmaw->header_blob_table_size = newsize;
979 + uint32_t cpos = vmaw->header_blob_table_pos;
980 + vmaw->header_blob_table[cpos] = len & 255;
981 + vmaw->header_blob_table[cpos+1] = (len >> 8) & 255;
982 + memcpy(vmaw->header_blob_table + cpos + 2, data, len);
983 + vmaw->header_blob_table_pos += len + 2;
987 +static uint32_t allocate_header_string(VmaWriter *vmaw, const char *str)
991 + size_t len = strlen(str) + 1;
993 + return allocate_header_blob(vmaw, str, len);
996 +int vma_writer_add_config(VmaWriter *vmaw, const char *name, gpointer data,
1000 + assert(!vmaw->header_written);
1001 + assert(vmaw->config_count < VMA_MAX_CONFIGS);
1006 + gchar *basename = g_path_get_basename(name);
1007 + uint32_t name_ptr = allocate_header_string(vmaw, basename);
1014 + uint32_t data_ptr = allocate_header_blob(vmaw, data, len);
1019 + vmaw->config_names[vmaw->config_count] = name_ptr;
1020 + vmaw->config_data[vmaw->config_count] = data_ptr;
1022 + vmaw->config_count++;
1027 +int vma_writer_register_stream(VmaWriter *vmaw, const char *devname,
1032 + assert(!vmaw->status);
1034 + if (vmaw->header_written) {
1035 + vma_writer_set_error(vmaw, "vma_writer_register_stream: header "
1036 + "already written");
1040 + guint n = vmaw->stream_count + 1;
1042 + /* we can have dev_ids form 1 to 255 (0 reserved)
1043 + * 255(-1) reseverd for safety
1046 + vma_writer_set_error(vmaw, "vma_writer_register_stream: "
1047 + "too many drives");
1052 + vma_writer_set_error(vmaw, "vma_writer_register_stream: "
1053 + "got strange size %zd", size);
1057 + DPRINTF("vma_writer_register_stream %s %zu %d\n", devname, size, n);
1059 + vmaw->stream_info[n].devname = g_strdup(devname);
1060 + vmaw->stream_info[n].size = size;
1062 + vmaw->stream_info[n].cluster_count = (size + VMA_CLUSTER_SIZE - 1) /
1065 + vmaw->stream_count = n;
1067 + if (strcmp(devname, "vmstate") == 0) {
1068 + vmaw->vmstate_stream = n;
1074 +static void vma_co_continue_write(void *opaque)
1076 + VmaWriter *vmaw = opaque;
1078 + DPRINTF("vma_co_continue_write\n");
1079 + qemu_coroutine_enter(vmaw->co_writer);
1082 +static ssize_t coroutine_fn
1083 +vma_co_write(VmaWriter *vmaw, const void *buf, size_t bytes)
1088 + /* atomic writes (we cannot interleave writes) */
1089 + qemu_co_mutex_lock(&vmaw->writer_lock);
1091 + DPRINTF("vma_co_write enter %zd\n", bytes);
1093 + assert(vmaw->co_writer == NULL);
1095 + vmaw->co_writer = qemu_coroutine_self();
1097 + aio_set_fd_handler(qemu_get_aio_context(), vmaw->fd, false, NULL, vma_co_continue_write, vmaw);
1099 + DPRINTF("vma_co_write wait until writable\n");
1100 + qemu_coroutine_yield();
1101 + DPRINTF("vma_co_write starting %zd\n", bytes);
1103 + while (done < bytes) {
1104 + ret = write(vmaw->fd, buf + done, bytes - done);
1107 + DPRINTF("vma_co_write written %zd %zd\n", done, ret);
1108 + } else if (ret < 0) {
1109 + if (errno == EAGAIN || errno == EWOULDBLOCK) {
1110 + DPRINTF("vma_co_write yield %zd\n", done);
1111 + qemu_coroutine_yield();
1112 + DPRINTF("vma_co_write restart %zd\n", done);
1114 + vma_writer_set_error(vmaw, "vma_co_write write error - %s",
1115 + g_strerror(errno));
1116 + done = -1; /* always return failure for partial writes */
1119 + } else if (ret == 0) {
1120 + /* should not happen - simply try again */
1124 + aio_set_fd_handler(qemu_get_aio_context(), vmaw->fd, false, NULL, NULL, NULL);
1126 + vmaw->co_writer = NULL;
1128 + qemu_co_mutex_unlock(&vmaw->writer_lock);
1130 + DPRINTF("vma_co_write leave %zd\n", done);
1134 +static void coroutine_fn vma_co_writer_task(void *opaque)
1136 + VmaAIOCB *cb = opaque;
1138 + DPRINTF("vma_co_writer_task start\n");
1140 + int64_t done = vma_co_write(cb->vmaw, cb->buffer, cb->bytes);
1141 + DPRINTF("vma_co_writer_task write done %zd\n", done);
1143 + if (done != cb->bytes) {
1144 + DPRINTF("vma_co_writer_task failed write %zd %zd", cb->bytes, done);
1145 + vma_writer_set_error(cb->vmaw, "vma_co_writer_task failed write %zd",
1151 + qemu_co_queue_next(&cb->vmaw->wqueue);
1153 + DPRINTF("vma_co_writer_task end\n");
1156 +static void coroutine_fn vma_queue_flush(VmaWriter *vmaw)
1158 + DPRINTF("vma_queue_flush enter\n");
1164 + VmaAIOCB *cb = NULL;
1165 + for (i = 0; i < WRITE_BUFFERS; i++) {
1166 + if (vmaw->aiocbs[i]->bytes) {
1167 + cb = vmaw->aiocbs[i];
1168 + DPRINTF("FOUND USED AIO BUFFER %d %zd\n", i,
1169 + vmaw->aiocbs[i]->bytes);
1176 + qemu_co_queue_wait(&vmaw->wqueue);
1179 + DPRINTF("vma_queue_flush leave\n");
1183 + * NOTE: pipe buffer size in only 4096 bytes on linux (see 'ulimit -a')
1184 + * So we need to create a coroutione to allow 'parallel' execution.
1186 +static ssize_t coroutine_fn
1187 +vma_queue_write(VmaWriter *vmaw, const void *buf, size_t bytes)
1189 + DPRINTF("vma_queue_write enter %zd\n", bytes);
1193 + assert(bytes <= VMA_MAX_EXTENT_SIZE);
1195 + VmaAIOCB *cb = NULL;
1198 + for (i = 0; i < WRITE_BUFFERS; i++) {
1199 + if (!vmaw->aiocbs[i]->bytes) {
1200 + cb = vmaw->aiocbs[i];
1205 + qemu_co_queue_wait(&vmaw->wqueue);
1209 + memcpy(cb->buffer, buf, bytes);
1210 + cb->bytes = bytes;
1213 + DPRINTF("vma_queue_write start %zd\n", bytes);
1214 + cb->co = qemu_coroutine_create(vma_co_writer_task);
1215 + qemu_coroutine_enter(cb->co, cb);
1217 + DPRINTF("vma_queue_write leave\n");
1222 +VmaWriter *vma_writer_create(const char *filename, uuid_t uuid, Error **errp)
1226 + assert(sizeof(VmaHeader) == (4096 + 8192));
1227 + assert(G_STRUCT_OFFSET(VmaHeader, config_names) == 2044);
1228 + assert(G_STRUCT_OFFSET(VmaHeader, config_data) == 3068);
1229 + assert(G_STRUCT_OFFSET(VmaHeader, dev_info) == 4096);
1230 + assert(sizeof(VmaExtentHeader) == 512);
1232 + VmaWriter *vmaw = g_new0(VmaWriter, 1);
1235 + vmaw->md5csum = g_checksum_new(G_CHECKSUM_MD5);
1236 + if (!vmaw->md5csum) {
1237 + error_setg(errp, "can't allocate cmsum\n");
1241 + if (strstart(filename, "exec:", &p)) {
1242 + vmaw->cmd = popen(p, "w");
1243 + if (vmaw->cmd == NULL) {
1244 + error_setg(errp, "can't popen command '%s' - %s\n", p,
1245 + g_strerror(errno));
1248 + vmaw->fd = fileno(vmaw->cmd);
1250 + /* try to use O_NONBLOCK and O_DIRECT */
1251 + fcntl(vmaw->fd, F_SETFL, fcntl(vmaw->fd, F_GETFL)|O_NONBLOCK);
1252 + fcntl(vmaw->fd, F_SETFL, fcntl(vmaw->fd, F_GETFL)|O_DIRECT);
1257 + const char *tmp_id_str;
1259 + if ((stat(filename, &st) == 0) && S_ISFIFO(st.st_mode)) {
1260 + oflags = O_NONBLOCK|O_DIRECT|O_WRONLY;
1261 + vmaw->fd = qemu_open(filename, oflags, 0644);
1262 + } else if (strstart(filename, "/dev/fdset/", &tmp_id_str)) {
1263 + oflags = O_NONBLOCK|O_DIRECT|O_WRONLY;
1264 + vmaw->fd = qemu_open(filename, oflags, 0644);
1265 + } else if (strstart(filename, "/dev/fdname/", &tmp_id_str)) {
1266 + vmaw->fd = monitor_get_fd(cur_mon, tmp_id_str, errp);
1267 + if (vmaw->fd < 0) {
1270 + /* try to use O_NONBLOCK and O_DIRECT */
1271 + fcntl(vmaw->fd, F_SETFL, fcntl(vmaw->fd, F_GETFL)|O_NONBLOCK);
1272 + fcntl(vmaw->fd, F_SETFL, fcntl(vmaw->fd, F_GETFL)|O_DIRECT);
1274 + oflags = O_NONBLOCK|O_DIRECT|O_WRONLY|O_CREAT|O_EXCL;
1275 + vmaw->fd = qemu_open(filename, oflags, 0644);
1278 + if (vmaw->fd < 0) {
1279 + error_setg(errp, "can't open file %s - %s\n", filename,
1280 + g_strerror(errno));
1285 + /* we use O_DIRECT, so we need to align IO buffers */
1287 + for (i = 0; i < WRITE_BUFFERS; i++) {
1288 + vmaw->aiocbs[i] = qemu_memalign(512, sizeof(VmaAIOCB));
1289 + memset(vmaw->aiocbs[i], 0, sizeof(VmaAIOCB));
1292 + vmaw->outbuf_count = 0;
1293 + vmaw->outbuf_pos = VMA_EXTENT_HEADER_SIZE;
1295 + vmaw->header_blob_table_pos = 1; /* start at pos 1 */
1297 + qemu_co_mutex_init(&vmaw->writer_lock);
1298 + qemu_co_mutex_init(&vmaw->flush_lock);
1299 + qemu_co_queue_init(&vmaw->wqueue);
1301 + uuid_copy(vmaw->uuid, uuid);
1308 + pclose(vmaw->cmd);
1309 + } else if (vmaw->fd >= 0) {
1313 + if (vmaw->md5csum) {
1314 + g_checksum_free(vmaw->md5csum);
1323 +static int coroutine_fn vma_write_header(VmaWriter *vmaw)
1326 + int header_clusters = 8;
1327 + char buf[65536*header_clusters];
1328 + VmaHeader *head = (VmaHeader *)buf;
1332 + DPRINTF("VMA WRITE HEADER\n");
1334 + if (vmaw->status < 0) {
1335 + return vmaw->status;
1338 + memset(buf, 0, sizeof(buf));
1340 + head->magic = VMA_MAGIC;
1341 + head->version = GUINT32_TO_BE(1); /* v1 */
1342 + memcpy(head->uuid, vmaw->uuid, 16);
1344 + time_t ctime = time(NULL);
1345 + head->ctime = GUINT64_TO_BE(ctime);
1347 + if (!vmaw->stream_count) {
1351 + for (i = 0; i < VMA_MAX_CONFIGS; i++) {
1352 + head->config_names[i] = GUINT32_TO_BE(vmaw->config_names[i]);
1353 + head->config_data[i] = GUINT32_TO_BE(vmaw->config_data[i]);
1356 + /* 32 bytes per device (12 used currently) = 8192 bytes max */
1357 + for (i = 1; i <= 254; i++) {
1358 + VmaStreamInfo *si = &vmaw->stream_info[i];
1360 + assert(si->devname);
1361 + uint32_t devname_ptr = allocate_header_string(vmaw, si->devname);
1362 + if (!devname_ptr) {
1365 + head->dev_info[i].devname_ptr = GUINT32_TO_BE(devname_ptr);
1366 + head->dev_info[i].size = GUINT64_TO_BE(si->size);
1370 + uint32_t header_size = sizeof(VmaHeader) + vmaw->header_blob_table_size;
1371 + head->header_size = GUINT32_TO_BE(header_size);
1373 + if (header_size > sizeof(buf)) {
1374 + return -1; /* just to be sure */
1377 + uint32_t blob_buffer_offset = sizeof(VmaHeader);
1378 + memcpy(buf + blob_buffer_offset, vmaw->header_blob_table,
1379 + vmaw->header_blob_table_size);
1380 + head->blob_buffer_offset = GUINT32_TO_BE(blob_buffer_offset);
1381 + head->blob_buffer_size = GUINT32_TO_BE(vmaw->header_blob_table_pos);
1383 + g_checksum_reset(vmaw->md5csum);
1384 + g_checksum_update(vmaw->md5csum, (const guchar *)buf, header_size);
1386 + g_checksum_get_digest(vmaw->md5csum, (guint8 *)(head->md5sum), &csize);
1388 + return vma_queue_write(vmaw, buf, header_size);
1391 +static int coroutine_fn vma_writer_flush(VmaWriter *vmaw)
1398 + if (vmaw->status < 0) {
1399 + return vmaw->status;
1402 + if (!vmaw->header_written) {
1403 + vmaw->header_written = true;
1404 + ret = vma_write_header(vmaw);
1406 + vma_writer_set_error(vmaw, "vma_writer_flush: write header failed");
1411 + DPRINTF("VMA WRITE FLUSH %d %d\n", vmaw->outbuf_count, vmaw->outbuf_pos);
1414 + VmaExtentHeader *ehead = (VmaExtentHeader *)vmaw->outbuf;
1416 + ehead->magic = VMA_EXTENT_MAGIC;
1417 + ehead->reserved1 = 0;
1419 + for (i = 0; i < VMA_BLOCKS_PER_EXTENT; i++) {
1420 + ehead->blockinfo[i] = GUINT64_TO_BE(vmaw->outbuf_block_info[i]);
1423 + guint16 block_count = (vmaw->outbuf_pos - VMA_EXTENT_HEADER_SIZE) /
1426 + ehead->block_count = GUINT16_TO_BE(block_count);
1428 + memcpy(ehead->uuid, vmaw->uuid, sizeof(ehead->uuid));
1429 + memset(ehead->md5sum, 0, sizeof(ehead->md5sum));
1431 + g_checksum_reset(vmaw->md5csum);
1432 + g_checksum_update(vmaw->md5csum, vmaw->outbuf, VMA_EXTENT_HEADER_SIZE);
1434 + g_checksum_get_digest(vmaw->md5csum, ehead->md5sum, &csize);
1436 + int bytes = vmaw->outbuf_pos;
1437 + ret = vma_queue_write(vmaw, vmaw->outbuf, bytes);
1438 + if (ret != bytes) {
1439 + vma_writer_set_error(vmaw, "vma_writer_flush: failed write");
1442 + vmaw->outbuf_count = 0;
1443 + vmaw->outbuf_pos = VMA_EXTENT_HEADER_SIZE;
1445 + for (i = 0; i < VMA_BLOCKS_PER_EXTENT; i++) {
1446 + vmaw->outbuf_block_info[i] = 0;
1449 + return vmaw->status;
1452 +static int vma_count_open_streams(VmaWriter *vmaw)
1454 + g_assert(vmaw != NULL);
1457 + int open_drives = 0;
1458 + for (i = 0; i <= 255; i++) {
1459 + if (vmaw->stream_info[i].size && !vmaw->stream_info[i].finished) {
1464 + return open_drives;
1468 + * all jobs should call this when there is no more data
1469 + * Returns: number of remaining stream (0 ==> finished)
1472 +vma_writer_close_stream(VmaWriter *vmaw, uint8_t dev_id)
1474 + g_assert(vmaw != NULL);
1476 + DPRINTF("vma_writer_set_status %d\n", dev_id);
1477 + if (!vmaw->stream_info[dev_id].size) {
1478 + vma_writer_set_error(vmaw, "vma_writer_close_stream: "
1479 + "no such stream %d", dev_id);
1482 + if (vmaw->stream_info[dev_id].finished) {
1483 + vma_writer_set_error(vmaw, "vma_writer_close_stream: "
1484 + "stream already closed %d", dev_id);
1488 + vmaw->stream_info[dev_id].finished = true;
1490 + int open_drives = vma_count_open_streams(vmaw);
1492 + if (open_drives <= 0) {
1493 + DPRINTF("vma_writer_set_status all drives completed\n");
1494 + qemu_co_mutex_lock(&vmaw->flush_lock);
1495 + int ret = vma_writer_flush(vmaw);
1496 + qemu_co_mutex_unlock(&vmaw->flush_lock);
1498 + vma_writer_set_error(vmaw, "vma_writer_close_stream: flush failed");
1502 + return open_drives;
1505 +int vma_writer_get_status(VmaWriter *vmaw, VmaStatus *status)
1509 + g_assert(vmaw != NULL);
1512 + status->status = vmaw->status;
1513 + g_strlcpy(status->errmsg, vmaw->errmsg, sizeof(status->errmsg));
1514 + for (i = 0; i <= 255; i++) {
1515 + status->stream_info[i] = vmaw->stream_info[i];
1518 + uuid_unparse_lower(vmaw->uuid, status->uuid_str);
1521 + status->closed = vmaw->closed;
1523 + return vmaw->status;
1526 +static int vma_writer_get_buffer(VmaWriter *vmaw)
1530 + qemu_co_mutex_lock(&vmaw->flush_lock);
1532 + /* wait until buffer is available */
1533 + while (vmaw->outbuf_count >= (VMA_BLOCKS_PER_EXTENT - 1)) {
1534 + ret = vma_writer_flush(vmaw);
1536 + vma_writer_set_error(vmaw, "vma_writer_get_buffer: flush failed");
1541 + qemu_co_mutex_unlock(&vmaw->flush_lock);
1547 +int64_t coroutine_fn
1548 +vma_writer_write(VmaWriter *vmaw, uint8_t dev_id, int64_t cluster_num,
1549 + unsigned char *buf, size_t *zero_bytes)
1551 + g_assert(vmaw != NULL);
1552 + g_assert(zero_bytes != NULL);
1556 + if (vmaw->status < 0) {
1557 + return vmaw->status;
1560 + if (!dev_id || !vmaw->stream_info[dev_id].size) {
1561 + vma_writer_set_error(vmaw, "vma_writer_write: "
1562 + "no such stream %d", dev_id);
1566 + if (vmaw->stream_info[dev_id].finished) {
1567 + vma_writer_set_error(vmaw, "vma_writer_write: "
1568 + "stream already closed %d", dev_id);
1573 + if (cluster_num >= (((uint64_t)1)<<32)) {
1574 + vma_writer_set_error(vmaw, "vma_writer_write: "
1575 + "cluster number out of range");
1579 + if (dev_id == vmaw->vmstate_stream) {
1580 + if (cluster_num != vmaw->vmstate_clusters) {
1581 + vma_writer_set_error(vmaw, "vma_writer_write: "
1582 + "non sequential vmstate write");
1584 + vmaw->vmstate_clusters++;
1585 + } else if (cluster_num >= vmaw->stream_info[dev_id].cluster_count) {
1586 + vma_writer_set_error(vmaw, "vma_writer_write: cluster number too big");
1590 + /* wait until buffer is available */
1591 + if (vma_writer_get_buffer(vmaw) < 0) {
1592 + vma_writer_set_error(vmaw, "vma_writer_write: "
1593 + "vma_writer_get_buffer failed");
1597 + DPRINTF("VMA WRITE %d %zd\n", dev_id, cluster_num);
1599 + uint16_t mask = 0;
1604 + for (i = 0; i < 16; i++) {
1605 + unsigned char *vmablock = buf + (i*VMA_BLOCK_SIZE);
1606 + if (!buffer_is_zero(vmablock, VMA_BLOCK_SIZE)) {
1608 + memcpy(vmaw->outbuf + vmaw->outbuf_pos, vmablock,
1610 + vmaw->outbuf_pos += VMA_BLOCK_SIZE;
1612 + DPRINTF("VMA WRITE %zd ZERO BLOCK %d\n", cluster_num, i);
1613 + vmaw->stream_info[dev_id].zero_bytes += VMA_BLOCK_SIZE;
1614 + *zero_bytes += VMA_BLOCK_SIZE;
1620 + DPRINTF("VMA WRITE %zd ZERO CLUSTER\n", cluster_num);
1621 + vmaw->stream_info[dev_id].zero_bytes += VMA_CLUSTER_SIZE;
1622 + *zero_bytes += VMA_CLUSTER_SIZE;
1625 + uint64_t block_info = ((uint64_t)mask) << (32+16);
1626 + block_info |= ((uint64_t)dev_id) << 32;
1627 + block_info |= (cluster_num & 0xffffffff);
1628 + vmaw->outbuf_block_info[vmaw->outbuf_count] = block_info;
1630 + DPRINTF("VMA WRITE MASK %zd %zx\n", cluster_num, block_info);
1632 + vmaw->outbuf_count++;
1634 + /** NOTE: We allways write whole clusters, but we correctly set
1635 + * transferred bytes. So transferred == size when when everything
1638 + size_t transferred = VMA_CLUSTER_SIZE;
1640 + if (dev_id != vmaw->vmstate_stream) {
1641 + uint64_t last = (cluster_num + 1) * VMA_CLUSTER_SIZE;
1642 + if (last > vmaw->stream_info[dev_id].size) {
1643 + uint64_t diff = last - vmaw->stream_info[dev_id].size;
1644 + if (diff >= VMA_CLUSTER_SIZE) {
1645 + vma_writer_set_error(vmaw, "vma_writer_write: "
1646 + "read after last cluster");
1649 + transferred -= diff;
1653 + vmaw->stream_info[dev_id].transferred += transferred;
1655 + return transferred;
1658 +int vma_writer_close(VmaWriter *vmaw, Error **errp)
1660 + g_assert(vmaw != NULL);
1664 + vma_queue_flush(vmaw);
1666 + /* this should not happen - just to be sure */
1667 + while (!qemu_co_queue_empty(&vmaw->wqueue)) {
1668 + DPRINTF("vma_writer_close wait\n");
1669 + co_aio_sleep_ns(qemu_get_aio_context(), QEMU_CLOCK_REALTIME, 1000000);
1673 + if (pclose(vmaw->cmd) < 0) {
1674 + vma_writer_set_error(vmaw, "vma_writer_close: "
1675 + "pclose failed - %s", g_strerror(errno));
1678 + if (close(vmaw->fd) < 0) {
1679 + vma_writer_set_error(vmaw, "vma_writer_close: "
1680 + "close failed - %s", g_strerror(errno));
1684 + for (i = 0; i <= 255; i++) {
1685 + VmaStreamInfo *si = &vmaw->stream_info[i];
1687 + if (!si->finished) {
1688 + vma_writer_set_error(vmaw, "vma_writer_close: "
1689 + "detected open stream '%s'", si->devname);
1690 + } else if ((si->transferred != si->size) &&
1691 + (i != vmaw->vmstate_stream)) {
1692 + vma_writer_set_error(vmaw, "vma_writer_close: "
1693 + "incomplete stream '%s' (%zd != %zd)",
1694 + si->devname, si->transferred, si->size);
1699 + for (i = 0; i <= 255; i++) {
1700 + vmaw->stream_info[i].finished = 1; /* mark as closed */
1705 + if (vmaw->status < 0 && *errp == NULL) {
1706 + error_setg(errp, "%s", vmaw->errmsg);
1709 + return vmaw->status;
1712 +void vma_writer_destroy(VmaWriter *vmaw)
1718 + for (i = 0; i <= 255; i++) {
1719 + if (vmaw->stream_info[i].devname) {
1720 + g_free(vmaw->stream_info[i].devname);
1724 + if (vmaw->md5csum) {
1725 + g_checksum_free(vmaw->md5csum);
1728 + for (i = 0; i < WRITE_BUFFERS; i++) {
1729 + free(vmaw->aiocbs[i]);
1734 diff --git a/vma.c b/vma.c
1735 new file mode 100644
1736 index 0000000..8014090
1741 + * VMA: Virtual Machine Archive
1743 + * Copyright (C) 2012-2013 Proxmox Server Solutions
1746 + * Dietmar Maurer (dietmar@proxmox.com)
1748 + * This work is licensed under the terms of the GNU GPL, version 2 or later.
1749 + * See the COPYING file in the top-level directory.
1753 +#include "qemu/osdep.h"
1757 +#include "qemu-common.h"
1758 +#include "qemu/error-report.h"
1759 +#include "qemu/main-loop.h"
1760 +#include "sysemu/char.h" /* qstring_from_str */
1762 +static void help(void)
1764 + const char *help_msg =
1765 + "usage: vma command [command options]\n"
1767 + "vma list <filename>\n"
1768 + "vma create <filename> [-c config] <archive> pathname ...\n"
1769 + "vma extract <filename> [-r <fifo>] <targetdir>\n"
1772 + printf("%s", help_msg);
1776 +static const char *extract_devname(const char *path, char **devname, int index)
1780 + const char *sep = strchr(path, '=');
1783 + *devname = g_strndup(path, sep - path);
1787 + *devname = g_strdup_printf("disk%d", index);
1796 +static void print_content(VmaReader *vmar)
1800 + VmaHeader *head = vma_reader_get_header(vmar);
1802 + GList *l = vma_reader_get_config_data(vmar);
1803 + while (l && l->data) {
1804 + VmaConfigData *cdata = (VmaConfigData *)l->data;
1805 + l = g_list_next(l);
1806 + printf("CFG: size: %d name: %s\n", cdata->len, cdata->name);
1810 + VmaDeviceInfo *di;
1811 + for (i = 1; i < 255; i++) {
1812 + di = vma_reader_get_device_info(vmar, i);
1814 + if (strcmp(di->devname, "vmstate") == 0) {
1815 + printf("VMSTATE: dev_id=%d memory: %zd\n", i, di->size);
1817 + printf("DEV: dev_id=%d size: %zd devname: %s\n",
1818 + i, di->size, di->devname);
1822 + /* ctime is the last entry we print */
1823 + printf("CTIME: %s", ctime(&head->ctime));
1827 +static int list_content(int argc, char **argv)
1830 + const char *filename;
1833 + c = getopt(argc, argv, "h");
1843 + g_assert_not_reached();
1847 + /* Get the filename */
1848 + if ((optind + 1) != argc) {
1851 + filename = argv[optind++];
1853 + Error *errp = NULL;
1854 + VmaReader *vmar = vma_reader_create(filename, &errp);
1857 + g_error("%s", error_get_pretty(errp));
1860 + print_content(vmar);
1862 + vma_reader_destroy(vmar);
1867 +typedef struct RestoreMap {
1873 +static int extract_content(int argc, char **argv)
1877 + const char *filename;
1878 + const char *dirname;
1879 + const char *readmap = NULL;
1882 + c = getopt(argc, argv, "hvr:");
1902 + /* Get the filename */
1903 + if ((optind + 2) != argc) {
1906 + filename = argv[optind++];
1907 + dirname = argv[optind++];
1909 + Error *errp = NULL;
1910 + VmaReader *vmar = vma_reader_create(filename, &errp);
1913 + g_error("%s", error_get_pretty(errp));
1916 + if (mkdir(dirname, 0777) < 0) {
1917 + g_error("unable to create target directory %s - %s",
1918 + dirname, g_strerror(errno));
1921 + GList *l = vma_reader_get_config_data(vmar);
1922 + while (l && l->data) {
1923 + VmaConfigData *cdata = (VmaConfigData *)l->data;
1924 + l = g_list_next(l);
1925 + char *cfgfn = g_strdup_printf("%s/%s", dirname, cdata->name);
1926 + GError *err = NULL;
1927 + if (!g_file_set_contents(cfgfn, (gchar *)cdata->data, cdata->len,
1929 + g_error("unable to write file: %s", err->message);
1933 + GHashTable *devmap = g_hash_table_new(g_str_hash, g_str_equal);
1936 + print_content(vmar);
1938 + FILE *map = fopen(readmap, "r");
1940 + g_error("unable to open fifo %s - %s", readmap, g_strerror(errno));
1945 + char *line = fgets(inbuf, sizeof(inbuf), map);
1946 + if (!line || line[0] == '\0' || !strcmp(line, "done\n")) {
1949 + int len = strlen(line);
1950 + if (line[len - 1] == '\n') {
1951 + line[len - 1] = '\0';
1959 + if (line[0] == '0' && line[1] == ':') {
1961 + write_zero = false;
1962 + } else if (line[0] == '1' && line[1] == ':') {
1964 + write_zero = true;
1966 + g_error("read map failed - parse error ('%s')", inbuf);
1969 + char *devname = NULL;
1970 + path = extract_devname(path, &devname, -1);
1972 + g_error("read map failed - no dev name specified ('%s')",
1976 + RestoreMap *map = g_new0(RestoreMap, 1);
1977 + map->devname = g_strdup(devname);
1978 + map->path = g_strdup(path);
1979 + map->write_zero = write_zero;
1981 + g_hash_table_insert(devmap, map->devname, map);
1987 + int vmstate_fd = -1;
1988 + guint8 vmstate_stream = 0;
1990 + for (i = 1; i < 255; i++) {
1991 + VmaDeviceInfo *di = vma_reader_get_device_info(vmar, i);
1992 + if (di && (strcmp(di->devname, "vmstate") == 0)) {
1993 + vmstate_stream = i;
1994 + char *statefn = g_strdup_printf("%s/vmstate.bin", dirname);
1995 + vmstate_fd = open(statefn, O_WRONLY|O_CREAT|O_EXCL, 0644);
1996 + if (vmstate_fd < 0) {
1997 + g_error("create vmstate file '%s' failed - %s", statefn,
1998 + g_strerror(errno));
2002 + char *devfn = NULL;
2003 + int flags = BDRV_O_RDWR|BDRV_O_CACHE_WB;
2004 + bool write_zero = true;
2008 + map = (RestoreMap *)g_hash_table_lookup(devmap, di->devname);
2009 + if (map == NULL) {
2010 + g_error("no device name mapping for %s", di->devname);
2012 + devfn = map->path;
2013 + write_zero = map->write_zero;
2015 + devfn = g_strdup_printf("%s/tmp-disk-%s.raw",
2016 + dirname, di->devname);
2017 + printf("DEVINFO %s %zd\n", devfn, di->size);
2019 + bdrv_img_create(devfn, "raw", NULL, NULL, NULL, di->size,
2022 + g_error("can't create file %s: %s", devfn,
2023 + error_get_pretty(errp));
2026 + /* Note: we created an empty file above, so there is no
2027 + * need to write zeroes (so we generate a sparse file)
2029 + write_zero = false;
2032 + BlockDriverState *bs = bdrv_new();
2033 + if (errp || bdrv_open(&bs, devfn, NULL, NULL, flags, &errp)) {
2034 + g_error("can't open file %s - %s", devfn,
2035 + error_get_pretty(errp));
2037 + if (vma_reader_register_bs(vmar, i, bs, write_zero, &errp) < 0) {
2038 + g_error("%s", error_get_pretty(errp));
2047 + if (vma_reader_restore(vmar, vmstate_fd, verbose, &errp) < 0) {
2048 + g_error("restore failed - %s", error_get_pretty(errp));
2052 + for (i = 1; i < 255; i++) {
2053 + VmaDeviceInfo *di = vma_reader_get_device_info(vmar, i);
2054 + if (di && (i != vmstate_stream)) {
2055 + char *tmpfn = g_strdup_printf("%s/tmp-disk-%s.raw",
2056 + dirname, di->devname);
2057 + char *fn = g_strdup_printf("%s/disk-%s.raw",
2058 + dirname, di->devname);
2059 + if (rename(tmpfn, fn) != 0) {
2060 + g_error("rename %s to %s failed - %s",
2061 + tmpfn, fn, g_strerror(errno));
2067 + vma_reader_destroy(vmar);
2074 +typedef struct BackupJob {
2075 + BlockDriverState *bs;
2081 +#define BACKUP_SECTORS_PER_CLUSTER (VMA_CLUSTER_SIZE / BDRV_SECTOR_SIZE)
2083 +static void coroutine_fn backup_run(void *opaque)
2085 + BackupJob *job = (BackupJob *)opaque;
2087 + QEMUIOVector qiov;
2089 + int64_t start, end;
2092 + unsigned char *buf = qemu_blockalign(job->bs, VMA_CLUSTER_SIZE);
2095 + end = DIV_ROUND_UP(job->len / BDRV_SECTOR_SIZE,
2096 + BACKUP_SECTORS_PER_CLUSTER);
2098 + for (; start < end; start++) {
2099 + iov.iov_base = buf;
2100 + iov.iov_len = VMA_CLUSTER_SIZE;
2101 + qemu_iovec_init_external(&qiov, &iov, 1);
2103 + ret = bdrv_co_readv(job->bs, start * BACKUP_SECTORS_PER_CLUSTER,
2104 + BACKUP_SECTORS_PER_CLUSTER, &qiov);
2106 + vma_writer_set_error(job->vmaw, "read error", -1);
2111 + if (vma_writer_write(job->vmaw, job->dev_id, start, buf, &zb) < 0) {
2112 + vma_writer_set_error(job->vmaw, "backup_dump_cb vma_writer_write failed", -1);
2119 + if (vma_writer_close_stream(job->vmaw, job->dev_id) <= 0) {
2120 + Error *err = NULL;
2121 + if (vma_writer_close(job->vmaw, &err) != 0) {
2122 + g_warning("vma_writer_close failed %s", error_get_pretty(err));
2127 +static int create_archive(int argc, char **argv)
2131 + const char *archivename;
2132 + GList *config_files = NULL;
2135 + c = getopt(argc, argv, "hvc:");
2145 + config_files = g_list_append(config_files, optarg);
2151 + g_assert_not_reached();
2156 + /* make sure we have archive name and at least one path */
2157 + if ((optind + 2) > argc) {
2161 + archivename = argv[optind++];
2164 + uuid_generate(uuid);
2166 + Error *local_err = NULL;
2167 + VmaWriter *vmaw = vma_writer_create(archivename, uuid, &local_err);
2169 + if (vmaw == NULL) {
2170 + g_error("%s", error_get_pretty(local_err));
2173 + GList *l = config_files;
2174 + while (l && l->data) {
2175 + char *name = l->data;
2176 + char *cdata = NULL;
2178 + GError *err = NULL;
2179 + if (!g_file_get_contents(name, &cdata, &clen, &err)) {
2180 + unlink(archivename);
2181 + g_error("Unable to read file: %s", err->message);
2184 + if (vma_writer_add_config(vmaw, name, cdata, clen) != 0) {
2185 + unlink(archivename);
2186 + g_error("Unable to append config data %s (len = %zd)",
2189 + l = g_list_next(l);
2193 + while (optind < argc) {
2194 + const char *path = argv[optind++];
2195 + char *devname = NULL;
2196 + path = extract_devname(path, &devname, ind++);
2198 + Error *errp = NULL;
2199 + BlockDriverState *bs;
2201 + bs = bdrv_open(path, NULL, NULL, 0, &errp);
2203 + unlink(archivename);
2204 + g_error("bdrv_open '%s' failed - %s", path, error_get_pretty(errp));
2206 + int64_t size = bdrv_getlength(bs);
2207 + int dev_id = vma_writer_register_stream(vmaw, devname, size);
2208 + if (dev_id <= 0) {
2209 + unlink(archivename);
2210 + g_error("vma_writer_register_stream '%s' failed", devname);
2213 + BackupJob *job = g_new0(BackupJob, 1);
2217 + job->dev_id = dev_id;
2219 + Coroutine *co = qemu_coroutine_create(backup_run, job);
2220 + qemu_coroutine_enter(co);
2223 + VmaStatus vmastat;
2225 + int last_percent = -1;
2228 + main_loop_wait(false);
2229 + vma_writer_get_status(vmaw, &vmastat);
2233 + uint64_t total = 0;
2234 + uint64_t transferred = 0;
2235 + uint64_t zero_bytes = 0;
2238 + for (i = 0; i < 256; i++) {
2239 + if (vmastat.stream_info[i].size) {
2240 + total += vmastat.stream_info[i].size;
2241 + transferred += vmastat.stream_info[i].transferred;
2242 + zero_bytes += vmastat.stream_info[i].zero_bytes;
2245 + percent = (transferred*100)/total;
2246 + if (percent != last_percent) {
2247 + fprintf(stderr, "progress %d%% %zd/%zd %zd\n", percent,
2248 + transferred, total, zero_bytes);
2251 + last_percent = percent;
2255 + if (vmastat.closed) {
2259 + Coroutine *co = qemu_coroutine_create(backup_run_empty, vmaw);
2260 + qemu_coroutine_enter(co);
2262 + main_loop_wait(false);
2263 + vma_writer_get_status(vmaw, &vmastat);
2264 + if (vmastat.closed) {
2272 + vma_writer_get_status(vmaw, &vmastat);
2275 + for (i = 0; i < 256; i++) {
2276 + VmaStreamInfo *si = &vmastat.stream_info[i];
2278 + fprintf(stderr, "image %s: size=%zd zeros=%zd saved=%zd\n",
2279 + si->devname, si->size, si->zero_bytes,
2280 + si->size - si->zero_bytes);
2285 + if (vmastat.status < 0) {
2286 + unlink(archivename);
2287 + g_error("creating vma archive failed");
2293 +int main(int argc, char **argv)
2295 + const char *cmdname;
2296 + Error *main_loop_err = NULL;
2298 + error_set_progname(argv[0]);
2300 + if (qemu_init_main_loop(&main_loop_err)) {
2301 + g_error("%s", error_get_pretty(main_loop_err));
2310 + cmdname = argv[1];
2314 + if (!strcmp(cmdname, "list")) {
2315 + return list_content(argc, argv);
2316 + } else if (!strcmp(cmdname, "create")) {
2317 + return create_archive(argc, argv);
2318 + } else if (!strcmp(cmdname, "extract")) {
2319 + return extract_content(argc, argv);
2325 diff --git a/vma.h b/vma.h
2326 new file mode 100644
2327 index 0000000..6625eb9
2332 + * VMA: Virtual Machine Archive
2334 + * Copyright (C) Proxmox Server Solutions
2337 + * Dietmar Maurer (dietmar@proxmox.com)
2339 + * This work is licensed under the terms of the GNU GPL, version 2 or later.
2340 + * See the COPYING file in the top-level directory.
2344 +#ifndef BACKUP_VMA_H
2345 +#define BACKUP_VMA_H
2347 +#include <uuid/uuid.h>
2348 +#include "qapi/error.h"
2349 +#include "block/block.h"
2351 +#define VMA_BLOCK_BITS 12
2352 +#define VMA_BLOCK_SIZE (1<<VMA_BLOCK_BITS)
2353 +#define VMA_CLUSTER_BITS (VMA_BLOCK_BITS+4)
2354 +#define VMA_CLUSTER_SIZE (1<<VMA_CLUSTER_BITS)
2356 +#if VMA_CLUSTER_SIZE != 65536
2357 +#error unexpected cluster size
2360 +#define VMA_EXTENT_HEADER_SIZE 512
2361 +#define VMA_BLOCKS_PER_EXTENT 59
2362 +#define VMA_MAX_CONFIGS 256
2364 +#define VMA_MAX_EXTENT_SIZE \
2365 + (VMA_EXTENT_HEADER_SIZE+VMA_CLUSTER_SIZE*VMA_BLOCKS_PER_EXTENT)
2366 +#if VMA_MAX_EXTENT_SIZE != 3867136
2367 +#error unexpected VMA_EXTENT_SIZE
2370 +/* File Format Definitions */
2372 +#define VMA_MAGIC (GUINT32_TO_BE(('V'<<24)|('M'<<16)|('A'<<8)|0x00))
2373 +#define VMA_EXTENT_MAGIC (GUINT32_TO_BE(('V'<<24)|('M'<<16)|('A'<<8)|'E'))
2375 +typedef struct VmaDeviceInfoHeader {
2376 + uint32_t devname_ptr; /* offset into blob_buffer table */
2377 + uint32_t reserved0;
2378 + uint64_t size; /* device size in bytes */
2379 + uint64_t reserved1;
2380 + uint64_t reserved2;
2381 +} VmaDeviceInfoHeader;
2383 +typedef struct VmaHeader {
2386 + unsigned char uuid[16];
2388 + unsigned char md5sum[16];
2390 + uint32_t blob_buffer_offset;
2391 + uint32_t blob_buffer_size;
2392 + uint32_t header_size;
2394 + unsigned char reserved[1984];
2396 + uint32_t config_names[VMA_MAX_CONFIGS]; /* offset into blob_buffer table */
2397 + uint32_t config_data[VMA_MAX_CONFIGS]; /* offset into blob_buffer table */
2399 + uint32_t reserved1;
2401 + VmaDeviceInfoHeader dev_info[256];
2404 +typedef struct VmaExtentHeader {
2406 + uint16_t reserved1;
2407 + uint16_t block_count;
2408 + unsigned char uuid[16];
2409 + unsigned char md5sum[16];
2410 + uint64_t blockinfo[VMA_BLOCKS_PER_EXTENT];
2413 +/* functions/definitions to read/write vma files */
2415 +typedef struct VmaReader VmaReader;
2417 +typedef struct VmaWriter VmaWriter;
2419 +typedef struct VmaConfigData {
2425 +typedef struct VmaStreamInfo {
2427 + uint64_t cluster_count;
2428 + uint64_t transferred;
2429 + uint64_t zero_bytes;
2434 +typedef struct VmaStatus {
2437 + char errmsg[8192];
2438 + char uuid_str[37];
2439 + VmaStreamInfo stream_info[256];
2442 +typedef struct VmaDeviceInfo {
2443 + uint64_t size; /* device size in bytes */
2444 + const char *devname;
2447 +VmaWriter *vma_writer_create(const char *filename, uuid_t uuid, Error **errp);
2448 +int vma_writer_close(VmaWriter *vmaw, Error **errp);
2449 +void vma_writer_destroy(VmaWriter *vmaw);
2450 +int vma_writer_add_config(VmaWriter *vmaw, const char *name, gpointer data,
2452 +int vma_writer_register_stream(VmaWriter *vmaw, const char *devname,
2455 +int64_t coroutine_fn vma_writer_write(VmaWriter *vmaw, uint8_t dev_id,
2456 + int64_t cluster_num, unsigned char *buf,
2457 + size_t *zero_bytes);
2459 +int coroutine_fn vma_writer_close_stream(VmaWriter *vmaw, uint8_t dev_id);
2461 +int vma_writer_get_status(VmaWriter *vmaw, VmaStatus *status);
2462 +void vma_writer_set_error(VmaWriter *vmaw, const char *fmt, ...);
2465 +VmaReader *vma_reader_create(const char *filename, Error **errp);
2466 +void vma_reader_destroy(VmaReader *vmar);
2467 +VmaHeader *vma_reader_get_header(VmaReader *vmar);
2468 +GList *vma_reader_get_config_data(VmaReader *vmar);
2469 +VmaDeviceInfo *vma_reader_get_device_info(VmaReader *vmar, guint8 dev_id);
2470 +int vma_reader_register_bs(VmaReader *vmar, guint8 dev_id,
2471 + BlockDriverState *bs, bool write_zeroes,
2473 +int vma_reader_restore(VmaReader *vmar, int vmstate_fd, bool verbose,
2476 +#endif /* BACKUP_VMA_H */