git: 16edda206cc4 - releng/15.2 - virtio_pci_modern: enable virtqueues before completing attach

From: Colin Percival <cperciva_at_FreeBSD.org>
Date: Tue, 10 Nov 2026 20:51:33 UTC
The branch releng/15.2 has been updated by cperciva:

URL: https://cgit.FreeBSD.org/src/commit/?id=16edda206cc4972a9fbe1433fb5bb25907fc40cc

commit 16edda206cc4972a9fbe1433fb5bb25907fc40cc
Author:     Kyle Evans <kevans@FreeBSD.org>
AuthorDate: 2026-11-04 21:31:31 +0000
Commit:     Colin Percival <cperciva@FreeBSD.org>
CommitDate: 2026-11-10 20:51:14 +0000

    virtio_pci_modern: enable virtqueues before completing attach
    
    Most of our drivers setup interrupt(s) and virtqueues are enabled at
    that time, but nothing will currently enable them for devices that we're
    only going to poll.  This most notably affects virtio-random, and the
    problem can be observed with qemu's q35 emulation and a random device
    attached.  The q35 implementation ignores the ring unless it's enabled,
    so vtrnd_harvest() will consistently EAGAIN rather than contribute
    anything of value, but with this patch it becomes functional.
    
    This can be reproduced with a qemu invocation like so:
    
    qemu-system-x86_64 -machine q35,accel=tcg -cpu max -smp 2 -m 2G \
      -drive file=FreeBSD-16.0-CURRENT-amd64-ufs.qcow2,if=virtio \
      -device pcie-root-port,id=rp1,bus=pcie.0,chassis=1 \
      -object rng-random,id=rng0,filename=/dev/urandom \
      -device virtio-rng-pci,rng=rng0,bus=rp1 \
      -display curses
    
    Approved by:    re (cperciva)
    Reviewed by:    bnovkov, kfv
    Sponsored by:   Stormshield
    Sponsored by:   Klara, Inc.
    
    (cherry picked from commit c67e695b8f7eff84f7daa9e30eba7eb5ec552436)
    (cherry picked from commit ffa1d4d70a747abccc476321beaea7d1c0bd1cda)
---
 sys/dev/virtio/pci/virtio_pci_modern.c | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/sys/dev/virtio/pci/virtio_pci_modern.c b/sys/dev/virtio/pci/virtio_pci_modern.c
index 4b16b198b3f0..685b113d11c4 100644
--- a/sys/dev/virtio/pci/virtio_pci_modern.c
+++ b/sys/dev/virtio/pci/virtio_pci_modern.c
@@ -1145,6 +1145,13 @@ vtpci_modern_probe_and_attach_child(struct vtpci_modern_softc *sc)
 		/* Reset state for later attempt. */
 		vtpci_modern_child_detached(dev, child);
 	} else {
+		/*
+		 * It may be the case that the device will only be polled and
+		 * an interrupt never configured, so enable our virtqueues here
+		 * if they hadn't been already.
+		 */
+		vtpci_modern_enable_virtqueues(sc);
+
 		vtpci_modern_set_status(sc, VIRTIO_CONFIG_STATUS_DRIVER_OK);
 		VIRTIO_ATTACH_COMPLETED(child);
 	}
@@ -1296,6 +1303,9 @@ vtpci_modern_enable_virtqueues(struct vtpci_modern_softc *sc)
 
 	for (idx = 0; idx < sc->vtpci_common.vtpci_nvqs; idx++) {
 		vtpci_modern_select_virtqueue(sc, idx);
+		if (vtpci_modern_read_common_2(sc,
+		    VIRTIO_PCI_COMMON_Q_ENABLE) != 0)
+			continue;
 		vtpci_modern_write_common_2(sc, VIRTIO_PCI_COMMON_Q_ENABLE, 1);
 	}
 }