1 /// 为virtio-drivers库提供的操作系统接口 2 use crate::include::bindings::bindings::{ 3 alloc_pages, free_pages, memory_management_struct, Page, PAGE_2M_SHIFT, PAGE_2M_SIZE, 4 PAGE_OFFSET, PAGE_SHARED, ZONE_NORMAL, 5 }; 6 use crate::mm::virt_2_phys; 7 use core::mem::size_of; 8 use core::ptr::NonNull; 9 use virtio_drivers::{BufferDirection, Hal, PhysAddr, PAGE_SIZE}; 10 pub struct HalImpl; 11 unsafe impl Hal for HalImpl { 12 /// @brief 申请用于DMA的内存页 13 /// @param pages 页数(4k一页) 14 /// @return PhysAddr 获得的内存页的初始物理地址 dma_alloc(pages: usize, _direction: BufferDirection) -> (PhysAddr, NonNull<u8>)15 fn dma_alloc(pages: usize, _direction: BufferDirection) -> (PhysAddr, NonNull<u8>) { 16 let page_num = (pages * PAGE_SIZE - 1 + PAGE_2M_SIZE as usize) / PAGE_2M_SIZE as usize; 17 unsafe { 18 let pa = alloc_pages(ZONE_NORMAL, page_num as i32, PAGE_SHARED as u64); 19 let page = *pa; 20 //kdebug!("alloc pages num:{},Phyaddr={:#x}",pages,page.addr_phys); 21 ( 22 page.addr_phys as PhysAddr, 23 NonNull::new((page.addr_phys as PhysAddr + PAGE_OFFSET as usize) as _).unwrap(), 24 ) 25 } 26 } 27 /// @brief 释放用于DMA的内存页 28 /// @param paddr 起始物理地址 pages 页数(4k一页) 29 /// @return i32 0表示成功 dma_dealloc(paddr: PhysAddr, _vaddr: NonNull<u8>, pages: usize) -> i3230 unsafe fn dma_dealloc(paddr: PhysAddr, _vaddr: NonNull<u8>, pages: usize) -> i32 { 31 let page_num = (pages * PAGE_SIZE - 1 + PAGE_2M_SIZE as usize) / PAGE_2M_SIZE as usize; 32 unsafe { 33 let pa = (memory_management_struct.pages_struct as usize 34 + (paddr >> PAGE_2M_SHIFT) * size_of::<Page>()) as *mut Page; 35 //kdebug!("free pages num:{},Phyaddr={}",page_num,paddr); 36 free_pages(pa, page_num as i32); 37 } 38 return 0; 39 } 40 /// @brief mmio物理地址转换为虚拟地址,不需要使用 41 /// @param paddr 起始物理地址 42 /// @return NonNull<u8> 虚拟地址的指针 mmio_phys_to_virt(_paddr: PhysAddr, _size: usize) -> NonNull<u8>43 unsafe fn mmio_phys_to_virt(_paddr: PhysAddr, _size: usize) -> NonNull<u8> { 44 NonNull::new((0) as _).unwrap() 45 } 46 /// @brief 与真实物理设备共享 47 /// @param buffer 要共享的buffer _direction:设备到driver或driver到设备 48 /// @return buffer在内存中的物理地址 share(buffer: NonNull<[u8]>, _direction: BufferDirection) -> PhysAddr49 unsafe fn share(buffer: NonNull<[u8]>, _direction: BufferDirection) -> PhysAddr { 50 let vaddr = buffer.as_ptr() as *mut u8 as usize; 51 //kdebug!("virt:{:x}", vaddr); 52 // Nothing to do, as the host already has access to all memory. 53 virt_2_phys(vaddr) 54 } 55 /// @brief 停止共享(让主机可以访问全部内存的话什么都不用做) unshare(_paddr: PhysAddr, _buffer: NonNull<[u8]>, _direction: BufferDirection)56 unsafe fn unshare(_paddr: PhysAddr, _buffer: NonNull<[u8]>, _direction: BufferDirection) { 57 // Nothing to do, as the host already has access to all memory and we didn't copy the buffer 58 // anywhere else. 59 } 60 } 61