tools: optional LZ4 compression of the libxenguest migration stream
v2 cover tools: optional LZ4 compression of the libxenguest migration stream
Hello,
This series adds optional LZ4 compression of the PAGE_DATA records of the libxenguest migration stream. It is off by default: a toolstack asks for it with XCFLAGS_COMPRESS_LZ4, xl with "xl migrate --compress", and it is compiled in only if a supported liblz4 is present. Based on staging at 7e020a4dd6ed (2026-10-15).
v1: https://lists.xenproject.org/archives/html/xen-devel/2026-07/msg00916.html
Main changes since v1 (details in each patch):
- No new record type: PAGE_DATA's reserved field becomes a flags field (algorithm in bits 7-0, bit 8 for a compressed pfn array, bits 31-9 must be zero). New patch 1 makes receivers reject non-zero reserved fields.
- One LZ4 frame for each record's page data (patch 9 adds a second for the pfn array), with mandatory block checksums, compressed from a staged copy of the batch rather than from the live mapping.
- A batch is sent compressed whenever that makes it smaller (v1: below 97%). The 90% cut-off is unchanged: once an iteration's total after compression is 90% or more of its total before, compression stops for the rest of the save.
- xl marks compressed streams with a mandatory flag, so an older xl refuses them before creating the domain (new patch 8).
- New patch 9 compresses each record's pfn array too, as discussed in v1, so the whole record body apart from count and flags is compressed. It saves a little: 0.33% of the page data bytes on a compressible guest.
Notes for reviewers:
- Patches 1-2 check PAGE_DATA's reserved field and use it to extend the record in place. To allow this, they amend two general rules of the stream spec: reserved fields are ignored on restore, and a record type is extended only by adding a new one. An old receiver rejects an LZ4 record rather than misreading it: with patch 1, at the reserved-field check; without it, at its PAGE_DATA checks, at the latest the length check.
- Patch 9 keeps the pfn array in plaintext when the compressed record would have a valid uncompressed length. This only protects receivers without patch 1, and can be removed once none of those remain.
- 64KB interleaved staging (compressing each 64KB as it is copied), suggested on v1, was measured and not taken. It needs 64KB LZ4 blocks, and in a dom0 benchmark it compressed 25-124% slower than this series' staging with 4MB blocks, on EPYC 9354 and Xeon Gold 6430 with 0%, 50%, 90% and 100% random data.
Performance: wall time of the whole command, mean of 2-6 runs, and change against no compression. Ten Windows VMs of 64 GiB evacuated together (xe host-evacuate, which returns when all ten have moved), or one of them migrated (xe vm-migrate), while the guests:
- are idle: optimistic scenario;
- run desktop applications: average scenario;
- or run an extreme memory-write burner: a worst-case scenario.
off LZ4
Intel Xeon Gold 6430, 100 Gb/s
idle evacuate 195s 123s -37%
migrate 182s 96s -47%
desktop apps evacuate 318s 197s -38%
migrate 208s 156s -25%
memory burner evacuate 1339s 1417s +6%
migrate 1004s 992s -1%
AMD EPYC 9354, 25 Gb/s
idle evacuate 260s 73s -72%
migrate 167s 49s -71%
desktop apps evacuate 266s 105s -61%
migrate 179s 82s -54%
memory burner evacuate 556s 416s -25%
migrate 1833s 1883s +3%PV guest, xl migrate to the same host, 2 GiB, n=3: 15.1s and 2.54 GB plain, 10.1s and 0.89 GB with --compress.
Testing: every patch builds with and without liblz4, and the Python stream tests pass. Out of tree, with Xen stubbed out and under gcc's ASan and UBSan, the changed save and restore functions round-trip uncompressed and LZ4 records with plaintext and compressed pfns, and reject damaged and malformed ones, with every supported liblz4 release. On XenServer hosts: performance tests; 100 migrations of a loaded guest between two hosts; uncompressed migrations both ways between hosts with and without the series; xl migrate of PVH and PV guests with --debug (the receiver checks every page against a second copy: no mismatch); xl save/restore; a sender built without a supported liblz4 fails with --compress, as expected, before sending any guest memory; older receivers refuse LZ4 streams cleanly; damaged streams are rejected (bad checksum, reserved bits, unknown algorithm). With patch 9: 200 live migrations of loaded 64 GiB Windows VMs (100 to the same host, 100 between two hosts), evacuations of 10-VM hosts, and receivers without patch 9 refuse the compressed pfn array stream as expected.
Marcus Granado (9):
tools/libs/guest: reject non-zero reserved fields in PAGE_DATA docs/specs, tools: define the PAGE_DATA flags field tools/libs/guest: decompress LZ4 PAGE_DATA records on restore tools/libs/guest: compress PAGE_DATA records with LZ4 on save tools/libs/guest: stop compressing PAGE_DATA when it stops paying off tools/libs/guest: add XCFLAGS_COMPRESS_LZ4 to request LZ4 compression tools/libxl,xl: add a --compress option to xl migrate tools/xl: mark LZ4 migration streams with a mandatory header flag tools/libs/guest: compress the PAGE_DATA pfn array too
CHANGELOG.md | 3 + docs/man/xl.1.pod.in | 8 + docs/specs/libxc-migration-stream.pandoc | 108 +++++++++- tools/include/libxl.h | 1 + tools/include/xenguest.h | 5 +- tools/libs/guest/Makefile | 2 +- tools/libs/guest/xg_sr_common.h | 39 ++++ tools/libs/guest/xg_sr_restore.c | 243 ++++++++++++++++++++-- tools/libs/guest/xg_sr_save.c | 250 +++++++++++++++++++++++ tools/libs/guest/xg_sr_stream_format.h | 18 +- tools/libs/light/libxl_dom_save.c | 4 +- tools/libs/light/libxl_domain.c | 1 + tools/libs/light/libxl_internal.h | 1 + tools/python/xen/migration/libxc.py | 90 +++++++- tools/python/xen/migration/tests.py | 87 +++++++- tools/xl/xl.h | 7 +- tools/xl/xl_cmdtable.c | 2 + tools/xl/xl_migrate.c | 21 +- tools/xl/xl_saverestore.c | 7 +- 19 files changed, 850 insertions(+), 47 deletions(-)
base-commit: 7e020a4dd6ed30eb6c91a9abe2767034e2bb270a
Signature · 1 line
2.43.0
PATCH v2 1/9 tools/libs/guest: reject non-zero reserved fields in PAGE_DATA
A PAGE_DATA record has two reserved fields: the 32-bit field after count, and bits 59-52 of each pfn entry. libxenguest ignores both on restore, as the specification's general rule for reserved fields requires, while the Python stream validator (tools/python/xen/migration/libxc.py) rejects both.
A receiver which ignores either field can silently misread a record which uses it to change how the record's contents are organised.
Reject a PAGE_DATA record with either field non-zero. Qualify the specification's general rule so that a record can override it, require rejection of both reserved fields, and bump the specification's revision.
This deliberately tightens restore. Every libxenguest since Xen 4.6, and convert-legacy-stream, writes both fields as zero, so no stream they produce is rejected.
Backport: 4.17+
---
Notes:
Changes in v2:
- New patch, after Teddy Astie pointed out on v1 that ignoring reserved fields does not help a future field which changes how the record's contents are organised.
docs/specs/libxc-migration-stream.pandoc | 11 ++++++++--- tools/libs/guest/xg_sr_restore.c | 15 +++++++++++++++ tools/libs/guest/xg_sr_stream_format.h | 5 +++-- 3 files changed, 26 insertions(+), 5 deletions(-)
docs/specs/libxc-migration-stream.pandoc +8 -3
@@ -3,7 +3,7 @@ Andrew Cooper <<[email protected]>> Wen Congyang <<[email protected]>> Yang Hongyang <<[email protected]>> -% Revision 3 +% Revision 4 Introduction ============
@@ -76,7 +76,8 @@ All the fields within the headers and records have a fixed width. Fields are always aligned to their size. Padding and reserved fields are set to zero on save and must be -ignored during restore. +ignored during restore, unless the record containing them says +otherwise. Integer (numeric) fields in the image header are always in big-endian byte order.
@@ -298,12 +299,16 @@ Field Description ----------- -------------------------------------------------------- count Number of pages described in this record. +(reserved) Set to zero on save. A restoring side must reject a + record with this field non-zero. + pfn An array of count PFNs and their types. Bit 63-60: XEN_DOMCTL_PFINFO_* type (from `public/domctl.h` but shifted by 32 bits) - Bit 59-52: Reserved. + Bit 59-52: Reserved. Set to zero on save. A restoring + side must reject a record with any of these bits set. Bit 51-0: PFN.
tools/libs/guest/xg_sr_restore.c +15 -0
@@ -400,6 +400,14 @@ static int handle_page_data(struct xc_sr_context *ctx, struct xc_sr_record *rec) goto err; } +/* Reject rather than ignore: a future use may change the layout. */ +if ( pages->_res1 !=0 ) + { +ERROR ("Reserved field set in PAGE_DATA record: %#x" , + (unsigned int )pages->_res1); + goto err; + } +if ( pages->count <1 ) {ERROR ("Expected at least 1 pfn in PAGE_DATA record" );
@@ -424,6 +432,13 @@ static int handle_page_data(struct xc_sr_context *ctx, struct xc_sr_record *rec)for ( i =0 ; i < pages->count; ++i ) { +if ( pages->pfn[i] &PAGE_DATA_PFN_RESZ_MASK ) + { +ERROR ("Reserved bits set in pfn[%u]: %#" PRIx64, i, + pages->pfn[i]); + goto err; + } + pfn = pages->pfn[i] &PAGE_DATA_PFN_MASK ;if ( !ctx->restore.ops.pfn_is_valid (ctx, pfn) ) {
tools/libs/guest/xg_sr_stream_format.h +3 -2
@@ -87,8 +87,9 @@ struct xc_sr_rec_page_data_headeruint64_t pfn[0 ]; }; -#define PAGE_DATA_PFN_MASK 0x000fffffffffffffULL -#define PAGE_DATA_TYPE_MASK 0xf000000000000000ULL +#define PAGE_DATA_PFN_MASK 0x000fffffffffffffULL +#define PAGE_DATA_PFN_RESZ_MASK 0x0ff0000000000000ULL +#define PAGE_DATA_TYPE_MASK 0xf000000000000000ULL/* X86_PV_INFO */ struct xc_sr_rec_x86_pv_info
Signature · 1 line
2.43.0
Re: [PATCH v2 1/9] tools/libs/guest: reject non-zero reserved fields in PAGE_DATA
Le 20/10/2026 à 22:05, Marcus Granado a écrit :
Quoted 30 lines
A
PAGE_DATArecord has two reserved fields: the 32-bit field after count, and bits 59-52 of each pfn entry. libxenguest ignores both on restore, as the specification's general rule for reserved fields requires, while the Python stream validator (tools/python/xen/migration/libxc.py) rejects both.A receiver which ignores either field can silently misread a record which uses it to change how the record's contents are organised.
Reject a
PAGE_DATArecord with either field non-zero. Qualify the specification's general rule so that a record can override it, require rejection of both reserved fields, and bump the specification's revision.This deliberately tightens restore. Every libxenguest since Xen 4.6, and convert-legacy-stream, writes both fields as zero, so no stream they produce is rejected.
Backport: 4.17+
Reported-by Teddy Astie <[email protected]>Assisted-by Claude:claude-opus-5-5Signed-off-by Marcus Granado <[email protected]>---
Notes:
Changes in v2:
- New patch, after Teddy Astie pointed out on v1 that ignoring reserved fields does not help a future field which changes how the record's contents are organised.
Quoted 5 lines
docs/specs/libxc-migration-stream.pandoc | 11 ++++++++--- tools/libs/guest/xg_sr_restore.c | 15 +++++++++++++++ tools/libs/guest/xg_sr_stream_format.h | 5 +++-- 3 files changed, 26 insertions(+), 5 deletions(-)
PATCH v2 2/9 docs/specs, tools: define the PAGE_DATA flags field
In reply to Marcus GranadoThe 32-bit field after count in a PAGE_DATA record is reserved, and libxenguest and the Python stream validator reject a record which sets it. The record's page_data is page_size bytes of uncompressed contents per present page, and nothing in the record can say that it is encoded otherwise, so pages cannot be sent compressed.
Turn that field into a flags field. Bits 7-0 identify the algorithm used to encode page_data, 0x00 meaning none, and a restoring side must fail on a value it does not implement. Bits 31-8 stay reserved, and a restoring side must still reject a record which sets any of them, overriding the general rule for reserved fields. Make libxenguest and the Python validator enforce both rules, and check the length of page_data according to the algorithm. Add test_page_data_flags for the Python checks.
The specification's Future Extensions section requires a new record type for any extension of an existing one. Also allow an existing type to be extended in place when a receiver which predates the extension is guaranteed to reject the extended record rather than misread it. For PAGE_DATA, this holds for an encoding which leaves count and the pfn array in plaintext and shortens page_data: an older libxenguest which ignores the field fails its exact length check.
The stream version is not bumped. A zero flags field means what the reserved field meant, and no other value is accepted.
---
Notes:
Changes in v2:
- Replaces v1 1/6, which added a PAGE_DATA_LZ4 record type: PAGE_DATA's reserved field becomes a flags field, following review by Teddy Astie and Frediano Ziglio. LZ4 is assigned in patch 3.
docs/specs/libxc-migration-stream.pandoc | 28 +++++++++++++++++------ tools/libs/guest/xg_sr_restore.c | 29 ++++++++++++++++-------- tools/libs/guest/xg_sr_stream_format.h | 8 ++++++- tools/python/xen/migration/libxc.py | 28 ++++++++++++++++++----- tools/python/xen/migration/tests.py | 25 +++++++++++++++++++- 5 files changed, 94 insertions(+), 24 deletions(-)
docs/specs/libxc-migration-stream.pandoc +21 -7
@@ -3,7 +3,8 @@ Andrew Cooper <<[email protected]>> Wen Congyang <<[email protected]>> Yang Hongyang <<[email protected]>> -% Revision 4 + Marcus Granado <<[email protected]>> +% Revision 5 Introduction ============
@@ -279,7 +280,7 @@ memory contents. 0 1 2 3 4 5 6 7 octet +-----------------------+-------------------------+ - | count (C) | (reserved) | + | count (C) | flags | +-----------------------+-------------------------+ | pfn[0] | +-------------------------------------------------+
@@ -299,8 +300,19 @@ Field Description ----------- -------------------------------------------------------- count Number of pages described in this record. -(reserved) Set to zero on save. A restoring side must reject a - record with this field non-zero. +flags Bit 7-0: Algorithm used to encode page_data. + + 0x00: None. page_data is page_size octets of + uncompressed contents per present page. + + 0x01 - 0xFF: Unassigned. + + A restoring side must fail on an algorithm value it + does not implement, rather than attempting to + interpret the page_data. + + Bit 31-8: Reserved. Set to zero on save. A restoring side + must reject a record with any of these bits set. pfn An array of count PFNs and their types.
@@ -312,8 +324,8 @@ pfn An array of count PFNs and their types. Bit 51-0: PFN. -page_data page_size octets of uncompressed page contents for each - page set as present in the pfn array. +page_data Contents of each page set as present in the pfn array, + encoded with the algorithm in flags bits 7-0. -------------------------------------------------------------------- Note: Count is strictly > 0. N is strictly <= C and it is possible for there
@@ -802,7 +814,9 @@ The format may be extended by adding additional record types. Extending an existing record type must be done by adding a new record type. This allows old images with the old record to still be -restored. +restored. An existing record type may instead be extended in place if +a receiver which predates the extension is guaranteed to reject the +extended record rather than misread it. The image header may only be extended by _appending_ additional fields. In particular, the `marker`, `id` and `version` fields must
tools/libs/guest/xg_sr_restore.c +20 -9
@@ -401,10 +401,10 @@ static int handle_page_data(struct xc_sr_context *ctx, struct xc_sr_record *rec) }/* Reject rather than ignore: a future use may change the layout. */ -if ( pages->_res1 !=0 ) +if ( pages->flags &PAGE_DATA_FLAGS_RESZ_MASK ) { -ERROR ("Reserved field set in PAGE_DATA record: %#x" , - (unsigned int )pages->_res1); +ERROR ("Reserved bits set in PAGE_DATA record: %#x" , + (unsigned int )(pages->flags &PAGE_DATA_FLAGS_RESZ_MASK )); goto err; }
@@ -463,13 +463,24 @@ static int handle_page_data(struct xc_sr_context *ctx, struct xc_sr_record *rec) types[i] = type; } -if ( rec->length != (sizeof (*pages) + - (sizeof (uint64_t ) * pages->count) + - (PAGE_SIZE * pages_of_data)) ) +switch ( pages->flags &PAGE_DATA_ALGO_MASK ) { -ERROR ("PAGE_DATA record wrong size: length %u, expected " -"%zu + %zu + %lu" , rec->length,sizeof (*pages), - (sizeof (uint64_t ) * pages->count), (PAGE_SIZE * pages_of_data)); +case PAGE_DATA_ALGO_NONE : +if ( rec->length != (sizeof (*pages) + + (sizeof (uint64_t ) * pages->count) + + (PAGE_SIZE * pages_of_data)) ) + { +ERROR ("PAGE_DATA record wrong size: length %u, expected " +"%zu + %zu + %lu" , rec->length,sizeof (*pages), + (sizeof (uint64_t ) * pages->count), + (PAGE_SIZE * pages_of_data)); + goto err; + } +break ; + +default : +ERROR ("Unsupported algorithm %u in PAGE_DATA record" , + (unsigned int )(pages->flags &PAGE_DATA_ALGO_MASK )); goto err; }
tools/libs/guest/xg_sr_stream_format.h +7 -1
@@ -83,10 +83,16 @@ struct xc_sr_rhdrstruct xc_sr_rec_page_data_header {uint32_t count; -uint32_t _res1; +uint32_t flags;uint64_t pfn[0 ]; }; +/* PAGE_DATA flags: bits 7-0 are the algorithm, bits 31-8 are reserved. */ +#define PAGE_DATA_ALGO_MASK 0x000000ffU +#define PAGE_DATA_FLAGS_RESZ_MASK 0xffffff00U + +#define PAGE_DATA_ALGO_NONE 0x00000000U +#define PAGE_DATA_PFN_MASK 0x000fffffffffffffULL#define PAGE_DATA_PFN_RESZ_MASK 0x0ff0000000000000ULL#define PAGE_DATA_TYPE_MASK 0xf000000000000000ULL
tools/python/xen/migration/libxc.py +22 -6
@@ -86,6 +86,11 @@ PAGE_DATA_FORMAT = "II" PAGE_DATA_PFN_MASK = (1 << 52) - 1 PAGE_DATA_PFN_RESZ_MASK = ((1 << 60) - 1) & ~((1 << 52) - 1) +# page_data flags: bits 7-0 algorithm, bits 31-8 reserved (must reject) +PAGE_DATA_ALGO_MASK = 0x000000ff +PAGE_DATA_FLAGS_RESZ_MASK = 0xffffff00 +PAGE_DATA_ALGO_NONE = 0x00 + # flags from xen/public/domctl.h: XEN_DOMCTL_PFINFO_* shifted by 32 bits PAGE_DATA_TYPE_SHIFT = 60 PAGE_DATA_TYPE_LTABTYPE_MASK = (0x7 << PAGE_DATA_TYPE_SHIFT)
@@ -259,11 +264,14 @@ class VerifyLibxc(VerifyBase): raise RecordError( "PAGE_DATA record must be at least %d bytes long" % (minsz, )) - count, res1 = unpack(PAGE_DATA_FORMAT, content[:minsz]) + count, flags = unpack(PAGE_DATA_FORMAT, content[:minsz]) - if res1 != 0: + if flags & PAGE_DATA_FLAGS_RESZ_MASK: raise StreamError( - "Reserved bits set in PAGE_DATA record 0x%04x" % (res1, )) + "Reserved bits set in PAGE_DATA record 0x%08x" + % (flags & PAGE_DATA_FLAGS_RESZ_MASK, )) + + algo = flags & PAGE_DATA_ALGO_MASK pfnsz = count * 8 if (len(content) - minsz) < pfnsz:
@@ -289,9 +297,17 @@ class VerifyLibxc(VerifyBase): nr_pages += 1 pagesz = nr_pages * 4096 - if len(content) != minsz + pfnsz + pagesz: - raise RecordError("Expected %u + %u + %u, got %u" % - (minsz, pfnsz, pagesz, len(content))) + datasz = len(content) - minsz - pfnsz + + if algo == PAGE_DATA_ALGO_NONE: + + if datasz != pagesz: + raise RecordError("Expected %u + %u + %u, got %u" % + (minsz, pfnsz, pagesz, len(content))) + + else: + raise StreamError( + "Unsupported algorithm %u in PAGE_DATA record" % (algo, )) def verify_record_x86_pv_info(self, content):
tools/python/xen/migration/tests.py +24 -1
@@ -6,7 +6,7 @@ Unit tests for migration v2 streams import unittest -from struct import calcsize +from struct import calcsize, pack from xen.migration import libxc, libxl
@@ -30,6 +30,29 @@ class TestLibxc(unittest.TestCase): ): self.assertEqual(calcsize(fmt), sz) + def test_page_data_flags(self): + """ PAGE_DATA flags: algorithm dispatch and the reserved bits """ + + v = libxc.VerifyLibxc(lambda *_: None, lambda *_: b"") + PAGE = b"\x00" * 4096 + NOTAB = libxc.PAGE_DATA_TYPE_NOTAB | 0x1 # one normal page, pfn 1 + + def rec(flags, data): + return pack(libxc.PAGE_DATA_FORMAT, 1, flags) + \ + pack("=Q", NOTAB) + data + + # Uncompressed: exactly one page of data, and nothing else accepted. + v.verify_record_page_data(rec(libxc.PAGE_DATA_ALGO_NONE, PAGE)) + self.assertRaises(libxc.RecordError, v.verify_record_page_data, + rec(libxc.PAGE_DATA_ALGO_NONE, PAGE[:-1])) + + # An unimplemented algorithm, and any reserved bit, are refused. + self.assertRaises(libxc.StreamError, v.verify_record_page_data, + rec(libxc.PAGE_DATA_ALGO_NONE + 1, PAGE)) + for bit in range(8, 32): + self.assertRaises(libxc.StreamError, v.verify_record_page_data, + rec(1 << bit, PAGE)) + class TestLibxl(unittest.TestCase):
Signature · 1 line
2.43.0
Re: [PATCH v2 2/9] docs/specs, tools: define the PAGE_DATA flags field
Le 20/10/2026 à 22:05, Marcus Granado a écrit :
Quoted 45 lines
The 32-bit field after count in a
PAGE_DATArecord is reserved, and libxenguest and the Python stream validator reject a record which sets it. The record'spage_dataispage_sizebytes of uncompressed contents per present page, and nothing in the record can say that it is encoded otherwise, so pages cannot be sent compressed.Turn that field into a flags field. Bits 7-0 identify the algorithm used to encode
page_data,0x00meaning none, and a restoring side must fail on a value it does not implement. Bits 31-8 stay reserved, and a restoring side must still reject a record which sets any of them, overriding the general rule for reserved fields. Make libxenguest and the Python validator enforce both rules, and check the length ofpage_dataaccording to the algorithm. Addtest_page_data_flagsfor the Python checks.The specification's Future Extensions section requires a new record type for any extension of an existing one. Also allow an existing type to be extended in place when a receiver which predates the extension is guaranteed to reject the extended record rather than misread it. For
PAGE_DATA, this holds for an encoding which leaves count and the pfn array in plaintext and shortenspage_data: an older libxenguest which ignores the field fails its exact length check.The stream version is not bumped. A zero flags field means what the reserved field meant, and no other value is accepted.
Assisted-by Claude:claude-opus-5-5Signed-off-by Marcus Granado <[email protected]>---
Notes:
Changes in v2:
- Replaces v1 1/6, which added aPAGE_DATA_LZ4record type: PAGE_DATA's reserved field becomes a flags field, following review by Teddy Astie and Frediano Ziglio. LZ4 is assigned in patch 3.docs/specs/libxc-migration-stream.pandoc | 28 +++++++++++++++++------ tools/libs/guest/xg_sr_restore.c | 29 ++++++++++++++++-------- tools/libs/guest/xg_sr_stream_format.h | 8 ++++++- tools/python/xen/migration/libxc.py | 28 ++++++++++++++++++----- tools/python/xen/migration/tests.py | 25 +++++++++++++++++++- 5 files changed, 94 insertions(+), 24 deletions(-)docs/specs/libxc-migration-stream.pandoc +0
-0
(...)
Quoted 9 lines
tools/libs/guest/xg_sr_stream_format.h +0
-1@@ -83,10 +83,16 @@ struct xc_sr_rhdrstruct xc_sr_rec_page_data_header {uint32_t count; -uint32_t _res1;
tools/libs/guest/xg_sr_stream_format.h struct xc_sr_rhdr · line 95
Quoted 10 lines
tools/libs/guest/xg_sr_stream_format.h +7
-0+uint32_t flags;uint64_t pfn[0 ]; }; +/* PAGE_DATA flags: bits 7-0 are the algorithm, bits 31-8 are reserved. */ +#define PAGE_DATA_ALGO_MASK 0x000000ffU +#define PAGE_DATA_FLAGS_RESZ_MASK 0xffffff00U + +#define PAGE_DATA_ALGO_NONE 0x00000000U +
nit: I would prefer having each algorithm as a explicit 8-bit number, i.e 0x00U for ALGO_NONE, given that they can't be larger than it.
Quoted 91 lines
tools/libs/guest/xg_sr_stream_format.h +0
-0#define PAGE_DATA_PFN_MASK 0x000fffffffffffffULL#define PAGE_DATA_PFN_RESZ_MASK 0x0ff0000000000000ULL#define PAGE_DATA_TYPE_MASK 0xf000000000000000ULLtools/python/xen/migration/libxc.py +22
-6@@ -86,6 +86,11 @@ PAGE_DATA_FORMAT = "II" PAGE_DATA_PFN_MASK = (1 << 52) - 1 PAGE_DATA_PFN_RESZ_MASK = ((1 << 60) - 1) & ~((1 << 52) - 1) +# page_data flags: bits 7-0 algorithm, bits 31-8 reserved (must reject) +PAGE_DATA_ALGO_MASK = 0x000000ff +PAGE_DATA_FLAGS_RESZ_MASK = 0xffffff00 +PAGE_DATA_ALGO_NONE = 0x00 + # flags from xen/public/domctl.h: XEN_DOMCTL_PFINFO_* shifted by 32 bits PAGE_DATA_TYPE_SHIFT = 60 PAGE_DATA_TYPE_LTABTYPE_MASK = (0x7 << PAGE_DATA_TYPE_SHIFT)@@ -259,11 +264,14 @@ class VerifyLibxc(VerifyBase): raise RecordError( "PAGE_DATA record must be at least %d bytes long" % (minsz, )) - count, res1 = unpack(PAGE_DATA_FORMAT, content[:minsz]) + count, flags = unpack(PAGE_DATA_FORMAT, content[:minsz]) - if res1 != 0: + if flags & PAGE_DATA_FLAGS_RESZ_MASK: raise StreamError( - "Reserved bits set in PAGE_DATA record 0x%04x" % (res1, )) + "Reserved bits set in PAGE_DATA record 0x%08x" + % (flags & PAGE_DATA_FLAGS_RESZ_MASK, )) + + algo = flags & PAGE_DATA_ALGO_MASK pfnsz = count * 8 if (len(content) - minsz) < pfnsz:@@ -289,9 +297,17 @@ class VerifyLibxc(VerifyBase): nr_pages += 1 pagesz = nr_pages * 4096 - if len(content) != minsz + pfnsz + pagesz: - raise RecordError("Expected %u + %u + %u, got %u" % - (minsz, pfnsz, pagesz, len(content))) + datasz = len(content) - minsz - pfnsz + + if algo == PAGE_DATA_ALGO_NONE: + + if datasz != pagesz: + raise RecordError("Expected %u + %u + %u, got %u" % + (minsz, pfnsz, pagesz, len(content))) + + else: + raise StreamError( + "Unsupported algorithm %u in PAGE_DATA record" % (algo, )) def verify_record_x86_pv_info(self, content):tools/python/xen/migration/tests.py +17
-1@@ -6,7 +6,7 @@ Unit tests for migration v2 streams import unittest -from struct import calcsize +from struct import calcsize, pack from xen.migration import libxc, libxl@@ -30,6 +30,29 @@ class TestLibxc(unittest.TestCase): ): self.assertEqual(calcsize(fmt), sz) + def test_page_data_flags(self): + """ PAGE_DATA flags: algorithm dispatch and the reserved bits """ + + v = libxc.VerifyLibxc(lambda *_: None, lambda *_: b"") + PAGE = b"\x00" * 4096 + NOTAB = libxc.PAGE_DATA_TYPE_NOTAB | 0x1 # one normal page, pfn 1 + + def rec(flags, data): + return pack(libxc.PAGE_DATA_FORMAT, 1, flags) + \ + pack("=Q", NOTAB) + data + + # Uncompressed: exactly one page of data, and nothing else accepted. + v.verify_record_page_data(rec(libxc.PAGE_DATA_ALGO_NONE, PAGE)) + self.assertRaises(libxc.RecordError, v.verify_record_page_data, + rec(libxc.PAGE_DATA_ALGO_NONE, PAGE[:-1])) +
tools/python/xen/migration/tests.py class TestLibxc(unittest.TestCase): · line 58
Quoted 10 lines
tools/python/xen/migration/tests.py +7
-0+ # An unimplemented algorithm, and any reserved bit, are refused. + self.assertRaises(libxc.StreamError, v.verify_record_page_data, + rec(libxc.PAGE_DATA_ALGO_NONE + 1, PAGE)) + for bit in range(8, 32): + self.assertRaises(libxc.StreamError, v.verify_record_page_data, + rec(1 << bit, PAGE)) + class TestLibxl(unittest.TestCase):
The rest looks good to me
With the change on number formatting
PATCH v2 3/9 tools/libs/guest: decompress LZ4 PAGE_DATA records on restore
In reply to Marcus GranadoPAGE_DATA records carry page contents uncompressed; algorithm 0x00 is the only one assigned in their flags field. Compressing them would put less data on the wire during migration, at a CPU cost on both hosts, worth paying where the bottleneck is the link, or encryption of the stream by ssh or TLS.
Assign algorithm 0x01 (PAGE_DATA_ALGO_LZ4) to LZ4, and decode it on restore. page_data is then one LZ4 frame: LZ4 for its speed, and its Frame Format because it is specified outside Xen, delimits itself and can carry block checksums. This encoding requires these checksums, as without them a corrupted frame can decode into wrong page contents; liblz4 accepts a frame without them, so the decoder checks the block-checksum flag itself.
The output size comes from the pfn array, and the frame must decode to exactly that size and end where the record ends. Before decoding, the record must have no more pages of data than the decoder's buffer holds (the most the saver puts in a record), and a payload strictly shorter than the uncompressed page data. The stream specification requires the latter for a saver: it makes an older libxenguest which ignores the flags field fail its exact length check on these records, rather than take the frame for page contents.
Nothing emits algorithm 0x01 yet, so receivers can be updated first. Restore has no option to turn it on or off: any stream may use it.
The decoder is guarded by XG_SR_LZ4, which xg_sr_common.h defines when HAVE_LZ4 is set and liblz4 is 1.8.1 or later, avoiding releases with known decoder bugs. A build without XG_SR_LZ4 rejects algorithm 0x01 with an error naming the missing LZ4 support. configure puts -DHAVE_LZ4 and liblz4's CFLAGS in ZLIB_CFLAGS, which only xg_dom_bzimageloader.o used: apply it to every libxenguest object, so that HAVE_LZ4, and the layout of any structure that depends on it, cannot differ between objects.
The Python stream validator checks algorithm 0x01's payload length and block-checksum flag, and test_page_data_flags gains LZ4 cases.
---
Notes:
Changes in v2:
- Was v1 2/6, which decoded per-page LZ4 blocks from a new PAGE_DATA_LZ4 record. Now PAGE_DATA algorithm 0x01: one LZ4 frame per record, as Teddy Astie suggested, with mandatory block checksums.
- The uncompressed size asked for by Teddy Astie and Frediano Ziglio comes from the pfn array; the decode buffer has a fixed size.
docs/specs/libxc-migration-stream.pandoc | 24 +++- tools/libs/guest/Makefile | 2 +- tools/libs/guest/xg_sr_common.h | 16 +++ tools/libs/guest/xg_sr_restore.c | 141 ++++++++++++++++++++++- tools/libs/guest/xg_sr_stream_format.h | 1 + tools/python/xen/migration/libxc.py | 23 ++++ tools/python/xen/migration/tests.py | 31 ++++- 7 files changed, 229 insertions(+), 9 deletions(-)
docs/specs/libxc-migration-stream.pandoc +21 -3
@@ -40,8 +40,6 @@ Not Yet Included The following features are not yet fully specified and will be included in a future draft. -* Page data compression. - * ARM
@@ -305,7 +303,24 @@ flags Bit 7-0: Algorithm used to encode page_data. 0x00: None. page_data is page_size octets of uncompressed contents per present page. - 0x01 - 0xFF: Unassigned. + 0x01: LZ4. page_data is a single LZ4 frame, as + defined by the LZ4 Frame Format specification[^1], + whose decompressed content is page_size octets + for each present page. A restoring side must + reject a frame which does not decode to exactly + that many octets, or which does not end where + page_data ends. + + The frame must set the block-checksum flag in + its frame descriptor, and a restoring side must + reject one which does not. + + A saving side may only use this value when the + frame is strictly shorter than the uncompressed + page_data it replaces; otherwise it must send the + record with algorithm 0x00. + + 0x02 - 0xFF: Unassigned. A restoring side must fail on an algorithm value it does not implement, rather than attempting to
@@ -371,6 +386,9 @@ guest's P2M table during a live migration[^2]. Restoring an image with unrecognised page types shall fail. +[^1]: LZ4 Frame Format Description, version 1.6.4: +<https://github.com/lz4/lz4/blob/v1.10.0/doc/lz4_Frame_format.md> + [^2]: In the legacy format, this is the list of unmapped PFNs in the tail.
tools/libs/guest/Makefile +1 -1
@@ -3,7 +3,7 @@ include $(XEN_ROOT)/tools/Rules.mk include Makefile.common -xg_dom_bzimageloader.o xg_dom_bzimageloader.opic: CFLAGS += $(ZLIB_CFLAGS) +CFLAGS += $(ZLIB_CFLAGS) $(LIBELF_OBJS:.o=.opic): CFLAGS += -Wno-pointer-sign
tools/libs/guest/xg_sr_common.h +16 -0
@@ -3,6 +3,18 @@#include <stdbool.h> +#if defined(HAVE_LZ4 ) +#include <lz4.h> +/* +* 1.8.1 fixed a memcpy() from NULL in LZ4F_decompress(). +* 1.9.0's decoder reads past its input (fixed in 1.9.1). +*/ +#if LZ4_VERSION_NUMBER >=10801 &&LZ4_VERSION_NUMBER !=10900 +#include <lz4frame.h> +#define XG_SR_LZ4 +#endif +#endif +#include "xg_private.h" #include "xg_save_restore.h" #include "xg_sr_stream_format.h"
@@ -277,6 +289,10 @@ struct xc_sr_context/* Whether a STATIC_DATA_END record has been seen/inferred. */ bool seen_static_data_end; +/* LZ4 decoder buffer and context, allocated on first use. */ +void *lz4_decomp_buf; +void *lz4_dctx; +/* * With Remus/COLO, we buffer the records sent by the primary at checkpoint, * in case the primary will fail, we can recover from the last
tools/libs/guest/xg_sr_restore.c +139 -2
177 lines not on this page · raw message
tools/libs/guest/xg_sr_stream_format.h +1 -0
@@ -92,6 +92,7 @@ struct xc_sr_rec_page_data_header#define PAGE_DATA_FLAGS_RESZ_MASK 0xffffff00U#define PAGE_DATA_ALGO_NONE 0x00000000U +#define PAGE_DATA_ALGO_LZ4 0x00000001U#define PAGE_DATA_PFN_MASK 0x000fffffffffffffULL#define PAGE_DATA_PFN_RESZ_MASK 0x0ff0000000000000ULL
tools/python/xen/migration/libxc.py +23 -0
@@ -90,6 +90,11 @@ PAGE_DATA_PFN_RESZ_MASK = ((1 << 60) - 1) & ~((1 << 52) - 1) PAGE_DATA_ALGO_MASK = 0x000000ff PAGE_DATA_FLAGS_RESZ_MASK = 0xffffff00 PAGE_DATA_ALGO_NONE = 0x00 +PAGE_DATA_ALGO_LZ4 = 0x01 + +# LZ4 frame: at least magic, FLG, BD and HC; FLG bit 4 is B.Checksum +PAGE_DATA_LZ4_FRAME_MIN = 7 +PAGE_DATA_LZ4_FLG_BLOCKSUM = 0x10 # flags from xen/public/domctl.h: XEN_DOMCTL_PFINFO_* shifted by 32 bits PAGE_DATA_TYPE_SHIFT = 60
@@ -305,6 +310,24 @@ class VerifyLibxc(VerifyBase): raise RecordError("Expected %u + %u + %u, got %u" % (minsz, pfnsz, pagesz, len(content))) + elif algo == PAGE_DATA_ALGO_LZ4: + + # Without decompressing, check the saver's length rule. + if datasz >= pagesz: + raise RecordError( + "LZ4 frame in PAGE_DATA record (%u bytes) is not shorter than its page data (%u bytes)" + % (datasz, pagesz)) + + frame = content[minsz + pfnsz:] + if len(frame) < PAGE_DATA_LZ4_FRAME_MIN: + raise RecordError( + "LZ4 frame in PAGE_DATA record too short: %u bytes" + % (len(frame), )) + + if not ord(frame[4:5]) & PAGE_DATA_LZ4_FLG_BLOCKSUM: + raise RecordError( + "LZ4 frame in PAGE_DATA record has no block checksums") + else: raise StreamError( "Unsupported algorithm %u in PAGE_DATA record" % (algo, ))
tools/python/xen/migration/tests.py +28 -3
@@ -36,19 +36,44 @@ class TestLibxc(unittest.TestCase): v = libxc.VerifyLibxc(lambda *_: None, lambda *_: b"") PAGE = b"\x00" * 4096 NOTAB = libxc.PAGE_DATA_TYPE_NOTAB | 0x1 # one normal page, pfn 1 + XTAB = libxc.PAGE_DATA_TYPE_XTAB | 0x1 # no page of data, pfn 1 - def rec(flags, data): + def rec(flags, data, pfn=NOTAB): return pack(libxc.PAGE_DATA_FORMAT, 1, flags) + \ - pack("=Q", NOTAB) + data + pack("=Q", pfn) + data # Uncompressed: exactly one page of data, and nothing else accepted. v.verify_record_page_data(rec(libxc.PAGE_DATA_ALGO_NONE, PAGE)) self.assertRaises(libxc.RecordError, v.verify_record_page_data, rec(libxc.PAGE_DATA_ALGO_NONE, PAGE[:-1])) + # An LZ4 frame header: magic, then FLG with the block-checksum bit. + FRAME = b"\x04\x22\x4d\x18\x70\x70\x72" + b"\x00" * 93 + + # LZ4: the payload is checked against the saver's length rule, + # 0 < len < the uncompressed size it replaces: one page here, and + # none with an XTAB pfn. FULL is a valid frame header padded to one + # page, so only the length rule can reject it. + FULL = FRAME + b"\x00" * (4096 - len(FRAME)) + v.verify_record_page_data(rec(libxc.PAGE_DATA_ALGO_LZ4, FULL[:-1])) + v.verify_record_page_data(rec(libxc.PAGE_DATA_ALGO_LZ4, FRAME)) + self.assertRaises(libxc.RecordError, v.verify_record_page_data, + rec(libxc.PAGE_DATA_ALGO_LZ4, b"")) + self.assertRaises(libxc.RecordError, v.verify_record_page_data, + rec(libxc.PAGE_DATA_ALGO_LZ4, FULL)) + self.assertRaises(libxc.RecordError, v.verify_record_page_data, + rec(libxc.PAGE_DATA_ALGO_LZ4, FRAME, XTAB)) + + # ... and against the frame having a whole header with block checksums. + self.assertRaises(libxc.RecordError, v.verify_record_page_data, + rec(libxc.PAGE_DATA_ALGO_LZ4, + FRAME[:4] + b"\x60" + FRAME[5:])) + self.assertRaises(libxc.RecordError, v.verify_record_page_data, + rec(libxc.PAGE_DATA_ALGO_LZ4, FRAME[:6])) + # An unimplemented algorithm, and any reserved bit, are refused. self.assertRaises(libxc.StreamError, v.verify_record_page_data, - rec(libxc.PAGE_DATA_ALGO_NONE + 1, PAGE)) + rec(libxc.PAGE_DATA_ALGO_LZ4 + 1, FRAME)) for bit in range(8, 32): self.assertRaises(libxc.StreamError, v.verify_record_page_data, rec(1 << bit, PAGE))
Signature · 1 line
2.43.0
Re: [PATCH v2 3/9] tools/libs/guest: decompress LZ4 PAGE_DATA records on restore
Le 20/10/2026 à 22:10, Marcus Granado a écrit :
Quoted 132 lines
PAGE_DATArecords carry page contents uncompressed; algorithm0x00is the only one assigned in their flags field. Compressing them would put less data on the wire during migration, at a CPU cost on both hosts, worth paying where the bottleneck is the link, or encryption of the stream by ssh or TLS.Assign algorithm
0x01(PAGE_DATA_ALGO_LZ4) to LZ4, and decode it on restore.page_datais then one LZ4 frame: LZ4 for its speed, and its Frame Format because it is specified outside Xen, delimits itself and can carry block checksums. This encoding requires these checksums, as without them a corrupted frame can decode into wrong page contents; liblz4 accepts a frame without them, so the decoder checks the block-checksum flag itself.The output size comes from the pfn array, and the frame must decode to exactly that size and end where the record ends. Before decoding, the record must have no more pages of data than the decoder's buffer holds (the most the saver puts in a record), and a payload strictly shorter than the uncompressed page data. The stream specification requires the latter for a saver: it makes an older libxenguest which ignores the flags field fail its exact length check on these records, rather than take the frame for page contents.
Nothing emits algorithm
0x01yet, so receivers can be updated first. Restore has no option to turn it on or off: any stream may use it.The decoder is guarded by
XG_SR_LZ4, whichxg_sr_common.hdefines whenHAVE_LZ4is set and liblz4 is 1.8.1 or later, avoiding releases with known decoder bugs. A build withoutXG_SR_LZ4rejects algorithm0x01with an error naming the missing LZ4 support. configure puts -DHAVE_LZ4 and liblz4's CFLAGS inZLIB_CFLAGS, which only xg_dom_bzimageloader.o used: apply it to every libxenguest object, so thatHAVE_LZ4, and the layout of any structure that depends on it, cannot differ between objects.The Python stream validator checks algorithm 0x01's payload length and block-checksum flag, and
test_page_data_flagsgains LZ4 cases.Suggested-by Teddy Astie <[email protected]>Assisted-by Claude:claude-opus-5-5Signed-off-by Marcus Granado <[email protected]>---
Notes:
Changes in v2:
- Was v1 2/6, which decoded per-page LZ4 blocks from a newPAGE_DATA_LZ4record. NowPAGE_DATAalgorithm0x01: one LZ4 frame per record, as Teddy Astie suggested, with mandatory block checksums.
- The uncompressed size asked for by Teddy Astie and Frediano Ziglio comes from the pfn array; the decode buffer has a fixed size.docs/specs/libxc-migration-stream.pandoc | 24 +++- tools/libs/guest/Makefile | 2 +- tools/libs/guest/xg_sr_common.h | 16 +++ tools/libs/guest/xg_sr_restore.c | 141 ++++++++++++++++++++++- tools/libs/guest/xg_sr_stream_format.h | 1 + tools/python/xen/migration/libxc.py | 23 ++++ tools/python/xen/migration/tests.py | 31 ++++- 7 files changed, 229 insertions(+), 9 deletions(-)docs/specs/libxc-migration-stream.pandoc +21
-3@@ -40,8 +40,6 @@ Not Yet Included The following features are not yet fully specified and will be included in a future draft. -* Page data compression. - * ARM@@ -305,7 +303,24 @@ flags Bit 7-0: Algorithm used to encode page_data. 0x00: None. page_data is page_size octets of uncompressed contents per present page. - 0x01 - 0xFF: Unassigned. + 0x01: LZ4. page_data is a single LZ4 frame, as + defined by the LZ4 Frame Format specification[^1], + whose decompressed content is page_size octets + for each present page. A restoring side must + reject a frame which does not decode to exactly + that many octets, or which does not end where + page_data ends. + + The frame must set the block-checksum flag in + its frame descriptor, and a restoring side must + reject one which does not. + + A saving side may only use this value when the + frame is strictly shorter than the uncompressed + page_data it replaces; otherwise it must send the + record with algorithm 0x00. + + 0x02 - 0xFF: Unassigned. A restoring side must fail on an algorithm value it does not implement, rather than attempting to@@ -371,6 +386,9 @@ guest's P2M table during a live migration[^2]. Restoring an image with unrecognised page types shall fail. +[^1]: LZ4 Frame Format Description, version 1.6.4: +<https://github.com/lz4/lz4/blob/v1.10.0/doc/lz4_Frame_format.md> + [^2]: In the legacy format, this is the list of unmapped PFNs in the tail.tools/libs/guest/Makefile +1
-1@@ -3,7 +3,7 @@ include $(XEN_ROOT)/tools/Rules.mk include Makefile.common -xg_dom_bzimageloader.o xg_dom_bzimageloader.opic: CFLAGS += $(ZLIB_CFLAGS) +CFLAGS += $(ZLIB_CFLAGS) $(LIBELF_OBJS:.o=.opic): CFLAGS += -Wno-pointer-signtools/libs/guest/xg_sr_common.h +2
-0@@ -3,6 +3,18 @@#include <stdbool.h> +#if defined(HAVE_LZ4 ) +#include <lz4.h>
tools/libs/guest/xg_sr_common.h line 17
Quoted 10 lines
tools/libs/guest/xg_sr_common.h +10
-0+/* +* 1.8.1 fixed a memcpy() from NULL in LZ4F_decompress(). +* 1.9.0's decoder reads past its input (fixed in 1.9.1). +*/ +#if LZ4_VERSION_NUMBER >=10801 &&LZ4_VERSION_NUMBER !=10900 +#include <lz4frame.h> +#define XG_SR_LZ4 +#endif +#endif +
I think it would be preferable to warn the user that we rejected the lz4 support here rather than silently disabling it. Perhaps with something like
#pragma GCC warning "Disabled LZ4 restore support due to library bugs"
Assuming it's something we support.
tools/libs/guest/xg_sr_common.h struct xc_sr_context · line 295
Quoted 11 lines
tools/libs/guest/xg_sr_common.h +4
-0#include "xg_private.h" #include "xg_save_restore.h" #include "xg_sr_stream_format.h" @@ -277,6 +289,10 @@ struct xc_sr_context/* Whether a STATIC_DATA_END record has been seen/inferred. */ bool seen_static_data_end; +/* LZ4 decoder buffer and context, allocated on first use. */ +void *lz4_decomp_buf; +void *lz4_dctx; +
I think these new fields are supposed (at least, lz4_dctx) to be gated behind XG_SR_LZ4, otherwise, they are effectively unused if lz4 live migration support is compiled out. (that way, we would be able to make lz4_dctx LZ4F_dctx instead of void)
lz4_decomp_buf is a MAX_BATCH_SIZE * PAGE_SIZE bytes buffer, but has no lz4 specific meaning. I would just call it "decomp_buf" directly, so that it can be reused for other compression algorithms when needed.
Quoted 8 lines
tools/libs/guest/xg_sr_common.h +0
-0/* * With Remus/COLO, we buffer the records sent by the primary at checkpoint, * in case the primary will fail, we can recover from the last tools/libs/guest/xg_sr_restore.c +0
-0
tools/libs/guest/xg_sr_restore.c static int process_page_data(struct xc_sr_context *ctx, unsigned int count, · line 363
Quoted 10 lines
tools/libs/guest/xg_sr_restore.c +7
-0@@ -354,6 +354,120 @@ static int process_page_data(struct xc_sr_context *ctx, unsigned int count,return rc; } +#if defined(XG_SR_LZ4 ) +/* +* Decode the LZ4 frame at src into ctx->restore.lz4_decomp_buf. The +* decoded size comes from the pfn array. +*/ +static void *decompress_page_data (struct xc_sr_context *ctx,const void *src, +size_t src_len,unsigned int nr_pages)
Given this is the lz4 implementation, I would rather name it decompress_lz4_page_data().
Quoted 27 lines
tools/libs/guest/xg_sr_restore.c +27
-0+{ +xc_interface *xch = ctx->xch; +LZ4F_frameInfo_t info; +size_t expected = (size_t )nr_pages *PAGE_SIZE ; +size_t out_len = expected, hdr_len = src_len, rest_len, in_len, ret; + +/* The buffer is a fixed MAX_BATCH_SIZE pages. */ +if ( nr_pages >MAX_BATCH_SIZE ) + { +ERROR ("Compressed PAGE_DATA record with %u pages exceeds MAX_BATCH_SIZE %u" , + nr_pages,MAX_BATCH_SIZE ); +return NULL ; + } + +/* The format requires the frame to be strictly shorter than the pages. */ +if ( src_len >= expected ) + { +ERROR ("LZ4 frame in PAGE_DATA record (%zu bytes) is not shorter than its page data (%zu bytes)" , + src_len, expected); +return NULL ; + } + +if ( !ctx->restore.lz4_dctx ) + { +LZ4F_dctx *dctx =NULL ; + + ret =LZ4F_createDecompressionContext (&dctx,LZ4F_VERSION );
tools/libs/guest/xg_sr_restore.c static int process_page_data(struct xc_sr_context *ctx, unsigned int count, · line 400
Quoted 10 lines
tools/libs/guest/xg_sr_restore.c +10
-0+if (LZ4F_isError (ret) ) + { +ERROR ("Unable to create LZ4 decompression context" ); +return NULL ; + } + ctx->restore.lz4_dctx = dctx; + } + +/* Start each frame at its header (restore stops at any error). */ +LZ4F_resetDecompressionContext (ctx->restore.lz4_dctx);
To me, it's not useful to reset the context right after creating it.
So, we can eventually fold this line into a else case i.e when the context already exist.
Quoted 34 lines
tools/libs/guest/xg_sr_restore.c +34
-0+ + ret =LZ4F_getFrameInfo (ctx->restore.lz4_dctx, &info, src, &hdr_len); +if (LZ4F_isError (ret) ) + { +ERROR ("LZ4 frame in PAGE_DATA record has a bad header: %s" , +LZ4F_getErrorName (ret)); +return NULL ; + } + +/* liblz4 accepts frames without the block checksums required here. */ +if ( info.blockChecksumFlag != LZ4F_blockChecksumEnabled ) + { +ERROR ("LZ4 frame in PAGE_DATA record has no block checksums" ); +return NULL ; + } + +if ( !ctx->restore.lz4_decomp_buf ) + { + ctx->restore.lz4_decomp_buf =malloc (MAX_BATCH_SIZE *PAGE_SIZE ); +if ( !ctx->restore.lz4_decomp_buf ) + { +ERROR ("Unable to allocate %lu bytes for decompression" , + (unsigned long )MAX_BATCH_SIZE *PAGE_SIZE ); +return NULL ; + } + } + +/* LZ4F_getFrameInfo() read the header; decode the rest of the frame. */ + rest_len = src_len - hdr_len; + in_len = rest_len; + +/* NULL options: checksums are verified; liblz4 keeps its own buffers. */ + ret = LZ4F_decompress(ctx->restore.lz4_dctx, ctx->restore.lz4_decomp_buf, + &out_len, (const uint8_t *)src + hdr_len, &in_len,
tools/libs/guest/xg_sr_restore.c static int process_page_data(struct xc_sr_context *ctx, unsigned int count, · line 444
Quoted 10 lines
tools/libs/guest/xg_sr_restore.c +10
-0+ NULL); + +if (LZ4F_isError (ret) ) + { +ERROR ("Failed to decompress PAGE_DATA record: %s" , +LZ4F_getErrorName (ret)); +return NULL ; + } + +/* Not an error, but the frame did not end: input or output ran out. */
nit: "Not a decompression error".
Quoted 195 lines
tools/libs/guest/xg_sr_restore.c +51
-2+if ( ret !=0 ) + { +ERROR ("LZ4 frame in PAGE_DATA record is truncated or decodes to over %zu bytes" , + expected); +return NULL ; + } + +/* in_len and out_len now hold the bytes consumed and produced. */ +if ( out_len != expected ) + { +ERROR ("LZ4 frame in PAGE_DATA record produced %zu bytes, expected %zu" , + out_len, expected); +return NULL ; + } + +if ( in_len != rest_len ) + { +ERROR ("LZ4 frame in PAGE_DATA record followed by %zu unconsumed bytes" , + rest_len - in_len); +return NULL ; + } + + return ctx->restore.lz4_decomp_buf; +} +#endif /* XG_SR_LZ4 */ +/* * Validate a PAGE_DATA record from the stream, and pass the results to * process_page_data() to actually perform the legwork. @@ -363,6 +477,7 @@ static int handle_page_data(struct xc_sr_context *ctx, struct xc_sr_record *rec)xc_interface *xch = ctx->xch;struct xc_sr_rec_page_data_header *pages = rec->data;unsigned int i, pages_of_data =0 ; +void *page_data;int rc =-1 ;xen_pfn_t *pfns =NULL , pfn;@@ -463,6 +578,8 @@ static int handle_page_data(struct xc_sr_context *ctx, struct xc_sr_record *rec) types[i] = type; } + page_data = &pages->pfn[pages->count]; +switch ( pages->flags &PAGE_DATA_ALGO_MASK ) {case PAGE_DATA_ALGO_NONE :@@ -478,14 +595,29 @@ static int handle_page_data(struct xc_sr_context *ctx, struct xc_sr_record *rec) }break ; +case PAGE_DATA_ALGO_LZ4 : +#if defined(XG_SR_LZ4 ) + { +size_t hdrsz =sizeof (*pages) + (sizeof (uint64_t ) * pages->count); + + page_data =decompress_page_data (ctx, page_data, + rec->length - hdrsz, pages_of_data); +if ( !page_data ) + goto err; +break ; + } +#else +ERROR ("LZ4 compressed PAGE_DATA record but LZ4 support not compiled in" ); + goto err; +#endif +default :ERROR ("Unsupported algorithm %u in PAGE_DATA record" , (unsigned int )(pages->flags &PAGE_DATA_ALGO_MASK )); goto err; } - rc =process_page_data (ctx, pages->count, pfns, types, - &pages->pfn[pages->count]); + rc =process_page_data (ctx, pages->count, pfns, types, page_data); err:free (types);free (pfns);@@ -822,6 +954,11 @@ static void cleanup(struct xc_sr_context *ctx)free (ctx->restore.buffered_records);free (ctx->restore.populated_pfns); +free (ctx->restore.lz4_decomp_buf); +#if defined(XG_SR_LZ4 ) +if ( ctx->restore.lz4_dctx ) +LZ4F_freeDecompressionContext (ctx->restore.lz4_dctx); +#endif if ( ctx->restore.ops.cleanup (ctx) )PERROR ("Failed to clean up" );tools/libs/guest/xg_sr_stream_format.h +1
-0@@ -92,6 +92,7 @@ struct xc_sr_rec_page_data_header#define PAGE_DATA_FLAGS_RESZ_MASK 0xffffff00U#define PAGE_DATA_ALGO_NONE 0x00000000U +#define PAGE_DATA_ALGO_LZ4 0x00000001U#define PAGE_DATA_PFN_MASK 0x000fffffffffffffULL#define PAGE_DATA_PFN_RESZ_MASK 0x0ff0000000000000ULLtools/python/xen/migration/libxc.py +23
-0@@ -90,6 +90,11 @@ PAGE_DATA_PFN_RESZ_MASK = ((1 << 60) - 1) & ~((1 << 52) - 1) PAGE_DATA_ALGO_MASK = 0x000000ff PAGE_DATA_FLAGS_RESZ_MASK = 0xffffff00 PAGE_DATA_ALGO_NONE = 0x00 +PAGE_DATA_ALGO_LZ4 = 0x01 + +# LZ4 frame: at least magic, FLG, BD and HC; FLG bit 4 is B.Checksum +PAGE_DATA_LZ4_FRAME_MIN = 7 +PAGE_DATA_LZ4_FLG_BLOCKSUM = 0x10 # flags from xen/public/domctl.h: XEN_DOMCTL_PFINFO_* shifted by 32 bits PAGE_DATA_TYPE_SHIFT = 60@@ -305,6 +310,24 @@ class VerifyLibxc(VerifyBase): raise RecordError("Expected %u + %u + %u, got %u" % (minsz, pfnsz, pagesz, len(content))) + elif algo == PAGE_DATA_ALGO_LZ4: + + # Without decompressing, check the saver's length rule. + if datasz >= pagesz: + raise RecordError( + "LZ4 frame in PAGE_DATA record (%u bytes) is not shorter than its page data (%u bytes)" + % (datasz, pagesz)) + + frame = content[minsz + pfnsz:] + if len(frame) < PAGE_DATA_LZ4_FRAME_MIN: + raise RecordError( + "LZ4 frame in PAGE_DATA record too short: %u bytes" + % (len(frame), )) + + if not ord(frame[4:5]) & PAGE_DATA_LZ4_FLG_BLOCKSUM: + raise RecordError( + "LZ4 frame in PAGE_DATA record has no block checksums") + else: raise StreamError( "Unsupported algorithm %u in PAGE_DATA record" % (algo, ))tools/python/xen/migration/tests.py +28
-3@@ -36,19 +36,44 @@ class TestLibxc(unittest.TestCase): v = libxc.VerifyLibxc(lambda *_: None, lambda *_: b"") PAGE = b"\x00" * 4096 NOTAB = libxc.PAGE_DATA_TYPE_NOTAB | 0x1 # one normal page, pfn 1 + XTAB = libxc.PAGE_DATA_TYPE_XTAB | 0x1 # no page of data, pfn 1 - def rec(flags, data): + def rec(flags, data, pfn=NOTAB): return pack(libxc.PAGE_DATA_FORMAT, 1, flags) + \ - pack("=Q", NOTAB) + data + pack("=Q", pfn) + data # Uncompressed: exactly one page of data, and nothing else accepted. v.verify_record_page_data(rec(libxc.PAGE_DATA_ALGO_NONE, PAGE)) self.assertRaises(libxc.RecordError, v.verify_record_page_data, rec(libxc.PAGE_DATA_ALGO_NONE, PAGE[:-1])) + # An LZ4 frame header: magic, then FLG with the block-checksum bit. + FRAME = b"\x04\x22\x4d\x18\x70\x70\x72" + b"\x00" * 93 + + # LZ4: the payload is checked against the saver's length rule, + # 0 < len < the uncompressed size it replaces: one page here, and + # none with an XTAB pfn. FULL is a valid frame header padded to one + # page, so only the length rule can reject it. + FULL = FRAME + b"\x00" * (4096 - len(FRAME)) + v.verify_record_page_data(rec(libxc.PAGE_DATA_ALGO_LZ4, FULL[:-1])) + v.verify_record_page_data(rec(libxc.PAGE_DATA_ALGO_LZ4, FRAME)) + self.assertRaises(libxc.RecordError, v.verify_record_page_data, + rec(libxc.PAGE_DATA_ALGO_LZ4, b"")) + self.assertRaises(libxc.RecordError, v.verify_record_page_data, + rec(libxc.PAGE_DATA_ALGO_LZ4, FULL)) + self.assertRaises(libxc.RecordError, v.verify_record_page_data, + rec(libxc.PAGE_DATA_ALGO_LZ4, FRAME, XTAB)) + + # ... and against the frame having a whole header with block checksums. + self.assertRaises(libxc.RecordError, v.verify_record_page_data, + rec(libxc.PAGE_DATA_ALGO_LZ4, + FRAME[:4] + b"\x60" + FRAME[5:])) + self.assertRaises(libxc.RecordError, v.verify_record_page_data, + rec(libxc.PAGE_DATA_ALGO_LZ4, FRAME[:6])) + # An unimplemented algorithm, and any reserved bit, are refused. self.assertRaises(libxc.StreamError, v.verify_record_page_data, - rec(libxc.PAGE_DATA_ALGO_NONE + 1, PAGE)) + rec(libxc.PAGE_DATA_ALGO_LZ4 + 1, FRAME)) for bit in range(8, 32): self.assertRaises(libxc.StreamError, v.verify_record_page_data, rec(1 << bit, PAGE))
PATCH v2 4/9 tools/libs/guest: compress PAGE_DATA records with LZ4 on save
In reply to Marcus Granadowrite_batch() sends the pages of each batch uncompressed, writing iovecs which point into the foreign mapping straight to the stream. Restore decodes PAGE_DATA algorithm 0x01, LZ4, but nothing emits it, so memory which compresses well still crosses the link at full size.
When ctx->save.compression selects LZ4, copy the batch's page data into a staging buffer, compress it into one LZ4 frame with block checksums, and send the frame, zero-padded to REC_ALIGN, in place of the pages. Send the batch uncompressed unless the frame is strictly shorter than the page data, as the stream specification requires of a saver.
The copy is required: LZ4 may encode a page P by reference to an earlier page Q, checked against Q's current bytes but rebuilt from Q as encoded earlier in the frame. A guest write to Q in between corrupts P undetected, as the block checksums cover the compressed data, and P is not re-sent unless the guest writes it again.
Stage from the iov rather than the mapping, as only the iov describes the record: PV pagetables are normalised into separately allocated pages, and a page deferred on EAGAIN stays in the mapping but has no data in the record.
The batch is staged whole and compressed as one block of up to 4MB; copying in smaller chunks interleaved with compression was slower in most configurations measured.
The two buffers, about 8MB together, are allocated on first use. If allocation or compression fails, compression is switched off for the rest of the save rather than failing it. The encoder is guarded by XG_SR_LZ4, as the decoder is.
Nothing sets ctx->save.compression yet, so behaviour is unchanged.
---
Notes:
Changes in v2:
- Was v1 3/6.
- One LZ4 frame per batch, carried in PAGE_DATA and compressed from a staged copy of the page data, replaces per-page blocks compressed from the live mapping in a separate record type.
- Send compressed whenever the frame is shorter (v1: below 97%).
- If allocation fails, compression is switched off rather than failing the save (v1 failed it).
tools/libs/guest/xg_sr_common.h | 14 ++++ tools/libs/guest/xg_sr_save.c | 133 ++++++++++++++++++++++++++++++++ 2 files changed, 147 insertions(+)
tools/libs/guest/xg_sr_common.h +14 -0
@@ -221,6 +221,12 @@ static inline int update_blob(struct xc_sr_blob *blob,return 0 ; } +enum xc_sr_compression +{ +XC_SR_COMPRESS_NONE , +XC_SR_COMPRESS_LZ4 , +}; +struct xc_sr_context {xc_interface *xch;
@@ -265,6 +271,14 @@ struct xc_sr_contextuint64_t rec_pfns[MAX_BATCH_SIZE ];int errors[MAX_BATCH_SIZE ]; } *buffers; + +/* Which algorithm to compress page data with. */ +enum xc_sr_compression compression; + +/* LZ4 staging and output buffers, allocated on first use. */ +void *lz4_staging_buf; +void *lz4_compress_buf; +size_t lz4_compress_buf_size; } save; struct /* Restore data. */
tools/libs/guest/xg_sr_save.c +133 -0
151 lines not on this page · raw message
Signature · 1 line
2.43.0
Re: [PATCH v2 4/9] tools/libs/guest: compress PAGE_DATA records with LZ4 on save
Le 20/10/2026 à 22:05, Marcus Granado a écrit :
Quoted 72 lines
write_batch()sends the pages of each batch uncompressed, writing iovecs which point into the foreign mapping straight to the stream. Restore decodesPAGE_DATAalgorithm0x01, LZ4, but nothing emits it, so memory which compresses well still crosses the link at full size.When
ctx->save.compressionselects LZ4, copy the batch's page data into a staging buffer, compress it into one LZ4 frame with block checksums, and send the frame, zero-padded toREC_ALIGN, in place of the pages. Send the batch uncompressed unless the frame is strictly shorter than the page data, as the stream specification requires of a saver.The copy is required: LZ4 may encode a page P by reference to an earlier page Q, checked against Q's current bytes but rebuilt from Q as encoded earlier in the frame. A guest write to Q in between corrupts P undetected, as the block checksums cover the compressed data, and P is not re-sent unless the guest writes it again.
Stage from the iov rather than the mapping, as only the iov describes the record: PV pagetables are normalised into separately allocated pages, and a page deferred on EAGAIN stays in the mapping but has no data in the record.
The batch is staged whole and compressed as one block of up to 4MB; copying in smaller chunks interleaved with compression was slower in most configurations measured.
The two buffers, about 8MB together, are allocated on first use. If allocation or compression fails, compression is switched off for the rest of the save rather than failing it. The encoder is guarded by
XG_SR_LZ4, as the decoder is.Nothing sets
ctx->save.compressionyet, so behaviour is unchanged.Suggested-by Frediano Ziglio <[email protected]>Suggested-by Teddy Astie <[email protected]>Assisted-by Claude:claude-opus-5-5Signed-off-by Marcus Granado <[email protected]>---
Notes:
Changes in v2:
- Was v1 3/6.
- One LZ4 frame per batch, carried inPAGE_DATAand compressed from a staged copy of the page data, replaces per-page blocks compressed from the live mapping in a separate record type.
- Send compressed whenever the frame is shorter (v1: below 97%).
- If allocation fails, compression is switched off rather than failing the save (v1 failed it).tools/libs/guest/xg_sr_common.h | 14 ++++ tools/libs/guest/xg_sr_save.c | 133 ++++++++++++++++++++++++++++++++ 2 files changed, 147 insertions(+)tools/libs/guest/xg_sr_common.h +6
-0@@ -221,6 +221,12 @@ static inline int update_blob(struct xc_sr_blob *blob,return 0 ; } +enum xc_sr_compression +{ +XC_SR_COMPRESS_NONE , +XC_SR_COMPRESS_LZ4 , +}; +struct xc_sr_context {xc_interface *xch;@@ -265,6 +271,14 @@ struct xc_sr_contextuint64_t rec_pfns[MAX_BATCH_SIZE ];
tools/libs/guest/xg_sr_common.h struct xc_sr_context · line 281
Quoted 10 lines
tools/libs/guest/xg_sr_common.h +8
-0int errors[MAX_BATCH_SIZE ]; } *buffers; + +/* Which algorithm to compress page data with. */ +enum xc_sr_compression compression; + +/* LZ4 staging and output buffers, allocated on first use. */ +void *lz4_staging_buf; +void *lz4_compress_buf; +size_t lz4_compress_buf_size;
Similar remark as for decompression side (gate lz4-specific variables behind XG_SR_LZ4.
Quoted 16 lines
tools/libs/guest/xg_sr_common.h +0
-0} save; struct /* Restore data. */tools/libs/guest/xg_sr_save.c +5
-0@@ -73,6 +73,118 @@ static int write_checkpoint_record(struct xc_sr_context *ctx)return write_record (ctx, &checkpoint); } +static void cleanup_compression (struct xc_sr_context *ctx) +{ +free (ctx->save.lz4_staging_buf); +free (ctx->save.lz4_compress_buf); + ctx->save.lz4_staging_buf =NULL ;
tools/libs/guest/xg_sr_save.c static int write_checkpoint_record(struct xc_sr_context *ctx) · line 90
Quoted 10 lines
tools/libs/guest/xg_sr_save.c +10
-0+ ctx->save.lz4_compress_buf =NULL ; + ctx->save.lz4_compress_buf_size =0 ; +} + +#if defined(XG_SR_LZ4 ) +/* +* One block per 4MB batch: smaller blocks can be 2x slower to decode. +* liblz4 allows 64KB, 256KB, 1MB and 4MB. +*/ +#define XC_SR_COMPRESS_BLOCK_SIZE LZ4F_max4MB
I'm not fully convinced this macro helps a lot given that it's only used below for setting blockSizeID. I would just move the comment and fold LZ4F_max4MB to its only user.
Quoted 49 lines
tools/libs/guest/xg_sr_save.c +49
-0+ +/* +* Compress the page data in iov[2..iovcnt) into an LZ4 frame, and replace +* those entries with one describing it, padded to the record alignment. +* Returns the new iovcnt, the original one with iov untouched if the batch +* should be sent uncompressed, or -1 if the batch itself is malformed. +*/ +static int lz4_compress_batch (struct xc_sr_context *ctx,struct iovec *iov, +int iovcnt,unsigned int nr_pages, +uint32_t *flags,uint32_t *length) +{ +static const LZ4F_preferences_t prefs = { + .frameInfo = { + .blockSizeID =XC_SR_COMPRESS_BLOCK_SIZE , + .blockChecksumFlag = LZ4F_blockChecksumEnabled, + }, + }; +xc_interface *xch = ctx->xch; +size_t raw = (size_t )nr_pages *PAGE_SIZE , clen, staged; +uint8_t *dst; +int i; + +if ( nr_pages ==0 ) +return iovcnt; + +if ( !ctx->save.lz4_staging_buf ) + { +size_t bound =LZ4F_compressFrameBound (MAX_BATCH_SIZE *PAGE_SIZE , + &prefs); + + ctx->save.lz4_staging_buf =malloc (MAX_BATCH_SIZE *PAGE_SIZE ); + ctx->save.lz4_compress_buf =malloc (bound); + ctx->save.lz4_compress_buf_size = bound; + +if ( !ctx->save.lz4_staging_buf || !ctx->save.lz4_compress_buf ) + { +IPRINTF ("Unable to allocate LZ4 buffers, sending uncompressed" ); +cleanup_compression (ctx); + ctx->save.compression =XC_SR_COMPRESS_NONE ; +return iovcnt; + } + } + +/* The iov must match nr_pages, or stale bytes would be compressed. */ +for ( i =2 , staged =0 ; i < iovcnt; ++i ) + staged += iov[i].iov_len; +if ( staged != raw ) + { +ERROR ("Staged %zu bytes for a batch of %u pages" , staged, nr_pages);
tools/libs/guest/xg_sr_save.c static int write_checkpoint_record(struct xc_sr_context *ctx) · line 149
Quoted 10 lines
tools/libs/guest/xg_sr_save.c +10
-0+return -1 ; + } + +/* LZ4 must not read live guest memory: the frame could decode wrong. */ +for ( i =2 , dst = ctx->save.lz4_staging_buf; i < iovcnt; ++i ) + { +memcpy (dst, iov[i].iov_base, iov[i].iov_len); + dst += iov[i].iov_len; + } +
Should work in practice as is, but I would add xen_barrier() (compiler barrier) right after the for loop and before the LZ4F_compressFrame() for correctness, so that the compiler is not allowed to elide the staging buffer copy inside LZ4F_compressFrame().
(in practice, that can't happen as the compiler hasn't visibility on LZ4F_compressFrame() internals to perform such optimization, as it's a external library)
Quoted 76 lines
tools/libs/guest/xg_sr_save.c +59
-0+ clen =LZ4F_compressFrame (ctx->save.lz4_compress_buf, + ctx->save.lz4_compress_buf_size, + ctx->save.lz4_staging_buf, raw, &prefs); + +if (LZ4F_isError (clen) ) + { +IPRINTF ("LZ4 compression failed: %s, sending uncompressed" , +LZ4F_getErrorName (clen)); +cleanup_compression (ctx); + ctx->save.compression =XC_SR_COMPRESS_NONE ; +return iovcnt; + } + +/* The stream format allows LZ4 only when strictly shorter. */ +if ( clen >= raw ) + { +DBGPRINTF ("LZ4: %zu -> %zu bytes, sending uncompressed" , raw, clen); +return iovcnt; + } + +DBGPRINTF ("LZ4: %zu -> %zu bytes (%zu.%zu%% ratio)" , raw, clen, + (clen *1000 / raw) /10 , (clen *1000 / raw) %10 ); + +/* Pad in place: raw is a multiple of REC_ALIGN and > clen, so it fits. */ +memset ((uint8_t *)ctx->save.lz4_compress_buf + clen,0 , +ROUNDUP (clen,REC_ALIGN ) - clen); + + iov[2 ].iov_base = ctx->save.lz4_compress_buf; + iov[2 ].iov_len =ROUNDUP (clen,REC_ALIGN ); + + *flags |=PAGE_DATA_ALGO_LZ4 ; + *length -= raw - clen; + +/* iov[0] headers, iov[1] pfns, iov[2] page data frame. */ + return 3; +} +#endif /* XG_SR_LZ4 */ +/* * Writes a batch of memory as a PAGE_DATA record into the stream. The batch * is constructed in ctx->save.buffers->batch_pfns. @@ -228,6 +340,26 @@ static int write_batch(struct xc_sr_context *ctx)for ( i =0 ; i < nr_pfns; ++i ) rec_pfns[i] = ((uint64_t )(types[i]) <<32 ) | batch_pfns[i]; +switch ( ctx->save.compression ) + { +case XC_SR_COMPRESS_NONE : +break ; + +case XC_SR_COMPRESS_LZ4 : +#if defined(XG_SR_LZ4 ) + iovcnt =lz4_compress_batch (ctx, iov, iovcnt, nr_pages, + &hdrs.page_data.flags, &hdrs.rec.length); +/* +* -1: iov[2..] is not nr_pages pages. Compressed: stale bytes for +* missing pages, or extra pages dropped, unseen by the checksums. +* Uncompressed: rec.length would not match the bytes writev() writes. +*/ +if ( iovcnt <0 ) + goto err; +#endif +break ; + } +if (writev_exact (ctx->fd, iov, iovcnt) ) {PERROR ("Failed to write page data to stream" );@@ -807,6 +939,7 @@ static void cleanup(struct xc_sr_context *ctx) NRPAGES(bitmap_size(ctx->save.p2m_size)));free (ctx->save.deferred_pages);free (ctx->save.buffers); +cleanup_compression (ctx); }/*
PATCH v2 5/9 tools/libs/guest: stop compressing PAGE_DATA when it stops paying off
In reply to Marcus GranadoWhen LZ4 compression is in use, write_batch() compresses the page data of every batch until the end of the save, whatever the result. For a guest whose memory hardly compresses, this spends CPU at both ends for little or no reduction of the stream.
Total the page data bytes before and after compression over each precopy iteration, counting a batch sent uncompressed as no saving. If an iteration's total after compression is 90% or more of its total before, stop compressing for the rest of the save.
The check runs in send_memory_live() at the end of each precopy iteration. A non-live save (xc_domain_save() without XCFLAGS_LIVE) has no precopy iterations, so it never stops compressing.
The 90% threshold is a heuristic; a poor choice costs CPU or bandwidth, never correctness. Log, at info level, the ratio of each judged iteration, the decision to stop and a summary of the batches sent while compression was on.
---
Notes:
Changes in v2:
- Was v1 4/6, "adaptively disable LZ4 on poor compression ratio".
- A batch sent uncompressed counts as no saving; v1 counted its compressed size.
tools/libs/guest/xg_sr_common.h | 9 +++++ tools/libs/guest/xg_sr_save.c | 69 +++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+)
tools/libs/guest/xg_sr_common.h +9 -0
@@ -275,6 +275,15 @@ struct xc_sr_context/* Which algorithm to compress page data with. */ enum xc_sr_compression compression; +/* +* Page data bytes before (raw) and after (out) compression, in +* the current iteration and in all iterations so far. +*/ +uint64_t compress_raw_total; +uint64_t compress_out_total; +uint64_t compress_raw_all_total; +uint64_t compress_out_all_total; +/* LZ4 staging and output buffers, allocated on first use. */ void *lz4_staging_buf;void *lz4_compress_buf;
tools/libs/guest/xg_sr_save.c +69 -0
98 lines not on this page · raw message
Signature · 1 line
2.43.0
Re: [PATCH v2 5/9] tools/libs/guest: stop compressing PAGE_DATA when it stops paying off
Le 20/10/2026 à 22:05, Marcus Granado a écrit :
Quoted 113 lines
When LZ4 compression is in use,
write_batch()compresses the page data of every batch until the end of the save, whatever the result. For a guest whose memory hardly compresses, this spends CPU at both ends for little or no reduction of the stream.Total the page data bytes before and after compression over each precopy iteration, counting a batch sent uncompressed as no saving. If an iteration's total after compression is 90% or more of its total before, stop compressing for the rest of the save.
The check runs in
send_memory_live()at the end of each precopy iteration. A non-live save (xc_domain_save()withoutXCFLAGS_LIVE) has no precopy iterations, so it never stops compressing.The 90% threshold is a heuristic; a poor choice costs CPU or bandwidth, never correctness. Log, at info level, the ratio of each judged iteration, the decision to stop and a summary of the batches sent while compression was on.
Suggested-by Edwin Török <[email protected]>Assisted-by Claude:claude-opus-5-5Signed-off-by Marcus Granado <[email protected]>---
Notes:
Changes in v2:
- Was v1 4/6, "adaptively disable LZ4 on poor compression ratio".
- A batch sent uncompressed counts as no saving; v1 counted its compressed size.tools/libs/guest/xg_sr_common.h | 9 +++++ tools/libs/guest/xg_sr_save.c | 69 +++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+)tools/libs/guest/xg_sr_common.h +9
-0@@ -275,6 +275,15 @@ struct xc_sr_context/* Which algorithm to compress page data with. */ enum xc_sr_compression compression; +/* +* Page data bytes before (raw) and after (out) compression, in +* the current iteration and in all iterations so far. +*/ +uint64_t compress_raw_total; +uint64_t compress_out_total; +uint64_t compress_raw_all_total; +uint64_t compress_out_all_total; +/* LZ4 staging and output buffers, allocated on first use. */ void *lz4_staging_buf;void *lz4_compress_buf;tools/libs/guest/xg_sr_save.c +51
-0@@ -83,6 +83,67 @@ static void cleanup_compression(struct xc_sr_context *ctx) }#if defined(XG_SR_LZ4 ) +static void compress_stats_reset (struct xc_sr_context *ctx) +{ + ctx->save.compress_raw_total =0 ; + ctx->save.compress_out_total =0 ; +} + +static void compress_stats_accumulate (struct xc_sr_context *ctx, +size_t raw_len,size_t compressed_len) +{ + ctx->save.compress_raw_total += raw_len; + ctx->save.compress_out_total += compressed_len; + ctx->save.compress_raw_all_total += raw_len; + ctx->save.compress_out_all_total += compressed_len; +} + +static void compress_stats_summary (const struct xc_sr_context *ctx) +{ +xc_interface *xch = ctx->xch; +uint64_t raw = ctx->save.compress_raw_all_total; +uint64_t out = ctx->save.compress_out_all_total; +unsigned int permil; + +if ( !raw ) +return ; + + permil = out *1000 / raw; +IPRINTF ("Compression summary: compressed %" PRIu64" -> %" PRIu64" bytes (%u.%u%% average ratio) while compression was on" , + raw, out, permil /10 , permil %10 ); +} + +#define XC_SR_COMPRESS_ITER_THRESHOLD 90 + +static void compress_stats_evaluate (struct xc_sr_context *ctx) +{ +xc_interface *xch = ctx->xch; +uint64_t raw = ctx->save.compress_raw_total; +uint64_t out = ctx->save.compress_out_total; +unsigned int iter = ctx->save.stats.iteration; + +if ( ctx->save.compression ==XC_SR_COMPRESS_NONE ) +return ; + +if ( raw ) + { +unsigned int permil = out *1000 / raw; + +IPRINTF ("Iteration %u: compressed %" PRIu64" -> %" PRIu64" bytes (%u.%u%% average ratio)" , + iter, raw, out, permil /10 , permil %10 ); + +if ( out *100 >= raw *XC_SR_COMPRESS_ITER_THRESHOLD ) + {
tools/libs/guest/xg_sr_save.c static void cleanup_compression(struct xc_sr_context *ctx) · line 146
Quoted 10 lines
tools/libs/guest/xg_sr_save.c +10
-0+IPRINTF ("Iteration %u: at or above the %u%% threshold - disabling compression for remaining iterations" , + iter,XC_SR_COMPRESS_ITER_THRESHOLD ); + ctx->save.compression =XC_SR_COMPRESS_NONE ; +cleanup_compression (ctx); + } + } + +compress_stats_reset (ctx); +} +
I think we can add a condition where the evaluation only occurs if enough pages got evaluated, otherwise, a iteration with only a few uncompressible pages would turn off the compression for the remainder, even if it would have compressed well.
Quoted 28 lines
tools/libs/guest/xg_sr_save.c +5
-0/* * One block per 4MB batch: smaller blocks can be 2x slower to decode. * liblz4 allows 64KB, 256KB, 1MB and 4MB. @@ -164,11 +225,13 @@ static int lz4_compress_batch(struct xc_sr_context *ctx, struct iovec *iov,if ( clen >= raw ) {DBGPRINTF ("LZ4: %zu -> %zu bytes, sending uncompressed" , raw, clen); +compress_stats_accumulate (ctx, raw, raw);return iovcnt; }DBGPRINTF ("LZ4: %zu -> %zu bytes (%zu.%zu%% ratio)" , raw, clen, (clen *1000 / raw) /10 , (clen *1000 / raw) %10 ); +compress_stats_accumulate (ctx, raw, clen);/* Pad in place: raw is a multiple of REC_ALIGN and > clen, so it fits. */ memset((uint8_t *)ctx->save.lz4_compress_buf + clen, 0,@@ -638,6 +701,9 @@ static int send_memory_live(struct xc_sr_context *ctx) rc =send_dirty_pages (ctx, stats.dirty_count);if ( rc ) goto out; +#if defined(XG_SR_LZ4 ) +compress_stats_evaluate (ctx); +#endif }if ( policy_decision !=XGS_POLICY_CONTINUE_PRECOPY )
tools/libs/guest/xg_sr_save.c static void cleanup(struct xc_sr_context *ctx) · line 1013
Quoted 9 lines
tools/libs/guest/xg_sr_save.c +3
-0@@ -939,6 +1005,9 @@ static void cleanup(struct xc_sr_context *ctx) NRPAGES(bitmap_size(ctx->save.p2m_size)));free (ctx->save.deferred_pages);free (ctx->save.buffers); +#if defined(XG_SR_LZ4 ) +compress_stats_summary (ctx); +#endif cleanup_compression (ctx); }
Overall, I think it would be preferable to have a lightweight heuristic to know if a page is likely to compress well, rather than empirically turning it off based on stats. But that's probably best answered with testing and benchmarks.
Teddy
PATCH v2 6/9 tools/libs/guest: add XCFLAGS_COMPRESS_LZ4 to request LZ4 compression
In reply to Marcus GranadoNothing sets ctx->save.compression to XC_SR_COMPRESS_LZ4, so the LZ4 path in write_batch() is unreachable and a caller of xc_domain_save() has no way to ask for compressed PAGE_DATA records.
Add XCFLAGS_COMPRESS_LZ4 and select LZ4 when it is set. A caller which does not set it sees no change; one which does needs a receiver able to decompress LZ4.
A libxenguest built without a supported liblz4 cannot honour the flag, so fail up front with EOPNOTSUPP rather than silently send uncompressed records.
---
Notes:
Changes in v2:
- Was v1 5/6.
- Set ctx->save.compression; the field moved into the save context.
Bit 2 was XCFLAGS_HVM until commit 2004db3ced18 ("tools/save: Drop unused parameters from xc_domain_save()") removed it in 4.14.
tools/include/xenguest.h | 5 +++-- tools/libs/guest/xg_sr_save.c | 11 +++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-)
tools/include/xenguest.h +3 -2
@@ -24,8 +24,9 @@#define XC_NUMA_NO_NODE (~0U) -#define XCFLAGS_LIVE (1 << 0) -#define XCFLAGS_DEBUG (1 << 1) +#define XCFLAGS_LIVE (1 << 0) +#define XCFLAGS_DEBUG (1 << 1) +#define XCFLAGS_COMPRESS_LZ4 (1 << 2)/* LZ4 on save; restorer needs LZ4 */ #define X86_64_B_SIZE 64#define X86_32_B_SIZE 32
tools/libs/guest/xg_sr_save.c +11 -0
@@ -1166,6 +1166,17 @@ int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom, ctx.save.debug = !!(flags &XCFLAGS_DEBUG ); ctx.save.recv_fd = recv_fd; +if ( flags &XCFLAGS_COMPRESS_LZ4 ) + { +#if defined(XG_SR_LZ4 ) + ctx.save.compression =XC_SR_COMPRESS_LZ4 ; +#else +ERROR ("XCFLAGS_COMPRESS_LZ4 requested but libxenguest was built without a supported liblz4" ); + errno =EOPNOTSUPP ; +return -1 ; +#endif + } +if (xc_domain_getinfo_single (xch, dom, &ctx.dominfo) <0 ) {PERROR ("Failed to get domain info" );
Signature · 1 line
2.43.0
Re: [PATCH v2 6/9] tools/libs/guest: add XCFLAGS_COMPRESS_LZ4 to request LZ4 compression
Le 20/10/2026 à 22:05, Marcus Granado a écrit :
Quoted 56 lines
Nothing sets
ctx->save.compressiontoXC_SR_COMPRESS_LZ4, so the LZ4 path inwrite_batch()is unreachable and a caller ofxc_domain_save()has no way to ask for compressedPAGE_DATArecords.Add
XCFLAGS_COMPRESS_LZ4and select LZ4 when it is set. A caller which does not set it sees no change; one which does needs a receiver able to decompress LZ4.A libxenguest built without a supported liblz4 cannot honour the flag, so fail up front with EOPNOTSUPP rather than silently send uncompressed records.
Assisted-by Claude:claude-opus-5-5Signed-off-by Marcus Granado <[email protected]>---
Notes:
Changes in v2:
- Was v1 5/6.
- Setctx->save.compression; the field moved into the save context.Bit 2 was
XCFLAGS_HVMuntil commit2004db3ced18("tools/save: Drop unused parameters fromxc_domain_save()") removed it in 4.14.tools/include/xenguest.h | 5 +++-- tools/libs/guest/xg_sr_save.c | 11 +++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-)tools/include/xenguest.h +3
-2@@ -24,8 +24,9 @@#define XC_NUMA_NO_NODE (~0U) -#define XCFLAGS_LIVE (1 << 0) -#define XCFLAGS_DEBUG (1 << 1) +#define XCFLAGS_LIVE (1 << 0) +#define XCFLAGS_DEBUG (1 << 1) +#define XCFLAGS_COMPRESS_LZ4 (1 << 2)/* LZ4 on save; restorer needs LZ4 */ #define X86_64_B_SIZE 64#define X86_32_B_SIZE 32tools/libs/guest/xg_sr_save.c +4
-0@@ -1166,6 +1166,17 @@ int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom, ctx.save.debug = !!(flags &XCFLAGS_DEBUG ); ctx.save.recv_fd = recv_fd; +if ( flags &XCFLAGS_COMPRESS_LZ4 ) + { +#if defined(XG_SR_LZ4 ) + ctx.save.compression =XC_SR_COMPRESS_LZ4 ;
tools/libs/guest/xg_sr_save.c int xc_domain_save(xc_interface *xch, int io_fd, uint32_t dom, · line 1182
Quoted 10 lines
tools/libs/guest/xg_sr_save.c +7
-0+#else +ERROR ("XCFLAGS_COMPRESS_LZ4 requested but libxenguest was built without a supported liblz4" ); + errno =EOPNOTSUPP ; +return -1 ; +#endif + } +if (xc_domain_getinfo_single (xch, dom, &ctx.dominfo) <0 ) {PERROR ("Failed to get domain info" );
Teddy
PATCH v2 7/9 tools/libxl,xl: add a --compress option to xl migrate
In reply to Marcus Granadolibxenguest can compress PAGE_DATA records with LZ4 when its caller sets XCFLAGS_COMPRESS_LZ4, but libxl never sets it, so xl has no way to ask for compression.
Add a LIBXL_SUSPEND_COMPRESS_LZ4 flag for libxl_domain_suspend(), pass it to libxenguest as XCFLAGS_COMPRESS_LZ4, and expose it as "xl migrate --compress".
Off by default: whether compressing pays off depends on how compressible the guest's memory is and on the CPU headroom of both hosts, so the caller decides. Only xl migrate gets the option; xl save and xl remus never use LZ4.
The receiving side needs no option, as each PAGE_DATA record says whether it is compressed. A receiver which cannot decompress rejects the first compressed record, after it has created the domain, and the migration fails with the guest still on the source. A sender whose libxenguest was built without a supported liblz4 fails the migration before sending any guest memory; libxl reports it as a suspend timeout.
---
Notes:
Changes in v2:
- Was v1 6/6. The libxl and xl code is unchanged; the help text and man page now say both hosts need liblz4 support in libxenguest, and CHANGELOG.md has an entry.
No LIBXL_HAVE_* macro: LIBXL_SUSPEND_COMPRESS_LZ4 is itself a #define, so a caller can test for it with #ifdef LIBXL_SUSPEND_COMPRESS_LZ4.
CHANGELOG.md | 3 +++ docs/man/xl.1.pod.in | 8 ++++++++ tools/include/libxl.h | 1 + tools/libs/light/libxl_dom_save.c | 4 +++- tools/libs/light/libxl_domain.c | 1 + tools/libs/light/libxl_internal.h | 1 + tools/xl/xl_cmdtable.c | 2 ++ tools/xl/xl_migrate.c | 13 ++++++++++--- 8 files changed, 29 insertions(+), 4 deletions(-)
CHANGELOG.md +3 -0
@@ -16,6 +16,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) afterwards. ### Added + - On x86: + - Optional LZ4 compression of the memory stream during migration + (xl migrate --compress). ### Removed - On Arm:
docs/man/xl.1.pod.in +8 -0
@@ -488,6 +488,14 @@ domain. Display huge (!) amount of debug information during the migration process. +=item B<--compress> + +Compress the memory stream using LZ4 inside libxenguest before sending it +to the destination host. This can significantly reduce migration time on +slow transports, and reduce dom0 CPU pressure during host evacuations when +the migration data is subsequently encrypted or copied through pipes. +Requires liblz4 support in libxenguest on both hosts. + =item B<-p> Leave the domain on the receive side paused after migration.
tools/include/libxl.h +1 -0
@@ -1922,6 +1922,7 @@ int libxl_domain_suspend(libxl_ctx *ctx, uint32_t domid, int fd,LIBXL_EXTERNAL_CALLERS_ONLY ;#define LIBXL_SUSPEND_DEBUG 1#define LIBXL_SUSPEND_LIVE 2 +#define LIBXL_SUSPEND_COMPRESS_LZ4 4/* * Only suspend domain, do not save its state to file, do not destroy it.
tools/libs/light/libxl_dom_save.c +3 -1
@@ -245,6 +245,7 @@ void libxl__domain_save(libxl__egc *egc, libxl__domain_save_state *dss)const libxl_domain_type type = dss->type;const int live = dss->live;const int debug = dss->debug; +const int compress_lz4 = dss->compress_lz4;const libxl_domain_remus_info *const r_info = dss->remus;libxl__srm_save_autogen_callbacks *const callbacks = &dss->sws.shs.callbacks.save.a;
@@ -269,7 +270,8 @@ void libxl__domain_save(libxl__egc *egc, libxl__domain_save_state *dss)if (rc) goto out; dss->xcflags = (live ?XCFLAGS_LIVE :0 ) - | (debug ?XCFLAGS_DEBUG :0 ); + | (debug ?XCFLAGS_DEBUG :0 ) + | (compress_lz4 ?XCFLAGS_COMPRESS_LZ4 :0 );/* Disallow saving a guest with vNUMA configured because migration * stream does not preserve node information.
tools/libs/light/libxl_domain.c +1 -0
@@ -527,6 +527,7 @@ int libxl_domain_suspend(libxl_ctx *ctx, uint32_t domid, int fd, int flags, dss->type = type; dss->live = flags &LIBXL_SUSPEND_LIVE ; dss->debug = flags &LIBXL_SUSPEND_DEBUG ; + dss->compress_lz4 = flags &LIBXL_SUSPEND_COMPRESS_LZ4 ; dss->checkpointed_stream =LIBXL_CHECKPOINTED_STREAM_NONE ; rc = libxl__fd_flags_modify_save(gc, dss->fd,
tools/libs/light/libxl_internal.h +1 -0
@@ -3598,6 +3598,7 @@ struct libxl__domain_save_state {libxl_domain_type type;int live;int debug; +int compress_lz4;int checkpointed_stream;const libxl_domain_remus_info *remus;/* private */
tools/xl/xl_cmdtable.c +2 -0
@@ -174,6 +174,8 @@ const struct cmd_spec cmd_table[] = {"-e Do not wait in the background (on <host>) for the death\n" " of the domain.\n" "--debug Print huge (!) amount of debug during the migration process.\n" +"--compress Compress the memory stream using LZ4 in libxenguest.\n" +" Requires liblz4 support in libxenguest on both hosts.\n" "-p Do not unpause domain after migrating it.\n" "-D Preserve the domain id" },
tools/xl/xl_migrate.c +10 -3
@@ -177,7 +177,7 @@ static void migrate_do_preamble(int send_fd, int recv_fd, pid_t child, }static void migrate_domain (uint32_t domid,int preserve_domid, -const char *rune,int debug, +const char *rune,int debug,int compress_lz4,const char *override_config_file) {pid_t child =-1 ;
@@ -206,6 +206,8 @@ static void migrate_domain(uint32_t domid, int preserve_domid,if (debug) flags |=LIBXL_SUSPEND_DEBUG ; +if (compress_lz4) + flags |=LIBXL_SUSPEND_COMPRESS_LZ4 ; rc =libxl_domain_suspend (ctx, domid, send_fd, flags,NULL );if (rc) { fprintf(stderr, "migration sender: libxl_domain_suspend failed"
@@ -538,10 +540,11 @@ int main_migrate(int argc, char **argv)char *rune =NULL ;char *host;int opt, daemonize =1 , monitor =1 , debug =0 , pause_after_migration =0 ; -int preserve_domid =0 ; +int preserve_domid =0 , compress_lz4 =0 ;static struct option opts[] = { {"debug" ,0 ,0 ,0x100 }, {"live" ,0 ,0 ,0x200 }, + {"compress" ,0 ,0 ,0x300 },COMMON_LONG_OPTS };
@@ -571,6 +574,9 @@ int main_migrate(int argc, char **argv)case 0x200 :/* --live */ /* ignored for compatibility with xm */ break ; +case 0x300 :/* --compress */ + compress_lz4 =1 ; +break ; } domid =find_domain (argv[optind]);
@@ -602,7 +608,8 @@ int main_migrate(int argc, char **argv) pause_after_migration ? " -p" : ""); } -migrate_domain (domid, preserve_domid, rune, debug, config_filename); +migrate_domain (domid, preserve_domid, rune, debug, compress_lz4, + config_filename);return EXIT_SUCCESS ; }
Signature · 1 line
2.43.0
Re: [PATCH v2 7/9] tools/libxl,xl: add a --compress option to xl migrate
Le 20/10/2026 à 22:05, Marcus Granado a écrit :
Quoted 20 lines
libxenguest can compress
PAGE_DATArecords with LZ4 when its caller setsXCFLAGS_COMPRESS_LZ4, but libxl never sets it, so xl has no way to ask for compression.Add a
LIBXL_SUSPEND_COMPRESS_LZ4flag forlibxl_domain_suspend(), pass it to libxenguest asXCFLAGS_COMPRESS_LZ4, and expose it as "xl migrate --compress".Off by default: whether compressing pays off depends on how compressible the guest's memory is and on the CPU headroom of both hosts, so the caller decides. Only xl migrate gets the option; xl save and xl remus never use LZ4.
The receiving side needs no option, as each
PAGE_DATArecord says whether it is compressed. A receiver which cannot decompress rejects the first compressed record, after it has created the domain, and the migration fails with the guest still on the source. A sender whose libxenguest was built without a supported liblz4 fails the migration before sending any guest memory; libxl reports it as a suspend timeout.
Quoted 3 lines
Assisted-by Claude:claude-opus-5-5Signed-off-by Marcus Granado <[email protected]>---
I wonder if we should name the option "--compress-lz4", like it is used in the code (compress_lz4, XCFLAGS_COMPRESS_LZ4, LIBXL_SUSPEND_COMPRESS_LZ4, ...).
Quoted 58 lines
Notes:
Changes in v2:
- Was v1 6/6. The libxl and xl code is unchanged; the help text and man page now say both hosts need liblz4 support in libxenguest, and CHANGELOG.md has an entry.No LIBXL_HAVE_* macro:
LIBXL_SUSPEND_COMPRESS_LZ4is itself a #define, so a caller can test for it with #ifdefLIBXL_SUSPEND_COMPRESS_LZ4.CHANGELOG.md | 3 +++ docs/man/xl.1.pod.in | 8 ++++++++ tools/include/libxl.h | 1 + tools/libs/light/libxl_dom_save.c | 4 +++- tools/libs/light/libxl_domain.c | 1 + tools/libs/light/libxl_internal.h | 1 + tools/xl/xl_cmdtable.c | 2 ++ tools/xl/xl_migrate.c | 13 ++++++++++--- 8 files changed, 29 insertions(+), 4 deletions(-)CHANGELOG.md +3
-0@@ -16,6 +16,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) afterwards. ### Added + - On x86: + - Optional LZ4 compression of the memory stream during migration + (xl migrate --compress). ### Removed - On Arm:docs/man/xl.1.pod.in +8
-0@@ -488,6 +488,14 @@ domain. Display huge (!) amount of debug information during the migration process. +=item B<--compress> + +Compress the memory stream using LZ4 inside libxenguest before sending it +to the destination host. This can significantly reduce migration time on +slow transports, and reduce dom0 CPU pressure during host evacuations when +the migration data is subsequently encrypted or copied through pipes. +Requires liblz4 support in libxenguest on both hosts. + =item B<-p> Leave the domain on the receive side paused after migration.tools/include/libxl.h +0
-0
tools/include/libxl.h int libxl_domain_suspend(libxl_ctx *ctx, uint32_t domid, int fd, · line 1926
Quoted 5 lines
tools/include/libxl.h +1
-0@@ -1922,6 +1922,7 @@ int libxl_domain_suspend(libxl_ctx *ctx, uint32_t domid, int fd,LIBXL_EXTERNAL_CALLERS_ONLY ;#define LIBXL_SUSPEND_DEBUG 1#define LIBXL_SUSPEND_LIVE 2 +#define LIBXL_SUSPEND_COMPRESS_LZ4 4
I think these wants to be converted to (1<<N) form.
Quoted 107 lines
tools/include/libxl.h +0
-0/* * Only suspend domain, do not save its state to file, do not destroy it. tools/libs/light/libxl_dom_save.c +3
-1@@ -245,6 +245,7 @@ void libxl__domain_save(libxl__egc *egc, libxl__domain_save_state *dss)const libxl_domain_type type = dss->type;const int live = dss->live;const int debug = dss->debug; +const int compress_lz4 = dss->compress_lz4;const libxl_domain_remus_info *const r_info = dss->remus;libxl__srm_save_autogen_callbacks *const callbacks = &dss->sws.shs.callbacks.save.a;@@ -269,7 +270,8 @@ void libxl__domain_save(libxl__egc *egc, libxl__domain_save_state *dss)if (rc) goto out; dss->xcflags = (live ?XCFLAGS_LIVE :0 ) - | (debug ?XCFLAGS_DEBUG :0 ); + | (debug ?XCFLAGS_DEBUG :0 ) + | (compress_lz4 ?XCFLAGS_COMPRESS_LZ4 :0 );/* Disallow saving a guest with vNUMA configured because migration * stream does not preserve node information. tools/libs/light/libxl_domain.c +1
-0@@ -527,6 +527,7 @@ int libxl_domain_suspend(libxl_ctx *ctx, uint32_t domid, int fd, int flags, dss->type = type; dss->live = flags &LIBXL_SUSPEND_LIVE ; dss->debug = flags &LIBXL_SUSPEND_DEBUG ; + dss->compress_lz4 = flags &LIBXL_SUSPEND_COMPRESS_LZ4 ; dss->checkpointed_stream =LIBXL_CHECKPOINTED_STREAM_NONE ; rc = libxl__fd_flags_modify_save(gc, dss->fd,tools/libs/light/libxl_internal.h +1
-0@@ -3598,6 +3598,7 @@ struct libxl__domain_save_state {libxl_domain_type type;int live;int debug; +int compress_lz4;int checkpointed_stream;const libxl_domain_remus_info *remus;/* private */ tools/xl/xl_cmdtable.c +2
-0@@ -174,6 +174,8 @@ const struct cmd_spec cmd_table[] = {"-e Do not wait in the background (on <host>) for the death\n" " of the domain.\n" "--debug Print huge (!) amount of debug during the migration process.\n" +"--compress Compress the memory stream using LZ4 in libxenguest.\n" +" Requires liblz4 support in libxenguest on both hosts.\n" "-p Do not unpause domain after migrating it.\n" "-D Preserve the domain id" },tools/xl/xl_migrate.c +8
-2@@ -177,7 +177,7 @@ static void migrate_do_preamble(int send_fd, int recv_fd, pid_t child, }static void migrate_domain (uint32_t domid,int preserve_domid, -const char *rune,int debug, +const char *rune,int debug,int compress_lz4,const char *override_config_file) {pid_t child =-1 ;@@ -206,6 +206,8 @@ static void migrate_domain(uint32_t domid, int preserve_domid,if (debug) flags |=LIBXL_SUSPEND_DEBUG ; +if (compress_lz4) + flags |=LIBXL_SUSPEND_COMPRESS_LZ4 ; rc =libxl_domain_suspend (ctx, domid, send_fd, flags,NULL );if (rc) { fprintf(stderr, "migration sender: libxl_domain_suspend failed"@@ -538,10 +540,11 @@ int main_migrate(int argc, char **argv)char *rune =NULL ;char *host;int opt, daemonize =1 , monitor =1 , debug =0 , pause_after_migration =0 ; -int preserve_domid =0 ; +int preserve_domid =0 , compress_lz4 =0 ;static struct option opts[] = { {"debug" ,0 ,0 ,0x100 }, {"live" ,0 ,0 ,0x200 }, + {"compress" ,0 ,0 ,0x300 },COMMON_LONG_OPTS };@@ -571,6 +574,9 @@ int main_migrate(int argc, char **argv)case 0x200 :/* --live */ /* ignored for compatibility with xm */ break ; +case 0x300 :/* --compress */ + compress_lz4 =1 ; +break ; } domid =find_domain (argv[optind]);
tools/xl/xl_migrate.c int main_migrate(int argc, char **argv) · line 615
Quoted 9 lines
tools/xl/xl_migrate.c +2
-1@@ -602,7 +608,8 @@ int main_migrate(int argc, char **argv) pause_after_migration ? " -p" : ""); } -migrate_domain (domid, preserve_domid, rune, debug, config_filename); +migrate_domain (domid, preserve_domid, rune, debug, compress_lz4, + config_filename);return EXIT_SUCCESS ; }
The rest looks good to me.
Teddy
PATCH v2 8/9 tools/xl: mark LZ4 migration streams with a mandatory header flag
In reply to Marcus GranadoA receiver which cannot decompress LZ4 rejects the first compressed PAGE_DATA record. That is late: the receiver has already created the domain, precopy has started, and an older libxenguest's error says nothing about compression.
xl can fail earlier. Its save file header carries mandatory_flags, and create_domain() rejects unknown bits before it calls libxl_domain_create_restore(). Similar to commit e72ce244dc91 ("tools/xl: Mandatory flag indicating the format of the migration stream"), claim bit 2 for LZ4 and set it for "xl migrate --compress". An older xl then reports mandatory flag 0x4 as unsupported and creates no domain.
This is defence in depth, for xl-to-xl migration only. An xl which knows the flag but whose libxenguest lacks liblz4 still accepts the header and fails late, at the first compressed PAGE_DATA record, though with an error that names LZ4. The header is written before any record, so a stream in which no record ends up compressed still carries the flag and needs an LZ4-aware xl.
---
Notes:
Changes in v2:
- New, after an off-list question from Ross Lagerwall: an older xl now refuses a compressed stream before it creates the domain.
tools/xl/xl.h | 7 +++++-- tools/xl/xl_migrate.c | 8 ++++---- tools/xl/xl_saverestore.c | 7 +++++-- 3 files changed, 14 insertions(+), 8 deletions(-)
tools/xl/xl.h +5 -2
@@ -77,8 +77,10 @@ static const char migrate_report[]=#define XL_MANDATORY_FLAG_JSON (1U << 0)/* config data is in JSON format */ #define XL_MANDATORY_FLAG_STREAMv2 (1U << 1)/* stream is v2 */ +#define XL_MANDATORY_FLAG_COMPRESS_LZ4 (1U << 2)/* PAGE_DATA may use LZ4 */ #define XL_MANDATORY_FLAG_ALL (XL_MANDATORY_FLAG_JSON | \ - XL_MANDATORY_FLAG_STREAMv2) + XL_MANDATORY_FLAG_STREAMv2 | \ + XL_MANDATORY_FLAG_COMPRESS_LZ4)struct save_file_header {char magic[32 ];/* savefileheader_magic */
@@ -102,7 +104,8 @@ void save_domain_core_begin(uint32_t domid,uint8_t **config_data_r, int *config_len_r);void save_domain_core_writeconfig (int fd,const char *source, -const uint8_t *config_data,int config_len); +const uint8_t *config_data,int config_len, +int compress_lz4);/* * The xl process should always return either EXIT_SUCCESS or
tools/xl/xl_migrate.c +4 -4
@@ -153,7 +153,7 @@ static void migration_child_report(int recv_fd) {static void migrate_do_preamble (int send_fd,int recv_fd,pid_t child,uint8_t *config_data,int config_len, -const char *rune) +const char *rune,int compress_lz4) {int rc =0 ;
@@ -172,7 +172,7 @@ static void migrate_do_preamble(int send_fd, int recv_fd, pid_t child, }save_domain_core_writeconfig (send_fd,"migration stream" , - config_data, config_len); + config_data, config_len, compress_lz4); }
@@ -200,7 +200,7 @@ static void migrate_domain(uint32_t domid, int preserve_domid, child =create_migration_child (rune, &send_fd, &recv_fd);migrate_do_preamble (send_fd, recv_fd, child, config_data, config_len, - rune); + rune, compress_lz4);xtl_stdiostream_adjust_flags (logger,XTL_STDIOSTREAM_HIDE_PROGRESS ,0 );
@@ -740,7 +740,7 @@ int main_remus(int argc, char **argv) child =create_migration_child (rune, &send_fd, &recv_fd);migrate_do_preamble (send_fd, recv_fd, child, config_data, config_len, - rune); + rune,0 );if (ssh_command[0 ])free (rune);
tools/xl/xl_saverestore.c +5 -2
@@ -79,7 +79,8 @@ void save_domain_core_begin(uint32_t domid, }void save_domain_core_writeconfig (int fd,const char *source, -const uint8_t *config_data,int config_len) +const uint8_t *config_data,int config_len, +int compress_lz4) {struct save_file_header hdr;uint8_t *optdata_begin;
@@ -89,6 +90,8 @@ void save_domain_core_writeconfig(int fd, const char *source,memcpy (hdr.magic, savefileheader_magic,sizeof (hdr.magic)); hdr.byteorder =SAVEFILE_BYTEORDER_VALUE ; hdr.mandatory_flags = XL_MANDATORY_FLAG_STREAMv2; +if (compress_lz4) + hdr.mandatory_flags |=XL_MANDATORY_FLAG_COMPRESS_LZ4 ; optdata_begin=0 ;
@@ -144,7 +147,7 @@ static int save_domain(uint32_t domid, int preserve_domid,exit (EXIT_FAILURE ); } -save_domain_core_writeconfig (fd, filename, config_data, config_len); +save_domain_core_writeconfig (fd, filename, config_data, config_len,0 );int rc =libxl_domain_suspend (ctx, domid, fd,0 ,NULL );close (fd);
Signature · 1 line
2.43.0
Re: [PATCH v2 8/9] tools/xl: mark LZ4 migration streams with a mandatory header flag
Le 20/10/2026 à 22:06, Marcus Granado a écrit :
Quoted 20 lines
A receiver which cannot decompress LZ4 rejects the first compressed
PAGE_DATArecord. That is late: the receiver has already created the domain, precopy has started, and an older libxenguest's error says nothing about compression.xl can fail earlier. Its save file header carries
mandatory_flags, andcreate_domain()rejects unknown bits before it callslibxl_domain_create_restore(). Similar to commite72ce244dc91("tools/xl: Mandatory flag indicating the format of the migration stream"), claim bit 2 for LZ4 and set it for "xl migrate --compress". An older xl then reports mandatory flag0x4as unsupported and creates no domain.This is defence in depth, for xl-to-xl migration only. An xl which knows the flag but whose libxenguest lacks liblz4 still accepts the header and fails late, at the first compressed
PAGE_DATArecord, though with an error that names LZ4. The header is written before any record, so a stream in which no record ends up compressed still carries the flag and needs an LZ4-aware xl.
Quoted 3 lines
Assisted-by Claude:claude-opus-5-5Signed-off-by Marcus Granado <[email protected]>---
I think it would be preferable to check for libxenguest lz4 support as well, so that libxenguest without lz4 would fail the same way as libxenguest prior to this patch.
Quoted 109 lines
Notes:
Changes in v2:
- New, after an off-list question from Ross Lagerwall: an older xl now refuses a compressed stream before it creates the domain.tools/xl/xl.h | 7 +++++-- tools/xl/xl_migrate.c | 8 ++++---- tools/xl/xl_saverestore.c | 7 +++++-- 3 files changed, 14 insertions(+), 8 deletions(-)tools/xl/xl.h +5
-2@@ -77,8 +77,10 @@ static const char migrate_report[]=#define XL_MANDATORY_FLAG_JSON (1U << 0)/* config data is in JSON format */ #define XL_MANDATORY_FLAG_STREAMv2 (1U << 1)/* stream is v2 */ +#define XL_MANDATORY_FLAG_COMPRESS_LZ4 (1U << 2)/* PAGE_DATA may use LZ4 */ #define XL_MANDATORY_FLAG_ALL (XL_MANDATORY_FLAG_JSON | \ - XL_MANDATORY_FLAG_STREAMv2) + XL_MANDATORY_FLAG_STREAMv2 | \ + XL_MANDATORY_FLAG_COMPRESS_LZ4)struct save_file_header {char magic[32 ];/* savefileheader_magic */ @@ -102,7 +104,8 @@ void save_domain_core_begin(uint32_t domid,uint8_t **config_data_r, int *config_len_r);void save_domain_core_writeconfig (int fd,const char *source, -const uint8_t *config_data,int config_len); +const uint8_t *config_data,int config_len, +int compress_lz4);/* * The xl process should always return either EXIT_SUCCESS or tools/xl/xl_migrate.c +4
-4@@ -153,7 +153,7 @@ static void migration_child_report(int recv_fd) {static void migrate_do_preamble (int send_fd,int recv_fd,pid_t child,uint8_t *config_data,int config_len, -const char *rune) +const char *rune,int compress_lz4) {int rc =0 ;@@ -172,7 +172,7 @@ static void migrate_do_preamble(int send_fd, int recv_fd, pid_t child, }save_domain_core_writeconfig (send_fd,"migration stream" , - config_data, config_len); + config_data, config_len, compress_lz4); }@@ -200,7 +200,7 @@ static void migrate_domain(uint32_t domid, int preserve_domid, child =create_migration_child (rune, &send_fd, &recv_fd);migrate_do_preamble (send_fd, recv_fd, child, config_data, config_len, - rune); + rune, compress_lz4);xtl_stdiostream_adjust_flags (logger,XTL_STDIOSTREAM_HIDE_PROGRESS ,0 );@@ -740,7 +740,7 @@ int main_remus(int argc, char **argv) child =create_migration_child (rune, &send_fd, &recv_fd);migrate_do_preamble (send_fd, recv_fd, child, config_data, config_len, - rune); + rune,0 );if (ssh_command[0 ])free (rune);tools/xl/xl_saverestore.c +5
-2@@ -79,7 +79,8 @@ void save_domain_core_begin(uint32_t domid, }void save_domain_core_writeconfig (int fd,const char *source, -const uint8_t *config_data,int config_len) +const uint8_t *config_data,int config_len, +int compress_lz4) {struct save_file_header hdr;uint8_t *optdata_begin;@@ -89,6 +90,8 @@ void save_domain_core_writeconfig(int fd, const char *source,memcpy (hdr.magic, savefileheader_magic,sizeof (hdr.magic)); hdr.byteorder =SAVEFILE_BYTEORDER_VALUE ; hdr.mandatory_flags = XL_MANDATORY_FLAG_STREAMv2; +if (compress_lz4) + hdr.mandatory_flags |=XL_MANDATORY_FLAG_COMPRESS_LZ4 ; optdata_begin=0 ;@@ -144,7 +147,7 @@ static int save_domain(uint32_t domid, int preserve_domid,exit (EXIT_FAILURE ); } -save_domain_core_writeconfig (fd, filename, config_data, config_len); +save_domain_core_writeconfig (fd, filename, config_data, config_len,0 );int rc =libxl_domain_suspend (ctx, domid, fd,0 ,NULL );close (fd);
PATCH v2 9/9 tools/libs/guest: compress the PAGE_DATA pfn array too
In reply to Marcus GranadoAn LZ4 PAGE_DATA record compresses only its page data. Its pfn array, 8 bytes per page, still travels in plaintext ahead of the frame.
Define bit 8 of the flags field: the pfn array is compressed too, with the record's algorithm, as a frame of its own immediately before the page data frame. That makes it easier to handle the pfns and the page data separately, in both the saver and restore. Bit 8 needs an algorithm other than PAGE_DATA_ALGO_NONE. For PAGE_DATA_ALGO_LZ4 both frames carry block checksums. The count stays in plaintext, so restore can bound it before decoding anything, and finds the page data frame where decoding the pfn frame ends. The saver sets bit 8 on every batch it compresses, except when a) the pfn frame is no smaller than the array, so would save nothing, or b) the size rule below applies, for backwards compatibility. Restore decodes both frames with a new helper, which resets the LZ4 context before each frame.
This compresses the whole record body apart from count and flags, as discussed in v1. Compressing the pfn array saves a little on real
traffic: 0.33% of the page data bytes for a compressible 64 GiB guest, 0.016% for an incompressible one.
The size rule (b) makes the saver send the pfn array in plaintext when the two frames total 8 * count bytes plus a whole number of pages. A receiver without "tools/libs/guest: reject non-zero reserved fields in PAGE_DATA" ignores the flags field, so it reads the frames as count pfns followed by page data. Its checks of those pfns may let them pass, which leaves its exact length check as the only certain rejection, and that check could pass at exactly those sizes. This rule can be removed once every receiver has that commit, which is marked for backport to 4.17 and later. libxenguest does not check the rule on restore, as that would prevent it ever being removed; only the Python stream checker does, as a test of the saver.
---
Notes:
Changes in v2:
- New in v2. Andrew Cooper suggested the pfn array to be compressed too; in v1 review Frediano Ziglio asked about compressing whole records.
Tested: builds with and without liblz4; the Python unit tests; a round trip of the changed save and restore functions with Xen stubbed out, under ASan and UBSan, through uncompressed records, LZ4 records with plaintext and with compressed pfns, the size-rule fallback and malformed bit-8 records; and live migrations with xl migrate --compress --debug.
docs/specs/libxc-migration-stream.pandoc | 55 ++++++++- tools/libs/guest/xg_sr_restore.c | 140 ++++++++++++++++------- tools/libs/guest/xg_sr_save.c | 59 ++++++++-- tools/libs/guest/xg_sr_stream_format.h | 8 +- tools/python/xen/migration/libxc.py | 43 ++++++- tools/python/xen/migration/tests.py | 39 ++++++- 6 files changed, 284 insertions(+), 60 deletions(-)
docs/specs/libxc-migration-stream.pandoc +54 -1
@@ -326,7 +326,47 @@ flags Bit 7-0: Algorithm used to encode page_data. does not implement, rather than attempting to interpret the page_data. - Bit 31-8: Reserved. Set to zero on save. A restoring side + Bit 8: Compressed pfn array. The pfn array is + compressed too, with the algorithm in bits 7-0. + May only be set when bits 7-0 are not 0x00; a + restoring side must reject the record otherwise. + + When set, the pfn array is not present in + plaintext. The flags field is instead followed + by pfn_frame, whose decompressed content is the + count pfn entries (count * 8 octets, encoded as + for pfn below), then page_data_frame, whose + decompressed content is page_size octets for each + page set as present in that pfn array. They are + back to back, with no separator, length field or + padding between them. + + The length of pfn_frame is not recorded; a + restoring side finds its end by decoding it, so + an algorithm can only be used with bit 8 if its + encoding marks its own end. count is never + compressed, so that a restoring side can bound + its buffers before decompressing anything. + + For algorithm 0x01, both are complete LZ4 frames. + Both must set the block-checksum flag, and a + restoring side must reject one which does not. + page_data_frame is subject to the rules for + algorithm 0x01, and a restoring side must reject + a pfn_frame which does not decode to exactly + count * 8 octets. + + A saving side must send the record with bit 8 + clear instead, the pfn array in plaintext and + page_data_frame as page_data, when the two frames + together, L octets, satisfy L >= count * 8 and + (L - count * 8) is a multiple of page_size. This + ensures that a restoring side which ignores this + field, as revisions 1 to 3 of this specification + required, and so judges the record by its length + alone, rejects it rather than misreading it. + + Bit 31-9: Reserved. Set to zero on save. A restoring side must reject a record with any of these bits set. pfn An array of count PFNs and their types.
@@ -346,6 +386,19 @@ page_data Contents of each page set as present in the pfn array, Note: Count is strictly > 0. N is strictly <= C and it is possible for there to be no page_data in the record if all pfns are of invalid types. +When flags bit 8 is set, the record is instead laid out as follows: + + 0 1 2 3 4 5 6 7 octet + +-----------------------+-------------------------+ + | count (C) | flags | + +-----------------------+-------------------------+ + | pfn_frame... | + ... + +-------------------------------------------------+ + | page_data_frame... | + ... + +-------------------------------------------------+ + -------------------------------------------------------------------- PFINFO type Value Description ------------- --------- ------------------------------------------
tools/libs/guest/xg_sr_restore.c +97 -43
239 lines not on this page · raw message
tools/libs/guest/xg_sr_save.c +48 -11
90 lines not on this page · raw message
tools/libs/guest/xg_sr_stream_format.h +6 -2
@@ -87,9 +87,13 @@ struct xc_sr_rec_page_data_headeruint64_t pfn[0 ]; }; -/* PAGE_DATA flags: bits 7-0 are the algorithm, bits 31-8 are reserved. */ +/* +* PAGE_DATA flags: bits 7-0 are the algorithm, bit 8 marks a compressed pfn +* array, bits 31-9 are reserved. +*/ #define PAGE_DATA_ALGO_MASK 0x000000ffU -#define PAGE_DATA_FLAGS_RESZ_MASK 0xffffff00U +#define PAGE_DATA_FLAG_COMPRESSED_PFNS 0x00000100U +#define PAGE_DATA_FLAGS_RESZ_MASK 0xfffffe00U#define PAGE_DATA_ALGO_NONE 0x00000000U#define PAGE_DATA_ALGO_LZ4 0x00000001U
tools/python/xen/migration/libxc.py +41 -2
62 lines not on this page · raw message
tools/python/xen/migration/tests.py +38 -1
@@ -74,10 +74,47 @@ class TestLibxc(unittest.TestCase): # An unimplemented algorithm, and any reserved bit, are refused. self.assertRaises(libxc.StreamError, v.verify_record_page_data, rec(libxc.PAGE_DATA_ALGO_LZ4 + 1, FRAME)) - for bit in range(8, 32): + for bit in range(9, 32): self.assertRaises(libxc.StreamError, v.verify_record_page_data, rec(1 << bit, PAGE)) + def test_page_data_compressed_pfns(self): + """ PAGE_DATA with the pfn array compressed too (flags bit 8) """ + + v = libxc.VerifyLibxc(lambda *_: None, lambda *_: b"") + FRAME = b"\x04\x22\x4d\x18\x70\x70\x72" + b"\x00" * 93 + PFNS = libxc.PAGE_DATA_FLAG_COMPRESSED_PFNS + LZ4 = libxc.PAGE_DATA_ALGO_LZ4 + + def rec(count, flags, payload): + return pack(libxc.PAGE_DATA_FORMAT, count, flags) + payload + + # Two frames are fine unless they total 8 * count plus whole pages, + # which a receiver ignoring the flags could misread. + v.verify_record_page_data(rec(1024, PFNS | LZ4, FRAME + FRAME)) + v.verify_record_page_data(rec(16, PFNS | LZ4, FRAME + FRAME)) + for extra in (0, 4096, 2 * 4096): + self.assertRaises(libxc.RecordError, v.verify_record_page_data, + rec(16, PFNS | LZ4, + FRAME + b"\x00" * (128 + extra - 100))) + + # The pfn frame has a whole header, with block checksums, and there + # are pfns at all. + self.assertRaises(libxc.RecordError, v.verify_record_page_data, + rec(16, PFNS | LZ4, FRAME[:6])) + self.assertRaises(libxc.RecordError, v.verify_record_page_data, + rec(16, PFNS | LZ4, + FRAME[:4] + b"\x60" + FRAME[5:] + FRAME)) + self.assertRaises(libxc.RecordError, v.verify_record_page_data, + rec(0, PFNS | LZ4, FRAME + FRAME)) + + # Bit 8 needs a compression algorithm, and one this checker knows. + self.assertRaises(libxc.RecordError, v.verify_record_page_data, + rec(16, PFNS | libxc.PAGE_DATA_ALGO_NONE, + FRAME + FRAME)) + self.assertRaises(libxc.StreamError, v.verify_record_page_data, + rec(16, PFNS | (LZ4 + 1), FRAME + FRAME)) + class TestLibxl(unittest.TestCase):
Signature · 1 line
2.43.0
Re: [PATCH v2 9/9] tools/libs/guest: compress the PAGE_DATA pfn array too
Le 20/10/2026 à 22:09, Marcus Granado a écrit :
Quoted 16 lines
An LZ4
PAGE_DATArecord compresses only its page data. Its pfn array, 8 bytes per page, still travels in plaintext ahead of the frame.Define bit 8 of the flags field: the pfn array is compressed too, with the record's algorithm, as a frame of its own immediately before the page data frame. That makes it easier to handle the pfns and the page data separately, in both the saver and restore. Bit 8 needs an algorithm other than
PAGE_DATA_ALGO_NONE. ForPAGE_DATA_ALGO_LZ4both frames carry block checksums. The count stays in plaintext, so restore can bound it before decoding anything, and finds the page data frame where decoding the pfn frame ends. The saver sets bit 8 on every batch it compresses, except when a) the pfn frame is no smaller than the array, so would save nothing, or b) the size rule below applies, for backwards compatibility. Restore decodes both frames with a new helper, which resets the LZ4 context before each frame.
Quoted 5 lines
This compresses the whole record body apart from count and flags, as discussed in v1. Compressing the pfn array saves a little on real
traffic: 0.33% of the page data bytes for a compressible 64 GiB guest, 0.016% for an incompressible one.
I'm not sure to understand. Is the pfn list compressed as 0.33% of its full size, or do we win 0.33% bandwidth by pfn compression ?
Quoted 15 lines
The size rule (b) makes the saver send the pfn array in plaintext when the two frames total 8 * count bytes plus a whole number of pages. A receiver without "
tools/libs/guest: reject non-zero reserved fields inPAGE_DATA" ignores the flags field, so it reads the frames as count pfns followed by page data. Its checks of those pfns may let them pass, which leaves its exact length check as the only certain rejection, and that check could pass at exactly those sizes. This rule can be removed once every receiver has that commit, which is marked for backport to 4.17 and later. libxenguest does not check the rule on restore, as that would prevent it ever being removed; only the Python stream checker does, as a test of the saver.Suggested-by Andrew Cooper <[email protected]>Assisted-by Claude:claude-opus-5-5Signed-off-by Marcus Granado <[email protected]>
Quoted 7 lines
---
Notes:
Changes in v2:
- New in v2. Andrew Cooper suggested the pfn array to be compressed too; in v1 review Frediano Ziglio asked about compressing whole records.
Compressing the entire record could be simpler than the current design.
We already have the entire record; that could have a compress combined pfn array and page data frame(s).
(that would imply lz4_decomp_buf to be MAX_BATCH_SIZE * (sizeof(uint64_t) + PAGE_SIZE) large, instead of MAX_BATCH_SIZE * PAGE_SIZE)
Then the pipeline can be made as :
If compressed :
- decompress the entire payload (pfn list and page data eventually as a single frame)
Then process it as usual (using the decompressed staging buffer instead).
The size of the compressed payload can already be derivated from body_length - header size.
To me, that looks simpler than trying to split the pfn array to the page datas.
Quoted 53 lines
Tested: builds with and without liblz4; the Python unit tests; a round trip of the changed save and restore functions with Xen stubbed out, under ASan and UBSan, through uncompressed records, LZ4 records with plaintext and with compressed pfns, the size-rule fallback and malformed bit-8 records; and live migrations with xl migrate --compress --debug.
docs/specs/libxc-migration-stream.pandoc | 55 ++++++++- tools/libs/guest/xg_sr_restore.c | 140 ++++++++++++++++------- tools/libs/guest/xg_sr_save.c | 59 ++++++++-- tools/libs/guest/xg_sr_stream_format.h | 8 +- tools/python/xen/migration/libxc.py | 43 ++++++- tools/python/xen/migration/tests.py | 39 ++++++- 6 files changed, 284 insertions(+), 60 deletions(-)docs/specs/libxc-migration-stream.pandoc +29
-1@@ -326,7 +326,47 @@ flags Bit 7-0: Algorithm used to encode page_data. does not implement, rather than attempting to interpret the page_data. - Bit 31-8: Reserved. Set to zero on save. A restoring side + Bit 8: Compressed pfn array. The pfn array is + compressed too, with the algorithm in bits 7-0. + May only be set when bits 7-0 are not 0x00; a + restoring side must reject the record otherwise. + + When set, the pfn array is not present in + plaintext. The flags field is instead followed + by pfn_frame, whose decompressed content is the + count pfn entries (count * 8 octets, encoded as + for pfn below), then page_data_frame, whose + decompressed content is page_size octets for each + page set as present in that pfn array. They are + back to back, with no separator, length field or + padding between them. + + The length of pfn_frame is not recorded; a + restoring side finds its end by decoding it, so + an algorithm can only be used with bit 8 if its + encoding marks its own end. count is never + compressed, so that a restoring side can bound + its buffers before decompressing anything. + + For algorithm 0x01, both are complete LZ4 frames. + Both must set the block-checksum flag, and a + restoring side must reject one which does not. + page_data_frame is subject to the rules for + algorithm 0x01, and a restoring side must reject + a pfn_frame which does not decode to exactly + count * 8 octets.
docs/specs/libxc-migration-stream.pandoc flags Bit 7-0: Algorithm used to encode page_data. · line 367
Quoted 10 lines
docs/specs/libxc-migration-stream.pandoc +10
-0+ + A saving side must send the record with bit 8 + clear instead, the pfn array in plaintext and + page_data_frame as page_data, when the two frames + together, L octets, satisfy L >= count * 8 and + (L - count * 8) is a multiple of page_size. This + ensures that a restoring side which ignores this + field, as revisions 1 to 3 of this specification + required, and so judges the record by its length + alone, rejects it rather than misreading it.
Given that algorithm 0x01 is LZ4, it's better refered as is. But I would prefer moving the LZ4 specific semantics to the bits 0..7=0x01 section (LZ4) instead, so adding new algorithms doesn't imply expanding the bit 8 definition.
In a way, saying something like
"The format of compressed pfn array is algorithm specific."
Quoted 326 lines
docs/specs/libxc-migration-stream.pandoc +15
-0+ + Bit 31-9: Reserved. Set to zero on save. A restoring side must reject a record with any of these bits set. pfn An array of count PFNs and their types.@@ -346,6 +386,19 @@ page_data Contents of each page set as present in the pfn array, Note: Count is strictly > 0. N is strictly <= C and it is possible for there to be no page_data in the record if all pfns are of invalid types. +When flags bit 8 is set, the record is instead laid out as follows: + + 0 1 2 3 4 5 6 7 octet + +-----------------------+-------------------------+ + | count (C) | flags | + +-----------------------+-------------------------+ + | pfn_frame... | + ... + +-------------------------------------------------+ + | page_data_frame... | + ... + +-------------------------------------------------+ + -------------------------------------------------------------------- PFINFO type Value Description ------------- --------- ------------------------------------------tools/libs/guest/xg_sr_restore.c +97
-43@@ -356,32 +356,19 @@ static int process_page_data(struct xc_sr_context *ctx, unsigned int count,#if defined(XG_SR_LZ4 )/* -* Decode the LZ4 frame at src into ctx->restore.lz4_decomp_buf. The -* decoded size comes from the pfn array. +* Decode the LZ4 frame at the start of src into exactly dst_len bytes of +* ctx->restore.lz4_decomp_buf. With consumed NULL the frame must use all of +* src, which rejects trailing data; otherwise its length is returned there. */ -static void *decompress_page_data (struct xc_sr_context *ctx,const void *src, -size_t src_len,unsigned int nr_pages) +static void *lz4_decode_frame (struct xc_sr_context *ctx,const char *what, +const void *src,size_t src_len,size_t dst_len, +size_t *consumed) {xc_interface *xch = ctx->xch;LZ4F_frameInfo_t info; -size_t expected = (size_t )nr_pages *PAGE_SIZE ; -size_t out_len = expected, hdr_len = src_len, rest_len, in_len, ret; - -/* The buffer is a fixed MAX_BATCH_SIZE pages. */ -if ( nr_pages >MAX_BATCH_SIZE ) - { -ERROR ("Compressed PAGE_DATA record with %u pages exceeds MAX_BATCH_SIZE %u" , - nr_pages,MAX_BATCH_SIZE ); -return NULL ; - } +size_t out_len = dst_len, hdr_len = src_len, rest_len, in_len, ret; -/* The format requires the frame to be strictly shorter than the pages. */ -if ( src_len >= expected ) - { -ERROR ("LZ4 frame in PAGE_DATA record (%zu bytes) is not shorter than its page data (%zu bytes)" , - src_len, expected); -return NULL ; - } +assert (dst_len <=MAX_BATCH_SIZE *PAGE_SIZE );if ( !ctx->restore.lz4_dctx ) {@@ -402,15 +389,15 @@ static void *decompress_page_data(struct xc_sr_context *ctx, const void *src, ret =LZ4F_getFrameInfo (ctx->restore.lz4_dctx, &info, src, &hdr_len);if (LZ4F_isError (ret) ) { -ERROR ("LZ4 frame in PAGE_DATA record has a bad header: %s" , -LZ4F_getErrorName (ret)); +ERROR ("LZ4 %s frame in PAGE_DATA record has a bad header: %s" , + what,LZ4F_getErrorName (ret));return NULL ; }/* liblz4 accepts frames without the block checksums required here. */ if ( info.blockChecksumFlag != LZ4F_blockChecksumEnabled ) { -ERROR ("LZ4 frame in PAGE_DATA record has no block checksums" ); +ERROR ("LZ4 %s frame in PAGE_DATA record has no block checksums" , what);return NULL ; }@@ -436,36 +423,64 @@ static void *decompress_page_data(struct xc_sr_context *ctx, const void *src,if (LZ4F_isError (ret) ) { -ERROR ("Failed to decompress PAGE_DATA record: %s" , -LZ4F_getErrorName (ret)); +ERROR ("Failed to decompress LZ4 %s frame in PAGE_DATA record: %s" , + what,LZ4F_getErrorName (ret));return NULL ; }/* Not an error, but the frame did not end: input or output ran out. */ if ( ret !=0 ) { -ERROR ("LZ4 frame in PAGE_DATA record is truncated or decodes to over %zu bytes" , - expected); +ERROR ("LZ4 %s frame in PAGE_DATA record is truncated or decodes to over %zu bytes" , + what, dst_len);return NULL ; }/* in_len and out_len now hold the bytes consumed and produced. */ -if ( out_len != expected ) +if ( out_len != dst_len ) { -ERROR ("LZ4 frame in PAGE_DATA record produced %zu bytes, expected %zu" , - out_len, expected); +ERROR ("LZ4 %s frame in PAGE_DATA record produced %zu bytes, expected %zu" , + what, out_len, dst_len);return NULL ; } -if ( in_len != rest_len ) +if ( consumed ) + *consumed = hdr_len + in_len; +else if ( in_len != rest_len ) { -ERROR ("LZ4 frame in PAGE_DATA record followed by %zu unconsumed bytes" , - rest_len - in_len); +ERROR ("LZ4 %s frame in PAGE_DATA record followed by %zu unconsumed bytes" , + what, rest_len - in_len);return NULL ; } return ctx->restore.lz4_decomp_buf; } + +/* Decompress the page data frame at src, of nr_pages pages. */ +static void *decompress_page_data (struct xc_sr_context *ctx,const void *src, +size_t src_len,unsigned int nr_pages) +{ +xc_interface *xch = ctx->xch; +size_t expected = (size_t )nr_pages *PAGE_SIZE ; + +/* The buffer is a fixed MAX_BATCH_SIZE pages. */ +if ( nr_pages >MAX_BATCH_SIZE ) + { +ERROR ("Compressed PAGE_DATA record with %u pages exceeds MAX_BATCH_SIZE %u" , + nr_pages,MAX_BATCH_SIZE ); +return NULL ; + } + +/* The format requires the frame to be strictly shorter than the pages. */ +if ( src_len >= expected ) + { +ERROR ("LZ4 frame in PAGE_DATA record (%zu bytes) is not shorter than its page data (%zu bytes)" , + src_len, expected); +return NULL ; + } + +return lz4_decode_frame (ctx,"page data" , src, src_len, expected,NULL ); +}#endif /* XG_SR_LZ4 */ /* @@ -476,7 +491,9 @@ static int handle_page_data(struct xc_sr_context *ctx, struct xc_sr_record *rec) {xc_interface *xch = ctx->xch;struct xc_sr_rec_page_data_header *pages = rec->data; +const uint64_t *rec_pfns;unsigned int i, pages_of_data =0 ; +size_t pfn_len;void *page_data;int rc =-1 ;@@ -523,17 +540,54 @@ static int handle_page_data(struct xc_sr_context *ctx, struct xc_sr_record *rec) goto err; } +/* Compressed pfns need an algorithm; only LZ4 is implemented. */ +if ( (pages->flags &PAGE_DATA_FLAG_COMPRESSED_PFNS ) && + (pages->flags &PAGE_DATA_ALGO_MASK ) !=PAGE_DATA_ALGO_LZ4 ) + { +ERROR ("Compressed pfn array with unsupported algorithm %u in PAGE_DATA record" , + (unsigned int )(pages->flags &PAGE_DATA_ALGO_MASK )); + goto err; + } +if ( pages->count <1 ) {ERROR ("Expected at least 1 pfn in PAGE_DATA record" ); goto err; } -if ( rec->length <sizeof (*pages) + (pages->count *sizeof (uint64_t )) ) +if ( pages->flags &PAGE_DATA_FLAG_COMPRESSED_PFNS ) { -ERROR ("PAGE_DATA record (length %u) too short to contain %u" -" pfns worth of information" , rec->length, pages->count); +#if defined(XG_SR_LZ4 ) +if ( pages->count >MAX_BATCH_SIZE ) + { +ERROR ("Compressed pfns in PAGE_DATA record: count %u exceeds MAX_BATCH_SIZE %u" , + pages->count,MAX_BATCH_SIZE ); + goto err; + } + +/* The page data frame overwrites these, after the copy below. */ + rec_pfns =lz4_decode_frame (ctx,"pfn" , pages->pfn, + rec->length -sizeof (*pages), + pages->count *sizeof (uint64_t ), + &pfn_len); +if ( !rec_pfns ) + goto err; +#else +ERROR ("LZ4 compressed PAGE_DATA record but LZ4 support not compiled in" ); goto err; +#endif + } +else + { +if ( rec->length <sizeof (*pages) + (pages->count *sizeof (uint64_t )) ) + { +ERROR ("PAGE_DATA record (length %u) too short to contain %u" +" pfns worth of information" , rec->length, pages->count); + goto err; + } + + rec_pfns = pages->pfn; + pfn_len = pages->count *sizeof (uint64_t ); } pfns =malloc (pages->count *sizeof (*pfns));@@ -547,21 +601,21 @@ static int handle_page_data(struct xc_sr_context *ctx, struct xc_sr_record *rec)for ( i =0 ; i < pages->count; ++i ) { -if ( pages->pfn[i] &PAGE_DATA_PFN_RESZ_MASK ) +if ( rec_pfns[i] &PAGE_DATA_PFN_RESZ_MASK ) {ERROR ("Reserved bits set in pfn[%u]: %#" PRIx64, i, - pages->pfn[i]); + rec_pfns[i]); goto err; } - pfn = pages->pfn[i] &PAGE_DATA_PFN_MASK ; + pfn = rec_pfns[i] &PAGE_DATA_PFN_MASK ;if ( !ctx->restore.ops.pfn_is_valid (ctx, pfn) ) {ERROR ("pfn %#" PRIpfn" (index %u) outside domain maximum" , pfn, i); goto err; } - type = (pages->pfn[i] &PAGE_DATA_TYPE_MASK ) >>32 ; + type = (rec_pfns[i] &PAGE_DATA_TYPE_MASK ) >>32 ;if ( !is_known_page_type (type) ) { ERROR("Unknown type %#"PRIx32" for pfn %#"PRIpfn" (index %u)",@@ -578,7 +632,7 @@ static int handle_page_data(struct xc_sr_context *ctx, struct xc_sr_record *rec) types[i] = type; } - page_data = &pages->pfn[pages->count]; + page_data = (uint8_t *)pages->pfn + pfn_len;switch ( pages->flags &PAGE_DATA_ALGO_MASK ) {@@ -598,7 +652,7 @@ static int handle_page_data(struct xc_sr_context *ctx, struct xc_sr_record *rec)case PAGE_DATA_ALGO_LZ4 :#if defined(XG_SR_LZ4 ) { -size_t hdrsz =sizeof (*pages) + (sizeof (uint64_t ) * pages->count); +size_t hdrsz =sizeof (*pages) + pfn_len; page_data =decompress_page_data (ctx, page_data, rec->length - hdrsz, pages_of_data);tools/libs/guest/xg_sr_save.c +14
-5@@ -150,11 +150,19 @@ static void compress_stats_evaluate(struct xc_sr_context *ctx)*/ #define XC_SR_COMPRESS_BLOCK_SIZE LZ4F_max4MB +/* Size rule: could len bytes pass as pfns_len of pfns plus whole pages? */ +static bool page_data_size_clash (size_t len,size_t pfns_len) +{ +return len >= pfns_len && (len - pfns_len) %PAGE_SIZE ==0 ; +} +/* * Compress the page data in iov[2..iovcnt) into an LZ4 frame, and replace -* those entries with one describing it, padded to the record alignment. -* Returns the new iovcnt, the original one with iov untouched if the batch -* should be sent uncompressed, or -1 if the batch itself is malformed. +* those entries with one describing it, padded to the record alignment. The +* pfn array in iov[1] becomes a second frame too, unless that is no smaller or +* the size rule applies. Returns the new iovcnt, the original one with iov +* untouched if the batch should be sent uncompressed, or -1 if the batch +* itself is malformed. */ static int lz4_compress_batch(struct xc_sr_context *ctx, struct iovec *iov, int iovcnt, unsigned int nr_pages,@@ -167,7 +175,7 @@ static int lz4_compress_batch(struct xc_sr_context *ctx, struct iovec *iov, }, };xc_interface *xch = ctx->xch; -size_t raw = (size_t )nr_pages *PAGE_SIZE , clen, staged; +size_t raw = (size_t )nr_pages *PAGE_SIZE , clen, pfn_clen, staged, pad;uint8_t *dst;int i;@@ -176,8 +184,9 @@ static int lz4_compress_batch(struct xc_sr_context *ctx, struct iovec *iov,if ( !ctx->save.lz4_staging_buf ) { +/* The page data frame plus up to REC_ALIGN - 1 bytes of padding. */ size_t bound =LZ4F_compressFrameBound (MAX_BATCH_SIZE *PAGE_SIZE , - &prefs); + &prefs) +REC_ALIGN ; ctx->save.lz4_staging_buf =malloc (MAX_BATCH_SIZE *PAGE_SIZE ); ctx->save.lz4_compress_buf =malloc (bound);@@ -233,16 +242,44 @@ static int lz4_compress_batch(struct xc_sr_context *ctx, struct iovec *iov, (clen * 1000 / raw) / 10, (clen * 1000 / raw) % 10);compress_stats_accumulate (ctx, raw, clen);
tools/libs/guest/xg_sr_save.c static int lz4_compress_batch(struct xc_sr_context *ctx, struct iovec *iov, · line 247
Quoted 10 lines
tools/libs/guest/xg_sr_save.c +3
-6-/* Pad in place: raw is a multiple of REC_ALIGN and > clen, so it fits. */ -memset ((uint8_t *)ctx->save.lz4_compress_buf + clen,0 , -ROUNDUP (clen,REC_ALIGN ) - clen); - - iov[2 ].iov_base = ctx->save.lz4_compress_buf; - iov[2 ].iov_len =ROUNDUP (clen,REC_ALIGN ); +/* The pages are compressed: reuse the staging buffer for the pfn frame. */ +assert (LZ4F_compressFrameBound (iov[1 ].iov_len, &prefs) <= +MAX_BATCH_SIZE *PAGE_SIZE );
Is this assert expected ?
tools/libs/guest/xg_sr_save.c static int lz4_compress_batch(struct xc_sr_context *ctx, struct iovec *iov, · line 257
Quoted 10 lines
tools/libs/guest/xg_sr_save.c +10
-0+ pfn_clen =LZ4F_compressFrame (ctx->save.lz4_staging_buf, +MAX_BATCH_SIZE *PAGE_SIZE , + iov[1 ].iov_base, iov[1 ].iov_len, &prefs); + +/* +* The size rule only protects receivers without "tools/libs/guest: +* reject non-zero reserved fields in PAGE_DATA"; drop it once none remain. +* Such a receiver reads the frames as iov[1].iov_len bytes of pfns and +* pages, so page_data_size_clash() checks the lengths as it sees them. +*/
That comment feels a bit odd.
We never really know when receiver without the patch remains.
Quoted 170 lines
tools/libs/guest/xg_sr_save.c +21
-0+if (LZ4F_isError (pfn_clen) || pfn_clen >= iov[1 ].iov_len || +page_data_size_clash (pfn_clen + clen, iov[1 ].iov_len) ) +DBGPRINTF ("LZ4: sending %zu bytes of pfns uncompressed" , + iov[1 ].iov_len); +else + { + *flags |=PAGE_DATA_FLAG_COMPRESSED_PFNS ; + *length -= iov[1 ].iov_len - pfn_clen; + iov[1 ].iov_base = ctx->save.lz4_staging_buf; + iov[1 ].iov_len = pfn_clen; + } *flags |=PAGE_DATA_ALGO_LZ4 ; *length -= raw - clen; +/* Pad in place: the buffer was allocated with REC_ALIGN to spare. */ + pad =ROUNDUP (*length,REC_ALIGN ) - *length; +memset ((uint8_t *)ctx->save.lz4_compress_buf + clen,0 , pad); + + iov[2 ].iov_base = ctx->save.lz4_compress_buf; + iov[2 ].iov_len = clen + pad; + +assert (iov[0 ].iov_len + iov[1 ].iov_len + iov[2 ].iov_len == +sizeof (struct xc_sr_rhdr ) +ROUNDUP (*length,REC_ALIGN )); +/* iov[0] headers, iov[1] pfns, iov[2] page data frame. */ return 3 ; }tools/libs/guest/xg_sr_stream_format.h +6
-2@@ -87,9 +87,13 @@ struct xc_sr_rec_page_data_headeruint64_t pfn[0 ]; }; -/* PAGE_DATA flags: bits 7-0 are the algorithm, bits 31-8 are reserved. */ +/* +* PAGE_DATA flags: bits 7-0 are the algorithm, bit 8 marks a compressed pfn +* array, bits 31-9 are reserved. +*/ #define PAGE_DATA_ALGO_MASK 0x000000ffU -#define PAGE_DATA_FLAGS_RESZ_MASK 0xffffff00U +#define PAGE_DATA_FLAG_COMPRESSED_PFNS 0x00000100U +#define PAGE_DATA_FLAGS_RESZ_MASK 0xfffffe00U#define PAGE_DATA_ALGO_NONE 0x00000000U#define PAGE_DATA_ALGO_LZ4 0x00000001Utools/python/xen/migration/libxc.py +41
-2@@ -86,9 +86,11 @@ PAGE_DATA_FORMAT = "II" PAGE_DATA_PFN_MASK = (1 << 52) - 1 PAGE_DATA_PFN_RESZ_MASK = ((1 << 60) - 1) & ~((1 << 52) - 1) -# page_data flags: bits 7-0 algorithm, bits 31-8 reserved (must reject) +# page_data flags: bits 7-0 algorithm, bit 8 pfn array compressed too (not with +# algorithm 0), bits 31-9 reserved (must reject) PAGE_DATA_ALGO_MASK = 0x000000ff -PAGE_DATA_FLAGS_RESZ_MASK = 0xffffff00 +PAGE_DATA_FLAG_COMPRESSED_PFNS = 0x00000100 +PAGE_DATA_FLAGS_RESZ_MASK = 0xfffffe00 PAGE_DATA_ALGO_NONE = 0x00 PAGE_DATA_ALGO_LZ4 = 0x01@@ -278,6 +280,10 @@ class VerifyLibxc(VerifyBase): algo = flags & PAGE_DATA_ALGO_MASK + if flags & PAGE_DATA_FLAG_COMPRESSED_PFNS: + self.verify_page_data_compressed_pfns(content[minsz:], count, algo) + return + pfnsz = count * 8 if (len(content) - minsz) < pfnsz: raise RecordError(@@ -333,6 +339,39 @@ class VerifyLibxc(VerifyBase): "Unsupported algorithm %u in PAGE_DATA record" % (algo, )) + def verify_page_data_compressed_pfns(self, payload, count, algo): + """ Page Data record whose pfn array is compressed too """ + + if algo == PAGE_DATA_ALGO_NONE: + raise RecordError( + "Compressed pfn array without an algorithm in PAGE_DATA record") + if algo != PAGE_DATA_ALGO_LZ4: + raise StreamError( + "Unsupported algorithm %u in PAGE_DATA record" % (algo, )) + + if count == 0: + raise RecordError("PAGE_DATA record with no pfns") + + # Without decompressing, check the saver's size rule: not count pfns + # plus whole pages, which a receiver ignoring flags could misread. + pfnsz = count * 8 + if len(payload) >= pfnsz and (len(payload) - pfnsz) % 4096 == 0: + raise RecordError( + "Compressed PAGE_DATA payload of %u is %u pfns and whole pages" + % (len(payload), count)) + + # Only the pfn frame's header is checkable: the page data frame starts + # where decoding the pfn frame ends. + if len(payload) < PAGE_DATA_LZ4_FRAME_MIN: + raise RecordError( + "LZ4 frame in PAGE_DATA record too short: %u bytes" + % (len(payload), )) + + if not ord(payload[4:5]) & PAGE_DATA_LZ4_FLG_BLOCKSUM: + raise RecordError( + "LZ4 frame in PAGE_DATA record has no block checksums") + + def verify_record_x86_pv_info(self, content): """ x86 PV Info record """tools/python/xen/migration/tests.py +38
-1@@ -74,10 +74,47 @@ class TestLibxc(unittest.TestCase): # An unimplemented algorithm, and any reserved bit, are refused. self.assertRaises(libxc.StreamError, v.verify_record_page_data, rec(libxc.PAGE_DATA_ALGO_LZ4 + 1, FRAME)) - for bit in range(8, 32): + for bit in range(9, 32): self.assertRaises(libxc.StreamError, v.verify_record_page_data, rec(1 << bit, PAGE)) + def test_page_data_compressed_pfns(self): + """ PAGE_DATA with the pfn array compressed too (flags bit 8) """ + + v = libxc.VerifyLibxc(lambda *_: None, lambda *_: b"") + FRAME = b"\x04\x22\x4d\x18\x70\x70\x72" + b"\x00" * 93 + PFNS = libxc.PAGE_DATA_FLAG_COMPRESSED_PFNS + LZ4 = libxc.PAGE_DATA_ALGO_LZ4 + + def rec(count, flags, payload): + return pack(libxc.PAGE_DATA_FORMAT, count, flags) + payload + + # Two frames are fine unless they total 8 * count plus whole pages, + # which a receiver ignoring the flags could misread. + v.verify_record_page_data(rec(1024, PFNS | LZ4, FRAME + FRAME)) + v.verify_record_page_data(rec(16, PFNS | LZ4, FRAME + FRAME)) + for extra in (0, 4096, 2 * 4096): + self.assertRaises(libxc.RecordError, v.verify_record_page_data, + rec(16, PFNS | LZ4, + FRAME + b"\x00" * (128 + extra - 100))) + + # The pfn frame has a whole header, with block checksums, and there + # are pfns at all. + self.assertRaises(libxc.RecordError, v.verify_record_page_data, + rec(16, PFNS | LZ4, FRAME[:6])) + self.assertRaises(libxc.RecordError, v.verify_record_page_data, + rec(16, PFNS | LZ4, + FRAME[:4] + b"\x60" + FRAME[5:] + FRAME)) + self.assertRaises(libxc.RecordError, v.verify_record_page_data, + rec(0, PFNS | LZ4, FRAME + FRAME)) + + # Bit 8 needs a compression algorithm, and one this checker knows. + self.assertRaises(libxc.RecordError, v.verify_record_page_data, + rec(16, PFNS | libxc.PAGE_DATA_ALGO_NONE, + FRAME + FRAME)) + self.assertRaises(libxc.StreamError, v.verify_record_page_data, + rec(16, PFNS | (LZ4 + 1), FRAME + FRAME)) + class TestLibxl(unittest.TestCase):