main.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. #![no_std]
  2. #![no_main]
  3. mod exceptions;
  4. mod hal;
  5. mod logger;
  6. #[cfg(platform = "qemu")]
  7. mod pl011;
  8. #[cfg(platform = "qemu")]
  9. use pl011 as uart;
  10. #[cfg(platform = "crosvm")]
  11. mod uart8250;
  12. #[cfg(platform = "crosvm")]
  13. use uart8250 as uart;
  14. use core::{
  15. mem::size_of,
  16. panic::PanicInfo,
  17. ptr::{self, NonNull},
  18. };
  19. use fdt::{node::FdtNode, standard_nodes::Compatible, Fdt};
  20. use hal::HalImpl;
  21. use log::{debug, error, info, trace, warn, LevelFilter};
  22. use psci::system_off;
  23. use virtio_drivers::{
  24. device::{blk::VirtIOBlk, console::VirtIOConsole, gpu::VirtIOGpu},
  25. transport::{
  26. mmio::{MmioTransport, VirtIOHeader},
  27. pci::{
  28. bus::{BarInfo, Cam, Command, DeviceFunction, MemoryBarType, PciRoot},
  29. virtio_device_type, PciTransport,
  30. },
  31. DeviceType, Transport,
  32. },
  33. };
  34. /// Base memory-mapped address of the primary PL011 UART device.
  35. #[cfg(platform = "qemu")]
  36. pub const UART_BASE_ADDRESS: usize = 0x900_0000;
  37. /// The base address of the first 8250 UART.
  38. #[cfg(platform = "crosvm")]
  39. pub const UART_BASE_ADDRESS: usize = 0x3f8;
  40. #[no_mangle]
  41. extern "C" fn main(x0: u64, x1: u64, x2: u64, x3: u64) {
  42. logger::init(LevelFilter::Debug).unwrap();
  43. info!("virtio-drivers example started.");
  44. debug!(
  45. "x0={:#018x}, x1={:#018x}, x2={:#018x}, x3={:#018x}",
  46. x0, x1, x2, x3
  47. );
  48. info!("Loading FDT from {:#018x}", x0);
  49. // Safe because the pointer is a valid pointer to unaliased memory.
  50. let fdt = unsafe { Fdt::from_ptr(x0 as *const u8).unwrap() };
  51. for node in fdt.all_nodes() {
  52. // Dump information about the node for debugging.
  53. trace!(
  54. "{}: {:?}",
  55. node.name,
  56. node.compatible().map(Compatible::first),
  57. );
  58. if let Some(reg) = node.reg() {
  59. for range in reg {
  60. trace!(
  61. " {:#018x?}, length {:?}",
  62. range.starting_address,
  63. range.size
  64. );
  65. }
  66. }
  67. // Check whether it is a VirtIO MMIO device.
  68. if let (Some(compatible), Some(region)) =
  69. (node.compatible(), node.reg().and_then(|mut reg| reg.next()))
  70. {
  71. if compatible.all().any(|s| s == "virtio,mmio")
  72. && region.size.unwrap_or(0) > size_of::<VirtIOHeader>()
  73. {
  74. debug!("Found VirtIO MMIO device at {:?}", region);
  75. let header = NonNull::new(region.starting_address as *mut VirtIOHeader).unwrap();
  76. match unsafe { MmioTransport::new(header) } {
  77. Err(e) => warn!("Error creating VirtIO MMIO transport: {}", e),
  78. Ok(transport) => {
  79. info!(
  80. "Detected virtio MMIO device with vendor id {:#X}, device type {:?}, version {:?}",
  81. transport.vendor_id(),
  82. transport.device_type(),
  83. transport.version(),
  84. );
  85. virtio_device(transport);
  86. }
  87. }
  88. }
  89. }
  90. }
  91. if let Some(pci_node) = fdt.find_compatible(&["pci-host-cam-generic"]) {
  92. info!("Found PCI node: {}", pci_node.name);
  93. enumerate_pci(pci_node, Cam::MmioCam);
  94. }
  95. if let Some(pcie_node) = fdt.find_compatible(&["pci-host-ecam-generic"]) {
  96. info!("Found PCIe node: {}", pcie_node.name);
  97. enumerate_pci(pcie_node, Cam::Ecam);
  98. }
  99. system_off().unwrap();
  100. }
  101. fn virtio_device(transport: impl Transport) {
  102. match transport.device_type() {
  103. DeviceType::Block => virtio_blk(transport),
  104. DeviceType::GPU => virtio_gpu(transport),
  105. // DeviceType::Network => virtio_net(transport), // currently is unsupported without alloc
  106. DeviceType::Console => virtio_console(transport),
  107. t => warn!("Unrecognized virtio device: {:?}", t),
  108. }
  109. }
  110. fn virtio_blk<T: Transport>(transport: T) {
  111. let mut blk = VirtIOBlk::<HalImpl, T>::new(transport).expect("failed to create blk driver");
  112. assert!(!blk.readonly());
  113. let mut input = [0xffu8; 512];
  114. let mut output = [0; 512];
  115. for i in 0..32 {
  116. for x in input.iter_mut() {
  117. *x = i as u8;
  118. }
  119. blk.write_block(i, &input).expect("failed to write");
  120. blk.read_block(i, &mut output).expect("failed to read");
  121. assert_eq!(input, output);
  122. }
  123. info!("virtio-blk test finished");
  124. }
  125. fn virtio_gpu<T: Transport>(transport: T) {
  126. let mut gpu = VirtIOGpu::<HalImpl, T>::new(transport).expect("failed to create gpu driver");
  127. let (width, height) = gpu.resolution().expect("failed to get resolution");
  128. let width = width as usize;
  129. let height = height as usize;
  130. info!("GPU resolution is {}x{}", width, height);
  131. let fb = gpu.setup_framebuffer().expect("failed to get fb");
  132. for y in 0..height {
  133. for x in 0..width {
  134. let idx = (y * width + x) * 4;
  135. fb[idx] = x as u8;
  136. fb[idx + 1] = y as u8;
  137. fb[idx + 2] = (x + y) as u8;
  138. }
  139. }
  140. gpu.flush().expect("failed to flush");
  141. //delay some time
  142. info!("virtio-gpu show graphics....");
  143. for _ in 0..100000 {
  144. for _ in 0..100000 {
  145. unsafe {
  146. core::arch::asm!("nop");
  147. }
  148. }
  149. }
  150. info!("virtio-gpu test finished");
  151. }
  152. fn virtio_console<T: Transport>(transport: T) {
  153. let mut console =
  154. VirtIOConsole::<HalImpl, T>::new(transport).expect("Failed to create console driver");
  155. let info = console.info();
  156. info!("VirtIO console {}x{}", info.rows, info.columns);
  157. for &c in b"Hello world on console!\n" {
  158. console.send(c).expect("Failed to send character");
  159. }
  160. let c = console.recv(true).expect("Failed to read from console");
  161. info!("Read {:?}", c);
  162. info!("virtio-console test finished");
  163. }
  164. #[derive(Copy, Clone, Debug, Eq, PartialEq)]
  165. enum PciRangeType {
  166. ConfigurationSpace,
  167. IoSpace,
  168. Memory32,
  169. Memory64,
  170. }
  171. impl From<u8> for PciRangeType {
  172. fn from(value: u8) -> Self {
  173. match value {
  174. 0 => Self::ConfigurationSpace,
  175. 1 => Self::IoSpace,
  176. 2 => Self::Memory32,
  177. 3 => Self::Memory64,
  178. _ => panic!("Tried to convert invalid range type {}", value),
  179. }
  180. }
  181. }
  182. fn enumerate_pci(pci_node: FdtNode, cam: Cam) {
  183. let reg = pci_node.reg().expect("PCI node missing reg property.");
  184. let mut allocator = PciMemory32Allocator::for_pci_ranges(&pci_node);
  185. for region in reg {
  186. info!(
  187. "Reg: {:?}-{:#x}",
  188. region.starting_address,
  189. region.starting_address as usize + region.size.unwrap()
  190. );
  191. assert_eq!(region.size.unwrap(), cam.size() as usize);
  192. // Safe because we know the pointer is to a valid MMIO region.
  193. let mut pci_root = unsafe { PciRoot::new(region.starting_address as *mut u8, cam) };
  194. for (device_function, info) in pci_root.enumerate_bus(0) {
  195. let (status, command) = pci_root.get_status_command(device_function);
  196. info!(
  197. "Found {} at {}, status {:?} command {:?}",
  198. info, device_function, status, command
  199. );
  200. if let Some(virtio_type) = virtio_device_type(&info) {
  201. info!(" VirtIO {:?}", virtio_type);
  202. allocate_bars(&mut pci_root, device_function, &mut allocator);
  203. dump_bar_contents(&mut pci_root, device_function, 4);
  204. let mut transport =
  205. PciTransport::new::<HalImpl>(&mut pci_root, device_function).unwrap();
  206. info!(
  207. "Detected virtio PCI device with device type {:?}, features {:#018x}",
  208. transport.device_type(),
  209. transport.read_device_features(),
  210. );
  211. virtio_device(transport);
  212. }
  213. }
  214. }
  215. }
  216. /// Allocates 32-bit memory addresses for PCI BARs.
  217. struct PciMemory32Allocator {
  218. start: u32,
  219. end: u32,
  220. }
  221. impl PciMemory32Allocator {
  222. /// Creates a new allocator based on the ranges property of the given PCI node.
  223. pub fn for_pci_ranges(pci_node: &FdtNode) -> Self {
  224. let ranges = pci_node
  225. .property("ranges")
  226. .expect("PCI node missing ranges property.");
  227. let mut memory_32_address = 0;
  228. let mut memory_32_size = 0;
  229. for i in 0..ranges.value.len() / 28 {
  230. let range = &ranges.value[i * 28..(i + 1) * 28];
  231. let prefetchable = range[0] & 0x80 != 0;
  232. let range_type = PciRangeType::from(range[0] & 0x3);
  233. let bus_address = u64::from_be_bytes(range[4..12].try_into().unwrap());
  234. let cpu_physical = u64::from_be_bytes(range[12..20].try_into().unwrap());
  235. let size = u64::from_be_bytes(range[20..28].try_into().unwrap());
  236. info!(
  237. "range: {:?} {}prefetchable bus address: {:#018x} host physical address: {:#018x} size: {:#018x}",
  238. range_type,
  239. if prefetchable { "" } else { "non-" },
  240. bus_address,
  241. cpu_physical,
  242. size,
  243. );
  244. // Use the largest range within the 32-bit address space for 32-bit memory, even if it
  245. // is marked as a 64-bit range. This is necessary because crosvm doesn't currently
  246. // provide any 32-bit ranges.
  247. if !prefetchable
  248. && matches!(range_type, PciRangeType::Memory32 | PciRangeType::Memory64)
  249. && size > memory_32_size.into()
  250. && bus_address + size < u32::MAX.into()
  251. {
  252. assert_eq!(bus_address, cpu_physical);
  253. memory_32_address = u32::try_from(cpu_physical).unwrap();
  254. memory_32_size = u32::try_from(size).unwrap();
  255. }
  256. }
  257. if memory_32_size == 0 {
  258. panic!("No 32-bit PCI memory region found.");
  259. }
  260. Self {
  261. start: memory_32_address,
  262. end: memory_32_address + memory_32_size,
  263. }
  264. }
  265. /// Allocates a 32-bit memory address region for a PCI BAR of the given power-of-2 size.
  266. ///
  267. /// It will have alignment matching the size. The size must be a power of 2.
  268. pub fn allocate_memory_32(&mut self, size: u32) -> u32 {
  269. assert!(size.is_power_of_two());
  270. let allocated_address = align_up(self.start, size);
  271. assert!(allocated_address + size <= self.end);
  272. self.start = allocated_address + size;
  273. allocated_address
  274. }
  275. }
  276. const fn align_up(value: u32, alignment: u32) -> u32 {
  277. ((value - 1) | (alignment - 1)) + 1
  278. }
  279. fn dump_bar_contents(root: &mut PciRoot, device_function: DeviceFunction, bar_index: u8) {
  280. let bar_info = root.bar_info(device_function, bar_index).unwrap();
  281. trace!("Dumping bar {}: {:#x?}", bar_index, bar_info);
  282. if let BarInfo::Memory { address, size, .. } = bar_info {
  283. let start = address as *const u8;
  284. unsafe {
  285. let mut buf = [0u8; 32];
  286. for i in 0..size / 32 {
  287. let ptr = start.add(i as usize * 32);
  288. ptr::copy(ptr, buf.as_mut_ptr(), 32);
  289. if buf.iter().any(|b| *b != 0xff) {
  290. trace!(" {:?}: {:x?}", ptr, buf);
  291. }
  292. }
  293. }
  294. }
  295. trace!("End of dump");
  296. }
  297. /// Allocates appropriately-sized memory regions and assigns them to the device's BARs.
  298. fn allocate_bars(
  299. root: &mut PciRoot,
  300. device_function: DeviceFunction,
  301. allocator: &mut PciMemory32Allocator,
  302. ) {
  303. let mut bar_index = 0;
  304. while bar_index < 6 {
  305. let info = root.bar_info(device_function, bar_index).unwrap();
  306. debug!("BAR {}: {}", bar_index, info);
  307. // Ignore I/O bars, as they aren't required for the VirtIO driver.
  308. if let BarInfo::Memory {
  309. address_type, size, ..
  310. } = info
  311. {
  312. match address_type {
  313. MemoryBarType::Width32 => {
  314. if size > 0 {
  315. let address = allocator.allocate_memory_32(size);
  316. debug!("Allocated address {:#010x}", address);
  317. root.set_bar_32(device_function, bar_index, address);
  318. }
  319. }
  320. MemoryBarType::Width64 => {
  321. if size > 0 {
  322. let address = allocator.allocate_memory_32(size);
  323. debug!("Allocated address {:#010x}", address);
  324. root.set_bar_64(device_function, bar_index, address.into());
  325. }
  326. }
  327. _ => panic!("Memory BAR address type {:?} not supported.", address_type),
  328. }
  329. }
  330. bar_index += 1;
  331. if info.takes_two_entries() {
  332. bar_index += 1;
  333. }
  334. }
  335. // Enable the device to use its BARs.
  336. root.set_command(
  337. device_function,
  338. Command::IO_SPACE | Command::MEMORY_SPACE | Command::BUS_MASTER,
  339. );
  340. let (status, command) = root.get_status_command(device_function);
  341. debug!(
  342. "Allocated BARs and enabled device, status {:?} command {:?}",
  343. status, command
  344. );
  345. }
  346. #[panic_handler]
  347. fn panic(info: &PanicInfo) -> ! {
  348. error!("{}", info);
  349. system_off().unwrap();
  350. loop {}
  351. }