[Bug] virtio: a driver features page written again is ORed into the acked features instead of replacing them

Aperta
#6,463 1 commento 0 reazioni 1 assegnatario Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

@zulinx86 ci sta già lavorando.

Dal 25/11/2026.

Valutazione

Difficoltà
3/5
Tempo stimato
1-2 giorni
Idoneità per principianti
52/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
rust
Ambito
backend

Direzione di ricerca

Start in ack_features_by_page in src/vmm/src/devices/virtio/device.rs, where the OR of the new page into acked_features happens. The two added tests, test_driver_features_written_again in transport/mmio.rs and in transport/pci/common_config.rs, reproduce the bug, so run them first to see the stale bit. Done when both tests pass, the replace-not-OR behaviour holds, and the existing virtio tests still pass.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Status: Awaiting assignee

Describe the bug

VirtioDevice::ack_features_by_page ORs every write of the driver features register into the device's acked features, so a write can set feature bits but never clear them:

https://github.com/firecracker-microvm/firecracker/blob/38f7f364f16757c4794d907e1e8cba610bd55ee6/src/vmm/src/devices/virtio/device.rs#L184-L204

self.set_acked_features(self.acked_features() | v);

Both transports send the register write there while the device status is ACKNOWLEDGE | DRIVER, before FEATURES_OK:

A driver may write a features page more than once before FEATURES_OK, and Linux does. virtio_dev_probe() writes the features through config->finalize_features(), then calls the driver's validate(). If validate() cleared any feature, it calls finalize_features() again ("Did validation change any features? Then write them again."):

https://github.com/torvalds/linux/blob/4843f6873f7c4835e62f2c73ba0fd538e57a2f22/drivers/virtio/virtio.c#L325-L344

Each finalize_features() writes every page:

On the second write the cleared bits are 0, but the OR keeps them acked. The device then holds acked_features that the driver has refused. That stale set is what has_feature() answers from, what device code reads at activation, and what a snapshot saves (VirtioDeviceState::from_device).

The spec gives the register write replace semantics. Per virtio 1.3 §4.2.2, a write to MMIO DriverFeatures sets bits DriverFeaturesSel*32 to DriverFeaturesSel*32+31. Per §4.1.4.3.1, a PCI device must present the valid bits the driver has written in driver_feature. Neither says to OR them into earlier writes. Firecracker's own Nitro Enclave transport already replaces: it sets acked_features to driver_features & avail (nitro_enclave.rs#L418-L420).

Linux drivers whose validate() clears features today:

  • virtio-balloon (virtballoon_validate()) clears VIRTIO_BALLOON_F_REPORTING (bit 5) when the guest uses init_on_free or page poisoning and the device does not offer VIRTIO_BALLOON_F_PAGE_POISON (bit 4). Firecracker's balloon offers bit 5 when free_page_reporting is on and never offers bit 4 (balloon/device.rs#L281-L304). So a stock guest booted with init_on_free=1 leaves free page reporting acked on the device, although the driver refused it and never sets up the reporting queue. The balloon checks avail_features rather than acked features for its reporting queue (#L743-L745), so in this case the visible damage today is a wrong acked set, saved into snapshots and restored from them (balloon/persist.rs#L179).
  • virtio-net (virtnet_validate()) clears VIRTIO_NET_F_MTU when the MTU is below 68, and VIRTIO_NET_F_STANDBY without VIRTIO_NET_F_MAC. Firecracker rejects an MTU below 68 and does not offer STANDBY, so neither fires with stock Firecracker today.
  • virtio-pmem (virtio_pmem_validate()) clears VIRTIO_PMEM_F_SHMEM_REGION, which Firecracker does not offer.

We hit the bug with a device of our own whose Linux driver clears an offered feature in validate(). The device then ran with a feature the driver had turned off. Any device that keys behaviour on an acked feature a driver can refuse in validate() is exposed the same way. That covers features added to existing devices later, too.

To Reproduce

The smallest deterministic repro is a unit test per transport. Each test makes the register writes that Linux's virtio_dev_probe() makes when validate() clears one feature, then checks the acked features. The script below clones upstream at 38f7f364, adds the two tests, and runs them. It needs a Linux host with git, rustup and a C toolchain.

  1. Save the script below as repro.sh and run ./repro.sh (optionally ./repro.sh <workdir>).
  2. Both tests fail. The device has 0x1_0000_0003 acked after the driver wrote 0x1_0000_0001: bit 1, which the second write cleared, is still acked.
  3. ./repro.sh --with-fix applies the change suggested below, and both tests pass.
