Skip to content
Open
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions vm/devices/virtio/virtio/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,12 @@ pub struct PeekedWork<'a> {
work: VirtioQueueCallbackWork,
}

pub(crate) enum PeekResult<'a> {
Empty,
Work(PeekedWork<'a>),
CapacityBlocked,
}

impl<'a> PeekedWork<'a> {
fn new(queue: &'a mut VirtioQueue, work: VirtioQueueCallbackWork) -> Self {
Self { queue, work }
Expand Down Expand Up @@ -368,6 +374,18 @@ impl VirtioQueue {
Ok(work.map(|w| PeekedWork::new(self, w)))
}

/// Like [`Self::try_peek`], but distinguishes an empty queue from a chain
/// exceeding the remaining capacity (heads for split, slots for packed).
/// Capacity blocking is temporary; other errors still retire the queue.
pub(crate) fn try_peek_with_backpressure(&mut self) -> Result<PeekResult<'_>, Error> {
match self.core.try_peek_work_with_backpressure() {
Ok(Some(work)) => Ok(PeekResult::Work(PeekedWork::new(self, work))),
Ok(None) => Ok(PeekResult::Empty),
Err(QueueError::TooManyInFlightDescriptors { .. }) => Ok(PeekResult::CapacityBlocked),
Err(err) => Err(Error::other(err)),
}
}

/// Waits until a descriptor is available for peeking, without advancing
/// the available index. See [`try_peek`](Self::try_peek).
///
Expand Down
81 changes: 62 additions & 19 deletions vm/devices/virtio/virtio/src/in_order.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,27 +14,35 @@
//! This is deliberately a *side* helper whose methods borrow a
//! [`VirtioQueue`], rather than being baked into the queue itself. Devices that
//! do not need in-order completion (virtio-blk, virtio-vsock, ...) never
//! instantiate it and pay nothing — the queue's hot path is untouched. It uses
//! only the queue's public API, mirroring QEMU's
//! `virtqueue_ordered_fill`/`virtqueue_ordered_flush` (`used_elems`): consumed
//! instantiate it and pay nothing — the queue's hot path is untouched. Consumed
//! descriptors are recorded in consumption order, completions fill their slot
//! (possibly out of order), and only the contiguous filled prefix is published
//! to the used ring, in order.
//!
//! A driver that makes a descriptor head available again before its previous
//! use has been published violates the virtio spec. The reused head is not
//! rejected: it is left in the available ring until the earlier use is
//! published and then processed normally. Use [`InOrderCompletion::poll_kick`]
//! to wait for work without spinning on a deferred descriptor.

use crate::VirtioQueue;
use crate::VirtioQueueCallbackWork;
use crate::common::PeekResult;
use crate::queue::QueueCompletion;
use inspect::Inspect;
use std::collections::VecDeque;
use std::io::Error;
use std::io::ErrorKind;
use std::task::Context;
use std::task::Poll;
use std::task::ready;

/// Enforces in-order used-ring publication for a single [`VirtioQueue`].
///
/// Consume descriptors via [`try_next`](Self::try_next) and complete them via
/// [`complete`](Self::complete) instead of calling the queue's methods
/// directly. Completions may be issued in any order; the used ring is always
/// published in consumption (available) order.
/// directly. Wait for work via [`poll_kick`](Self::poll_kick). Completions may be
/// issued in any order; the used ring is always published in consumption
/// (available) order.
#[derive(Inspect)]
pub struct InOrderCompletion {
/// Descriptor indices of outstanding descriptors, in consumption order.
Expand All @@ -48,9 +56,12 @@ pub struct InOrderCompletion {
/// Completed-but-not-yet-published work, indexed by descriptor index.
/// Bounded by the queue size, so a descriptor index (always
/// `< queue_size`) is a unique key for the outstanding set: a repeated
/// index while still outstanding is rejected by `try_next`.
/// index while still outstanding is deferred by `try_next`.
#[inspect(skip)]
completed: Vec<Option<Completed>>,
/// Used cursor observed when fetching required publication to make progress.
/// Cleared by the next fetch, never maintained by completion paths.
blocked_at_used: Option<u16>,
}

struct Completed {
Expand All @@ -65,42 +76,74 @@ impl InOrderCompletion {
order: VecDeque::with_capacity(queue_size as usize),
in_flight: vec![false; queue_size as usize],
completed: (0..queue_size).map(|_| None).collect(),
blocked_at_used: None,
}
}

/// Consumes the next available descriptor from `queue`, recording it for
/// in-order completion. Returns `Ok(None)` if no work is available.
/// Reusing an outstanding descriptor returns `InvalidData` without consuming it.
///
/// If the next available descriptor head is still outstanding, it is left
/// unconsumed and `Ok(None)` is returned until the earlier use is
/// published. A chain exceeding the remaining ring capacity is likewise
/// deferred until publication frees capacity.
///
/// Use this in place of [`VirtioQueue::try_next`].
pub fn try_next(
&mut self,
queue: &mut VirtioQueue,
) -> Result<Option<VirtioQueueCallbackWork>, Error> {
let Some(work) = queue.try_peek()? else {
return Ok(None);
self.blocked_at_used = None;
let work = match queue.try_peek_with_backpressure()? {
PeekResult::Empty => return Ok(None),
PeekResult::CapacityBlocked => {
self.blocked_at_used = Some(queue.queue_state().used_index);
return Ok(None);
Comment thread
jstarks marked this conversation as resolved.
Resolved
}
PeekResult::Work(work) => work,
};
let idx = work.descriptor_index() as usize;
let idx = work.descriptor_index();
// The queue validates the descriptor index against the ring size
// when it reads the descriptor, so an out-of-range index fails
// above rather than reaching here. Assert the invariant so a
// violation fails fast at entry instead of corrupting later state.
assert!(
idx < self.completed.len(),
(idx as usize) < self.completed.len(),
"descriptor index {idx} exceeds queue size {}",
self.completed.len()
);
if self.in_flight[idx] {
return Err(Error::new(
ErrorKind::InvalidData,
format!("descriptor {idx} is already outstanding"),
));
if self.in_flight[idx as usize] {
drop(work);
self.blocked_at_used = Some(queue.queue_state().used_index);
tracelimit::event_ratelimited_static!(
level: DEBUG,
descriptor_index = idx,
"guest reused an outstanding descriptor, deferring it"
);
return Ok(None);
}
self.in_flight[idx] = true;
self.order.push_back(work.descriptor_index());
self.in_flight[idx as usize] = true;
self.order.push_back(idx);
Ok(Some(work.consume()))
}

/// Waits for guest work that can be consumed by [`try_next`](Self::try_next).
///
/// Unlike [`VirtioQueue::poll_kick`], this returns `Pending` if fetching
/// encountered reuse or insufficient capacity and publication has not
/// advanced since. Any publication permits a retry, which may defer again.
/// Callers must also poll their completion source with the same waker and
/// retry fetching after processing completions: this method does not
/// register a waker for publication.
pub fn poll_kick(&self, queue: &mut VirtioQueue, cx: &mut Context<'_>) -> Poll<()> {
ready!(queue.poll_kick(cx));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ready! can return Pending before the outstanding count is checked. So this might lead to a packet stuck in the queue. If order.len() has already dropped, the worker can retry the queued work without another guest kick. It might make sense to check order.len() first.

Thanks

if self.blocked_at_used == Some(queue.queue_state().used_index) {
Poll::Pending
Comment thread
jstarks marked this conversation as resolved.
Resolved
} else {
Poll::Ready(())
}
}

/// Records a completion for the descriptor identified by `completion` and
/// publishes the contiguous run of completed descriptors at the front of
/// the consumption order to the used ring, in order.
Expand Down
23 changes: 20 additions & 3 deletions vm/devices/virtio/virtio/src/queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -322,14 +322,31 @@ impl QueueCoreGetWork {
/// Returns `Ok(None)` forever once the queue has failed, so that the error
/// is reported exactly once.
pub fn try_peek_work(&mut self) -> Result<Option<VirtioQueueCallbackWork>, QueueError> {
self.try_peek_work_with_policy(false)
}

/// Like [`Self::try_peek_work`], but a capacity error does not retire the
/// queue, allowing the caller to retry after outstanding work completes.
pub fn try_peek_work_with_backpressure(
&mut self,
) -> Result<Option<VirtioQueueCallbackWork>, QueueError> {
self.try_peek_work_with_policy(true)
}

fn try_peek_work_with_policy(
&mut self,
defer_capacity: bool,
) -> Result<Option<VirtioQueueCallbackWork>, QueueError> {
if self.failed {
return Ok(None);
}
let r = self.try_peek_work_inner();
if r.is_err() {
let result = self.try_peek_work_inner();
if let Err(err) = &result
&& !(defer_capacity && matches!(err, QueueError::TooManyInFlightDescriptors { .. }))
{
self.failed = true;
}
r
result
}

fn try_peek_work_inner(&mut self) -> Result<Option<VirtioQueueCallbackWork>, QueueError> {
Expand Down
Loading
Loading