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