repro.sh
#!/usr/bin/env bash
# Repro: a virtio driver features page written a second time is ORed into the acked features
# instead of replacing them. Adds one unit test per transport (MMIO and PCI) that performs the
# register writes Linux's virtio_dev_probe() makes when a driver's validate() clears a feature,
# then runs them against upstream main.
#
# Needs a Linux host with git, rustup (the pinned toolchain is fetched automatically) and a C
# toolchain. Usage: ./repro.sh [--with-fix] [workdir]
set -euo pipefail

SHA=38f7f364f16757c4794d907e1e8cba610bd55ee6
WITH_FIX=0
if [[ "${1:-}" == "--with-fix" ]]; then WITH_FIX=1; shift; fi
WORK="${1:-$(mktemp -d)}"
DIR="$WORK/firecracker"

if [[ ! -d "$DIR/.git" ]]; then
  git clone --quiet --filter=blob:none https://github.com/firecracker-microvm/firecracker "$DIR"
fi
git -C "$DIR" checkout --quiet --force "$SHA"
git -C "$DIR" clean --quiet -fd src
echo "firecracker at $(git -C "$DIR" rev-parse HEAD)"

git -C "$DIR" apply - <<'PATCH'
diff --git a/src/vmm/src/devices/virtio/transport/mmio.rs b/src/vmm/src/devices/virtio/transport/mmio.rs
--- a/src/vmm/src/devices/virtio/transport/mmio.rs
+++ b/src/vmm/src/devices/virtio/transport/mmio.rs
@@ -1300,6 +1300,41 @@ pub(crate) mod tests {
         assert_eq!(dummy_dev.acked_features(), 24);
     }
 
+    /// Linux's `virtio_dev_probe()` writes the driver features (`vm_finalize_features()`), lets
+    /// the driver's `validate()` clear some, and writes them again before `FEATURES_OK`. The
+    /// second write must leave the cleared features un-acked.
+    #[test]
+    fn test_driver_features_written_again() {
+        let m = single_region_mem(0x1000);
+        let interrupt = Arc::new(IrqTrigger::new());
+        let dummy_dev = Arc::new(Mutex::new(DummyDevice::new()));
+        dummy_dev
+            .lock()
+            .unwrap()
+            .set_avail_features((1 << 32) | 0b11);
+        let mut d = MmioTransport::new(m, interrupt, dummy_dev.clone(), false);
+        set_device_status(&mut d, device_status::ACKNOWLEDGE);
+        set_device_status(&mut d, device_status::ACKNOWLEDGE | device_status::DRIVER);
+
+        // The register writes of Linux's vm_finalize_features(): page 1, then page 0.
+        let finalize_features = |d: &mut MmioTransport, features: u64| {
+            let mut buf = [0u8; 4];
+            for page in [1u32, 0] {
+                write_le_u32(&mut buf, page);
+                d.write(0x0, 0x24, &buf); // DriverFeaturesSel
+                write_le_u32(&mut buf, (features >> (32 * page)) as u32);
+                d.write(0x0, 0x20, &buf); // DriverFeatures
+            }
+        };
+
+        finalize_features(&mut d, (1 << 32) | 0b11);
+        // The driver's validate() clears bit 1, and the features are written again.
+        finalize_features(&mut d, (1 << 32) | 0b01);
+
+        let acked = dummy_dev.lock().unwrap().acked_features();
+        assert_eq!(acked, (1 << 32) | 0b01, "acked features {acked:#x}");
+    }
+
     #[test]
     fn test_queue_config_immutable_after_activation() {
         // Verify that writes to queue configuration fields are rejected after the device has been
diff --git a/src/vmm/src/devices/virtio/transport/pci/common_config.rs b/src/vmm/src/devices/virtio/transport/pci/common_config.rs
--- a/src/vmm/src/devices/virtio/transport/pci/common_config.rs
+++ b/src/vmm/src/devices/virtio/transport/pci/common_config.rs
@@ -624,6 +624,35 @@ mod tests {
         );
     }
 
