blob: 0d3f445725e1f13b8357d1cacd0065d7d0c59765 [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;
Alice Wangeade1672023-06-08 14:56:20 +000018use crate::memory::{alloc_shared, dealloc_shared, phys_to_virt, virt_to_phys};
19use crate::util::RangeExt as _;
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
Andrew Walbran2b0c7fb2023-05-09 12:16:20 +000026/// The alignment to use for the temporary buffers allocated by `HalImpl::share`. There doesn't seem
27/// to be any particular alignment required by VirtIO for these, so 16 bytes should be enough to
28/// allow appropriate alignment for whatever fields are accessed. `alloc_shared` will increase the
29/// alignment to the memory sharing granule size anyway.
30const SHARED_BUFFER_ALIGNMENT: usize = size_of::<u128>();
31
Alice Wangeade1672023-06-08 14:56:20 +000032/// HAL implementation for the virtio_drivers crate.
Andrew Walbran848decf2022-12-15 14:39:38 +000033pub struct HalImpl;
34
Andrew Walbranc06e7342023-07-05 14:00:51 +000035/// SAFETY: See the 'Implementation Safety' comments on methods below for how they fulfill the
36/// safety requirements of the unsafe `Hal` trait.
Alice Wang63e0d0d2023-04-20 14:15:32 +000037unsafe impl Hal for HalImpl {
Alice Wang63e0d0d2023-04-20 14:15:32 +000038 /// # Implementation Safety
39 ///
40 /// `dma_alloc` ensures the returned DMA buffer is not aliased with any other allocation or
Andrew Walbran2b0c7fb2023-05-09 12:16:20 +000041 /// reference in the program until it is deallocated by `dma_dealloc` by allocating a unique
42 /// block of memory using `alloc_shared`, which is guaranteed to allocate valid and unique
Andrew Walbrancf9333e2023-05-16 16:00:35 +000043 /// memory. We request an alignment of at least `PAGE_SIZE` from `alloc_shared`. We zero the
44 /// buffer before returning it.
Andrew Walbran272bd7a2023-01-24 14:02:36 +000045 fn dma_alloc(pages: usize, _direction: BufferDirection) -> (PhysAddr, NonNull<u8>) {
Andrew Walbrancf9333e2023-05-16 16:00:35 +000046 let layout = dma_layout(pages);
47 let vaddr =
48 alloc_shared(layout).expect("Failed to allocate and share VirtIO DMA range with host");
Andrew Walbranc06e7342023-07-05 14:00:51 +000049 // SAFETY: vaddr points to a region allocated for the caller so is safe to access.
Andrew Walbrancf9333e2023-05-16 16:00:35 +000050 unsafe { core::ptr::write_bytes(vaddr.as_ptr(), 0, layout.size()) };
Andrew Walbran272bd7a2023-01-24 14:02:36 +000051 let paddr = virt_to_phys(vaddr);
52 (paddr, vaddr)
Andrew Walbran848decf2022-12-15 14:39:38 +000053 }
54
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000055 unsafe fn dma_dealloc(_paddr: PhysAddr, vaddr: NonNull<u8>, pages: usize) -> i32 {
Andrew Walbranc06e7342023-07-05 14:00:51 +000056 // SAFETY: Memory was allocated by `dma_alloc` using `alloc_shared` with the same layout.
Pierre-Clément Tosi2d5bc582023-05-03 11:23:11 +000057 unsafe { dealloc_shared(vaddr, dma_layout(pages)) }
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000058 .expect("Failed to unshare VirtIO DMA range with host");
Andrew Walbran848decf2022-12-15 14:39:38 +000059 0
60 }
61
Alice Wang63e0d0d2023-04-20 14:15:32 +000062 /// # Implementation Safety
63 ///
Andrew Walbran2b0c7fb2023-05-09 12:16:20 +000064 /// The returned pointer must be valid because the `paddr` describes a valid MMIO region, we
65 /// check that it is within the PCI MMIO range, and we previously mapped the entire PCI MMIO
66 /// range. It can't alias any other allocations because we previously validated in
67 /// `map_mmio_range` that the PCI MMIO range didn't overlap with any other memory ranges.
Alice Wang63e0d0d2023-04-20 14:15:32 +000068 unsafe fn mmio_phys_to_virt(paddr: PhysAddr, size: usize) -> NonNull<u8> {
Alice Wangeff58392023-07-04 13:32:09 +000069 let pci_info = PCI_INFO.get().expect("VirtIO HAL used before PCI_INFO was initialized");
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000070 let bar_range = {
71 let start = pci_info.bar_range.start.try_into().unwrap();
72 let end = pci_info.bar_range.end.try_into().unwrap();
73
74 start..end
75 };
76 let mmio_range = paddr..paddr.checked_add(size).expect("PCI MMIO region end overflowed");
77
Andrew Walbranb398fc82023-01-24 14:45:46 +000078 // Check that the region is within the PCI MMIO range that we read from the device tree. If
79 // not, the host is probably trying to do something malicious.
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000080 assert!(
81 mmio_range.is_within(&bar_range),
82 "PCI MMIO region was outside of expected BAR range.",
83 );
84
Andrew Walbran272bd7a2023-01-24 14:02:36 +000085 phys_to_virt(paddr)
Andrew Walbran848decf2022-12-15 14:39:38 +000086 }
87
Alice Wang63e0d0d2023-04-20 14:15:32 +000088 unsafe fn share(buffer: NonNull<[u8]>, direction: BufferDirection) -> PhysAddr {
Andrew Walbran848decf2022-12-15 14:39:38 +000089 let size = buffer.len();
90
Pierre-Clément Tosi2d5bc582023-05-03 11:23:11 +000091 let bounce = alloc_shared(bb_layout(size))
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000092 .expect("Failed to allocate and share VirtIO bounce buffer with host");
93 let paddr = virt_to_phys(bounce);
Andrew Walbran848decf2022-12-15 14:39:38 +000094 if direction == BufferDirection::DriverToDevice {
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000095 let src = buffer.cast::<u8>().as_ptr().cast_const();
96 trace!("VirtIO bounce buffer at {bounce:?} (PA:{paddr:#x}) initialized from {src:?}");
Andrew Walbranc06e7342023-07-05 14:00:51 +000097 // SAFETY: Both regions are valid, properly aligned, and don't overlap.
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000098 unsafe { copy_nonoverlapping(src, bounce.as_ptr(), size) };
Andrew Walbran848decf2022-12-15 14:39:38 +000099 }
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +0000100
101 paddr
Andrew Walbran848decf2022-12-15 14:39:38 +0000102 }
103
Alice Wang63e0d0d2023-04-20 14:15:32 +0000104 unsafe fn unshare(paddr: PhysAddr, buffer: NonNull<[u8]>, direction: BufferDirection) {
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +0000105 let bounce = phys_to_virt(paddr);
Andrew Walbran848decf2022-12-15 14:39:38 +0000106 let size = buffer.len();
107 if direction == BufferDirection::DeviceToDriver {
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +0000108 let dest = buffer.cast::<u8>().as_ptr();
109 trace!("VirtIO bounce buffer at {bounce:?} (PA:{paddr:#x}) copied back to {dest:?}");
Andrew Walbranc06e7342023-07-05 14:00:51 +0000110 // SAFETY: Both regions are valid, properly aligned, and don't overlap.
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +0000111 unsafe { copy_nonoverlapping(bounce.as_ptr(), dest, size) };
Andrew Walbran848decf2022-12-15 14:39:38 +0000112 }
113
Andrew Walbranc06e7342023-07-05 14:00:51 +0000114 // SAFETY: Memory was allocated by `share` using `alloc_shared` with the same layout.
Pierre-Clément Tosi2d5bc582023-05-03 11:23:11 +0000115 unsafe { dealloc_shared(bounce, bb_layout(size)) }
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +0000116 .expect("Failed to unshare and deallocate VirtIO bounce buffer");
Andrew Walbran848decf2022-12-15 14:39:38 +0000117 }
118}
Pierre-Clément Tosi2d5bc582023-05-03 11:23:11 +0000119
120fn dma_layout(pages: usize) -> Layout {
121 let size = pages.checked_mul(PAGE_SIZE).unwrap();
122 Layout::from_size_align(size, PAGE_SIZE).unwrap()
123}
124
125fn bb_layout(size: usize) -> Layout {
Andrew Walbran2b0c7fb2023-05-09 12:16:20 +0000126 Layout::from_size_align(size, SHARED_BUFFER_ALIGNMENT).unwrap()
Pierre-Clément Tosi2d5bc582023-05-03 11:23:11 +0000127}