blob: c84ca5ed0a4c41ee2a0c3d455739153cce887c8d [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
Andrew Walbrancf9333e2023-05-16 16:00:35 +000045 /// memory. We request an alignment of at least `PAGE_SIZE` from `alloc_shared`. We zero the
46 /// buffer before returning it.
Andrew Walbran272bd7a2023-01-24 14:02:36 +000047 fn dma_alloc(pages: usize, _direction: BufferDirection) -> (PhysAddr, NonNull<u8>) {
Andrew Walbrancf9333e2023-05-16 16:00:35 +000048 let layout = dma_layout(pages);
49 let vaddr =
50 alloc_shared(layout).expect("Failed to allocate and share VirtIO DMA range with host");
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +000051 // SAFETY - vaddr points to a region allocated for the caller so is safe to access.
Andrew Walbrancf9333e2023-05-16 16:00:35 +000052 unsafe { core::ptr::write_bytes(vaddr.as_ptr(), 0, layout.size()) };
Andrew Walbran272bd7a2023-01-24 14:02:36 +000053 let paddr = virt_to_phys(vaddr);
54 (paddr, vaddr)
Andrew Walbran848decf2022-12-15 14:39:38 +000055 }
56
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000057 unsafe fn dma_dealloc(_paddr: PhysAddr, vaddr: NonNull<u8>, pages: usize) -> i32 {
Andrew Walbran2b0c7fb2023-05-09 12:16:20 +000058 // SAFETY - Memory was allocated by `dma_alloc` using `alloc_shared` with the same layout.
Pierre-Clément Tosi2d5bc582023-05-03 11:23:11 +000059 unsafe { dealloc_shared(vaddr, dma_layout(pages)) }
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000060 .expect("Failed to unshare VirtIO DMA range with host");
Andrew Walbran848decf2022-12-15 14:39:38 +000061 0
62 }
63
Alice Wang63e0d0d2023-04-20 14:15:32 +000064 /// # Implementation Safety
65 ///
Andrew Walbran2b0c7fb2023-05-09 12:16:20 +000066 /// The returned pointer must be valid because the `paddr` describes a valid MMIO region, we
67 /// check that it is within the PCI MMIO range, and we previously mapped the entire PCI MMIO
68 /// range. It can't alias any other allocations because we previously validated in
69 /// `map_mmio_range` that the PCI MMIO range didn't overlap with any other memory ranges.
Alice Wang63e0d0d2023-04-20 14:15:32 +000070 unsafe fn mmio_phys_to_virt(paddr: PhysAddr, size: usize) -> NonNull<u8> {
Alice Wangeff58392023-07-04 13:32:09 +000071 let pci_info = PCI_INFO.get().expect("VirtIO HAL used before PCI_INFO was initialized");
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000072 let bar_range = {
73 let start = pci_info.bar_range.start.try_into().unwrap();
74 let end = pci_info.bar_range.end.try_into().unwrap();
75
76 start..end
77 };
78 let mmio_range = paddr..paddr.checked_add(size).expect("PCI MMIO region end overflowed");
79
Andrew Walbranb398fc82023-01-24 14:45:46 +000080 // Check that the region is within the PCI MMIO range that we read from the device tree. If
81 // not, the host is probably trying to do something malicious.
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000082 assert!(
83 mmio_range.is_within(&bar_range),
84 "PCI MMIO region was outside of expected BAR range.",
85 );
86
Andrew Walbran272bd7a2023-01-24 14:02:36 +000087 phys_to_virt(paddr)
Andrew Walbran848decf2022-12-15 14:39:38 +000088 }
89
Alice Wang63e0d0d2023-04-20 14:15:32 +000090 unsafe fn share(buffer: NonNull<[u8]>, direction: BufferDirection) -> PhysAddr {
Andrew Walbran848decf2022-12-15 14:39:38 +000091 let size = buffer.len();
92
Pierre-Clément Tosi2d5bc582023-05-03 11:23:11 +000093 let bounce = alloc_shared(bb_layout(size))
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000094 .expect("Failed to allocate and share VirtIO bounce buffer with host");
95 let paddr = virt_to_phys(bounce);
Andrew Walbran848decf2022-12-15 14:39:38 +000096 if direction == BufferDirection::DriverToDevice {
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000097 let src = buffer.cast::<u8>().as_ptr().cast_const();
98 trace!("VirtIO bounce buffer at {bounce:?} (PA:{paddr:#x}) initialized from {src:?}");
99 // SAFETY - Both regions are valid, properly aligned, and don't overlap.
100 unsafe { copy_nonoverlapping(src, bounce.as_ptr(), size) };
Andrew Walbran848decf2022-12-15 14:39:38 +0000101 }
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +0000102
103 paddr
Andrew Walbran848decf2022-12-15 14:39:38 +0000104 }
105
Alice Wang63e0d0d2023-04-20 14:15:32 +0000106 unsafe fn unshare(paddr: PhysAddr, buffer: NonNull<[u8]>, direction: BufferDirection) {
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +0000107 let bounce = phys_to_virt(paddr);
Andrew Walbran848decf2022-12-15 14:39:38 +0000108 let size = buffer.len();
109 if direction == BufferDirection::DeviceToDriver {
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +0000110 let dest = buffer.cast::<u8>().as_ptr();
111 trace!("VirtIO bounce buffer at {bounce:?} (PA:{paddr:#x}) copied back to {dest:?}");
112 // SAFETY - Both regions are valid, properly aligned, and don't overlap.
113 unsafe { copy_nonoverlapping(bounce.as_ptr(), dest, size) };
Andrew Walbran848decf2022-12-15 14:39:38 +0000114 }
115
Andrew Walbran2b0c7fb2023-05-09 12:16:20 +0000116 // SAFETY - Memory was allocated by `share` using `alloc_shared` with the same layout.
Pierre-Clément Tosi2d5bc582023-05-03 11:23:11 +0000117 unsafe { dealloc_shared(bounce, bb_layout(size)) }
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +0000118 .expect("Failed to unshare and deallocate VirtIO bounce buffer");
Andrew Walbran848decf2022-12-15 14:39:38 +0000119 }
120}
Pierre-Clément Tosi2d5bc582023-05-03 11:23:11 +0000121
122fn dma_layout(pages: usize) -> Layout {
123 let size = pages.checked_mul(PAGE_SIZE).unwrap();
124 Layout::from_size_align(size, PAGE_SIZE).unwrap()
125}
126
127fn bb_layout(size: usize) -> Layout {
Andrew Walbran2b0c7fb2023-05-09 12:16:20 +0000128 Layout::from_size_align(size, SHARED_BUFFER_ALIGNMENT).unwrap()
Pierre-Clément Tosi2d5bc582023-05-03 11:23:11 +0000129}