queue.rs 29 KB

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