From f653afe7ed6dc3979378ef941d46bc67c5cfaba9 Mon Sep 17 00:00:00 2001 From: CMGS Date: Thu, 23 Jul 2026 13:55:44 +0800 Subject: [PATCH 01/11] ci: add dev branch build and release workflow Build cloud-hypervisor on the dev branch for x86_64 and aarch64, then publish both static binaries to a rolling dev prerelease with checksums and build provenance. The binaries are built with the fw_cfg feature. On aarch64 that is what lets `--firmware` and `--kernel` be combined so EDK2 boots the kernel through fw_cfg and the guest gets ACPI; without `--fw-cfg-config` the feature changes nothing. The staged binary prints its enabled features so the release log shows the flag took effect. Signed-off-by: CMGS --- .github/workflows/dev-release.yaml | 110 +++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 .github/workflows/dev-release.yaml diff --git a/.github/workflows/dev-release.yaml b/.github/workflows/dev-release.yaml new file mode 100644 index 0000000000..067fb01cf2 --- /dev/null +++ b/.github/workflows/dev-release.yaml @@ -0,0 +1,110 @@ +name: Build and Release Dev + +on: + push: + branches: [dev] + +permissions: + contents: write + +concurrency: + group: dev-release + cancel-in-progress: true + +jobs: + build: + strategy: + fail-fast: false + matrix: + include: + - runner: ubuntu-22.04 + arch: x86_64 + - runner: ubuntu-22.04-arm + arch: aarch64 + runs-on: ${{ matrix.runner }} + steps: + - uses: actions/checkout@v7 + + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: stable + + - name: Show toolchain + run: | + rustc --version --verbose + cargo --version --verbose + + - name: Build cloud-hypervisor (release) + run: CH_EXTRA_VERSION="dev-${GITHUB_SHA::12}" cargo build --release --features fw_cfg + + - name: Stage artifacts + run: | + set -euo pipefail + mkdir -p dist + cp -v target/release/cloud-hypervisor "dist/cloud-hypervisor-${{ matrix.arch }}" + "./dist/cloud-hypervisor-${{ matrix.arch }}" -v --version + rustc --version --verbose | tr '\n' ';' > "dist/rustc-${{ matrix.arch }}.txt" + + - uses: actions/upload-artifact@v7 + with: + name: dist-${{ matrix.arch }} + path: dist/ + + release: + needs: build + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + + - uses: actions/download-artifact@v8 + with: + pattern: dist-* + merge-multiple: true + path: dist + + - name: Add provenance and checksums + run: | + set -euo pipefail + chmod +x dist/*-x86_64 dist/*-aarch64 + version=$(./dist/cloud-hypervisor-x86_64 --version | awk 'NR==1 {v=$2} END {print v}') + cat > dist/build-info.json < SHA256SUMS) + cat dist/SHA256SUMS + + - name: Create dev release + uses: softprops/action-gh-release@v3 + with: + tag_name: dev + target_commitish: ${{ github.sha }} + name: Dev Build + body: | + Branch: `${{ github.ref_name }}` + Commit: `${{ github.sha }}` + Workflow Run: `${{ github.run_id }}` + files: dist/* + prerelease: true + make_latest: false + overwrite_files: true + fail_on_unmatched_files: true + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Move dev tag to current commit + run: | + git tag -f dev "${GITHUB_SHA}" + git push origin refs/tags/dev --force From 18345df6de2a99c1092fdab9adffad7baee36a1d Mon Sep 17 00:00:00 2001 From: CMGS Date: Sun, 19 Jul 2026 17:11:47 +0800 Subject: [PATCH 02/11] vmm: add diff snapshots Every snapshot currently dumps the entire guest RAM, so the pause a snapshot imposes grows with the memory size regardless of how little the guest has changed. Iterative checkpointing and warm pre-copy (take a snapshot, let the guest run, take another) repeat that full-memory cost every round. Add a diff snapshot: `vm.snapshot` accepts a `snapshot_type` of `full` (default) or `diff`, exposed as `ch-remote snapshot --diff`. The first diff of a series writes a full baseline and enables dirty-page tracking; each subsequent diff writes only the pages dirtied since the previous one, so its pause is proportional to the dirtied memory rather than to the guest RAM size. Dirty pages are harvested after the device snapshot, so pages touched by snapshot side effects are included. The whole series lives in one directory, and every diff request of a series must target that directory. A delta `memory-ranges.diff.N` starts with a magic, an entry count and a table of (gpa, length) pairs, followed by the bytes of each entry, so it does not rely on the filesystem preserving holes. It is written under a temporary name, synced and renamed into place before `config.json` and `state.json` are replaced; both are synced under temporary names first and then renamed back to back. The memory manager state records how many deltas it covers, so an interrupted diff leaves the previous snapshot of the series restorable. The three syncs run inside the pause, in time proportional to the dirtied memory. A full snapshot, a memory layout change, a failed snapshot, a migration, a reboot, a shutdown or deleting the VM ends the series and stops dirty logging. Restore needs no new parameter: memory fills from the baseline (in any restore mode except ondemand, which a series rejects), then the deltas the state counts replay in order. A missing delta, or one whose table does not fit the snapshot's memory layout or its own file size, fails the restore before that delta touches memory. Dirty tracking is enabled lazily on the first diff rather than at boot, so a VM that never takes a diff snapshot pays no runtime cost; while a series is active the guest pays KVM dirty logging. Validated: an integration test writes tmpfs markers before and after the baseline and reads both back through a restore of the series directory; unit tests cover replaying only a delta's entries and rejecting foreign, out-of-layout and truncated delta files. Allow rename in the seccomp filter of the VMM thread: the delta and the staged config and state files are installed with it. A backend with DEVICE_STATE is stopped by the state save of every snapshot, and resuming it sends SET_FEATURES without F_LOG_ALL and a new SET_MEM_TABLE whose regions have no log bitmap. A series continues after that resume, so while a log region is active keep F_LOG_ALL, send the log base again after the memory table and enable vring logging before the vrings are enabled. Otherwise backend writes never reach a delta and a restore returns stale guest memory. A hot-added region can outgrow the log, so setup then stays unlogged and the next diff reports the layout change. Signed-off-by: CMGS --- cloud-hypervisor/src/bin/ch-remote.rs | 30 +- cloud-hypervisor/tests/integration.rs | 130 ++++++++ docs/snapshot_restore.md | 32 ++ fuzz/fuzz_targets/http_api.rs | 4 +- virtio-devices/src/vhost_user/mod.rs | 159 ++++++++++ .../src/vhost_user/vu_common_ctrl.rs | 51 ++- vmm/src/api/mod.rs | 34 +- vmm/src/api/openapi/cloud-hypervisor.yaml | 8 + vmm/src/lib.rs | 85 ++++- vmm/src/memory_manager.rs | 300 +++++++++++++++++- vmm/src/seccomp_filters.rs | 6 + vmm/src/vm.rs | 127 +++++--- 12 files changed, 895 insertions(+), 71 deletions(-) diff --git a/cloud-hypervisor/src/bin/ch-remote.rs b/cloud-hypervisor/src/bin/ch-remote.rs index c935198bae..4abb99539e 100644 --- a/cloud-hypervisor/src/bin/ch-remote.rs +++ b/cloud-hypervisor/src/bin/ch-remote.rs @@ -462,8 +462,11 @@ fn rest_api_do_command( simple_api_command(socket, "PUT", "add-vsock", Some(&vsock_config)) .map_err(Error::HttpApiClient) } - Command::Snapshot { destination_url } => { - let snapshot_config = snapshot_config(destination_url); + Command::Snapshot { + destination_url, + diff, + } => { + let snapshot_config = snapshot_config(destination_url, *diff); simple_api_command(socket, "PUT", "snapshot", Some(&snapshot_config)) .map_err(Error::HttpApiClient) } @@ -598,8 +601,11 @@ fn dbus_api_do_command( let vsock_config = add_vsock_config(arg_vsock_config)?; proxy.api_vm_add_vsock(&vsock_config) } - Command::Snapshot { destination_url } => { - let snapshot_config = snapshot_config(destination_url); + Command::Snapshot { + destination_url, + diff, + } => { + let snapshot_config = snapshot_config(destination_url, *diff); proxy.api_vm_snapshot(&snapshot_config) } Command::Restore { .. } => proxy.api_vm_restore(fd_request_body.as_deref().unwrap()), @@ -747,9 +753,14 @@ fn add_vsock_config(config: &str) -> Result { Ok(vsock_config) } -fn snapshot_config(url: &str) -> String { +fn snapshot_config(url: &str, diff: bool) -> String { let snapshot_config = api::VmSnapshotConfig { destination_url: String::from(url), + snapshot_type: if diff { + api::VmSnapshotType::Diff + } else { + api::VmSnapshotType::Full + }, }; serde_json::to_string(&snapshot_config).unwrap() @@ -999,6 +1010,11 @@ enum Command { // TODO: Take a PathBuf, as only file:// URLs are supported. #[arg(help = "file:// URL of an existing snapshot directory, e.g. file:///tmp/snapshot")] destination_url: String, + #[arg( + long, + help = "Write only pages dirtied since the previous snapshot; the first --diff takes a full baseline and starts dirty tracking" + )] + diff: bool, }, } @@ -1190,7 +1206,9 @@ mod tests { ( vec!["snapshot", "file:///tmp/snapshot"], "PUT /api/v1/vm.snapshot HTTP/1.1", - Some(serde_json::json!({"destination_url": "file:///tmp/snapshot"})), + Some( + serde_json::json!({"destination_url": "file:///tmp/snapshot", "snapshot_type": "full"}), + ), ), ] { let cli = Cli::try_parse_from(iter::once("ch-remote").chain(args)) diff --git a/cloud-hypervisor/tests/integration.rs b/cloud-hypervisor/tests/integration.rs index 5f116241f2..0007a8802f 100644 --- a/cloud-hypervisor/tests/integration.rs +++ b/cloud-hypervisor/tests/integration.rs @@ -10596,6 +10596,12 @@ mod ivshmem { ); } + #[test] + #[cfg(not(feature = "mshv"))] + fn test_snapshot_restore_diff_chain() { + snapshot_restore_common::_test_snapshot_restore_diff_chain(); + } + #[test] fn test_snapshot_restore_with_resume() { snapshot_restore_common::_test_snapshot_restore( @@ -10736,6 +10742,8 @@ mod ivshmem { } mod snapshot_restore_common { + #[cfg(not(feature = "mshv"))] + use std::fs::create_dir; use std::fs::{read_to_string, remove_dir_all}; use std::process::Command; use std::sync::atomic::{AtomicU64, Ordering}; @@ -10787,6 +10795,128 @@ mod snapshot_restore_common { )); } + fn snapshot_diff(api_socket: &str, url: &str) -> bool { + let output = Command::new(clh_command("ch-remote")) + .args([ + &format!("--api-socket={api_socket}"), + "snapshot", + "--diff", + url, + ]) + .output() + .unwrap(); + if !output.status.success() { + eprintln!( + "ch-remote snapshot --diff failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + } + output.status.success() + } + + #[cfg(not(feature = "mshv"))] + pub(crate) fn _test_snapshot_restore_diff_chain() { + let disk_config = UbuntuDiskConfig::new(JAMMY_IMAGE_NAME.to_string()); + let guest = Guest::new(Box::new(disk_config)); + let kernel_path = direct_kernel_boot_path(); + + let api_socket_source = format!("{}.1", temp_api_path(&guest.tmp_dir)); + let net_params = format!( + "id=net123,tap=,mac={},ip={},mask=255.255.255.128", + guest.network.guest_mac0, guest.network.host_ip0 + ); + + let mut child = GuestCommand::new(&guest) + .args(["--api-socket", &api_socket_source]) + .args(["--cpus", "boot=1"]) + .args(["--memory", "size=1G"]) + .args(["--kernel", kernel_path.to_str().unwrap()]) + .args([ + "--disk", + format!( + "path={}", + guest.disk_config.disk(DiskType::OperatingSystem).unwrap() + ) + .as_str(), + format!( + "path={}", + guest.disk_config.disk(DiskType::CloudInit).unwrap() + ) + .as_str(), + ]) + .args(["--net", net_params.as_str()]) + .args(["--cmdline", DIRECT_KERNEL_BOOT_CMDLINE]) + .capture_output() + .spawn() + .unwrap(); + + let snapshot_dir = temp_snapshot_dir_path(&guest.tmp_dir); + let series_dir = format!("{snapshot_dir}/series"); + create_dir(&series_dir).unwrap(); + + let r = panic::catch_unwind(|| { + guest.wait_vm_boot().unwrap(); + + guest + .ssh_command("echo diffmarkerA > /dev/shm/marker_a") + .unwrap(); + + assert!(remote_command(&api_socket_source, "pause", None)); + assert!(snapshot_diff( + &api_socket_source, + format!("file://{series_dir}").as_str(), + )); + assert!(remote_command(&api_socket_source, "resume", None)); + + guest + .ssh_command("echo diffmarkerB > /dev/shm/marker_b") + .unwrap(); + + assert!(remote_command(&api_socket_source, "pause", None)); + assert!(snapshot_diff( + &api_socket_source, + format!("file://{series_dir}").as_str(), + )); + }); + + kill_child(&mut child); + let output = child.wait_with_output().unwrap(); + handle_child_output(r, &output); + + let api_socket_restored = format!("{}.2", temp_api_path(&guest.tmp_dir)); + let mut child = GuestCommand::new(&guest) + .args(["--api-socket", &api_socket_restored]) + .args([ + "--restore", + format!("source_url=file://{series_dir},resume=true").as_str(), + ]) + .capture_output() + .spawn() + .unwrap(); + + let r = panic::catch_unwind(|| { + assert!(wait_until(Duration::from_secs(30), || remote_command( + &api_socket_restored, + "info", + None + ))); + + assert_eq!( + guest.ssh_command("cat /dev/shm/marker_a").unwrap().trim(), + "diffmarkerA" + ); + assert_eq!( + guest.ssh_command("cat /dev/shm/marker_b").unwrap().trim(), + "diffmarkerB" + ); + }); + + let _ = remove_dir_all(snapshot_dir.as_str()); + kill_child(&mut child); + let output = child.wait_with_output().unwrap(); + handle_child_output(r, &output); + } + /// Easy disambiguation between snapshot/restore variants. #[derive(Clone, Copy, Default)] pub(crate) struct SnapshotRestoreTest { diff --git a/docs/snapshot_restore.md b/docs/snapshot_restore.md index 6703f4b091..0930e7db95 100644 --- a/docs/snapshot_restore.md +++ b/docs/snapshot_restore.md @@ -60,6 +60,38 @@ be needed. `state.json` contains the virtual machine state. It is used to restore each component in the state it was left before the snapshot occurred. +## Diff snapshots + +Passing `snapshot_type=diff` (`ch-remote snapshot --diff `) writes only +the pages dirtied since the previous snapshot of the series. The first `diff` +request takes a full baseline and enables dirty-page tracking; each subsequent +one dumps the delta, so the pause cost is proportional to the amount of dirtied +memory rather than to the guest RAM size. A `full` request (or any snapshot +failure, a memory layout change, a migration, a reboot, a shutdown, or +deleting the VM) ends the series; the next `diff` starts a new one with a +fresh baseline in a fresh directory. + +The whole series lives in one directory, and every `diff` request of a series +must target that same directory: + +```bash +ls /foo/snapshot/ +config.json memory-ranges memory-ranges.diff.1 memory-ranges.diff.2 state.json +``` + +Each `memory-ranges.diff.N` starts with a table of the guest memory ranges it +carries, followed by their contents, so it does not depend on the filesystem +keeping holes. A delta is written under a temporary name and renamed into +place before `config.json` and `state.json` are replaced, and `state.json` +records how many deltas belong to it: an interrupted diff leaves the previous +snapshot of the series restorable. + +Restore needs no extra parameter: point `source_url` at the directory. Memory +fills from the baseline and the deltas `state.json` counts replay in order; +a missing delta, or one whose table does not fit the snapshot's memory +layout or file size, fails the restore before that delta touches memory. A +diff-snapshot series cannot be combined with `memory_restore_mode=ondemand`. + ## Restore a Cloud Hypervisor VM Given that one has access to an existing snapshot in `/home/foo/snapshot`, diff --git a/fuzz/fuzz_targets/http_api.rs b/fuzz/fuzz_targets/http_api.rs index 7010b9b6fb..6a7ebe8bf8 100644 --- a/fuzz/fuzz_targets/http_api.rs +++ b/fuzz/fuzz_targets/http_api.rs @@ -15,7 +15,7 @@ use vm_migration::MigratableError; use vmm::api::http::*; use vmm::api::{ ApiRequest, BalloonStatsResponse, RequestHandler, VmInfoResponse, VmReceiveMigrationData, - VmSendMigrationData, VmmPingResponse, + VmSendMigrationData, VmSnapshotConfig, VmmPingResponse, }; use vmm::config::RestoreConfig; use vmm::vm::{Error as VmError, VmState}; @@ -105,7 +105,7 @@ impl RequestHandler for StubApiRequestHandler { Ok(()) } - fn vm_snapshot(&mut self, _: &str) -> Result<(), VmError> { + fn vm_snapshot(&mut self, _: &VmSnapshotConfig) -> Result<(), VmError> { Ok(()) } diff --git a/virtio-devices/src/vhost_user/mod.rs b/virtio-devices/src/vhost_user/mod.rs index 6285211959..9eef5bf846 100644 --- a/virtio-devices/src/vhost_user/mod.rs +++ b/virtio-devices/src/vhost_user/mod.rs @@ -964,7 +964,9 @@ mod tests { use std::os::unix::net::{UnixListener, UnixStream}; use std::thread; + use vhost::vhost_kern::vhost_binding::VHOST_VRING_F_LOG; use vhost::vhost_user::message::{FrontendReq, VhostUserHeaderFlag}; + use virtio_queue::QueueT; use vm_memory::{FileOffset, GuestAddress}; use vm_migration::Snapshottable; use vmm_sys_util::tempdir::TempDir; @@ -995,6 +997,16 @@ mod tests { stream.write_all(&reply).unwrap(); } + fn ack_log_base(stream: &mut UnixStream) { + let log = read_request(stream, FrontendReq::SET_LOG_BASE); + let mut reply = Vec::with_capacity(12 + log.len()); + reply.extend_from_slice(&u32::from(FrontendReq::SET_LOG_BASE).to_ne_bytes()); + reply.extend_from_slice(&(VhostUserHeaderFlag::REPLY.bits() | 1).to_ne_bytes()); + reply.extend_from_slice(&(log.len() as u32).to_ne_bytes()); + reply.extend_from_slice(&log); + stream.write_all(&reply).unwrap(); + } + // Connects a handle to a fake backend that offers the given features. fn connect_handle(features: u64) -> (VhostUserHandle, UnixStream) { let temp_dir = TempDir::new_with_prefix("/tmp/vhost-user-handle-").unwrap(); @@ -1186,6 +1198,153 @@ mod tests { backend.join().unwrap(); } + fn vring_addr_flags(payload: &[u8]) -> u32 { + u32::from_ne_bytes(payload[4..8].try_into().unwrap()) + } + + // Runs setup on a handle with an active log that covers one u64 word of pages. + fn setup_with_active_log( + mem_size: u64, + backend_check: impl FnOnce(&mut UnixStream) + Send + 'static, + handle_check: impl FnOnce(&mut VhostUserHandle), + ) { + let protocol_features = VhostUserVirtioFeatures::PROTOCOL_FEATURES.bits(); + let log_all = VhostUserVirtioFeatures::LOG_ALL.bits(); + let log_shmfd = VhostUserProtocolFeatures::LOG_SHMFD; + let temp_dir = TempDir::new_with_prefix("/tmp/vhost-user-log-").unwrap(); + let socket_path = temp_dir.as_path().join("backend.sock"); + let listener = UnixListener::bind(&socket_path).unwrap(); + let backend = thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + assert!(read_request(&mut stream, FrontendReq::SET_OWNER).is_empty()); + assert!(read_request(&mut stream, FrontendReq::GET_FEATURES).is_empty()); + write_reply( + &mut stream, + FrontendReq::GET_FEATURES, + protocol_features | log_all, + ); + assert!(read_request(&mut stream, FrontendReq::GET_PROTOCOL_FEATURES).is_empty()); + write_reply( + &mut stream, + FrontendReq::GET_PROTOCOL_FEATURES, + log_shmfd.bits(), + ); + read_request(&mut stream, FrontendReq::SET_PROTOCOL_FEATURES); + ack_log_base(&mut stream); + read_request(&mut stream, FrontendReq::SET_FEATURES); + backend_check(&mut stream); + }); + + let file = File::options() + .read(true) + .write(true) + .create_new(true) + .open(temp_dir.as_path().join("memory")) + .unwrap(); + file.set_len(mem_size).unwrap(); + let mem = GuestMemory::from_ranges_with_files(&[( + GuestAddress(0), + mem_size as usize, + Some(FileOffset::new(file, 0)), + )]) + .unwrap(); + let kill_evt = EventFd::new(libc::EFD_NONBLOCK).unwrap(); + let mut vu = VhostUserHandle::connect_vhost_user( + false, + socket_path.to_str().unwrap(), + 1, + false, + &kill_evt, + |_| Ok(()), + ) + .unwrap(); + vu.negotiate_features_vhost_user(protocol_features | log_all, log_shmfd, false) + .unwrap(); + vu.start_dirty_log(0xfff).unwrap(); + + struct BackendReqHandler; + impl VhostUserFrontendReqHandler for BackendReqHandler {} + let queues = [( + 0u16, + Queue::new(2).unwrap(), + EventFd::new(libc::EFD_NONBLOCK).unwrap(), + )]; + vu.setup_vhost_user::( + &mem, + &queues, + &NoopVirtioInterrupt {}, + protocol_features, + &None, + None, + Some(&[0]), + ) + .unwrap(); + handle_check(&mut vu); + backend.join().unwrap(); + } + + #[test] + fn setup_rearms_active_dirty_log_before_enabling_vrings() { + let protocol_features = VhostUserVirtioFeatures::PROTOCOL_FEATURES.bits(); + let log_all = VhostUserVirtioFeatures::LOG_ALL.bits(); + setup_with_active_log( + 0x1000, + move |stream| { + assert_eq!( + read_request(stream, FrontendReq::SET_FEATURES), + (protocol_features | log_all).to_ne_bytes() + ); + read_request(stream, FrontendReq::SET_MEM_TABLE); + ack_log_base(stream); + read_request(stream, FrontendReq::SET_VRING_NUM); + assert_eq!( + vring_addr_flags(&read_request(stream, FrontendReq::SET_VRING_ADDR)), + 0 + ); + read_request(stream, FrontendReq::SET_VRING_BASE); + read_request(stream, FrontendReq::SET_VRING_KICK); + assert_eq!( + vring_addr_flags(&read_request(stream, FrontendReq::SET_VRING_ADDR)), + 1 << VHOST_VRING_F_LOG + ); + read_request(stream, FrontendReq::SET_VRING_ENABLE); + assert_eq!( + vring_addr_flags(&read_request(stream, FrontendReq::SET_VRING_ADDR)), + 0 + ); + assert_eq!( + read_request(stream, FrontendReq::SET_FEATURES), + protocol_features.to_ne_bytes() + ); + }, + |vu| vu.stop_dirty_log().unwrap(), + ); + } + + #[test] + fn setup_stays_unlogged_when_memory_outgrew_the_log() { + let protocol_features = VhostUserVirtioFeatures::PROTOCOL_FEATURES.bits(); + setup_with_active_log( + 0x41000, + move |stream| { + assert_eq!( + read_request(stream, FrontendReq::SET_FEATURES), + protocol_features.to_ne_bytes() + ); + read_request(stream, FrontendReq::SET_MEM_TABLE); + read_request(stream, FrontendReq::SET_VRING_NUM); + assert_eq!( + vring_addr_flags(&read_request(stream, FrontendReq::SET_VRING_ADDR)), + 0 + ); + read_request(stream, FrontendReq::SET_VRING_BASE); + read_request(stream, FrontendReq::SET_VRING_KICK); + read_request(stream, FrontendReq::SET_VRING_ENABLE); + }, + |_| {}, + ); + } + #[test] fn restored_protocol_features_must_be_supported() { let protocol_features = VhostUserVirtioFeatures::PROTOCOL_FEATURES.bits(); diff --git a/virtio-devices/src/vhost_user/vu_common_ctrl.rs b/virtio-devices/src/vhost_user/vu_common_ctrl.rs index e29c634b74..206a85ba50 100644 --- a/virtio-devices/src/vhost_user/vu_common_ctrl.rs +++ b/virtio-devices/src/vhost_user/vu_common_ctrl.rs @@ -267,8 +267,18 @@ impl VhostUserHandle { (acked_features & self.backend_features & !(1u64 << VIRTIO_F_ACCESS_PLATFORM)) | VhostUserVirtioFeatures::PROTOCOL_FEATURES.bits(); + let required_log_size = dirty_log_size(mem.last_addr().raw_value()); + let dirty_logging = self + .shm_log + .as_ref() + .is_some_and(|log| log.size() as u64 >= required_log_size); + let log_all = if dirty_logging { + VhostUserVirtioFeatures::LOG_ALL.bits() + } else { + 0 + }; self.vu - .set_features(acked_features) + .set_features(acked_features | log_all) .map_err(Error::VhostUserSetFeatures)?; // Update internal value after it's been sent to the backend. @@ -277,6 +287,10 @@ impl VhostUserHandle { // Let's first provide the memory table to the backend. self.update_mem_table(mem)?; + if dirty_logging { + self.send_log_base()?; + } + // Send set_vring_num here, since it could tell backends, like SPDK, // how many virt queues to be handled, which backend required to know // at early stage. @@ -376,6 +390,12 @@ impl VhostUserHandle { self.queue_indexes.push(*queue_index); } + self.vrings_info = Some(vrings_info); + + if dirty_logging { + self.set_vring_logging(true)?; + } + self.enable_vhost_user_vrings(self.queue_indexes.clone(), true)?; if let Some(backend_req_handler) = backend_req_handler { @@ -384,7 +404,6 @@ impl VhostUserHandle { .map_err(Error::VhostUserSetBackendRequestFd)?; } - self.vrings_info = Some(vrings_info); self.ready = true; Ok(()) @@ -849,9 +868,7 @@ impl VhostUserHandle { // A page is always 4kiB from a vhost-user perspective, and each bit is // a page. The bitmap is read back as u64 words, so round it up to a // whole word to keep the last pages of guest RAM covered. - let ram_size_per_u64 = VHOST_LOG_PAGE * u64::from(u64::BITS); - let mmap_size = (last_ram_addr / ram_size_per_u64 + 1) * size_of::() as u64; - let mmap_handle = file.as_raw_fd(); + let mmap_size = dirty_log_size(last_ram_addr); // Set shm_log region size file.set_len(mmap_size).map_err(Error::SetFileSize)?; @@ -882,17 +899,28 @@ impl VhostUserHandle { // released. let old_region = self.shm_log.replace(Arc::new(region)); + self.send_log_base()?; + + Ok(old_region) + } + + fn send_log_base(&mut self) -> Result<()> { + let region = self.shm_log.as_ref().ok_or(Error::MissingShmLogRegion)?; + let mmap_handle = region + .file_offset() + .ok_or(Error::MissingShmLogRegion)? + .file() + .as_raw_fd(); + // Send the shm_log fd over to the backend let log = VhostUserDirtyLogRegion { - mmap_size, + mmap_size: region.size() as u64, mmap_offset: 0, mmap_handle, }; self.vu .set_log_base(0, Some(log)) - .map_err(Error::VhostUserSetLogBase)?; - - Ok(old_region) + .map_err(Error::VhostUserSetLogBase) } fn set_vring_logging(&mut self, enable: bool) -> Result<()> { @@ -975,6 +1003,11 @@ impl VhostUserHandle { } } +fn dirty_log_size(last_ram_addr: u64) -> u64 { + let ram_size_per_u64 = VHOST_LOG_PAGE * u64::from(u64::BITS); + (last_ram_addr / ram_size_per_u64 + 1) * size_of::() as u64 +} + fn memfd_create(name: &ffi::CStr, flags: u32) -> io::Result { // SAFETY: FFI call with valid arguments let res = unsafe { libc::syscall(libc::SYS_memfd_create, name.as_ptr(), flags) }; diff --git a/vmm/src/api/mod.rs b/vmm/src/api/mod.rs index 83199e00d7..71c3619327 100644 --- a/vmm/src/api/mod.rs +++ b/vmm/src/api/mod.rs @@ -268,10 +268,23 @@ pub struct VmRemoveDeviceData { pub id: String, } +/// Type of a VM snapshot: full memory dump or dirty-pages-only delta. +#[derive(Copy, Clone, Default, Deserialize, Serialize, Debug, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum VmSnapshotType { + /// Complete guest memory dump. + #[default] + Full, + /// Pages dirtied since the previous snapshot; the first diff is a full baseline. + Diff, +} + #[derive(Clone, Deserialize, Serialize, Default, Debug)] pub struct VmSnapshotConfig { /// The snapshot destination URL pub destination_url: String, + #[serde(default)] + pub snapshot_type: VmSnapshotType, } #[derive(Clone, Deserialize, Serialize, Default, Debug)] @@ -877,7 +890,7 @@ pub trait RequestHandler { fn vm_resume(&mut self) -> Result<(), VmError>; - fn vm_snapshot(&mut self, destination_url: &str) -> Result<(), VmError>; + fn vm_snapshot(&mut self, config: &VmSnapshotConfig) -> Result<(), VmError>; fn vm_restore(&mut self, restore_cfg: RestoreConfig) -> Result<(), VmError>; @@ -2072,7 +2085,7 @@ impl ApiAction for VmSnapshot { info!("API request event: VmSnapshot {config:?}"); let response = vmm - .vm_snapshot(&config.destination_url) + .vm_snapshot(&config) .map_err(ApiError::VmSnapshot) .map(|_| ApiResponsePayload::Empty); @@ -2776,4 +2789,21 @@ mod tests { .unwrap(); assert_eq!(data.effective_memory_mode(), MigrationMode::MemFDs); } + + #[test] + fn test_vm_snapshot_config_snapshot_type() { + let config: VmSnapshotConfig = + serde_json::from_str(r#"{"destination_url": "file:///foo"}"#).unwrap(); + assert_eq!(config.snapshot_type, VmSnapshotType::Full); + + let config: VmSnapshotConfig = + serde_json::from_str(r#"{"destination_url": "file:///foo", "snapshot_type": "diff"}"#) + .unwrap(); + assert_eq!(config.snapshot_type, VmSnapshotType::Diff); + + serde_json::from_str::( + r#"{"destination_url": "file:///foo", "snapshot_type": "bogus"}"#, + ) + .unwrap_err(); + } } diff --git a/vmm/src/api/openapi/cloud-hypervisor.yaml b/vmm/src/api/openapi/cloud-hypervisor.yaml index 5a9a9ed868..12256fa0cd 100644 --- a/vmm/src/api/openapi/cloud-hypervisor.yaml +++ b/vmm/src/api/openapi/cloud-hypervisor.yaml @@ -1840,6 +1840,14 @@ components: properties: destination_url: type: string + snapshot_type: + type: string + enum: [full, diff] + default: full + description: + With "diff", only pages dirtied since the previous snapshot of the + series are written; the first "diff" takes a full baseline and + starts dirty tracking. VmCoredumpData: required: diff --git a/vmm/src/lib.rs b/vmm/src/lib.rs index eed0caf1e1..c2665f30e6 100644 --- a/vmm/src/lib.rs +++ b/vmm/src/lib.rs @@ -51,7 +51,8 @@ use vmm_sys_util::sock_ctrl_msg::ScmSocket; use crate::api::{ ApiRequest, ApiResponse, BalloonStatsResponse, MigrationMode, RequestHandler, TimeoutStrategy, - VmInfoResponse, VmReceiveMigrationData, VmSendMigrationData, VmmPingResponse, + VmInfoResponse, VmReceiveMigrationData, VmSendMigrationData, VmSnapshotConfig, VmSnapshotType, + VmmPingResponse, }; use crate::config::{MemoryRestoreMode, RestoreConfig, VmMemoryZoneUpdateData, add_to_config}; #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] @@ -717,6 +718,12 @@ pub enum GuestResetAction { ShutdownVm, } +struct SnapshotSeries { + destination_url: String, + layout: MemoryRangeTable, + next_seq: u32, +} + pub struct Vmm { epoll: EpollContext, exit_evt: EventFd, @@ -745,6 +752,8 @@ pub struct Vmm { shutdown_action: GuestShutdownAction, reset_action: GuestResetAction, check_migration_evt: EventFd, + // dirty logging is active while a series exists + snapshot_series: Option, } /// Time before aborting on the page fault connection. @@ -974,6 +983,7 @@ impl Vmm { shutdown_action, reset_action, check_migration_evt, + snapshot_series: None, }) } @@ -2583,20 +2593,77 @@ impl RequestHandler for Vmm { } } - fn vm_snapshot(&mut self, destination_url: &str) -> result::Result<(), VmError> { + fn vm_snapshot(&mut self, config: &VmSnapshotConfig) -> result::Result<(), VmError> { match self.vm { VmOwnership::Owned(ref mut vm) => { if vm.restoring() { return Err(VmError::VmRestoring); } + let requested_diff = config.snapshot_type == VmSnapshotType::Diff; + // the first diff of a series is a full baseline + let effective_diff = requested_diff && self.snapshot_series.is_some(); + if requested_diff { + let layout = vm + .memory_range_table(MemoryRangePolicy::SkipPersisted) + .map_err(VmError::Snapshot)?; + if let Some(series) = &self.snapshot_series { + if config.destination_url != series.destination_url { + return Err(VmError::Snapshot(MigratableError::Snapshot(anyhow!( + "a diff snapshot must target its series directory {}", + series.destination_url + )))); + } + if series.layout.ranges() != layout.ranges() { + self.snapshot_series = None; + let _ = vm.stop_dirty_log(); + return Err(VmError::Snapshot(MigratableError::Snapshot(anyhow!( + "memory layout changed since the snapshot series \ + started; take a full snapshot" + )))); + } + } else { + if let Err(e) = vm.start_dirty_log() { + let _ = vm.stop_dirty_log(); + return Err(VmError::Snapshot(e)); + } + self.snapshot_series = Some(SnapshotSeries { + destination_url: config.destination_url.clone(), + layout, + next_seq: 1, + }); + } + } else if self.snapshot_series.take().is_some() { + vm.stop_dirty_log().map_err(VmError::Snapshot)?; + } + + let diff_seq = self + .snapshot_series + .as_ref() + .filter(|_| effective_diff) + .map(|s| s.next_seq); + vm.set_snapshot_diff_count(diff_seq.unwrap_or(0)); // Drain console_info so that FDs are not reused let _ = self.console_info.take(); - vm.snapshot() + let result = vm + .snapshot() .map_err(VmError::Snapshot) .and_then(|snapshot| { - vm.send(&snapshot, destination_url) + if diff_seq.is_some() { + // harvest after device capture to include its side-effect writes + let table = vm.dirty_log().map_err(VmError::Snapshot)?; + vm.set_diff_snapshot_ranges(table); + } + vm.send(&snapshot, &config.destination_url) .map_err(VmError::SnapshotSend) - }) + }); + if result.is_err() { + if self.snapshot_series.take().is_some() { + let _ = vm.stop_dirty_log(); + } + } else if let (Some(_), Some(series)) = (diff_seq, self.snapshot_series.as_mut()) { + series.next_seq += 1; + } + result } VmOwnership::Migration { .. } => Err(VmError::VmMigrating), VmOwnership::None => Err(VmError::VmNotRunning), @@ -2685,6 +2752,7 @@ impl RequestHandler for Vmm { return Err(VmError::VmNotCreated); } let mut vm = self.vm.take_owned_or(VmError::VmNotRunning)?; + self.snapshot_series = None; // Drain console_info so that the FDs are not reused let _ = self.console_info.take(); vm.shutdown(); @@ -2699,6 +2767,7 @@ impl RequestHandler for Vmm { // we reboot. let config = { let mut vm = self.vm.take_owned_or(VmError::VmNotCreated)?; + self.snapshot_series = None; let config = vm.get_config(); // First we stop the current VM vm.shutdown(); @@ -2827,6 +2896,7 @@ impl RequestHandler for Vmm { } fn vm_delete(&mut self) -> result::Result<(), VmError> { + self.snapshot_series = None; if self.vm_config.is_none() { return Ok(()); } @@ -3387,6 +3457,11 @@ impl RequestHandler for Vmm { &mut self, send_data_migration: VmSendMigrationData, ) -> result::Result<(), MigratableError> { + if self.snapshot_series.take().is_some() + && let VmOwnership::Owned(ref mut vm) = self.vm + { + let _ = vm.stop_dirty_log(); + } match self.vm { VmOwnership::Owned(ref vm) => { if vm.restoring() { diff --git a/vmm/src/memory_manager.rs b/vmm/src/memory_manager.rs index f5cc72322c..7aa2d156b6 100644 --- a/vmm/src/memory_manager.rs +++ b/vmm/src/memory_manager.rs @@ -6,8 +6,8 @@ #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] use std::collections::BTreeMap; use std::collections::{HashMap, HashSet}; -use std::fs::{File, OpenOptions}; -use std::io::{self, Seek, SeekFrom}; +use std::fs::{self, File, OpenOptions}; +use std::io::{self, Read, Seek, SeekFrom, Write}; use std::mem::{self, MaybeUninit, zeroed}; use std::num::NonZeroUsize; use std::ops::{BitAnd, Not, Sub}; @@ -190,6 +190,9 @@ const VMM_UFFD_ID: &str = "__vmm"; /// Filename used to store guest RAM in snapshot directories. pub const SNAPSHOT_FILENAME: &str = "memory-ranges"; +// a diff file holds this magic, a u64 entry count, (gpa, length) u64 pairs, +// then each entry's bytes in table order +const DIFF_SNAPSHOT_MAGIC: [u8; 8] = *b"CHDIFF01"; #[cfg(target_arch = "x86_64")] const X86_64_IRQ_BASE: u32 = 5; @@ -381,6 +384,8 @@ pub struct MemoryManager { thp: bool, user_provided_zones: bool, snapshot_memory_ranges: MemoryRangeTable, + diff_snapshot_ranges: Option, + diff_count: u32, cow_source: Option, memory_zones: MemoryZones, log_dirty: bool, // Enable dirty logging for created RAM regions @@ -539,6 +544,14 @@ pub enum Error { #[error("Error reading from snapshot file")] SnapshotRead(#[source] io::Error), + /// A diff-snapshot series cannot be restored on demand + #[error("A diff-snapshot series cannot be combined with 'memory_restore_mode=ondemand'")] + RestoreDiffWithOnDemand, + + /// A diff snapshot file does not describe this snapshot's memory + #[error("Invalid diff snapshot {0:?}: {1}")] + RestoreDiffInvalid(PathBuf, &'static str), + // Error copying snapshot into region #[error("Error copying snapshot into region")] SnapshotCopy(#[source] GuestMemoryError), @@ -2479,6 +2492,8 @@ impl MemoryManager { reserve: config.reserve, user_provided_zones, snapshot_memory_ranges: MemoryRangeTable::default(), + diff_snapshot_ranges: None, + diff_count: 0, cow_source: None, memory_zones, guest_ram_mappings: Vec::new(), @@ -2527,6 +2542,10 @@ impl MemoryManager { )?; if !mem_snapshot.memory_ranges.is_empty() { + if mem_snapshot.diff_count > 0 && memory_restore_mode == MemoryRestoreMode::OnDemand + { + return Err(Error::RestoreDiffWithOnDemand); + } match memory_restore_mode { MemoryRestoreMode::OnDemand => mm.lock().unwrap().restore_by_uffd( &memory_file_path, @@ -2542,6 +2561,17 @@ impl MemoryManager { .unwrap() .fill_saved_regions(memory_file_path, &mem_snapshot.memory_ranges)?, } + if mem_snapshot.diff_count > 0 { + let source_dir = url_to_path(source_url).map_err(Error::Restore)?; + let guest_memory = mm.lock().unwrap().guest_memory.memory(); + for seq in 1..=mem_snapshot.diff_count { + apply_diff_file( + &guest_memory, + &diff_file_path(&source_dir, seq), + &mem_snapshot.memory_ranges, + )?; + } + } } Ok(mm) @@ -3226,9 +3256,24 @@ impl MemoryManager { Some(ranges) } + /// Sets how many diff files the next snapshot's state replays. + pub fn set_snapshot_diff_count(&mut self, count: u32) { + self.diff_count = count; + } + + /// Makes the next send write diff file number `diff_count` holding these ranges. + pub fn set_diff_snapshot_ranges(&mut self, table: MemoryRangeTable) { + self.diff_snapshot_ranges = Some(table); + } + + pub fn diff_snapshot_active(&self) -> bool { + self.diff_snapshot_ranges.is_some() + } + pub fn snapshot_data(&self) -> MemoryManagerSnapshotData { MemoryManagerSnapshotData { memory_ranges: self.snapshot_memory_ranges.clone(), + diff_count: self.diff_count, guest_ram_mappings: self.guest_ram_mappings.clone(), start_of_device_area: self.start_of_device_area.0, boot_ram: self.boot_ram, @@ -3732,6 +3777,8 @@ impl Drop for MemoryManager { #[derive(Clone, Serialize, Deserialize)] pub struct MemoryManagerSnapshotData { memory_ranges: MemoryRangeTable, + #[serde(default)] + diff_count: u32, guest_ram_mappings: Vec, start_of_device_area: u64, boot_ram: u64, @@ -3749,6 +3796,7 @@ impl Snapshottable for MemoryManager { } fn snapshot(&mut self) -> result::Result { + self.diff_snapshot_ranges = None; let memory_ranges = self.memory_range_table(MemoryRangePolicy::SkipPersisted)?; // Store locally this list of ranges as it will be used through the @@ -3777,6 +3825,16 @@ impl Transportable for MemoryManager { return Ok(()); } + if let Some(dirty) = &self.diff_snapshot_ranges { + return write_diff_file( + &self.guest_memory.memory(), + &url_to_path(destination_url)?, + self.diff_count, + &self.snapshot_memory_ranges, + dirty, + ); + } + let mut memory_file_path = url_to_path(destination_url)?; memory_file_path.push(String::from(SNAPSHOT_FILENAME)); @@ -3936,6 +3994,137 @@ impl Migratable for MemoryManager { } } +fn diff_file_path(dir: &Path, seq: u32) -> PathBuf { + dir.join(format!("{SNAPSHOT_FILENAME}.diff.{seq}")) +} + +// Writes the dirty part of `layout` as diff file `seq`, through a temporary +// name so a failed write leaves no partial file under the final name. +fn write_diff_file( + guest_memory: &GuestMemory, + dir: &Path, + seq: u32, + layout: &MemoryRangeTable, + dirty: &MemoryRangeTable, +) -> result::Result<(), MigratableError> { + let mut entries = Vec::new(); + for full in layout.ranges() { + for d in dirty.ranges() { + let start = d.gpa.max(full.gpa); + let end = (d.gpa + d.length).min(full.gpa + full.length); + if start < end { + entries.push(MemoryRange { + gpa: start, + length: end - start, + }); + } + } + } + let mut header = Vec::with_capacity(16 + 16 * entries.len()); + header.extend_from_slice(&DIFF_SNAPSHOT_MAGIC); + header.extend_from_slice(&(entries.len() as u64).to_le_bytes()); + for e in &entries { + header.extend_from_slice(&e.gpa.to_le_bytes()); + header.extend_from_slice(&e.length.to_le_bytes()); + } + + let final_path = diff_file_path(dir, seq); + let tmp_path = dir.join(format!("{SNAPSHOT_FILENAME}.diff.{seq}.tmp")); + let _ = fs::remove_file(&tmp_path); + let send_err = |e: io::Error, what: &str| { + MigratableError::MigrateSend(anyhow!("Error {what} diff snapshot {tmp_path:?}: {e}")) + }; + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .open(&tmp_path) + .map_err(|e| send_err(e, "creating"))?; + file.write_all(&header) + .map_err(|e| send_err(e, "writing"))?; + for e in &entries { + let mut offset = 0; + // Manual partial-write loop preserves the workaround for + // https://github.com/rust-vmm/vm-memory/issues/174 + while offset < e.length { + offset += guest_memory + .write_volatile_to( + GuestAddress(e.gpa + offset), + &mut file, + (e.length - offset) as usize, + ) + .context("Error writing diff snapshot memory") + .map_err(MigratableError::MigrateSend)? as u64; + } + } + file.sync_all().map_err(|e| send_err(e, "syncing"))?; + fs::rename(&tmp_path, &final_path).map_err(|e| send_err(e, "renaming"))?; + Ok(()) +} + +// Replays a diff file over restored RAM after checking that every entry lies +// inside `layout` and that the file holds exactly the bytes its table names. +fn apply_diff_file( + guest_memory: &GuestMemory, + path: &Path, + layout: &MemoryRangeTable, +) -> Result<(), Error> { + let invalid = |why| Error::RestoreDiffInvalid(path.to_path_buf(), why); + let mut file = File::open(path).map_err(Error::SnapshotOpen)?; + let file_len = file.metadata().map_err(Error::SnapshotOpen)?.len(); + let mut head = [[0u8; 8]; 2]; + file.read_exact(head.as_flattened_mut()) + .map_err(|_| invalid("truncated header"))?; + if head[0] != DIFF_SNAPSHOT_MAGIC { + return Err(invalid("bad magic")); + } + let count = u64::from_le_bytes(head[1]); + let table_len = count + .checked_mul(16) + .and_then(|n| n.checked_add(16)) + .filter(|&n| n <= file_len) + .ok_or_else(|| invalid("entry table exceeds the file"))?; + let mut table = vec![0u8; (table_len - 16) as usize]; + file.read_exact(&mut table).map_err(Error::SnapshotRead)?; + let mut entries = Vec::with_capacity(count as usize); + let mut data_len: u64 = 0; + for &[gpa, length] in table.as_chunks::<8>().0.as_chunks::<2>().0 { + let (gpa, length) = (u64::from_le_bytes(gpa), u64::from_le_bytes(length)); + let inside = gpa.checked_add(length).is_some_and(|end| { + layout + .ranges() + .iter() + .any(|r| gpa >= r.gpa && end <= r.gpa + r.length) + }); + if length == 0 || !inside { + return Err(invalid("entry outside the snapshot memory layout")); + } + data_len += length; + entries.push(MemoryRange { gpa, length }); + } + if table_len + data_len != file_len { + return Err(invalid("data size does not match the entry table")); + } + for e in entries { + let mut offset = 0; + while offset < e.length { + let n = guest_memory + .read_volatile_from( + GuestAddress(e.gpa + offset), + &mut file, + (e.length - offset) as usize, + ) + .map_err(Error::SnapshotCopy)?; + if n == 0 { + return Err(Error::SnapshotRead(io::Error::from( + io::ErrorKind::UnexpectedEof, + ))); + } + offset += n as u64; + } + } + Ok(()) +} + // Streams guest memory `[gpa, gpa + length)` into `file` at `file_offset`. fn write_guest_range( guest_memory: &GuestMemory, @@ -4452,4 +4641,111 @@ mod tests { assert_eq!(gm.read_obj::(GuestAddress(0)).unwrap(), 0xcd); } } + + fn two_page_guest(fill: u8) -> (GuestMemory, MemoryRangeTable) { + let page = get_page_size(); + let gm = GuestMemory::from_ranges(&[(GuestAddress(0), (2 * page) as usize)]).unwrap(); + gm.write_slice(&vec![fill; (2 * page) as usize], GuestAddress(0)) + .unwrap(); + let mut layout = MemoryRangeTable::default(); + layout.push(MemoryRange { + gpa: 0, + length: 2 * page, + }); + (gm, layout) + } + + #[test] + fn diff_file_replays_only_its_entries() { + let page = get_page_size(); + let dir = tempfile::tempdir().unwrap(); + let (source, layout) = two_page_guest(0xab); + let mut dirty = MemoryRangeTable::default(); + dirty.push(MemoryRange { + gpa: page, + length: page, + }); + write_diff_file(&source, dir.path(), 1, &layout, &dirty).unwrap(); + assert!(!dir.path().join("memory-ranges.diff.1.tmp").exists()); + + let (target, _) = two_page_guest(0x11); + apply_diff_file(&target, &diff_file_path(dir.path(), 1), &layout).unwrap(); + assert_eq!(target.read_obj::(GuestAddress(page - 1)).unwrap(), 0x11); + assert_eq!(target.read_obj::(GuestAddress(page)).unwrap(), 0xab); + assert_eq!( + target.read_obj::(GuestAddress(2 * page - 1)).unwrap(), + 0xab + ); + } + + #[test] + #[cfg(feature = "kvm")] + fn diff_file_round_trip_passes_the_vmm_seccomp_filter() { + use std::thread; + + use hypervisor::HypervisorType; + use seccompiler::{SeccompAction, apply_filter}; + + use crate::seccomp_filters::{Thread, get_seccomp_filter}; + + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().to_path_buf(); + thread::spawn(move || { + let page = get_page_size(); + let (source, layout) = two_page_guest(0xab); + let mut dirty = MemoryRangeTable::default(); + dirty.push(MemoryRange { + gpa: page, + length: page, + }); + let (target, _) = two_page_guest(0x11); + let filter = get_seccomp_filter( + &SeccompAction::Errno(libc::EPERM as u32), + Thread::Vmm, + Some(HypervisorType::Kvm), + ) + .unwrap(); + if let Err(e) = apply_filter(&filter) { + eprintln!("skipping: seccomp filter not installed: {e}"); + return; + } + + write_diff_file(&source, &path, 1, &layout, &dirty).unwrap(); + apply_diff_file(&target, &diff_file_path(&path, 1), &layout).unwrap(); + assert_eq!(target.read_obj::(GuestAddress(page)).unwrap(), 0xab); + }) + .join() + .unwrap(); + } + + #[test] + fn diff_file_rejects_foreign_or_damaged_files() { + let page = get_page_size(); + let dir = tempfile::tempdir().unwrap(); + let (gm, layout) = two_page_guest(0x11); + let path = dir.path().join("diff"); + let header = |gpa: u64, length: u64| { + let mut bytes = DIFF_SNAPSHOT_MAGIC.to_vec(); + bytes.extend_from_slice(&1u64.to_le_bytes()); + bytes.extend_from_slice(&gpa.to_le_bytes()); + bytes.extend_from_slice(&length.to_le_bytes()); + bytes + }; + let rejects = |bytes: &[u8]| { + fs::write(&path, bytes).unwrap(); + matches!( + apply_diff_file(&gm, &path, &layout), + Err(Error::RestoreDiffInvalid(..)) + ) + }; + + assert!(rejects(&vec![0xab; (2 * page) as usize])); + let mut outside = header(2 * page, page); + outside.extend(vec![0xab; page as usize]); + assert!(rejects(&outside)); + let mut short = header(0, page); + short.extend(vec![0xab; (page / 2) as usize]); + assert!(rejects(&short)); + assert_eq!(gm.read_obj::(GuestAddress(0)).unwrap(), 0x11); + } } diff --git a/vmm/src/seccomp_filters.rs b/vmm/src/seccomp_filters.rs index 3d677dbb56..630eaf0715 100644 --- a/vmm/src/seccomp_filters.rs +++ b/vmm/src/seccomp_filters.rs @@ -832,6 +832,12 @@ fn vmm_thread_rules( (libc::SYS_readlinkat, vec![]), (libc::SYS_recvfrom, vec![]), (libc::SYS_recvmsg, vec![]), + #[cfg(target_arch = "x86_64")] + (libc::SYS_rename, vec![]), + #[cfg(target_arch = "aarch64")] + (libc::SYS_renameat, vec![]), + #[cfg(target_arch = "riscv64")] + (libc::SYS_renameat2, vec![]), (libc::SYS_restart_syscall, vec![]), (libc::SYS_rseq, vec![]), (libc::SYS_rt_sigreturn, vec![]), diff --git a/vmm/src/vm.rs b/vmm/src/vm.rs index f0618eade8..81b5da255b 100644 --- a/vmm/src/vm.rs +++ b/vmm/src/vm.rs @@ -14,11 +14,12 @@ use std::collections::{BTreeMap, BTreeSet, HashMap}; #[cfg(feature = "fw_cfg")] use std::ffi; -use std::fs::{File, OpenOptions}; +use std::fs::{self, File, OpenOptions}; use std::io::{self, Seek, SeekFrom, Write}; use std::ops::Deref; use std::os::unix::net::UnixStream; use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::path::PathBuf; use std::process::exit; use std::sync::{Arc, Mutex}; #[cfg(not(target_arch = "riscv64"))] @@ -2695,6 +2696,20 @@ impl Vm { self.memory_manager.lock().unwrap().memory_range_table(mode) } + pub fn set_snapshot_diff_count(&mut self, count: u32) { + self.memory_manager + .lock() + .unwrap() + .set_snapshot_diff_count(count); + } + + pub fn set_diff_snapshot_ranges(&mut self, table: MemoryRangeTable) { + self.memory_manager + .lock() + .unwrap() + .set_diff_snapshot_ranges(table); + } + pub fn guest_memory(&self) -> GuestMemoryAtomic { self.memory_manager.lock().unwrap().guest_memory() } @@ -3036,66 +3051,88 @@ impl Snapshottable for Vm { } } +// With `replace` the file is synced under a temporary name and the returned +// rename installs it; otherwise the file must not exist yet. +fn store_snapshot_file( + destination_url: &str, + name: &str, + bytes: &[u8], + replace: bool, +) -> result::Result, MigratableError> { + let mut final_path = url_to_path(destination_url)?; + final_path.push(name); + let write_path = if replace { + let tmp = final_path.with_extension("tmp"); + let _ = fs::remove_file(&tmp); + tmp + } else { + final_path.clone() + }; + let mut file = OpenOptions::new() + .read(true) + .write(true) + .create_new(true) + .open(&write_path) + .with_context(|| format!("Error creating snapshot file {write_path:?}")) + .map_err(MigratableError::MigrateSend)?; + file.write_all(bytes) + .with_context(|| format!("Error writing snapshot file {write_path:?}")) + .map_err(MigratableError::MigrateSend)?; + if replace { + file.sync_all() + .with_context(|| format!("Error syncing snapshot file {write_path:?}")) + .map_err(MigratableError::MigrateSend)?; + return Ok(Some((write_path, final_path))); + } + Ok(None) +} + impl Transportable for Vm { fn send( &self, snapshot: &Snapshot, destination_url: &str, ) -> result::Result<(), MigratableError> { - let mut snapshot_config_path = url_to_path(destination_url)?; - snapshot_config_path.push(SNAPSHOT_CONFIG_FILE); + let replace = self.memory_manager.lock().unwrap().diff_snapshot_active(); + let send_memory = || match snapshot.snapshots.get(MEMORY_MANAGER_SNAPSHOT_ID) { + Some(memory_manager_snapshot) => self + .memory_manager + .lock() + .unwrap() + .send(&memory_manager_snapshot.clone(), destination_url), + None => Err(MigratableError::Restore(anyhow!( + "Missing memory manager snapshot" + ))), + }; - // Create the snapshot config file - let mut snapshot_config_file = OpenOptions::new() - .read(true) - .write(true) - .create_new(true) - .open(snapshot_config_path) - .context("Error creating VM config snapshot file") - .map_err(MigratableError::MigrateSend)?; + // a diff file lands before the state that counts it + if replace { + send_memory()?; + } - // Serialize and write the snapshot config let vm_config = serde_json::to_string(self.config.lock().unwrap().deref()) .context("Error serializing VM config snapshot") .map_err(MigratableError::MigrateSend)?; + let config_rename = store_snapshot_file( + destination_url, + SNAPSHOT_CONFIG_FILE, + vm_config.as_bytes(), + replace, + )?; - snapshot_config_file - .write_all(vm_config.as_bytes()) - .context("Error writing VM config snapshot") - .map_err(MigratableError::MigrateSend)?; - - let mut snapshot_state_path = url_to_path(destination_url)?; - snapshot_state_path.push(SNAPSHOT_STATE_FILE); - - // Create the snapshot state file - let mut snapshot_state_file = OpenOptions::new() - .read(true) - .write(true) - .create_new(true) - .open(snapshot_state_path) - .context("Error creating VM state snapshot file") - .map_err(MigratableError::MigrateSend)?; - - // Serialize and write the snapshot state let vm_state = serde_json::to_vec(snapshot) .context("Error serializing VM state snapshot") .map_err(MigratableError::MigrateSend)?; + let state_rename = + store_snapshot_file(destination_url, SNAPSHOT_STATE_FILE, &vm_state, replace)?; + for (from, to) in config_rename.into_iter().chain(state_rename) { + fs::rename(&from, &to) + .with_context(|| format!("Error renaming {from:?} to {to:?}")) + .map_err(MigratableError::MigrateSend)?; + } - snapshot_state_file - .write_all(&vm_state) - .context("Error writing VM state snapshot") - .map_err(MigratableError::MigrateSend)?; - - // Tell the memory manager to also send/write its own snapshot. - if let Some(memory_manager_snapshot) = snapshot.snapshots.get(MEMORY_MANAGER_SNAPSHOT_ID) { - self.memory_manager - .lock() - .unwrap() - .send(&memory_manager_snapshot.clone(), destination_url)?; - } else { - return Err(MigratableError::Restore(anyhow!( - "Missing memory manager snapshot" - ))); + if !replace { + send_memory()?; } Ok(()) From eabb2006514440f61d945c47e227e2d741ac0ab6 Mon Sep 17 00:00:00 2001 From: doge Date: Wed, 30 Sep 2026 17:00:48 +0800 Subject: [PATCH 03/11] block: Reissue io_uring requests that complete with -EAGAIN io_uring can complete an O_DIRECT read with -EAGAIN on kernels without commit b08e02045002 ("io_uring/rw: don't gate retry on completion context"), which was merged for Linux 6.14. This happens on XFS for a read that spans several extents when a concurrent allocating write holds the inode lock: the bios for the first extents are already in flight when mapping a later extent fails with -EAGAIN, iomap completes the request from a workqueue, and io_uring does not retry it outside the submitting task. virtio-blk then reports VIRTIO_BLK_S_IOERR to the guest for data that is intact. Reissue a read or write that completes with -EAGAIN or -EINTR once, with IOSQE_ASYNC so that io-wq runs it in blocking mode, where it cannot fail this way again. QEMU resubmits both errors as well. Signed-off-by: doge --- block/src/io/async_io/uring_data_io.rs | 112 +++++++++++++++++++++++-- 1 file changed, 103 insertions(+), 9 deletions(-) diff --git a/block/src/io/async_io/uring_data_io.rs b/block/src/io/async_io/uring_data_io.rs index 346440c614..431e281652 100644 --- a/block/src/io/async_io/uring_data_io.rs +++ b/block/src/io/async_io/uring_data_io.rs @@ -10,7 +10,7 @@ use std::{io, mem}; use io_uring::register::Restriction; use io_uring::{IoUring, opcode, squeue, types}; -use log::{error, warn}; +use log::{debug, error, warn}; use vmm_sys_util::eventfd::EventFd; use super::common::{duplicate_user_data_error, validate_batch}; @@ -28,6 +28,11 @@ pub struct UringDataIo { // data operations store `Some(op)` so their iovecs and backing buffers // remain valid until completion; metadata operations store `None`. in_flight: HashMap>, + // `reissue_fds` holds the file descriptor of each owned data operation + // that has not been reissued. + reissue_fds: HashMap, + // `rw_flags` holds the RWF_* flags of read and write SQEs, set by tests. + rw_flags: i32, completions: CompletionCommon, // `needs_submit_retry` is set when SQEs have been published to the ring, // but the submit syscall failed before confirming kernel ownership. @@ -49,13 +54,15 @@ impl UringDataIo { Restriction::sqe_op(opcode::Readv::CODE), Restriction::sqe_op(opcode::Writev::CODE), Restriction::sqe_op(opcode::Fsync::CODE), - Restriction::sqe_flags_allowed(0), + Restriction::sqe_flags_allowed(squeue::Flags::ASYNC.bits()), ])?; io_uring.submitter().register_enable_rings()?; Ok(Self { io_uring, in_flight: HashMap::new(), + reissue_fds: HashMap::new(), + rw_flags: 0, completions, needs_submit_retry: false, }) @@ -133,13 +140,15 @@ impl UringDataIo { let mut batch = batch.into_iter(); while let Some(op) = batch.next() { let user_data = op.user_data(); - let entry = Self::build_entry(fd, &op); + let entry = Self::build_entry(fd, &op, self.rw_flags); self.in_flight.insert(user_data, Some(op)); + self.reissue_fds.insert(user_data, fd); // SAFETY: the SQ capacity was just checked. Every iovec's pointer is retained in // self.in_flight before the SQ tail is advanced by sync or drop. in_flight only // drops the memory after a completion. if let Err(e) = unsafe { sq.push(&entry) } { + self.reissue_fds.remove(&user_data); Self::handle_push_failure( &mut self.in_flight, &mut self.completions, @@ -190,17 +199,19 @@ impl UringDataIo { warn!("io_uring submission queue became full after capacity check: {error:?}"); } - fn build_entry(fd: RawFd, op: &AsyncIoOperation) -> squeue::Entry { + fn build_entry(fd: RawFd, op: &AsyncIoOperation, rw_flags: i32) -> squeue::Entry { let iovecs = op.iovecs(); let fd = types::Fd(fd); if op.is_read() { opcode::Readv::new(fd, iovecs.as_ptr(), iovecs.len() as u32) .offset(op.offset() as u64) + .rw_flags(rw_flags) .build() .user_data(op.user_data()) } else { opcode::Writev::new(fd, iovecs.as_ptr(), iovecs.len() as u32) .offset(op.offset() as u64) + .rw_flags(rw_flags) .build() .user_data(op.user_data()) } @@ -232,7 +243,8 @@ impl UringDataIo { /// Returns the next kernel or injected completion if one is available. /// /// Consuming a kernel completion returns ownership of any buffer retained - /// by the corresponding operation. + /// by the corresponding operation. A read or write that completes with + /// `-EAGAIN` or `-EINTR` is reissued once instead of being returned. pub fn next_completion(&mut self) -> Option { if self.needs_submit_retry { match self.io_uring.submitter().submit() { @@ -241,11 +253,39 @@ impl UringDataIo { } } - if let Some(entry) = self.io_uring.completion().next() { - let user_data = entry.user_data(); + loop { + let Some(cqe) = self.io_uring.completion().next() else { + break; + }; + let user_data = cqe.user_data(); + let result = cqe.result(); + let reissue_fd = self.reissue_fds.remove(&user_data); + if (result == -libc::EAGAIN || result == -libc::EINTR) + && let Some(fd) = reissue_fd + && let Some(Some(op)) = self.in_flight.get(&user_data) + { + // IOSQE_ASYNC makes io-wq run the request in blocking mode. + let entry = Self::build_entry(fd, op, self.rw_flags).flags(squeue::Flags::ASYNC); + let (submitter, mut sq, _) = self.io_uring.split(); + // SAFETY: the operation and its iovecs stay in self.in_flight + // until its final completion is consumed. + if unsafe { sq.push(&entry) }.is_ok() { + sq.sync(); + if let Err(e) = submitter.submit() { + self.needs_submit_retry = true; + warn!("io_uring submit failed after SQE was reissued: {e}"); + self.completions.notifier().write(1).unwrap(); + } + debug!( + "Reissued io_uring request {user_data:#x} after {}", + io::Error::from_raw_os_error(-result) + ); + continue; + } + } return Some(AsyncIoCompletion::new( user_data, - entry.result(), + result, self.in_flight .remove(&user_data) .flatten() @@ -307,6 +347,7 @@ impl Drop for UringDataIo { #[cfg(test)] mod tests { + use std::io::Write; use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; use std::thread::sleep; use std::time::Duration; @@ -355,7 +396,7 @@ mod tests { let mut data_io = UringDataIo::new(8).unwrap(); let nop = opcode::Nop::new() .build() - .flags(squeue::Flags::ASYNC) + .flags(squeue::Flags::IO_LINK) .user_data(1); data_io.submit_kernel_entry(1, &nop).unwrap(); assert_eq!(wait_for_completion(&mut data_io).result, -libc::EACCES); @@ -456,4 +497,57 @@ mod tests { completed.sort_unstable(); assert_eq!(completed, (0..batch_len as u64).collect::>()); } + + #[test] + fn uring_reissues_operation_after_eagain() { + let (reader, mut writer) = io::pipe().unwrap(); + let mut data_io = UringDataIo::new(8).unwrap(); + // RWF_NOWAIT makes a read of an empty pipe complete with -EAGAIN. + data_io.rw_flags = libc::RWF_NOWAIT; + + data_io + .submit_operation( + reader.as_raw_fd(), + AsyncIoOperation::read_to_vec(0, OwnedIoBuffer::from_vec(vec![0; 4]), 9), + ) + .unwrap(); + // Written after the first attempt, so only the reissue can read it. + writer.write_all(b"data").unwrap(); + + let completion = wait_for_completion(&mut data_io); + if completion.result == -libc::EOPNOTSUPP { + eprintln!("skipping: RWF_NOWAIT not supported on pipes"); + return; + } + assert_eq!(completion.user_data, 9); + assert_eq!(completion.result, 4); + assert_eq!(completion.buffer.unwrap().as_slice(), b"data"); + assert!(data_io.in_flight.is_empty()); + assert!(data_io.reissue_fds.is_empty()); + } + + #[test] + fn uring_delivers_eagain_after_reissue() { + let (reader, _writer) = io::pipe().unwrap(); + let mut data_io = UringDataIo::new(8).unwrap(); + data_io.rw_flags = libc::RWF_NOWAIT; + + data_io + .submit_operation( + reader.as_raw_fd(), + AsyncIoOperation::read_to_vec(0, OwnedIoBuffer::from_vec(vec![0; 4]), 3), + ) + .unwrap(); + + let completion = wait_for_completion(&mut data_io); + if completion.result == -libc::EOPNOTSUPP { + eprintln!("skipping: RWF_NOWAIT not supported on pipes"); + return; + } + assert_eq!(completion.user_data, 3); + assert_eq!(completion.result, -libc::EAGAIN); + assert!(completion.buffer.is_some()); + assert!(data_io.in_flight.is_empty()); + assert!(data_io.reissue_fds.is_empty()); + } } From 4162e72ec883bd4c896cc9b7ecf0984d05c52ea3 Mon Sep 17 00:00:00 2001 From: CMGS Date: Wed, 4 Nov 2026 11:30:53 +0800 Subject: [PATCH 04/11] vmm: refuse diff snapshots that cannot see device writes Ejecting a vhost-user device during a diff series drops its log with the pages not yet harvested. The next diff succeeds and a restore returns stale guest memory. End the series on a removal request, and fail the next diff after any eject during dirty logging, because the guest can eject a device on its own and later than the request. vDPA and vfio-user devices track no dirty pages, and the DMA log of a VFIO device behind a virtual IOMMU has no translation to guest addresses. Fail a diff request while one of them is present. A kernel VFIO device added during a series is not logged at all, so adding one ends the series too. None of this changes full snapshots or live migration. Stop the dirty log and run the diff check without holding the device tree lock while locking devices. A vCPU moving a BAR takes these locks in the other order, and these paths now run on a running VM. --- docs/snapshot_restore.md | 14 +++++++++++--- pci/src/vfio.rs | 10 ++++++++++ pci/src/vfio_user.rs | 10 +++++++++- virtio-devices/src/vdpa.rs | 7 +++++++ vm-migration/src/lib.rs | 4 ++++ vmm/src/device_manager.rs | 39 ++++++++++++++++++++++++++++++++++---- vmm/src/lib.rs | 12 ++++++++++++ vmm/src/vm.rs | 4 ++++ 8 files changed, 92 insertions(+), 8 deletions(-) diff --git a/docs/snapshot_restore.md b/docs/snapshot_restore.md index 0930e7db95..78569342f7 100644 --- a/docs/snapshot_restore.md +++ b/docs/snapshot_restore.md @@ -67,9 +67,17 @@ the pages dirtied since the previous snapshot of the series. The first `diff` request takes a full baseline and enables dirty-page tracking; each subsequent one dumps the delta, so the pause cost is proportional to the amount of dirtied memory rather than to the guest RAM size. A `full` request (or any snapshot -failure, a memory layout change, a migration, a reboot, a shutdown, or -deleting the VM) ends the series; the next `diff` starts a new one with a -fresh baseline in a fresh directory. +failure, a memory layout change, a migration, a reboot, a shutdown, removing a +device, hot-adding a VFIO device, or deleting the VM) ends the series; the next +`diff` starts a new one with a fresh baseline in a fresh directory. A `diff` to +another directory fails and keeps the series. + +The first `diff` after a guest ejects a device fails and ends the series, and so +does the first `diff` after a vhost-user device is hot-added. + +A `diff` request fails when the VM has a device whose guest memory writes cannot +be tracked: a vDPA device, a vfio-user device, or a VFIO device behind a virtual +IOMMU. The whole series lives in one directory, and every `diff` request of a series must target that same directory: diff --git a/pci/src/vfio.rs b/pci/src/vfio.rs index 7ba415b0ce..d1cb1f63c4 100644 --- a/pci/src/vfio.rs +++ b/pci/src/vfio.rs @@ -3079,6 +3079,16 @@ impl Snapshottable for VfioPciDevice { impl Transportable for VfioPciDevice {} impl Migratable for VfioPciDevice { + fn check_diff_snapshot(&self) -> result::Result<(), MigratableError> { + if self.iommu_attached { + return Err(MigratableError::Snapshot(anyhow!( + "VFIO device {} behind a virtual IOMMU does not support dirty tracking", + self.id + ))); + } + Ok(()) + } + fn notify_started_migration(&mut self) -> result::Result<(), MigratableError> { // Reject a device that does not implement migration v2 up front, // rather than silently skipping its state and dirty tracking. diff --git a/pci/src/vfio_user.rs b/pci/src/vfio_user.rs index bb862c65d8..eaa1aebec0 100644 --- a/pci/src/vfio_user.rs +++ b/pci/src/vfio_user.rs @@ -8,6 +8,7 @@ use std::os::unix::prelude::AsRawFd; use std::sync::{Arc, Barrier, Mutex}; use std::{io, result}; +use anyhow::anyhow; use log::{error, info}; use thiserror::Error; use vfio_bindings::bindings::vfio::*; @@ -442,7 +443,14 @@ impl Snapshottable for VfioUserPciDevice { } } impl Transportable for VfioUserPciDevice {} -impl Migratable for VfioUserPciDevice {} +impl Migratable for VfioUserPciDevice { + fn check_diff_snapshot(&self) -> result::Result<(), MigratableError> { + Err(MigratableError::Snapshot(anyhow!( + "vfio-user device {} does not track dirty pages", + self.id + ))) + } +} pub struct VfioUserDmaMapping { client: Arc>, diff --git a/virtio-devices/src/vdpa.rs b/virtio-devices/src/vdpa.rs index d61ba0ef30..2273c203e7 100644 --- a/virtio-devices/src/vdpa.rs +++ b/virtio-devices/src/vdpa.rs @@ -533,6 +533,13 @@ impl Snapshottable for Vdpa { impl Transportable for Vdpa {} impl Migratable for Vdpa { + fn check_diff_snapshot(&self) -> result::Result<(), MigratableError> { + Err(MigratableError::Snapshot(anyhow!( + "vDPA device {} does not track dirty pages", + self.id + ))) + } + fn notify_started_migration(&mut self) -> result::Result<(), MigratableError> { if self.backend_features & (1 << VHOST_BACKEND_F_RESUME) == 0 { warn!( diff --git a/vm-migration/src/lib.rs b/vm-migration/src/lib.rs index ea9c9b47e5..9eef6cb8d8 100644 --- a/vm-migration/src/lib.rs +++ b/vm-migration/src/lib.rs @@ -302,6 +302,10 @@ pub trait Migratable: Send + Pausable + Snapshottable + Transportable { Ok(MemoryRangeTable::default()) } + fn check_diff_snapshot(&self) -> result::Result<(), MigratableError> { + Ok(()) + } + fn notify_started_migration(&mut self) -> result::Result<(), MigratableError> { Ok(()) } diff --git a/vmm/src/device_manager.rs b/vmm/src/device_manager.rs index 126f3b454b..1ef39aed8d 100644 --- a/vmm/src/device_manager.rs +++ b/vmm/src/device_manager.rs @@ -35,6 +35,7 @@ use std::{iter, path, result, sync}; use acpi_tables::sdt::GenericAddress; use acpi_tables::{Aml, aml}; +use anyhow::anyhow; #[cfg(target_arch = "x86_64")] use arch::layout::{APIC_START, IOAPIC_SIZE, IOAPIC_START}; #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))] @@ -1060,6 +1061,9 @@ pub struct DeviceManager { // information for filling the ACPI VIOT table. iommu_attached_devices: Option<(PciBdf, Vec)>, + dirty_logging: bool, + ejected_while_dirty_logging: bool, + // Emulated SMMUv3s, keyed by the physical SMMUv3 they sit on top of, as // one is created per physical SMMUv3. #[cfg(target_arch = "aarch64")] @@ -1446,6 +1450,8 @@ impl DeviceManager { iommu_device: None, iommu_mapping: None, iommu_attached_devices: None, + dirty_logging: false, + ejected_while_dirty_logging: false, #[cfg(target_arch = "aarch64")] smmuv3s: BTreeMap::new(), pci_segments: pci_segments.into_boxed_slice(), @@ -5629,6 +5635,15 @@ impl DeviceManager { Ok(()) } + fn migratable_devices(&self) -> Vec>> { + self.device_tree + .lock() + .unwrap() + .iter() + .filter_map(|(_, node)| node.migratable.clone()) + .collect() + } + pub fn eject_device(&mut self, pci_segment_id: u16, device_id: u8) -> DeviceManagerResult<()> { info!("Ejecting device_id = {device_id} on segment_id={pci_segment_id}"); @@ -5644,6 +5659,8 @@ impl DeviceManager { return Err(DeviceManagerError::InvalidIommuRemove(pci_device_bdf)); } + self.ejected_while_dirty_logging |= self.dirty_logging; + let (pci_device_handle, id, pci_bar_resources) = { // Clone the node so a failed bus removal leaves it in the device tree. let device_tree = self.device_tree.lock().unwrap(); @@ -6567,7 +6584,21 @@ impl Snapshottable for DeviceManager { impl Transportable for DeviceManager {} impl Migratable for DeviceManager { + fn check_diff_snapshot(&self) -> result::Result<(), MigratableError> { + if self.ejected_while_dirty_logging { + return Err(MigratableError::Snapshot(anyhow!( + "a device was ejected during the snapshot series" + ))); + } + for migratable in self.migratable_devices() { + migratable.lock().unwrap().check_diff_snapshot()?; + } + Ok(()) + } + fn start_dirty_log(&mut self) -> result::Result<(), MigratableError> { + self.dirty_logging = true; + self.ejected_while_dirty_logging = false; for (_, device_node) in self.device_tree.lock().unwrap().iter() { if let Some(migratable) = &device_node.migratable { migratable.lock().unwrap().start_dirty_log()?; @@ -6577,10 +6608,10 @@ impl Migratable for DeviceManager { } fn stop_dirty_log(&mut self) -> result::Result<(), MigratableError> { - for (_, device_node) in self.device_tree.lock().unwrap().iter() { - if let Some(migratable) = &device_node.migratable { - migratable.lock().unwrap().stop_dirty_log()?; - } + self.dirty_logging = false; + self.ejected_while_dirty_logging = false; + for migratable in self.migratable_devices() { + migratable.lock().unwrap().stop_dirty_log()?; } Ok(()) } diff --git a/vmm/src/lib.rs b/vmm/src/lib.rs index c2665f30e6..3a2c7e583b 100644 --- a/vmm/src/lib.rs +++ b/vmm/src/lib.rs @@ -2603,6 +2603,12 @@ impl RequestHandler for Vmm { // the first diff of a series is a full baseline let effective_diff = requested_diff && self.snapshot_series.is_some(); if requested_diff { + if let Err(e) = vm.check_diff_snapshot() { + if self.snapshot_series.take().is_some() { + let _ = vm.stop_dirty_log(); + } + return Err(VmError::Snapshot(e)); + } let layout = vm .memory_range_table(MemoryRangePolicy::SkipPersisted) .map_err(VmError::Snapshot)?; @@ -3060,6 +3066,9 @@ impl RequestHandler for Vmm { let info = vm.add_device(device_cfg).inspect_err(|e| { error!("Error when adding new device to the VM: {e:?}"); })?; + if self.snapshot_series.take().is_some() { + let _ = vm.stop_dirty_log(); + } serde_json::to_vec(&info) .map(Some) .map_err(VmError::SerializeJson) @@ -3111,6 +3120,9 @@ impl RequestHandler for Vmm { VmOwnership::Owned(ref mut vm) => { vm.remove_device(&id) .inspect_err(|e| error!("Error when removing device from the VM: {e:?}"))?; + if self.snapshot_series.take().is_some() { + let _ = vm.stop_dirty_log(); + } Ok(()) } VmOwnership::Migration { .. } => Err(VmError::VmMigrating), diff --git a/vmm/src/vm.rs b/vmm/src/vm.rs index 81b5da255b..c332038610 100644 --- a/vmm/src/vm.rs +++ b/vmm/src/vm.rs @@ -3140,6 +3140,10 @@ impl Transportable for Vm { } impl Migratable for Vm { + fn check_diff_snapshot(&self) -> result::Result<(), MigratableError> { + self.device_manager.lock().unwrap().check_diff_snapshot() + } + fn start_dirty_log(&mut self) -> result::Result<(), MigratableError> { self.memory_manager.lock().unwrap().start_dirty_log()?; self.device_manager.lock().unwrap().start_dirty_log() From 2f707534d4e0ac118004ce66170a19e5b52cb57a Mon Sep 17 00:00:00 2001 From: CMGS Date: Wed, 4 Nov 2026 11:38:00 +0800 Subject: [PATCH 05/11] vmm: add vm.end-snapshot-series A caller that gives up on a diff series, such as an aborted migration attempt, has no way to end it without a side effect. The series stays active, dirty logging stays on and every diff to a new directory fails. PUT /vm.end-snapshot-series ends the series and stops dirty logging. It returns 204 also when no series is active, so a caller can run it at the start of every attempt. --- cloud-hypervisor/src/bin/ch-remote.rs | 12 +++++++ docs/snapshot_restore.md | 4 +++ fuzz/fuzz_targets/http_api.rs | 4 +++ vmm/src/api/dbus/mod.rs | 11 +++++-- vmm/src/api/http/http_endpoint.rs | 7 ++-- vmm/src/api/http/mod.rs | 10 ++++-- vmm/src/api/mod.rs | 39 +++++++++++++++++++++++ vmm/src/api/openapi/cloud-hypervisor.yaml | 10 ++++++ vmm/src/lib.rs | 10 ++++++ 9 files changed, 98 insertions(+), 9 deletions(-) diff --git a/cloud-hypervisor/src/bin/ch-remote.rs b/cloud-hypervisor/src/bin/ch-remote.rs index 4abb99539e..2dc96c4a11 100644 --- a/cloud-hypervisor/src/bin/ch-remote.rs +++ b/cloud-hypervisor/src/bin/ch-remote.rs @@ -102,6 +102,7 @@ trait DBusApi1 { fn vm_create(&self, vm_config: &str) -> zbus::Result<()>; fn vm_delete(&self) -> zbus::Result<()>; fn vm_info(&self) -> zbus::Result; + fn vm_end_snapshot_series(&self) -> zbus::Result<()>; fn vm_pause(&self) -> zbus::Result<()>; fn vm_nmi(&self) -> zbus::Result<()>; fn vm_power_button(&self) -> zbus::Result<()>; @@ -223,6 +224,10 @@ impl<'a> DBusApi1ProxyBlocking<'a> { .map_err(Error::DBusApiClient) } + fn api_vm_end_snapshot_series(&self) -> ApiResult { + self.vm_end_snapshot_series().map_err(Error::DBusApiClient) + } + fn api_vm_pause(&self) -> ApiResult { self.vm_pause().map_err(Error::DBusApiClient) } @@ -342,6 +347,10 @@ fn rest_api_do_command( Command::Reboot => { simple_api_command(socket, "PUT", "reboot", None).map_err(Error::HttpApiClient) } + Command::EndSnapshotSeries => { + simple_api_command(socket, "PUT", "end-snapshot-series", None) + .map_err(Error::HttpApiClient) + } Command::Pause => { simple_api_command(socket, "PUT", "pause", None).map_err(Error::HttpApiClient) } @@ -523,6 +532,7 @@ fn dbus_api_do_command( Command::Resume => proxy.api_vm_resume(), Command::PowerButton => proxy.api_vm_power_button(), Command::Reboot => proxy.api_vm_reboot(), + Command::EndSnapshotSeries => proxy.api_vm_end_snapshot_series(), Command::Pause => proxy.api_vm_pause(), Command::Info => proxy.api_vm_info(), Command::BalloonStats => proxy.api_vm_balloon_stats(), @@ -938,6 +948,8 @@ enum Command { }, #[command(about = "Delete a VM")] Delete, + #[command(about = "End the active diff snapshot series")] + EndSnapshotSeries, #[command(about = "Info on the VM")] Info, #[command(about = "Trigger NMI")] diff --git a/docs/snapshot_restore.md b/docs/snapshot_restore.md index 78569342f7..415206a4b9 100644 --- a/docs/snapshot_restore.md +++ b/docs/snapshot_restore.md @@ -75,6 +75,10 @@ another directory fails and keeps the series. The first `diff` after a guest ejects a device fails and ends the series, and so does the first `diff` after a vhost-user device is hot-added. +`PUT /vm.end-snapshot-series` (`ch-remote end-snapshot-series`) ends a series +without taking a snapshot and stops dirty-page tracking. It succeeds when no +series is active. + A `diff` request fails when the VM has a device whose guest memory writes cannot be tracked: a vDPA device, a vfio-user device, or a VFIO device behind a virtual IOMMU. diff --git a/fuzz/fuzz_targets/http_api.rs b/fuzz/fuzz_targets/http_api.rs index 6a7ebe8bf8..73da7d65ff 100644 --- a/fuzz/fuzz_targets/http_api.rs +++ b/fuzz/fuzz_targets/http_api.rs @@ -97,6 +97,10 @@ impl RequestHandler for StubApiRequestHandler { Ok(()) } + fn vm_end_snapshot_series(&mut self) -> Result<(), VmError> { + Ok(()) + } + fn vm_pause(&mut self) -> Result<(), VmError> { Ok(()) } diff --git a/vmm/src/api/dbus/mod.rs b/vmm/src/api/dbus/mod.rs index 7c70709f1b..7e97046aad 100644 --- a/vmm/src/api/dbus/mod.rs +++ b/vmm/src/api/dbus/mod.rs @@ -23,9 +23,10 @@ use crate::api::VmCoredump; use crate::api::{ AddDisk, Body, VmAddDevice, VmAddFs, VmAddGenericVhostUser, VmAddNet, VmAddPmem, VmAddUserDevice, VmAddVdpa, VmAddVsock, VmBalloonStats, VmBoot, VmCancelMigration, VmCounters, - VmCreate, VmDelete, VmInfo, VmNmi, VmPause, VmPowerButton, VmReboot, VmReceiveMigration, - VmReceiveMigrationData, VmRemoveDevice, VmResize, VmResizeDisk, VmResizeZone, VmRestore, - VmResume, VmSendMigration, VmShutdown, VmSnapshot, VmmPing, VmmShutdown, + VmCreate, VmDelete, VmEndSnapshotSeries, VmInfo, VmNmi, VmPause, VmPowerButton, VmReboot, + VmReceiveMigration, VmReceiveMigrationData, VmRemoveDevice, VmResize, VmResizeDisk, + VmResizeZone, VmRestore, VmResume, VmSendMigration, VmShutdown, VmSnapshot, VmmPing, + VmmShutdown, }; use crate::config::RestoreConfig; use crate::external_fds::{ExternalFds, ScmRights, UpdateFdsComponent}; @@ -247,6 +248,10 @@ impl DBusApi { serde_json::to_string(&result).map_err(api_error) } + async fn vm_end_snapshot_series(&self) -> Result<()> { + self.vm_action(&VmEndSnapshotSeries, ()).await.map(|_| ()) + } + async fn vm_pause(&self) -> Result<()> { self.vm_action(&VmPause, ()).await.map(|_| ()) } diff --git a/vmm/src/api/http/http_endpoint.rs b/vmm/src/api/http/http_endpoint.rs index 14bca3dcfe..4f8bdef323 100644 --- a/vmm/src/api/http/http_endpoint.rs +++ b/vmm/src/api/http/http_endpoint.rs @@ -48,9 +48,9 @@ use crate::api::http::{EndpointHandler, HttpError, error_response}; use crate::api::{ AddDisk, ApiAction, ApiError, ApiRequest, DeviceConfig, NetConfig, VmAddDevice, VmAddFs, VmAddGenericVhostUser, VmAddNet, VmAddPmem, VmAddUserDevice, VmAddVdpa, VmAddVsock, VmBoot, - VmCancelMigration, VmConfig, VmCounters, VmDelete, VmNmi, VmPause, VmPowerButton, VmReboot, - VmReceiveMigration, VmReceiveMigrationData, VmRemoveDevice, VmResize, VmResizeDisk, - VmResizeZone, VmRestore, VmResume, VmSendMigration, VmShutdown, VmSnapshot, + VmCancelMigration, VmConfig, VmCounters, VmDelete, VmEndSnapshotSeries, VmNmi, VmPause, + VmPowerButton, VmReboot, VmReceiveMigration, VmReceiveMigrationData, VmRemoveDevice, VmResize, + VmResizeDisk, VmResizeZone, VmRestore, VmResume, VmSendMigration, VmShutdown, VmSnapshot, }; use crate::config::RestoreConfig; use crate::cpu::Error as CpuError; @@ -200,6 +200,7 @@ vm_action_put_handler!(VmBoot); vm_action_put_handler!(VmDelete); vm_action_put_handler!(VmShutdown); vm_action_put_handler!(VmReboot); +vm_action_put_handler!(VmEndSnapshotSeries); vm_action_put_handler!(VmPause); vm_action_put_handler!(VmResume); vm_action_put_handler!(VmPowerButton); diff --git a/vmm/src/api/http/mod.rs b/vmm/src/api/http/mod.rs index fe9724aecf..900c772564 100644 --- a/vmm/src/api/http/mod.rs +++ b/vmm/src/api/http/mod.rs @@ -31,9 +31,9 @@ use crate::api::VmCoredump; use crate::api::{ AddDisk, ApiError, ApiRequest, VmAddDevice, VmAddFs, VmAddGenericVhostUser, VmAddNet, VmAddPmem, VmAddUserDevice, VmAddVdpa, VmAddVsock, VmBoot, VmCancelMigration, VmCounters, - VmDelete, VmNmi, VmPause, VmPowerButton, VmReboot, VmReceiveMigration, VmRemoveDevice, - VmResize, VmResizeDisk, VmResizeZone, VmRestore, VmResume, VmSendMigration, VmShutdown, - VmSnapshot, + VmDelete, VmEndSnapshotSeries, VmNmi, VmPause, VmPowerButton, VmReboot, VmReceiveMigration, + VmRemoveDevice, VmResize, VmResizeDisk, VmResizeZone, VmRestore, VmResume, VmSendMigration, + VmShutdown, VmSnapshot, }; use crate::config::ValidationError; use crate::device_manager::DeviceManagerError; @@ -294,6 +294,10 @@ pub static HTTP_ROUTES: LazyLock = LazyLock::new(|| { Box::new(VmActionHandler::new(&VmDelete)), ); r.routes.insert(endpoint!("/vm.info"), Box::new(VmInfo {})); + r.routes.insert( + endpoint!("/vm.end-snapshot-series"), + Box::new(VmActionHandler::new(&VmEndSnapshotSeries)), + ); r.routes.insert( endpoint!("/vm.pause"), Box::new(VmActionHandler::new(&VmPause)), diff --git a/vmm/src/api/mod.rs b/vmm/src/api/mod.rs index 71c3619327..838f6b36ef 100644 --- a/vmm/src/api/mod.rs +++ b/vmm/src/api/mod.rs @@ -113,6 +113,10 @@ pub enum ApiError { #[error("The VM could not be paused")] VmPause(#[source] VmError), + /// The snapshot series could not end + #[error("The snapshot series could not end")] + VmEndSnapshotSeries(#[source] VmError), + /// The VM could not resume. #[error("The VM could not resume")] VmResume(#[source] VmError), @@ -892,6 +896,8 @@ pub trait RequestHandler { fn vm_snapshot(&mut self, config: &VmSnapshotConfig) -> Result<(), VmError>; + fn vm_end_snapshot_series(&mut self) -> Result<(), VmError>; + fn vm_restore(&mut self, restore_cfg: RestoreConfig) -> Result<(), VmError>; #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] @@ -1615,6 +1621,39 @@ impl ApiAction for VmInfo { } } +pub struct VmEndSnapshotSeries; + +impl ApiAction for VmEndSnapshotSeries { + type RequestBody = (); + type ResponseBody = Option; + + fn request(&self, _: Self::RequestBody, response_sender: Sender) -> ApiRequest { + Box::new(move |vmm| { + info!("API request event: VmEndSnapshotSeries"); + + let response = vmm + .vm_end_snapshot_series() + .map_err(ApiError::VmEndSnapshotSeries) + .map(|_| ApiResponsePayload::Empty); + + response_sender + .send(response) + .map_err(VmmError::ApiResponseSend)?; + + Ok(false) + }) + } + + fn send( + &self, + api_evt: EventFd, + api_sender: Sender, + data: Self::RequestBody, + ) -> ApiResult { + get_response_body(self, api_evt, api_sender, data) + } +} + pub struct VmPause; impl ApiAction for VmPause { diff --git a/vmm/src/api/openapi/cloud-hypervisor.yaml b/vmm/src/api/openapi/cloud-hypervisor.yaml index 12256fa0cd..eee8d12bfb 100644 --- a/vmm/src/api/openapi/cloud-hypervisor.yaml +++ b/vmm/src/api/openapi/cloud-hypervisor.yaml @@ -126,6 +126,16 @@ paths: 409: description: The operation conflicts with the current state of the VM. + /vm.end-snapshot-series: + put: + summary: End the active diff snapshot series and stop dirty page tracking. + operationId: vmEndSnapshotSeries + responses: + 204: + description: No series is active any more. This also holds when none was active. + 500: + description: Dirty page tracking could not stop. The series is over regardless. + /vm.resume: put: summary: Resume a previously paused VM instance. diff --git a/vmm/src/lib.rs b/vmm/src/lib.rs index 3a2c7e583b..67a389a2ac 100644 --- a/vmm/src/lib.rs +++ b/vmm/src/lib.rs @@ -2676,6 +2676,15 @@ impl RequestHandler for Vmm { } } + fn vm_end_snapshot_series(&mut self) -> result::Result<(), VmError> { + if self.snapshot_series.take().is_some() + && let VmOwnership::Owned(ref mut vm) = self.vm + { + vm.stop_dirty_log().map_err(VmError::Snapshot)?; + } + Ok(()) + } + fn vm_restore(&mut self, mut restore_cfg: RestoreConfig) -> result::Result<(), VmError> { match &self.vm { VmOwnership::Owned(_) => Err(VmError::VmAlreadyCreated), @@ -3853,6 +3862,7 @@ pub(crate) mod tests { let mut vmm = create_dummy_vmm(); assert!(matches!(vmm.vm_pause(), Err(VmError::VmNotCreated))); + vmm.vm_end_snapshot_series().unwrap(); assert!(matches!(vmm.vm_resume(), Err(VmError::VmNotCreated))); assert!(matches!(vmm.vm_power_button(), Err(VmError::VmNotCreated))); assert!(matches!(vmm.vm_shutdown(), Err(VmError::VmNotCreated))); From 9dbb844b11e54532da93e2a67179c081adde2b97 Mon Sep 17 00:00:00 2001 From: CMGS Date: Fri, 6 Nov 2026 20:23:09 +0800 Subject: [PATCH 06/11] devices, vmm: Bound serial input and block the client when full The 16550 and PL011 models queue host input in a buffer with no limit. When a client writes faster than the guest reads, the buffer grows on the serial-manager thread until a reallocation needs mremap, which its seccomp filter rejects, and the VMM dies with SIGSYS. Cap the buffer at 4 KiB, allocated up front, and make queue_input_bytes() report how many bytes it took. serial-manager keeps the rest, stops polling the input fd and retries every 10 ms until the guest has read enough. The client then waits on the full socket or PTY buffer and no input byte is lost. Signed-off-by: CMGS --- devices/src/legacy/serial.rs | 60 +++++++++++++++++--- devices/src/legacy/uart_pl011.rs | 60 +++++++++++++++++--- vmm/src/serial_manager.rs | 94 ++++++++++++++++++++++++++++++-- 3 files changed, 193 insertions(+), 21 deletions(-) diff --git a/devices/src/legacy/serial.rs b/devices/src/legacy/serial.rs index b282594ec2..5a0fa2d09c 100644 --- a/devices/src/legacy/serial.rs +++ b/devices/src/legacy/serial.rs @@ -16,6 +16,7 @@ use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottabl use vmm_sys_util::errno::Result; const LOOP_SIZE: usize = 0x40; +const IN_BUFFER_SIZE: usize = 0x1000; const DATA: u8 = 0; const IER: u8 = 1; @@ -101,7 +102,7 @@ impl Serial { modem_status, scratch, baud_divisor, - in_buffer, + saved_input, ) = if let Some(state) = state { ( state.interrupt_enable, @@ -112,7 +113,7 @@ impl Serial { state.modem_status, state.scratch, state.baud_divisor, - state.in_buffer.into(), + state.in_buffer, ) } else { ( @@ -124,10 +125,14 @@ impl Serial { DEFAULT_MODEM_STATUS, 0, DEFAULT_BAUD_DIVISOR, - VecDeque::new(), + Vec::new(), ) }; + // Allocate the whole buffer here so that queuing input never reallocates. + let mut in_buffer = VecDeque::with_capacity(IN_BUFFER_SIZE.max(saved_input.len())); + in_buffer.extend(saved_input); + Serial { id, interrupt_enable, @@ -168,13 +173,21 @@ impl Serial { } /// Queues raw bytes for the guest to read and signals the interrupt if the line status would - /// change. - pub fn queue_input_bytes(&mut self, c: &[u8]) -> Result<()> { - if !self.is_loop() { - self.in_buffer.extend(c); - self.recv_data()?; + /// change. Returns how many bytes the device took; the caller retries the rest after the guest + /// has read some input. + pub fn queue_input_bytes(&mut self, c: &[u8]) -> Result { + if self.is_loop() { + return Ok(c.len()); } - Ok(()) + let count = c + .len() + .min(IN_BUFFER_SIZE.saturating_sub(self.in_buffer.len())); + if count == 0 { + return Ok(0); + } + self.in_buffer.extend(&c[..count]); + self.recv_data()?; + Ok(count) } pub fn flush_output(&mut self) -> io::Result<()> { @@ -494,6 +507,35 @@ mod tests { assert_eq!(data[0], 0); } + #[test] + fn serial_input_bounded() { + let intr_evt = EventFd::new(EFD_NONBLOCK).unwrap(); + let mut serial = Serial::new_sink( + String::from(SERIAL_NAME), + Arc::new(TestInterrupt::new(intr_evt.try_clone().unwrap())), + None, + ); + let capacity = serial.in_buffer.capacity(); + let input = [b'x'; 64]; + + let mut queued = 0; + while queued < IN_BUFFER_SIZE { + queued += serial.queue_input_bytes(&input).unwrap(); + } + assert_eq!(queued, IN_BUFFER_SIZE); + assert_eq!(serial.queue_input_bytes(&input).unwrap(), 0); + assert_eq!(serial.in_buffer.len(), IN_BUFFER_SIZE); + assert_eq!(serial.in_buffer.capacity(), capacity); + + let mut data = [0u8]; + for _ in 0..3 { + serial.read(0, DATA as u64, &mut data[..]); + } + assert_eq!(serial.queue_input_bytes(&input).unwrap(), 3); + assert_eq!(serial.in_buffer.len(), IN_BUFFER_SIZE); + assert_eq!(serial.in_buffer.capacity(), capacity); + } + #[test] fn serial_recv_pending_until_read() { let intr_evt = EventFd::new(0).unwrap(); diff --git a/devices/src/legacy/uart_pl011.rs b/devices/src/legacy/uart_pl011.rs index 5aa0512e45..8f89174c18 100644 --- a/devices/src/legacy/uart_pl011.rs +++ b/devices/src/legacy/uart_pl011.rs @@ -48,6 +48,8 @@ const PL011_ID: [u8; 8] = [0x11, 0x10, 0x14, 0x00, 0x0d, 0xf0, 0x05, 0xb1]; const AMBA_ID_LOW: u64 = 0x3f8; const AMBA_ID_HIGH: u64 = 0x401; +const READ_FIFO_SIZE: usize = 0x1000; + #[derive(Debug, Error)] pub(super) enum Error { #[error("PL011 write: Bad write offset: {0}")] @@ -124,7 +126,7 @@ impl Pl011 { debug, int_enabled, int_level, - read_fifo, + saved_input, ilpr, ibrd, fbrd, @@ -141,7 +143,7 @@ impl Pl011 { state.debug, state.int_enabled, state.int_level, - state.read_fifo.into(), + state.read_fifo, state.ilpr, state.ibrd, state.fbrd, @@ -159,7 +161,7 @@ impl Pl011 { 0, 0, 0, - VecDeque::new(), + Vec::new(), 0, 0, 0, @@ -169,6 +171,10 @@ impl Pl011 { ) }; + // Allocate the whole FIFO here so that queuing input never reallocates. + let mut read_fifo = VecDeque::with_capacity(READ_FIFO_SIZE.max(saved_input.len())); + read_fifo.extend(saved_input); + Self { id, flags, @@ -216,10 +222,17 @@ impl Pl011 { } } - /// Queues raw bytes for the guest to read and signals the interrupt - pub fn queue_input_bytes(&mut self, c: &[u8]) -> errno::Result<()> { - self.read_fifo.extend(c); - self.read_count += c.len() as u32; + /// Queues raw bytes for the guest to read and signals the interrupt. Returns how many bytes + /// the device took; the caller retries the rest after the guest has read some input. + pub fn queue_input_bytes(&mut self, c: &[u8]) -> errno::Result { + let count = c + .len() + .min(READ_FIFO_SIZE.saturating_sub(self.read_fifo.len())); + if count == 0 { + return Ok(0); + } + self.read_fifo.extend(&c[..count]); + self.read_count += count as u32; self.flags &= !PL011_FLAG_RXFE; if ((self.lcr & 0x10) == 0) || (self.read_count == 16) { @@ -231,7 +244,7 @@ impl Pl011 { self.trigger_interrupt()?; } - Ok(()) + Ok(count) } pub fn flush_output(&mut self) -> io::Result<()> { @@ -562,4 +575,35 @@ mod tests { pl011.read(0, UARTDR, &mut data); assert_eq!(data[0], b'c'); } + + #[test] + fn pl011_input_bounded() { + let intr_evt = EventFd::new(0).unwrap(); + let mut pl011 = Pl011::new( + String::from(SERIAL_NAME), + Arc::new(TestInterrupt::new(intr_evt.try_clone().unwrap())), + None, + Instant::now(), + None, + ); + let capacity = pl011.read_fifo.capacity(); + let input = [b'x'; 64]; + + let mut queued = 0; + while queued < READ_FIFO_SIZE { + queued += pl011.queue_input_bytes(&input).unwrap(); + } + assert_eq!(queued, READ_FIFO_SIZE); + assert_eq!(pl011.queue_input_bytes(&input).unwrap(), 0); + assert_eq!(pl011.read_fifo.len(), READ_FIFO_SIZE); + assert_eq!(pl011.read_fifo.capacity(), capacity); + + let mut data = [0u8]; + for _ in 0..3 { + pl011.read(0, UARTDR, &mut data); + } + assert_eq!(pl011.queue_input_bytes(&input).unwrap(), 3); + assert_eq!(pl011.read_fifo.len(), READ_FIFO_SIZE); + assert_eq!(pl011.read_fifo.capacity(), capacity); + } } diff --git a/vmm/src/serial_manager.rs b/vmm/src/serial_manager.rs index a17365f72c..b067003b60 100644 --- a/vmm/src/serial_manager.rs +++ b/vmm/src/serial_manager.rs @@ -92,6 +92,7 @@ pub(crate) enum EpollDispatch { Unknown, } const EPOLL_EVENTS_LEN: usize = 4; +const INPUT_RETRY_MS: i32 = 10; impl From for EpollDispatch { fn from(v: u64) -> Self { @@ -253,6 +254,36 @@ impl SerialManager { Ok(()) } + fn input_fd( + transport: &ConsoleTransport, + socket_console: Option<&SocketConsole>, + ) -> Option { + match transport { + ConsoleTransport::Pty(file) | ConsoleTransport::Tty(file) => Some(file.as_raw_fd()), + ConsoleTransport::Socket(_) | ConsoleTransport::TcpListen(_) => { + socket_console.and_then(SocketConsole::client_fd) + } + _ => None, + } + } + + // Stops or resumes reading the input fd. A stopped fd reports a hang-up + // once and then stays quiet until it is resumed. + fn set_input_enabled(epoll_fd: RawFd, fd: RawFd, enabled: bool) -> Result<()> { + let events = if enabled { + epoll::Events::EPOLLIN + } else { + epoll::Events::EPOLLONESHOT + }; + epoll::ctl( + epoll_fd, + epoll::ControlOptions::EPOLL_CTL_MOD, + fd, + epoll::Event::new(events, EpollDispatch::File as u64), + ) + .map_err(Error::Epoll) + } + pub(crate) fn start_thread( &mut self, exit_evt: EventFd, @@ -284,6 +315,10 @@ impl SerialManager { let mut events = [epoll::Event::new(epoll::Events::empty(), 0); EPOLL_EVENTS_LEN]; + // Input the device could not take yet. The input fd stays + // stopped until the guest has read it, so the client blocks. + let mut input = [0u8; 64]; + let mut backlog = 0..0; loop { // In case of PTY, we want to be able to detect a connection on the @@ -292,7 +327,13 @@ impl SerialManager { // epoll_wait() function to return after the timeout expired. // In case of TTY, we don't expect to detect such behavior, which is // why we can afford to block until an actual event is triggered. - let timeout = if pty_write_out.is_some() { 500 } else { -1 }; + let timeout = if !backlog.is_empty() { + INPUT_RETRY_MS + } else if pty_write_out.is_some() { + 500 + } else { + -1 + }; let num_events = match epoll::wait(epoll_fd.as_raw_fd(), timeout, &mut events[..]) { @@ -312,8 +353,26 @@ impl SerialManager { } }; + let was_backlogged = !backlog.is_empty(); + if was_backlogged { + backlog.start += serial + .as_ref() + .lock() + .unwrap() + .queue_input_bytes(&input[backlog.clone()]) + .map_err(Error::QueueInput)?; + if backlog.is_empty() + && let Some(fd) = + Self::input_fd(&transport, socket_console.as_ref()) + { + Self::set_input_enabled(epoll_fd.as_raw_fd(), fd, true)?; + } + } + if num_events == 0 { - if matches!(transport, ConsoleTransport::Pty(_)) { + // A stopped input fd reports no hang-up, so a + // timeout says nothing about the PTY peer. + if matches!(transport, ConsoleTransport::Pty(_)) && !was_backlogged { // This very specific case happens when the serial is connected // to a PTY. We know EPOLLHUP is always present when there's nothing // connected at the other end of the PTY. That's why getting no event @@ -399,7 +458,22 @@ impl SerialManager { || matches!(transport, ConsoleTransport::TcpListen(_)) && event.events & (libc::EPOLLHUP | libc::EPOLLERR) as u32 != 0 { - let mut input = [0u8; 64]; + if !backlog.is_empty() { + // A new socket client starts with its fd enabled. + if event.events & libc::EPOLLIN as u32 != 0 + && let Some(fd) = Self::input_fd( + &transport, + socket_console.as_ref(), + ) + { + Self::set_input_enabled( + epoll_fd.as_raw_fd(), + fd, + false, + )?; + } + continue; + } let count = match &transport { ConsoleTransport::Socket(_) | ConsoleTransport::TcpListen(_) => { @@ -446,12 +520,24 @@ impl SerialManager { input[0] = 0x0d; } - serial + let queued = serial .as_ref() .lock() .unwrap() .queue_input_bytes(&input[..count]) .map_err(Error::QueueInput)?; + if queued < count { + backlog = queued..count; + if let Some(fd) = + Self::input_fd(&transport, socket_console.as_ref()) + { + Self::set_input_enabled( + epoll_fd.as_raw_fd(), + fd, + false, + )?; + } + } } if matches!(transport, ConsoleTransport::TcpListen(_)) { continue; From 08e419c6dcdfd78c897c93129b277f5c3ce4c1ac Mon Sep 17 00:00:00 2001 From: Isaku Yamahata Date: Thu, 19 Nov 2026 11:20:29 +0800 Subject: [PATCH 07/11] pci, vmm: Rework BAR relocation Squash of the part of cloud-hypervisor/cloud-hypervisor#9122 by Isaku Yamahata that upstream has not taken yet, ported onto upstream's common VFIO BAR relocation and its GuestRegion-based shared memory BARs. The upstream PR was closed in favour of smaller ones; the commits that went in that way are left out. The ported series is kept on the pci-bar-rework-1119 branch. BAR moves are split into prepare and commit phases, a BAR is released when the guest disables its decoding, and pending installs are retried after a release or an eject. Windows guests that disable and re-enable several NICs at once swap their BARs; without this, CH refuses the move ("Failed moving device BAR ... keeping old BAR") and leaves those NICs in Code 10. Signed-off-by: Isaku Yamahata Signed-off-by: CMGS --- devices/src/ivshmem.rs | 71 +- devices/src/pvmemcontrol.rs | 27 +- devices/src/pvpanic.rs | 39 +- pci/src/bus.rs | 194 ++- pci/src/configuration.rs | 1401 +++++++++++++------ pci/src/device.rs | 86 +- pci/src/lib.rs | 8 +- pci/src/vfio.rs | 331 +++-- pci/src/vfio_user.rs | 55 +- virtio-devices/src/transport/pci_device.rs | 75 +- vm-allocator/src/address.rs | 91 -- vm-allocator/src/guest_memory.rs | 60 +- vm-allocator/src/system.rs | 44 - vmm/src/device_manager.rs | 1431 ++++++++++++++++++-- vmm/src/pci_segment.rs | 17 +- 15 files changed, 2956 insertions(+), 974 deletions(-) diff --git a/devices/src/ivshmem.rs b/devices/src/ivshmem.rs index 214aa8d4dd..f30f4cd557 100644 --- a/devices/src/ivshmem.rs +++ b/devices/src/ivshmem.rs @@ -10,7 +10,7 @@ use std::{io, result}; use log::{debug, error}; use pci::{ - BarReprogrammingParams, PCI_CONFIGURATION_ID, PciBarConfiguration, PciBarPrefetchable, + BarRelocation, InstallParams, PCI_CONFIGURATION_ID, PciBarConfiguration, PciBarPrefetchable, PciBarRegionType, PciBdf, PciClassCode, PciConfiguration, PciDevice, PciDeviceError, PciHeaderType, PciSubclass, }; @@ -208,14 +208,22 @@ impl PciDevice for IvshmemDevice { } // BAR0 holds device registers (256 Byte MMIO) - let bar0_alignment = if restoring { - None + // A BAR released on restore is not allocated: another device may hold + // its saved range by now, and its install allocates at its register. + let bar0_addr = if let Some(addr) = bar0_addr + && self.configuration.is_bar_released(IVSHMEM_BAR0_IDX) + { + addr } else { - Some(IVSHMEM_REG_BAR_SIZE) + let bar0_alignment = if restoring { + None + } else { + Some(IVSHMEM_REG_BAR_SIZE) + }; + mmio32_allocator + .allocate(bar0_addr, IVSHMEM_REG_BAR_SIZE, bar0_alignment) + .ok_or(PciDeviceError::IoAllocationFailed(IVSHMEM_REG_BAR_SIZE))? }; - let bar0_addr = mmio32_allocator - .allocate(bar0_addr, IVSHMEM_REG_BAR_SIZE, bar0_alignment) - .ok_or(PciDeviceError::IoAllocationFailed(IVSHMEM_REG_BAR_SIZE))?; debug!("ivshmem bar0 address 0x{:x}", bar0_addr.0); let bar0 = PciBarConfiguration::default() @@ -229,10 +237,16 @@ impl PciDevice for IvshmemDevice { // The data BAR maps the shared memory object let data_bar_size = self.region_size; - let data_bar_alignment = if restoring { None } else { Some(data_bar_size) }; - let data_bar_addr = mmio64_allocator - .allocate(data_bar_addr, data_bar_size, data_bar_alignment) - .ok_or(PciDeviceError::IoAllocationFailed(data_bar_size))?; + let data_bar_addr = if let Some(addr) = data_bar_addr + && self.configuration.is_bar_released(IVSHMEM_DATA_BAR_IDX) + { + addr + } else { + let data_bar_alignment = if restoring { None } else { Some(data_bar_size) }; + mmio64_allocator + .allocate(data_bar_addr, data_bar_size, data_bar_alignment) + .ok_or(PciDeviceError::IoAllocationFailed(data_bar_size))? + }; debug!("ivshmem data BAR address 0x{:x}", data_bar_addr.0); let data_bar = PciBarConfiguration::default() @@ -272,7 +286,7 @@ impl PciDevice for IvshmemDevice { reg_idx: usize, offset: u64, data: &[u8], - ) -> (Vec, Option>) { + ) -> (BarRelocation, Option>) { ( self.configuration .write_config_register(reg_idx, offset, data), @@ -313,13 +327,28 @@ impl PciDevice for IvshmemDevice { None } - fn move_bar(&mut self, bar_idx: usize, new_base: u64) -> io::Result<()> { + fn move_bar_prepare(&mut self, bar_idx: usize) -> io::Result<()> { if bar_idx == IVSHMEM_DATA_BAR_IDX { self.region .as_mut() .ok_or_else(|| io::Error::other(IvshmemError::MissingMemoryRegion))? + .unregister() + .map_err(io::Error::other)?; + } + + Ok(()) + } + + fn move_bar_commit(&mut self, bar_idx: usize, new_base: u64) -> io::Result<()> { + if bar_idx == IVSHMEM_DATA_BAR_IDX { + let region = self + .region + .as_mut() + .ok_or_else(|| io::Error::other(IvshmemError::MissingMemoryRegion))?; + region .move_guest_address(GuestAddress(new_base)) .map_err(io::Error::other)?; + region.register().map_err(io::Error::other)?; } for bar in self.bar_regions.iter_mut() { if bar.idx() == bar_idx { @@ -330,8 +359,20 @@ impl PciDevice for IvshmemDevice { Ok(()) } - fn restore_bar_addr(&mut self, params: &BarReprogrammingParams) { - self.configuration.restore_bar_addr(params); + fn release_stale_bar(&mut self, bar_idx: usize, mapped_at: u64) -> bool { + self.configuration.release_stale_bar(bar_idx, mapped_at) + } + + fn is_bar_released(&self, bar_idx: usize) -> bool { + self.configuration.is_bar_released(bar_idx) + } + + fn on_bar_installed(&mut self, bar_idx: usize) { + self.configuration.on_bar_installed(bar_idx); + } + + fn pending_bar_installs(&self) -> Vec { + self.configuration.pending_bar_installs() } fn as_any_mut(&mut self) -> &mut dyn Any { diff --git a/devices/src/pvmemcontrol.rs b/devices/src/pvmemcontrol.rs index 36b68c3636..fe25796eba 100644 --- a/devices/src/pvmemcontrol.rs +++ b/devices/src/pvmemcontrol.rs @@ -12,8 +12,8 @@ use std::{fmt, io, mem, ptr, result}; use log::{debug, warn}; use pci::{ - BarReprogrammingParams, PciBarConfiguration, PciBarPrefetchable, PciBarRegionType, PciBdf, - PciClassCode, PciConfiguration, PciDevice, PciDeviceError, PciHeaderType, PciSubclass, + BarRelocation, InstallParams, PciBarConfiguration, PciBarPrefetchable, PciBarRegionType, + PciBdf, PciClassCode, PciConfiguration, PciDevice, PciDeviceError, PciHeaderType, PciSubclass, }; use thiserror::Error; use vm_allocator::page_size::get_page_size; @@ -837,7 +837,7 @@ impl PciDevice for PvmemcontrolPciDevice { reg_idx: usize, offset: u64, data: &[u8], - ) -> (Vec, Option>) { + ) -> (BarRelocation, Option>) { ( self.configuration .write_config_register(reg_idx, offset, data), @@ -849,8 +849,20 @@ impl PciDevice for PvmemcontrolPciDevice { self.configuration.read_config_register(reg_idx) } - fn restore_bar_addr(&mut self, params: &BarReprogrammingParams) { - self.configuration.restore_bar_addr(params); + fn release_stale_bar(&mut self, bar_idx: usize, mapped_at: u64) -> bool { + self.configuration.release_stale_bar(bar_idx, mapped_at) + } + + fn is_bar_released(&self, bar_idx: usize) -> bool { + self.configuration.is_bar_released(bar_idx) + } + + fn on_bar_installed(&mut self, bar_idx: usize) { + self.configuration.on_bar_installed(bar_idx); + } + + fn pending_bar_installs(&self) -> Vec { + self.configuration.pending_bar_installs() } fn as_any_mut(&mut self) -> &mut dyn Any { @@ -923,12 +935,15 @@ impl PciDevice for PvmemcontrolPciDevice { _mmio64_allocator: &mut AddressAllocator, ) -> Result<(), PciDeviceError> { for bar in self.bar_regions.drain(..) { + if self.configuration.is_bar_released(bar.idx()) { + continue; + } mmio32_allocator.free(GuestAddress(bar.addr()), bar.size()); } Ok(()) } - fn move_bar(&mut self, bar_idx: usize, new_base: u64) -> io::Result<()> { + fn move_bar_commit(&mut self, bar_idx: usize, new_base: u64) -> io::Result<()> { for bar in self.bar_regions.iter_mut() { if bar.idx() == bar_idx { *bar = bar.set_address(new_base); diff --git a/devices/src/pvpanic.rs b/devices/src/pvpanic.rs index f7fc619d0e..d365747fe1 100644 --- a/devices/src/pvpanic.rs +++ b/devices/src/pvpanic.rs @@ -10,7 +10,7 @@ use std::{io, result}; use event_monitor::event; use log::{debug, info}; use pci::{ - BarReprogrammingParams, PCI_CONFIGURATION_ID, PciBarConfiguration, PciBarPrefetchable, + BarRelocation, InstallParams, PCI_CONFIGURATION_ID, PciBarConfiguration, PciBarPrefetchable, PciBarRegionType, PciBdf, PciClassCode, PciConfiguration, PciDevice, PciDeviceError, PciHeaderType, PciSubclass, }; @@ -156,7 +156,7 @@ impl PciDevice for PvPanicDevice { reg_idx: usize, offset: u64, data: &[u8], - ) -> (Vec, Option>) { + ) -> (BarRelocation, Option>) { ( self.configuration .write_config_register(reg_idx, offset, data), @@ -199,9 +199,17 @@ impl PciDevice for PvPanicDevice { } } - let bar_addr = mmio32_allocator - .allocate(bar_addr, region_size, Some(PVPANIC_DEVICE_MMIO_ALIGNMENT)) - .ok_or(PciDeviceError::IoAllocationFailed(region_size))?; + // A BAR released on restore is not allocated: another device may hold + // its saved range by now, and its install allocates at its register. + let bar_addr = if let Some(addr) = bar_addr + && self.configuration.is_bar_released(bar_id as usize) + { + addr + } else { + mmio32_allocator + .allocate(bar_addr, region_size, Some(PVPANIC_DEVICE_MMIO_ALIGNMENT)) + .ok_or(PciDeviceError::IoAllocationFailed(region_size))? + }; let bar = PciBarConfiguration::default() .set_index(bar_id as usize) @@ -230,13 +238,16 @@ impl PciDevice for PvPanicDevice { _mmio64_allocator: &mut AddressAllocator, ) -> result::Result<(), PciDeviceError> { for bar in self.bar_regions.drain(..) { + if self.configuration.is_bar_released(bar.idx()) { + continue; + } mmio32_allocator.free(GuestAddress(bar.addr()), bar.size()); } Ok(()) } - fn move_bar(&mut self, bar_idx: usize, new_base: u64) -> io::Result<()> { + fn move_bar_commit(&mut self, bar_idx: usize, new_base: u64) -> io::Result<()> { for bar in self.bar_regions.iter_mut() { if bar.idx() == bar_idx { *bar = bar.set_address(new_base); @@ -246,8 +257,20 @@ impl PciDevice for PvPanicDevice { Ok(()) } - fn restore_bar_addr(&mut self, params: &BarReprogrammingParams) { - self.configuration.restore_bar_addr(params); + fn release_stale_bar(&mut self, bar_idx: usize, mapped_at: u64) -> bool { + self.configuration.release_stale_bar(bar_idx, mapped_at) + } + + fn is_bar_released(&self, bar_idx: usize) -> bool { + self.configuration.is_bar_released(bar_idx) + } + + fn on_bar_installed(&mut self, bar_idx: usize) { + self.configuration.on_bar_installed(bar_idx); + } + + fn pending_bar_installs(&self) -> Vec { + self.configuration.pending_bar_installs() } fn read_bar(&mut self, _base: u64, _offset: u64, data: &mut [u8]) { diff --git a/pci/src/bus.rs b/pci/src/bus.rs index 80cb5ae6c0..46232c628e 100644 --- a/pci/src/bus.rs +++ b/pci/src/bus.rs @@ -10,15 +10,15 @@ use std::ops::DerefMut; use std::result; use std::sync::{Arc, Barrier, Mutex}; -use log::warn; +use log::{error, warn}; use serde::{Deserialize, Serialize}; use thiserror::Error; -use vm_device::BusDevice; +use vm_device::{BusDevice, BusDeviceSync}; use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; use crate::PciBdf; use crate::configuration::{PciBridgeSubclass, PciClassCode, PciConfiguration, PciHeaderType}; -use crate::device::{BarReprogrammingParams, DeviceRelocation, PciDevice}; +use crate::device::{BarRelocation, DeviceRelocation, InstallParams, PciDevice}; /// Denotes the PCI device ID of a bus' root bridge device. pub const PCI_ROOT_DEVICE_ID: u8 = 0; @@ -82,7 +82,7 @@ impl PciDevice for PciRoot { reg_idx: usize, offset: u64, data: &[u8], - ) -> (Vec, Option>) { + ) -> (BarRelocation, Option>) { ( self.config.write_config_register(reg_idx, offset, data), None, @@ -93,6 +93,22 @@ impl PciDevice for PciRoot { self.config.read_reg(reg_idx) } + fn is_bar_released(&self, bar_idx: usize) -> bool { + self.config.is_bar_released(bar_idx) + } + + fn on_bar_installed(&mut self, bar_idx: usize) { + self.config.on_bar_installed(bar_idx); + } + + fn release_stale_bar(&mut self, bar_idx: usize, mapped_at: u64) -> bool { + self.config.release_stale_bar(bar_idx, mapped_at) + } + + fn pending_bar_installs(&self) -> Vec { + self.config.pending_bar_installs() + } + fn as_any_mut(&mut self) -> &mut dyn Any { self } @@ -113,20 +129,32 @@ enum DeviceIdState { Allocated, } +struct PciBusDevice { + pci: Arc>, + /// None only for the host bridge, which has no BARs to relocate. + bus: Option>, +} + pub struct PciBus { /// Devices attached to this bus. - devices: HashMap>>, + devices: HashMap, device_reloc: Arc, device_ids: [DeviceIdState; NUM_DEVICE_IDS as usize], } impl PciBus { pub fn new(pci_root: Option, device_reloc: Arc) -> Self { - let mut devices: HashMap>> = HashMap::new(); + let mut devices: HashMap = HashMap::new(); let mut device_ids = [DeviceIdState::Free; NUM_DEVICE_IDS as usize]; if let Some(pci_root) = pci_root { - devices.insert(PCI_ROOT_DEVICE_ID, Arc::new(Mutex::new(pci_root))); + devices.insert( + PCI_ROOT_DEVICE_ID, + PciBusDevice { + pci: Arc::new(Mutex::new(pci_root)), + bus: None, + }, + ); device_ids[PCI_ROOT_DEVICE_ID as usize] = DeviceIdState::Allocated; } @@ -137,13 +165,49 @@ impl PciBus { } } - pub fn add_device(&mut self, device_id: u8, device: Arc>) -> Result<()> { - self.devices.insert(device_id, device); + pub fn add_device( + &mut self, + device_id: u8, + device: Arc>, + bus_device: Option>, + ) -> Result<()> { + self.devices.insert( + device_id, + PciBusDevice { + pci: device, + bus: bus_device, + }, + ); Ok(()) } + /// The ids of the devices on the bus but the host bridge, in order. + fn device_ids(&self) -> Vec { + let mut ids: Vec = self.devices.keys().copied().collect(); + ids.sort_unstable(); + ids.retain(|id| *id != PCI_ROOT_DEVICE_ID); + ids + } + + /// Install the pending BARs of every device but `writer_device_id`, + /// whose config write just released a range they may be waiting for. + pub fn retry_pending_installs(&self, writer_device_id: u8) { + for id in self.device_ids() { + if id == writer_device_id { + continue; + } + let d = &self.devices[&id]; + let mut device = d.pci.lock().unwrap(); + let reloc = BarRelocation { + release: Vec::new(), + install: device.pending_bar_installs(), + }; + self.apply_bar_relocation(device.deref_mut(), d.bus.as_ref(), &reloc); + } + } + pub fn remove_by_device(&mut self, device: &Arc>) -> Result<()> { - self.devices.retain(|_, dev| !Arc::ptr_eq(dev, device)); + self.devices.retain(|_, dev| !Arc::ptr_eq(&dev.pci, device)); Ok(()) } @@ -227,23 +291,49 @@ impl PciBus { } } - fn apply_bar_reprogramming(&self, device: &mut dyn PciDevice, bars: &[BarReprogrammingParams]) { - for bar in bars { - if let Err(e) = self.device_reloc.move_bar( - bar.bar_idx - .expect("bar_idx is set on detection and on restore"), - bar.old_base, - bar.new_base, - bar.len, - device, - bar.region_type, - ) { - // Rollback the changes from detect_bar_reprogramming(). - warn!( - "Failed moving device BAR: {:?}: 0x{:x}->0x{:x}(0x{:x}), keeping old BAR", - e, bar.old_base, bar.new_base, bar.len + fn apply_bar_relocation( + &self, + device: &mut dyn PciDevice, + bus_device: Option<&Arc>, + reloc: &BarRelocation, + ) { + let mut failed = Vec::new(); + for r in &reloc.release { + if let Err(e) = self.device_reloc.move_bar_prepare(device, r) { + // The BAR stays mapped at its old address, which its register + // no longer names, until the guest moves it again. + error!( + "Failed releasing BAR {}: {:?}; BAR kept at its old address", + r.bar_idx, e ); - device.restore_bar_addr(bar); + device.on_bar_installed(r.bar_idx); + failed.push(r.bar_idx); + } + } + + for a in &reloc.install { + if failed.contains(&a.bar_idx) { + continue; + } + let Some(bus_device) = bus_device else { + // Only the host bridge, which has no BARs, lacks a bus handle. + error!( + "BAR {} install at 0x{:x} for a device with no bus handle", + a.bar_idx, a.new_base + ); + continue; + }; + + match self.device_reloc.move_bar_commit(device, bus_device, a) { + Ok(()) => { + device.on_bar_installed(a.bar_idx); + } + Err(e) => { + warn!( + "Failed installing BAR {} at {:#x}: {:?}; retried on the next BAR or COMMAND write", + a.bar_idx, a.new_base, e + ); + } } } } @@ -296,7 +386,7 @@ impl PciConfigIo { .devices .get(&(device as u8)) .map_or(0xffff_ffff, |d| { - d.lock().unwrap().read_config_register(register) + d.pci.lock().unwrap().read_config_register(register) }) } @@ -318,15 +408,20 @@ impl PciConfigIo { return None; } + let device_id = device as u8; let pci_bus = self.pci_bus.as_ref().lock().unwrap(); - if let Some(d) = pci_bus.devices.get(&(device as u8)) { - let mut device = d.lock().unwrap(); + if let Some(d) = pci_bus.devices.get(&device_id) { + let mut device = d.pci.lock().unwrap(); // Update the register value - let (bar_reprogram, ret) = device.write_config_register(register, offset, data); + let (reloc, ret) = device.write_config_register(register, offset, data); - // Move the device's BAR if needed - pci_bus.apply_bar_reprogramming(device.deref_mut(), &bar_reprogram); + pci_bus.apply_bar_relocation(device.deref_mut(), d.bus.as_ref(), &reloc); + // Never hold two device locks at once. + drop(device); + if !reloc.release.is_empty() { + pci_bus.retry_pending_installs(device_id); + } ret } else { @@ -433,7 +528,7 @@ impl PciConfigMmio { .devices .get(&(device as u8)) .map_or(0xffff_ffff, |d| { - d.lock().unwrap().read_config_register(register) + d.pci.lock().unwrap().read_config_register(register) }) } @@ -454,15 +549,20 @@ impl PciConfigMmio { return None; } + let device_id = device as u8; let pci_bus = self.pci_bus.lock().unwrap(); - if let Some(d) = pci_bus.devices.get(&(device as u8)) { - let mut device = d.lock().unwrap(); + if let Some(d) = pci_bus.devices.get(&device_id) { + let mut device = d.pci.lock().unwrap(); // Update the register value - let (bar_reprogram, ret) = device.write_config_register(register, offset, data); + let (reloc, ret) = device.write_config_register(register, offset, data); - // Move the device's BAR if needed - pci_bus.apply_bar_reprogramming(device.deref_mut(), &bar_reprogram); + pci_bus.apply_bar_relocation(device.deref_mut(), d.bus.as_ref(), &reloc); + // Never hold two device locks at once. + drop(device); + if !reloc.release.is_empty() { + pci_bus.retry_pending_installs(device_id); + } ret } else { @@ -548,21 +648,25 @@ mod tests { use std::result::Result; use super::*; - use crate::configuration::PciBarRegionType; #[derive(Debug)] /// Helper struct that mocks the implementation of DeviceRelocation struct MockDeviceRelocation; impl DeviceRelocation for MockDeviceRelocation { - fn move_bar( + fn move_bar_prepare( + &self, + _pci_dev: &mut dyn PciDevice, + _params: &crate::ReleaseParams, + ) -> Result<(), io::Error> { + Ok(()) + } + + fn move_bar_commit( &self, - _bar_idx: usize, - _old_base: u64, - _new_base: u64, - _len: u64, _pci_dev: &mut dyn PciDevice, - _region_type: PciBarRegionType, + _bus_device: &Arc, + _params: &crate::InstallParams, ) -> Result<(), io::Error> { Ok(()) } diff --git a/pci/src/configuration.rs b/pci/src/configuration.rs index 9f25c73dbb..4336ed1110 100644 --- a/pci/src/configuration.rs +++ b/pci/src/configuration.rs @@ -4,8 +4,8 @@ // // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause +use std::result; use std::sync::{Arc, Mutex}; -use std::{mem, result}; use log::{debug, info, warn}; use serde::{Deserialize, Serialize}; @@ -14,13 +14,14 @@ use vm_device::PciBarType; use vm_migration::{MigratableError, Pausable, Snapshot, Snapshottable}; use crate::MsixConfig; -use crate::device::BarReprogrammingParams; +use crate::device::{BarRelocation, InstallParams, ReleaseParams}; // The number of 32bit registers in the config space, 4096 bytes. const NUM_CONFIGURATION_REGISTERS: usize = 1024; -pub(crate) const COMMAND_REG: usize = 1; -pub(crate) const COMMAND_REG_MEMORY_SPACE_MASK: u32 = 0x0000_0002; +pub const COMMAND_REG: usize = 1; +pub const COMMAND_REG_IO_SPACE_MASK: u32 = 0x0000_0001; +pub const COMMAND_REG_MEMORY_SPACE_MASK: u32 = 0x0000_0002; const STATUS_REG: usize = 1; const STATUS_REG_CAPABILITIES_USED_MASK: u32 = 0x0010_0000; const BAR0_REG: usize = 4; @@ -445,17 +446,6 @@ fn encode_32_bits_bar_size(bar_size: u32) -> Option { None } -fn decode_32_bits_bar_size(bar_size: u32) -> Option { - if bar_size > 0 { - let size = !bar_size + 1; - // PCI specification requires BAR sizes to be non-zero powers of two. - if size.is_power_of_two() { - return Some(size); - } - } - None -} - fn encode_64_bits_bar_size(bar_size: u64) -> Option<(u32, u32)> { if bar_size > 0 { let result = !(bar_size - 1); @@ -466,18 +456,6 @@ fn encode_64_bits_bar_size(bar_size: u64) -> Option<(u32, u32)> { None } -fn decode_64_bits_bar_size(bar_size_hi: u32, bar_size_lo: u32) -> Option { - let bar_size: u64 = ((bar_size_hi as u64) << 32) | (bar_size_lo as u64); - if bar_size > 0 { - let size = !bar_size + 1; - // PCI specification requires BAR sizes to be non-zero powers of two. - if size.is_power_of_two() { - return Some(size); - } - } - None -} - #[derive(Debug, Default, Clone, Copy, Serialize, Deserialize)] struct PciBar { addr: u32, @@ -541,11 +519,23 @@ pub struct PciConfigurationState { rom_bar_used: bool, last_capability: Option<(usize, usize)>, msix_cap_reg_idx: Option, - // Preserve deferred BAR moves across snapshot and restore. + // Legacy in-flight BAR moves: decoded for old snapshots, otherwise ignored. #[serde(default)] pending_bar_reprogram: Vec, } +/// Legacy in-flight BAR move, only kept so that old snapshots still decode. +#[derive(Clone, Copy, Debug, Serialize, Deserialize)] +struct BarReprogrammingParams { + /// The BAR slot; missing from older snapshots. + #[serde(default)] + bar_idx: Option, + old_base: u64, + new_base: u64, + len: u64, + region_type: PciBarRegionType, +} + /// Contains the configuration space of a PCI node. /// /// See the [specification](https://en.wikipedia.org/wiki/PCI_configuration_space). @@ -561,7 +551,11 @@ pub struct PciConfiguration { last_capability: Option<(usize, usize)>, msix_cap_reg_idx: Option, msix_config: Option>>, - pending_bar_reprogram: Vec, + /// Whether each BAR slot (the ROM at ROM_BAR_IDX) is mapped at its + /// register. Set by add_pci_bar() and on a reported install, cleared by + /// a release. A restored device starts with every BAR mapped, at its + /// saved address; release_stale_bar() then settles each one. + bar_installed: [bool; NUM_BAR_REGS + 1], } /// See pci_regs.h in kernel @@ -664,6 +658,7 @@ impl PciConfiguration { msix_config: Option>>, state: Option, ) -> Self { + let restoring = state.is_some(); let ( registers, writable_bits, @@ -673,8 +668,13 @@ impl PciConfiguration { rom_bar_used, last_capability, msix_cap_reg_idx, - pending_bar_reprogram, ) = if let Some(state) = state { + let legacy_moves = state.pending_bar_reprogram.len(); + if legacy_moves != 0 { + info!( + "Ignoring {legacy_moves} legacy in-flight BAR moves: undecoded BARs are reinstalled on decode enable" + ); + } let registers: Vec = state.registers.into(); let writable_bits: Vec = state.writable_bits.into(); ( @@ -686,7 +686,6 @@ impl PciConfiguration { state.rom_bar_used, state.last_capability, state.msix_cap_reg_idx, - state.pending_bar_reprogram, ) } else { let mut registers = [0u32; NUM_CONFIGURATION_REGISTERS]; @@ -726,11 +725,10 @@ impl PciConfiguration { false, None, None, - Vec::new(), ) }; - let config = PciConfiguration { + let mut config = PciConfiguration { registers, writable_bits, bars, @@ -740,73 +738,18 @@ impl PciConfiguration { last_capability, msix_cap_reg_idx, msix_config, - pending_bar_reprogram, + bar_installed: [false; NUM_BAR_REGS + 1], }; - config.fixup_pending_bar_reprogram() - } - fn fixup_pending_bar_reprogram(mut self) -> Self { - for i in (0..self.pending_bar_reprogram.len()).rev() { - if self.pending_bar_reprogram[i].bar_idx.is_some() { - continue; + // A restored device is mapped at its saved addresses, like a new one + // by add_pci_bar(); release_stale_bar() then settles each BAR. + if restoring { + for slot in (0..NUM_BAR_REGS).chain([ROM_BAR_IDX]) { + config.bar_installed[slot] = config.bar_region_type(slot).is_some(); } - - let p = self.pending_bar_reprogram[i]; - self.pending_bar_reprogram[i].bar_idx = self.pending_bar_reprogram[i + 1..] - .iter() - .find(|q| { - q.old_base == p.new_base && q.len == p.len && q.region_type == p.region_type - }) - .and_then(|q| q.bar_idx) - .or_else(|| self.find_bar_idx_by_addr(p.new_base, p.region_type)); - } - - // If the corresponding bar_idx isn't found, there is inconsistency. - // Give up with warning. - self.pending_bar_reprogram.retain(|p| { - if p.bar_idx.is_none() { - warn!("Dropping pending BAR move {p:x?}"); - } - p.bar_idx.is_some() - }); - - for param in mem::take(&mut self.pending_bar_reprogram) { - self.enqueue_bar_reprogramming(param); - } - - self - } - - fn enqueue_bar_reprogramming(&mut self, param: BarReprogrammingParams) { - if let Some(idx) = self - .pending_bar_reprogram - .iter() - .position(|pending| pending.bar_idx == param.bar_idx) - { - // The mapping is still at the first old_base while decoding is - // disabled. Only the most recent destination needs to be applied. - self.pending_bar_reprogram[idx].new_base = param.new_base; - if self.pending_bar_reprogram[idx].old_base == param.new_base { - self.pending_bar_reprogram.remove(idx); - } - } else if param.old_base != param.new_base { - self.pending_bar_reprogram.push(param); } - } - fn find_bar_idx_by_addr(&self, base_addr: u64, region_type: PciBarRegionType) -> Option { - (0..NUM_BAR_REGS) - .find(|&idx| { - self.bars[idx].used - && self.get_bar_addr(idx) == base_addr - && self.bars[idx].r#type == Some(region_type) - }) - .or_else(|| { - (self.rom_bar_used - && u64::from(self.rom_bar_addr & self.writable_bits[ROM_BAR_REG]) == base_addr - && region_type == PciBarRegionType::Memory32BitRegion) - .then_some(ROM_BAR_IDX) - }) + config } fn state(&self) -> PciConfigurationState { @@ -819,7 +762,7 @@ impl PciConfiguration { rom_bar_used: self.rom_bar_used, last_capability: self.last_capability, msix_cap_reg_idx: self.msix_cap_reg_idx, - pending_bar_reprogram: self.pending_bar_reprogram.clone(), + pending_bar_reprogram: Vec::new(), } } @@ -969,6 +912,7 @@ impl PciConfiguration { self.bars[bar_idx].addr = self.registers[reg_idx]; self.bars[bar_idx].used = true; self.bars[bar_idx].r#type = Some(config.region_type); + self.bar_installed[bar_idx] = true; Ok(()) } @@ -1005,6 +949,7 @@ impl PciConfiguration { self.rom_bar_size = encode_32_bits_bar_size(config.size as u32).ok_or(Error::Encode32BarSize)?; self.rom_bar_used = true; + self.bar_installed[ROM_BAR_IDX] = true; Ok(()) } @@ -1078,9 +1023,9 @@ impl PciConfiguration { reg_idx: usize, offset: u64, data: &[u8], - ) -> Vec { + ) -> BarRelocation { if offset as usize + data.len() > 4 { - return Vec::new(); + return BarRelocation::default(); } // Handle potential write to MSI-X message control register @@ -1111,6 +1056,8 @@ impl PciConfiguration { } } + let old_command = self.registers[COMMAND_REG]; + match data.len() { 1 => self.write_byte(reg_idx * 4 + offset as usize, data[0]), 2 => self.write_word( @@ -1124,44 +1071,156 @@ impl PciConfiguration { _ => (), } - if let Some(param) = self.detect_bar_reprogramming(reg_idx, data) { - self.enqueue_bar_reprogramming(param); + let mut reloc = BarRelocation::default(); + + // Release the old location as soon as the guest moves the BAR. + if let Some(slot) = self.detect_bar_reprogramming(reg_idx, data) + && self.bar_installed[slot] + { + reloc.release.push(ReleaseParams { bar_idx: slot }); + self.bar_installed[slot] = false; + } + // A size probe is answered from the register alone; the write-back of + // the address, which is no move, retries the installs. Any other BAR + // register write, moving the BAR or not, retries them. + let probe = <[u8; 4]>::try_from(data).is_ok_and(|bytes| { + let value = u32::from_le_bytes(bytes); + self.is_bar_size_probe(reg_idx, value) + || (reg_idx == ROM_BAR_REG && value & ROM_BAR_ADDR_MASK == ROM_BAR_ADDR_MASK) + }); + let bar_written = !probe + && ((BAR0_REG..BAR0_REG + NUM_BAR_REGS).contains(®_idx) || reg_idx == ROM_BAR_REG); + + if reg_idx == COMMAND_REG { + self.release_disabled_bars(old_command, &mut reloc); } - self.drain_pending_bar_reprogram() + // After a BAR or COMMAND write, install every released BAR whose space + // is decoded: a moved BAR, a failed install or a newly enabled space. + if bar_written || reg_idx == COMMAND_REG { + self.drain_pending_installs(&mut reloc); + } + + reloc } - // Return pending BAR reprogramming if MSE bit is set - pub(crate) fn drain_pending_bar_reprogram(&mut self) -> Vec { - if !self.pending_bar_reprogram.is_empty() { - // Return bar reprogramming only if the MSE bit is enabled; - if self.read_config_register(COMMAND_REG) & COMMAND_REG_MEMORY_SPACE_MASK - == COMMAND_REG_MEMORY_SPACE_MASK + /// Release every mapped BAR whose space a COMMAND write, from + /// `old_command`, stopped decoding: the device no longer claims the + /// range, so another device may be placed there, as Windows does while + /// a device is disabled. + pub(crate) fn release_disabled_bars(&mut self, old_command: u32, reloc: &mut BarRelocation) { + let disabled = old_command & !self.registers[COMMAND_REG]; + for slot in (0..NUM_BAR_REGS).chain([ROM_BAR_IDX]) { + if self.bar_installed[slot] + && let Some(region_type) = self.bar_region_type(slot) + && disabled & Self::decode_mask(region_type) != 0 { - info!( - "BAR reprogramming parameter is returned: {:x?}", - self.pending_bar_reprogram - ); - return mem::take(&mut self.pending_bar_reprogram); + reloc.release.push(ReleaseParams { bar_idx: slot }); + self.bar_installed[slot] = false; } - info!( - "MSE bit is disabled. No BAR reprogramming parameter is returned: {:x?}", - self.pending_bar_reprogram - ); } + } + + /// Queue the installs of every released BAR whose space is decoded. + pub(crate) fn drain_pending_installs(&mut self, reloc: &mut BarRelocation) { + reloc.install.extend(self.pending_bar_installs()); + if !reloc.is_empty() { + info!("BAR relocation plan: {reloc:x?}"); + } + } + + // A failed install is not reported, so the slot stays released and is + // retried later. + pub fn on_bar_installed(&mut self, bar_idx: usize) { + self.bar_installed[bar_idx] = true; + } + + /// The installs owed to the guest: released BARs whose space is decoded, + /// at their config-space targets. + pub fn pending_bar_installs(&self) -> Vec { + (0..NUM_BAR_REGS) + .chain([ROM_BAR_IDX]) + .filter_map(|slot| { + let region_type = self.bar_region_type(slot)?; + if self.bar_installed[slot] || !self.decode_enabled(region_type) { + return None; + } + Some(InstallParams { + bar_idx: slot, + new_base: self.bar_target(slot), + }) + }) + .collect() + } + + pub fn is_bar_released(&self, bar_idx: usize) -> bool { + self.bar_region_type(bar_idx).is_some() && !self.bar_installed[bar_idx] + } + + /// On restore, release BAR `slot` unless its space is decoded and its + /// register names `mapped_at`, the saved address it is about to be + /// mapped at. Returns whether it was released, in which case the caller + /// leaves it unmapped; a decoded BAR is then owed an install at its + /// register. + pub fn release_stale_bar(&mut self, slot: usize, mapped_at: u64) -> bool { + let Some(region_type) = self.bar_region_type(slot) else { + return false; + }; + let keep = self.decode_enabled(region_type) && self.bar_target(slot) == mapped_at; + self.bar_installed[slot] = keep; + !keep + } + + #[cfg(test)] + pub(crate) fn pending_slots(&self) -> Vec { + (0..NUM_BAR_REGS) + .chain([ROM_BAR_IDX]) + .filter(|&slot| self.is_bar_released(slot)) + .collect() + } + + /// The COMMAND bit decoding `region_type`: IOSE for IO, MSE otherwise. + pub fn decode_mask(region_type: PciBarRegionType) -> u32 { + match region_type { + PciBarRegionType::IoRegion => COMMAND_REG_IO_SPACE_MASK, + _ => COMMAND_REG_MEMORY_SPACE_MASK, + } + } - Vec::new() + fn decode_enabled(&self, region_type: PciBarRegionType) -> bool { + self.registers[COMMAND_REG] & Self::decode_mask(region_type) != 0 + } + + fn bar_target(&self, slot: usize) -> u64 { + if slot == ROM_BAR_IDX { + return u64::from(self.registers[ROM_BAR_REG] & self.writable_bits[ROM_BAR_REG]); + } + + let reg_idx = BAR0_REG + slot; + let mut addr = u64::from(self.registers[reg_idx] & self.writable_bits[reg_idx]); + if self.bars[slot].r#type == Some(PciBarRegionType::Memory64BitRegion) { + addr |= u64::from(self.registers[reg_idx + 1] & self.writable_bits[reg_idx + 1]) << 32; + } + + addr + } + + fn bar_region_type(&self, slot: usize) -> Option { + if slot == ROM_BAR_IDX { + // The expansion ROM is a 32-bit memory region. + return self + .rom_bar_used + .then_some(PciBarRegionType::Memory32BitRegion); + } + + self.bars.get(slot)?.r#type } pub fn read_config_register(&self, reg_idx: usize) -> u32 { self.read_reg(reg_idx) } - fn detect_bar_reprogramming( - &mut self, - reg_idx: usize, - data: &[u8], - ) -> Option { + fn detect_bar_reprogramming(&mut self, reg_idx: usize, data: &[u8]) -> Option { let Ok(data) = <[u8; 4]>::try_from(data) else { return None; }; @@ -1196,21 +1255,10 @@ impl PciConfiguration { "Detected BAR reprogramming: (BAR {}) 0x{:x}->0x{:x}", bar_idx, self.bars[bar_idx].addr, value ); - let old_base = u64::from(self.bars[bar_idx].addr & mask); - let new_base = u64::from(value & mask); - let decoded_len = decode_32_bits_bar_size(self.bars[bar_idx].size)?; - let len = u64::from(decoded_len); - let region_type = bar_type; self.bars[bar_idx].addr = value; - return Some(BarReprogrammingParams { - bar_idx: Some(bar_idx), - old_base, - new_base, - len, - region_type, - }); + return Some(bar_idx); } else if (bar_idx > 0) && self.bars[bar_idx].used && self.bars[bar_idx - 1].r#type == Some(PciBarRegionType::Memory64BitRegion) @@ -1222,25 +1270,12 @@ impl PciConfiguration { "Detected BAR reprogramming: (BAR {}) 0x{:x}->0x{:x}", bar_idx, self.bars[bar_idx].addr, value ); - let old_base = (u64::from(self.bars[bar_idx].addr & mask) << 32) - | u64::from(self.bars[bar_idx - 1].addr & self.writable_bits[reg_idx - 1]); - let new_base = (u64::from(value & mask) << 32) - | u64::from(self.registers[reg_idx - 1] & self.writable_bits[reg_idx - 1]); - let len = - decode_64_bits_bar_size(self.bars[bar_idx].size, self.bars[bar_idx - 1].size)?; - let region_type = PciBarRegionType::Memory64BitRegion; self.bars[bar_idx].addr = value; self.bars[bar_idx - 1].addr = self.registers[reg_idx - 1]; - return Some(BarReprogrammingParams { - // 64-bit BAR is tracked by the lower slot. - bar_idx: Some(bar_idx - 1), - old_base, - new_base, - len, - region_type, - }); + // A 64-bit BAR is keyed by its low slot. + return Some(bar_idx - 1); } } else if reg_idx == ROM_BAR_REG && (value & mask) != (self.rom_bar_addr & mask) { // Ignore the case where the BAR size is being asked for. @@ -1252,21 +1287,10 @@ impl PciConfiguration { "Detected ROM BAR reprogramming: (Expansion ROM BAR) 0x{:x}->0x{:x}", self.rom_bar_addr, value ); - let old_base = u64::from(self.rom_bar_addr & mask); - let new_base = u64::from(value & mask); - let decoded_len = decode_32_bits_bar_size(self.rom_bar_size)?; - let len = u64::from(decoded_len); - let region_type = PciBarRegionType::Memory32BitRegion; self.rom_bar_addr = value; - return Some(BarReprogrammingParams { - bar_idx: Some(ROM_BAR_IDX), - old_base, - new_base, - len, - region_type, - }); + return Some(ROM_BAR_IDX); } None @@ -1292,64 +1316,6 @@ impl PciConfiguration { None => value == BAR_SIZE_PROBE_ALL_ONES, } } - - /// Restore BAR address after a failed move. This undoes the premature - /// address update in detect_bar_reprogramming() so that config space - /// stays consistent with the actual MMIO mapping. - pub fn restore_bar_addr(&mut self, params: &BarReprogrammingParams) { - let i = params - .bar_idx - .expect("bar_idx is set on detection and on restore"); - - if i < NUM_BAR_REGS { - match params.region_type { - PciBarRegionType::Memory64BitRegion => { - // 64-bit BAR spans two slots: bars[i] (low, type Memory64BitRegion) - // and bars[i+1] (high, type None). Mirror detect_bar_reprogramming - // by matching the combined address and restoring both halves. - if i + 1 >= NUM_BAR_REGS - || self.bars[i].r#type != Some(PciBarRegionType::Memory64BitRegion) - { - return; - } - let low_mask = self.writable_bits[BAR0_REG + i]; - let high_mask = self.writable_bits[BAR0_REG + i + 1]; - let current = (u64::from(self.bars[i + 1].addr & high_mask) << 32) - | u64::from(self.bars[i].addr & low_mask); - if current == params.new_base { - let old_low = params.old_base as u32; - let old_high = (params.old_base >> 32) as u32; - self.bars[i].addr = old_low; - self.bars[i + 1].addr = old_high; - self.registers[BAR0_REG + i] = - (self.registers[BAR0_REG + i] & !low_mask) | (old_low & low_mask); - self.registers[BAR0_REG + i + 1] = (self.registers[BAR0_REG + i + 1] - & !high_mask) - | (old_high & high_mask); - } - } - _ => { - // 32-bit Memory or IO BAR - let mask = self.writable_bits[BAR0_REG + i]; - if self.bars[i].r#type == Some(params.region_type) - && u64::from(self.bars[i].addr & mask) == params.new_base - { - let old = params.old_base as u32; - self.bars[i].addr = old; - self.registers[BAR0_REG + i] = - (self.registers[BAR0_REG + i] & !mask) | (old & mask); - } - } - } - } else if i == ROM_BAR_IDX && self.rom_bar_used { - let mask = self.writable_bits[ROM_BAR_REG]; - if u64::from(self.rom_bar_addr & mask) == params.new_base { - let old = params.old_base as u32; - self.registers[ROM_BAR_REG] = (self.registers[ROM_BAR_REG] & !mask) | (old & mask); - self.rom_bar_addr = self.registers[ROM_BAR_REG]; - } - } - } } impl Pausable for PciConfiguration {} @@ -1634,9 +1600,10 @@ mod tests { // A move lands on the aligned address. let reprogram = cfg.write_config_register(BAR0_REG, 0, &0xd008_0000u32.to_le_bytes()); - assert_eq!(reprogram.len(), 1); - assert_eq!(reprogram[0].new_base, 0xd000_0000); + assert_eq!(reprogram.install.len(), 1); + assert_eq!(reprogram.install[0].new_base, 0xd000_0000); assert_eq!(cfg.read_reg(BAR0_REG), 0xd000_0000); + cfg.on_bar_installed(0); // An 8 GiB BAR has no writable address bit in its low half and // none below bit 33 in its high half. @@ -1646,10 +1613,11 @@ mod tests { assert!(reprogram.is_empty()); assert_eq!(cfg.get_bar_addr(2), 0x8_0000_0000); let reprogram = cfg.write_config_register(BAR0_REG + 3, 0, &0xbu32.to_le_bytes()); - assert_eq!(reprogram.len(), 1); - assert_eq!(reprogram[0].new_base, 0xa_0000_0000); + assert_eq!(reprogram.install.len(), 1); + assert_eq!(reprogram.install[0].new_base, 0xa_0000_0000); assert_eq!(cfg.read_reg(BAR0_REG + 3), 0xa); assert_eq!(cfg.get_bar_addr(2), 0xa_0000_0000); + cfg.on_bar_installed(2); let reprogram = cfg.write_config_register(ROM_BAR_REG, 0, &0xf000_8001u32.to_le_bytes()); assert!(reprogram.is_empty()); @@ -1680,8 +1648,8 @@ mod tests { // The bits below the size stay writable, as in the older version. let reprogram = cfg.write_config_register(BAR0_REG, 0, &0xc008_0000u32.to_le_bytes()); - assert_eq!(reprogram.len(), 1); - assert_eq!(reprogram[0].new_base, 0xc008_0000); + assert_eq!(reprogram.install.len(), 1); + assert_eq!(reprogram.install[0].new_base, 0xc008_0000); assert_eq!(cfg.read_reg(BAR0_REG), 0xc008_0000); } @@ -1759,6 +1727,16 @@ mod tests { assert_eq!(&actual_vec[..8], expected); } + // ---- Deferred BAR relocation state machine --------------------------- + + const DEFER_BAR_SIZE: u64 = 0x1000; + const ADDR_A: u64 = 0x1000_0000; + const ADDR_B: u64 = 0x2000_0000; + const ADDR_C: u64 = 0x3000_0000; + const ADDR_D: u64 = 0x4000_0000; + const IOSE: u32 = COMMAND_REG_IO_SPACE_MASK; + const MSE: u32 = COMMAND_REG_MEMORY_SPACE_MASK; + const RELOC_BAR_SIZE: u64 = 0x8_0000; fn reloc_config(state: Option) -> PciConfiguration { @@ -1797,11 +1775,10 @@ mod tests { let reprogram = cfg.write_config_register(BAR0_REG + 1, 0, &0xe000_0000u32.to_le_bytes()); - assert_eq!(reprogram.len(), 1); - assert_eq!(reprogram[0].bar_idx, Some(1)); - assert_eq!(reprogram[0].old_base, 0xd000_0000); - assert_eq!(reprogram[0].new_base, 0xe000_0000); - assert_eq!(reprogram[0].len, RELOC_BAR_SIZE); + assert_eq!(reprogram.install.len(), 1); + assert_eq!(reprogram.install[0].bar_idx, 1); + assert_eq!(reprogram.release[0].bar_idx, 1); + assert_eq!(reprogram.install[0].new_base, 0xe000_0000); } #[test] @@ -1811,37 +1788,21 @@ mod tests { add_reloc_bar(&mut cfg, 1, 0xd000_0000); let aliased = cfg.write_config_register(BAR0_REG, 0, &0xd000_0000u32.to_le_bytes()); - assert_eq!(aliased.len(), 1); - assert_eq!(aliased[0].bar_idx, Some(0)); + assert_eq!(aliased.install.len(), 1); + assert_eq!(aliased.install[0].bar_idx, 0); assert_eq!(cfg.get_bar_addr(0), cfg.get_bar_addr(1)); + // The move lands; otherwise the next write re-emits BAR0's install. + cfg.on_bar_installed(0); let reprogram = cfg.write_config_register(BAR0_REG + 1, 0, &0xe000_0000u32.to_le_bytes()); - assert_eq!(reprogram.len(), 1); - assert_eq!(reprogram[0].bar_idx, Some(1)); - assert_eq!(reprogram[0].old_base, 0xd000_0000); - assert_eq!(reprogram[0].new_base, 0xe000_0000); + assert_eq!(reprogram.install.len(), 1); + assert_eq!(reprogram.install[0].bar_idx, 1); + assert_eq!(reprogram.release[0].bar_idx, 1); + assert_eq!(reprogram.install[0].new_base, 0xe000_0000); assert_eq!(cfg.get_bar_addr(0), 0xd000_0000); } - #[test] - fn failed_bar_move_restores_the_indexed_bar() { - let mut cfg = reloc_config(None); - add_reloc_bar(&mut cfg, 0, 0xc000_0000); - add_reloc_bar(&mut cfg, 1, 0xd000_0000); - - let reprogram = cfg.write_config_register(BAR0_REG + 1, 0, &0xc000_0000u32.to_le_bytes()); - assert_eq!(reprogram.len(), 1); - assert_eq!(reprogram[0].bar_idx, Some(1)); - - cfg.restore_bar_addr(&reprogram[0]); - - assert_eq!(cfg.get_bar_addr(0), 0xc000_0000); - assert_eq!(cfg.read_reg(BAR0_REG), 0xc000_0000); - assert_eq!(cfg.get_bar_addr(1), 0xd000_0000); - assert_eq!(cfg.read_reg(BAR0_REG + 1), 0xd000_0000); - } - #[test] fn bar_reprogramming_of_64bit_bar_reports_the_low_slot() { let mut cfg = reloc_config(None); @@ -1864,13 +1825,10 @@ mod tests { // The high bar address triggers 64-bit bar move. let reprogram = cfg.write_config_register(BAR0_REG + 1, 0, &8u32.to_le_bytes()); - assert_eq!(reprogram.len(), 1); - assert_eq!(reprogram[0].bar_idx, Some(0)); - assert_eq!(reprogram[0].old_base, 0x4_0000_0000); - assert_eq!(reprogram[0].new_base, 0x8_0000_0000); - cfg.restore_bar_addr(&reprogram[0]); - assert_eq!(cfg.get_bar_addr(0), 0x4_0000_0000); - assert_eq!(cfg.read_reg(BAR0_REG + 1), 4); + assert_eq!(reprogram.install.len(), 1); + assert_eq!(reprogram.install[0].bar_idx, 0); + assert_eq!(reprogram.release[0].bar_idx, 0); + assert_eq!(reprogram.install[0].new_base, 0x8_0000_0000); } #[test] @@ -1888,232 +1846,791 @@ mod tests { let reprogram = cfg.write_config_register(ROM_BAR_REG, 0, &0xf100_0000u32.to_le_bytes()); - assert_eq!(reprogram.len(), 1); - assert_eq!(reprogram[0].bar_idx, Some(ROM_BAR_IDX)); - assert_eq!(reprogram[0].old_base, 0xf000_0000); - assert_eq!(reprogram[0].new_base, 0xf100_0000); - cfg.restore_bar_addr(&reprogram[0]); - assert_eq!(cfg.rom_bar_addr, 0xf000_0001); - assert_eq!(cfg.read_reg(ROM_BAR_REG), 0xf000_0001); + assert_eq!(reprogram.install.len(), 1); + assert_eq!(reprogram.install[0].bar_idx, ROM_BAR_IDX); + assert_eq!(reprogram.release[0].bar_idx, ROM_BAR_IDX); + assert_eq!(reprogram.install[0].new_base, 0xf100_0000); } - fn restore_legacy(cfg: &PciConfiguration) -> Vec { - let mut state = cfg.state(); - for p in state.pending_bar_reprogram.iter_mut() { - p.bar_idx = None; + #[test] + fn unused_bar_write_does_not_fabricate_64bit_bar_reprogram() { + let mut cfg = PciConfiguration::new( + 0x1234, + 0x5678, + 0x1, + PciClassCode::MultimediaController, + &PciMultimediaSubclass::AudioController, + None, + PciHeaderType::Device, + 0xABCD, + 0x2468, + None, + None, + ); + let bar_addr = 0xc000_0000; + let bar = PciBarConfiguration::new( + 0, + 0x80000, + PciBarRegionType::Memory32BitRegion, + PciBarPrefetchable::NotPrefetchable, + ) + .set_address(bar_addr); + + cfg.add_pci_bar(&bar).unwrap(); + // Enable memory space decoding. + cfg.write_reg(COMMAND_REG, COMMAND_REG_MEMORY_SPACE_MASK); + + // Step 1: Probe 32-bit BAR 0 size by writing all ones. + cfg.write_config_register(BAR0_REG, 0, &0xffff_ffffu32.to_le_bytes()); + + // Step 2: Write 0 to unused BAR 1. + let reprogram = cfg.write_config_register(BAR0_REG + 1, 0, &0u32.to_le_bytes()); + + // Must not fabricate 64-bit BAR reprogramming on an unused slot. + assert!( + reprogram.is_empty(), + "Must not fabricate phantom 64-bit BAR reprogramming!" + ); + assert_eq!(cfg.get_bar_addr(0), bar_addr); + } + + fn add_mem32_bar(cfg: &mut PciConfiguration, idx: usize, addr: u64) { + cfg.add_pci_bar( + &PciBarConfiguration::default() + .set_index(idx) + .set_address(addr) + .set_size(DEFER_BAR_SIZE) + .set_region_type(PciBarRegionType::Memory32BitRegion) + .set_prefetchable(PciBarPrefetchable::NotPrefetchable), + ) + .unwrap(); + } + + fn add_io_bar(cfg: &mut PciConfiguration, idx: usize, addr: u64, size: u64) { + cfg.add_pci_bar( + &PciBarConfiguration::default() + .set_index(idx) + .set_address(addr) + .set_size(size) + .set_region_type(PciBarRegionType::IoRegion) + .set_prefetchable(PciBarPrefetchable::NotPrefetchable), + ) + .unwrap(); + } + + fn write_bar(cfg: &mut PciConfiguration, bar_idx: usize, addr: u32) -> BarRelocation { + cfg.write_config_register(BAR0_REG + bar_idx, 0, &addr.to_le_bytes()) + } + + fn write_command(cfg: &mut PciConfiguration, value: u32) -> BarRelocation { + cfg.write_config_register(COMMAND_REG, 0, &(value as u16).to_le_bytes()) + } + + /// Report every install of `reloc` as successful, like the bus does. + fn apply_ok(cfg: &mut PciConfiguration, reloc: &BarRelocation) { + for a in &reloc.install { + cfg.on_bar_installed(a.bar_idx); } - reloc_config(Some(state)).pending_bar_reprogram } - fn legacy_pending_move( - idx: usize, - region_type: PciBarRegionType, - prefetchable: PciBarPrefetchable, - old: u64, - new: u64, - ) -> Vec { + /// Swapping two BARs with MSE off only releases them; enabling MSE then + /// installs both in one plan, without a transient overlap. + #[test] + fn test_bar_reprogram_swap_defers_until_mse() { let mut cfg = reloc_config(None); - let size = if region_type == PciBarRegionType::IoRegion { - 0x100 - } else { - RELOC_BAR_SIZE - }; - let bar = PciBarConfiguration::new(idx, size, region_type, prefetchable).set_address(old); - if idx == ROM_BAR_IDX { - cfg.add_pci_rom_bar(&bar, 0).unwrap(); - cfg.write_config_register(ROM_BAR_REG, 0, &(new as u32).to_le_bytes()); - } else { - cfg.add_pci_bar(&bar).unwrap(); - let low = cfg.read_reg(BAR0_REG + idx) & !cfg.writable_bits[BAR0_REG + idx]; - cfg.write_config_register(BAR0_REG + idx, 0, &(new as u32 | low).to_le_bytes()); - if region_type == PciBarRegionType::Memory64BitRegion { - let high = (new >> 32) as u32; - cfg.write_config_register(BAR0_REG + idx + 1, 0, &high.to_le_bytes()); - } - } - assert_eq!(cfg.pending_bar_reprogram.len(), 1); - restore_legacy(&cfg) + add_mem32_bar(&mut cfg, 0, ADDR_A); + add_mem32_bar(&mut cfg, 1, ADDR_B); + + // A fresh device boots with COMMAND == 0: MSE starts cleared. + assert_eq!(cfg.read_config_register(COMMAND_REG) & MSE, 0); + assert!(cfg.bar_installed[0]); + assert_eq!(cfg.get_bar_addr(0), ADDR_A); + assert!(cfg.bar_installed[1]); + assert_eq!(cfg.get_bar_addr(1), ADDR_B); + assert!(cfg.pending_slots().is_empty()); + + // Swap the addresses with MSE off: each write only releases its BAR. + let reloc0 = write_bar(&mut cfg, 0, ADDR_B as u32); + assert_eq!(reloc0.release.len(), 1); + assert_eq!(reloc0.release[0].bar_idx, 0); + assert!(reloc0.install.is_empty(), "install must wait for MSE"); + assert!(!cfg.bar_installed[0]); + assert!(cfg.is_bar_released(0)); + assert!(cfg.bar_installed[1]); + assert_eq!(cfg.get_bar_addr(1), ADDR_B); + + let reloc1 = write_bar(&mut cfg, 1, ADDR_A as u32); + assert_eq!(reloc1.release.len(), 1); + assert_eq!(reloc1.release[0].bar_idx, 1); + assert!(reloc1.install.is_empty(), "install must wait for MSE"); + assert!(!cfg.bar_installed[1]); + assert!(cfg.is_bar_released(1)); + + // Enabling MSE installs both, in slot order, with no release. + let reloc_mse = write_command(&mut cfg, MSE); + assert!(reloc_mse.release.is_empty()); + assert_eq!(reloc_mse.install.len(), 2); + assert_eq!(reloc_mse.install[0].bar_idx, 0); + assert_eq!(reloc_mse.install[0].new_base, ADDR_B); + assert_eq!(reloc_mse.install[1].bar_idx, 1); + assert_eq!(reloc_mse.install[1].new_base, ADDR_A); + + // Only the reported installs update the bookkeeping. + assert!(!cfg.bar_installed[0]); + apply_ok(&mut cfg, &reloc_mse); + assert!(cfg.bar_installed[0]); + assert_eq!(cfg.get_bar_addr(0), ADDR_B); + assert!(cfg.bar_installed[1]); + assert_eq!(cfg.get_bar_addr(1), ADDR_A); + assert!(cfg.pending_slots().is_empty()); + } + + /// Clearing a decode bit releases the mapped BARs of that space; setting + /// it again installs them at their registers. A write that leaves a space + /// undecoded releases nothing: at boot BARs stay mapped until enabled. + #[test] + fn test_command_decode_clear_releases_mapped_bars() { + const IO_ADDR: u64 = 0x1000; + + let mut cfg = reloc_config(None); + add_mem32_bar(&mut cfg, 0, ADDR_A); + add_io_bar(&mut cfg, 1, IO_ADDR, 0x100); + + // COMMAND starts at 0: writing it with both spaces still off is no + // release. + assert!(write_command(&mut cfg, 0).is_empty()); + assert!(cfg.bar_installed[0]); + assert!(cfg.bar_installed[1]); + assert!(write_command(&mut cfg, MSE | IOSE).is_empty()); + + // Clearing MSE releases the memory BAR only. + let reloc = write_command(&mut cfg, IOSE); + assert_eq!(reloc.release.len(), 1); + assert_eq!(reloc.release[0].bar_idx, 0); + assert!(reloc.install.is_empty()); + assert!(cfg.is_bar_released(0)); + assert!(cfg.bar_installed[1]); + + // Rewriting COMMAND with MSE still clear changes nothing. + assert!(write_command(&mut cfg, IOSE).is_empty()); + assert!(cfg.is_bar_released(0)); + + // Setting MSE installs it at its unchanged register. + let reloc = write_command(&mut cfg, MSE | IOSE); + assert!(reloc.release.is_empty()); + assert_eq!(reloc.install.len(), 1); + assert_eq!(reloc.install[0].bar_idx, 0); + assert_eq!(reloc.install[0].new_base, ADDR_A); + apply_ok(&mut cfg, &reloc); + assert!(cfg.bar_installed[0]); + + // Clearing IOSE releases the IO BAR only. + let reloc = write_command(&mut cfg, MSE); + assert_eq!(reloc.release.len(), 1); + assert_eq!(reloc.release[0].bar_idx, 1); + assert!(reloc.install.is_empty()); + assert!(cfg.bar_installed[0]); + assert!(cfg.is_bar_released(1)); + + // One write swapping the decodes releases and installs at once. + let reloc = write_command(&mut cfg, IOSE); + assert_eq!(reloc.release.len(), 1); + assert_eq!(reloc.release[0].bar_idx, 0); + assert_eq!(reloc.install.len(), 1); + assert_eq!(reloc.install[0].bar_idx, 1); + assert_eq!(reloc.install[0].new_base, IO_ADDR); + } + + /// A 64-bit BAR moved low dword first with MSE off is released by the + /// high-dword write, under its low slot. + #[test] + fn test_bar_reprogram_64bit_defers_until_mse() { + const OLD_ADDR: u64 = 0x2_0000_0000; + const NEW_LOW: u32 = 0x3000_0000; + const NEW_HIGH: u32 = 0x3; + const NEW_ADDR: u64 = ((NEW_HIGH as u64) << 32) | NEW_LOW as u64; + + let mut cfg = reloc_config(None); + cfg.add_pci_bar( + &PciBarConfiguration::default() + .set_index(0) + .set_address(OLD_ADDR) + .set_size(0x2000) + .set_region_type(PciBarRegionType::Memory64BitRegion) + .set_prefetchable(PciBarPrefetchable::Prefetchable), + ) + .unwrap(); + + // Bookkeeping lives on the LOW slot; the HIGH slot has none. + assert!(cfg.bar_installed[0]); + assert_eq!(cfg.get_bar_addr(0), OLD_ADDR); + assert!(!cfg.bar_installed[1]); + + // The low-dword write alone emits nothing. + let reloc_low = write_bar(&mut cfg, 0, NEW_LOW); + assert!(reloc_low.is_empty()); + + // The high-dword write releases the BAR under its low slot. + let reloc_high = write_bar(&mut cfg, 1, NEW_HIGH); + assert_eq!(reloc_high.release.len(), 1); + assert_eq!(reloc_high.release[0].bar_idx, 0); + assert!(reloc_high.install.is_empty()); + assert!(!cfg.bar_installed[0]); + assert!(cfg.is_bar_released(0)); + + // Enabling MSE installs at the full 64-bit address. + let reloc_mse = write_command(&mut cfg, MSE); + assert!(reloc_mse.release.is_empty()); + assert_eq!(reloc_mse.install.len(), 1); + assert_eq!(reloc_mse.install[0].bar_idx, 0); + assert_eq!(reloc_mse.install[0].new_base, NEW_ADDR); + + apply_ok(&mut cfg, &reloc_mse); + assert!(cfg.bar_installed[0]); + assert_eq!(cfg.get_bar_addr(0), NEW_ADDR); + assert!(cfg.pending_slots().is_empty()); + } + + /// A 64-bit BAR moved high dword first: the install target comes from the + /// registers, as the later low-dword write is not seen as a move. + #[test] + fn test_bar_reprogram_64bit_high_dword_first() { + const OLD_ADDR: u64 = 0x2_0000_0000; + const NEW_LOW: u32 = 0x3000_0000; + const NEW_HIGH: u32 = 0x3; + const NEW_ADDR: u64 = ((NEW_HIGH as u64) << 32) | NEW_LOW as u64; + + let mut cfg = reloc_config(None); + cfg.add_pci_bar( + &PciBarConfiguration::default() + .set_index(0) + .set_address(OLD_ADDR) + .set_size(0x2000) + .set_region_type(PciBarRegionType::Memory64BitRegion) + .set_prefetchable(PciBarPrefetchable::Prefetchable), + ) + .unwrap(); + + // The high-dword write releases the BAR. + let reloc_high = write_bar(&mut cfg, 1, NEW_HIGH); + assert_eq!(reloc_high.release.len(), 1); + assert_eq!(reloc_high.release[0].bar_idx, 0); + assert!(cfg.is_bar_released(0)); + + // The low-dword write only updates the register. + let reloc_low = write_bar(&mut cfg, 0, NEW_LOW); + assert!(reloc_low.is_empty()); + + // The install uses both new dwords. + let reloc_mse = write_command(&mut cfg, MSE); + assert_eq!(reloc_mse.install.len(), 1); + assert_eq!( + reloc_mse.install[0].new_base, NEW_ADDR, + "install target must be assembled from the live registers" + ); } + /// With MSE on, a BAR write releases and installs in one plan. #[test] - fn legacy_pending_move_recovers_the_bar_index() { - use PciBarPrefetchable::{NotPrefetchable, Prefetchable}; - use PciBarRegionType::{IoRegion, Memory32BitRegion, Memory64BitRegion}; + fn test_bar_reprogram_immediate_when_mse_on() { + let mut cfg = reloc_config(None); + add_mem32_bar(&mut cfg, 0, ADDR_A); + assert!(write_command(&mut cfg, MSE).is_empty()); + + let reloc = write_bar(&mut cfg, 0, ADDR_B as u32); + assert_eq!(reloc.release.len(), 1); + assert_eq!(reloc.release[0].bar_idx, 0); + assert_eq!(reloc.install.len(), 1); + assert_eq!(reloc.install[0].new_base, ADDR_B); + + // Released until the install is reported. + assert!(!cfg.bar_installed[0]); + assert!(cfg.is_bar_released(0)); + apply_ok(&mut cfg, &reloc); + assert!(cfg.bar_installed[0]); + assert_eq!(cfg.get_bar_addr(0), ADDR_B); + assert!(cfg.pending_slots().is_empty()); + } + + /// Rewriting a released BAR emits no second release; the install targets + /// the last written address. + #[test] + fn test_bar_rewrite_while_released_keeps_release_base() { + let mut cfg = reloc_config(None); + add_mem32_bar(&mut cfg, 0, ADDR_A); - let cases = [ - ( - 1, - Memory32BitRegion, - NotPrefetchable, - 0xd000_0000, - 0xe000_0000, - ), - (1, Memory32BitRegion, Prefetchable, 0xd000_0000, 0xe000_0000), - (1, IoRegion, NotPrefetchable, 0xc000, 0xd000), - ( - 0, - Memory64BitRegion, - Prefetchable, - 0x4_0000_0000, - 0x8_0000_0000, - ), - ( - 1, - Memory64BitRegion, - NotPrefetchable, - 0x4_0000_0000, - 0x8_0000_0000, - ), - ( - ROM_BAR_IDX, - Memory32BitRegion, - NotPrefetchable, - 0xf000_0000, - 0xf100_0000, - ), - ]; - for (idx, region_type, prefetchable, old, new) in cases { - let pending = legacy_pending_move(idx, region_type, prefetchable, old, new); - assert_eq!(pending.len(), 1, "BAR {idx} {region_type:?}"); - assert_eq!(pending[0].bar_idx, Some(idx), "BAR {idx} {region_type:?}"); - assert_eq!(pending[0].old_base, old); - assert_eq!(pending[0].new_base, new); - } + let first = write_bar(&mut cfg, 0, ADDR_B as u32); + assert_eq!(first.release.len(), 1); + + let second = write_bar(&mut cfg, 0, ADDR_C as u32); + assert!( + second.is_empty(), + "rewrite while released must not release again" + ); + assert!(cfg.is_bar_released(0)); + + let reloc_mse = write_command(&mut cfg, MSE); + assert_eq!(reloc_mse.install.len(), 1); + assert_eq!(reloc_mse.install[0].new_base, ADDR_C); } + /// Writing back the original address while released installs there. #[test] - fn legacy_chained_moves_resolve_to_the_same_bar() { + fn test_bar_write_back_to_original_then_enable() { let mut cfg = reloc_config(None); - add_reloc_bar(&mut cfg, 0, 0xc000_0000); - add_reloc_bar(&mut cfg, 1, 0xd000_0000); - cfg.write_reg(COMMAND_REG, 0); + add_mem32_bar(&mut cfg, 0, ADDR_A); - cfg.write_config_register(BAR0_REG + 1, 0, &0xf000_0000u32.to_le_bytes()); - let mut state = cfg.state(); - let mut first = state.pending_bar_reprogram[0]; - first.bar_idx = None; - first.new_base = 0xe000_0000; - let mut second = first; - second.old_base = first.new_base; - second.new_base = 0xf000_0000; - state.pending_bar_reprogram = vec![first, second]; + write_bar(&mut cfg, 0, ADDR_B as u32); + assert!(write_bar(&mut cfg, 0, ADDR_A as u32).is_empty()); - let pending = reloc_config(Some(state)).pending_bar_reprogram; + let reloc_mse = write_command(&mut cfg, MSE); + assert_eq!(reloc_mse.install.len(), 1); + assert_eq!(reloc_mse.install[0].new_base, ADDR_A); + } - assert_eq!(pending.len(), 1); - assert_eq!(pending[0].bar_idx, Some(1)); - assert_eq!(pending[0].old_base, 0xd000_0000); - assert_eq!(pending[0].new_base, 0xf000_0000); + /// Rewriting the same address into a released BAR is no move, but it + /// retries the failed install all the same. + #[test] + fn test_same_address_rewrite_retries_failed_install() { + let mut cfg = reloc_config(None); + add_mem32_bar(&mut cfg, 0, ADDR_A); + assert!(write_command(&mut cfg, MSE).is_empty()); + + // The move's install fails: the BAR stays released. + let reloc = write_bar(&mut cfg, 0, ADDR_B as u32); + assert_eq!(reloc.install.len(), 1); + assert!(cfg.is_bar_released(0)); + + let again = write_bar(&mut cfg, 0, ADDR_B as u32); + assert!(again.release.is_empty()); + assert_eq!(again.install.len(), 1); + assert_eq!(again.install[0].bar_idx, 0); + assert_eq!(again.install[0].new_base, ADDR_B); } + /// A failed install is retried, with the device's other released BARs, by + /// its next BAR or COMMAND write. #[test] - fn deferred_bar_moves_preserve_the_mapped_address() { + fn test_failed_install_retries_on_bar_and_command_writes() { let mut cfg = reloc_config(None); - add_reloc_bar(&mut cfg, 0, 0xc000_0000); - add_reloc_bar(&mut cfg, 1, 0xd000_0000); - cfg.write_reg(COMMAND_REG, 0); - - for i in 1..=128u32 { - for idx in 0..2 { - let address = 0xe000_0000 + (idx as u32 * 0x100 + i) * RELOC_BAR_SIZE as u32; - assert!( - cfg.write_config_register(BAR0_REG + idx, 0, &address.to_le_bytes()) - .is_empty() - ); - } - assert_eq!(cfg.pending_bar_reprogram.len(), 2); - } - let pending = - cfg.write_config_register(COMMAND_REG, 0, &COMMAND_REG_MEMORY_SPACE_MASK.to_le_bytes()); - assert_eq!(pending.len(), 2); - for (idx, param) in pending.iter().enumerate() { - assert_eq!(param.bar_idx, Some(idx)); - assert_eq!(param.old_base, 0xc000_0000 + idx as u64 * 0x1000_0000); - assert_eq!(param.new_base, cfg.get_bar_addr(idx)); - cfg.restore_bar_addr(param); - assert_eq!(cfg.get_bar_addr(idx), param.old_base); - } + add_mem32_bar(&mut cfg, 0, ADDR_A); + + write_bar(&mut cfg, 0, ADDR_B as u32); + let first_edge = write_command(&mut cfg, MSE); + assert_eq!(first_edge.install.len(), 1); + + // The install failed: nothing is mapped, the slot stays released. + assert!(!cfg.bar_installed[0]); + assert!(cfg.is_bar_released(0)); + + // A COMMAND write with MSE already set re-emits the install. + let command = write_command(&mut cfg, MSE); + assert!(command.release.is_empty()); + assert_eq!(command.install.len(), 1); + assert_eq!(command.install[0].bar_idx, 0); + assert_eq!(command.install[0].new_base, ADDR_B); + + // Rewriting the released BAR installs at the new target. + let rewrite = write_bar(&mut cfg, 0, ADDR_C as u32); + assert!(rewrite.release.is_empty()); + assert_eq!(rewrite.install.len(), 1); + assert_eq!(rewrite.install[0].bar_idx, 0); + assert_eq!(rewrite.install[0].new_base, ADDR_C); + + // Moving another, installed BAR also retries the failed one. + add_mem32_bar(&mut cfg, 1, ADDR_D); + assert!(cfg.bar_installed[1]); + let other = write_bar(&mut cfg, 1, ADDR_B as u32); + assert_eq!(other.release.len(), 1); + assert_eq!(other.release[0].bar_idx, 1); + assert_eq!(other.install.len(), 2); + assert_eq!(other.install[0].bar_idx, 0); + assert_eq!(other.install[0].new_base, ADDR_C); + assert_eq!(other.install[1].bar_idx, 1); + assert_eq!(other.install[1].new_base, ADDR_B); + + apply_ok(&mut cfg, &other); + assert!(cfg.bar_installed[0]); + assert!(cfg.bar_installed[1]); + assert!(cfg.pending_slots().is_empty()); + assert_eq!(cfg.get_bar_addr(0), ADDR_C); + assert_eq!(cfg.get_bar_addr(1), ADDR_B); + } + + /// Other config writes do not retry a failed install. + #[test] + fn test_unrelated_config_write_does_not_retry() { + let mut cfg = reloc_config(None); + add_mem32_bar(&mut cfg, 0, ADDR_A); + + write_bar(&mut cfg, 0, ADDR_B as u32); + let first_edge = write_command(&mut cfg, MSE); + assert_eq!(first_edge.install.len(), 1); + assert!(cfg.is_bar_released(0)); + + // Interrupt line register. + let reloc = cfg.write_config_register(15, 0, &0u32.to_le_bytes()); + assert!(reloc.is_empty()); + assert!(cfg.is_bar_released(0)); } + /// pending_bar_installs() lists only released BARs whose space is decoded. #[test] - fn deferred_bar_move_back_to_mapped_address_is_a_noop() { + fn test_pending_bar_installs_follows_decode() { let mut cfg = reloc_config(None); - add_reloc_bar(&mut cfg, 0, 0xc000_0000); - cfg.write_reg(COMMAND_REG, 0); - cfg.write_config_register(BAR0_REG, 0, &0xd000_0000u32.to_le_bytes()); - cfg.write_config_register(BAR0_REG, 0, &0xc000_0000u32.to_le_bytes()); - assert!(cfg.pending_bar_reprogram.is_empty()); - assert!(cfg.write_config_register( - COMMAND_REG, 0, &COMMAND_REG_MEMORY_SPACE_MASK.to_le_bytes(), - ).is_empty()); + add_mem32_bar(&mut cfg, 0, ADDR_A); + + write_bar(&mut cfg, 0, ADDR_B as u32); + assert!(cfg.pending_bar_installs().is_empty()); + + let reloc = write_command(&mut cfg, MSE); + let pending = cfg.pending_bar_installs(); + assert_eq!(pending.len(), 1); + assert_eq!(pending[0].bar_idx, 0); + assert_eq!(pending[0].new_base, ADDR_B); + + apply_ok(&mut cfg, &reloc); + assert!(cfg.pending_bar_installs().is_empty()); } + /// A released BAR is not installed while the guest is sizing it. #[test] - fn legacy_pending_move_without_a_match_is_dropped() { + fn test_size_probe_of_released_bar_is_not_installed() { let mut cfg = reloc_config(None); - add_reloc_bar(&mut cfg, 0, 0xc000_0000); - let mut state = cfg.state(); - state.pending_bar_reprogram.push(BarReprogrammingParams { - bar_idx: None, - old_base: 0xa000_0000, - new_base: 0xb000_0000, - len: RELOC_BAR_SIZE, - region_type: PciBarRegionType::Memory32BitRegion, - }); + add_mem32_bar(&mut cfg, 0, ADDR_A); + assert!(write_command(&mut cfg, MSE).is_empty()); - assert!(reloc_config(Some(state)).pending_bar_reprogram.is_empty()); + // Moved with decoding on; the install is not reported back (failed). + let moved = write_bar(&mut cfg, 0, ADDR_B as u32); + assert_eq!(moved.release.len(), 1); + assert_eq!(moved.install.len(), 1); + assert!(cfg.is_bar_released(0)); + + // The probe is not a move and installs nothing. + assert!(write_bar(&mut cfg, 0, 0xffff_ffff).is_empty()); + assert!(cfg.is_bar_released(0)); + + // Writing the address back ends the sizing and retries the install. + let retry = write_bar(&mut cfg, 0, ADDR_B as u32); + assert!(retry.release.is_empty()); + assert_eq!(retry.install.len(), 1); + assert_eq!(retry.install[0].new_base, ADDR_B); + apply_ok(&mut cfg, &retry); + assert!(cfg.pending_slots().is_empty()); } + /// The same for the expansion ROM, whose probe sets the enable bit too. #[test] - fn decode_bar_size_requires_power_of_two() { - assert_eq!(decode_32_bits_bar_size(0xfff8_0000), Some(0x80000)); - assert_eq!(decode_32_bits_bar_size(0xffff_fffa), None); + fn test_size_probe_of_released_rom_bar_is_not_installed() { + const ROM_OLD: u64 = 0x4000_0000; + const ROM_NEW: u64 = 0x4100_0000; + const ROM_SIZE: u64 = 0x1_0000; + + let mut cfg = reloc_config(None); + cfg.add_pci_rom_bar( + &PciBarConfiguration::default() + .set_index(ROM_BAR_IDX) + .set_address(ROM_OLD) + .set_size(ROM_SIZE) + .set_region_type(PciBarRegionType::Memory32BitRegion) + .set_prefetchable(PciBarPrefetchable::NotPrefetchable), + 0x1, + ) + .unwrap(); + assert!(write_command(&mut cfg, MSE).is_empty()); + + let moved = + cfg.write_config_register(ROM_BAR_REG, 0, &(ROM_NEW as u32 | 0x1).to_le_bytes()); + assert_eq!(moved.release.len(), 1); + assert!(cfg.is_bar_released(ROM_BAR_IDX)); + + assert!( + cfg.write_config_register(ROM_BAR_REG, 0, &0xffff_ffffu32.to_le_bytes()) + .is_empty() + ); + assert!(cfg.is_bar_released(ROM_BAR_IDX)); + + let retry = + cfg.write_config_register(ROM_BAR_REG, 0, &(ROM_NEW as u32 | 0x1).to_le_bytes()); + assert!(retry.release.is_empty()); + assert_eq!(retry.install.len(), 1); + assert_eq!(retry.install[0].bar_idx, ROM_BAR_IDX); + assert_eq!(retry.install[0].new_base, ROM_NEW); + } + + /// A released 64-bit BAR of 4 GiB or more is installed again: its low + /// dword at rest is also what its size probe reads back. + #[test] + fn test_released_64bit_bar_of_4g_or_more_reinstalls() { + const SIZE: u64 = 64 << 30; + const ADDR: u64 = 0x40_0000_0000; + + let mut cfg = reloc_config(None); + cfg.add_pci_bar( + &PciBarConfiguration::default() + .set_index(0) + .set_address(ADDR) + .set_size(SIZE) + .set_region_type(PciBarRegionType::Memory64BitRegion) + .set_prefetchable(PciBarPrefetchable::Prefetchable), + ) + .unwrap(); + assert!(write_command(&mut cfg, MSE).is_empty()); + + // Disabled and enabled again: released, then owed its install. + let cleared = write_command(&mut cfg, 0); + assert_eq!(cleared.release.len(), 1); + assert!(cfg.is_bar_released(0)); + let enabled = write_command(&mut cfg, MSE); + assert_eq!(enabled.install.len(), 1); + assert_eq!(enabled.install[0].bar_idx, 0); + assert_eq!(enabled.install[0].new_base, ADDR); + + // A probe of either dword installs nothing; the write-back does. + apply_ok(&mut cfg, &enabled); + assert!(write_command(&mut cfg, 0).release.len() == 1); + assert!(write_command(&mut cfg, MSE).install.len() == 1); + assert!(cfg.is_bar_released(0)); + assert!(write_bar(&mut cfg, 1, 0xffff_ffff).is_empty()); + let back = write_bar(&mut cfg, 1, (ADDR >> 32) as u32); + assert_eq!(back.install.len(), 1); + assert_eq!(back.install[0].new_base, ADDR); + } + + /// A BAR in the last slot of its size below a 4 GiB boundary reads like + /// its own size probe at rest, and is installed again all the same. + #[test] + fn test_released_bar_in_top_slot_below_4g_reinstalls() { + const SIZE: u64 = 2 << 20; + const ADDR: u64 = 0x41_0000_0000 - SIZE; + + let mut cfg = reloc_config(None); + cfg.add_pci_bar( + &PciBarConfiguration::default() + .set_index(0) + .set_address(ADDR) + .set_size(SIZE) + .set_region_type(PciBarRegionType::Memory64BitRegion) + .set_prefetchable(PciBarPrefetchable::Prefetchable), + ) + .unwrap(); + assert!(write_command(&mut cfg, MSE).is_empty()); assert_eq!( - decode_64_bits_bar_size(0xffff_ffff, 0xfff8_0000), - Some(0x80000) + cfg.read_config_register(BAR0_REG) & 0xffff_fff0, + 0xffe0_0000 ); - assert_eq!(decode_64_bits_bar_size(0xffff_ffff, 0xffff_fffa), None); + + assert_eq!(write_command(&mut cfg, 0).release.len(), 1); + let enabled = write_command(&mut cfg, MSE); + assert_eq!(enabled.install.len(), 1); + assert_eq!(enabled.install[0].new_base, ADDR); } + /// IO BARs are gated on IOSE and memory BARs on MSE. #[test] - fn unused_bar_write_does_not_fabricate_64bit_bar_reprogram() { - let mut cfg = PciConfiguration::new( - 0x1234, - 0x5678, + fn test_io_bar_gated_on_iose_not_mse() { + const IO_OLD: u64 = 0x1000; + const IO_NEW: u64 = 0x2000; + + let mut cfg = reloc_config(None); + add_io_bar(&mut cfg, 0, IO_OLD, 0x100); + add_mem32_bar(&mut cfg, 1, ADDR_A); + + // Move both BARs with all decode off. + let io_reloc = write_bar(&mut cfg, 0, IO_NEW as u32); + assert_eq!(io_reloc.release.len(), 1); + assert_eq!(io_reloc.release[0].bar_idx, 0); + let mem_reloc = write_bar(&mut cfg, 1, ADDR_B as u32); + assert_eq!(mem_reloc.release.len(), 1); + + // MSE alone drains only the memory BAR. + let mse_edge = write_command(&mut cfg, MSE); + assert_eq!(mse_edge.install.len(), 1); + assert_eq!(mse_edge.install[0].bar_idx, 1); + apply_ok(&mut cfg, &mse_edge); + assert!(cfg.is_bar_released(0)); + + // IOSE drains the IO BAR. + let iose_edge = write_command(&mut cfg, MSE | IOSE); + assert_eq!(iose_edge.install.len(), 1); + assert_eq!(iose_edge.install[0].bar_idx, 0); + assert_eq!(iose_edge.install[0].new_base, IO_NEW); + apply_ok(&mut cfg, &iose_edge); + assert!(cfg.pending_slots().is_empty()); + + // And a single write raising both bits drains both spaces. + let mut cfg2 = reloc_config(None); + add_io_bar(&mut cfg2, 0, IO_OLD, 0x100); + add_mem32_bar(&mut cfg2, 1, ADDR_A); + write_bar(&mut cfg2, 0, IO_NEW as u32); + write_bar(&mut cfg2, 1, ADDR_B as u32); + let both_edge = write_command(&mut cfg2, MSE | IOSE); + assert_eq!(both_edge.install.len(), 2); + } + + /// The expansion ROM defers on MSE like a memory BAR, under ROM_BAR_IDX. + #[test] + fn test_rom_bar_reprogram_defers_until_mse() { + const ROM_OLD: u64 = 0x4000_0000; + const ROM_NEW: u64 = 0x4100_0000; + const ROM_SIZE: u64 = 0x1_0000; + + let mut cfg = reloc_config(None); + cfg.add_pci_rom_bar( + &PciBarConfiguration::default() + .set_index(ROM_BAR_IDX) + .set_address(ROM_OLD) + .set_size(ROM_SIZE) + .set_region_type(PciBarRegionType::Memory32BitRegion) + .set_prefetchable(PciBarPrefetchable::NotPrefetchable), 0x1, - PciClassCode::MultimediaController, - &PciMultimediaSubclass::AudioController, - None, - PciHeaderType::Device, - 0xABCD, - 0x2468, - None, - None, - ); - let bar_addr = 0xc000_0000; - let bar = PciBarConfiguration::new( - 0, - 0x80000, - PciBarRegionType::Memory32BitRegion, - PciBarPrefetchable::NotPrefetchable, ) - .set_address(bar_addr); + .unwrap(); + assert!(cfg.bar_installed[ROM_BAR_IDX]); + assert_eq!(u64::from(cfg.rom_bar_addr & ROM_BAR_ADDR_MASK), ROM_OLD); + + let reloc = + cfg.write_config_register(ROM_BAR_REG, 0, &(ROM_NEW as u32 | 0x1).to_le_bytes()); + assert_eq!(reloc.release.len(), 1); + assert_eq!(reloc.release[0].bar_idx, ROM_BAR_IDX); + assert!(reloc.install.is_empty()); + assert!(!cfg.bar_installed[ROM_BAR_IDX]); + assert!(cfg.is_bar_released(ROM_BAR_IDX)); + + let reloc_mse = write_command(&mut cfg, MSE); + assert_eq!(reloc_mse.install.len(), 1); + assert_eq!(reloc_mse.install[0].bar_idx, ROM_BAR_IDX); + assert_eq!(reloc_mse.install[0].new_base, ROM_NEW); + + apply_ok(&mut cfg, &reloc_mse); + assert!(cfg.bar_installed[ROM_BAR_IDX]); + assert_eq!(u64::from(cfg.rom_bar_addr & ROM_BAR_ADDR_MASK), ROM_NEW); + assert!(cfg.pending_slots().is_empty()); + } + + /// A BAR released at snapshot time restores mapped at its old address, + /// is released again by release_stale_bar() as its space is undecoded, + /// and is installed at its target once decoding is enabled. + #[test] + fn test_mid_window_snapshot_restore_leaves_bar_unmapped_until_enable() { + let mut cfg = reloc_config(None); + add_mem32_bar(&mut cfg, 0, ADDR_A); + write_bar(&mut cfg, 0, ADDR_B as u32); + assert!(cfg.is_bar_released(0)); + + let state = cfg.state(); + let mut restored = reloc_config(Some(state)); + + // Restored mapped at the old address, with the register holding the + // target; the VMM then releases it. + assert!(restored.bar_installed[0]); + assert!(restored.release_stale_bar(0, ADDR_A)); + assert!(!restored.bar_installed[0]); + assert_eq!(restored.pending_slots(), vec![0]); + assert_eq!( + u64::from(restored.read_config_register(BAR0_REG) & 0xffff_fff0), + ADDR_B + ); - cfg.add_pci_bar(&bar).unwrap(); - // Enable memory space decoding. - cfg.write_reg(COMMAND_REG, COMMAND_REG_MEMORY_SPACE_MASK); + // The post-restore enable edge installs at the target only. + let reloc_mse = write_command(&mut restored, MSE); + assert!(reloc_mse.release.is_empty(), "nothing is mapped to release"); + assert_eq!(reloc_mse.install.len(), 1); + assert_eq!(reloc_mse.install[0].bar_idx, 0); + assert_eq!(reloc_mse.install[0].new_base, ADDR_B); - // Step 1: Probe 32-bit BAR 0 size by writing all ones. - cfg.write_config_register(BAR0_REG, 0, &0xffff_ffffu32.to_le_bytes()); + apply_ok(&mut restored, &reloc_mse); + assert!(restored.bar_installed[0]); + assert_eq!(restored.get_bar_addr(0), ADDR_B); + assert!(restored.pending_slots().is_empty()); + } - // Step 2: Write 0 to unused BAR 1. - let reprogram = cfg.write_config_register(BAR0_REG + 1, 0, &0u32.to_le_bytes()); + /// Legacy in-flight entries from old snapshots are ignored. + #[test] + fn test_legacy_snapshot_pending_entries_are_ignored() { + let mut cfg = reloc_config(None); + add_mem32_bar(&mut cfg, 0, ADDR_A); + add_mem32_bar(&mut cfg, 3, ADDR_B); - // Must not fabricate 64-bit BAR reprogramming on an unused slot. + // Move BAR 3 (not BAR 0!) while decode is off. + const TARGET: u64 = 0x3000_0000; + write_bar(&mut cfg, 3, TARGET as u32); + + let mut state = cfg.state(); + assert!(state.pending_bar_reprogram.is_empty()); + // A legacy entry without bar_idx. + state.pending_bar_reprogram.push(BarReprogrammingParams { + bar_idx: None, + old_base: ADDR_B, + new_base: TARGET, + len: DEFER_BAR_SIZE, + region_type: PciBarRegionType::Memory32BitRegion, + }); + + let mut cfg = reloc_config(Some(state)); + + // The entry has no effect: both BARs restore mapped at their old + // addresses and the VMM releases both, as their space is undecoded. + assert!(cfg.pending_slots().is_empty()); + assert!(cfg.release_stale_bar(0, ADDR_A)); + assert!(cfg.release_stale_bar(3, ADDR_B)); + assert_eq!(cfg.pending_slots(), vec![0, 3]); + assert_eq!( + u64::from(cfg.read_config_register(BAR0_REG) & 0xffff_fff0), + ADDR_A + ); + assert_eq!( + u64::from(cfg.read_config_register(BAR0_REG + 3) & 0xffff_fff0), + TARGET + ); + + // The enable edge installs both at their registers' targets. + let reloc_mse = write_command(&mut cfg, MSE); + assert!(reloc_mse.release.is_empty()); + assert_eq!(reloc_mse.install.len(), 2); + assert_eq!(reloc_mse.install[0].bar_idx, 0); + assert_eq!(reloc_mse.install[0].new_base, ADDR_A); + assert_eq!(reloc_mse.install[1].bar_idx, 3); + assert_eq!(reloc_mse.install[1].new_base, TARGET); + } + + /// After a restore, release_stale_bar() keeps only the decoded BARs + /// that are mapped at their registers. + #[test] + fn test_release_stale_bar_keeps_only_decoded_bars_at_their_register() { + let mut cfg = reloc_config(None); + add_mem32_bar(&mut cfg, 0, ADDR_A); + add_mem32_bar(&mut cfg, 1, ADDR_B); + write_command(&mut cfg, MSE); + + // A restored device starts mapped at its saved addresses, so its own + // COMMAND write before the VMM settles the BARs plans nothing (pvpanic + // enables its spaces at creation). + let mut restored = reloc_config(Some(cfg.state())); + assert!(restored.pending_slots().is_empty()); + assert!(write_command(&mut restored, MSE | IOSE).is_empty()); + + // Decoded and mapped where the register says: kept. Mapped elsewhere + // (a failed install was pending): released, and owed an install at + // the register. + assert!(!restored.release_stale_bar(0, ADDR_A)); + assert!(restored.bar_installed[0]); + assert!(restored.release_stale_bar(1, ADDR_C)); + assert!(restored.is_bar_released(1)); + let pending = restored.pending_bar_installs(); + assert_eq!(pending.len(), 1); + assert_eq!(pending[0].bar_idx, 1); + assert_eq!(pending[0].new_base, ADDR_B); assert!( - reprogram.is_empty(), - "Must not fabricate phantom 64-bit BAR reprogramming!" + !restored.release_stale_bar(ROM_BAR_IDX, 0), + "no ROM BAR to restore" ); - assert_eq!(cfg.get_bar_addr(0), bar_addr); + + // Undecoded: released, with no install owed until MSE is set. + write_command(&mut cfg, 0); + let mut restored = reloc_config(Some(cfg.state())); + assert!(restored.release_stale_bar(0, ADDR_A)); + assert!(restored.is_bar_released(0)); + assert!(restored.pending_bar_installs().is_empty()); } } diff --git a/pci/src/device.rs b/pci/src/device.rs index 13ced7b9e3..06d1acc010 100644 --- a/pci/src/device.rs +++ b/pci/src/device.rs @@ -8,13 +8,11 @@ use std::any::Any; use std::sync::{Arc, Barrier}; use std::{io, result}; -use serde::{Deserialize, Serialize}; use thiserror::Error; use vm_allocator::{AddressAllocator, SystemAllocator}; -use vm_device::Resource; +use vm_device::{BusDeviceSync, Resource}; -use crate::configuration::{self, PciBarRegionType}; -use crate::{PciBarConfiguration, PciBdf}; +use crate::{PciBarConfiguration, PciBdf, configuration}; #[derive(Error, Debug)] pub enum Error { @@ -36,14 +34,29 @@ pub enum Error { } pub(crate) type Result = result::Result; -#[derive(Clone, Copy, Debug, Serialize, Deserialize)] -pub struct BarReprogrammingParams { - #[serde(default)] - pub bar_idx: Option, - pub old_base: u64, +/// A BAR whose current location is to be released. +#[derive(Clone, Copy, Debug)] +pub struct ReleaseParams { + pub bar_idx: usize, +} + +/// A BAR to install at new_base. +#[derive(Clone, Copy, Debug)] +pub struct InstallParams { + pub bar_idx: usize, pub new_base: u64, - pub len: u64, - pub region_type: PciBarRegionType, +} + +#[derive(Clone, Debug, Default)] +pub struct BarRelocation { + pub release: Vec, + pub install: Vec, +} + +impl BarRelocation { + pub fn is_empty(&self) -> bool { + self.release.is_empty() && self.install.is_empty() + } } pub trait PciDevice: Send { @@ -77,7 +90,7 @@ pub trait PciDevice: Send { reg_idx: usize, offset: u64, data: &[u8], - ) -> (Vec, Option>); + ) -> (BarRelocation, Option>); /// Gets a register from the configuration space. /// * `reg_idx` - The index of the config register to read. fn read_config_register(&mut self, reg_idx: usize) -> u32; @@ -91,14 +104,30 @@ pub trait PciDevice: Send { fn write_bar(&mut self, _base: u64, _offset: u64, _data: &[u8]) -> Option> { None } - /// Relocates the BAR to a different address in guest address space. - fn move_bar(&mut self, _bar_idx: usize, _new_base: u64) -> result::Result<(), io::Error> { + /// Tear down the device's host-side resource for the BAR at its old base. + fn move_bar_prepare(&mut self, _bar_idx: usize) -> result::Result<(), io::Error> { Ok(()) } - /// Restore BAR address in config space after a failed move_bar. - /// This rolls back the address update made by detect_bar_reprogramming() - /// so that the config register stays consistent with the MMIO bus mapping. - fn restore_bar_addr(&mut self, _params: &BarReprogrammingParams) {} + /// Set up the device's host-side resource at `new_base` and record it. + fn move_bar_commit( + &mut self, + _bar_idx: usize, + _new_base: u64, + ) -> result::Result<(), io::Error> { + Ok(()) + } + /// On restore, release BAR `bar_idx` unless its space is decoded and its + /// register names `mapped_at`, the saved address it is about to be + /// mapped at. Return whether it was released, so that the VMM leaves it + /// unmapped; a decoded BAR is then installed at its register. + fn release_stale_bar(&mut self, bar_idx: usize, mapped_at: u64) -> bool; + /// Whether BAR `bar_idx` is released, i.e. not mapped. + fn is_bar_released(&self, bar_idx: usize) -> bool; + /// BAR `bar_idx` is now mapped at its config-space address. + fn on_bar_installed(&mut self, bar_idx: usize); + /// The installs owed to the guest: released BARs whose space is + /// decoded, at their registers. + fn pending_bar_installs(&self) -> Vec; /// Provides a mutable reference to the Any trait. This is useful to let /// the caller have access to the underlying type behind the trait. fn as_any_mut(&mut self) -> &mut dyn Any; @@ -113,15 +142,20 @@ pub trait PciDevice: Send { /// This trait defines a set of functions which can be triggered whenever a /// PCI device is modified in any way. pub trait DeviceRelocation: Send + Sync { - /// The BAR needs to be moved to a different location in the guest address - /// space. This follows a decision from the software running in the guest. - fn move_bar( + /// Release a BAR's current location: its allocator and bus ranges and + /// the device's mappings. + fn move_bar_prepare( + &self, + pci_dev: &mut dyn PciDevice, + params: &ReleaseParams, + ) -> result::Result<(), io::Error>; + + /// Install a released BAR at params.new_base, inserting bus_device on + /// the bus. + fn move_bar_commit( &self, - bar_idx: usize, - old_base: u64, - new_base: u64, - len: u64, pci_dev: &mut dyn PciDevice, - region_type: PciBarRegionType, + bus_device: &Arc, + params: &InstallParams, ) -> result::Result<(), io::Error>; } diff --git a/pci/src/lib.rs b/pci/src/lib.rs index 28bedd56c8..b6c9f0c0fb 100644 --- a/pci/src/lib.rs +++ b/pci/src/lib.rs @@ -25,13 +25,15 @@ pub use self::bus::{ PciConfigIoState, PciConfigMmio, PciRoot, PciRootError, }; pub use self::configuration::{ - PCI_CONFIGURATION_ID, PasidCap, PciBarConfiguration, PciBarPrefetchable, PciBarRegionType, - PciCapability, PciCapabilityId, PciClassCode, PciConfiguration, PciExpressCapability, + COMMAND_REG, COMMAND_REG_IO_SPACE_MASK, COMMAND_REG_MEMORY_SPACE_MASK, PCI_CONFIGURATION_ID, + PasidCap, PciBarConfiguration, PciBarPrefetchable, PciBarRegionType, PciCapability, + PciCapabilityId, PciClassCode, PciConfiguration, PciConfigurationState, PciExpressCapability, PciExpressCapabilityId, PciHeaderType, PciMassStorageSubclass, PciNetworkControllerSubclass, PciProgrammingInterface, PciSerialBusSubClass, PciSubclass, }; pub use self::device::{ - BarReprogrammingParams, DeviceRelocation, Error as PciDeviceError, PciDevice, + BarRelocation, DeviceRelocation, Error as PciDeviceError, InstallParams, PciDevice, + ReleaseParams, }; pub use self::msi::{MsiCap, MsiConfig, msi_num_enabled_vectors}; pub use self::msix::{ diff --git a/pci/src/vfio.rs b/pci/src/vfio.rs index d1cb1f63c4..94fe2b85b2 100644 --- a/pci/src/vfio.rs +++ b/pci/src/vfio.rs @@ -65,10 +65,10 @@ use crate::configuration::{ use crate::msi::{Error as MsiError, MSI_CONFIG_ID, MsiConfigState}; use crate::msix::{Error as MsixError, MaybeMutInterruptSourceGroup, MsixConfigState}; use crate::{ - BarReprogrammingParams, MSIX_CONFIG_ID, MSIX_TABLE_ENTRY_SIZE, MsiCap, MsiConfig, MsixCap, - MsixConfig, PCI_CONFIGURATION_ID, PciBarConfiguration, PciBarPrefetchable, PciBarRegionType, - PciBdf, PciCapabilityId, PciClassCode, PciConfiguration, PciDevice, PciDeviceError, - PciExpressCapability, PciExpressCapabilityId, PciHeaderType, PciSubclass, + BarRelocation, InstallParams, MSIX_CONFIG_ID, MSIX_TABLE_ENTRY_SIZE, MsiCap, MsiConfig, + MsixCap, MsixConfig, PCI_CONFIGURATION_ID, PciBarConfiguration, PciBarPrefetchable, + PciBarRegionType, PciBdf, PciCapabilityId, PciClassCode, PciConfiguration, PciDevice, + PciDeviceError, PciExpressCapability, PciExpressCapabilityId, PciHeaderType, PciSubclass, msi_num_enabled_vectors, }; @@ -377,12 +377,6 @@ impl VfioBarMemoryRegion { self.region.lock().unwrap().as_ptr() } - fn p2p_mapped(&self) -> bool { - self.p2p_mapping - .as_ref() - .is_some_and(|mapping| mapping.lock().unwrap().mapped) - } - fn map_for_p2p(&self) -> Result<(), VfioPciError> { let Some(p2p_mapping) = &self.p2p_mapping else { return Ok(()); @@ -927,12 +921,37 @@ pub(crate) struct VfioCommonConfig { } impl VfioCommon { - pub(crate) fn move_bar(&mut self, bar_idx: usize, new_base: u64) -> Result<(), VfioPciError> { + pub(crate) fn move_bar_prepare(&mut self, bar_idx: usize) -> Result<(), VfioPciError> { + for region in &mut self.bars { + if region.index as usize != bar_idx { + continue; + } + for bar_memory_region in ®ion.bar_memory_regions { + bar_memory_region + .unmap_p2p() + .map_err(VfioPciError::DmaUnmap)?; + bar_memory_region + .region + .lock() + .unwrap() + .unregister() + .map_err(VfioPciError::MoveBarMemoryRegion)?; + } + } + Ok(()) + } + + pub(crate) fn move_bar_commit( + &mut self, + bar_idx: usize, + new_base: u64, + ) -> Result<(), VfioPciError> { for region in &mut self.bars { - if region.index as usize != bar_idx || region.start == GuestAddress(new_base) { + if region.index as usize != bar_idx { continue; } - let moves = region + let old_base = region.start.raw_value(); + let new_addresses = region .bar_memory_regions .iter() .map(|bar_memory_region| { @@ -949,63 +968,42 @@ impl VfioCommon { address: new_address, size, })?; - Ok(( - bar_memory_region.start(), - new_address, - bar_memory_region.p2p_mapped(), - )) + Ok(new_address) }) .collect::, VfioPciError>>()?; - for (i, &(_, new_address, map_p2p)) in moves.iter().enumerate() { + for (i, &new_address) in new_addresses.iter().enumerate() { let bar_memory_region = &mut region.bar_memory_regions[i]; let result = (|| { - bar_memory_region - .unmap_p2p() - .map_err(VfioPciError::DmaUnmap)?; bar_memory_region .move_region(new_address) .map_err(VfioPciError::MoveBarMemoryRegion)?; - if map_p2p { - bar_memory_region.map_for_p2p()?; - } - Ok(()) + bar_memory_region + .region + .lock() + .unwrap() + .register() + .map_err(VfioPciError::CreateUserMemoryRegion)?; + bar_memory_region.map_for_p2p() })(); if let Err(e) = result { - for (bar_memory_region, &(old_address, _, was_mapped)) in region - .bar_memory_regions[..=i] - .iter_mut() - .zip(&moves[..=i]) - .rev() - { - if bar_memory_region.start() == old_address - && bar_memory_region.p2p_mapped() == was_mapped - && bar_memory_region.region.lock().unwrap().is_registered() - { - continue; - } - let rollback: Result<(), VfioPciError> = (|| { + // The caller gives the range back, so no area may stay mapped there. + for bar_memory_region in &mut region.bar_memory_regions[..=i] { + let unwind: Result<(), VfioPciError> = (|| { bar_memory_region .unmap_p2p() .map_err(VfioPciError::DmaUnmap)?; bar_memory_region - .move_region(old_address) + .region + .lock() + .unwrap() + .unregister() .map_err(VfioPciError::MoveBarMemoryRegion)?; - { - let mapping = bar_memory_region.region.lock().unwrap(); - if !mapping.is_registered() { - mapping - .register() - .map_err(VfioPciError::CreateUserMemoryRegion)?; - } - } - if was_mapped { - bar_memory_region.map_for_p2p()?; - } - Ok(()) + bar_memory_region + .move_region(old_base + bar_memory_region.offset) + .map_err(VfioPciError::MoveBarMemoryRegion) })(); - if let Err(rollback) = rollback { - // Continuing would leave the BAR with inconsistent mappings. - error!("FATAL: Failed to restore BAR mapping: {rollback:?}"); + if let Err(unwind) = unwind { + error!("FATAL: Failed to unwind BAR install: {unwind:?}"); process::exit(1); } } @@ -1276,34 +1274,44 @@ impl VfioCommon { } } - let bar_addr = match region_type { - PciBarRegionType::IoRegion => { - let alignment = if restored_bar_addr.is_some() { - Some(4) - } else { - Some(region_size.max(4)) - }; - allocator - .allocate_io_addresses(restored_bar_addr, region_size, alignment) - .ok_or(PciDeviceError::IoAllocationFailed(region_size))? - } - PciBarRegionType::Memory32BitRegion => { - // BAR allocation must be naturally aligned - mmio32_allocator - .allocate(restored_bar_addr, region_size, Some(region_size)) - .ok_or(PciDeviceError::IoAllocationFailed(region_size))? - } - PciBarRegionType::Memory64BitRegion => { - // We need do some fixup to keep MMIO RW region and msix cap region page size - // aligned. - region_size = self.fixup_msix_region(bar_id, region_size); - mmio64_allocator + if region_type == PciBarRegionType::Memory64BitRegion { + // We need do some fixup to keep MMIO RW region and msix cap region page size + // aligned. + region_size = self.fixup_msix_region(bar_id, region_size); + } + + // A BAR released on restore is not allocated: another device may + // hold its saved range by now, and its install allocates at its + // register. + let bar_addr = if let Some(addr) = restored_bar_addr + && self.configuration.is_bar_released(bar_id as usize) + { + addr + } else { + match region_type { + PciBarRegionType::IoRegion => { + let alignment = if restored_bar_addr.is_some() { + Some(4) + } else { + Some(region_size.max(4)) + }; + allocator + .allocate_io_addresses(restored_bar_addr, region_size, alignment) + .ok_or(PciDeviceError::IoAllocationFailed(region_size))? + } + PciBarRegionType::Memory32BitRegion => { + // BAR allocation must be naturally aligned + mmio32_allocator + .allocate(restored_bar_addr, region_size, Some(region_size)) + .ok_or(PciDeviceError::IoAllocationFailed(region_size))? + } + PciBarRegionType::Memory64BitRegion => mmio64_allocator .allocate( restored_bar_addr, region_size, Some(cmp::max(get_page_size(), region_size)), ) - .ok_or(PciDeviceError::IoAllocationFailed(region_size))? + .ok_or(PciDeviceError::IoAllocationFailed(region_size))?, } }; @@ -1354,6 +1362,9 @@ impl VfioCommon { mmio64_allocator: &mut AddressAllocator, ) -> Result<(), PciDeviceError> { for region in self.bars.iter() { + if self.configuration.is_bar_released(region.index as usize) { + continue; + } match region.type_ { PciBarRegionType::IoRegion => { allocator.free_io_addresses(region.start, region.length); @@ -1979,7 +1990,7 @@ impl VfioCommon { reg_idx: usize, offset: u64, data: &[u8], - ) -> (Vec, Option>) { + ) -> (BarRelocation, Option>) { // When the guest wants to write to a BAR, we trap it into // our local configuration space. We're not reprogramming // VFIO device. @@ -2001,7 +2012,7 @@ impl VfioCommon { let device_writes = patch.write(offset, data); if patch.mask == 0xffff_ffff { - return (Vec::new(), None); + return (BarRelocation::default(), None); } device_writes @@ -2044,15 +2055,11 @@ impl VfioCommon { self.vfio_wrapper.write_config((reg + offset) as u32, data); } - // The non BAR write path goes directly to the VFIO device and not the shadow, - // so the PciConfiguration shadow can get stale. Mirror the write into the - // shadow here since snapshot() serializes it. Without this the shadow keeps its - // device init values and a snapshot encodes PCI_COMMAND as zero. - // - // Use the raw write_* helpers rather than the PciConfiguration method - // self.configuration.write_config_register(), which would otherwise drain - // pending_bar_reprogram, owned by the BAR block below, and rerun MSI-X - // set_msg_ctl, already done by update_msix_capabilities above. + // Mirror the write into the shadow, which snapshot() serializes and + // which releases and installs BARs on COMMAND writes. MSI-X was + // handled above and BAR writes returned early, so write the raw bytes. + let old_command = + (reg_idx == COMMAND_REG).then(|| self.configuration.read_config_register(COMMAND_REG)); let byte_offset = reg_idx * PCI_CONFIG_REGISTER_SIZE + offset as usize; match data.len() { 1 => self.configuration.write_byte(byte_offset, data[0]), @@ -2066,7 +2073,14 @@ impl VfioCommon { _ => {} } - (self.configuration.drain_pending_bar_reprogram(), None) + let mut reloc = BarRelocation::default(); + if let Some(old_command) = old_command { + self.configuration + .release_disabled_bars(old_command, &mut reloc); + self.configuration.drain_pending_installs(&mut reloc); + } + + (reloc, None) } pub(crate) fn read_config_register(&mut self, reg_idx: usize) -> u32 { @@ -2701,6 +2715,10 @@ impl VfioPciDevice { let page_size = get_page_size(); let map_p2p = self.p2p_dma && region.is_p2p_mappable(); + let released = self + .common + .configuration + .is_bar_released(region.index as usize); if self.p2p_dma && !map_p2p { warn!( "Skipping P2P DMA mapping of BAR {} of device {}: its size \ @@ -2761,9 +2779,11 @@ impl VfioPciDevice { VfioPciError::MmapArea })?; - mapping - .register() - .map_err(VfioPciError::CreateUserMemoryRegion)?; + if !released { + mapping + .register() + .map_err(VfioPciError::CreateUserMemoryRegion)?; + } let bar_memory_region = VfioBarMemoryRegion { offset: area.offset, region: Arc::new(Mutex::new(mapping)), @@ -2781,10 +2801,14 @@ impl VfioPciDevice { })) }), }; - // Map the MMIO BAR into the host IOMMU address space via VfioOps - // Only needed if p2p_dma is enabled. - if map_p2p { - bar_memory_region.map_for_p2p()?; + // A BAR released on restore keeps its mapping and slot + // for its install, but is not mapped into the guest yet. + if !released { + // Map the MMIO BAR into the host IOMMU address space via VfioOps + // Only needed if p2p_dma is enabled. + if map_p2p { + bar_memory_region.map_for_p2p()?; + } } region.bar_memory_regions.push(bar_memory_region); } @@ -2822,6 +2846,14 @@ impl VfioPciDevice { }; for mmio_region in self.common.bars.iter_mut() { + // A released BAR is mapped by its install, at its new address. + if self + .common + .configuration + .is_bar_released(mmio_region.index as usize) + { + continue; + } for bar_memory_region in mmio_region.bar_memory_regions.iter_mut() { let Some(p2p_mapping) = &bar_memory_region.p2p_mapping else { continue; @@ -2832,6 +2864,9 @@ impl VfioPciDevice { let Some(dma_buf) = &p2p_mapping.dma_buf else { continue; }; + if p2p_mapping.mapped == memory_space_enabled { + continue; + } let res = if memory_space_enabled { vfio_iommufd @@ -2992,7 +3027,7 @@ impl PciDevice for VfioPciDevice { reg_idx: usize, offset: u64, data: &[u8], - ) -> (Vec, Option>) { + ) -> (BarRelocation, Option>) { #[cfg(feature = "kvm")] let memory_space_enabled = reg_idx == COMMAND_REG && self.is_memory_space_enabled(); @@ -3018,14 +3053,34 @@ impl PciDevice for VfioPciDevice { self.common.write_bar(base, offset, data) } - fn move_bar(&mut self, bar_idx: usize, new_base: u64) -> Result<(), io::Error> { + fn move_bar_prepare(&mut self, bar_idx: usize) -> Result<(), io::Error> { self.common - .move_bar(bar_idx, new_base) + .move_bar_prepare(bar_idx) .map_err(io::Error::other) } - fn restore_bar_addr(&mut self, params: &BarReprogrammingParams) { - self.common.configuration.restore_bar_addr(params); + fn move_bar_commit(&mut self, bar_idx: usize, new_base: u64) -> Result<(), io::Error> { + self.common + .move_bar_commit(bar_idx, new_base) + .map_err(io::Error::other) + } + + fn release_stale_bar(&mut self, bar_idx: usize, mapped_at: u64) -> bool { + self.common + .configuration + .release_stale_bar(bar_idx, mapped_at) + } + + fn is_bar_released(&self, bar_idx: usize) -> bool { + self.common.configuration.is_bar_released(bar_idx) + } + + fn on_bar_installed(&mut self, bar_idx: usize) { + self.common.configuration.on_bar_installed(bar_idx); + } + + fn pending_bar_installs(&self) -> Vec { + self.common.configuration.pending_bar_installs() } fn as_any_mut(&mut self) -> &mut dyn Any { @@ -3224,6 +3279,7 @@ mod tests { use super::*; use crate::PasidCap; + use crate::configuration::COMMAND_REG_MEMORY_SPACE_MASK; #[test] fn find_alignment_scales_with_length() { @@ -3344,7 +3400,7 @@ mod tests { #[cfg(feature = "kvm")] #[test] - fn move_bar_restores_sparse_areas_after_failed_relocation() { + fn move_bar_commit_unwinds_sparse_areas_after_failed_install() { let page_size = get_page_size(); let vm = hypervisor::new() .unwrap() @@ -3388,26 +3444,17 @@ mod tests { index: 0, bar_memory_regions: regions, }); - let lookup_regions = common.bars.clone(); - common.move_bar(0, 4 * page_size).unwrap_err(); + common.move_bar_prepare(0).unwrap(); + common.move_bar_commit(0, 4 * page_size).unwrap_err(); assert_eq!(common.bars[0].start, GuestAddress(page_size)); for (i, entry) in common.bars[0].bar_memory_regions.iter().enumerate() { - let address = page_size + entry.offset; let mapping = entry.region.lock().unwrap(); - assert_eq!(mapping.start_addr(), GuestAddress(address)); + assert_eq!(mapping.start_addr(), GuestAddress(page_size + entry.offset)); assert_eq!(mapping.slot(), Some(slots[i])); - assert!(mapping.is_registered()); + assert!(!mapping.is_registered()); } - assert!(lookup_regions.check_range(page_size, 3 * page_size)); - assert!(!lookup_regions.check_range(4 * page_size, page_size)); - lookup_regions - .find_user_address(page_size, page_size) - .unwrap(); - lookup_regions - .find_user_address(3 * page_size, page_size) - .unwrap(); } fn sparse_mmio_regions() -> Vec { @@ -3483,9 +3530,8 @@ mod tests { #[test] fn dma_lookup_through_cloned_bar_tracks_relocation() { let page_size = get_page_size(); - let mut common = test_vfio_common(Arc::new(DefaultVfio), None); - common.bars = sparse_mmio_regions(); - let lookup_regions = common.bars.clone(); + let mut regions = sparse_mmio_regions(); + let lookup_regions = regions.clone(); let host_addresses = [ lookup_regions .find_user_address(page_size, page_size) @@ -3496,8 +3542,11 @@ mod tests { ]; for new_base in [10 * page_size, page_size] { - let old_base = common.bars[0].start.raw_value(); - common.move_bar(0, new_base).unwrap(); + let old_base = regions[0].start.raw_value(); + for entry in &mut regions[0].bar_memory_regions { + entry.move_region(new_base + entry.offset).unwrap(); + } + regions[0].start = GuestAddress(new_base); // Only the shared mappings change in the cloned lookup records. assert_eq!(lookup_regions[0].start, GuestAddress(page_size)); @@ -4451,4 +4500,44 @@ mod tests { assert_eq!(sparse_areas[1].offset, hole_end); assert_eq!(sparse_areas[1].size, region_size - hole_end); } + + /// A COMMAND write mirrored into the shadow releases the BARs of the + /// spaces it disables and installs them again when it enables them, as + /// the generic config-space path does. + #[test] + fn test_command_write_releases_and_installs_bars() { + const BAR_ADDR: u64 = 0x1000_0000; + let mse = COMMAND_REG_MEMORY_SPACE_MASK as u16; + + let mut common = test_vfio_common(MockVfio::for_load(), None); + common + .configuration + .add_pci_bar( + &PciBarConfiguration::default() + .set_index(0) + .set_address(BAR_ADDR) + .set_size(0x1000) + .set_region_type(PciBarRegionType::Memory32BitRegion) + .set_prefetchable(PciBarPrefetchable::NotPrefetchable), + ) + .unwrap(); + + // The BAR is mapped from creation: enabling the space installs nothing. + let (reloc, _) = common.write_config_register(COMMAND_REG, 0, &mse.to_le_bytes()); + assert!(reloc.is_empty()); + + // Disabling the space releases it. + let (reloc, _) = common.write_config_register(COMMAND_REG, 0, &0u16.to_le_bytes()); + assert_eq!(reloc.release.len(), 1); + assert_eq!(reloc.release[0].bar_idx, 0); + assert!(reloc.install.is_empty()); + assert!(common.configuration.is_bar_released(0)); + + // Enabling it again installs at the register. + let (reloc, _) = common.write_config_register(COMMAND_REG, 0, &mse.to_le_bytes()); + assert!(reloc.release.is_empty()); + assert_eq!(reloc.install.len(), 1); + assert_eq!(reloc.install[0].bar_idx, 0); + assert_eq!(reloc.install[0].new_base, BAR_ADDR); + } } diff --git a/pci/src/vfio_user.rs b/pci/src/vfio_user.rs index eaa1aebec0..4036aa2741 100644 --- a/pci/src/vfio_user.rs +++ b/pci/src/vfio_user.rs @@ -29,8 +29,8 @@ use crate::vfio::{ find_alignment, }; use crate::{ - BarReprogrammingParams, PciBarConfiguration, PciBdf, PciDevice, PciDeviceError, PciSubclass, - VfioPciError, + BarRelocation, InstallParams, PciBarConfiguration, PciBdf, PciDevice, PciDeviceError, + PciSubclass, VfioPciError, }; pub struct VfioUserPciDevice { @@ -124,6 +124,12 @@ impl VfioUserPciDevice { /// Map all of the MMIO regions. pub fn map_mmio_regions(&mut self) -> Result<(), VfioUserPciDeviceError> { for mmio_region in &mut self.common.bars { + // A BAR released on restore keeps its mapping and slot for its + // install, but is not mapped into the guest yet. + let released = self + .common + .configuration + .is_bar_released(mmio_region.index as usize); let (region_flags, region_size, file_offset, sparse_areas) = { let client = self.client.lock().unwrap(); let region = client @@ -191,9 +197,11 @@ impl VfioUserPciDevice { Arc::clone(&self.memory_slot_allocator), ) .map_err(|e| VfioUserPciDeviceError::Other(io::Error::other(e)))?; - mapping - .register() - .map_err(VfioUserPciDeviceError::MapRegionGuest)?; + if !released { + mapping + .register() + .map_err(VfioUserPciDeviceError::MapRegionGuest)?; + } let mapping = Arc::new(Mutex::new(mapping)); let bar_memory_region = VfioBarMemoryRegion { @@ -355,10 +363,6 @@ impl PciDevice for VfioUserPciDevice { .free_bars(allocator, mmio32_allocator, mmio64_allocator) } - fn restore_bar_addr(&mut self, params: &BarReprogrammingParams) { - self.common.configuration.restore_bar_addr(params); - } - fn as_any_mut(&mut self) -> &mut dyn Any { self } @@ -368,7 +372,7 @@ impl PciDevice for VfioUserPciDevice { reg_idx: usize, offset: u64, data: &[u8], - ) -> (Vec, Option>) { + ) -> (BarRelocation, Option>) { self.common.write_config_register(reg_idx, offset, data) } @@ -384,13 +388,38 @@ impl PciDevice for VfioUserPciDevice { self.common.write_bar(base, offset, data) } - fn move_bar(&mut self, bar_idx: usize, new_base: u64) -> Result<(), io::Error> { - info!("Moving BAR {bar_idx} -> 0x{new_base:x}"); + fn move_bar_prepare(&mut self, bar_idx: usize) -> Result<(), io::Error> { + info!("Unmapping BAR {bar_idx}"); + self.common + .move_bar_prepare(bar_idx) + .map_err(io::Error::other) + } + + fn move_bar_commit(&mut self, bar_idx: usize, new_base: u64) -> Result<(), io::Error> { + info!("Mapping BAR {bar_idx} -> 0x{new_base:x}"); self.common - .move_bar(bar_idx, new_base) + .move_bar_commit(bar_idx, new_base) .map_err(io::Error::other) } + fn release_stale_bar(&mut self, bar_idx: usize, mapped_at: u64) -> bool { + self.common + .configuration + .release_stale_bar(bar_idx, mapped_at) + } + + fn is_bar_released(&self, bar_idx: usize) -> bool { + self.common.configuration.is_bar_released(bar_idx) + } + + fn on_bar_installed(&mut self, bar_idx: usize) { + self.common.configuration.on_bar_installed(bar_idx); + } + + fn pending_bar_installs(&self) -> Vec { + self.common.configuration.pending_bar_installs() + } + fn id(&self) -> Option { Some(self.id.clone()) } diff --git a/virtio-devices/src/transport/pci_device.rs b/virtio-devices/src/transport/pci_device.rs index 360560f43f..e83eeaaf45 100644 --- a/virtio-devices/src/transport/pci_device.rs +++ b/virtio-devices/src/transport/pci_device.rs @@ -16,10 +16,10 @@ use anyhow::anyhow; use libc::EFD_NONBLOCK; use log::{debug, error, info, warn}; use pci::{ - BarReprogrammingParams, MaybeMutInterruptSourceGroup, MsixCap, MsixConfig, PciBarConfiguration, - PciBarRegionType, PciBdf, PciCapability, PciCapabilityId, PciClassCode, PciConfiguration, - PciDevice, PciDeviceError, PciHeaderType, PciMassStorageSubclass, PciNetworkControllerSubclass, - PciSubclass, + BarRelocation, InstallParams, MaybeMutInterruptSourceGroup, MsixCap, MsixConfig, + PciBarConfiguration, PciBarRegionType, PciBdf, PciCapability, PciCapabilityId, PciClassCode, + PciConfiguration, PciDevice, PciDeviceError, PciHeaderType, PciMassStorageSubclass, + PciNetworkControllerSubclass, PciSubclass, }; use serde::{Deserialize, Serialize}; use thiserror::Error; @@ -1027,7 +1027,7 @@ impl PciDevice for VirtioPciDevice { reg_idx: usize, offset: u64, data: &[u8], - ) -> (Vec, Option>) { + ) -> (BarRelocation, Option>) { // Handle the special case where the capability VIRTIO_PCI_CAP_PCI_CFG // is accessed. This capability has a special meaning as it allows the // guest to access other capabilities without mapping the PCI BAR. @@ -1037,7 +1037,10 @@ impl PciDevice for VirtioPciDevice { <= self.cap_pci_cfg_info.offset + self.cap_pci_cfg_info.cap.bytes().len() { let offset = base + offset as usize - self.cap_pci_cfg_info.offset; - (Vec::new(), self.write_cap_pci_cfg(offset, data)) + ( + BarRelocation::default(), + self.write_cap_pci_cfg(offset, data), + ) } else { ( self.configuration @@ -1104,27 +1107,34 @@ impl PciDevice for VirtioPciDevice { // Allocate the virtio-pci capability BAR. // See http://docs.oasis-open.org/virtio/virtio/v1.0/cs04/virtio-v1.0-cs04.html#x1-740004 - let (virtio_pci_bar_addr, region_type) = if use_64bit_bar { - let region_type = PciBarRegionType::Memory64BitRegion; + let region_type = if use_64bit_bar { + PciBarRegionType::Memory64BitRegion + } else { + PciBarRegionType::Memory32BitRegion + }; + // A BAR released on restore is not allocated: another device may hold + // its saved range by now, and its install allocates at its register. + let virtio_pci_bar_addr = if let Some(addr) = settings_bar_addr + && self.configuration.is_bar_released(VIRTIO_CONFIG_BAR_INDEX) + { + addr + } else if use_64bit_bar { let alignment = if restoring { None } else { Some(VIRTIO_PCI_BAR_ALIGN) }; - let addr = mmio64_allocator + mmio64_allocator .allocate(settings_bar_addr, CAPABILITY_BAR_SIZE, alignment) - .ok_or(PciDeviceError::IoAllocationFailed(CAPABILITY_BAR_SIZE))?; - (addr, region_type) + .ok_or(PciDeviceError::IoAllocationFailed(CAPABILITY_BAR_SIZE))? } else { - let region_type = PciBarRegionType::Memory32BitRegion; - let addr = mmio32_allocator + mmio32_allocator .allocate( settings_bar_addr, CAPABILITY_BAR_SIZE, Some(CAPABILITY_BAR_SIZE), ) - .ok_or(PciDeviceError::IoAllocationFailed(CAPABILITY_BAR_SIZE))?; - (addr, region_type) + .ok_or(PciDeviceError::IoAllocationFailed(CAPABILITY_BAR_SIZE))? }; let bar = PciBarConfiguration::default() @@ -1195,6 +1205,9 @@ impl PciDevice for VirtioPciDevice { mmio64_allocator: &mut AddressAllocator, ) -> result::Result<(), PciDeviceError> { for bar in self.bar_regions.drain(..) { + if self.configuration.is_bar_released(bar.idx()) { + continue; + } match bar.region_type() { PciBarRegionType::Memory32BitRegion => { mmio32_allocator.free(GuestAddress(bar.addr()), bar.size()); @@ -1208,7 +1221,7 @@ impl PciDevice for VirtioPciDevice { Ok(()) } - fn move_bar(&mut self, bar_idx: usize, new_base: u64) -> io::Result<()> { + fn move_bar_prepare(&mut self, bar_idx: usize) -> io::Result<()> { if bar_idx == VIRTIO_SHM_BAR_INDEX && let Some(shm_list) = self.device.lock().unwrap().get_shm_regions() { @@ -1216,8 +1229,22 @@ impl PciDevice for VirtioPciDevice { .mapping .lock() .unwrap() + .unregister() + .map_err(io::Error::other)?; + } + + Ok(()) + } + + fn move_bar_commit(&mut self, bar_idx: usize, new_base: u64) -> io::Result<()> { + if bar_idx == VIRTIO_SHM_BAR_INDEX + && let Some(shm_list) = self.device.lock().unwrap().get_shm_regions() + { + let mut mapping = shm_list.mapping.lock().unwrap(); + mapping .move_guest_address(GuestAddress(new_base)) .map_err(io::Error::other)?; + mapping.register().map_err(io::Error::other)?; } for bar in self.bar_regions.iter_mut() { @@ -1229,8 +1256,20 @@ impl PciDevice for VirtioPciDevice { Ok(()) } - fn restore_bar_addr(&mut self, params: &BarReprogrammingParams) { - self.configuration.restore_bar_addr(params); + fn release_stale_bar(&mut self, bar_idx: usize, mapped_at: u64) -> bool { + self.configuration.release_stale_bar(bar_idx, mapped_at) + } + + fn is_bar_released(&self, bar_idx: usize) -> bool { + self.configuration.is_bar_released(bar_idx) + } + + fn on_bar_installed(&mut self, bar_idx: usize) { + self.configuration.on_bar_installed(bar_idx); + } + + fn pending_bar_installs(&self) -> Vec { + self.configuration.pending_bar_installs() } fn read_bar(&mut self, _base: u64, offset: u64, data: &mut [u8]) { diff --git a/vm-allocator/src/address.rs b/vm-allocator/src/address.rs index 8be9daefe3..0a69c68771 100644 --- a/vm-allocator/src/address.rs +++ b/vm-allocator/src/address.rs @@ -200,43 +200,6 @@ impl AddressAllocator { Some(new_addr) } - /// Moves an allocated address range to `new_address`. - /// - /// The range at `old_address` must match `size` exactly. The new range may overlap the old - /// range, but it cannot overlap any other allocation. Returns `Some(new_address)` when - /// successful, or `None` if the range cannot be moved. A failed move leaves the old range - /// allocated. - pub fn move_range( - &mut self, - old_address: GuestAddress, - new_address: GuestAddress, - size: GuestUsize, - align_size: Option, - ) -> Option { - if self.ranges.get(&old_address) != Some(&size) { - debug!( - "Cannot move address range from {:#x} to {:#x} with size {size:#x}: allocated size is {:?}", - old_address.0, - new_address.0, - self.ranges.get(&old_address) - ); - return None; - } - - self.ranges.remove(&old_address); - - if let Some(new_address) = self.allocate(Some(new_address), size, align_size) { - Some(new_address) - } else { - self.ranges.insert(old_address, size); - debug!( - "Cannot move address range from {:#x} to {:#x} with size {size:#x}: destination allocation failed", - old_address.0, new_address.0 - ); - None - } - } - /// Free an already allocated address range. /// We can only free a range if it matches exactly an already allocated range. pub fn free(&mut self, address: GuestAddress, size: GuestUsize) { @@ -442,58 +405,4 @@ mod tests { Some(GuestAddress(0x1200)) ); } - - #[test] - fn move_range_overlapping_old_range() { - let mut pool = AddressAllocator::new(GuestAddress(0x1000), 0x1000).unwrap(); - - assert_eq!( - pool.allocate(Some(GuestAddress(0x1400)), 0x400, Some(0x100)), - Some(GuestAddress(0x1400)) - ); - assert_eq!( - pool.move_range( - GuestAddress(0x1400), - GuestAddress(0x1600), - 0x400, - Some(0x100), - ), - Some(GuestAddress(0x1600)) - ); - assert_eq!( - pool.move_range( - GuestAddress(0x1600), - GuestAddress(0x1400), - 0x400, - Some(0x100), - ), - Some(GuestAddress(0x1400)) - ); - } - - #[test] - fn move_range_fails_when_overlapping_another_range() { - let mut pool = AddressAllocator::new(GuestAddress(0x1000), 0x1000).unwrap(); - - assert_eq!( - pool.allocate(Some(GuestAddress(0x1400)), 0x400, Some(0x100)), - Some(GuestAddress(0x1400)) - ); - assert_eq!( - pool.allocate(Some(GuestAddress(0x1900)), 0x200, Some(0x100)), - Some(GuestAddress(0x1900)) - ); - let old_ranges = pool.ranges.clone(); - - assert_eq!( - pool.move_range( - GuestAddress(0x1400), - GuestAddress(0x1600), - 0x400, - Some(0x100), - ), - None - ); - assert_eq!(pool.ranges, old_ranges); - } } diff --git a/vm-allocator/src/guest_memory.rs b/vm-allocator/src/guest_memory.rs index 9624356b7c..820aa98269 100644 --- a/vm-allocator/src/guest_memory.rs +++ b/vm-allocator/src/guest_memory.rs @@ -228,6 +228,39 @@ impl GuestRegion { Ok(()) } + /// Removes the region from the hypervisor, keeping its mapping and + /// guest address, so that it can be registered again later, possibly + /// after a move. A region that is not registered is left as is. + pub fn unregister(&mut self) -> Result<(), Error> { + if !*self.registered.get_mut() { + return Ok(()); + } + let vm = self.vm.as_ref().ok_or(Error::MissingVm)?; + let slot = self.slot.unwrap(); + let guest_phys_addr = self.region.start_addr().raw_value(); + let memory_size = self.region.size(); + let userspace_addr = self.region.as_ptr(); + // SAFETY: exclusive access keeps the region and its mapping alive. + unsafe { + vm.remove_user_memory_region( + slot, + guest_phys_addr, + memory_size, + userspace_addr, + false, // Read-only flags are ignored when removing a region. + ) + } + .map_err(Error::RemoveRegion)?; + *self.registered.get_mut() = false; + + info!( + "Removed userspace mapping: {:#} -> {:#} {:#}", + guest_phys_addr, userspace_addr as usize, memory_size + ); + + Ok(()) + } + /// The reserved slot, including before registration. pub fn slot(&self) -> Option { self.slot @@ -354,31 +387,12 @@ impl From> for GuestRegion { impl Drop for GuestRegion { fn drop(&mut self) { - let guest_phys_addr = self.region.start_addr().raw_value(); + if let Err(e) = self.unregister() { + error!("Error releasing memory region: {e:?}"); + process::exit(1); + } let memory_size = self.region.size(); let userspace_addr = self.region.as_ptr(); - if *self.registered.get_mut() { - let vm = self.vm.as_ref().unwrap(); - let slot = self.slot.unwrap(); - // SAFETY: the owned region remains mapped until after this destructor returns. - if let Err(e) = unsafe { - vm.remove_user_memory_region( - slot, - guest_phys_addr, - memory_size, - userspace_addr, - false, // Read-only flags are ignored when removing a region. - ) - } { - error!("Error releasing memory region: {e}"); - process::exit(1); - } - - info!( - "Removed userspace mapping: {:#} -> {:#} {:#}", - guest_phys_addr, userspace_addr as usize, memory_size - ); - } if self.mergeable { // SAFETY: the address and size are valid as the region was // previously advised. diff --git a/vm-allocator/src/system.rs b/vm-allocator/src/system.rs index 02da48669a..f747fe8828 100644 --- a/vm-allocator/src/system.rs +++ b/vm-allocator/src/system.rs @@ -110,22 +110,6 @@ impl SystemAllocator { .allocate(address, size, Some(align_size.unwrap_or(0x1))) } - /// Moves an allocated IO address range to `new_address`. - pub fn move_io_addresses( - &mut self, - old_address: GuestAddress, - new_address: GuestAddress, - size: GuestUsize, - align_size: Option, - ) -> Option { - self.io_address_space.move_range( - old_address, - new_address, - size, - Some(align_size.unwrap_or(0x1)), - ) - } - /// Reserves a section of `size` bytes of platform MMIO address space. pub fn allocate_platform_mmio_addresses( &mut self, @@ -146,31 +130,3 @@ impl SystemAllocator { self.io_address_space.free(address, size); } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn move_io_addresses_overlapping_old_range() { - let mut allocator = SystemAllocator::new( - GuestAddress(0x1000), - 0x1000, - GuestAddress(0x1_0000), - 0x1000, - #[cfg(target_arch = "x86_64")] - &[GsiApic::new(5, 19)], - #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))] - 32, - ) - .unwrap(); - - assert_eq!( - allocator.allocate_io_addresses(Some(GuestAddress(0x1201)), 0x100, None), - Some(GuestAddress(0x1201)) - ); - let new_address = - allocator.move_io_addresses(GuestAddress(0x1201), GuestAddress(0x1281), 0x100, None); - assert_eq!(new_address, Some(GuestAddress(0x1281))); - } -} diff --git a/vmm/src/device_manager.rs b/vmm/src/device_manager.rs index 1ef39aed8d..41e4a30dba 100644 --- a/vmm/src/device_manager.rs +++ b/vmm/src/device_manager.rs @@ -98,9 +98,9 @@ use libc::{ use log::{debug, error, info, warn}; use net_util::MacAddr; use pci::{ - DeviceRelocation, PasidCap, PciBarConfiguration, PciBarRegionType, PciBdf, PciDevice, - PciExpressCapability, VfioBar, VfioDmaMapping, VfioPciDevice, VfioUserDmaMapping, - VfioUserPciDevice, VfioUserPciDeviceError, + DeviceRelocation, InstallParams, PasidCap, PciBarConfiguration, PciBarRegionType, PciBdf, + PciDevice, PciExpressCapability, ReleaseParams, VfioBar, VfioDmaMapping, VfioPciDevice, + VfioUserDmaMapping, VfioUserPciDevice, VfioUserPciDeviceError, }; use rate_limiter::group; use rate_limiter::group::RateLimiterGroup; @@ -113,7 +113,8 @@ use vfio_ioctls::VfioIommufd; use vfio_ioctls::{VfioContainer, VfioDevice, VfioDeviceFd, VfioOps}; use virtio_devices::block::Error as VirtioBlockError; use virtio_devices::transport::{ - VIRTIO_CONFIG_BAR_INDEX, VirtioPciDevice, VirtioPciDeviceActivator, VirtioTransport, + VIRTIO_CONFIG_BAR_INDEX, VIRTIO_SHM_BAR_INDEX, VirtioPciDevice, VirtioPciDeviceActivator, + VirtioTransport, }; use virtio_devices::vhost_user::{PostcopyHandler, VhostUserConfig}; use virtio_devices::{ @@ -320,6 +321,10 @@ pub enum DeviceManagerError { #[error("Cannot allocate PCI BARs")] AllocateBars(#[source] pci::PciDeviceError), + /// Failed leaving a released BAR unmapped + #[error("Failed leaving a released BAR unmapped")] + UnmapReleasedBar(#[source] io::Error), + /// Could not free the BARs associated with a PCI device. #[error("Could not free the BARs associated with a PCI device")] FreePciBars(#[source] pci::PciDeviceError), @@ -710,7 +715,48 @@ pub(crate) struct AddressManager { pci_mmio64_allocators: Box<[Arc>]>, } +/// What the device tree records about one BAR of a device. +struct BarResource { + /// The address the BAR was last installed at; a released BAR keeps it. + base: u64, + len: u64, + region_type: PciBarRegionType, +} + impl AddressManager { + fn bar_resource( + &self, + pci_dev: &dyn PciDevice, + bar_idx: usize, + ) -> result::Result { + let id = pci_dev + .id() + .ok_or_else(|| io::Error::other("PCI device without an id"))?; + let device_tree = self.device_tree.lock().unwrap(); + let node = device_tree + .get(&id) + .ok_or_else(|| io::Error::other(format!("No device-tree node for {id}")))?; + node.resources + .iter() + .find_map(|resource| match resource { + Resource::PciBar { + index, + base, + size, + type_, + .. + } if *index == bar_idx => Some(BarResource { + base: *base, + len: *size, + region_type: PciBarRegionType::from(*type_), + }), + _ => None, + }) + .ok_or_else(|| { + io::Error::other(format!("No resource for BAR {bar_idx} of device {id}")) + }) + } + // Update the device_tree resources associated with the device fn update_device_tree( &self, @@ -718,103 +764,131 @@ impl AddressManager { bar_idx: usize, new_base: u64, ) -> result::Result<(), io::Error> { - if let Some(id) = pci_dev.id() { - if let Some(node) = self.device_tree.lock().unwrap().get_mut(&id) { - let mut resource_updated = false; - for resource in node.resources.iter_mut() { - if let Resource::PciBar { index, base, .. } = resource - && *index == bar_idx - { - *base = new_base; - resource_updated = true; - break; - } - } - - if !resource_updated { - return Err(io::Error::other(format!( - "Couldn't find a resource for BAR {bar_idx} of device {id}" - ))); - } - } else { - return Err(io::Error::other(format!( - "Couldn't find device {id} from device tree" - ))); - } - } + let id = pci_dev + .id() + .ok_or_else(|| io::Error::other("PCI device without an id"))?; + let mut device_tree = self.device_tree.lock().unwrap(); + let node = device_tree + .get_mut(&id) + .ok_or_else(|| io::Error::other(format!("No device-tree node for {id}")))?; + let base = node + .resources + .iter_mut() + .find_map(|resource| match resource { + Resource::PciBar { index, base, .. } if *index == bar_idx => Some(base), + _ => None, + }) + .ok_or_else(|| { + io::Error::other(format!("No resource for BAR {bar_idx} of device {id}")) + })?; + *base = new_base; Ok(()) } - fn update_io_range( - &self, - allocator: &mut SystemAllocator, - old_base: u64, - new_base: u64, - len: u64, - ) -> result::Result<(), io::Error> { - if allocator - .move_io_addresses( - GuestAddress(old_base), - GuestAddress(new_base), - len as GuestUsize, - Some(len.max(4)), - ) - .is_none() - { - return Err(io::Error::other(format!( - "Cannot move IO BAR address range from {old_base:#x} to {new_base:#x}" - ))); + fn allocator_free(&self, segment: usize, base: u64, len: u64, region_type: PciBarRegionType) { + match region_type { + PciBarRegionType::IoRegion => { + self.allocator + .lock() + .unwrap() + .free_io_addresses(GuestAddress(base), len as GuestUsize); + } + PciBarRegionType::Memory32BitRegion | PciBarRegionType::Memory64BitRegion => { + let allocators = if region_type == PciBarRegionType::Memory32BitRegion { + &self.pci_mmio32_allocators + } else { + &self.pci_mmio64_allocators + }; + allocators[segment] + .lock() + .unwrap() + .free(GuestAddress(base), len as GuestUsize); + } } - - self.io_bus - .update_range(old_base, len, new_base, len) - .map_err(io::Error::other) } - fn update_mmio_range( + fn allocator_allocate( &self, - allocator: &mut AddressAllocator, - old_base: u64, - new_base: u64, + segment: usize, + base: u64, len: u64, + region_type: PciBarRegionType, ) -> result::Result<(), io::Error> { - if allocator - .move_range( - GuestAddress(old_base), - GuestAddress(new_base), - len as GuestUsize, - Some(len), - ) - .is_none() - { - return Err(io::Error::other(format!( - "Cannot move MMIO BAR address range from {old_base:#x} to {new_base:#x}" - ))); + match region_type { + PciBarRegionType::IoRegion => { + self.allocator + .lock() + .unwrap() + .allocate_io_addresses( + Some(GuestAddress(base)), + len as GuestUsize, + Some(len.max(4)), + ) + .ok_or_else(|| { + io::Error::other(format!("failed allocating new IO range: 0x{base:x}")) + })?; + } + PciBarRegionType::Memory32BitRegion | PciBarRegionType::Memory64BitRegion => { + let allocators = if region_type == PciBarRegionType::Memory32BitRegion { + &self.pci_mmio32_allocators + } else { + &self.pci_mmio64_allocators + }; + // A range outside this segment's window is rejected. + allocators[segment] + .lock() + .unwrap() + .allocate(Some(GuestAddress(base)), len as GuestUsize, Some(len)) + .ok_or_else(|| { + io::Error::other(format!( + "failed allocating new MMIO range: 0x{base:x}(0x{len:x})" + )) + })?; + } } - self.mmio_bus - .update_range(old_base, len, new_base, len) - .map_err(io::Error::other) + Ok(()) } - fn update_device( + /// Device-side release of a BAR at `base`: the virtio follow-on mappings, + /// then the device's own prepare. + fn move_bar_prepare_device( &self, pci_dev: &mut dyn PciDevice, bar_idx: usize, - old_base: u64, - new_base: u64, + base: u64, ) -> result::Result<(), io::Error> { let any_dev = pci_dev.as_any_mut(); if let Some(virtio_pci_dev) = any_dev.downcast_ref::() && bar_idx == VIRTIO_CONFIG_BAR_INDEX { - for (event, addr) in virtio_pci_dev.ioeventfds(old_base) { + for (event, addr) in virtio_pci_dev.ioeventfds(base) { let io_addr = IoEventAddress::Mmio(addr); self.vm.unregister_ioevent(event, &io_addr).map_err(|e| { io::Error::other(format!("failed to unregister ioevent: {e:?}")) })?; } + } + + pci_dev.move_bar_prepare(bar_idx) + } + + /// Device-side install of a BAR at `new_base`: the device's own commit, + /// then the virtio follow-on mappings. + fn move_bar_commit_device( + &self, + pci_dev: &mut dyn PciDevice, + params: &InstallParams, + ) -> result::Result<(), io::Error> { + let &InstallParams { bar_idx, new_base } = params; + + pci_dev.move_bar_commit(bar_idx, new_base)?; + + let any_dev = pci_dev.as_any_mut(); + if let Some(virtio_pci_dev) = any_dev.downcast_ref::() + && bar_idx == VIRTIO_CONFIG_BAR_INDEX + { for (event, addr) in virtio_pci_dev.ioeventfds(new_base) { let io_addr = IoEventAddress::Mmio(addr); self.vm @@ -823,45 +897,71 @@ impl AddressManager { } } - pci_dev.move_bar(bar_idx, new_base) + Ok(()) } } impl DeviceRelocation for AddressManager { - fn move_bar( + fn move_bar_prepare( &self, - bar_idx: usize, - old_base: u64, - new_base: u64, - len: u64, pci_dev: &mut dyn PciDevice, - region_type: PciBarRegionType, + params: &ReleaseParams, ) -> result::Result<(), io::Error> { - // Keep the allocator locked until the BAR has fully moved, so a - // concurrent allocation (e.g. a hotplug) cannot get the old range - // while the device still uses it. - let mut sys_allocator; - let mut pci_mmio_allocator; - - match region_type { - PciBarRegionType::IoRegion => { - sys_allocator = self.allocator.lock().unwrap(); - self.update_io_range(&mut sys_allocator, old_base, new_base, len)?; + let bar_idx = params.bar_idx; + let BarResource { + base, + len, + region_type, + } = self.bar_resource(pci_dev, bar_idx)?; + let segment = usize::from(pci_dev.bdf().segment()); + + // Tear the device side down first: if it fails, the range stays held + // and no other BAR is installed over a live mapping. + self.move_bar_prepare_device(pci_dev, bar_idx, base)?; + + let bus = match region_type { + PciBarRegionType::IoRegion => &self.io_bus, + PciBarRegionType::Memory32BitRegion | PciBarRegionType::Memory64BitRegion => { + &self.mmio_bus } + }; + bus.remove(base, len).map_err(io::Error::other)?; + self.allocator_free(segment, base, len, region_type); + + Ok(()) + } + + fn move_bar_commit( + &self, + pci_dev: &mut dyn PciDevice, + bus_device: &Arc, + params: &InstallParams, + ) -> result::Result<(), io::Error> { + let InstallParams { bar_idx, new_base } = *params; + let BarResource { + len, region_type, .. + } = self.bar_resource(pci_dev, bar_idx)?; + let segment = usize::from(pci_dev.bdf().segment()); + self.allocator_allocate(segment, new_base, len, region_type)?; + + let bus = match region_type { + PciBarRegionType::IoRegion => &self.io_bus, PciBarRegionType::Memory32BitRegion | PciBarRegionType::Memory64BitRegion => { - let pci_mmio_allocators = if region_type == PciBarRegionType::Memory32BitRegion { - &self.pci_mmio32_allocators - } else { - &self.pci_mmio64_allocators - }; - pci_mmio_allocator = pci_mmio_allocators[usize::from(pci_dev.bdf().segment())] - .lock() - .unwrap(); - self.update_mmio_range(&mut pci_mmio_allocator, old_base, new_base, len)?; + &self.mmio_bus } + }; + if let Err(e) = bus.insert(Arc::clone(bus_device), new_base, len) { + self.allocator_free(segment, new_base, len, region_type); + return Err(io::Error::other(e)); } - self.update_device(pci_dev, bar_idx, old_base, new_base)?; + if let Err(e) = self.move_bar_commit_device(pci_dev, params) { + if let Err(remove_err) = bus.remove(new_base, len) { + error!("Failed unwinding bus range for BAR {bar_idx}: {remove_err}"); + } + self.allocator_free(segment, new_base, len, region_type); + return Err(e); + } self.update_device_tree(pci_dev, bar_idx, new_base) } @@ -4760,6 +4860,26 @@ impl DeviceManager { segment_id: u16, resources: Option>, ) -> DeviceManagerResult<(Vec, Vec)> { + // On restore, a BAR whose space is not decoded, or whose register no + // longer names its saved address, is left unmapped: the device marks + // it released here, before anything is allocated or mapped, so that + // allocate_bars() leaves its saved range alone, which + // another device may hold by now, and the creation path skips the + // rest. The configuration reads as mapped until this point, so a + // device that writes its own COMMAND register at creation (pvpanic) + // plans nothing. + let mut released = Vec::new(); + if let Some(resources) = &resources { + let mut device = pci_device.lock().unwrap(); + for resource in resources { + if let Resource::PciBar { index, base, .. } = resource + && device.release_stale_bar(*index, *base) + { + released.push(*index); + } + } + } + let bars = pci_device .lock() .unwrap() @@ -4788,9 +4908,54 @@ impl DeviceManager { }); } + if !released.is_empty() { + let mut device = pci_device.lock().unwrap(); + for bar in bars.iter().filter(|bar| released.contains(&bar.idx())) { + self.unmap_released_bar(&mut *device, segment_id, bar) + .map_err(DeviceManagerError::UnmapReleasedBar)?; + } + } + Ok((bars, new_resources)) } + /// Give back what a virtio device set up for its shared memory BAR when + /// it was created, before the BAR was marked released: its allocator + /// range and its memory region. The other BARs of a released device are + /// not allocated or mapped in the first place. + fn unmap_released_bar( + &self, + pci_device: &mut dyn PciDevice, + segment_id: u16, + bar: &PciBarConfiguration, + ) -> result::Result<(), io::Error> { + if bar.idx() == VIRTIO_SHM_BAR_INDEX + && let Some(virtio_pci_dev) = pci_device.as_any_mut().downcast_ref::() + { + self.address_manager.allocator_free( + segment_id as usize, + bar.addr(), + bar.size(), + bar.region_type(), + ); + if let Some(shm_regions) = virtio_pci_dev + .virtio_device() + .lock() + .unwrap() + .get_shm_regions() + { + shm_regions + .mapping + .lock() + .unwrap() + .unregister() + .map_err(io::Error::other)?; + } + } + + Ok(()) + } + #[expect(clippy::needless_pass_by_value)] fn commit_pci_device( &mut self, @@ -4802,13 +4967,21 @@ impl DeviceManager { ) -> DeviceManagerResult<()> { self.bus_devices.push(Arc::clone(&bus_device)); - self.register_bar_mapping(bus_device, &bars)?; + // A BAR the device marked released on restore stays off the bus. + let mapped: Vec = { + let device = pci_device.lock().unwrap(); + bars.iter() + .filter(|bar| !device.is_bar_released(bar.idx())) + .copied() + .collect() + }; + self.register_bar_mapping(Arc::clone(&bus_device), &mapped)?; self.pci_segments[segment_id as usize] .pci_bus .lock() .unwrap() - .add_device(bdf.device(), pci_device) + .add_device(bdf.device(), pci_device, Some(bus_device)) .map_err(DeviceManagerError::AddPciDevice)?; Ok(()) @@ -5150,12 +5323,20 @@ impl DeviceManager { .find(|bar| bar.idx() == VIRTIO_CONFIG_BAR_INDEX) .unwrap() .addr(); - for (event, addr) in virtio_pci_device.lock().unwrap().ioeventfds(bar_addr) { - let io_addr = IoEventAddress::Mmio(addr); - self.address_manager - .vm - .register_ioevent(event, &io_addr, None) - .map_err(DeviceManagerError::RegisterIoevent)?; + // A config BAR left unmapped on restore gets its ioeventfds when it + // is installed. + if !virtio_pci_device + .lock() + .unwrap() + .is_bar_released(VIRTIO_CONFIG_BAR_INDEX) + { + for (event, addr) in virtio_pci_device.lock().unwrap().ioeventfds(bar_addr) { + let io_addr = IoEventAddress::Mmio(addr); + self.address_manager + .vm + .register_ioevent(event, &io_addr, None) + .map_err(DeviceManagerError::RegisterIoevent)?; + } } // Update the device tree with correct resource information. @@ -5287,9 +5468,16 @@ impl DeviceManager { hypervisor::MemoryVisibility::Shared, ) .map_err(DeviceManagerError::RegisterGuestRegion)?; - region - .register() - .map_err(DeviceManagerError::RegisterGuestRegion)?; + // A data BAR left unmapped on restore is registered when installed. + if !ivshmem_device + .lock() + .unwrap() + .is_bar_released(IVSHMEM_DATA_BAR_IDX) + { + region + .register() + .map_err(DeviceManagerError::RegisterGuestRegion)?; + } ivshmem_device.lock().unwrap().set_region(region); let mut node = device_node!(id, ivshmem_device); @@ -5730,7 +5918,10 @@ impl DeviceManager { } _ => None, }); - if let Some(bar_addr) = bar_addr { + // A released BAR has no ioeventfds registered. + if let Some(bar_addr) = bar_addr + && !dev.is_bar_released(config_bar_idx) + { for (event, addr) in dev.ioeventfds(bar_addr) { let io_addr = IoEventAddress::Mmio(addr); self.address_manager @@ -6887,6 +7078,19 @@ mod tests { ); } + use std::any::Any; + use std::collections::HashSet; + use std::sync::Barrier; + + use pci::{ + BarRelocation, COMMAND_REG, COMMAND_REG_IO_SPACE_MASK, COMMAND_REG_MEMORY_SPACE_MASK, + PciBarPrefetchable, PciBus, PciClassCode, PciConfigMmio, PciConfiguration, + PciConfigurationState, PciHeaderType, PciRoot, PciSubclass, + }; + #[cfg(target_arch = "x86_64")] + use vm_allocator::GsiApic; + use vm_migration::Snapshottable; + use super::*; #[test] @@ -6984,4 +7188,1005 @@ mod tests { Err(DeviceManagerError::PciSegmentMmioAperture(0)) )); } + + // ---- BAR relocation through the real AddressManager ----------------- + // + // Guest-style config writes go through PciConfigMmio, a real PciBus, + // AddressManager and VM; only the PCI device is a test device. + + // Config-space register constants the pci crate does not export. + const BAR0_REG: usize = 4; + const ROM_BAR_REG: usize = 12; + const ROM_BAR_IDX: usize = 6; + const BAR_SIZE: u64 = 0x1000; + const BAR0_ADDR: u64 = 0x8010_0000; + const BAR1_ADDR: u64 = 0x8020_0000; + const MMIO32_BASE: u64 = 0x8000_0000; + const MMIO32_SIZE: u64 = 0x1000_0000; + const OUT_OF_WINDOW_ADDR: u64 = 0xf800_0000; + const IO_OLD: u64 = 0x2000; + const IO_NEW: u64 = 0x3000; + const IO_SIZE: u64 = 0x100; + const ROM_ADDR: u64 = 0x8040_0000; + const ROM_NEW_ADDR: u64 = 0x8050_0000; + const ROM_SIZE: u64 = 0x1000; + const TEST_DEV_ID: &str = "_bar_test_dev"; + const TEST_DEV_SLOT: u8 = 1; + const BAR1_REG: usize = BAR0_REG + 1; + const IOSE: u32 = COMMAND_REG_IO_SPACE_MASK; + const MSE: u32 = COMMAND_REG_MEMORY_SPACE_MASK; + + #[derive(Clone, Copy)] + enum TestSubclass { + Other, + } + + impl PciSubclass for TestSubclass { + fn get_register_value(&self) -> u8 { + 0xff + } + } + + fn mem_bar(idx: usize, addr: u64) -> PciBarConfiguration { + PciBarConfiguration::new( + idx, + BAR_SIZE, + PciBarRegionType::Memory32BitRegion, + PciBarPrefetchable::NotPrefetchable, + ) + .set_address(addr) + } + + fn io_bar(idx: usize, addr: u64) -> PciBarConfiguration { + PciBarConfiguration::new( + idx, + IO_SIZE, + PciBarRegionType::IoRegion, + PciBarPrefetchable::NotPrefetchable, + ) + .set_address(addr) + } + + fn rom_bar(addr: u64) -> PciBarConfiguration { + PciBarConfiguration::new( + ROM_BAR_IDX, + ROM_SIZE, + PciBarRegionType::Memory32BitRegion, + PciBarPrefetchable::NotPrefetchable, + ) + .set_address(addr) + } + + /// A minimal PciDevice around a real PciConfiguration. BAR reads return + /// the BAR index, so that tests can tell which BAR an access reached. + struct TestBarDevice { + configuration: PciConfiguration, + bar_regions: Vec, + commit_fail_bases: HashSet, + prepare_fail_bars: HashSet, + id: String, + bdf: PciBdf, + restoring: bool, + } + + impl TestBarDevice { + fn new(bars: &[PciBarConfiguration], state: Option) -> Self { + let restoring = state.is_some(); + let mut configuration = PciConfiguration::new( + 0, + 0, + 0, + PciClassCode::Other, + &TestSubclass::Other, + None, + PciHeaderType::Device, + 0, + 0, + None, + state, + ); + + let mut bar_regions = Vec::new(); + for bar in bars { + // On restore the registers come from the state; only the + // device-side BAR records are rebuilt, like real devices do. + if !restoring { + if bar.idx() == ROM_BAR_IDX { + configuration.add_pci_rom_bar(bar, 0x1).unwrap(); + } else { + configuration.add_pci_bar(bar).unwrap(); + } + } + bar_regions.push(*bar); + } + + TestBarDevice { + configuration, + bar_regions, + commit_fail_bases: HashSet::new(), + prepare_fail_bars: HashSet::new(), + id: TEST_DEV_ID.to_string(), + bdf: PciBdf::new(0, 0, TEST_DEV_SLOT, 0), + restoring, + } + } + } + + impl PciDevice for TestBarDevice { + fn write_config_register( + &mut self, + reg_idx: usize, + offset: u64, + data: &[u8], + ) -> (BarRelocation, Option>) { + ( + self.configuration + .write_config_register(reg_idx, offset, data), + None, + ) + } + + fn read_config_register(&mut self, reg_idx: usize) -> u32 { + self.configuration.read_reg(reg_idx) + } + + fn move_bar_prepare(&mut self, bar_idx: usize) -> Result<(), io::Error> { + if self.prepare_fail_bars.contains(&bar_idx) { + return Err(io::Error::other("injected device-prepare failure")); + } + Ok(()) + } + + fn move_bar_commit(&mut self, bar_idx: usize, new_base: u64) -> Result<(), io::Error> { + if self.commit_fail_bases.contains(&new_base) { + return Err(io::Error::other("injected device-commit failure")); + } + for bar in self.bar_regions.iter_mut() { + if bar.idx() == bar_idx { + *bar = bar.set_address(new_base); + return Ok(()); + } + } + Err(io::Error::other(format!("no BAR record for {bar_idx}"))) + } + + fn is_bar_released(&self, bar_idx: usize) -> bool { + self.configuration.is_bar_released(bar_idx) + } + + fn release_stale_bar(&mut self, bar_idx: usize, mapped_at: u64) -> bool { + self.configuration.release_stale_bar(bar_idx, mapped_at) + } + + fn on_bar_installed(&mut self, bar_idx: usize) { + self.configuration.on_bar_installed(bar_idx); + } + + fn pending_bar_installs(&self) -> Vec { + self.configuration.pending_bar_installs() + } + + fn read_bar(&mut self, base: u64, _offset: u64, data: &mut [u8]) { + let marker = self + .bar_regions + .iter() + .find(|bar| bar.addr() == base) + .map_or(0xee, |bar| bar.idx() as u8); + if let Some(b) = data.first_mut() { + *b = marker; + } + } + + fn as_any_mut(&mut self) -> &mut dyn Any { + self + } + + fn id(&self) -> Option { + Some(self.id.clone()) + } + + fn bdf(&self) -> PciBdf { + self.bdf + } + } + + impl BusDevice for TestBarDevice { + fn read(&mut self, base: u64, offset: u64, data: &mut [u8]) { + self.read_bar(base, offset, data); + } + } + + struct BarBench { + address_manager: Arc, + pci_bus: Arc>, + config_mmio: PciConfigMmio, + device: Arc>, + } + + fn test_address_manager(mmio32_windows: &[(u64, u64)]) -> Arc { + let hv = hypervisor::new().unwrap(); + let vm = hv + .create_vm(hypervisor::HypervisorVmConfig::default()) + .unwrap(); + Arc::new(AddressManager { + allocator: Arc::new(Mutex::new( + SystemAllocator::new( + GuestAddress(0x1000), + 0xffff, + GuestAddress(0x1000_0000), + 0x100_0000, + #[cfg(target_arch = "x86_64")] + &[GsiApic::new(5, 19)], + #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))] + arch::IRQ_BASE, + ) + .unwrap(), + )), + io_bus: Arc::new(Bus::new()), + mmio_bus: Arc::new(Bus::new()), + vm, + device_tree: Arc::new(Mutex::new(DeviceTree::new())), + pci_mmio32_allocators: mmio32_windows + .iter() + .map(|&(base, size)| { + Arc::new(Mutex::new( + AddressAllocator::new(GuestAddress(base), size).unwrap(), + )) + }) + .collect(), + pci_mmio64_allocators: vec![Arc::new(Mutex::new( + AddressAllocator::new(GuestAddress(0x1_0000_0000), 0x1_0000_0000).unwrap(), + ))] + .into_boxed_slice(), + }) + } + + /// Register `device` like DeviceManager does: a PciBus entry, bus and + /// allocator ranges at `bars`, and a device-tree node. + fn bar_bench_with( + address_manager: Arc, + device: TestBarDevice, + bars: &[PciBarConfiguration], + ) -> BarBench { + let device = Arc::new(Mutex::new(device)); + + let mut pci_bus = PciBus::new( + Some(PciRoot::new(None)), + Arc::clone(&address_manager) as Arc, + ); + register_bar_device(&address_manager, &mut pci_bus, TEST_DEV_SLOT, &device, bars); + + let pci_bus = Arc::new(Mutex::new(pci_bus)); + BarBench { + address_manager, + config_mmio: PciConfigMmio::new(Arc::clone(&pci_bus)), + pci_bus, + device, + } + } + + /// The per-device part of bar_bench_with(). + fn register_bar_device( + address_manager: &Arc, + pci_bus: &mut PciBus, + slot: u8, + device: &Arc>, + bars: &[PciBarConfiguration], + ) { + assert_eq!(pci_bus.allocate_device_id(Some(slot)).unwrap(), slot); + pci_bus + .add_device( + slot, + Arc::clone(device) as Arc>, + Some(Arc::clone(device) as Arc), + ) + .unwrap(); + + let id = device.lock().unwrap().id.clone(); + let mut node = DeviceNode::new(id.clone(), None); + node.pci_bdf = Some(PciBdf::new(0, 0, slot, 0)); + for bar in bars { + // On restore the device decides, before anything is allocated or + // mapped, whether the BAR is left unmapped, like + // allocate_pci_bars(). + let released = { + let mut d = device.lock().unwrap(); + d.restoring && d.release_stale_bar(bar.idx(), bar.addr()) + }; + node.resources.push(Resource::PciBar { + index: bar.idx(), + base: bar.addr(), + size: bar.size(), + type_: bar.region_type().into(), + prefetchable: false, + }); + if released { + continue; + } + match bar.region_type() { + PciBarRegionType::IoRegion => { + address_manager + .allocator + .lock() + .unwrap() + .allocate_io_addresses( + Some(GuestAddress(bar.addr())), + bar.size() as GuestUsize, + None, + ) + .unwrap(); + address_manager + .io_bus + .insert( + Arc::clone(device) as Arc, + bar.addr(), + bar.size(), + ) + .unwrap(); + } + _ => { + address_manager.pci_mmio32_allocators[0] + .lock() + .unwrap() + .allocate( + Some(GuestAddress(bar.addr())), + bar.size() as GuestUsize, + Some(bar.size()), + ) + .unwrap(); + address_manager + .mmio_bus + .insert( + Arc::clone(device) as Arc, + bar.addr(), + bar.size(), + ) + .unwrap(); + } + } + } + address_manager.device_tree.lock().unwrap().insert(id, node); + } + + fn bar_bench(bars: &[PciBarConfiguration]) -> BarBench { + let mut device = TestBarDevice::new(bars, None); + // Boot-style initial state: decode enabled, BARs mapped. + device.configuration.write_config_register( + COMMAND_REG, + 0, + &((MSE | IOSE) as u16).to_le_bytes(), + ); + bar_bench_with( + test_address_manager(&[(MMIO32_BASE, MMIO32_SIZE)]), + device, + bars, + ) + } + + impl BarBench { + /// A guest-style dword config write through ECAM. + fn cfg_write(&mut self, reg: usize, value: u32) { + self.cfg_write_at(TEST_DEV_SLOT, reg, value); + } + + fn cfg_write_at(&mut self, slot: u8, reg: usize, value: u32) { + let offset = (u64::from(slot) << 15) | ((reg as u64) << 2); + BusDevice::write(&mut self.config_mmio, 0, offset, &value.to_le_bytes()); + } + + fn cfg_read(&mut self, reg: usize) -> u32 { + self.cfg_read_at(TEST_DEV_SLOT, reg) + } + + fn cfg_read_at(&mut self, slot: u8, reg: usize) -> u32 { + let offset = (u64::from(slot) << 15) | ((reg as u64) << 2); + let mut data = [0u8; 4]; + BusDevice::read(&mut self.config_mmio, 0, offset, &mut data); + u32::from_le_bytes(data) + } + + /// Add a second device at `slot`, set up like bar_bench(). + fn add_device( + &mut self, + slot: u8, + bars: &[PciBarConfiguration], + ) -> Arc> { + let mut device = TestBarDevice::new(bars, None); + device.id = format!("{TEST_DEV_ID}_{slot}"); + device.bdf = PciBdf::new(0, 0, slot, 0); + device.configuration.write_config_register( + COMMAND_REG, + 0, + &((MSE | IOSE) as u16).to_le_bytes(), + ); + let device = Arc::new(Mutex::new(device)); + register_bar_device( + &self.address_manager, + &mut self.pci_bus.lock().unwrap(), + slot, + &device, + bars, + ); + device + } + + /// The BAR is released awaiting install (nothing backs it). + fn released(&self, bar_idx: usize) -> bool { + self.released_of(&self.device, bar_idx) + } + + fn released_of(&self, device: &Arc>, bar_idx: usize) -> bool { + device + .lock() + .unwrap() + .configuration + .is_bar_released(bar_idx) + } + + /// Read one byte through the mmio_bus: the BAR marker, or None. + fn mmio_probe(&self, addr: u64) -> Option { + let mut data = [0u8; 1]; + self.address_manager + .mmio_bus + .read(addr, &mut data) + .ok() + .map(|_| data[0]) + } + + fn io_probe(&self, addr: u64) -> Option { + let mut data = [0u8; 1]; + self.address_manager + .io_bus + .read(addr, &mut data) + .ok() + .map(|_| data[0]) + } + + fn mmio32_range_free(&self, base: u64, size: u64) -> bool { + let mut allocator = self.address_manager.pci_mmio32_allocators[0] + .lock() + .unwrap(); + if allocator + .allocate(Some(GuestAddress(base)), size as GuestUsize, Some(size)) + .is_some() + { + allocator.free(GuestAddress(base), size as GuestUsize); + true + } else { + false + } + } + + fn io_range_free(&self, base: u64, size: u64) -> bool { + let mut allocator = self.address_manager.allocator.lock().unwrap(); + if allocator + .allocate_io_addresses(Some(GuestAddress(base)), size as GuestUsize, None) + .is_some() + { + allocator.free_io_addresses(GuestAddress(base), size as GuestUsize); + true + } else { + false + } + } + + fn tree_bar_base(&self, bar_idx: usize) -> Option { + self.tree_bar_base_of(&self.device, bar_idx) + } + + fn tree_bar_base_of( + &self, + device: &Arc>, + bar_idx: usize, + ) -> Option { + let id = device.lock().unwrap().id.clone(); + self.address_manager + .device_tree + .lock() + .unwrap() + .get(&id) + .and_then(|node| { + node.resources.iter().find_map(|resource| match resource { + Resource::PciBar { index, base, .. } if *index == bar_idx => Some(*base), + _ => None, + }) + }) + } + + /// Assert that the memory BAR released from `addr` has no allocator + /// or bus range; its device-tree resource keeps `addr`. + fn assert_released(&self, bar_idx: usize, addr: u64) { + assert!(self.released(bar_idx), "BAR {bar_idx} should be released"); + assert!( + self.mmio32_range_free(addr, BAR_SIZE), + "allocator range 0x{addr:x} should be free" + ); + assert_eq!(self.mmio_probe(addr), None, "bus range 0x{addr:x} remains"); + assert_eq!( + self.tree_bar_base(bar_idx), + Some(addr), + "tree resource must keep the released-from base" + ); + } + + /// Asserts the full mapped state of one memory BAR at `addr`. + fn assert_mapped(&self, bar_idx: usize, addr: u64) { + self.assert_mapped_of(&self.device, bar_idx, addr); + } + + fn assert_mapped_of(&self, device: &Arc>, bar_idx: usize, addr: u64) { + assert!( + !self.released_of(device, bar_idx), + "BAR {bar_idx} still released" + ); + assert!( + !self.mmio32_range_free(addr, BAR_SIZE), + "allocator range 0x{addr:x} should be occupied" + ); + assert_eq!( + self.mmio_probe(addr), + Some(bar_idx as u8), + "bus access at 0x{addr:x} should reach BAR {bar_idx}" + ); + assert_eq!(self.tree_bar_base_of(device, bar_idx), Some(addr)); + } + } + + // Swap both BARs of a device with decode off, then enable decode: no + // transient overlap. + #[test] + fn test_bar_swap_relocates_both_bars_through_vmm() { + let mut bench = bar_bench(&[mem_bar(0, BAR0_ADDR), mem_bar(1, BAR1_ADDR)]); + bench.assert_mapped(0, BAR0_ADDR); + bench.assert_mapped(1, BAR1_ADDR); + + bench.cfg_write(COMMAND_REG, 0); + // Each decode-off BAR write releases eagerly and in full. + bench.cfg_write(BAR0_REG, BAR1_ADDR as u32); + bench.assert_released(0, BAR0_ADDR); + bench.cfg_write(BAR1_REG, BAR0_ADDR as u32); + bench.assert_released(1, BAR1_ADDR); + + // The registers carry the guest-written targets mid-window. + assert_eq!(bench.cfg_read(BAR0_REG) & !0xf, BAR1_ADDR as u32); + assert_eq!(bench.cfg_read(BAR1_REG) & !0xf, BAR0_ADDR as u32); + + // Enabling decode installs both at their swapped addresses. + bench.cfg_write(COMMAND_REG, MSE); + bench.assert_mapped(0, BAR1_ADDR); + bench.assert_mapped(1, BAR0_ADDR); + } + + // A target in another PCI segment's window is rejected. + #[test] + fn test_bar_move_into_other_segment_window_rejected() { + const WIN_B_BASE: u64 = MMIO32_BASE + MMIO32_SIZE; + // Valid inside window B, but outside the BAR's own window A. + const TARGET_IN_B: u64 = WIN_B_BASE + 0x10_0000; + + let am = test_address_manager(&[(MMIO32_BASE, MMIO32_SIZE), (WIN_B_BASE, MMIO32_SIZE)]); + let mut device = TestBarDevice::new(&[mem_bar(0, BAR0_ADDR)], None); + device.configuration.write_config_register( + COMMAND_REG, + 0, + &((MSE | IOSE) as u16).to_le_bytes(), + ); + let mut bench = bar_bench_with(am, device, &[mem_bar(0, BAR0_ADDR)]); + bench.assert_mapped(0, BAR0_ADDR); + + // Reprogram (decode off) to a valid address in the SIBLING window B. + bench.cfg_write(COMMAND_REG, 0); + bench.cfg_write(BAR0_REG, TARGET_IN_B as u32); + bench.assert_released(0, BAR0_ADDR); + + // The BAR stays released and window B is untouched. + bench.cfg_write(COMMAND_REG, MSE); + assert!(bench.released(0), "cross-segment target must be rejected"); + { + let mut win_b = bench.address_manager.pci_mmio32_allocators[1] + .lock() + .unwrap(); + assert!( + win_b + .allocate( + Some(GuestAddress(TARGET_IN_B)), + BAR_SIZE as GuestUsize, + Some(BAR_SIZE), + ) + .is_some(), + "window B must be untouched by the rejected move" + ); + win_b.free(GuestAddress(TARGET_IN_B), BAR_SIZE as GuestUsize); + } + + // Recovery: a valid in-segment (window A) target installs at the BAR + // write, as MSE is on, and survives a decode toggle. + bench.cfg_write(BAR0_REG, BAR1_ADDR as u32); + bench.cfg_write(COMMAND_REG, 0); + bench.cfg_write(COMMAND_REG, MSE); + bench.assert_mapped(0, BAR1_ADDR); + } + + // A snapshot taken with a BAR released and decode off, restored into a + // fresh VMM: the BAR stays unmapped until decode is enabled. + #[test] + fn test_mid_window_restore_unmaps_undecoded_bar_until_enable() { + // Source side: enter the window, then snapshot the config space. + let mut bench = bar_bench(&[mem_bar(0, BAR0_ADDR)]); + bench.cfg_write(COMMAND_REG, 0); + bench.cfg_write(BAR0_REG, BAR1_ADDR as u32); + bench.assert_released(0, BAR0_ADDR); + let state: PciConfigurationState = bench + .device + .lock() + .unwrap() + .configuration + .snapshot() + .unwrap() + .to_state() + .unwrap(); + + // Restore: the BAR is left unmapped, as its space is undecoded. + let device = TestBarDevice::new(&[mem_bar(0, BAR0_ADDR)], Some(state)); + let mut restored = bar_bench_with( + test_address_manager(&[(MMIO32_BASE, MMIO32_SIZE)]), + device, + &[mem_bar(0, BAR0_ADDR)], + ); + + // Unmapped, with the register holding the target. + assert!(restored.released(0)); + assert_eq!(restored.mmio_probe(BAR0_ADDR), None); + assert!(restored.mmio32_range_free(BAR0_ADDR, BAR_SIZE)); + assert_eq!(restored.cfg_read(BAR0_REG) & !0xf, BAR1_ADDR as u32); + + // Post-restore decode enable: the drain installs at the target. + restored.cfg_write(COMMAND_REG, MSE); + restored.assert_mapped(0, BAR1_ADDR); + assert_eq!(restored.mmio_probe(BAR0_ADDR), None); + } + + /// Snapshot the device's config space, as a migration does. + fn config_state(bench: &BarBench) -> PciConfigurationState { + bench + .device + .lock() + .unwrap() + .configuration + .snapshot() + .unwrap() + .to_state() + .unwrap() + } + + /// Restore `state` with the BAR at `base`, its device-tree address. + fn restore_bench(state: PciConfigurationState, base: u64) -> BarBench { + let device = TestBarDevice::new(&[mem_bar(0, base)], Some(state)); + bar_bench_with( + test_address_manager(&[(MMIO32_BASE, MMIO32_SIZE)]), + device, + &[mem_bar(0, base)], + ) + } + + // A decoded BAR whose register names its mapping is left alone by restore. + #[test] + fn test_restore_keeps_decoded_bar_at_its_register() { + let mut bench = bar_bench(&[mem_bar(0, BAR0_ADDR)]); + bench.cfg_write(COMMAND_REG, MSE); + let state = config_state(&bench); + + let restored = restore_bench(state, BAR0_ADDR); + restored.assert_mapped(0, BAR0_ADDR); + } + + // A failed install pending at snapshot time: the register names the + // target, the device tree the old base. Restore leaves the old base + // unmapped; the guest's next write to the device installs at the + // register. + #[test] + fn test_restore_reinstalls_decoded_bar_at_its_register() { + const DEV_B_SLOT: u8 = 2; + + // Source side: A's move onto B's range fails and stays pending. + let mut bench = bar_bench(&[mem_bar(0, BAR0_ADDR)]); + let b = bench.add_device(DEV_B_SLOT, &[mem_bar(0, BAR1_ADDR)]); + bench.cfg_write(COMMAND_REG, MSE); + bench.cfg_write(BAR0_REG, BAR1_ADDR as u32); + bench.assert_released(0, BAR0_ADDR); + bench.assert_mapped_of(&b, 0, BAR1_ADDR); + let state = config_state(&bench); + + // Restored without B, the target is free, but nothing installs until + // the guest writes the device: a COMMAND write does. + let mut restored = restore_bench(state, BAR0_ADDR); + restored.assert_released(0, BAR0_ADDR); + assert_eq!(restored.cfg_read(BAR0_REG) & !0xf, BAR1_ADDR as u32); + restored.cfg_write(COMMAND_REG, MSE); + restored.assert_mapped(0, BAR1_ADDR); + assert!(restored.mmio32_range_free(BAR0_ADDR, BAR_SIZE)); + assert_eq!(restored.mmio_probe(BAR0_ADDR), None); + } + + // The same, with the target still held by another restored device: the + // BAR stays released until the holder moves away. + #[test] + fn test_restore_mismatched_bar_waits_for_holder() { + const DEV_B_SLOT: u8 = 2; + + let mut bench = bar_bench(&[mem_bar(0, BAR0_ADDR)]); + bench.add_device(DEV_B_SLOT, &[mem_bar(0, BAR1_ADDR)]); + bench.cfg_write(COMMAND_REG, MSE); + bench.cfg_write(BAR0_REG, BAR1_ADDR as u32); + bench.assert_released(0, BAR0_ADDR); + let state = config_state(&bench); + + let mut restored = restore_bench(state, BAR0_ADDR); + let b = restored.add_device(DEV_B_SLOT, &[mem_bar(0, BAR1_ADDR)]); + restored.assert_released(0, BAR0_ADDR); + restored.assert_mapped_of(&b, 0, BAR1_ADDR); + assert_eq!(restored.cfg_read(BAR0_REG) & !0xf, BAR1_ADDR as u32); + + // B moves away: A's install is retried. + restored.cfg_write_at(DEV_B_SLOT, BAR0_REG, BAR0_ADDR as u32); + restored.assert_mapped_of(&b, 0, BAR0_ADDR); + restored.assert_mapped(0, BAR1_ADDR); + } + + // A failing device commit unwinds the allocator and bus; the next COMMAND + // write retries. + // A release that fails keeps the BAR mapped at its old address and + // skips its install; the guest's next move releases it again. + #[test] + fn test_release_failure_keeps_bar_mapped_and_skips_install() { + const NEW_ADDR: u64 = 0x8030_0000; + + let mut bench = bar_bench(&[mem_bar(0, BAR0_ADDR)]); + bench.device.lock().unwrap().prepare_fail_bars.insert(0); + bench.cfg_write(BAR0_REG, BAR1_ADDR as u32); + + // Still mapped at the old address, with the register at the target. + assert!(!bench.released(0)); + assert!(!bench.mmio32_range_free(BAR0_ADDR, BAR_SIZE)); + assert_eq!(bench.mmio_probe(BAR0_ADDR), Some(0)); + assert!(bench.mmio32_range_free(BAR1_ADDR, BAR_SIZE)); + assert_eq!(bench.tree_bar_base(0), Some(BAR0_ADDR)); + assert_eq!(bench.cfg_read(BAR0_REG) & !0xf, BAR1_ADDR as u32); + + // Not owed an install: a COMMAND write changes nothing. + bench.cfg_write(COMMAND_REG, MSE); + assert!(!bench.released(0)); + assert!(bench.mmio32_range_free(BAR1_ADDR, BAR_SIZE)); + assert_eq!(bench.mmio_probe(BAR0_ADDR), Some(0)); + + // The next move releases it again and installs at the new target. + bench.device.lock().unwrap().prepare_fail_bars.clear(); + bench.cfg_write(BAR0_REG, NEW_ADDR as u32); + bench.assert_mapped(0, NEW_ADDR); + assert!(bench.mmio32_range_free(BAR0_ADDR, BAR_SIZE)); + assert_eq!(bench.mmio_probe(BAR0_ADDR), None); + } + + #[test] + fn test_install_device_commit_failure_unwinds_and_command_write_recovers() { + let mut bench = bar_bench(&[mem_bar(0, BAR0_ADDR)]); + bench.cfg_write(COMMAND_REG, 0); + bench.cfg_write(BAR0_REG, BAR1_ADDR as u32); + + bench + .device + .lock() + .unwrap() + .commit_fail_bases + .insert(BAR1_ADDR); + bench.cfg_write(COMMAND_REG, MSE); + + // Fully released, with the target kept in config space. + assert_eq!(bench.cfg_read(COMMAND_REG) & MSE, MSE); + assert!(bench.released(0)); + assert!(bench.mmio32_range_free(BAR1_ADDR, BAR_SIZE)); + assert_eq!(bench.mmio_probe(BAR1_ADDR), None); + assert!(bench.mmio32_range_free(BAR0_ADDR, BAR_SIZE)); + assert_eq!(bench.cfg_read(BAR0_REG) & !0xf, BAR1_ADDR as u32); + + // Any COMMAND write with decode on is the retry handle. + bench.device.lock().unwrap().commit_fail_bases.clear(); + bench.cfg_write(COMMAND_REG, MSE); + bench.assert_mapped(0, BAR1_ADDR); + } + + // A target outside every MMIO window fails to allocate; rewriting it to a + // valid address installs it at once. + #[test] + fn test_install_alloc_failure_stays_pending_and_new_target_installs_at_once() { + let mut bench = bar_bench(&[mem_bar(0, BAR0_ADDR)]); + bench.cfg_write(COMMAND_REG, 0); + bench.cfg_write(BAR0_REG, OUT_OF_WINDOW_ADDR as u32); + bench.assert_released(0, BAR0_ADDR); + + bench.cfg_write(COMMAND_REG, MSE); + assert!(bench.released(0)); + assert!(bench.mmio32_range_free(BAR0_ADDR, BAR_SIZE)); + + // With decode on, the rewrite itself installs the BAR. + bench.cfg_write(BAR0_REG, BAR1_ADDR as u32); + bench.assert_mapped(0, BAR1_ADDR); + } + + // A bus insert conflict returns the allocator range; the next COMMAND + // write retries. + #[test] + fn test_install_bus_conflict_unwinds_allocator_and_command_write_recovers() { + struct Blocker; + impl BusDeviceSync for Blocker {} + + let mut bench = bar_bench(&[mem_bar(0, BAR0_ADDR)]); + bench.cfg_write(COMMAND_REG, 0); + bench.cfg_write(BAR0_REG, BAR1_ADDR as u32); + + bench + .address_manager + .mmio_bus + .insert(Arc::new(Blocker), BAR1_ADDR, BAR_SIZE) + .unwrap(); + bench.cfg_write(COMMAND_REG, MSE); + + assert!(bench.released(0)); + assert!( + bench.mmio32_range_free(BAR1_ADDR, BAR_SIZE), + "allocator range must be unwound after the bus conflict" + ); + + bench + .address_manager + .mmio_bus + .remove(BAR1_ADDR, BAR_SIZE) + .unwrap(); + bench.cfg_write(COMMAND_REG, MSE); + bench.assert_mapped(0, BAR1_ADDR); + } + + // A BAR moved onto another device's range is installed once that device + // moves away. + #[test] + fn test_other_device_release_retries_failed_install() { + const DEV_B_SLOT: u8 = 2; + + let mut bench = bar_bench(&[mem_bar(0, BAR0_ADDR)]); + let a = Arc::clone(&bench.device); + let b = bench.add_device(DEV_B_SLOT, &[mem_bar(0, BAR1_ADDR)]); + bench.assert_mapped_of(&a, 0, BAR0_ADDR); + bench.assert_mapped_of(&b, 0, BAR1_ADDR); + + // A moves onto B's range: its install fails. + bench.cfg_write(BAR0_REG, BAR1_ADDR as u32); + assert!(bench.released_of(&a, 0)); + assert!(bench.mmio32_range_free(BAR0_ADDR, BAR_SIZE)); + bench.assert_mapped_of(&b, 0, BAR1_ADDR); + assert_eq!( + bench.cfg_read_at(TEST_DEV_SLOT, BAR0_REG) & !0xf, + BAR1_ADDR as u32 + ); + + // B moves away: its own plan installs it, then the retry installs A. + bench.cfg_write_at(DEV_B_SLOT, BAR0_REG, BAR0_ADDR as u32); + bench.assert_mapped_of(&a, 0, BAR1_ADDR); + bench.assert_mapped_of(&b, 0, BAR0_ADDR); + } + + // IO BARs are gated on IOSE, through the real PIO path. + #[test] + fn test_io_bar_release_and_drain_gated_on_iose() { + let mut bench = bar_bench(&[io_bar(0, IO_OLD)]); + assert_eq!(bench.io_probe(IO_OLD), Some(0)); + + bench.cfg_write(COMMAND_REG, 0); + bench.cfg_write(BAR0_REG, IO_NEW as u32); + + // Released from the PIO side eagerly. + assert!(bench.released(0)); + assert!(bench.io_range_free(IO_OLD, IO_SIZE)); + assert_eq!(bench.io_probe(IO_OLD), None); + + // MSE alone must not drain an IO BAR. + bench.cfg_write(COMMAND_REG, MSE); + assert!(bench.released(0)); + assert_eq!(bench.io_probe(IO_NEW), None); + + // IOSE drains it. + bench.cfg_write(COMMAND_REG, MSE | IOSE); + assert!(!bench.released(0)); + assert_eq!(bench.io_probe(IO_NEW), Some(0)); + assert!(!bench.io_range_free(IO_NEW, IO_SIZE)); + assert_eq!(bench.tree_bar_base(0), Some(IO_NEW)); + } + + // Clearing a decode bit unmaps the BARs of that space; setting it again + // maps them back at their registers. + #[test] + fn test_decode_clear_unmaps_bar_until_reenable() { + let mut bench = bar_bench(&[mem_bar(0, BAR0_ADDR), io_bar(1, IO_OLD)]); + bench.cfg_write(COMMAND_REG, MSE | IOSE); + bench.assert_mapped(0, BAR0_ADDR); + assert_eq!(bench.io_probe(IO_OLD), Some(1)); + + // MSE off: the memory BAR is released, the IO BAR untouched. + bench.cfg_write(COMMAND_REG, IOSE); + bench.assert_released(0, BAR0_ADDR); + assert_eq!(bench.io_probe(IO_OLD), Some(1)); + assert_eq!(bench.cfg_read(BAR0_REG) & !0xf, BAR0_ADDR as u32); + + // MSE on: installed at the unchanged register. + bench.cfg_write(COMMAND_REG, MSE | IOSE); + bench.assert_mapped(0, BAR0_ADDR); + + // IOSE off: the IO BAR is released, the memory BAR untouched. + bench.cfg_write(COMMAND_REG, MSE); + assert!(bench.released(1)); + assert_eq!(bench.io_probe(IO_OLD), None); + assert!(bench.io_range_free(IO_OLD, IO_SIZE)); + assert_eq!(bench.tree_bar_base(1), Some(IO_OLD)); + bench.assert_mapped(0, BAR0_ADDR); + + bench.cfg_write(COMMAND_REG, MSE | IOSE); + assert!(!bench.released(1)); + assert_eq!(bench.io_probe(IO_OLD), Some(1)); + } + + // A BAR moved onto a range whose holder then stops decoding is installed + // when the holder's space is disabled, as Windows expects while it cycles + // several devices. + #[test] + fn test_other_device_decode_clear_retries_failed_install() { + const DEV_B_SLOT: u8 = 2; + + let mut bench = bar_bench(&[mem_bar(0, BAR0_ADDR)]); + let a = Arc::clone(&bench.device); + let b = bench.add_device(DEV_B_SLOT, &[mem_bar(0, BAR1_ADDR)]); + bench.cfg_write(COMMAND_REG, MSE); + bench.assert_mapped_of(&a, 0, BAR0_ADDR); + bench.assert_mapped_of(&b, 0, BAR1_ADDR); + + // B moves onto A's range while A decodes: its install fails. + bench.cfg_write_at(DEV_B_SLOT, BAR0_REG, BAR0_ADDR as u32); + assert!(bench.released_of(&b, 0)); + assert!(bench.mmio32_range_free(BAR1_ADDR, BAR_SIZE)); + bench.assert_mapped_of(&a, 0, BAR0_ADDR); + + // A stops decoding: its BAR is unmapped and B's install is retried. + bench.cfg_write(COMMAND_REG, 0); + assert!(bench.released_of(&a, 0)); + bench.assert_mapped_of(&b, 0, BAR0_ADDR); + + // A decodes again while B holds its range: A stays pending until it is + // moved away. + bench.cfg_write(COMMAND_REG, MSE); + assert!(bench.released_of(&a, 0)); + bench.assert_mapped_of(&b, 0, BAR0_ADDR); + bench.cfg_write(BAR0_REG, BAR1_ADDR as u32); + bench.assert_mapped_of(&a, 0, BAR1_ADDR); + bench.assert_mapped_of(&b, 0, BAR0_ADDR); + } + + // The expansion ROM takes the memory BAR path, gated on MSE. + #[test] + fn test_rom_bar_reprogram_defers_and_lands_via_mse() { + let mut bench = bar_bench(&[mem_bar(0, BAR0_ADDR), rom_bar(ROM_ADDR)]); + assert_eq!(bench.mmio_probe(ROM_ADDR), Some(ROM_BAR_IDX as u8)); + + bench.cfg_write(COMMAND_REG, 0); + bench.cfg_write(ROM_BAR_REG, ROM_NEW_ADDR as u32 | 0x1); + + assert!(bench.released(ROM_BAR_IDX)); + assert!(bench.mmio32_range_free(ROM_ADDR, ROM_SIZE)); + assert_eq!(bench.mmio_probe(ROM_ADDR), None); + // Disabling MSE released the memory BAR as well. + bench.assert_released(0, BAR0_ADDR); + + bench.cfg_write(COMMAND_REG, MSE); + assert!(!bench.released(ROM_BAR_IDX)); + assert_eq!(bench.mmio_probe(ROM_NEW_ADDR), Some(ROM_BAR_IDX as u8)); + assert_eq!(bench.tree_bar_base(ROM_BAR_IDX), Some(ROM_NEW_ADDR)); + bench.assert_mapped(0, BAR0_ADDR); + } } diff --git a/vmm/src/pci_segment.rs b/vmm/src/pci_segment.rs index 5bd3f353b7..55eae7324d 100644 --- a/vmm/src/pci_segment.rs +++ b/vmm/src/pci_segment.rs @@ -604,14 +604,19 @@ mod tests { #[derive(Debug)] struct MockDeviceRelocation; impl DeviceRelocation for MockDeviceRelocation { - fn move_bar( + fn move_bar_prepare( &self, - _bar_idx: usize, - _old_base: u64, - _new_base: u64, - _len: u64, _pci_dev: &mut dyn pci::PciDevice, - _region_type: pci::PciBarRegionType, + _params: &pci::ReleaseParams, + ) -> Result<(), io::Error> { + Ok(()) + } + + fn move_bar_commit( + &self, + _pci_dev: &mut dyn pci::PciDevice, + _bus_device: &Arc, + _params: &pci::InstallParams, ) -> Result<(), io::Error> { Ok(()) } From ed8500964431062d08ed0482c522d23a1f2b3d42 Mon Sep 17 00:00:00 2001 From: CMGS Date: Tue, 10 Nov 2026 20:08:24 +0800 Subject: [PATCH 08/11] virtio-devices: balloon: Remap released copy-on-write memory A VM restored with memory_restore_mode=copyonwrite maps the snapshot file MAP_PRIVATE over its guest RAM. MADV_DONTNEED there only drops the private copy: the next guest touch of a released page, even a write, faults the page back in from the snapshot file with read-around. With free page reporting on, every page the guest frees and reuses pays that read. Map anonymous memory over the 2 MiB-aligned part of each released range instead, so a reused page is zero-filled without I/O. The head and tail below 2 MiB keep MADV_DONTNEED. This covers free page reporting, which reports pageblock-sized ranges. Inflate releases at most 256 pages (1 MiB) per batch, so it releases each batch with MADV_DONTNEED at once and tracks the inflated 4 KiB pages per 2 MiB chunk across batches. A chunk the guest inflates completely is remapped the same way, and a deflated page clears its bit. The tracking costs at most one 64-byte bitmap per partly inflated chunk. In the worst case, alternate 2 MiB blocks reported, that gives one mapping per 2 MiB of guest RAM, which stays under the default vm.max_map_count for guests up to about 100 GiB. The new mapping keeps the region's MAP_NORESERVE, and a failed mmap falls back to MADV_DONTNEED. Kernels before 6.12 can leave a hole if MAP_FIXED fails after the unmap. The remapped range gets MADV_DONTDUMP like the rest of guest RAM, and MADV_NOHUGEPAGE: a private copy of a file page is 4 KiB today, and hugepage memory never takes the copy-on-write restore path, so a reused page keeps costing 4 KiB instead of a 2 MiB host page. An overlay region still records itself as anonymous, so the memory manager notes that the overlay was mapped and the balloon remaps only then. OnDemand restore never remaps, which would drop the userfaultfd registration. Gates: fork CI on e6221b942 and node1 fmt, typos, clippy (4 feature sets), fuzz check and virtio-devices tests; 16-clone hardware A/B and an inflate/deflate integrity run on a testbed host. Signed-off-by: CMGS --- fuzz/fuzz_targets/balloon.rs | 9 + virtio-devices/src/balloon.rs | 337 +++++++++++++++++++++++++++++++++- vmm/src/device_manager.rs | 1 + vmm/src/memory_manager.rs | 8 + 4 files changed, 351 insertions(+), 4 deletions(-) diff --git a/fuzz/fuzz_targets/balloon.rs b/fuzz/fuzz_targets/balloon.rs index 2199445987..c36d3f7279 100644 --- a/fuzz/fuzz_targets/balloon.rs +++ b/fuzz/fuzz_targets/balloon.rs @@ -96,6 +96,7 @@ fuzz_target!(|bytes: &[u8]| -> Corpus { SeccompAction::Allow, EventFd::new(EFD_NONBLOCK).unwrap(), None, + false, ) .unwrap(); balloon.set_access_platform(Arc::new(IdentityAccessPlatform {})); @@ -115,6 +116,7 @@ fuzz_target!(|bytes: &[u8]| -> Corpus { SeccompAction::Allow, EventFd::new(EFD_NONBLOCK).unwrap(), Some(state), + false, ); } } @@ -197,6 +199,7 @@ fuzz_target!(|bytes: &[u8]| -> Corpus { SeccompAction::Allow, EventFd::new(EFD_NONBLOCK).unwrap(), None, + false, ) .unwrap(); balloon_no_reporting.set_access_platform(Arc::new(IdentityAccessPlatform {})); @@ -244,6 +247,7 @@ fuzz_target!(|bytes: &[u8]| -> Corpus { SeccompAction::Allow, EventFd::new(EFD_NONBLOCK).unwrap(), None, + false, ) .unwrap(); balloon_reporting_empty.ack_features(1u64 << VIRTIO_BALLOON_F_REPORTING); @@ -459,6 +463,7 @@ fn exercise_stats_queue(bytes: &[u8], queue_data: &[u8]) { SeccompAction::Allow, EventFd::new(EFD_NONBLOCK).unwrap(), None, + false, ) { Ok(balloon) => balloon, Err(_) => return, @@ -594,6 +599,7 @@ fn run_failing_interrupt_case( SeccompAction::Allow, EventFd::new(EFD_NONBLOCK).unwrap(), None, + false, ) .unwrap(); balloon.ack_features(1u64 << VIRTIO_BALLOON_F_REPORTING); @@ -654,6 +660,7 @@ fn activate_with_too_few_queues(queue_data: &[u8]) { SeccompAction::Allow, EventFd::new(EFD_NONBLOCK).unwrap(), None, + false, ) .unwrap(); @@ -700,6 +707,7 @@ fn activate_reporting_acked_without_reporting_queue(queue_data: &[u8]) { SeccompAction::Allow, EventFd::new(EFD_NONBLOCK).unwrap(), None, + false, ) .unwrap(); balloon.ack_features(1u64 << VIRTIO_BALLOON_F_REPORTING); @@ -755,6 +763,7 @@ fn activate_reporting_available_unacked(queue_data: &[u8]) { SeccompAction::Allow, EventFd::new(EFD_NONBLOCK).unwrap(), None, + false, ) .unwrap(); diff --git a/virtio-devices/src/balloon.rs b/virtio-devices/src/balloon.rs index e068186d35..03f4d66b1a 100644 --- a/virtio-devices/src/balloon.rs +++ b/virtio-devices/src/balloon.rs @@ -14,6 +14,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +use std::collections::HashMap; use std::io::{self, Write}; use std::ops::Deref; use std::os::unix::io::AsRawFd; @@ -76,6 +77,9 @@ const VIRTIO_BALLOON_PAGE_SIZE: usize = 1 << VIRTIO_BALLOON_PFN_SHIFT; // Batch the number of PFNs handled in one pass const VIRTIO_BALLOON_PFNS_PER_BATCH: usize = 256; +const COW_REMAP_SIZE: u64 = 2 << 20; +const COW_CHUNK_WORDS: usize = COW_REMAP_SIZE as usize / VIRTIO_BALLOON_PAGE_SIZE / 64; + // Enable statistics virtqueue. const VIRTIO_BALLOON_F_STATS_VQ: u64 = 1; // Deflate balloon on OOM @@ -296,6 +300,8 @@ struct BalloonEpollHandler { pause_evt: EventFd, pbp: Option, access_platform: Option>, + cow_restored: bool, + inflated_chunks: HashMap, } impl BalloonEpollHandler { @@ -331,6 +337,7 @@ impl BalloonEpollHandler { memory: &GuestMemory, range_base: GuestAddress, range_len: usize, + cow_restored: bool, ) -> result::Result<(), Error> { let region = memory.find_region(range_base).ok_or(Error::GuestMemory( GuestMemoryError::InvalidGuestAddress(range_base), @@ -372,11 +379,86 @@ impl BalloonEpollHandler { } else { Ok(()) } + } else if cow_restored { + Self::remap_anonymous_range( + memory, + range_base, + len, + region.flags() & libc::MAP_NORESERVE, + ) } else { Self::advise_memory_range(memory, range_base, len as usize, libc::MADV_DONTNEED) } } + // DONTNEED would refault copy-on-write pages from the snapshot file. + fn remap_anonymous_range( + memory: &GuestMemory, + range_base: GuestAddress, + len: u64, + reserve_flag: libc::c_int, + ) -> result::Result<(), Error> { + let start = range_base.0; + let end = start + len; + let remap_start = start.next_multiple_of(COW_REMAP_SIZE).min(end); + let remap_end = (end - end % COW_REMAP_SIZE).max(remap_start); + if remap_start == remap_end { + return Self::advise_memory_range( + memory, + range_base, + len as usize, + libc::MADV_DONTNEED, + ); + } + for (base, part) in [(start, remap_start - start), (remap_end, end - remap_end)] { + if part != 0 { + Self::advise_memory_range( + memory, + GuestAddress(base), + part as usize, + libc::MADV_DONTNEED, + )?; + } + } + + let remap_len = (remap_end - remap_start) as usize; + let slice = memory + .get_slice(GuestAddress(remap_start), remap_len) + .map_err(Error::GuestMemory)?; + // SAFETY: the slice lies inside a live guest RAM mapping, and MAP_FIXED + // replaces exactly that window. + let addr = unsafe { + libc::mmap( + slice.ptr_guard_mut().as_ptr().cast(), + remap_len, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_FIXED | libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | reserve_flag, + -1, + 0, + ) + }; + if addr == libc::MAP_FAILED { + warn!( + "Failed to remap released memory at GPA 0x{remap_start:x}: {}", + io::Error::last_os_error() + ); + return Self::advise_memory_range( + memory, + GuestAddress(remap_start), + remap_len, + libc::MADV_DONTNEED, + ); + } + for advice in [libc::MADV_DONTDUMP, libc::MADV_NOHUGEPAGE] { + if let Err(e) = + Self::advise_memory_range(memory, GuestAddress(remap_start), remap_len, advice) + { + warn!("Failed to madvise remapped memory at GPA 0x{remap_start:x}: {e:?}"); + } + } + Ok(()) + } + fn release_memory_range_partial_page( pbp: &mut Option, memory: &GuestMemory, @@ -399,6 +481,7 @@ impl BalloonEpollHandler { memory, vm_memory::GuestAddress(pbp.as_ref().unwrap().addr), page_size as usize, + false, )?; pbp.as_mut().unwrap().reset(); @@ -442,7 +525,8 @@ impl BalloonEpollHandler { if previous_address.checked_add(VIRTIO_BALLOON_PAGE_SIZE as u64) == Some(address) { range_len += VIRTIO_BALLOON_PAGE_SIZE; } else { - if let Err(e) = Self::release_memory_range(memory, range_base, range_len) { + if let Err(e) = Self::release_memory_range(memory, range_base, range_len, false) + { warn!("Failed to release ballooned memory range: {e}"); } range_base = address; @@ -451,10 +535,41 @@ impl BalloonEpollHandler { previous_address = address; } - if let Err(e) = Self::release_memory_range(memory, range_base, range_len) { + if let Err(e) = Self::release_memory_range(memory, range_base, range_len, false) { warn!("Failed to release ballooned memory range: {e}"); } } + + if !self.cow_restored { + return; + } + for address in addresses.iter() { + let chunk = address.0 / COW_REMAP_SIZE; + let base = GuestAddress(chunk * COW_REMAP_SIZE); + let Some(region) = memory.find_region(base) else { + continue; + }; + if base.0 + COW_REMAP_SIZE > region.start_addr().0 + region.len() + || region.flags() & libc::MAP_SHARED != 0 + { + continue; + } + let page = (address.0 % COW_REMAP_SIZE) as usize / VIRTIO_BALLOON_PAGE_SIZE; + let bits = self.inflated_chunks.entry(chunk).or_default(); + bits[page / 64] |= 1 << (page % 64); + if *bits != [u64::MAX; COW_CHUNK_WORDS] { + continue; + } + self.inflated_chunks.remove(&chunk); + if let Err(e) = Self::remap_anonymous_range( + memory, + base, + COW_REMAP_SIZE, + region.flags() & libc::MAP_NORESERVE, + ) { + warn!("Failed to remap inflated memory at GPA 0x{:x}: {e}", base.0); + } + } } fn process_queue(&mut self, queue_index: u16) -> result::Result<(), Error> { @@ -513,7 +628,18 @@ impl BalloonEpollHandler { inflate_addresses.clear(); } } - DEFLATE_QUEUE => {} // Nothing to do on deflate + DEFLATE_QUEUE => { + let address = u64::from(pfn) << VIRTIO_BALLOON_PFN_SHIFT; + let chunk = address / COW_REMAP_SIZE; + if let Some(bits) = self.inflated_chunks.get_mut(&chunk) { + let page = + (address % COW_REMAP_SIZE) as usize / VIRTIO_BALLOON_PAGE_SIZE; + bits[page / 64] &= !(1 << (page % 64)); + if *bits == [0; COW_CHUNK_WORDS] { + self.inflated_chunks.remove(&chunk); + } + } + } _ => return Err(Error::InvalidQueueIndex(queue_index)), } } @@ -652,6 +778,7 @@ impl BalloonEpollHandler { desc_chain.memory(), desc.addr(), desc.len() as usize, + self.cow_restored, ) { warn!("Failed to release reported memory range: {e}"); } @@ -812,6 +939,7 @@ pub struct Balloon { stats_request_evt: EventFd, stats_request_sender: Option>, stats_cache: BalloonStatsCache, + cow_restored: bool, } impl Balloon { @@ -826,6 +954,7 @@ impl Balloon { seccomp_action: SeccompAction, exit_evt: EventFd, state: Option, + cow_restored: bool, ) -> io::Result { let mut queue_sizes = vec![QUEUE_SIZE; MIN_NUM_QUEUES as usize]; @@ -885,6 +1014,7 @@ impl Balloon { stats_request_evt, stats_request_sender: None, stats_cache: Arc::new(Mutex::new(None)), + cow_restored, }) } @@ -1067,6 +1197,8 @@ impl VirtioDevice for Balloon { pause_evt, pbp: None, access_platform: self.common.access_platform(), + cow_restored: self.cow_restored, + inflated_chunks: HashMap::new(), }; if let Err(e) = self.common.spawn_worker( @@ -1126,7 +1258,10 @@ impl Migratable for Balloon {} #[cfg(test)] mod tests { + use std::fs; + use vm_virtio::queue::testing::VirtQueue; + use vmm_sys_util::tempfile::TempFile; use super::*; @@ -1176,6 +1311,8 @@ mod tests { pause_evt: EventFd::new(EFD_NONBLOCK).unwrap(), pbp: None, access_platform: None, + cow_restored: false, + inflated_chunks: HashMap::new(), } } @@ -1218,7 +1355,7 @@ mod tests { memory.write_slice(&[0xa5], GuestAddress(0)).unwrap(); assert_eq!(memory.read_obj::(GuestAddress(0)).unwrap(), 0xa5); - let res = BalloonEpollHandler::release_memory_range(&memory, GuestAddress(0), 4096); + let res = BalloonEpollHandler::release_memory_range(&memory, GuestAddress(0), 4096, false); assert!(res.is_ok(), "release_memory_range failed: {res:?}"); assert_eq!(memory.read_obj::(GuestAddress(0)).unwrap(), 0x5a); assert_eq!(fs::read(backing_file.as_path()).unwrap(), original); @@ -1236,6 +1373,194 @@ mod tests { test_release_private_page(false); } + fn cow_restored_memory(size: u64) -> (GuestMemory, TempFile) { + let memory = GuestMemory::from_ranges(&[(GuestAddress(0), size as usize)]).unwrap(); + let backing_file = TempFile::new().unwrap(); + backing_file + .as_file() + .write_all(&vec![0x5a; size as usize]) + .unwrap(); + let host = memory.get_host_address(GuestAddress(0)).unwrap(); + // SAFETY: the window is the whole private anonymous region created above. + let ret = unsafe { + libc::mmap( + host.cast(), + size as usize, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_PRIVATE | libc::MAP_FIXED, + backing_file.as_file().as_raw_fd(), + 0, + ) + }; + assert_ne!(ret, libc::MAP_FAILED); + (memory, backing_file) + } + + fn has_vm_flag(addr: u64, flag: &str) -> bool { + let smaps = fs::read_to_string("/proc/self/smaps").unwrap(); + let mut inside = false; + for line in smaps.lines() { + if let Some((range, _)) = line.split_once(' ') + && let Some((start, end)) = range.split_once('-') + && let (Ok(start), Ok(end)) = + (u64::from_str_radix(start, 16), u64::from_str_radix(end, 16)) + { + inside = (start..end).contains(&addr); + } else if inside && let Some(flags) = line.strip_prefix("VmFlags:") { + return flags.split_whitespace().any(|f| f == flag); + } + } + panic!("no mapping at {addr:#x}"); + } + + #[test] + fn release_cow_restored_remaps_aligned_part() { + let page = get_page_size(); + let chunk = COW_REMAP_SIZE; + let (memory, backing_file) = cow_restored_memory(3 * chunk); + let original = fs::read(backing_file.as_path()).unwrap(); + for gpa in [0, page, chunk - page, chunk, 2 * chunk, 2 * chunk + page] { + memory.write_obj(0xa5u8, GuestAddress(gpa)).unwrap(); + } + + let len = (2 * chunk) as usize; + BalloonEpollHandler::release_memory_range(&memory, GuestAddress(page), len, true).unwrap(); + + for (gpa, value) in [ + (0, 0xa5), + (2 * chunk + page, 0xa5), + (page, 0x5a), + (chunk - page, 0x5a), + (2 * chunk, 0x5a), + (chunk, 0), + (2 * chunk - 1, 0), + ] { + assert_eq!(memory.read_obj::(GuestAddress(gpa)).unwrap(), value); + } + assert_eq!(fs::read(backing_file.as_path()).unwrap(), original); + let host = memory.get_host_address(GuestAddress(chunk)).unwrap() as u64; + assert!(has_vm_flag(host, "dd")); + assert!(has_vm_flag(host, "nh")); + assert!(!has_vm_flag(host - 1, "nh")); + } + + fn inflate_pfns( + handler: &mut BalloonEpollHandler, + memory: &GuestMemory, + pfns: impl Iterator, + ) { + let mut addresses: SmallVec<[GuestAddress; VIRTIO_BALLOON_PFNS_PER_BATCH]> = pfns + .map(|pfn| GuestAddress(pfn << VIRTIO_BALLOON_PFN_SHIFT)) + .collect(); + handler.process_inflate_addresses(memory, &mut addresses); + } + + #[test] + fn inflate_remaps_full_cow_chunk_across_batches() { + if get_page_size() as usize != VIRTIO_BALLOON_PAGE_SIZE { + return; + } + let chunk = COW_REMAP_SIZE; + let first = chunk >> VIRTIO_BALLOON_PFN_SHIFT; + let (memory, _backing_file) = cow_restored_memory(3 * chunk); + memory.write_obj(0xa5u8, GuestAddress(chunk)).unwrap(); + let mut handler = create_stats_handler( + &memory, + Queue::new(16).unwrap(), + BalloonStatsState::WaitingForInitialDescriptor, + ); + handler.cow_restored = true; + + inflate_pfns(&mut handler, &memory, first..first + 256); + assert_eq!(memory.read_obj::(GuestAddress(chunk)).unwrap(), 0x5a); + inflate_pfns(&mut handler, &memory, first + 256..first + 512); + + assert_eq!(memory.read_obj::(GuestAddress(chunk)).unwrap(), 0); + assert!(handler.inflated_chunks.is_empty()); + } + + #[test] + fn inflate_keeps_cow_chunk_with_deflated_page() { + const QUEUE_ADDRESS: GuestAddress = GuestAddress(0x1_0000); + const PFNS_ADDRESS: GuestAddress = GuestAddress(0x2_0000); + + if get_page_size() as usize != VIRTIO_BALLOON_PAGE_SIZE { + return; + } + let chunk = COW_REMAP_SIZE; + let first = chunk >> VIRTIO_BALLOON_PFN_SHIFT; + let (memory, _backing_file) = cow_restored_memory(3 * chunk); + let mut handler = create_stats_handler( + &memory, + Queue::new(16).unwrap(), + BalloonStatsState::WaitingForInitialDescriptor, + ); + handler.cow_restored = true; + inflate_pfns(&mut handler, &memory, first..first + 256); + + memory.write_obj(first as u32, PFNS_ADDRESS).unwrap(); + let deflate_queue = VirtQueue::new(QUEUE_ADDRESS, &memory, 16); + deflate_queue.dtable[0].set(PFNS_ADDRESS.0, size_of::() as u32, 0, 0); + deflate_queue.avail.ring[0].set(0); + deflate_queue.avail.idx.set(1); + handler.queues.push(deflate_queue.create_queue()); + handler.process_queue(DEFLATE_QUEUE).unwrap(); + memory.write_obj(0xa5u8, GuestAddress(chunk)).unwrap(); + + inflate_pfns(&mut handler, &memory, first + 256..first + 512); + + assert_eq!(memory.read_obj::(GuestAddress(chunk)).unwrap(), 0xa5); + assert_eq!( + memory.read_obj::(GuestAddress(chunk + 4096)).unwrap(), + 0x5a + ); + assert_eq!(handler.inflated_chunks.len(), 1); + } + + #[test] + fn inflate_tracks_nothing_without_cow_restore() { + if get_page_size() as usize != VIRTIO_BALLOON_PAGE_SIZE { + return; + } + let chunk = COW_REMAP_SIZE; + let first = chunk >> VIRTIO_BALLOON_PFN_SHIFT; + let (memory, _backing_file) = cow_restored_memory(3 * chunk); + let mut handler = create_stats_handler( + &memory, + Queue::new(16).unwrap(), + BalloonStatsState::WaitingForInitialDescriptor, + ); + + inflate_pfns(&mut handler, &memory, first..first + 256); + + assert!(handler.inflated_chunks.is_empty()); + assert_eq!(memory.read_obj::(GuestAddress(chunk)).unwrap(), 0x5a); + } + + #[test] + fn inflate_tracks_nothing_outside_guest_ram() { + if get_page_size() as usize != VIRTIO_BALLOON_PAGE_SIZE { + return; + } + let chunk = COW_REMAP_SIZE; + let pages_per_chunk = chunk >> VIRTIO_BALLOON_PFN_SHIFT; + let (memory, _backing_file) = cow_restored_memory(3 * chunk); + let mut handler = create_stats_handler( + &memory, + Queue::new(16).unwrap(), + BalloonStatsState::WaitingForInitialDescriptor, + ); + handler.cow_restored = true; + + inflate_pfns( + &mut handler, + &memory, + (4..260).map(|index| index * pages_per_chunk), + ); + + assert!(handler.inflated_chunks.is_empty()); + } + #[test] fn process_inflate_addresses_releases_coalesced_ranges() { let page_size = get_page_size() as usize; @@ -1391,6 +1716,7 @@ mod tests { SeccompAction::Allow, EventFd::new(EFD_NONBLOCK).unwrap(), None, + false, ) .unwrap(); @@ -1408,6 +1734,7 @@ mod tests { SeccompAction::Allow, EventFd::new(EFD_NONBLOCK).unwrap(), None, + false, ) .unwrap(); balloon.common.acked_features = 1u64 << VIRTIO_BALLOON_F_STATS_VQ; @@ -1429,6 +1756,7 @@ mod tests { SeccompAction::Allow, EventFd::new(EFD_NONBLOCK).unwrap(), None, + false, ) .unwrap(); balloon.common.acked_features = 1u64 << VIRTIO_BALLOON_F_STATS_VQ; @@ -1461,6 +1789,7 @@ mod tests { SeccompAction::Allow, EventFd::new(EFD_NONBLOCK).unwrap(), None, + false, ) .unwrap(); balloon.common.acked_features = 1u64 << VIRTIO_BALLOON_F_STATS_VQ; diff --git a/vmm/src/device_manager.rs b/vmm/src/device_manager.rs index 41e4a30dba..9164c5af09 100644 --- a/vmm/src/device_manager.rs +++ b/vmm/src/device_manager.rs @@ -4074,6 +4074,7 @@ impl DeviceManager { .map_err(DeviceManagerError::EventFd)?, state_from_id(snapshot, id.as_str()) .map_err(DeviceManagerError::RestoreGetState)?, + self.memory_manager.lock().unwrap().cow_restored(), ) .map_err(DeviceManagerError::CreateVirtioBalloon)?, )); diff --git a/vmm/src/memory_manager.rs b/vmm/src/memory_manager.rs index 7aa2d156b6..0461d506fa 100644 --- a/vmm/src/memory_manager.rs +++ b/vmm/src/memory_manager.rs @@ -387,6 +387,7 @@ pub struct MemoryManager { diff_snapshot_ranges: Option, diff_count: u32, cow_source: Option, + cow_restored: bool, memory_zones: MemoryZones, log_dirty: bool, // Enable dirty logging for created RAM regions arch_mem_regions: Vec, @@ -1169,6 +1170,7 @@ impl MemoryManager { ))); } do_mmap_cow_saved_regions(&guest_memory, &memory_file, saved_regions, self.thp)?; + self.cow_restored = true; // Landlock applies after the restore, so the pagemap is opened here. self.cow_source = match PageMap::open() { Ok(pagemap) => Some(CowSource { @@ -1526,6 +1528,11 @@ impl MemoryManager { Some(Arc::clone(&uffd_handler.uffd_registry)) } + /// True when guest RAM is a copy-on-write mapping of the snapshot file. + pub fn cow_restored(&self) -> bool { + self.cow_restored + } + /// True while an on-demand (UFFD) restore is still faulting in guest RAM. pub fn restoring(&self) -> bool { self.uffd_handler @@ -2495,6 +2502,7 @@ impl MemoryManager { diff_snapshot_ranges: None, diff_count: 0, cow_source: None, + cow_restored: false, memory_zones, guest_ram_mappings: Vec::new(), uffd_handler: None, From a8f410a1a50c5ea651e7a19ba56ced3c89b89aed Mon Sep 17 00:00:00 2001 From: CMGS Date: Tue, 10 Nov 2026 20:04:06 +0800 Subject: [PATCH 09/11] vmm: Do not mark the copy-on-write restore mapping MADV_HUGEPAGE A copy-on-write restore maps the snapshot file MAP_PRIVATE over guest RAM, and marked that mapping MADV_HUGEPAGE when thp is on. A page the guest writes becomes a private anonymous copy of one host base page (4 KiB on x86_64) with or without the hint. On a filesystem with large folios, the hint lets read faults map PMD-sized file folios read-only, but a read fault that misses the page cache can then request readahead of two PMD-sized folios, about 4 MiB, including the faults the restore path takes. Measured on x86_64 with Linux 6.12 and XFS, 16 copy-on-write clones of a 2 GiB guest, with and without the hint: - a restore on an idle host took p50 5.6 ms instead of 8.5 ms, and p50 8.9 ms instead of 47.8 ms with 16 clones restoring at once; - random reads of read-mostly guest memory ran about 3.5% slower, since the file-backed PMD mappings (about 448 MB per clone) are gone; streaming reads and CPU-bound work were unchanged. Restore latency sits on the clone path, so drop the hint from the overlay. The reserve policy is still applied, and the docs state the trade-off. Signed-off-by: CMGS --- docs/memory.md | 3 +++ docs/snapshot_restore.md | 11 +++++++++-- vmm/src/memory_manager.rs | 24 ++++++------------------ 3 files changed, 18 insertions(+), 20 deletions(-) diff --git a/docs/memory.md b/docs/memory.md index e6036321ce..5a5ec7ee7f 100644 --- a/docs/memory.md +++ b/docs/memory.md @@ -208,6 +208,9 @@ there will be fewer virtualisation related page faults. Unlike using `hugepages=on` a specific number of huge pages do not need to be allocated by the kernel. +A restore with `memory_restore_mode=copyonwrite` does not apply this option to +the restored memory. + By default this option is turned on. _Example_ diff --git a/docs/snapshot_restore.md b/docs/snapshot_restore.md index 415206a4b9..17522cc99c 100644 --- a/docs/snapshot_restore.md +++ b/docs/snapshot_restore.md @@ -221,8 +221,15 @@ Current constraints for `memory_restore_mode=copyonwrite`: `id`+`size` zone is fine), resizable RAM (`hotplug_size`, virtio-mem), KSM (`mergeable=on`), `--pvmemcontrol`, device passthrough (`--device`/`--user-device`/`--vdpa`), and snapshot ranges that are not - page-aligned single-region extents. Each region's `reserve` policy and the - THP policy are re-applied to the mapped region. + page-aligned single-region extents. Each region's `reserve` policy is + re-applied to the mapped region. THP is not. A page the guest writes becomes + a private anonymous copy of one host base page (4 KiB on x86_64) either way. + On a filesystem with large folios, `MADV_HUGEPAGE` lets read faults map + PMD-sized file folios (2 MiB on x86_64), which speeds up random reads of + read-mostly guest memory (by about 3.5% in one measurement). But a read fault + that misses the page cache can then request readahead of two PMD-sized + folios, about 4 MiB, which made the restore about 1.5 times slower on an idle + host and about 5 times slower with 16 VMs restoring at once. - A snapshot memory file shorter than the saved ranges is rejected up front (it would otherwise fault `SIGBUS` at run time). - `prefault` is rejected. diff --git a/vmm/src/memory_manager.rs b/vmm/src/memory_manager.rs index 0461d506fa..e9f8ccc1b5 100644 --- a/vmm/src/memory_manager.rs +++ b/vmm/src/memory_manager.rs @@ -1169,7 +1169,7 @@ impl MemoryManager { "snapshot memory file is shorter than the saved ranges", ))); } - do_mmap_cow_saved_regions(&guest_memory, &memory_file, saved_regions, self.thp)?; + do_mmap_cow_saved_regions(&guest_memory, &memory_file, saved_regions)?; self.cow_restored = true; // Landlock applies after the restore, so the pagemap is opened here. self.cow_source = match PageMap::open() { @@ -4223,13 +4223,11 @@ fn is_restore_cow_compatible(guest_memory: &GuestMemory, saved_regions: &MemoryR } // Maps each saved range over its guest RAM window, re-applying the owning -// region's reserve policy and the THP policy. Ranges must have passed -// `is_restore_cow_compatible`. +// region's reserve policy. Ranges must have passed `is_restore_cow_compatible`. fn do_mmap_cow_saved_regions( guest_memory: &GuestMemory, memory_file: &File, saved_regions: &MemoryRangeTable, - thp: bool, ) -> Result<(), Error> { let mut file_offset: u64 = 0; for range in saved_regions.ranges() { @@ -4262,16 +4260,6 @@ fn do_mmap_cow_saved_regions( if ret == libc::MAP_FAILED { return Err(Error::SnapshotMmap(io::Error::last_os_error())); } - if thp { - // SAFETY: ret/length name the private mapping just installed above. - let adv = unsafe { libc::madvise(ret, length, libc::MADV_HUGEPAGE) }; - if adv != 0 { - warn!( - "Restore (mode=copyonwrite): MADV_HUGEPAGE failed: {}", - io::Error::last_os_error() - ); - } - } file_offset = file_offset.checked_add(range.length).ok_or_else(|| { Error::SnapshotMmap(io::Error::other("snapshot range file offset overflow")) })?; @@ -4519,7 +4507,7 @@ mod tests { }); assert!(is_restore_cow_compatible(&gm, &table)); - do_mmap_cow_saved_regions(&gm, &file, &table, false).unwrap(); + do_mmap_cow_saved_regions(&gm, &file, &table).unwrap(); assert_eq!(gm.read_obj::(GuestAddress(0)).unwrap(), 0xab); assert_eq!(gm.read_obj::(GuestAddress(page - 1)).unwrap(), 0xab); @@ -4547,7 +4535,7 @@ mod tests { gpa: 0, length: 16 * page, }); - do_mmap_cow_saved_regions(&gm, &file, &ranges, false).unwrap(); + do_mmap_cow_saved_regions(&gm, &file, &ranges).unwrap(); let source = CowSource { file, ranges, @@ -4620,7 +4608,7 @@ mod tests { } #[test] - fn cow_restore_honors_region_reserve_and_thp() { + fn cow_restore_honors_region_reserve() { let page = get_page_size(); let mut file = tempfile::tempfile().unwrap(); file.write_all(&vec![0xcdu8; page as usize]).unwrap(); @@ -4645,7 +4633,7 @@ mod tests { gpa: 0, length: page, }); - do_mmap_cow_saved_regions(&gm, &file, &table, true).unwrap(); + do_mmap_cow_saved_regions(&gm, &file, &table).unwrap(); assert_eq!(gm.read_obj::(GuestAddress(0)).unwrap(), 0xcd); } } From d77d4628a5d20f47a3e89bd9b49c930bfc216729 Mon Sep 17 00:00:00 2001 From: zili-simular Date: Thu, 19 Nov 2026 17:27:14 +0800 Subject: [PATCH 10/11] hypervisor: Add a clock restore mode without catch-up Restoring a snapshot advances the guest clock by the wall time since the snapshot was taken. On x86_64 with KVM this also moves the TSC, and with it every clock a guest derives from the TSC, such as the uptime of a Windows guest. Add ClockRestoreMode::SnapshotRestoreNoCatchUp for a restore that continues from the saved clock instead. On x86_64 with KVM, kvmclock is set without KVM_CLOCK_REALTIME, so KVM does not add the elapsed time, and the TSC stays at the value restored with the vCPUs. On aarch64 the virtual counter stays at its restored value. MSHV has no catch-up, so its restore is unchanged. Nothing selects the new mode yet. Link: https://github.com/cocoonstack/cloud-hypervisor/issues/9 Signed-off-by: zili-simular --- hypervisor/src/kvm/mod.rs | 49 +++++++++++++++++++++++++++++++++------ hypervisor/src/lib.rs | 23 +++++++++++++++++- hypervisor/src/vm.rs | 5 ++-- 3 files changed, 67 insertions(+), 10 deletions(-) diff --git a/hypervisor/src/kvm/mod.rs b/hypervisor/src/kvm/mod.rs index d908480af8..77a1291fc4 100644 --- a/hypervisor/src/kvm/mod.rs +++ b/hypervisor/src/kvm/mod.rs @@ -1190,6 +1190,12 @@ impl vm::Vm for KvmVm { state: &ClockState, mode: ClockRestoreMode, ) -> vm::Result<()> { + if mode == ClockRestoreMode::SnapshotRestoreNoCatchUp { + // KVM advances kvmclock by the wall time elapsed since a saved + // `KVM_CLOCK_REALTIME`. Without it, kvmclock continues from the + // saved value, which matches the TSC restored with the vCPUs. + return self.set_clock(&state.data.without_realtime()); + } self.set_clock(&state.data)?; if mode != ClockRestoreMode::SnapshotRestore || !state.data.has_realtime() { return Ok(()); @@ -1248,7 +1254,9 @@ impl vm::Vm for KvmVm { /// Advance the guest virtual counter to current wall time before the vCPUs /// resume. A no-op for a `SameHostResume` (the counter free-ran across the - /// pause); on `SnapshotRestore`/migration-receive it must catch up. + /// pause) and for a `SnapshotRestoreNoCatchUp` (the counter stays at the + /// value restored with the vCPUs); on `SnapshotRestore`/migration-receive + /// it must catch up. #[cfg(target_arch = "aarch64")] fn restore_clock( &self, @@ -1256,7 +1264,7 @@ impl vm::Vm for KvmVm { saved: &ClockState, mode: ClockRestoreMode, ) -> vm::Result<()> { - if mode == ClockRestoreMode::SameHostResume { + if mode != ClockRestoreMode::SnapshotRestore { return Ok(()); } // KVM does not rescale the counter frequency across hosts (unlike x86 @@ -3732,14 +3740,18 @@ mod tests { } fn restore_clock(&self, state: &ClockState) { + self.restore_clock_with_mode(state, ClockRestoreMode::SnapshotRestore); + } + + fn restore_clock_with_mode(&self, state: &ClockState, mode: ClockRestoreMode) { self.vm - .restore_clock( - &[self.vcpu.as_ref()], - state, - ClockRestoreMode::SnapshotRestore, - ) + .restore_clock(&[self.vcpu.as_ref()], state, mode) .unwrap(); } + + fn kvmclock_ns(&self) -> u64 { + kvm_clock_data::from(self.vm.get_clock().unwrap()).clock + } } #[test] @@ -3781,6 +3793,29 @@ mod tests { ); } + #[test] + #[cfg(target_arch = "x86_64")] + fn test_restore_clock_without_catch_up_keeps_saved_clock() { + const GAP_SECS: u64 = 3600; + const GAP_NS: u64 = GAP_SECS * 1_000_000_000; + + let vm = TscDeadlineVm::new(); + let state = vm.clock_state_with_gap(GAP_SECS); + let saved_ns = kvm_clock_data::from(state.data).clock; + let saved_tsc = state.tsc.unwrap(); + + vm.restore_clock_with_mode(&state, ClockRestoreMode::SnapshotRestoreNoCatchUp); + let kvmclock_ns = vm.kvmclock_ns(); + assert!(kvmclock_ns >= saved_ns); + assert!(kvmclock_ns < saved_ns + GAP_NS); + assert!(vm.read_msr(msr_index::MSR_IA32_TSC) < saved_tsc + GAP_SECS * vm.tsc_hz); + + // The same state with catch-up advances both clocks by the gap. + vm.restore_clock(&state); + assert!(vm.kvmclock_ns() >= saved_ns + GAP_NS); + assert!(vm.read_msr(msr_index::MSR_IA32_TSC) >= saved_tsc + GAP_SECS * vm.tsc_hz); + } + #[test] #[cfg(feature = "sev_snp")] fn test_validate_gpa_range() { diff --git a/hypervisor/src/lib.rs b/hypervisor/src/lib.rs index 51207a46d1..ecf86695fb 100644 --- a/hypervisor/src/lib.rs +++ b/hypervisor/src/lib.rs @@ -214,6 +214,23 @@ impl ClockData { } } + /// Returns the clock without `CLOCK_REALTIME`, so that restoring it leaves + /// the guest clock at the saved value instead of advancing it by the wall + /// time elapsed since the capture. + #[must_use] + pub fn without_realtime(mut self) -> Self { + match &mut self { + #[cfg(feature = "kvm")] + ClockData::Kvm(s) => { + s.realtime = 0; + s.flags &= !kvm_bindings::KVM_CLOCK_REALTIME; + } + #[allow(unreachable_patterns)] + _ => {} + } + self + } + /// Returns the clock with `CLOCK_REALTIME` filled from the host wall clock /// when absent, so a later restore can advance the guest to current wall /// time. No-op for backends without a realtime field (e.g. MSHV). @@ -258,13 +275,17 @@ pub struct TimerState { /// How the guest clock is re-established when the vCPUs resume: a same-host /// pause/resume left it running, whereas a snapshot restore / migration-receive -/// means the guest was off-host and the clock must catch up to wall time. +/// means the guest was off-host and the clock must catch up to wall time, +/// unless the restore asked for the guest to continue from the saved clock. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ClockRestoreMode { /// Same-host pause -> resume; the clock kept running, nothing to advance. SameHostResume, /// Restored from a snapshot or migrated in; advance to current wall time. SnapshotRestore, + /// Restored from a snapshot; continue from the saved clock, as if no time + /// had passed since the snapshot was taken. + SnapshotRestoreNoCatchUp, } #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] diff --git a/hypervisor/src/vm.rs b/hypervisor/src/vm.rs index b6b4587335..ae2d14b878 100644 --- a/hypervisor/src/vm.rs +++ b/hypervisor/src/vm.rs @@ -321,8 +321,9 @@ pub trait Vm: Send + Sync + Any { } /// Re-establish the guest clock before the vCPUs resume. `mode` distinguishes a /// same-host pause/resume (the clock kept running) from a restore/migration where - /// it must catch up to wall time. aarch64 writes the counter on all `vcpus` (older - /// kernels track the offset per-vCPU). + /// it must catch up to wall time, and from a restore that continues from the saved + /// clock. aarch64 writes the counter on all `vcpus` (older kernels track the offset + /// per-vCPU). fn restore_clock( &self, _vcpus: &[&dyn Vcpu], From f36303873999011532b5f0468127f314a92ea475 Mon Sep 17 00:00:00 2001 From: zili-simular Date: Thu, 19 Nov 2026 17:27:14 +0800 Subject: [PATCH 11/11] vmm: Add clock_catchup to the restore config A Windows guest whose uptime jumps forward by 2^31 to 2^32 ms (24.9 to 49.7 days) on restore can resume with its TCP retransmission timers stopped, and a golden snapshot of that age is ordinary. Add `clock_catchup=on|off` to the restore config, on by default. With `off`, the guest clock continues from the snapshot, as if no time had passed, and the guest's wall clock is behind by the age of the snapshot until something in the guest sets it. A received migration always catches up. Link: https://github.com/cocoonstack/cloud-hypervisor/issues/9 Signed-off-by: zili-simular --- docs/snapshot_restore.md | 19 +++++++ vmm/src/api/openapi/cloud-hypervisor.yaml | 3 ++ vmm/src/config.rs | 61 ++++++++++++++++++++++- vmm/src/lib.rs | 7 +++ vmm/src/vm.rs | 21 +++++--- 5 files changed, 102 insertions(+), 9 deletions(-) diff --git a/docs/snapshot_restore.md b/docs/snapshot_restore.md index 17522cc99c..22d190a1d3 100644 --- a/docs/snapshot_restore.md +++ b/docs/snapshot_restore.md @@ -259,6 +259,25 @@ Current constraints for `memory_restore_mode=copyonwrite`: page-cache sharing is lost for that VM and host memory use grows to the eager-copy level. The same applies to `ondemand` restores. +### Guest clock after restore + +By default, a restore advances the guest clock by the wall time that elapsed +since the snapshot was taken, so the guest resumes with the current time. With +`clock_catchup=off`, the guest clock continues from its value in the snapshot, +as if no time had passed: + +```bash +./cloud-hypervisor \ + --api-socket /tmp/cloud-hypervisor.sock \ + --restore source_url=file:///home/foo/snapshot,clock_catchup=off +``` + +The guest's wall clock is then behind by the age of the snapshot until +something in the guest sets it, for example an NTP client or a guest agent. +This is for guests that do not handle a large forward jump of their monotonic +clock. A VM received through a migration, which includes a restore from an +offload daemon, always catches up. + ## Restore a VM with new external FDs For a VM created with FDs explicitly passed to `NetConfig`, replacement FDs diff --git a/vmm/src/api/openapi/cloud-hypervisor.yaml b/vmm/src/api/openapi/cloud-hypervisor.yaml index eee8d12bfb..e643c20697 100644 --- a/vmm/src/api/openapi/cloud-hypervisor.yaml +++ b/vmm/src/api/openapi/cloud-hypervisor.yaml @@ -1940,6 +1940,9 @@ components: type: boolean memory_restore_mode: $ref: "#/components/schemas/MemoryRestoreMode" + clock_catchup: + type: boolean + default: true net_fds: type: array deprecated: true diff --git a/vmm/src/config.rs b/vmm/src/config.rs index 586bfbad99..e559f8cdae 100644 --- a/vmm/src/config.rs +++ b/vmm/src/config.rs @@ -3105,14 +3105,21 @@ pub struct RestoredVfioConfig { pub fd: ExternalFd, } +fn default_restoreconfig_clock_catchup() -> bool { + true +} + #[serde_with::skip_serializing_none] -#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize, Default)] +#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct RestoreConfig { pub source_url: PathBuf, #[serde(default)] pub prefault: bool, #[serde(default)] pub memory_restore_mode: MemoryRestoreMode, + /// Advance the guest clock by the time elapsed since the snapshot. + #[serde(default = "default_restoreconfig_clock_catchup")] + pub clock_catchup: bool, /// Deprecated: use `external_fds` with network targets instead. #[serde(default)] pub net_fds: Option>, @@ -3135,10 +3142,29 @@ pub struct RestoreConfig { pub(crate) external_fds: ExternalFds, } +impl Default for RestoreConfig { + fn default() -> Self { + RestoreConfig { + source_url: PathBuf::default(), + prefault: false, + memory_restore_mode: MemoryRestoreMode::default(), + clock_catchup: default_restoreconfig_clock_catchup(), + net_fds: None, + vfio_fds: None, + iommufd_fd: ExternalFd::default(), + resume: false, + zone_updates: Vec::new(), + serial: None, + console: None, + external_fds: ExternalFds::default(), + } + } +} + impl RestoreConfig { pub const SYNTAX: &'static str = "Restore from a VM snapshot.\ \nRestore parameters \"source_url=,prefault=on|off,\ - memory_restore_mode=copy|ondemand|copyonwrite,\ + memory_restore_mode=copy|ondemand|copyonwrite,clock_catchup=on|off,\ external_fds=[net()@[,...],vfio()@[],iommu@[]],resume=true|false,\ zone_updates=,\ serial_file=|serial_socket=|serial_tcp=:,\ @@ -3150,6 +3176,9 @@ impl RestoreConfig { `memory_restore_mode=ondemand` enables lazy demand paging and fails restore if \ userfaultfd support is unavailable, and `memory_restore_mode=copyonwrite` maps the \ snapshot file copy-on-write (plain private RAM only; falls back to copy otherwise)\ + \n`clock_catchup` controls whether the guest clock is advanced by the time elapsed \ + since the snapshot (enabled by default). When disabled, the guest clock continues \ + from the snapshot.\ \n`external_fds` provides replacement file descriptors. `net()` entries replace \ the FDs of network devices, `vfio()` entries replace VFIO cdev FDs, and `iommu` \ provides the iommufd FD. \ @@ -3171,6 +3200,7 @@ impl RestoreConfig { .add("source_url") .add("prefault") .add("memory_restore_mode") + .add("clock_catchup") .add("net_fds") .add("vfio_fds") .add("iommufd_fd") @@ -3199,6 +3229,11 @@ impl RestoreConfig { .convert::("memory_restore_mode") .map_err(Error::ParseRestore)? .unwrap_or_default(); + let clock_catchup = parser + .convert::("clock_catchup") + .map_err(Error::ParseRestore)? + .unwrap_or(Toggle(default_restoreconfig_clock_catchup())) + .0; let mut net_fds = parser .convert::>>("net_fds") .map_err(Error::ParseRestore)? @@ -3283,6 +3318,7 @@ impl RestoreConfig { source_url, prefault, memory_restore_mode, + clock_catchup, net_fds, vfio_fds, iommufd_fd, @@ -7023,6 +7059,15 @@ id=\"{id}\",pci_segment={pci_segment},queue_sizes={queue_sizes}" ..Default::default() } ); + assert_eq!( + // SAFETY: This input contains no inherited descriptors. + unsafe { RestoreConfig::parse("source_url=/path/to/snapshot,clock_catchup=off") }?, + RestoreConfig { + source_url: PathBuf::from("/path/to/snapshot"), + clock_catchup: false, + ..Default::default() + } + ); assert_eq!( // SAFETY: This input contains no inherited descriptors. unsafe { @@ -7108,6 +7153,18 @@ id=\"{id}\",pci_segment={pci_segment},queue_sizes={queue_sizes}" #[test] fn test_restore_config_serde() { + assert!( + serde_json::from_str::(r#"{"source_url":"/path/to/snapshot"}"#) + .unwrap() + .clock_catchup + ); + assert!( + !serde_json::from_str::( + r#"{"source_url":"/path/to/snapshot","clock_catchup":false}"# + ) + .unwrap() + .clock_catchup + ); assert_eq!( serde_json::from_str::(r#"{"source_url":"/path/to/snapshot"}"#) .unwrap() diff --git a/vmm/src/lib.rs b/vmm/src/lib.rs index 67a389a2ac..109422f36d 100644 --- a/vmm/src/lib.rs +++ b/vmm/src/lib.rs @@ -1493,6 +1493,8 @@ impl Vmm { self.console_resize_pipe.clone(), Arc::clone(&self.original_termios_opt), Some(&snapshot), + // A received migration always catches up to wall time. + true, #[cfg(feature = "igvm")] None, ) @@ -2086,6 +2088,7 @@ impl Vmm { vm_config: Arc>, prefault: bool, memory_restore_mode: MemoryRestoreMode, + clock_catchup: bool, ) -> result::Result<(), VmError> { match &self.vm { VmOwnership::Owned(_) => Err(VmError::VmAlreadyCreated), @@ -2138,6 +2141,7 @@ impl Vmm { Some(source_url), Some(prefault), Some(memory_restore_mode), + Some(clock_catchup), )?; { @@ -2546,6 +2550,7 @@ impl RequestHandler for Vmm { None, None, None, + None, )?; let r = vm.boot(); @@ -2730,6 +2735,7 @@ impl RequestHandler for Vmm { vm_config, restore_cfg.prefault, restore_cfg.memory_restore_mode, + restore_cfg.clock_catchup, ) .and_then(|()| { if restore_cfg.resume { @@ -2830,6 +2836,7 @@ impl RequestHandler for Vmm { None, None, None, + None, )?; // And we boot it diff --git a/vmm/src/vm.rs b/vmm/src/vm.rs index c332038610..954c461102 100644 --- a/vmm/src/vm.rs +++ b/vmm/src/vm.rs @@ -490,8 +490,9 @@ fn is_restore_cow_supported(config: &VmConfig) -> bool { /// Guest clock baseline captured for snapshot/restore, plus how it must be /// re-established on the next resume. `mode` is runtime-only (`SnapshotRestore` -/// after restore/migration-receive, `SameHostResume` for a live same-host capture) -/// and is not serialized: it is re-derived from "was this VM built from a snapshot". +/// after restore/migration-receive, `SnapshotRestoreNoCatchUp` after a restore +/// with `clock_catchup=off`, `SameHostResume` for a live same-host capture) and +/// is not serialized: it is re-derived from how this VM was built. #[derive(Clone, Copy)] struct SavedClock { mode: hypervisor::ClockRestoreMode, @@ -559,6 +560,7 @@ impl Vm { console_resize_pipe: Option>, original_termios: Arc>>, snapshot: Option<&Snapshot>, + clock_catchup: bool, #[cfg(feature = "igvm")] igvm_file: Option, ) -> Result { trace_scoped!("Vm::new_from_memory_manager"); @@ -664,11 +666,14 @@ impl Vm { let saved_clock = if let Some(snapshot) = snapshot.as_ref() { let vm_snapshot = get_vm_snapshot(snapshot).map_err(Error::Restore)?; // Restored or migrated in: the guest clock must catch up to wall time - // on resume (the counter was reset to the saved value). - vm_snapshot.clock.map(|state| SavedClock { - mode: hypervisor::ClockRestoreMode::SnapshotRestore, - state, - }) + // on resume (the counter was reset to the saved value), unless the + // restore asked for the guest to continue from the saved clock. + let mode = if clock_catchup { + hypervisor::ClockRestoreMode::SnapshotRestore + } else { + hypervisor::ClockRestoreMode::SnapshotRestoreNoCatchUp + }; + vm_snapshot.clock.map(|state| SavedClock { mode, state }) } else { None }; @@ -1351,6 +1356,7 @@ impl Vm { source_url: Option<&str>, prefault: Option, memory_restore_mode: Option, + clock_catchup: Option, ) -> Result { trace_scoped!("Vm::new"); @@ -1447,6 +1453,7 @@ impl Vm { console_resize_pipe, original_termios, snapshot, + clock_catchup.unwrap_or(true), #[cfg(feature = "igvm")] igvm_file, )