blob: 6abe66e82ec39dfa4a201a231d4709f3e85fb8cf [file] [log] [blame]
Andrew Walbran8217d062022-11-22 16:56:18 +00001// Copyright 2022, 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
Andrew Walbran0a8dac72022-12-21 13:49:06 +000015//! Functions to scan the PCI bus for VirtIO device.
Andrew Walbran8217d062022-11-22 16:56:18 +000016
17use aarch64_paging::paging::MemoryRegion;
Andrew Walbrancf9333e2023-05-16 16:00:35 +000018use alloc::alloc::{alloc_zeroed, dealloc, handle_alloc_error, Layout};
Andrew Walbran336d0cb2023-01-06 16:33:15 +000019use core::{mem::size_of, ptr::NonNull};
Andrew Walbran730375d2022-12-21 14:04:34 +000020use fdtpci::PciInfo;
Andrew Walbran8217d062022-11-22 16:56:18 +000021use log::{debug, info};
22use virtio_drivers::{
Andrew Walbran8d05dae2023-03-22 16:42:55 +000023 device::{blk::VirtIOBlk, console::VirtIOConsole},
Andrew Walbran336d0cb2023-01-06 16:33:15 +000024 transport::{
25 pci::{bus::PciRoot, virtio_device_type, PciTransport},
26 DeviceType, Transport,
27 },
Andrew Walbran6ac174e2023-06-23 14:58:51 +000028 BufferDirection, Error, Hal, PhysAddr, PAGE_SIZE,
Andrew Walbran8217d062022-11-22 16:56:18 +000029};
30
31/// The standard sector size of a VirtIO block device, in bytes.
Andrew Walbranb713baa2022-12-07 14:34:49 +000032const SECTOR_SIZE_BYTES: usize = 512;
33
34/// The size in sectors of the test block device we expect.
35const EXPECTED_SECTOR_COUNT: usize = 4;
Andrew Walbran8217d062022-11-22 16:56:18 +000036
Andrew Walbran730375d2022-12-21 14:04:34 +000037pub fn check_pci(pci_root: &mut PciRoot) {
Andrew Walbranb713baa2022-12-07 14:34:49 +000038 let mut checked_virtio_device_count = 0;
Andrew Walbran6ac174e2023-06-23 14:58:51 +000039 let mut block_device_count = 0;
Andrew Walbran8217d062022-11-22 16:56:18 +000040 for (device_function, info) in pci_root.enumerate_bus(0) {
41 let (status, command) = pci_root.get_status_command(device_function);
42 info!("Found {} at {}, status {:?} command {:?}", info, device_function, status, command);
43 if let Some(virtio_type) = virtio_device_type(&info) {
44 info!(" VirtIO {:?}", virtio_type);
Andrew Walbran730375d2022-12-21 14:04:34 +000045 let mut transport = PciTransport::new::<HalImpl>(pci_root, device_function).unwrap();
Andrew Walbran8217d062022-11-22 16:56:18 +000046 info!(
47 "Detected virtio PCI device with device type {:?}, features {:#018x}",
48 transport.device_type(),
49 transport.read_device_features(),
50 );
Andrew Walbran6ac174e2023-06-23 14:58:51 +000051 match virtio_type {
52 DeviceType::Block => {
53 check_virtio_block_device(transport, block_device_count);
54 block_device_count += 1;
55 checked_virtio_device_count += 1;
56 }
57 DeviceType::Console => {
58 check_virtio_console_device(transport);
59 checked_virtio_device_count += 1;
60 }
61 _ => {}
Andrew Walbranb713baa2022-12-07 14:34:49 +000062 }
Andrew Walbran8217d062022-11-22 16:56:18 +000063 }
64 }
Andrew Walbranb713baa2022-12-07 14:34:49 +000065
Andrew Walbran6ac174e2023-06-23 14:58:51 +000066 assert_eq!(checked_virtio_device_count, 5);
67 assert_eq!(block_device_count, 2);
Andrew Walbran8217d062022-11-22 16:56:18 +000068}
69
Andrew Walbran6ac174e2023-06-23 14:58:51 +000070/// Checks the given VirtIO block device.
71fn check_virtio_block_device(transport: impl Transport, index: usize) {
72 let mut blk = VirtIOBlk::<HalImpl, _>::new(transport).expect("failed to create blk driver");
73 info!("Found {} KiB block device.", blk.capacity() * SECTOR_SIZE_BYTES as u64 / 1024);
74 match index {
75 0 => {
Andrew Walbran8d05dae2023-03-22 16:42:55 +000076 assert_eq!(blk.capacity(), EXPECTED_SECTOR_COUNT as u64);
77 let mut data = [0; SECTOR_SIZE_BYTES * EXPECTED_SECTOR_COUNT];
78 for i in 0..EXPECTED_SECTOR_COUNT {
79 blk.read_block(i, &mut data[i * SECTOR_SIZE_BYTES..(i + 1) * SECTOR_SIZE_BYTES])
80 .expect("Failed to read block device.");
81 }
82 for (i, chunk) in data.chunks(size_of::<u32>()).enumerate() {
83 assert_eq!(chunk, &(i as u32).to_le_bytes());
84 }
85 info!("Read expected data from block device.");
Andrew Walbranb713baa2022-12-07 14:34:49 +000086 }
Andrew Walbran6ac174e2023-06-23 14:58:51 +000087 1 => {
88 assert_eq!(blk.capacity(), 0);
89 let mut data = [0; SECTOR_SIZE_BYTES];
90 assert_eq!(blk.read_block(0, &mut data), Err(Error::IoError));
Andrew Walbranb713baa2022-12-07 14:34:49 +000091 }
Andrew Walbran6ac174e2023-06-23 14:58:51 +000092 _ => panic!("Unexpected VirtIO block device index {}.", index),
Andrew Walbran8217d062022-11-22 16:56:18 +000093 }
94}
95
Andrew Walbran6ac174e2023-06-23 14:58:51 +000096/// Checks the given VirtIO console device.
97fn check_virtio_console_device(transport: impl Transport) {
98 let mut console = VirtIOConsole::<HalImpl, _>::new(transport)
99 .expect("Failed to create VirtIO console driver");
100 info!("Found console device: {:?}", console.info());
101 for &c in b"Hello VirtIO console\n" {
102 console.send(c).expect("Failed to send character to VirtIO console device");
103 }
104 info!("Wrote to VirtIO console.");
105}
106
Andrew Walbran730375d2022-12-21 14:04:34 +0000107/// Gets the memory region in which BARs are allocated.
108pub fn get_bar_region(pci_info: &PciInfo) -> MemoryRegion {
109 MemoryRegion::new(pci_info.bar_range.start as usize, pci_info.bar_range.end as usize)
Andrew Walbran8217d062022-11-22 16:56:18 +0000110}
111
Andrew Walbran8217d062022-11-22 16:56:18 +0000112struct HalImpl;
113
Alice Wang63e0d0d2023-04-20 14:15:32 +0000114unsafe impl Hal for HalImpl {
Andrew Walbran272bd7a2023-01-24 14:02:36 +0000115 fn dma_alloc(pages: usize, _direction: BufferDirection) -> (PhysAddr, NonNull<u8>) {
Andrew Walbran8217d062022-11-22 16:56:18 +0000116 debug!("dma_alloc: pages={}", pages);
117 let layout = Layout::from_size_align(pages * PAGE_SIZE, PAGE_SIZE).unwrap();
118 // Safe because the layout has a non-zero size.
Andrew Walbrancf9333e2023-05-16 16:00:35 +0000119 let vaddr = unsafe { alloc_zeroed(layout) };
Andrew Walbran272bd7a2023-01-24 14:02:36 +0000120 let vaddr =
121 if let Some(vaddr) = NonNull::new(vaddr) { vaddr } else { handle_alloc_error(layout) };
122 let paddr = virt_to_phys(vaddr);
123 (paddr, vaddr)
Andrew Walbran8217d062022-11-22 16:56:18 +0000124 }
125
Alice Wang63e0d0d2023-04-20 14:15:32 +0000126 unsafe fn dma_dealloc(paddr: PhysAddr, vaddr: NonNull<u8>, pages: usize) -> i32 {
Andrew Walbran8217d062022-11-22 16:56:18 +0000127 debug!("dma_dealloc: paddr={:#x}, pages={}", paddr, pages);
Andrew Walbran8217d062022-11-22 16:56:18 +0000128 let layout = Layout::from_size_align(pages * PAGE_SIZE, PAGE_SIZE).unwrap();
129 // Safe because the memory was allocated by `dma_alloc` above using the same allocator, and
130 // the layout is the same as was used then.
131 unsafe {
Andrew Walbran272bd7a2023-01-24 14:02:36 +0000132 dealloc(vaddr.as_ptr(), layout);
Andrew Walbran8217d062022-11-22 16:56:18 +0000133 }
134 0
135 }
136
Alice Wang63e0d0d2023-04-20 14:15:32 +0000137 unsafe fn mmio_phys_to_virt(paddr: PhysAddr, _size: usize) -> NonNull<u8> {
Andrew Walbran272bd7a2023-01-24 14:02:36 +0000138 NonNull::new(paddr as _).unwrap()
Andrew Walbran8217d062022-11-22 16:56:18 +0000139 }
140
Alice Wang63e0d0d2023-04-20 14:15:32 +0000141 unsafe fn share(buffer: NonNull<[u8]>, _direction: BufferDirection) -> PhysAddr {
Andrew Walbran272bd7a2023-01-24 14:02:36 +0000142 let vaddr = buffer.cast();
Andrew Walbran336d0cb2023-01-06 16:33:15 +0000143 // Nothing to do, as the host already has access to all memory.
144 virt_to_phys(vaddr)
Andrew Walbran8217d062022-11-22 16:56:18 +0000145 }
Andrew Walbran336d0cb2023-01-06 16:33:15 +0000146
Alice Wang63e0d0d2023-04-20 14:15:32 +0000147 unsafe fn unshare(_paddr: PhysAddr, _buffer: NonNull<[u8]>, _direction: BufferDirection) {
Andrew Walbran336d0cb2023-01-06 16:33:15 +0000148 // Nothing to do, as the host already has access to all memory and we didn't copy the buffer
149 // anywhere else.
150 }
151}
152
Andrew Walbran272bd7a2023-01-24 14:02:36 +0000153fn virt_to_phys(vaddr: NonNull<u8>) -> PhysAddr {
154 vaddr.as_ptr() as _
Andrew Walbran8217d062022-11-22 16:56:18 +0000155}