queue.rs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  1. #![allow(unused_unsafe)]
  2. use crate::hal::{BufferDirection, Dma, Hal, PhysAddr};
  3. use crate::transport::Transport;
  4. use crate::{align_up, nonnull_slice_from_raw_parts, pages, Error, Result, PAGE_SIZE};
  5. use bitflags::bitflags;
  6. #[cfg(test)]
  7. use core::cmp::min;
  8. use core::hint::spin_loop;
  9. use core::mem::{size_of, take};
  10. #[cfg(test)]
  11. use core::ptr;
  12. use core::ptr::NonNull;
  13. use core::sync::atomic::{fence, Ordering};
  14. use zerocopy::FromBytes;
  15. /// The mechanism for bulk data transport on virtio devices.
  16. ///
  17. /// Each device can have zero or more virtqueues.
  18. ///
  19. /// * `SIZE`: The size of the queue. This is both the number of descriptors, and the number of slots
  20. /// in the available and used rings.
  21. #[derive(Debug)]
  22. pub struct VirtQueue<H: Hal, const SIZE: usize> {
  23. /// DMA guard
  24. layout: VirtQueueLayout<H>,
  25. /// Descriptor table
  26. ///
  27. /// The device may be able to modify this, even though it's not supposed to, so we shouldn't
  28. /// trust values read back from it. Use `desc_shadow` instead to keep track of what we wrote to
  29. /// it.
  30. desc: NonNull<[Descriptor]>,
  31. /// Available ring
  32. ///
  33. /// The device may be able to modify this, even though it's not supposed to, so we shouldn't
  34. /// trust values read back from it. The only field we need to read currently is `idx`, so we
  35. /// have `avail_idx` below to use instead.
  36. avail: NonNull<AvailRing<SIZE>>,
  37. /// Used ring
  38. used: NonNull<UsedRing<SIZE>>,
  39. /// The index of queue
  40. queue_idx: u16,
  41. /// The number of descriptors currently in use.
  42. num_used: u16,
  43. /// The head desc index of the free list.
  44. free_head: u16,
  45. /// Our trusted copy of `desc` that the device can't access.
  46. desc_shadow: [Descriptor; SIZE],
  47. /// Our trusted copy of `avail.idx`.
  48. avail_idx: u16,
  49. last_used_idx: u16,
  50. }
  51. impl<H: Hal, const SIZE: usize> VirtQueue<H, SIZE> {
  52. /// Create a new VirtQueue.
  53. pub fn new<T: Transport>(transport: &mut T, idx: u16) -> Result<Self> {
  54. if transport.queue_used(idx) {
  55. return Err(Error::AlreadyUsed);
  56. }
  57. if !SIZE.is_power_of_two()
  58. || SIZE > u16::MAX.into()
  59. || transport.max_queue_size() < SIZE as u32
  60. {
  61. return Err(Error::InvalidParam);
  62. }
  63. let size = SIZE as u16;
  64. let layout = if transport.requires_legacy_layout() {
  65. VirtQueueLayout::allocate_legacy(size)?
  66. } else {
  67. VirtQueueLayout::allocate_flexible(size)?
  68. };
  69. transport.queue_set(
  70. idx,
  71. size.into(),
  72. layout.descriptors_paddr(),
  73. layout.driver_area_paddr(),
  74. layout.device_area_paddr(),
  75. );
  76. let desc =
  77. nonnull_slice_from_raw_parts(layout.descriptors_vaddr().cast::<Descriptor>(), SIZE);
  78. let avail = layout.avail_vaddr().cast();
  79. let used = layout.used_vaddr().cast();
  80. let mut desc_shadow: [Descriptor; SIZE] = FromBytes::new_zeroed();
  81. // Link descriptors together.
  82. for i in 0..(size - 1) {
  83. desc_shadow[i as usize].next = i + 1;
  84. // Safe because `desc` is properly aligned, dereferenceable, initialised, and the device
  85. // won't access the descriptors for the duration of this unsafe block.
  86. unsafe {
  87. (*desc.as_ptr())[i as usize].next = i + 1;
  88. }
  89. }
  90. Ok(VirtQueue {
  91. layout,
  92. desc,
  93. avail,
  94. used,
  95. queue_idx: idx,
  96. num_used: 0,
  97. free_head: 0,
  98. desc_shadow,
  99. avail_idx: 0,
  100. last_used_idx: 0,
  101. })
  102. }
  103. /// Add buffers to the virtqueue, return a token.
  104. ///
  105. /// Ref: linux virtio_ring.c virtqueue_add
  106. ///
  107. /// # Safety
  108. ///
  109. /// The input and output buffers must remain valid and not be accessed until a call to
  110. /// `pop_used` with the returned token succeeds.
  111. pub unsafe fn add<'a, 'b>(
  112. &mut self,
  113. inputs: &'a [&'b [u8]],
  114. outputs: &'a mut [&'b mut [u8]],
  115. ) -> Result<u16> {
  116. if inputs.is_empty() && outputs.is_empty() {
  117. return Err(Error::InvalidParam);
  118. }
  119. if inputs.len() + outputs.len() + self.num_used as usize > SIZE {
  120. return Err(Error::QueueFull);
  121. }
  122. // allocate descriptors from free list
  123. let head = self.free_head;
  124. let mut last = self.free_head;
  125. for (buffer, direction) in InputOutputIter::new(inputs, outputs) {
  126. // Write to desc_shadow then copy.
  127. let desc = &mut self.desc_shadow[usize::from(self.free_head)];
  128. desc.set_buf::<H>(buffer, direction, DescFlags::NEXT);
  129. last = self.free_head;
  130. self.free_head = desc.next;
  131. self.write_desc(last);
  132. }
  133. // set last_elem.next = NULL
  134. self.desc_shadow[usize::from(last)]
  135. .flags
  136. .remove(DescFlags::NEXT);
  137. self.write_desc(last);
  138. self.num_used += (inputs.len() + outputs.len()) as u16;
  139. let avail_slot = self.avail_idx & (SIZE as u16 - 1);
  140. // Safe because self.avail is properly aligned, dereferenceable and initialised.
  141. unsafe {
  142. (*self.avail.as_ptr()).ring[avail_slot as usize] = head;
  143. }
  144. // Write barrier so that device sees changes to descriptor table and available ring before
  145. // change to available index.
  146. fence(Ordering::SeqCst);
  147. // increase head of avail ring
  148. self.avail_idx = self.avail_idx.wrapping_add(1);
  149. // Safe because self.avail is properly aligned, dereferenceable and initialised.
  150. unsafe {
  151. (*self.avail.as_ptr()).idx = self.avail_idx;
  152. }
  153. // Write barrier so that device can see change to available index after this method returns.
  154. fence(Ordering::SeqCst);
  155. Ok(head)
  156. }
  157. /// Add the given buffers to the virtqueue, notifies the device, blocks until the device uses
  158. /// them, then pops them.
  159. ///
  160. /// This assumes that the device isn't processing any other buffers at the same time.
  161. pub fn add_notify_wait_pop<'a>(
  162. &mut self,
  163. inputs: &'a [&'a [u8]],
  164. outputs: &'a mut [&'a mut [u8]],
  165. transport: &mut impl Transport,
  166. ) -> Result<u32> {
  167. // Safe because we don't return until the same token has been popped, so the buffers remain
  168. // valid and are not otherwise accessed until then.
  169. let token = unsafe { self.add(inputs, outputs) }?;
  170. // Notify the queue.
  171. if self.should_notify() {
  172. transport.notify(self.queue_idx);
  173. }
  174. // Wait until there is at least one element in the used ring.
  175. while !self.can_pop() {
  176. spin_loop();
  177. }
  178. // Safe because these are the same buffers as we passed to `add` above and they are still
  179. // valid.
  180. unsafe { self.pop_used(token, inputs, outputs) }
  181. }
  182. /// Returns whether the driver should notify the device after adding a new buffer to the
  183. /// virtqueue.
  184. ///
  185. /// This will be false if the device has supressed notifications.
  186. pub fn should_notify(&self) -> bool {
  187. // Read barrier, so we read a fresh value from the device.
  188. fence(Ordering::SeqCst);
  189. // Safe because self.used points to a valid, aligned, initialised, dereferenceable, readable
  190. // instance of UsedRing.
  191. unsafe { (*self.used.as_ptr()).flags & 0x0001 == 0 }
  192. }
  193. /// Copies the descriptor at the given index from `desc_shadow` to `desc`, so it can be seen by
  194. /// the device.
  195. fn write_desc(&mut self, index: u16) {
  196. let index = usize::from(index);
  197. // Safe because self.desc is properly aligned, dereferenceable and initialised, and nothing
  198. // else reads or writes the descriptor during this block.
  199. unsafe {
  200. (*self.desc.as_ptr())[index] = self.desc_shadow[index].clone();
  201. }
  202. }
  203. /// Returns whether there is a used element that can be popped.
  204. pub fn can_pop(&self) -> bool {
  205. // Read barrier, so we read a fresh value from the device.
  206. fence(Ordering::SeqCst);
  207. // Safe because self.used points to a valid, aligned, initialised, dereferenceable, readable
  208. // instance of UsedRing.
  209. self.last_used_idx != unsafe { (*self.used.as_ptr()).idx }
  210. }
  211. /// Returns the descriptor index (a.k.a. token) of the next used element without popping it, or
  212. /// `None` if the used ring is empty.
  213. pub fn peek_used(&self) -> Option<u16> {
  214. if self.can_pop() {
  215. let last_used_slot = self.last_used_idx & (SIZE as u16 - 1);
  216. // Safe because self.used points to a valid, aligned, initialised, dereferenceable,
  217. // readable instance of UsedRing.
  218. Some(unsafe { (*self.used.as_ptr()).ring[last_used_slot as usize].id as u16 })
  219. } else {
  220. None
  221. }
  222. }
  223. /// Returns the number of free descriptors.
  224. pub fn available_desc(&self) -> usize {
  225. SIZE - self.num_used as usize
  226. }
  227. /// Unshares buffers in the list starting at descriptor index `head` and adds them to the free
  228. /// list. Unsharing may involve copying data back to the original buffers, so they must be
  229. /// passed in too.
  230. ///
  231. /// This will push all linked descriptors at the front of the free list.
  232. ///
  233. /// # Safety
  234. ///
  235. /// The buffers in `inputs` and `outputs` must match the set of buffers originally added to the
  236. /// queue by `add`.
  237. unsafe fn recycle_descriptors<'a>(
  238. &mut self,
  239. head: u16,
  240. inputs: &'a [&'a [u8]],
  241. outputs: &'a mut [&'a mut [u8]],
  242. ) {
  243. let original_free_head = self.free_head;
  244. self.free_head = head;
  245. let mut next = Some(head);
  246. for (buffer, direction) in InputOutputIter::new(inputs, outputs) {
  247. let desc_index = next.expect("Descriptor chain was shorter than expected.");
  248. let desc = &mut self.desc_shadow[usize::from(desc_index)];
  249. let paddr = desc.addr;
  250. desc.unset_buf();
  251. self.num_used -= 1;
  252. next = desc.next();
  253. if next.is_none() {
  254. desc.next = original_free_head;
  255. }
  256. self.write_desc(desc_index);
  257. // Safe because the caller ensures that the buffer is valid and matches the descriptor
  258. // from which we got `paddr`.
  259. unsafe {
  260. // Unshare the buffer (and perhaps copy its contents back to the original buffer).
  261. H::unshare(paddr as usize, buffer, direction);
  262. }
  263. }
  264. if next.is_some() {
  265. panic!("Descriptor chain was longer than expected.");
  266. }
  267. }
  268. /// If the given token is next on the device used queue, pops it and returns the total buffer
  269. /// length which was used (written) by the device.
  270. ///
  271. /// Ref: linux virtio_ring.c virtqueue_get_buf_ctx
  272. ///
  273. /// # Safety
  274. ///
  275. /// The buffers in `inputs` and `outputs` must match the set of buffers originally added to the
  276. /// queue by `add` when it returned the token being passed in here.
  277. pub unsafe fn pop_used<'a>(
  278. &mut self,
  279. token: u16,
  280. inputs: &'a [&'a [u8]],
  281. outputs: &'a mut [&'a mut [u8]],
  282. ) -> Result<u32> {
  283. if !self.can_pop() {
  284. return Err(Error::NotReady);
  285. }
  286. // Read barrier not necessary, as can_pop already has one.
  287. // Get the index of the start of the descriptor chain for the next element in the used ring.
  288. let last_used_slot = self.last_used_idx & (SIZE as u16 - 1);
  289. let index;
  290. let len;
  291. // Safe because self.used points to a valid, aligned, initialised, dereferenceable, readable
  292. // instance of UsedRing.
  293. unsafe {
  294. index = (*self.used.as_ptr()).ring[last_used_slot as usize].id as u16;
  295. len = (*self.used.as_ptr()).ring[last_used_slot as usize].len;
  296. }
  297. if index != token {
  298. // The device used a different descriptor chain to the one we were expecting.
  299. return Err(Error::WrongToken);
  300. }
  301. // Safe because the caller ensures the buffers are valid and match the descriptor.
  302. unsafe {
  303. self.recycle_descriptors(index, inputs, outputs);
  304. }
  305. self.last_used_idx = self.last_used_idx.wrapping_add(1);
  306. Ok(len)
  307. }
  308. }
  309. /// The inner layout of a VirtQueue.
  310. ///
  311. /// Ref: 2.6 Split Virtqueues
  312. #[derive(Debug)]
  313. enum VirtQueueLayout<H: Hal> {
  314. Legacy {
  315. dma: Dma<H>,
  316. avail_offset: usize,
  317. used_offset: usize,
  318. },
  319. Modern {
  320. /// The region used for the descriptor area and driver area.
  321. driver_to_device_dma: Dma<H>,
  322. /// The region used for the device area.
  323. device_to_driver_dma: Dma<H>,
  324. /// The offset from the start of the `driver_to_device_dma` region to the driver area
  325. /// (available ring).
  326. avail_offset: usize,
  327. },
  328. }
  329. impl<H: Hal> VirtQueueLayout<H> {
  330. /// Allocates a single DMA region containing all parts of the virtqueue, following the layout
  331. /// required by legacy interfaces.
  332. ///
  333. /// Ref: 2.6.2 Legacy Interfaces: A Note on Virtqueue Layout
  334. fn allocate_legacy(queue_size: u16) -> Result<Self> {
  335. let (desc, avail, used) = queue_part_sizes(queue_size);
  336. let size = align_up(desc + avail) + align_up(used);
  337. // Allocate contiguous pages.
  338. let dma = Dma::new(size / PAGE_SIZE, BufferDirection::Both)?;
  339. Ok(Self::Legacy {
  340. dma,
  341. avail_offset: desc,
  342. used_offset: align_up(desc + avail),
  343. })
  344. }
  345. /// Allocates separate DMA regions for the the different parts of the virtqueue, as supported by
  346. /// non-legacy interfaces.
  347. ///
  348. /// This is preferred over `allocate_legacy` where possible as it reduces memory fragmentation
  349. /// and allows the HAL to know which DMA regions are used in which direction.
  350. fn allocate_flexible(queue_size: u16) -> Result<Self> {
  351. let (desc, avail, used) = queue_part_sizes(queue_size);
  352. let driver_to_device_dma = Dma::new(pages(desc + avail), BufferDirection::DriverToDevice)?;
  353. let device_to_driver_dma = Dma::new(pages(used), BufferDirection::DeviceToDriver)?;
  354. Ok(Self::Modern {
  355. driver_to_device_dma,
  356. device_to_driver_dma,
  357. avail_offset: desc,
  358. })
  359. }
  360. /// Returns the physical address of the descriptor area.
  361. fn descriptors_paddr(&self) -> PhysAddr {
  362. match self {
  363. Self::Legacy { dma, .. } => dma.paddr(),
  364. Self::Modern {
  365. driver_to_device_dma,
  366. ..
  367. } => driver_to_device_dma.paddr(),
  368. }
  369. }
  370. /// Returns a pointer to the descriptor table (in the descriptor area).
  371. fn descriptors_vaddr(&self) -> NonNull<u8> {
  372. match self {
  373. Self::Legacy { dma, .. } => dma.vaddr(0),
  374. Self::Modern {
  375. driver_to_device_dma,
  376. ..
  377. } => driver_to_device_dma.vaddr(0),
  378. }
  379. }
  380. /// Returns the physical address of the driver area.
  381. fn driver_area_paddr(&self) -> PhysAddr {
  382. match self {
  383. Self::Legacy {
  384. dma, avail_offset, ..
  385. } => dma.paddr() + avail_offset,
  386. Self::Modern {
  387. driver_to_device_dma,
  388. avail_offset,
  389. ..
  390. } => driver_to_device_dma.paddr() + avail_offset,
  391. }
  392. }
  393. /// Returns a pointer to the available ring (in the driver area).
  394. fn avail_vaddr(&self) -> NonNull<u8> {
  395. match self {
  396. Self::Legacy {
  397. dma, avail_offset, ..
  398. } => dma.vaddr(*avail_offset),
  399. Self::Modern {
  400. driver_to_device_dma,
  401. avail_offset,
  402. ..
  403. } => driver_to_device_dma.vaddr(*avail_offset),
  404. }
  405. }
  406. /// Returns the physical address of the device area.
  407. fn device_area_paddr(&self) -> PhysAddr {
  408. match self {
  409. Self::Legacy {
  410. used_offset, dma, ..
  411. } => dma.paddr() + used_offset,
  412. Self::Modern {
  413. device_to_driver_dma,
  414. ..
  415. } => device_to_driver_dma.paddr(),
  416. }
  417. }
  418. /// Returns a pointer to the used ring (in the driver area).
  419. fn used_vaddr(&self) -> NonNull<u8> {
  420. match self {
  421. Self::Legacy {
  422. dma, used_offset, ..
  423. } => dma.vaddr(*used_offset),
  424. Self::Modern {
  425. device_to_driver_dma,
  426. ..
  427. } => device_to_driver_dma.vaddr(0),
  428. }
  429. }
  430. }
  431. /// Returns the size in bytes of the descriptor table, available ring and used ring for a given
  432. /// queue size.
  433. ///
  434. /// Ref: 2.6 Split Virtqueues
  435. fn queue_part_sizes(queue_size: u16) -> (usize, usize, usize) {
  436. assert!(
  437. queue_size.is_power_of_two(),
  438. "queue size should be a power of 2"
  439. );
  440. let queue_size = queue_size as usize;
  441. let desc = size_of::<Descriptor>() * queue_size;
  442. let avail = size_of::<u16>() * (3 + queue_size);
  443. let used = size_of::<u16>() * 3 + size_of::<UsedElem>() * queue_size;
  444. (desc, avail, used)
  445. }
  446. #[repr(C, align(16))]
  447. #[derive(Clone, Debug, FromBytes)]
  448. pub(crate) struct Descriptor {
  449. addr: u64,
  450. len: u32,
  451. flags: DescFlags,
  452. next: u16,
  453. }
  454. impl Descriptor {
  455. /// Sets the buffer address, length and flags, and shares it with the device.
  456. ///
  457. /// # Safety
  458. ///
  459. /// The caller must ensure that the buffer lives at least as long as the descriptor is active.
  460. unsafe fn set_buf<H: Hal>(
  461. &mut self,
  462. buf: NonNull<[u8]>,
  463. direction: BufferDirection,
  464. extra_flags: DescFlags,
  465. ) {
  466. self.addr = H::share(buf, direction) as u64;
  467. self.len = buf.len() as u32;
  468. self.flags = extra_flags
  469. | match direction {
  470. BufferDirection::DeviceToDriver => DescFlags::WRITE,
  471. BufferDirection::DriverToDevice => DescFlags::empty(),
  472. BufferDirection::Both => {
  473. panic!("Buffer passed to device should never use BufferDirection::Both.")
  474. }
  475. };
  476. }
  477. /// Sets the buffer address and length to 0.
  478. ///
  479. /// This must only be called once the device has finished using the descriptor.
  480. fn unset_buf(&mut self) {
  481. self.addr = 0;
  482. self.len = 0;
  483. }
  484. /// Returns the index of the next descriptor in the chain if the `NEXT` flag is set, or `None`
  485. /// if it is not (and thus this descriptor is the end of the chain).
  486. fn next(&self) -> Option<u16> {
  487. if self.flags.contains(DescFlags::NEXT) {
  488. Some(self.next)
  489. } else {
  490. None
  491. }
  492. }
  493. }
  494. bitflags! {
  495. /// Descriptor flags
  496. #[derive(FromBytes)]
  497. struct DescFlags: u16 {
  498. const NEXT = 1;
  499. const WRITE = 2;
  500. const INDIRECT = 4;
  501. }
  502. }
  503. /// The driver uses the available ring to offer buffers to the device:
  504. /// each ring entry refers to the head of a descriptor chain.
  505. /// It is only written by the driver and read by the device.
  506. #[repr(C)]
  507. #[derive(Debug)]
  508. struct AvailRing<const SIZE: usize> {
  509. flags: u16,
  510. /// A driver MUST NOT decrement the idx.
  511. idx: u16,
  512. ring: [u16; SIZE],
  513. used_event: u16, // unused
  514. }
  515. /// The used ring is where the device returns buffers once it is done with them:
  516. /// it is only written to by the device, and read by the driver.
  517. #[repr(C)]
  518. #[derive(Debug)]
  519. struct UsedRing<const SIZE: usize> {
  520. flags: u16,
  521. idx: u16,
  522. ring: [UsedElem; SIZE],
  523. avail_event: u16, // unused
  524. }
  525. #[repr(C)]
  526. #[derive(Debug)]
  527. struct UsedElem {
  528. id: u32,
  529. len: u32,
  530. }
  531. struct InputOutputIter<'a, 'b> {
  532. inputs: &'a [&'b [u8]],
  533. outputs: &'a mut [&'b mut [u8]],
  534. }
  535. impl<'a, 'b> InputOutputIter<'a, 'b> {
  536. fn new(inputs: &'a [&'b [u8]], outputs: &'a mut [&'b mut [u8]]) -> Self {
  537. Self { inputs, outputs }
  538. }
  539. }
  540. impl<'a, 'b> Iterator for InputOutputIter<'a, 'b> {
  541. type Item = (NonNull<[u8]>, BufferDirection);
  542. fn next(&mut self) -> Option<Self::Item> {
  543. if let Some(input) = take_first(&mut self.inputs) {
  544. Some(((*input).into(), BufferDirection::DriverToDevice))
  545. } else {
  546. let output = take_first_mut(&mut self.outputs)?;
  547. Some(((*output).into(), BufferDirection::DeviceToDriver))
  548. }
  549. }
  550. }
  551. // TODO: Use `slice::take_first` once it is stable
  552. // (https://github.com/rust-lang/rust/issues/62280).
  553. fn take_first<'a, T>(slice: &mut &'a [T]) -> Option<&'a T> {
  554. let (first, rem) = slice.split_first()?;
  555. *slice = rem;
  556. Some(first)
  557. }
  558. // TODO: Use `slice::take_first_mut` once it is stable
  559. // (https://github.com/rust-lang/rust/issues/62280).
  560. fn take_first_mut<'a, T>(slice: &mut &'a mut [T]) -> Option<&'a mut T> {
  561. let (first, rem) = take(slice).split_first_mut()?;
  562. *slice = rem;
  563. Some(first)
  564. }
  565. /// Simulates the device reading from a VirtIO queue and writing a response back, for use in tests.
  566. ///
  567. /// The fake device always uses descriptors in order.
  568. #[cfg(test)]
  569. pub(crate) fn fake_read_write_queue<const QUEUE_SIZE: usize>(
  570. descriptors: *const [Descriptor; QUEUE_SIZE],
  571. queue_driver_area: *const u8,
  572. queue_device_area: *mut u8,
  573. handler: impl FnOnce(Vec<u8>) -> Vec<u8>,
  574. ) {
  575. use core::{ops::Deref, slice};
  576. let available_ring = queue_driver_area as *const AvailRing<QUEUE_SIZE>;
  577. let used_ring = queue_device_area as *mut UsedRing<QUEUE_SIZE>;
  578. // Safe because the various pointers are properly aligned, dereferenceable, initialised, and
  579. // nothing else accesses them during this block.
  580. unsafe {
  581. // Make sure there is actually at least one descriptor available to read from.
  582. assert_ne!((*available_ring).idx, (*used_ring).idx);
  583. // The fake device always uses descriptors in order, like VIRTIO_F_IN_ORDER, so
  584. // `used_ring.idx` marks the next descriptor we should take from the available ring.
  585. let next_slot = (*used_ring).idx & (QUEUE_SIZE as u16 - 1);
  586. let head_descriptor_index = (*available_ring).ring[next_slot as usize];
  587. let mut descriptor = &(*descriptors)[head_descriptor_index as usize];
  588. // Loop through all input descriptors in the chain, reading data from them.
  589. let mut input = Vec::new();
  590. while !descriptor.flags.contains(DescFlags::WRITE) {
  591. input.extend_from_slice(slice::from_raw_parts(
  592. descriptor.addr as *const u8,
  593. descriptor.len as usize,
  594. ));
  595. if let Some(next) = descriptor.next() {
  596. descriptor = &(*descriptors)[next as usize];
  597. } else {
  598. break;
  599. }
  600. }
  601. let input_length = input.len();
  602. // Let the test handle the request.
  603. let output = handler(input);
  604. // Write the response to the remaining descriptors.
  605. let mut remaining_output = output.deref();
  606. if descriptor.flags.contains(DescFlags::WRITE) {
  607. loop {
  608. assert!(descriptor.flags.contains(DescFlags::WRITE));
  609. let length_to_write = min(remaining_output.len(), descriptor.len as usize);
  610. ptr::copy(
  611. remaining_output.as_ptr(),
  612. descriptor.addr as *mut u8,
  613. length_to_write,
  614. );
  615. remaining_output = &remaining_output[length_to_write..];
  616. if let Some(next) = descriptor.next() {
  617. descriptor = &(*descriptors)[next as usize];
  618. } else {
  619. break;
  620. }
  621. }
  622. }
  623. assert_eq!(remaining_output.len(), 0);
  624. // Mark the buffer as used.
  625. (*used_ring).ring[next_slot as usize].id = head_descriptor_index as u32;
  626. (*used_ring).ring[next_slot as usize].len = (input_length + output.len()) as u32;
  627. (*used_ring).idx += 1;
  628. }
  629. }
  630. #[cfg(test)]
  631. mod tests {
  632. use super::*;
  633. use crate::{
  634. hal::fake::FakeHal,
  635. transport::mmio::{MmioTransport, VirtIOHeader, MODERN_VERSION},
  636. };
  637. use core::ptr::NonNull;
  638. #[test]
  639. fn invalid_queue_size() {
  640. let mut header = VirtIOHeader::make_fake_header(MODERN_VERSION, 1, 0, 0, 4);
  641. let mut transport = unsafe { MmioTransport::new(NonNull::from(&mut header)) }.unwrap();
  642. // Size not a power of 2.
  643. assert_eq!(
  644. VirtQueue::<FakeHal, 3>::new(&mut transport, 0).unwrap_err(),
  645. Error::InvalidParam
  646. );
  647. }
  648. #[test]
  649. fn queue_too_big() {
  650. let mut header = VirtIOHeader::make_fake_header(MODERN_VERSION, 1, 0, 0, 4);
  651. let mut transport = unsafe { MmioTransport::new(NonNull::from(&mut header)) }.unwrap();
  652. assert_eq!(
  653. VirtQueue::<FakeHal, 8>::new(&mut transport, 0).unwrap_err(),
  654. Error::InvalidParam
  655. );
  656. }
  657. #[test]
  658. fn queue_already_used() {
  659. let mut header = VirtIOHeader::make_fake_header(MODERN_VERSION, 1, 0, 0, 4);
  660. let mut transport = unsafe { MmioTransport::new(NonNull::from(&mut header)) }.unwrap();
  661. VirtQueue::<FakeHal, 4>::new(&mut transport, 0).unwrap();
  662. assert_eq!(
  663. VirtQueue::<FakeHal, 4>::new(&mut transport, 0).unwrap_err(),
  664. Error::AlreadyUsed
  665. );
  666. }
  667. #[test]
  668. fn add_empty() {
  669. let mut header = VirtIOHeader::make_fake_header(MODERN_VERSION, 1, 0, 0, 4);
  670. let mut transport = unsafe { MmioTransport::new(NonNull::from(&mut header)) }.unwrap();
  671. let mut queue = VirtQueue::<FakeHal, 4>::new(&mut transport, 0).unwrap();
  672. assert_eq!(
  673. unsafe { queue.add(&[], &mut []) }.unwrap_err(),
  674. Error::InvalidParam
  675. );
  676. }
  677. #[test]
  678. fn add_too_many() {
  679. let mut header = VirtIOHeader::make_fake_header(MODERN_VERSION, 1, 0, 0, 4);
  680. let mut transport = unsafe { MmioTransport::new(NonNull::from(&mut header)) }.unwrap();
  681. let mut queue = VirtQueue::<FakeHal, 4>::new(&mut transport, 0).unwrap();
  682. assert_eq!(queue.available_desc(), 4);
  683. assert_eq!(
  684. unsafe { queue.add(&[&[], &[], &[]], &mut [&mut [], &mut []]) }.unwrap_err(),
  685. Error::QueueFull
  686. );
  687. }
  688. #[test]
  689. fn add_buffers() {
  690. let mut header = VirtIOHeader::make_fake_header(MODERN_VERSION, 1, 0, 0, 4);
  691. let mut transport = unsafe { MmioTransport::new(NonNull::from(&mut header)) }.unwrap();
  692. let mut queue = VirtQueue::<FakeHal, 4>::new(&mut transport, 0).unwrap();
  693. assert_eq!(queue.available_desc(), 4);
  694. // Add a buffer chain consisting of two device-readable parts followed by two
  695. // device-writable parts.
  696. let token = unsafe { queue.add(&[&[1, 2], &[3]], &mut [&mut [0, 0], &mut [0]]) }.unwrap();
  697. assert_eq!(queue.available_desc(), 0);
  698. assert!(!queue.can_pop());
  699. // Safe because the various parts of the queue are properly aligned, dereferenceable and
  700. // initialised, and nothing else is accessing them at the same time.
  701. unsafe {
  702. let first_descriptor_index = (*queue.avail.as_ptr()).ring[0];
  703. assert_eq!(first_descriptor_index, token);
  704. assert_eq!(
  705. (*queue.desc.as_ptr())[first_descriptor_index as usize].len,
  706. 2
  707. );
  708. assert_eq!(
  709. (*queue.desc.as_ptr())[first_descriptor_index as usize].flags,
  710. DescFlags::NEXT
  711. );
  712. let second_descriptor_index =
  713. (*queue.desc.as_ptr())[first_descriptor_index as usize].next;
  714. assert_eq!(
  715. (*queue.desc.as_ptr())[second_descriptor_index as usize].len,
  716. 1
  717. );
  718. assert_eq!(
  719. (*queue.desc.as_ptr())[second_descriptor_index as usize].flags,
  720. DescFlags::NEXT
  721. );
  722. let third_descriptor_index =
  723. (*queue.desc.as_ptr())[second_descriptor_index as usize].next;
  724. assert_eq!(
  725. (*queue.desc.as_ptr())[third_descriptor_index as usize].len,
  726. 2
  727. );
  728. assert_eq!(
  729. (*queue.desc.as_ptr())[third_descriptor_index as usize].flags,
  730. DescFlags::NEXT | DescFlags::WRITE
  731. );
  732. let fourth_descriptor_index =
  733. (*queue.desc.as_ptr())[third_descriptor_index as usize].next;
  734. assert_eq!(
  735. (*queue.desc.as_ptr())[fourth_descriptor_index as usize].len,
  736. 1
  737. );
  738. assert_eq!(
  739. (*queue.desc.as_ptr())[fourth_descriptor_index as usize].flags,
  740. DescFlags::WRITE
  741. );
  742. }
  743. }
  744. }