blob: 41d0f2484aba5d559c32878bf6a851a937d63e98 [file] [log] [blame]
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +00001// Copyright 2023, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! HAL for the virtio_drivers crate.
16
Andrew Walbranb398fc82023-01-24 14:45:46 +000017use super::pci::PCI_INFO;
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000018use crate::helpers::RangeExt as _;
Andrew Walbran272bd7a2023-01-24 14:02:36 +000019use crate::memory::{alloc_shared, dealloc_shared, phys_to_virt, virt_to_phys};
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000020use core::ptr::{copy_nonoverlapping, NonNull};
21use log::trace;
Andrew Walbran272bd7a2023-01-24 14:02:36 +000022use virtio_drivers::{BufferDirection, Hal, PhysAddr, PAGE_SIZE};
Andrew Walbran848decf2022-12-15 14:39:38 +000023
24pub struct HalImpl;
25
Alice Wang63e0d0d2023-04-20 14:15:32 +000026/// Implements the `Hal` trait for `HalImpl`.
27///
28/// # Safety
29///
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000030/// Callers of this implementatation must follow the safety requirements documented in the `Hal`
31/// trait for the unsafe methods.
Alice Wang63e0d0d2023-04-20 14:15:32 +000032unsafe impl Hal for HalImpl {
33 /// Allocates the given number of contiguous physical pages of DMA memory for VirtIO use.
34 ///
35 /// # Implementation Safety
36 ///
37 /// `dma_alloc` ensures the returned DMA buffer is not aliased with any other allocation or
38 /// reference in the program until it is deallocated by `dma_dealloc` by allocating a unique
39 /// block of memory using `alloc_shared` and returning a non-null pointer to it that is
40 /// aligned to `PAGE_SIZE`.
Andrew Walbran272bd7a2023-01-24 14:02:36 +000041 fn dma_alloc(pages: usize, _direction: BufferDirection) -> (PhysAddr, NonNull<u8>) {
Andrew Walbran848decf2022-12-15 14:39:38 +000042 let size = pages * PAGE_SIZE;
Andrew Walbran272bd7a2023-01-24 14:02:36 +000043 let vaddr =
44 alloc_shared(size).expect("Failed to allocate and share VirtIO DMA range with host");
45 let paddr = virt_to_phys(vaddr);
46 (paddr, vaddr)
Andrew Walbran848decf2022-12-15 14:39:38 +000047 }
48
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000049 unsafe fn dma_dealloc(_paddr: PhysAddr, vaddr: NonNull<u8>, pages: usize) -> i32 {
Andrew Walbran848decf2022-12-15 14:39:38 +000050 let size = pages * PAGE_SIZE;
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000051 // SAFETY - Memory was allocated by `dma_alloc` using `alloc_shared` with the same size.
52 unsafe { dealloc_shared(vaddr, size) }
53 .expect("Failed to unshare VirtIO DMA range with host");
Andrew Walbran848decf2022-12-15 14:39:38 +000054 0
55 }
56
Alice Wang63e0d0d2023-04-20 14:15:32 +000057 /// Converts a physical address used for MMIO to a virtual address which the driver can access.
58 ///
59 /// # Implementation Safety
60 ///
61 /// `mmio_phys_to_virt` satisfies the requirement by checking that the mapped memory region
62 /// is within the PCI MMIO range.
63 unsafe fn mmio_phys_to_virt(paddr: PhysAddr, size: usize) -> NonNull<u8> {
Andrew Walbranb398fc82023-01-24 14:45:46 +000064 let pci_info = PCI_INFO.get().expect("VirtIO HAL used before PCI_INFO was initialised");
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000065 let bar_range = {
66 let start = pci_info.bar_range.start.try_into().unwrap();
67 let end = pci_info.bar_range.end.try_into().unwrap();
68
69 start..end
70 };
71 let mmio_range = paddr..paddr.checked_add(size).expect("PCI MMIO region end overflowed");
72
Andrew Walbranb398fc82023-01-24 14:45:46 +000073 // Check that the region is within the PCI MMIO range that we read from the device tree. If
74 // not, the host is probably trying to do something malicious.
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000075 assert!(
76 mmio_range.is_within(&bar_range),
77 "PCI MMIO region was outside of expected BAR range.",
78 );
79
Andrew Walbran272bd7a2023-01-24 14:02:36 +000080 phys_to_virt(paddr)
Andrew Walbran848decf2022-12-15 14:39:38 +000081 }
82
Alice Wang63e0d0d2023-04-20 14:15:32 +000083 unsafe fn share(buffer: NonNull<[u8]>, direction: BufferDirection) -> PhysAddr {
Andrew Walbran848decf2022-12-15 14:39:38 +000084 let size = buffer.len();
85
86 // TODO: Copy to a pre-shared region rather than allocating and sharing each time.
87 // Allocate a range of pages, copy the buffer if necessary, and share the new range instead.
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000088 let bounce = alloc_shared(size)
89 .expect("Failed to allocate and share VirtIO bounce buffer with host");
90 let paddr = virt_to_phys(bounce);
Andrew Walbran848decf2022-12-15 14:39:38 +000091 if direction == BufferDirection::DriverToDevice {
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000092 let src = buffer.cast::<u8>().as_ptr().cast_const();
93 trace!("VirtIO bounce buffer at {bounce:?} (PA:{paddr:#x}) initialized from {src:?}");
94 // SAFETY - Both regions are valid, properly aligned, and don't overlap.
95 unsafe { copy_nonoverlapping(src, bounce.as_ptr(), size) };
Andrew Walbran848decf2022-12-15 14:39:38 +000096 }
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000097
98 paddr
Andrew Walbran848decf2022-12-15 14:39:38 +000099 }
100
Alice Wang63e0d0d2023-04-20 14:15:32 +0000101 unsafe fn unshare(paddr: PhysAddr, buffer: NonNull<[u8]>, direction: BufferDirection) {
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +0000102 let bounce = phys_to_virt(paddr);
Andrew Walbran848decf2022-12-15 14:39:38 +0000103 let size = buffer.len();
104 if direction == BufferDirection::DeviceToDriver {
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +0000105 let dest = buffer.cast::<u8>().as_ptr();
106 trace!("VirtIO bounce buffer at {bounce:?} (PA:{paddr:#x}) copied back to {dest:?}");
107 // SAFETY - Both regions are valid, properly aligned, and don't overlap.
108 unsafe { copy_nonoverlapping(bounce.as_ptr(), dest, size) };
Andrew Walbran848decf2022-12-15 14:39:38 +0000109 }
110
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +0000111 // SAFETY - Memory was allocated by `share` using `alloc_shared` with the same size.
112 unsafe { dealloc_shared(bounce, size) }
113 .expect("Failed to unshare and deallocate VirtIO bounce buffer");
Andrew Walbran848decf2022-12-15 14:39:38 +0000114 }
115}