blob: 51567cd2cb26364d8fd365be403e3bab596569d6 [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 Tosi2d5bc582023-05-03 11:23:11 +000020use core::alloc::Layout;
21use core::mem::size_of;
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000022use core::ptr::{copy_nonoverlapping, NonNull};
23use log::trace;
Andrew Walbran272bd7a2023-01-24 14:02:36 +000024use virtio_drivers::{BufferDirection, Hal, PhysAddr, PAGE_SIZE};
Andrew Walbran848decf2022-12-15 14:39:38 +000025
26pub struct HalImpl;
27
Alice Wang63e0d0d2023-04-20 14:15:32 +000028/// Implements the `Hal` trait for `HalImpl`.
29///
30/// # Safety
31///
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000032/// Callers of this implementatation must follow the safety requirements documented in the `Hal`
33/// trait for the unsafe methods.
Alice Wang63e0d0d2023-04-20 14:15:32 +000034unsafe impl Hal for HalImpl {
35 /// Allocates the given number of contiguous physical pages of DMA memory for VirtIO use.
36 ///
37 /// # Implementation Safety
38 ///
39 /// `dma_alloc` ensures the returned DMA buffer is not aliased with any other allocation or
40 /// reference in the program until it is deallocated by `dma_dealloc` by allocating a unique
41 /// block of memory using `alloc_shared` and returning a non-null pointer to it that is
42 /// aligned to `PAGE_SIZE`.
Andrew Walbran272bd7a2023-01-24 14:02:36 +000043 fn dma_alloc(pages: usize, _direction: BufferDirection) -> (PhysAddr, NonNull<u8>) {
Pierre-Clément Tosi2d5bc582023-05-03 11:23:11 +000044 let vaddr = alloc_shared(dma_layout(pages))
45 .expect("Failed to allocate and share VirtIO DMA range with host");
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +000046 // TODO(ptosi): Move this zeroing to virtio_drivers, if it silently wants a zeroed region.
47 // SAFETY - vaddr points to a region allocated for the caller so is safe to access.
48 unsafe { core::ptr::write_bytes(vaddr.as_ptr(), 0, dma_layout(pages).size()) };
Andrew Walbran272bd7a2023-01-24 14:02:36 +000049 let paddr = virt_to_phys(vaddr);
50 (paddr, vaddr)
Andrew Walbran848decf2022-12-15 14:39:38 +000051 }
52
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000053 unsafe fn dma_dealloc(_paddr: PhysAddr, vaddr: NonNull<u8>, pages: usize) -> i32 {
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000054 // SAFETY - Memory was allocated by `dma_alloc` using `alloc_shared` with the same size.
Pierre-Clément Tosi2d5bc582023-05-03 11:23:11 +000055 unsafe { dealloc_shared(vaddr, dma_layout(pages)) }
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000056 .expect("Failed to unshare VirtIO DMA range with host");
Andrew Walbran848decf2022-12-15 14:39:38 +000057 0
58 }
59
Alice Wang63e0d0d2023-04-20 14:15:32 +000060 /// Converts a physical address used for MMIO to a virtual address which the driver can access.
61 ///
62 /// # Implementation Safety
63 ///
64 /// `mmio_phys_to_virt` satisfies the requirement by checking that the mapped memory region
65 /// is within the PCI MMIO range.
66 unsafe fn mmio_phys_to_virt(paddr: PhysAddr, size: usize) -> NonNull<u8> {
Andrew Walbranb398fc82023-01-24 14:45:46 +000067 let pci_info = PCI_INFO.get().expect("VirtIO HAL used before PCI_INFO was initialised");
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000068 let bar_range = {
69 let start = pci_info.bar_range.start.try_into().unwrap();
70 let end = pci_info.bar_range.end.try_into().unwrap();
71
72 start..end
73 };
74 let mmio_range = paddr..paddr.checked_add(size).expect("PCI MMIO region end overflowed");
75
Andrew Walbranb398fc82023-01-24 14:45:46 +000076 // Check that the region is within the PCI MMIO range that we read from the device tree. If
77 // not, the host is probably trying to do something malicious.
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000078 assert!(
79 mmio_range.is_within(&bar_range),
80 "PCI MMIO region was outside of expected BAR range.",
81 );
82
Andrew Walbran272bd7a2023-01-24 14:02:36 +000083 phys_to_virt(paddr)
Andrew Walbran848decf2022-12-15 14:39:38 +000084 }
85
Alice Wang63e0d0d2023-04-20 14:15:32 +000086 unsafe fn share(buffer: NonNull<[u8]>, direction: BufferDirection) -> PhysAddr {
Andrew Walbran848decf2022-12-15 14:39:38 +000087 let size = buffer.len();
88
Pierre-Clément Tosi2d5bc582023-05-03 11:23:11 +000089 let bounce = alloc_shared(bb_layout(size))
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000090 .expect("Failed to allocate and share VirtIO bounce buffer with host");
91 let paddr = virt_to_phys(bounce);
Andrew Walbran848decf2022-12-15 14:39:38 +000092 if direction == BufferDirection::DriverToDevice {
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000093 let src = buffer.cast::<u8>().as_ptr().cast_const();
94 trace!("VirtIO bounce buffer at {bounce:?} (PA:{paddr:#x}) initialized from {src:?}");
95 // SAFETY - Both regions are valid, properly aligned, and don't overlap.
96 unsafe { copy_nonoverlapping(src, bounce.as_ptr(), size) };
Andrew Walbran848decf2022-12-15 14:39:38 +000097 }
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000098
99 paddr
Andrew Walbran848decf2022-12-15 14:39:38 +0000100 }
101
Alice Wang63e0d0d2023-04-20 14:15:32 +0000102 unsafe fn unshare(paddr: PhysAddr, buffer: NonNull<[u8]>, direction: BufferDirection) {
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +0000103 let bounce = phys_to_virt(paddr);
Andrew Walbran848decf2022-12-15 14:39:38 +0000104 let size = buffer.len();
105 if direction == BufferDirection::DeviceToDriver {
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +0000106 let dest = buffer.cast::<u8>().as_ptr();
107 trace!("VirtIO bounce buffer at {bounce:?} (PA:{paddr:#x}) copied back to {dest:?}");
108 // SAFETY - Both regions are valid, properly aligned, and don't overlap.
109 unsafe { copy_nonoverlapping(bounce.as_ptr(), dest, size) };
Andrew Walbran848decf2022-12-15 14:39:38 +0000110 }
111
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +0000112 // SAFETY - Memory was allocated by `share` using `alloc_shared` with the same size.
Pierre-Clément Tosi2d5bc582023-05-03 11:23:11 +0000113 unsafe { dealloc_shared(bounce, bb_layout(size)) }
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +0000114 .expect("Failed to unshare and deallocate VirtIO bounce buffer");
Andrew Walbran848decf2022-12-15 14:39:38 +0000115 }
116}
Pierre-Clément Tosi2d5bc582023-05-03 11:23:11 +0000117
118fn dma_layout(pages: usize) -> Layout {
119 let size = pages.checked_mul(PAGE_SIZE).unwrap();
120 Layout::from_size_align(size, PAGE_SIZE).unwrap()
121}
122
123fn bb_layout(size: usize) -> Layout {
124 // In theory, it would be legal to align to 1-byte but use a larger alignment for good measure.
125 const VIRTIO_BOUNCE_BUFFER_ALIGN: usize = size_of::<u128>();
126 Layout::from_size_align(size, VIRTIO_BOUNCE_BUFFER_ALIGN).unwrap()
127}