hal.rs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. #[cfg(test)]
  2. pub mod fake;
  3. use crate::{Error, Result, PAGE_SIZE};
  4. use core::{marker::PhantomData, ptr::NonNull};
  5. /// A physical address as used for virtio.
  6. pub type PhysAddr = usize;
  7. /// A region of contiguous physical memory used for DMA.
  8. #[derive(Debug)]
  9. pub struct Dma<H: Hal> {
  10. paddr: usize,
  11. vaddr: NonNull<u8>,
  12. pages: usize,
  13. _hal: PhantomData<H>,
  14. }
  15. impl<H: Hal> Dma<H> {
  16. /// Allocates the given number of pages of physically contiguous memory to be used for DMA in
  17. /// the given direction.
  18. ///
  19. /// The pages will be zeroed.
  20. pub fn new(pages: usize, direction: BufferDirection) -> Result<Self> {
  21. let (paddr, vaddr) = H::dma_alloc(pages, direction);
  22. if paddr == 0 {
  23. return Err(Error::DmaError);
  24. }
  25. Ok(Self {
  26. paddr,
  27. vaddr,
  28. pages,
  29. _hal: PhantomData,
  30. })
  31. }
  32. /// Returns the physical address of the start of the DMA region, as seen by devices.
  33. pub fn paddr(&self) -> usize {
  34. self.paddr
  35. }
  36. /// Returns a pointer to the given offset within the DMA region.
  37. pub fn vaddr(&self, offset: usize) -> NonNull<u8> {
  38. assert!(offset < self.pages * PAGE_SIZE);
  39. NonNull::new((self.vaddr.as_ptr() as usize + offset) as _).unwrap()
  40. }
  41. /// Returns a pointer to the entire DMA region as a slice.
  42. pub fn raw_slice(&self) -> NonNull<[u8]> {
  43. let raw_slice =
  44. core::ptr::slice_from_raw_parts_mut(self.vaddr(0).as_ptr(), self.pages * PAGE_SIZE);
  45. NonNull::new(raw_slice).unwrap()
  46. }
  47. }
  48. impl<H: Hal> Drop for Dma<H> {
  49. fn drop(&mut self) {
  50. // Safe because the memory was previously allocated by `dma_alloc` in `Dma::new`, not yet
  51. // deallocated, and we are passing the values from then.
  52. let err = unsafe { H::dma_dealloc(self.paddr, self.vaddr, self.pages) };
  53. assert_eq!(err, 0, "failed to deallocate DMA");
  54. }
  55. }
  56. /// The interface which a particular hardware implementation must implement.
  57. ///
  58. /// # Safety
  59. ///
  60. /// Implementations of this trait must follow the "implementation safety" requirements documented
  61. /// for each method. Callers must follow the safety requirements documented for the unsafe methods.
  62. pub unsafe trait Hal {
  63. /// Allocates and zeroes the given number of contiguous physical pages of DMA memory for VirtIO
  64. /// use.
  65. ///
  66. /// Returns both the physical address which the device can use to access the memory, and a
  67. /// pointer to the start of it which the driver can use to access it.
  68. ///
  69. /// # Implementation safety
  70. ///
  71. /// Implementations of this method must ensure that the `NonNull<u8>` returned is a
  72. /// [_valid_](https://doc.rust-lang.org/std/ptr/index.html#safety) pointer, aligned to
  73. /// [`PAGE_SIZE`], and won't alias any other allocations or references in the program until it
  74. /// is deallocated by `dma_dealloc`. The pages must be zeroed.
  75. fn dma_alloc(pages: usize, direction: BufferDirection) -> (PhysAddr, NonNull<u8>);
  76. /// Deallocates the given contiguous physical DMA memory pages.
  77. ///
  78. /// # Safety
  79. ///
  80. /// The memory must have been allocated by `dma_alloc` on the same `Hal` implementation, and not
  81. /// yet deallocated. `pages` must be the same number passed to `dma_alloc` originally, and both
  82. /// `paddr` and `vaddr` must be the values returned by `dma_alloc`.
  83. unsafe fn dma_dealloc(paddr: PhysAddr, vaddr: NonNull<u8>, pages: usize) -> i32;
  84. /// Converts a physical address used for MMIO to a virtual address which the driver can access.
  85. ///
  86. /// This is only used for MMIO addresses within BARs read from the device, for the PCI
  87. /// transport. It may check that the address range up to the given size is within the region
  88. /// expected for MMIO.
  89. ///
  90. /// # Implementation safety
  91. ///
  92. /// Implementations of this method must ensure that the `NonNull<u8>` returned is a
  93. /// [_valid_](https://doc.rust-lang.org/std/ptr/index.html#safety) pointer, and won't alias any
  94. /// other allocations or references in the program.
  95. ///
  96. /// # Safety
  97. ///
  98. /// The `paddr` and `size` must describe a valid MMIO region. The implementation may validate it
  99. /// in some way (and panic if it is invalid) but is not guaranteed to.
  100. unsafe fn mmio_phys_to_virt(paddr: PhysAddr, size: usize) -> NonNull<u8>;
  101. /// Shares the given memory range with the device, and returns the physical address that the
  102. /// device can use to access it.
  103. ///
  104. /// This may involve mapping the buffer into an IOMMU, giving the host permission to access the
  105. /// memory, or copying it to a special region where it can be accessed.
  106. ///
  107. /// # Safety
  108. ///
  109. /// The buffer must be a valid pointer to a non-empty memory range which will not be accessed by
  110. /// any other thread for the duration of this method call.
  111. unsafe fn share(buffer: NonNull<[u8]>, direction: BufferDirection) -> PhysAddr;
  112. /// Unshares the given memory range from the device and (if necessary) copies it back to the
  113. /// original buffer.
  114. ///
  115. /// # Safety
  116. ///
  117. /// The buffer must be a valid pointer to a non-empty memory range which will not be accessed by
  118. /// any other thread for the duration of this method call. The `paddr` must be the value
  119. /// previously returned by the corresponding `share` call.
  120. unsafe fn unshare(paddr: PhysAddr, buffer: NonNull<[u8]>, direction: BufferDirection);
  121. }
  122. /// The direction in which a buffer is passed.
  123. #[derive(Copy, Clone, Debug, Eq, PartialEq)]
  124. pub enum BufferDirection {
  125. /// The buffer may be read or written by the driver, but only read by the device.
  126. DriverToDevice,
  127. /// The buffer may be read or written by the device, but only read by the driver.
  128. DeviceToDriver,
  129. /// The buffer may be read or written by both the device and the driver.
  130. Both,
  131. }