Registry Mirror
Skip to content

Conversation

@phip1611

@phip1611 phip1611 commented Dec 4, 2026 •

Copy link
Copy Markdown
Member

Part of bumping our gardenlinux patchset to upstream CH v55. This follows our agreed process, see ticket.

About

Follow-up of #238 that adds our disk mirroring series: the vm.disk-mirror-{start,status,complete,cancel} endpoints, mirror events, and postponing guest reboot/shutdown while a mirror is active. With this, all gardenlinux series that we keep are ported. The migration keep-alive series and our TCP serial console extensions are intentionally dropped for v55.

Hints for Reviewers

  • libvirt nixos-tests pipeline
    • ??/140 passing (+??)
  • Check out our commits from the base gardenlinux branch and compare them. There might be some consolidations, squashing, and reorderings included but the general nature of our patchset must be preserved. Some patches are removed or changed as the new upstream version diverged.
  • Commits that differ from their gardenlinux original carry an [ Adapted to v55: ... ] note before the trailers.
  • Ticket

scholzp and others added 30 commits December 4, 2026 11:00
The DMA interface in `fw_cfg` in the CHV implementation is broken and
needs an overhaul. We deactivate it to force a guest to use the
traditional interface instead and ignore the DMA interface.[0]

We make DMA transfers no-ops for now and adjust the test to verify this
instead until we do a rework of the DMA path.

[0] https://www.qemu.org/docs/master/specs/fw_cfg.html#guest-side-dma-interface

On-behalf-of: SAP pascal.scholz@sap.com
Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
QEMU checks if the read has an allowed width.[0] If it detects an
invalid read to a device mapped port, then QEMU will treat the
register reads as a read from unassigned I/O.[1] As a result, it
will return 0x0 for the whole buffer. For unmapped IO port access,
QEMU writes all-ones to the buffer. Unlike QEMU, CHV doesn't answer
unmapped reads with a deterministic value and leaves the buffer
unchanged instead. We preserve CHV behavior for ports unknown to
fw_cfg.

QEMU maps two separate memory regions to fw_cfg. One starting
at FW_CFG_IO_BASE which is 0x510 and one starting at 0x514.[2] The first
is two bytes, the size of the latter is eight bytes. This leaves a hole
at addresses 0x512 and 0x513 in the x86 I/O port mapping.

We mimic this behavior for CHV's `fw_cfg` design for improved
compatibility and respect the hole accordingly. In the last case this
means that reading from the hole at 0x512 and 0x513 is not treated by
zero-filling the buffer. Instead, we tread them as unmapped port and
leave the buffer unchanged.

[0] https://github.com/qemu/qemu/blob/6e9a825c1d4e7b62d072e99a89ecd1a74c7f0d55/hw/nvram/fw_cfg.c#L533
[1] https://github.com/qemu/qemu/blob/6e9a825c1d4e7b62d072e99a89ecd1a74c7f0d55/system/memory.c#L1480
[2] https://github.com/qemu/qemu/blob/6e9a825c1d4e7b62d072e99a89ecd1a74c7f0d55/hw/i386/fw_cfg.c#L130

[ Adapted to v55: match on data.len() as v55 dropped the size local,
  tests use the v55 FwCfg::new() and the FW_CFG_*_OFFSET constants ]

On-behalf-of: SAP pascal.scholz@sap.com
Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
Using the result of an addition comes with the risk of it overflowing.
In terms of the address matching in `read` and `write` it makes no
difference if we use the provided offset directly instead of adding the
base to it.

[ Adapted to v55: test constant renames already happen in the previous
  commit, the log uses data.len() ]

On-behalf-of: SAP pascal.scholz@sap.com
Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
While the documentation states that the SELECTOR register is
write-only, QEMU actually allows reading the SELECTOR register. This
is because QEMU uses a contiguous mapping for the SELECTOR and DATA
registers to allow the 16-bit width of the SELECTOR register.[0]
As a consequence, a read from SELECTOR is delegated to the same callback
as a read from DATA. It does not return the SELECTOR value.

We mimic this for maximal compatibility.

[0] https://github.com/qemu/qemu/blob/6e9a825c1d4e7b62d072e99a89ecd1a74c7f0d55/hw/nvram/fw_cfg.c#L539

[ Adapted to v55: read_data() takes no size argument, test uses the v55
  FwCfg::new() ]

On-behalf-of: SAP pascal.scholz@sap.com
Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
Currently, the read implementation isn't complete and doesn't handle
some error cases gracefully. We rework it with the aim of maximal
compatibility to QEMU and add tests for it.
Problems of the old implementation include:
 * Reads beyond EOF should yield 0x0.[0] These currently panic.
 * Register reads with invalid SELECTOR should also yield 0x0.[1]
 * If provided with a buffer larger than an item, then the remaining
   buffer bytes should be set to zero.[1]

We use the existing interface for reading items that is also used for
DMA access and bring bug fixes from the POI read interface to it.
These include:
 * Fixing a possible underflow when calculating the offset within a
   file. Such an underflow can occur if the file is shrunk after
   the last successful access, placing the cursor behind the EOF.
 * Replace `seek` + `read` pattern by `read_exact_at` to make
   repeated access save.

[0] https://www.qemu.org/docs/master/specs/fw_cfg.html#data-register
[1] https://github.com/qemu/qemu/blob/6e9a825c1d4e7b62d072e99a89ecd1a74c7f0d55/hw/nvram/fw_cfg.c#L382

Original c217b8e:
devices: Restrict x86 fw_cfg PIO reads to one byte

In the traditional/PIO interface the DATA register has a width of one
byte on x86.[0]
We therefore do not allow reads with larger widths. Currently, all
tests assume a read with a width of one byte too.

We reject `fw_cfg` in aarch64 builds for now as these changes introduce
an incompatibility that adds to the incomplete implementation of it.
aarch64 support is a task to be solved in follow-up work, as this also
includes making corrections to the MMIO transport implementation and
FDT corrections.

[0] https://www.qemu.org/docs/master/specs/fw_cfg.html#data-register

Original 70a5b43:
devices: Allow arbitrary length reads from fw_cfg DATA