+    /// Linux's `virtio_dev_probe()` writes the driver features (`vp_modern_set_extended_features()`),
+    /// lets the driver's `validate()` clear some, and writes them again before `FEATURES_OK`. The
+    /// second write must leave the cleared features un-acked.
+    #[test]
+    fn test_driver_features_written_again() {
+        let mut config = default_pci_common_config();
+        let device = default_device();
+        device.lock().unwrap().set_avail_features((1 << 32) | 0b11);
+        config.set_device_status(ACKNOWLEDGE, &*device, false);
+        config.set_device_status(ACKNOWLEDGE | DRIVER, &*device, false);
+
+        // The register writes of Linux's vp_modern_set_extended_features(): every 32-bit page of
+        // its 128 feature bits, in order.
+        let finalize_features = |config: &mut VirtioPciCommonConfig, features: u64| {
+            let pages = [features as u32, (features >> 32) as u32, 0, 0];
+            for (page, value) in (0u32..).zip(pages) {
+                config.write(DRIVER_FEATURE_SELECT, page.as_slice(), device.clone(), false);
+                config.write(DRIVER_FEATURE, value.as_slice(), device.clone(), false);
+            }
+        };
+
+        finalize_features(&mut config, (1 << 32) | 0b11);
+        // The driver's validate() clears bit 1, and the features are written again.
+        finalize_features(&mut config, (1 << 32) | 0b01);
+
+        let acked = device.lock().unwrap().acked_features();
+        assert_eq!(acked, (1 << 32) | 0b01, "acked features {acked:#x}");
+    }
+
     #[test]
     fn test_num_queues() {
         let mut config = default_pci_common_config();
PATCH

if [[ "$WITH_FIX" == 1 ]]; then
  echo "applying the suggested fix"
  git -C "$DIR" apply - <<'PATCH'
diff --git a/src/vmm/src/devices/virtio/device.rs b/src/vmm/src/devices/virtio/device.rs
--- a/src/vmm/src/devices/virtio/device.rs
+++ b/src/vmm/src/devices/virtio/device.rs
@@ -181,14 +181,22 @@ pub trait VirtioDevice: AsAny + MutEventSubscriber + Send {
         }
     }
 
-    /// Acknowledges that this set of features should be enabled.
+    /// Acknowledges that this set of features should be enabled: the page's features, in place of
+    /// those the driver wrote to it before. A driver may write a page again before `FEATURES_OK`,
+    /// as Linux does once a driver's `validate` has cleared some.
     fn ack_features_by_page(&mut self, page: u32, value: u32) {
-        let mut v = match page {
-            0 => u64::from(value),
-            1 => u64::from(value) << 32,
+        let (mut v, kept) = match page {
+            0 => (
+                u64::from(value),
+                self.acked_features() & !u64::from(u32::MAX),
+            ),
+            1 => (
+                u64::from(value) << 32,
+                self.acked_features() & u64::from(u32::MAX),
+            ),
             _ => {
                 warn!("Cannot acknowledge unknown features page: {}", page);
-                0u64
+                (0u64, self.acked_features())
             }
         };
 
@@ -200,7 +208,7 @@ pub trait VirtioDevice: AsAny + MutEventSubscriber + Send {
             // Don't count these features as acked.
             v &= !unrequested_features;
         }
-        self.set_acked_features(self.acked_features() | v);
+        self.set_acked_features(kept | v);
     }
 
     /// Returns the full device-specific configuration as a byte slice.
PATCH
fi

cd "$DIR"
cargo test --quiet -p vmm --lib -- test_driver_features_written_again

Output on an Ubuntu 24.04 host (kernel 7.0.0-1017-gcp, x86_64), build-script noise trimmed. The first run is upstream main; the second adds the suggested fix:

$ ./repro.sh
firecracker at 38f7f364f16757c4794d907e1e8cba610bd55ee6

running 2 tests
devices::virtio::transport::pci::common_config::tests::test_driver_features_written_again --- FAILED
devices::virtio::transport::mmio::tests::test_driver_features_written_again --- FAILED

failures:

---- devices::virtio::transport::pci::common_config::tests::test_driver_features_written_again stdout ----

thread 'devices::virtio::transport::pci::common_config::tests::test_driver_features_written_again' (1852499) panicked at src/vmm/src/devices/virtio/transport/pci/common_config.rs:653:9:
assertion `left == right` failed: acked features 0x100000003
  left: 4294967299
 right: 4294967297
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

---- devices::virtio::transport::mmio::tests::test_driver_features_written_again stdout ----

thread 'devices::virtio::transport::mmio::tests::test_driver_features_written_again' (1852497) panicked at src/vmm/src/devices/virtio/transport/mmio.rs:1335:9:
assertion `left == right` failed: acked features 0x100000003
  left: 4294967299
 right: 4294967297


failures:
    devices::virtio::transport::mmio::tests::test_driver_features_written_again
    devices::virtio::transport::pci::common_config::tests::test_driver_features_written_again

test result: FAILED. 0 passed; 2 failed; 0 ignored; 0 measured; 1025 filtered out; finished in 0.00s

error: test failed, to rerun pass `-p vmm --lib`
[exit status 101]
$ ./repro.sh --with-fix
firecracker at 38f7f364f16757c4794d907e1e8cba610bd55ee6
applying the suggested fix

running 2 tests
..
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 1025 filtered out; finished in 0.00s

[exit status 0]

Expected behaviour

A write to a driver features page replaces that page's 32 bits of the acked features, less any bit the device did not offer, and leaves the other page's bits alone. After Linux's second write, the device has exactly the features the driver kept: 0x1_0000_0001 in the repro.

Environment

  • Firecracker version: main at 38f7f364f16757c4794d907e1e8cba610bd55ee6. The same code is in v1.16.1, where we first hit it.
  • Host and guest kernel versions: repro is a unit test and needs no guest. It ran on host kernel 7.0.0-1017-gcp. The guest-side code path is cited from Linux at 4843f6873f7c4835e62f2c73ba0fd538e57a2f22.
  • Rootfs used: n/a
  • Architecture: x86_64 (the code is architecture-independent)
  • Any other relevant software versions: Rust 1.99.1 (from rust-toolchain.toml)

Additional context

How has this bug affected you? A device of ours ran with a feature its Linux driver had refused in validate(), so device and driver disagreed about the negotiated features.

What are you trying to achieve? Feature negotiation where the device's acked features are exactly what the driver last wrote before FEATURES_OK.

Suggested fix (what we run): a page write replaces that page's half and keeps the other page's half. Pages above 1 keep everything, so the zero pages 2 and 3 that Linux's PCI driver writes change nothing.

diff --git a/src/vmm/src/devices/virtio/device.rs b/src/vmm/src/devices/virtio/device.rs
--- a/src/vmm/src/devices/virtio/device.rs
+++ b/src/vmm/src/devices/virtio/device.rs
@@ -181,14 +181,22 @@ pub trait VirtioDevice: AsAny + MutEventSubscriber + Send {
         }
     }
 
