blob: ac5b967c3094f909fc6467fd196a4f277c8b313f [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
Alice Wang63e0d0d2023-04-20 14:15:32 +000035/// # Safety
36///
Andrew Walbran2b0c7fb2023-05-09 12:16:20 +000037/// See the 'Implementation Safety' comments on methods below for how they fulfill the safety
38/// requirements of the unsafe `Hal` trait.
Alice Wang63e0d0d2023-04-20 14:15:32 +000039unsafe impl Hal for HalImpl {
Alice Wang63e0d0d2023-04-20 14:15:32 +000040 /// # Implementation Safety
41 ///
42 /// `dma_alloc` ensures the returned DMA buffer is not aliased with any other allocation or
Andrew Walbran2b0c7fb2023-05-09 12:16:20 +000043 /// reference in the program until it is deallocated by `dma_dealloc` by allocating a unique
44 /// block of memory using `alloc_shared`, which is guaranteed to allocate valid and unique
45 /// memory. We request an alignment of at least `PAGE_SIZE` from `alloc_shared`.
Andrew Walbran272bd7a2023-01-24 14:02:36 +000046 fn dma_alloc(pages: usize, _direction: BufferDirection) -> (PhysAddr, NonNull<u8>) {
Pierre-Clément Tosi2d5bc582023-05-03 11:23:11 +000047 let vaddr = alloc_shared(dma_layout(pages))
48 .expect("Failed to allocate and share VirtIO DMA range with host");
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +000049 // TODO(ptosi): Move this zeroing to virtio_drivers, if it silently wants a zeroed region.
50 // SAFETY - vaddr points to a region allocated for the caller so is safe to access.
51 unsafe { core::ptr::write_bytes(vaddr.as_ptr(), 0, dma_layout(pages).size()) };
Andrew Walbran272bd7a2023-01-24 14:02:36 +000052 let paddr = virt_to_phys(vaddr);
53 (paddr, vaddr)
Andrew Walbran848decf2022-12-15 14:39:38 +000054 }
55
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000056 unsafe fn dma_dealloc(_paddr: PhysAddr, vaddr: NonNull<u8>, pages: usize) -> i32 {
Andrew Walbran2b0c7fb2023-05-09 12:16:20 +000057 // SAFETY - Memory was allocated by `dma_alloc` using `alloc_shared` with the same layout.
Pierre-Clément Tosi2d5bc582023-05-03 11:23:11 +000058 unsafe { dealloc_shared(vaddr, dma_layout(pages)) }
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000059 .expect("Failed to unshare VirtIO DMA range with host");
Andrew Walbran848decf2022-12-15 14:39:38 +000060 0
61 }
62
Alice Wang63e0d0d2023-04-20 14:15:32 +000063 /// # Implementation Safety
64 ///
Andrew Walbran2b0c7fb2023-05-09 12:16:20 +000065 /// The returned pointer must be valid because the `paddr` describes a valid MMIO region, we
66 /// check that it is within the PCI MMIO range, and we previously mapped the entire PCI MMIO
67 /// range. It can't alias any other allocations because we previously validated in
68 /// `map_mmio_range` that the PCI MMIO range didn't overlap with any other memory ranges.
Alice Wang63e0d0d2023-04-20 14:15:32 +000069 unsafe fn mmio_phys_to_virt(paddr: PhysAddr, size: usize) -> NonNull<u8> {
Andrew Walbranb398fc82023-01-24 14:45:46 +000070 let pci_info = PCI_INFO.get().expect("VirtIO HAL used before PCI_INFO was initialised");
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000071 let bar_range = {
72 let start = pci_info.bar_range.start.try_into().unwrap();
73 let end = pci_info.bar_range.end.try_into().unwrap();
74
75 start..end
76 };
77 let mmio_range = paddr..paddr.checked_add(size).expect("PCI MMIO region end overflowed");
78
Andrew Walbranb398fc82023-01-24 14:45:46 +000079 // Check that the region is within the PCI MMIO range that we read from the device tree. If
80 // not, the host is probably trying to do something malicious.
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000081 assert!(
82 mmio_range.is_within(&bar_range),
83 "PCI MMIO region was outside of expected BAR range.",
84 );
85
Andrew Walbran272bd7a2023-01-24 14:02:36 +000086 phys_to_virt(paddr)
Andrew Walbran848decf2022-12-15 14:39:38 +000087 }
88
Alice Wang63e0d0d2023-04-20 14:15:32 +000089 unsafe fn share(buffer: NonNull<[u8]>, direction: BufferDirection) -> PhysAddr {
Andrew Walbran848decf2022-12-15 14:39:38 +000090 let size = buffer.len();
91
Pierre-Clément Tosi2d5bc582023-05-03 11:23:11 +000092 let bounce = alloc_shared(bb_layout(size))
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000093 .expect("Failed to allocate and share VirtIO bounce buffer with host");
94 let paddr = virt_to_phys(bounce);
Andrew Walbran848decf2022-12-15 14:39:38 +000095 if direction == BufferDirection::DriverToDevice {
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000096 let src = buffer.cast::<u8>().as_ptr().cast_const();
97 trace!("VirtIO bounce buffer at {bounce:?} (PA:{paddr:#x}) initialized from {src:?}");
98 // SAFETY - Both regions are valid, properly aligned, and don't overlap.
99 unsafe { copy_nonoverlapping(src, bounce.as_ptr(), size) };
Andrew Walbran848decf2022-12-15 14:39:38 +0000100 }
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +0000101
102 paddr
Andrew Walbran848decf2022-12-15 14:39:38 +0000103 }
104
Alice Wang63e0d0d2023-04-20 14:15:32 +0000105 unsafe fn unshare(paddr: PhysAddr, buffer: NonNull<[u8]>, direction: BufferDirection) {
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +0000106 let bounce = phys_to_virt(paddr);
Andrew Walbran848decf2022-12-15 14:39:38 +0000107 let size = buffer.len();
108 if direction == BufferDirection::DeviceToDriver {
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +0000109 let dest = buffer.cast::<u8>().as_ptr();
110 trace!("VirtIO bounce buffer at {bounce:?} (PA:{paddr:#x}) copied back to {dest:?}");
111 // SAFETY - Both regions are valid, properly aligned, and don't overlap.
112 unsafe { copy_nonoverlapping(bounce.as_ptr(), dest, size) };
Andrew Walbran848decf2022-12-15 14:39:38 +0000113 }
114
Andrew Walbran2b0c7fb2023-05-09 12:16:20 +0000115 // SAFETY - Memory was allocated by `share` using `alloc_shared` with the same layout.
Pierre-Clément Tosi2d5bc582023-05-03 11:23:11 +0000116 unsafe { dealloc_shared(bounce, bb_layout(size)) }
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +0000117 .expect("Failed to unshare and deallocate VirtIO bounce buffer");
Andrew Walbran848decf2022-12-15 14:39:38 +0000118 }
119}
Pierre-Clément Tosi2d5bc582023-05-03 11:23:11 +0000120
121fn dma_layout(pages: usize) -> Layout {
122 let size = pages.checked_mul(PAGE_SIZE).unwrap();
123 Layout::from_size_align(size, PAGE_SIZE).unwrap()
124}
125
126fn bb_layout(size: usize) -> Layout {
Andrew Walbran2b0c7fb2023-05-09 12:16:20 +0000127 Layout::from_size_align(size, SHARED_BUFFER_ALIGNMENT).unwrap()
Pierre-Clément Tosi2d5bc582023-05-03 11:23:11 +0000128}