This is a fix to allow string reads that map to `rep ins`. KVM returns
an I/O exit with the respective port, the read size of the instruction
and the count of such reads. `kvm-ioctls` creates a buffer from this
with the size of `count * size` bytes.[0]

This makes it impossible to decide if the buffer was a single
four-byte-width read of the kind `inl` or `rep ins` with RCX set to 4,
for example. While the first would be invalid according to QEMU
semantics, the second is a valid repeated access with one byte width. We
therefore accept reads of any size until we can solve this issue.

[0] https://github.com/rust-vmm/kvm/blob/b4c9ed8df95a9e10a68f50f5ef5e7d04108759ba/kvm-ioctls/src/ioctls/vcpu.rs#L1549

[ Adapted to v55, which already consolidated the read paths: kept the
  static read_content()/read_data() with io::Result instead of
  FwCfgContentAccess and FwCfgContentAccessError, and ported the partial
  read, EOF cursor clamp, and zero fill semantics into them ]

On-behalf-of: SAP pascal.scholz@sap.com
Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
Some entries are also 2 and 8 bytes in size. We therefore add the
missing content sizes.

[ Adapted to v55: U16/U64 arms go into read_content() as
  FwCfgContentAccess no longer exists ]

On-behalf-of: SAP pascal.scholz@sap.com
Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
Fully populating a `fw_cfg` will require a lot more data than what is
currently passed to the associated function. We therefore make
`populate_fw_cfg` a method to gain access to all data stored in `Vm`.

[ Adapted to v55, which already has a populate_fw_cfg(&self) wrapper:
  made populate_fw_cfg_items() a method instead ]

On-behalf-of: SAP pascal.scholz@sap.com
Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
To keep all data needed to initialize `fw_cfg` together, we move them
from function arguments to a dedicated helper. As their number is going
to grow, this will also help keeping the number of function arguments
low.

[ Adapted to v55: dropped e820_size as v55 adds the E820 map separately
  via add_e820() ]

On-behalf-of: SAP pascal.scholz@sap.com
Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
Introduce a helper that reads an item through fw_cfg's legacy interface
and verifies that:
  - writing a selector resets the cursor
  - payload bytes are exact
  - reads beyond EOF return zero
  - the cursor does not advance beyond EOF

Use it in tests that repeatedly read items through the legacy interface.
This reduces repetition and ensures consistent coverage of these
properties. Use an empty guest-memory map in tests that do not require
the DMA interface.

[ Adapted to v55: the helper selects via the existing select(), tests
  use GuestMemory::default(), and v55's
  test_stage0_reserved_only_for_sev_snp is kept ]

On-behalf-of: SAP pascal.scholz@sap.com
Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
QEMU uses a global variable to store the VM's UUID.[0] The same UUID is
used to initialize the corresponding SMBIOS and fw_cfg fields.[1,2]
Through C's static initialization this is initialized to all zeros.

We mimic this behavior by reading the UUID from the VM configuration.

[0] https://github.com/qemu/qemu/blob/6e9a825c1d4e7b62d072e99a89ecd1a74c7f0d55/system/globals.c#L67
[1] https://github.com/qemu/qemu/blob/6e9a825c1d4e7b62d072e99a89ecd1a74c7f0d55/hw/smbios/smbios.c#L624
[2] https://github.com/qemu/qemu/blob/6e9a825c1d4e7b62d072e99a89ecd1a74c7f0d55/hw/nvram/fw_cfg.c#L1006

[ Adapted to v55: test helper uses the v55 FwCfg::new() ]

On-behalf-of: SAP pascal.scholz@sap.com
Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
QEMU uses the machine's settings to initialize `fw_cfg`'s memory size
field.[0] The machine field state is written once and the `fw_cfg` field
is written once at creation time. The entry in `fw_cfg` therefore
reflects the initial memory size at VM creation time in QEMU.

We initialize `fw_cfg` the same way in CHV.

[0] https://github.com/qemu/qemu/blob/6e9a825c1d4e7b62d072e99a89ecd1a74c7f0d55/hw/i386/fw_cfg.c#L147

On-behalf-of: SAP pascal.scholz@sap.com
Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
QEMU emulates graphical output by default. This can be disabled through
the CLI option `-nographics` which also sets the global `nographic` to
true.[0]

CHV doesn't have graphical output. So we set the FW_CFG_NOGRAPHIC entry
to true.

[0] https://github.com/qemu/qemu/blob/6e9a825c1d4e7b62d072e99a89ecd1a74c7f0d55/system/vl.c#L2999

On-behalf-of: SAP pascal.scholz@sap.com
Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
QEMU initializes `FW_CFG_NB_CPUS` with the number of boot vCPUs stored
in the machine's configuration.[0]

We do the same when populating `fw_cfg`. We don't follow QEMU's update
semantics whenever a vCPU is hot-plugged or hot-unplugged because CHV's
`fw_cfg` doesn't implement stateful recreation (e.g. snapshotting, live
migration...) yet. This means that whenever the VM is instantiated, a
new `fw_cfg` is created and populated with the then up-to-date values.

[0] https://github.com/qemu/qemu/blob/6e9a825c1d4e7b62d072e99a89ecd1a74c7f0d55/hw/i386/pc.c#L886

On-behalf-of: SAP pascal.scholz@sap.com
Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
The current implementation uses architecture-specific guards through
all parts of `add_kernel_data` which lowers readability and
maintainability. We therefore move architecture-specific code into
specific helper functions and dispatch to those in `add_kernel_data`.

This also helps when trying to identify what selectors are implemented
for what architecture.

We additionally add a test for `add_kernel_data`.

Note: FW_CFG_SETUP_DATA is specific to x86 platforms.

[ Adapted to v55: use the existing x86-only io::Error import instead of
  IoError ]

On-behalf-of: SAP pascal.scholz@sap.com
Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
We modify the existing kernel data processing routine to also set
FW_CFG_KERNEL_ADDR correctly depending on the supplied bzImage.

The current code assumes a recent bzImage. While doing so, it misses
any validation logic after it created `boot_params` from the first
bytes in the file. We add the missing validation logic and restrict
the supported bzImage versions to recent, high-loaded ones on x86. This
helps us safely support recent images and allows us to abort loading
the kernel data if an unsupported image/file format was supplied.