-    /// Acknowledges that this set of features should be enabled.
+    /// Acknowledges that this set of features should be enabled: the page's features, in place of
+    /// those the driver wrote to it before. A driver may write a page again before `FEATURES_OK`,
+    /// as Linux does once a driver's `validate` has cleared some.
     fn ack_features_by_page(&mut self, page: u32, value: u32) {
-        let mut v = match page {
-            0 => u64::from(value),
-            1 => u64::from(value) << 32,
+        let (mut v, kept) = match page {
+            0 => (
+                u64::from(value),
+                self.acked_features() & !u64::from(u32::MAX),
+            ),
+            1 => (
+                u64::from(value) << 32,
+                self.acked_features() & u64::from(u32::MAX),
+            ),
             _ => {
                 warn!("Cannot acknowledge unknown features page: {}", page);
-                0u64
+                (0u64, self.acked_features())
             }
         };
 
@@ -200,7 +208,7 @@ pub trait VirtioDevice: AsAny + MutEventSubscriber + Send {
             // Don't count these features as acked.
             v &= !unrequested_features;
         }
-        self.set_acked_features(self.acked_features() | v);
+        self.set_acked_features(kept | v);
     }
 
     /// Returns the full device-specific configuration as a byte slice.

Three existing tests assume the OR and need updating with it:

With the fix applied on the same host, those three are the only devices::virtio unit tests that newly fail. We compared failure lists against clean main. Other failures on that host also fail on clean main: TAP tests that need /dev/net/tun access, and virtio::mem tests that fail at random there.

Checks

  • Have you searched the Firecracker Issues database for similar problems?
  • Have you read the existing relevant Firecracker documentation?
  • Are you certain the bug being reported is a Firecracker issue?
Lingua principale
Rust
Stelle
38.2k
Fork
2.8k
Merge medio
2g 12h
PR unite (30g)
59

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di firecracker-microvm/firecracker

Tutte le issue di firecracker-microvm/firecracker

Issue simili

Altre issue su Rust

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.