Repository navigation
virtio: defer descriptor reuse until completion is published #5193
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
John Starks (jstarks)
wants to merge
11
commits into
microsoft:main
Choose a base branch
from
jstarks:virtio-defer-reused-descriptors
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 10 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
14ba0b7
virtio: defer reused outstanding descriptors instead of stopping the …
smalis-msft 2691e9a
feedback fix
smalis-msft de47ee5
virtio: encapsulate in-order queue readiness
jstarks bebdd58
virtio: avoid redundant deferred-head checks
jstarks dc4c5ae
virtio: remove QEMU comparison from completion comments
jstarks 4bc9210
virtio: keep capacity backpressure in queue APIs
jstarks b306d6c
virtio: defer capacity exhaustion at the existing chain-fit check
jstarks e9be2f8
virtio: defer blocked checks until kick readiness
jstarks 6cedf36
virtio: retry deferred descriptors after publication advances
jstarks 8dfc6f6
virtio: lower deferred descriptor reuse logging to debug
jstarks 316ac01
virtio: restrict descriptor deferral to split rings
jstarks File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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. | ||
|
|
@@ -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 { | ||
|
|
@@ -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); | ||
| } | ||
| 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)); | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Thanks |
||
| if self.blocked_at_used == Some(queue.queue_state().used_index) { | ||
| Poll::Pending | ||
|
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. | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.