For such images, QEMU publishes FW_CFG_KERNEL_ADDR as
`0x10_0000`.[0, 1]. Note that QEMU doesn't populate this item for
AArch64 and RISC-V.

[0] https://github.com/qemu/qemu/blob/6e9a825c1d4e7b62d072e99a89ecd1a74c7f0d55/hw/i386/x86-common.c#L966
[1] https://github.com/qemu/qemu/blob/6e9a825c1d4e7b62d072e99a89ecd1a74c7f0d55/hw/i386/x86-common.c#L762

[ Adapted to v55: Error instead of IoError, test uses the v55
  FwCfg::new() ]

On-behalf-of: SAP pascal.scholz@sap.com
Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
The name of this item is a bit misleading on x86 as the actual value
denotes the exclusive APIC-ID limit the firmware might see. This is
for compatibility reasons as documented in the QEMU code.[0]
QEMU does not populate this FW_CFG_MAX_CPUS for AArch64 and RISC-V, so
we make it an x86-specific item.

As `fw_cfg` is also available for MSHV featured builds, we need a way to
calculate the APIC-ID limit also in such builds. We therefore modify the
`kvm` guard for `max_apic_id` and include it for compilation if either
`kvm` or `fw_cfg` are used. All other call sites remain KVM specific.
Thus no additional changes are required.

[0] https://github.com/qemu/qemu/blob/6e9a825c1d4e7b62d072e99a89ecd1a74c7f0d55/hw/i386/fw_cfg.c#L134

On-behalf-of: SAP pascal.scholz@sap.com
Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
QEMU can hint firmware to show a boot menu. To do so, one can use the
`-boot menu` option.

Cloud Hypervisor doesn't have a comparable option. We therefore set the
FW_CFG_BOOT_MENU entry to false.

On-behalf-of: SAP pascal.scholz@sap.com
Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
We intentionally leave out certain fw_cfg legacy items. This commit adds
short documentation explaining why each item is omitted.

On-behalf-of: SAP pascal.scholz@sap.com
Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
We make `fw_cfg` a default feature to allow for an easier build at our
customer.

[ Adapted to v55: realign the dhat-heap comment as required by taplo ]

On-behalf-of: SAP pascal.scholz@sap.com
Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
fw_cfg is required for the bootorder feature.

Original 72531c5:
devices: Fix clippy: unneeded late initialization

```
warning: unneeded late initialization
   --> devices/src/legacy/gpio_pl061.rs:258:9
    |
258 |         let value;
    |         ^^^^^^^^^^
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_late_init
    = note: `-D clippy::needless-late-init` implied by `-D clippy::all`
```

On-behalf-of: SAP pascal.scholz@sap.com
Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
Signed-off-by: Rob Bradford <rbradford@meta.com>
QEMU uses the Open Firmware format for representing device paths in its
`fw_cfg`'s `bootorder` entry. Originally consumed by SeaBIOS, this is
also the format expected by OVMF/EDK2 for the respective `fw_cfg`
entry.[0]

CHV currently rejects device path generation for devices outside PCI
segment 0. This is required with the current OVMF integration: while
CHV exposes each PCI segment as a separate PCI domain/root complex,
OVMF only creates boot-time PCI root-bridge support for segment 0.[1]

To prepare the implementation of `fw_cfg`'s bootorder, we add support
for creating device paths in the Open Firmware format.

[0] https://github.com/tianocore/edk2/blob/2816ff0ab0d6505bf580aa8eec02cc2b89f04230/OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.c#L1222
[1] https://github.com/tianocore/edk2/blob/58a00ddd494845143667da0d807fa517bc5447b1/OvmfPkg/Library/PciHostBridgeUtilityLib/PciHostBridgeUtilityLib.c#L136

Original 72531c5:
devices: Fix clippy: unneeded late initialization

```
warning: unneeded late initialization
   --> devices/src/legacy/gpio_pl061.rs:258:9
    |
258 |         let value;
    |         ^^^^^^^^^^
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_late_init
    = note: `-D clippy::needless-late-init` implied by `-D clippy::all`
```

Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
On-behalf-of: SAP pascal.scholz@sap.com
Signed-off-by: Rob Bradford <rbradford@meta.com>
Signed-off-by: Julian Schindel <julian.schindel@cyberus-technology.de>
For now we only support setting `bootindex` for disk devices.
Supporting `bootindex` for other devices (e.g. network) is left open
for a follow up to add once we need such a feature.

[ Adapted to v55: the fw_cfg SYNTAX variant is based on v55's string
  with the burst options ]

Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
On-behalf-of: SAP pascal.scholz@sap.com
For consumption by the `fw_cfg` device, we make `DeviceManager` collect
and expose a list of devices for which a boot index was configured.

[ Adapted to v55: also forget the boot order entry after a failed
  hotplug. The fork did this in 6b2c581, but v55 carries the upstream
  version of that commit without the boot order part ]

Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
On-behalf-of: SAP pascal.scholz@sap.com
It is possible that the user might supply an item with the path
`bootorder` via CLI/API. In this case, QEMU overrides the supplied item
with its own data when resetting the machine after creating it.[0, 1]
We do the same here.

Clean up some absolute paths referencing `FwCfgContent` in the process.

[0] https://github.com/qemu/qemu/blob/6e9a825c1d4e7b62d072e99a89ecd1a74c7f0d55/hw/nvram/fw_cfg.c#L976
[1] https://github.com/qemu/qemu/blob/6e9a825c1d4e7b62d072e99a89ecd1a74c7f0d55/hw/core/machine.c#L1728

Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
On-behalf-of: SAP pascal.scholz@sap.com
QEMU's implementation does not provide any default binary blobs for
initrd, kernel and command line. We therefore also refrain from doing
so and make it the accepted default.

We replace the custom `Default` implementation with a derived one as
this implements `false` for all `bool` types and `None` for the
`Option` type.

[ Adapted to v55: e820 now also defaults to off (v55 enabled it on
  x86_64 only), kept v55's AArch64 note in the docs, and v55's SEV-SNP
  test fixture enables acpi_tables explicitly ]

Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
On-behalf-of: SAP pascal.scholz@sap.com
Using `bootorder` in device configurations requires a `fw_cfg` device
to be present. The current way of instantiating one is by explicitly
adding one to the command line. In cases one wasn't created this way,
we need to implicitly add one to make the `bootorder` applicable.

Adding it in the `device_manager` if we require one works for both
cases, VM instantiation via an API call and via the CLI.

Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
On-behalf-of: SAP pascal.scholz@sap.com
On-behalf-of: SAP pascal.scholz@sap.com
Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
virtio-devices: generalize disk locking

Block device mirroring, planned in a follow-up series, must lock the
mirror destination image through the same path as the block device's
own disk image.

As preparation, extract advisory lock acquisition into a helper that
accepts a disk backend, path, requested mode, and current mode. Keep
`try_lock_image` as the source-disk wrapper. No behavior change.

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>

virtio-devices: generalize lock granularity

Block device mirroring, planned in a follow-up series, must apply a
block device's locking policy to the mirror destination image.

Therefore, calculate the advisory lock granularity from a supplied disk
backend and path instead of using Block::disk_image.

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>

vmm: add option for QEMU compatible file locking

QEMU uses locks on specific bytes for modeling file lock permissions.
This commit only implements what's needed to model the permissions
cloud-hypervisor currently uses. This is needed to be compatible with
storage management systems that expect QEMU compatible file locking like
NetApp's NFS implementation.

QEMU uses two offsets from the start of the file to separate permissions
and "unshared" permissions. "unshared" permissions are permissions that
cannot be shared between lock holders [0] and can be considered
exclusive.
Starting from each offset, locks are placed with a length of one byte.
Each corresponds to a specific permission [1][2].

The locking is done by first signaling intent by locking the
required marker bytes. Next any conflicts with existing locks are
detected and in the failure case, the locks are rolled back.
Locking is done via `F_RDLCK`, which allows other parties to set the
same locks and check for conflicts with `F_WRLCK`.

[0]: https://github.com/qemu/qemu/blob/30e8a06b64aa58a3990ba39cb5d09531e7d265e0/block/file-posix.c#L131-L134
[1]: https://github.com/qemu/qemu/blob/30e8a06b64aa58a3990ba39cb5d09531e7d265e0/include/block/block-common.h#L392-L437
[2]: https://github.com/qemu/qemu/blob/30e8a06b64aa58a3990ba39cb5d09531e7d265e0/block/file-posix.c#L868-L940

Original a7a5471:
vmm: set `QemuCompatible` to the default `LockGranularityChoice`

Original b99d6ad:
block: Retry locking when interrupted by EINTR

Acquiring an image lock can be interrupted with EINTR. In this case, we
returned with an error. Instead, we now retry acquiring the lock.

Original 2c30474:
vmm: remove `get_` prefix

Rust typically doesn't use `get_` prefixes.

Original 8182977:
vmm: add resize permission to qemu-compatible locking

Also lock the resize permission lock for read-write opened disks.
Cloud-hypervisor can resize disks, so we should lock the byte.

Original af4a4c2:
block: release stale QEMU lock after downgrade

Block device mirroring, planned in a follow-up series, will lock the
mirror destination for writing during the copy and downgrade a
previously read-only disk to the source's read-only lock on completion.

That downgrade is broken: `try_acquire_lock_qemu()` only releases
unneeded bytes on rollback after a failed acquisition, so the write
marker byte stays locked and blocks other readers.

Release the bytes that the new lock type does not need once the conflict
checks succeed, and add a test that downgrades a write lock to a read
lock and verifies that another reader can still acquire the image.

On-behalf-of: SAP julian.schindel@sap.com
Signed-off-by: Julian Schindel <julian.schindel@cyberus-technology.de>
Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
On-behalf-of: SAP pascal.scholz@sap.com
On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>

vmm: move error handling into `fcntl` function

Avoids repeating the retry/error logic when adding new users of the
function.

Original 3945fd0:
vmm: fix safety comment for `fcntl` wrapper

Reference to pointer coercion doesn't happen for variadic functions like
`libc::fcntl`. While this doesn't pose a problem by itself, it removes
the check whether a reference can be coerced to the appropriate pointer
type or mutability. By explicitly casting to a pointer, we ensure
refactors don't accidentally break the safety requirements.

On-behalf-of: SAP julian.schindel@sap.com
Signed-off-by: Julian Schindel <julian.schindel@cyberus-technology.de>

vmm: refactor `LockGranularity` for easier addition of variants

By extracting the full file and file range locking, it's easier to add
file lock handling that's not following this pattern.

On-behalf-of: SAP julian.schindel@sap.com
Signed-off-by: Julian Schindel <julian.schindel@cyberus-technology.de>

vmm: refactor locking functions to be methods of `LockGranularity`

All functions take a `LockGranularity` already and making them part of
`LockGranularity` makes it easier to add associated helpers.

On-behalf-of: SAP julian.schindel@sap.com
Signed-off-by: Julian Schindel <julian.schindel@cyberus-technology.de>

vmm: remove `get_lock_state` function

The function suffers from a TOCTOU problem. There is no guarantee that
the locks set on the file at the time of the state check are the same as
at the time of the locking attempt.

[ Adapted to v55: kept the clippy::panic expectation on fcntl(), v55's
  lock file retry loop uses the new lock API, and the SYNTAX strings
  keep v55's burst options ]

Co-authored-by: Leander Kohler <leander.kohler@cyberus-technology.de>
On-behalf-of: SAP julian.schindel@sap.com
Signed-off-by: Julian Schindel <julian.schindel@cyberus-technology.de>
During live migration, VM ownership is moved away from the VMM thread.
To preserve guest-triggered reboot and shutdown lifecycle intent
across that ownership handover, we need a small lifecycle marker to
travel with the migrated VM state.

This change introduces `PostMigrationLifecycleEvent` and stores it in
`VmSnapshot` with `#[serde(default)]` for backward compatibility.
`Vm::snapshot()` now serializes the marker, and VM construction from a
snapshot restores it.

No control-loop behavior is changed in this commit. This is only the
data model/plumbing needed by follow-up commits.

Original 7a49a65:
vmm: generalize postponed lifecycle events

The postponed lifecycle event describes a deferred reboot or shutdown,
but its type and helpers are named after live migration.

Rename them to describe the lifecycle operation itself and centralize
event replay. This removes duplicate reboot and shutdown dispatch while
preserving live-migration behavior. It enables reuse within
blockdev-mirroring.

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>
Signed-off-by: Philipp Schuster <philipp.schuster@cyberus-technology.de>
Connect the explicit announcement API to the existing v54 net backend.
Send the first host RARP synchronously and rearm the existing control
worker for retries and guest notifications after an earlier guest ACK.
Without a control worker, send one host RARP per API request.

Keep the existing packet builder, automatic announcement lifecycle,
retry machinery, and device worker topology unchanged.

Original 216c3c8:
vmm: add internal post-migration announce action

Add an internal API action that triggers the post migration announce. We
can now wire this into the API.

Original a155689:
vmm: add mechanism for post-migration announcements

Some devices can or should do announcements after a live migration,
e.g., a network device announces its new location in a network to update
the MAC->port mappings in layer 2 switches. With this change a device
can return an announcement action ("announcer") to do that.

We use reverse ARP (RARP) packets for this, similar to QEMU. Also, we
do 5 rounds of announcements in background (in a dedicated thread).

[ Adapted to v55: ch-remote uses the clap derive Command enum, host RARP
  goes via the first tap as v55's VirtioNetHostAnnounceOps takes one
  tap, and the docs/api.md entry is dropped as v55 has no endpoint table
  there ]

On-behalf-of: SAP sebastian.eydam@sap.com
Signed-off-by: Sebastian Eydam <sebastian.eydam@cyberus-technology.de>
olivereanderson and others added 29 commits December 4, 2026 15:31
Introduce convenience methods for looking up CPUID value definitions.

We will later use these methods to assert certain policies at compile
time in order to stay consistent with MSR policies we introduce.

Due to the current limitations of const generics we unfortunately
need to duplicate a little bit code.

Signed-off-by: Oliver Anderson <oliver.anderson@cyberus-technology.de>
On-behalf-of: SAP oliver.anderson@sap.com
We refactor `generate_common_cpuid` to take CPU profiles into account.

Original 21cd135:
hypervisor: Remove redundant MSHV imports

Original 0c2c544:
misc: Make CPU profile part of various configs

We integrate the CPU profile into the various configs that
ultimately get set by the user.

This quickly ends up involving multiple files, luckily Rust
helps us find which ones via compilation errors.

Original 145622b:
arch: Fix typo in generate_common_cpuid

We fix a pre-existing typo in an info event in
the `generate_common_cpuid` function.

Original dbb1efd:
arch: Use backported CpuidParameters in profile generation code

In the cpuid_definitions crate we can now use the backported
CpuidParameters struct instead of Parameters.

In order to avoid further changes in this rather large patch set we
just re-export it for now.

Once the profile generation code has been upstreamed then we can just
simply replace these files with the upstreamed once anyway.

Original 46bd60a:
arch: Use backported RegisterAddress in CPU profile generation code

We re-export the backported RegisterAddress in the
msr_definitions module. We do this instead of directly importing
msr_adjustments::RegisterAddress everywhere because that is a larger
change.

Once we have upstreamed CPU profile generation then we can just simply
replace all of these files anyway.

Original 7551d1e:
arch: Remove duplicate serialization helpers

The serialization helpers have been moved into the helpers module.

We are now at a point where we can remove the duplicates in arch/lib.rs
without causing compilation errors.

Original 701188b:
arch: Allow unsafe for cpuid invocations

Since we have 1.89 as the MSRV (and not 1.95) we need to allow
unused unsafe in a few instances here.

It was painful to find the exact commit/revert that caused this
lint to appear so we just do it like this for now.

Original 9885fe5:
fuzz: Remove duplicate profile entry in CpusConfig

Original aea3800:
arch: Fix Clippy lints for CPUID updates

This fixes lints of the following kind:
```
error: this `if` can be collapsed into the outer `match`
   --> arch/src/x86_64/mod.rs:874:17
    |
874 | /                 if !config.amx {
875 | |                     if entry.index == 0 {
876 | |                         entry.edx &= !((1 << AMX_BF16) | (1 << AMX_TILE) | (1 << AMX_INT8));
...   |
882 | |                 }
    | |_________________^
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#collapsible_match
    = note: `-D clippy::collapsible-match` implied by `-D clippy::all`
    = help: to override `-D clippy::all` add `#[allow(clippy::collapsible_match)]`
help: collapse nested if block
    |
873 ~             0x7
874 ~                 if !config.amx => {
875 |                     if entry.index == 0 {
...
881 |                     }
882 ~                 }
    |
```

[ Adapted to v55: v55 already parses the nested option, and the MSHV
  get_sregs() signature change is not needed ]

Signed-off-by: Oliver Anderson <oliver.anderson@cyberus-technology.de>
On-behalf-of: SAP oliver.anderson@sap.com
On-behalf-of: SAP pascal.scholz@sap.com
Signed-off-by: Pascal Scholz <pascal.scholz@cyberus-technology.de>
Signed-off-by: Julian Schindel <julian.schindel@cyberus-technology.de>
This commit introduces a CLI for generating a CPU profile closely
matching the CPU of the machine the CLI is executed on. The idea is to
have a simple way to add more CPU profiles corresponding to physical
CPUs.

Note however that with the current setup one still needs a little bit
of manual work to integrate the generated CPU profile data into cloud
hypervisor itself.

Original 638c12d:
arch: Make the CPU profile generation tool MSR aware

We adapt the CPU profile generation tool to also take the MSR-based
features into account.

Original b83151c:
arch: Re-enable CPU profile generation tool

We adapt the CPU profile generation tool to the backported functionality
and re-enable the tool.

[ Adapted to v55: anyhow is optional and only used by the generator, as
  v55's arch crate no longer depends on it, the generator enables the
  clap features it needs because the v55 workspace disables clap's
  default features, and the absolute paths flagged by clippy are
  imported (folded in from "arch: fix clippy issues in CI") ]

Signed-off-by: Oliver Anderson <oliver.anderson@cyberus-technology.de>
On-behalf-of: SAP oliver.anderson@sap.com
[ Adapted to v55: keep dep:anyhow from the previous commit ]

Signed-off-by: Oliver Anderson <oliver.anderson@cyberus-technology.de>
On-behalf-of: SAP oliver.anderson@sap.com
Blockdev-mirroring for virtio-blk needs a home for its new types. Add
the mirror module with the lifecycle state, ahead of the logic that
fills it in.

MirrorPhase  the lifecycle: Running, Ready, Completing, Completed,
             Cancelling, Failed
MirrorState  the phase behind a Mutex, shared via Arc, with a guarded
             transition_to_phase that applies only the documented edges

Follow-up commits add the range lock for copy/write exclusion, the
AsyncIo wrapper that fans writes to both backends, the background copy
worker, and the virtio-blk and REST integration.

[ Adapted to v55: put #[expect(clippy::panic)] on the function that
  panics on an invalid phase transition, because v55 denies
  clippy::panic in production code. ]

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>
The copy worker and the virtqueue workers can both target the same
destination bytes during a mirror. Without coordination a destination
block can mix bytes from both. Add a primitive both will use to
serialise overlapping ranges.

RangeLockManager wraps a Mutex<BTreeMap<start, end_excl>> and a
Condvar.

    lock_range blocks while any held range overlaps.

Wired into the `AsyncIo` impl of `MirroringAsyncIo` and the copy worker
in follow-up commits.

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>
The mirror writes and the copy worker must block until a completion is
ready.

We add CompletionIo, pairing an AsyncIo backend with a PollContext so a
caller can wait for and drain a single notifier's completions.
PollContext uses epoll, which the virtio-block seccomp filter allows.
poll/ppoll are currently not permitted.

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>
Mirroring moves a virtio-blk disk to a new backend path while the guest
keeps running.
Guest writes during the move have to land on both disks. A background
copy worker streams the existing data across. The guest write path and
the copy worker can target the same byte range at the same time.

Mirror mutating guest requests to both backends via virtqueues, and
hold a range lock for each request so neither side touches the same
bytes at once.
Read requests are not mirrored and wired to the source disk.
The guest sees source's result, a destination failure moves MirrorPhase
to Failed.

Follow-ups: the copy worker that takes the same lock, and the
coordinator that handles start, cancel, complete, and rollback on
Failed.

Original 9fb9924:
block: add MirroringAsyncIo skeleton

Mirroring needs a per-queue AsyncIo that the virtio device can install
in place of the plain backend. Add the type now so later commits
introducing the range locks and the write fan-out have something to
reference.

The two backends may require different buffer alignments. Return the
stricter alignment and use separate owned buffers for mirrored writes.

Disable batching while mirroring so writes cannot be overtaken by a
flush, discard or write zeroes request. After a mirror failure, source
passthrough can use the source backend's batching support.

Hold a range lock until both backends complete each mirrored write,
discard or write zeroes request. Consume destination completions
internally and return the source completion to the guest. Both
backends use the original user_data.

Original c1a2e44:
block: use source passthrough after mirror failure

The virtqueue worker only owns the active AsyncIo and cannot create a
plain source backend after a mirror failure. `Block` retains the source
disk and must coordinate the backend switch across all virtqueues.

Until then, we keep the failed MirroringAsyncIo in source passthrough.
Requests bypass the destination and continue on the existing source
backend until `Block` cancels the mirror and swaps the queues back to
the source.

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>
Block device mirroring replicates new guest writes to the destination.
This does not copy data that was already present on the source when
mirroring started.
We introduce CopyWorker as a background worker that copies those
existing bytes while the guest keeps running.

A guest write (per-queue writers) can overlap the range CopyWorker is
currently copying.
Without synchronization, the background write could overwrite newer
guest data on the destination. Both paths therefore use the same range
lock, which CopyWorker holds across the source read and destination
write.

CopyWorker submits reads and writes through AsyncIo so it works with
any backend that implements the trait. It performs I/O sequentially and
uses CompletionIo to wait for completions from each non-blocking
notifier eventfd.

After copying all blocks, CopyWorker flushes the destination before
transitioning the mirror from Running to Ready. An I/O error transitions
the mirror to Failed, while a thread spawn error is returned to the
caller.

Original 0e4ef93:
block: preserve sparseness in CopyWorker

During block-dev mirroring, the CopyWorker reads each block from the
source disk and writes it to the destination. It used to write
zero-filled blocks as well, which allocates storage on the
destination for regions that hold no data.

When the destination supports sparse operations, we now check whether
a block is all zeros. If it is, we call punch_hole instead of
write_from_vec. This keeps the destination as sparse as the source.

The check currently looks at the full MIRROR_BLOCK_SIZE block, so only
all-zero blocks become holes. A smaller granularity would also punch
holes inside partly-zero blocks and save more space, at the cost of
more compute per block. We leave this for a later change.

[ Adapted to v55: put #[expect(clippy::panic)] on the function that
  panics on an invalid phase transition, because v55 denies
  clippy::panic in production code. ]

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>
Each queue worker owns its AsyncIo backend. Switching to or from
`MirroringAsyncIo` must therefore happen on the corresponding worker
thread.

We add a command receiver and eventfd for each queue. The eventfd wakes
the worker when a command is available. The worker waits for in-flight
requests to finish before replacing the backend and reporting the
result. Queue processing then resumes to avoid leaving descriptors
waiting after their kicks were consumed.

[ Adapted to v55: initialize the new handler field in the
  make_handler_with_io() test fixture, which v55 uses instead of
  building the test handler inline. ]

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>
Initialize block mirroring after verifying that the destination has the
same size as the source. Switch each virtqueue worker to a
`MirroringAsyncIo` backend that mirrors mutating requests to both disks.
Start the background `CopyWorker` after every worker acknowledges the
swap.

Create all replacement backends before sending any commands. If
installation fails after commands start being sent, mark the mirror as
failed and try to switch every worker back to the source backend.

Original 26007a7:
virtio-devices: set up mirror command channels

Set up a command path from `Block` to each virtqueue worker during
activation. Mirror operations use these paths to coordinate the
`AsyncIo` backend replacement across all workers.

`Block` retains one `BlockQueueCommandSender` for every worker. The
shared command slot carries the replacement request, and the eventfd
wakes the corresponding worker to handle it.

Original 65eabea:
virtio-devices, block: add Block::cancel_mirror

Cancel reverts every virtqueue worker to a plain AsyncIo on the source
disk, transitions the mirror to Cancelling state and joins the copy
worker, releasing the destination disk.
The copy worker now exits before the next block once the phase is
terminal instead of copying the remainder.

Cancel is rejected once a completion was attempted: a queue may already
write to the destination only, so reverting would lose acknowledged
guest writes.

The REST plumbing for cancel comes in a follow-up commit.

[ Adapted to v55: build the queue command channels in v55's activate()
  loop, which iterates over the enabled queues with the driver's queue
  index. ]

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>
Add device manager entrypoints for starting a block mirror and querying
its status. The upcoming REST API uses these entrypoints to control and
observe the mirror progress.

We require an existing destination with the same format and logical
size as the source. The copy worker and mirrored guest requests use
source offsets on the destination. Equal sizes guarantee that these
offsets are valid and avoid leaving an uncopied trailing range.
Matching the format preserves the configured image type after
completion. We open the destination for writing using the source disk's
backend configuration.

Mirroring continues in the background. We expose its phase and copy
progress to let operators decide when to complete or cancel it.

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>
After the copy worker reaches `Ready`, completion switches every
virtqueue to the destination and makes it the active disk.

We create all replacement backends before starting completion. A
failure at this point leaves the mirror unchanged.

Once completion starts, some virtqueue workers may already use the
destination backend exclusively. A failure at this point cannot be
recovered without risking acknowledged writes or serving stale data.
We treat command and acknowledgement failures as unrecoverable.

Original f6fc614:
virtio-devices: drain queues before a mirror switch-over

A destination failure during mirror completion or cancellation can race
the phase transition to Completing or Cancelling, which panics on an
illegal phase change.

Drain and freeze every virtqueue before the phase transition using a
new DrainAndStallQueue command until the next virtqueue command is
issued. Completion and cancellation always follow with a backend swap,
which resumes submissions. A frozen queue cannot fail, keeping the
phase transition race-free.

A failed drain resumes every queue with a new ResumeQueue command that
lifts the stall without replacing the backend.

If the mirror failed while draining, completion reverts the queues to
the source and returns NotReady.

The regression test fails the mirror when the drain command arrives
while the phase is Ready, and asserts that the completion fails
instead of switching over.

[ Adapted to v55: initialize the new handler field in the
  make_handler_with_io() test fixture and import AsyncIoError in the new
  tests, because v55's block.rs no longer imports it. ]

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>
Cancel reverts every virtqueue worker to a plain AsyncIo on the source
disk, transitions the mirror to Cancelling state and joins the copy
worker, releasing the destination disk.
The copy worker now exits before the next block once the phase is
terminal instead of copying the remainder.

Cancel is rejected once a completion was attempted: a queue may already
write to the destination only, so reverting would lose acknowledged
guest writes.

The REST plumbing for cancel comes in a follow-up commit.

Original f6fc614:
virtio-devices: drain queues before a mirror switch-over

A destination failure during mirror completion or cancellation can race
the phase transition to Completing or Cancelling, which panics on an
illegal phase change.

Drain and freeze every virtqueue before the phase transition using a
new DrainAndStallQueue command until the next virtqueue command is
issued. Completion and cancellation always follow with a backend swap,
which resumes submissions. A frozen queue cannot fail, keeping the
phase transition race-free.

A failed drain resumes every queue with a new ResumeQueue command that
lifts the stall without replacing the backend.

If the mirror failed while draining, completion reverts the queues to
the source and returns NotReady.

The regression test fails the mirror when the drain command arrives
while the phase is Ready, and asserts that the completion fails
instead of switching over.

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>
During block-dev mirroring, the CopyWorker reads each block from the
source disk and writes it to the destination. It used to write
zero-filled blocks as well, which allocates storage on the
destination for regions that hold no data.

When the destination supports sparse operations, we now check whether
a block is all zeros. If it is, we call punch_hole instead of
write_from_vec. This keeps the destination as sparse as the source.

The check currently looks at the full MIRROR_BLOCK_SIZE block, so only
all-zero blocks become holes. A smaller granularity would also punch
holes inside partly-zero blocks and save more space, at the cost of
more compute per block. We leave this for a later change.

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>
Signed-off-by: Julian Schindel <julian.schindel@cyberus-technology.de>
Cover the range-lock and passthrough behaviour of MirroringAsyncIo with
a mock AsyncIo, so the synchronization invariants are checked without
real disk I/O.

The tests cover:
- overlapping mirror writes complete in order under the range lock
- a copy-worker range hold blocks an overlapping guest write until it is
  released
- reads pass through to the source only
- a destination submit failure degrades the mirror to source passthrough

A watchdog thread fails a test on timeout, so a locking regression
surfaces as a failure rather than a hang.

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>
The synchronous mirrored write holds its range guard from acquisition
through both the source and destination completions. Nothing else pins
that lifetime, so a regression to dropping the guard early (`let _`
instead of `let _guard`) would let an overlapping lock_range acquire
while the write is still in flight, the exact race the range lock exists
to prevent.

Add guard_is_held_across_submit_and_wait and a GatedMockAsyncIo backend
whose destination completion is withheld until released from another
thread. The write parks in wait_for_completions holding its guard while
the test asserts an overlapping lock_range blocks, then acquires only
once the completion is released and the write drops the guard.

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>
Test the MirrorState phase state machine (allowed transitions, rejected
ones, terminal Completed, and Failed keeping its first reason), the
tracked-vs-barrier fsync split, write_zeroes mirroring, and that a
degraded mirror passes every op through to the source alone.

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>
Document the operator workflow (start, status, complete, cancel, failure
handling, unrecoverable errors, and conflicting operations) and the
design behind it: the CopyWorker, the MirroringAsyncIo write fan-out,
and the range lock.

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>
Signed-off-by: Julian Schindel <julian.schindel@cyberus-technology.de>
Wire disk mirroring through to the HTTP API so a running VM can be told
to start mirroring a disk onto a destination path.

Add the /vm.disk-mirror-start endpoint and its request handler, the
vm_disk_mirror_start dispatch on the VMM, and the Vm::mirror_disk
wrapper that locks the device manager and maps its error into the
vmm error type. A new DiskMirrorStart error covers the case where no
VM owns the device manager.

Original a603734:
vmm: deny conflicting ops while a disk mirror runs

Reject disk resizing, snapshotting, device removal, VM reboot and live
migration while a disk mirror is active. These operations can interrupt
mirroring or lose its state, which is not included in migration.

The operator must complete or cancel the mirror first. Shutting down or
deleting the VM cancels all active mirrors.

Original 98ee480:
vmm: dedup block device lookup in DeviceManager

Refactor the redundant find-by-id scan over block_devices.

[ Adapted to v55: check for an active mirror at the start of v55's
  reworked remove_device(), which also removes devices that are no
  longer in the device tree. Drop the early return in Vm::shutdown(),
  which v55 already has, and use PauseCommon::pause_requested() instead
  of the removed VirtioCommon::paused flag. ]

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>
Acquire a write lock on the destination before installing mirror queue
backends. The destination uses the source disk locking granularity and
retains the lock through its open file description.

On completion, retain a write lock for writable disks and downgrade to
a read lock for read-only disks. Report a lock conflict as HTTP 400.

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>
Emit one vm event for each disk-mirror outcome so management stacks
can track a mirror without polling vm.disk-mirror-status:

- vm:disk-mirror-ready when the background copy finishes
- vm:disk-mirror-failed when the mirror fails
- vm:disk-mirror-completed when the switch-over to the destination
  finishes
- vm:disk-mirror-cancelled when the mirror is cancelled

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>
Cloud Hypervisor holds the disk image lock process-wide, so re-opening
the destination here would not trip the lock. Compare canonicalized
paths instead and refuse a destination that already backs one of the
VM's disks.

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>
Signed-off-by: Julian Schindel <julian.schindel@cyberus-technology.de>
Block mirroring copies a disk's logical contents to the destination. For
QCOW2 images with backing files, this would flatten the image at the
destination and discard the backing-chain structure.

We add a disk backend validation hook and reject mirroring when either
the source or destination QCOW2 image has a backing file.  This
validates the source before creating the destination.  Hence, a rejected
request does not leave a new file behind. Return HTTP 400 for
unsupported images.

Standalone QCOW2 images remain supported.

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>
Wire disk mirroring through to the HTTP API so a running VM can be told
to start mirroring a disk onto a destination path.

Add the /vm.disk-mirror-start endpoint and its request handler, the
vm_disk_mirror_start dispatch on the VMM, and the Vm::mirror_disk
wrapper that locks the device manager and maps its error into the
vmm error type. A new DiskMirrorStart error covers the case where no
VM owns the device manager.

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>
Expose the disk mirror status operation as a REST entrypoint so
operators can poll progress and detect terminal phases. The endpoint
returns the current phase, copied bytes, total bytes, and a failure
reason when the mirror is in the failed phase.

The PutHandler maps unknown disk id and inactive mirror to 404 so
management layers can distinguish operator errors from server faults.

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>
Operators trigger the complete stage of blockdev-mirroring through this
entrypoint. The endpoint switches the device to the destination disk
after the copy worker reports the mirror ready.

The PutHandler maps device manager errors to HTTP status codes so
management layers can distinguish operator errors (404 for unknown disk
or no active mirror, 400 for not-yet-ready) from server faults.

Original 6898298:
virtio-devices, block: reject mirror ops on a paused device

A paused virtqueue worker is parked on its pause barrier and never
reaches its epoll loop, so it cannot pick up a staged BlockQueueCommand.
start_mirror, complete_mirror, and cancel_mirror staged the command
anyway and blocked in wait_for_mirror_queue_command_acks until the ack
timeout, then returned an error while the command lingered in the slot
and was applied late once the VM resumed, leaving the mirror
half-installed. complete_mirror additionally panicked on that timeout.

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>
Block::cancel_mirror was only reachable through a guest-initiated device
reset. Give the operator a way to abort a mirror and keep the guest on
the source disk.

Wire the call through the layers:
DeviceManager::mirror_disk_cancel resolves the device and maps errors,
Vm and the RequestHandler forward the call, and a new VmDiskMirrorCancel
action backs the PUT /vm.disk-mirror-cancel endpoint.
Unknown device ids and inactive mirrors map to 404, a cancel after an
attempted completion maps to 400, and revert failures surface as
internal errors.

A failed cancel keeps the mirror handle and leaves the mirror in the
Cancelling phase. Cancel accepts that phase as a retry, so the request
can simply be retried. CancelToSource commands are idempotent per
virtqueue.

Original 6898298:
virtio-devices, block: reject mirror ops on a paused device

A paused virtqueue worker is parked on its pause barrier and never
reaches its epoll loop, so it cannot pick up a staged BlockQueueCommand.
start_mirror, complete_mirror, and cancel_mirror staged the command
anyway and blocked in wait_for_mirror_queue_command_acks until the ack
timeout, then returned an error while the command lingered in the slot
and was applied late once the VM resumed, leaving the mirror
half-installed. complete_mirror additionally panicked on that timeout.

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>
Guest-initiated reboot and shutdown tear down the VM, which drops an
active mirror before the operator can complete or cancel it.

Instead, this change keeps the mirror and copy worker alive when the VM
stops. Record the guest lifecycle request and replay it after the
operator resolves the last active mirror.

When replaying, skip a second Vm::shutdown() because the VM was already
stopped while postponing the event.

[ Adapted to v55: postpone_lifecycle_event() returns a plain bool,
  because v55's Vm::shutdown() no longer returns an error. ]

On-behalf-of: SAP leander.kohler@sap.com
Signed-off-by: Leander Kohler <leander.kohler@cyberus-technology.de>
@phip1611 phip1611 self-assigned this Dec 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants